diff --git a/backend/src/features/aircrafts/aircrafts.controller.spec.ts b/backend/src/features/aircrafts/aircrafts.controller.spec.ts index e825f56..990f874 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.spec.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.spec.ts @@ -1,4 +1,8 @@ -import { ProductType } from '@prisma/client'; +import { ProductType, UserRole } from '@prisma/client'; +import { Reflector } from '@nestjs/core'; +import { ForbiddenException } from '@nestjs/common'; +import { ROLES_KEY } from 'src/shared/decorators/roles.decorator'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; import { AircraftsController } from './aircrafts.controller'; function mkController() { @@ -101,9 +105,7 @@ describe('AircraftsController — Calendly opcional', () => { it('aguarda upload fora da transação e compensa se a auditoria falhar', async () => { const { controller, aircraftsService, audit, prisma } = mkController(); - const prepared = [ - { image_url: 'aircrafts/new-key.jpg', is_primary: true }, - ]; + const prepared = [{ image_url: 'aircrafts/new-key.jpg', is_primary: true }]; let finishUpload!: (images: typeof prepared) => void; aircraftsService.prepareProductImages.mockReturnValueOnce( new Promise((resolve) => { @@ -182,3 +184,87 @@ describe('AircraftsController — Calendly opcional', () => { ); }); }); + +describe('AircraftsController — admin/all (Gestão de Produtos)', () => { + function mkListController() { + const aircraftsService = { + getAllAircrafts: jest.fn().mockResolvedValue({ + data: [], + count: 0, + filters: {}, + }), + } as any; + const prisma = { user: { findUnique: jest.fn() } } as any; + // ActorContextService real: é ele quem restringe o SPECIALIST a si mesmo. + const actorContext = new ActorContextService(prisma); + const controller = new (AircraftsController as any)( + aircraftsService, + {} as any, + actorContext, + {} as any, + prisma, + ); + return { controller, aircraftsService, prisma }; + } + + const owner = { + id: 'spec-1', + role: UserRole.SPECIALIST, + speciality: ProductType.AIRCRAFT, + is_active: true, + name: 'Esp', + surname: 'Um', + } as any; + + it('libera ADMIN e SPECIALIST nos metadados de roles', () => { + const roles = new Reflector().get( + ROLES_KEY, + AircraftsController.prototype.getAllAircraftsForAdmin, + ); + expect(roles).toEqual( + expect.arrayContaining([UserRole.ADMIN, UserRole.SPECIALIST]), + ); + }); + + it('lista só os produtos do próprio especialista, incluindo inativos', async () => { + const { controller, aircraftsService } = mkListController(); + + await controller.getAllAircraftsForAdmin( + { page: '2', perPage: '20', search: 'abc', specialist_id: 'spec-2' }, + owner, + ); + + expect(aircraftsService.getAllAircrafts).toHaveBeenCalledWith( + { + page: 2, + perPage: 20, + appliedFilters: { search: 'abc', specialist_id: 'spec-1' }, + }, + true, + ); + }); + + it('responde 403 se o especialista pedir outro target_specialist_id', async () => { + const { controller, aircraftsService } = mkListController(); + + await expect( + controller.getAllAircraftsForAdmin( + { target_specialist_id: 'spec-2' }, + owner, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(aircraftsService.getAllAircrafts).not.toHaveBeenCalled(); + }); + + it('responde 403 se a especialidade não corresponder ao recurso', async () => { + const { controller, aircraftsService } = mkListController(); + + await expect( + controller.getAllAircraftsForAdmin( + {}, + { ...owner, speciality: ProductType.BOAT }, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(aircraftsService.getAllAircrafts).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/features/aircrafts/aircrafts.controller.ts b/backend/src/features/aircrafts/aircrafts.controller.ts index 7520592..24d9b4f 100644 --- a/backend/src/features/aircrafts/aircrafts.controller.ts +++ b/backend/src/features/aircrafts/aircrafts.controller.ts @@ -42,6 +42,7 @@ import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; import { TransferProductDto } from '../products/dto/transfer-product.dto'; import { transferProductAsAdmin } from '../products/product-transfer'; +import { parsePaginationParams } from 'src/shared/helpers/pagination-params.helper'; @Controller('aircrafts') export class AircraftsController { @@ -175,8 +176,9 @@ export class AircraftsController { async getAllAircrafts(@Query() query: any) { //Tratamento das variáveis recebidas do front let { page, perPage, ...rawFilters } = query; - page = Number(page); - perPage = Number(perPage); + // Rota pública (sem login): limita perPage para ninguém pedir o catálogo + // inteiro de uma vez, com uma URL do S3 assinada por imagem. + ({ page, perPage } = parsePaginationParams(page, perPage)); const appliedFilters: FiltersAircraftMeta = rawFilters; @@ -197,7 +199,7 @@ export class AircraftsController { // Atualiza os metadados de paginação const pagination = new PaginationDto(); pagination.current_page = page; - pagination.total_pages = count / perPage; + pagination.total_pages = Math.ceil(count / perPage); pagination.has_next = skip + perPage < count; pagination.has_prev = skip > 0; pagination.total = count; @@ -217,15 +219,17 @@ export class AircraftsController { }; } + // SPECIALIST também acessa (tela "Gestão de Produtos", inclui inativos): + // o ActorContextService força specialistId = próprio id e responde 403 se + // target_specialist_id for de outro especialista ou a especialidade divergir. @Get('admin/all') - @Roles(UserRole.ADMIN) + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async getAllAircraftsForAdmin( @Query() query: any, @CurrentUser() user: UserEntity, ) { let { page, perPage, target_specialist_id, ...rawFilters } = query; - page = Number(page) || 1; - perPage = Number(perPage) || 20; + ({ page, perPage } = parsePaginationParams(page, perPage)); const context = await this.actorContextService.resolve( user, target_specialist_id, diff --git a/backend/src/features/aircrafts/aircrafts.service.spec.ts b/backend/src/features/aircrafts/aircrafts.service.spec.ts new file mode 100644 index 0000000..5d5d59b --- /dev/null +++ b/backend/src/features/aircrafts/aircrafts.service.spec.ts @@ -0,0 +1,123 @@ +import { AircraftsService } from './aircrafts.service'; + +describe('AircraftsService — getAllAircrafts (busca e ordenação)', () => { + function mkService() { + const findMany = jest.fn().mockResolvedValue([]); + const count = jest.fn().mockResolvedValue(0); + const prisma = { + aircraft: { findMany, count }, + $transaction: jest.fn((ops: Promise[]) => Promise.all(ops)), + } as any; + const service = new AircraftsService(prisma, {} as any); + return { service, findMany, count }; + } + + it('ordena por created_at desc e id asc para paginação estável', async () => { + const { service, findMany } = mkService(); + + await service.getAllAircrafts({ page: 2, perPage: 20, appliedFilters: {} }); + + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + skip: 20, + take: 20, + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], + }), + ); + }); + + it('busca em marca/modelo (insensitive) sem ano quando o termo não é um ano', async () => { + const { service, findMany, count } = mkService(); + + await service.getAllAircrafts( + { + page: 1, + perPage: 20, + appliedFilters: { search: ' Fer ', specialist_id: 'spec-1' }, + }, + true, + ); + + const expectedWhere = { + specialist_id: 'spec-1', + OR: [ + { marca: { contains: 'Fer', mode: 'insensitive' } }, + { modelo: { contains: 'Fer', mode: 'insensitive' } }, + + { estado: { contains: 'Fer', mode: 'insensitive' } }, + ], + }; + expect(findMany.mock.calls[0][0].where).toEqual(expectedWhere); + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + }); + + it('inclui ano exato quando o termo tem 4 dígitos', async () => { + const { service, findMany } = mkService(); + + await service.getAllAircrafts({ + page: 1, + perPage: 20, + appliedFilters: { search: '2021' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + OR: [ + { marca: { contains: '2021', mode: 'insensitive' } }, + { modelo: { contains: '2021', mode: 'insensitive' } }, + + { estado: { contains: '2021', mode: 'insensitive' } }, + { ano: 2021 }, + ], + }); + }); + + it('ignora busca vazia ou só com espaços', async () => { + const { service, findMany } = mkService(); + + await service.getAllAircrafts({ + page: 1, + perPage: 20, + appliedFilters: { search: ' ' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ is_active: true }); + }); + + it('limita o termo de busca a 100 caracteres', async () => { + const { service, findMany } = mkService(); + + await service.getAllAircrafts({ + page: 1, + perPage: 20, + appliedFilters: { search: 'x'.repeat(150) }, + }); + + expect(findMany.mock.calls[0][0].where.OR[0].marca.contains).toHaveLength( + 100, + ); + }); + + it('filtra ano, preço (`valor`) e assentos (`assentos`) na direção certa', async () => { + const { service, findMany } = mkService(); + + await service.getAllAircrafts({ + page: 1, + perPage: 20, + appliedFilters: { + ano_min: '2015', + ano_max: '2020', + preco_min: '2000000', + assentos_min: '6', + assentos_max: '12', + } as any, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + ano: { gte: 2015, lte: 2020 }, + valor: { gte: 2000000 }, + assentos: { gte: 6, lte: 12 }, + }); + }); +}); diff --git a/backend/src/features/aircrafts/aircrafts.service.ts b/backend/src/features/aircrafts/aircrafts.service.ts index 87d91a7..07cc94b 100644 --- a/backend/src/features/aircrafts/aircrafts.service.ts +++ b/backend/src/features/aircrafts/aircrafts.service.ts @@ -13,7 +13,6 @@ import { ContainsAircraftFilters, ExactAircraftFilters, FiltersAircraftMeta, - RangeAircraftFilters, } from 'src/shared/dto/filters.dto'; import { Prisma, ProductType } from '@prisma/client'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; @@ -25,6 +24,8 @@ import { PreparedProductImage, ProductImageInput, } from '../products/product-image-preparation'; +import { buildProductSearchConditions } from 'src/shared/helpers/product-search.helper'; +import { applyRangeFilters } from 'src/shared/helpers/product-range.helper'; @Injectable() export class AircraftsService { @@ -186,41 +187,44 @@ export class AircraftsService { } } - // Range - const rangeFilters: RangeAircraftFilters = { - ...appliedFilters, - }; - // Objeto para orientar o where wu utiliza gte e lte - const rangeMap = { - ano: { gte: rangeFilters?.ano_max, lte: rangeFilters?.ano_min }, - preco: { gte: rangeFilters?.preco_max, lte: rangeFilters?.preco_min }, - assento: { - gte: rangeFilters?.assentos_max, - lte: rangeFilters?.assentos_min, + // Range: antes o min/max estavam invertidos e os campos apontavam para + // `preco`/`assento`, colunas que não existem (são `valor`/`assentos`). + applyRangeFilters(where, { + ano: { + min: appliedFilters?.ano_min, + max: appliedFilters?.ano_max, + integer: true, }, - }; - // Insere a filtragem como um intervalo na variável where - for (const [key, { gte, lte }] of Object.entries(rangeMap)) { - const hasGte = gte !== undefined && gte !== null; - const hasLte = lte !== undefined && lte !== null; - if (hasGte || hasLte) { - where[key] = {}; - if (hasGte) where[key].gte = gte; - if (hasLte) where[key].lte = lte; - } - } + valor: { min: appliedFilters?.preco_min, max: appliedFilters?.preco_max }, + assentos: { + min: appliedFilters?.assentos_min, + max: appliedFilters?.assentos_max, + integer: true, + }, + }); // Filtro por especialista (usado na tela "Meus Produtos") if (appliedFilters?.specialist_id) { where.specialist_id = appliedFilters.specialist_id; } + // Busca textual (marca/modelo/estado e ano exato) — usada na "Gestão de Produtos". + // Nenhum outro filtro usa `OR`; se passar a usar, combinar via `AND`. + const searchConditions = buildProductSearchConditions( + appliedFilters?.search, + ); + if (searchConditions) { + where.OR = searchConditions; + } + //Agrupamento das operações que serão realizadas no banco de dados const [aircrafts, total] = await this.prismaService.$transaction([ this.prismaService.aircraft.findMany({ skip: skip, take: take, where: where, + // Ordem estável para a paginação não repetir/pular itens. + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], select: publicAircraftSelect, }), this.prismaService.aircraft.count({ where }), diff --git a/backend/src/features/boats/boats.controller.spec.ts b/backend/src/features/boats/boats.controller.spec.ts index d6a6430..2a773e6 100644 --- a/backend/src/features/boats/boats.controller.spec.ts +++ b/backend/src/features/boats/boats.controller.spec.ts @@ -1,4 +1,8 @@ -import { ProductType } from '@prisma/client'; +import { ProductType, UserRole } from '@prisma/client'; +import { Reflector } from '@nestjs/core'; +import { ForbiddenException } from '@nestjs/common'; +import { ROLES_KEY } from 'src/shared/decorators/roles.decorator'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; import { BoatsController } from './boats.controller'; function mkController() { @@ -174,3 +178,124 @@ describe('BoatsController — Calendly opcional', () => { ); }); }); + +describe('BoatsController — admin/all (Gestão de Produtos)', () => { + function mkListController() { + const boatsService = { + getAllBoats: jest.fn().mockResolvedValue({ + data: [], + count: 0, + filters: {}, + }), + } as any; + const prisma = { user: { findUnique: jest.fn() } } as any; + // ActorContextService real: é ele quem restringe o SPECIALIST a si mesmo. + const actorContext = new ActorContextService(prisma); + const controller = new (BoatsController as any)( + boatsService, + {} as any, + actorContext, + {} as any, + prisma, + ); + return { controller, boatsService, prisma }; + } + + const owner = { + id: 'spec-1', + role: UserRole.SPECIALIST, + speciality: ProductType.BOAT, + is_active: true, + name: 'Esp', + surname: 'Um', + } as any; + + it('libera ADMIN e SPECIALIST nos metadados de roles', () => { + const roles = new Reflector().get( + ROLES_KEY, + BoatsController.prototype.getAllBoatsForAdmin, + ); + expect(roles).toEqual( + expect.arrayContaining([UserRole.ADMIN, UserRole.SPECIALIST]), + ); + }); + + it('lista só os produtos do próprio especialista, incluindo inativos', async () => { + const { controller, boatsService } = mkListController(); + + await controller.getAllBoatsForAdmin( + { page: '2', perPage: '20', search: 'abc', specialist_id: 'spec-2' }, + owner, + ); + + expect(boatsService.getAllBoats).toHaveBeenCalledWith( + { + page: 2, + perPage: 20, + appliedFilters: { search: 'abc', specialist_id: 'spec-1' }, + }, + true, + ); + }); + + it('responde 403 se o especialista pedir outro target_specialist_id', async () => { + const { controller, boatsService } = mkListController(); + + await expect( + controller.getAllBoatsForAdmin({ target_specialist_id: 'spec-2' }, owner), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(boatsService.getAllBoats).not.toHaveBeenCalled(); + }); + + it('responde 403 se a especialidade não corresponder ao recurso', async () => { + const { controller, boatsService } = mkListController(); + + await expect( + controller.getAllBoatsForAdmin( + {}, + { ...owner, speciality: ProductType.CAR }, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(boatsService.getAllBoats).not.toHaveBeenCalled(); + }); + + it('listagem pública arredonda total_pages para cima', async () => { + const { controller, boatsService } = mkListController(); + boatsService.getAllBoats.mockResolvedValueOnce({ + data: [], + count: 47, + filters: {}, + }); + + const result = await controller.getAllBoats({ page: '1', perPage: '20' }); + + // Antes: 47 / 20 = 2.35, e o "ir para a última página" do catálogo + // pedia page=2.35. + expect(result.meta.pagination.total_pages).toBe(3); + }); + + it('listagem pública (sem login) limita perPage a 100 e normaliza page', async () => { + const { controller, boatsService } = mkListController(); + + await controller.getAllBoats({ page: '-3', perPage: '100000' }); + + expect(boatsService.getAllBoats).toHaveBeenCalledWith( + expect.objectContaining({ page: 1, perPage: 100 }), + ); + }); + + it('admin/all normaliza page negativo e limita perPage a 100', async () => { + const { controller, boatsService, prisma } = mkListController(); + prisma.user.findUnique.mockResolvedValue(owner); + + await controller.getAllBoatsForAdmin( + { page: '-1', perPage: '100000' }, + owner, + ); + + expect(boatsService.getAllBoats).toHaveBeenCalledWith( + expect.objectContaining({ page: 1, perPage: 100 }), + true, + ); + }); +}); diff --git a/backend/src/features/boats/boats.controller.ts b/backend/src/features/boats/boats.controller.ts index 7158eaa..7477599 100644 --- a/backend/src/features/boats/boats.controller.ts +++ b/backend/src/features/boats/boats.controller.ts @@ -42,6 +42,7 @@ import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; import { TransferProductDto } from '../products/dto/transfer-product.dto'; import { transferProductAsAdmin } from '../products/product-transfer'; +import { parsePaginationParams } from 'src/shared/helpers/pagination-params.helper'; @Controller('boats') export class BoatsController { @@ -174,8 +175,9 @@ export class BoatsController { async getAllBoats(@Query() query: any) { // Tratamento das varíaveis recebidas do front let { page, perPage, ...rawFilters } = query; - page = Number(page); - perPage = Number(perPage); + // Rota pública (sem login): limita perPage para ninguém pedir o catálogo + // inteiro de uma vez, com uma URL do S3 assinada por imagem. + ({ page, perPage } = parsePaginationParams(page, perPage)); const appliedFilters: FiltersBoatMeta = rawFilters; @@ -196,7 +198,7 @@ export class BoatsController { // Atualiza os metadados de paginação const pagination = new PaginationDto(); pagination.current_page = page; - pagination.total_pages = count / perPage; + pagination.total_pages = Math.ceil(count / perPage); pagination.has_next = skip + perPage < count; pagination.has_prev = skip > 0; pagination.total = count; @@ -216,15 +218,17 @@ export class BoatsController { }; } + // SPECIALIST também acessa (tela "Gestão de Produtos", inclui inativos): + // o ActorContextService força specialistId = próprio id e responde 403 se + // target_specialist_id for de outro especialista ou a especialidade divergir. @Get('admin/all') - @Roles(UserRole.ADMIN) + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async getAllBoatsForAdmin( @Query() query: any, @CurrentUser() user: UserEntity, ) { let { page, perPage, target_specialist_id, ...rawFilters } = query; - page = Number(page) || 1; - perPage = Number(perPage) || 20; + ({ page, perPage } = parsePaginationParams(page, perPage)); const context = await this.actorContextService.resolve( user, target_specialist_id, diff --git a/backend/src/features/boats/boats.service.spec.ts b/backend/src/features/boats/boats.service.spec.ts new file mode 100644 index 0000000..50a9684 --- /dev/null +++ b/backend/src/features/boats/boats.service.spec.ts @@ -0,0 +1,134 @@ +import { BoatsService } from './boats.service'; + +describe('BoatsService — getAllBoats (busca e ordenação)', () => { + function mkService() { + const findMany = jest.fn().mockResolvedValue([]); + const count = jest.fn().mockResolvedValue(0); + const prisma = { + boat: { findMany, count }, + $transaction: jest.fn((ops: Promise[]) => Promise.all(ops)), + } as any; + const service = new BoatsService(prisma, {} as any); + return { service, findMany, count }; + } + + it('ordena por created_at desc e id asc para paginação estável', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ page: 2, perPage: 20, appliedFilters: {} }); + + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + skip: 20, + take: 20, + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], + }), + ); + }); + + it('busca em marca/modelo (insensitive) sem ano quando o termo não é um ano', async () => { + const { service, findMany, count } = mkService(); + + await service.getAllBoats( + { + page: 1, + perPage: 20, + appliedFilters: { search: ' Fer ', specialist_id: 'spec-1' }, + }, + true, + ); + + const expectedWhere = { + specialist_id: 'spec-1', + OR: [ + { marca: { contains: 'Fer', mode: 'insensitive' } }, + { modelo: { contains: 'Fer', mode: 'insensitive' } }, + + { estado: { contains: 'Fer', mode: 'insensitive' } }, + ], + }; + expect(findMany.mock.calls[0][0].where).toEqual(expectedWhere); + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + }); + + it('inclui ano exato quando o termo tem 4 dígitos', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ + page: 1, + perPage: 20, + appliedFilters: { search: '2021' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + OR: [ + { marca: { contains: '2021', mode: 'insensitive' } }, + { modelo: { contains: '2021', mode: 'insensitive' } }, + + { estado: { contains: '2021', mode: 'insensitive' } }, + { ano: 2021 }, + ], + }); + }); + + it('ignora busca vazia ou só com espaços', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ + page: 1, + perPage: 20, + appliedFilters: { search: ' ' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ is_active: true }); + }); + + it('limita o termo de busca a 100 caracteres', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ + page: 1, + perPage: 20, + appliedFilters: { search: 'x'.repeat(150) }, + }); + + expect(findMany.mock.calls[0][0].where.OR[0].marca.contains).toHaveLength( + 100, + ); + }); + + it('filtra faixas de ano e preço na direção certa, em `valor` e como número', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ + page: 1, + perPage: 20, + // Como chega da query string: texto. + appliedFilters: { + ano_min: '2018', + ano_max: '2022', + preco_min: '1000000', + preco_max: '5000000', + } as any, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + ano: { gte: 2018, lte: 2022 }, + valor: { gte: 1000000, lte: 5000000 }, + }); + }); + + it('ignora limites de faixa vazios ou não numéricos', async () => { + const { service, findMany } = mkService(); + + await service.getAllBoats({ + page: 1, + perPage: 20, + appliedFilters: { ano_min: 'abc', preco_max: '' } as any, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ is_active: true }); + }); +}); diff --git a/backend/src/features/boats/boats.service.ts b/backend/src/features/boats/boats.service.ts index 13957af..347da5d 100644 --- a/backend/src/features/boats/boats.service.ts +++ b/backend/src/features/boats/boats.service.ts @@ -14,7 +14,6 @@ import { ContainsBoatFilters, ExactBoatFilters, FiltersBoatMeta, - RangeBoatFilters, } from 'src/shared/dto/filters.dto'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; import { publicBoatSelect } from 'src/shared/selects/public-catalog.select'; @@ -25,6 +24,8 @@ import { PreparedProductImage, ProductImageInput, } from '../products/product-image-preparation'; +import { buildProductSearchConditions } from 'src/shared/helpers/product-search.helper'; +import { applyRangeFilters } from 'src/shared/helpers/product-range.helper'; @Injectable() export class BoatsService { @@ -159,40 +160,39 @@ export class BoatsService { } } - // Range - const rangeFilter: RangeBoatFilters = { - ano_max: appliedFilters?.ano_max, - ano_min: appliedFilters?.ano_min, - preco_max: appliedFilters?.preco_max, - preco_min: appliedFilters?.preco_min, - }; - // Objeto para orientar o where que utiliza gte e lte - const rangeMap = { - ano: { gte: rangeFilter.ano_max, lte: rangeFilter.ano_min }, - preco: { gte: rangeFilter.preco_max, lte: rangeFilter.preco_min }, - }; - // Insere a filtragem como um intervalo na variável where - for (const [key, { gte, lte }] of Object.entries(rangeMap)) { - const hasGte = gte !== undefined && gte !== null; - const hasLte = lte !== undefined && lte !== null; - if (hasGte || hasLte) { - where[key] = {}; - if (hasGte) where[key].gte = gte; - if (hasLte) where[key].lte = lte; - } - } + // Range: antes o min/max estavam invertidos e o preço apontava para + // `preco`, coluna que não existe (é `valor`). + applyRangeFilters(where, { + ano: { + min: appliedFilters?.ano_min, + max: appliedFilters?.ano_max, + integer: true, + }, + valor: { min: appliedFilters?.preco_min, max: appliedFilters?.preco_max }, + }); // Filtro por especialista (usado na tela "Meus Produtos") if (appliedFilters?.specialist_id) { where.specialist_id = appliedFilters.specialist_id; } + // Busca textual (marca/modelo/estado e ano exato) — usada na "Gestão de Produtos". + // Nenhum outro filtro usa `OR`; se passar a usar, combinar via `AND`. + const searchConditions = buildProductSearchConditions( + appliedFilters?.search, + ); + if (searchConditions) { + where.OR = searchConditions; + } + // Agrupamento das operções para serem realizadas no banco de dados const [boats, total] = await this.prismaService.$transaction([ this.prismaService.boat.findMany({ skip: skip, take: take, where: where, + // Ordem estável para a paginação não repetir/pular itens. + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], select: publicBoatSelect, }), this.prismaService.boat.count({ where }), diff --git a/backend/src/features/cars/cars.controller.spec.ts b/backend/src/features/cars/cars.controller.spec.ts index bfc5129..4df712f 100644 --- a/backend/src/features/cars/cars.controller.spec.ts +++ b/backend/src/features/cars/cars.controller.spec.ts @@ -1,4 +1,8 @@ -import { ProductType } from '@prisma/client'; +import { ProductType, UserRole } from '@prisma/client'; +import { Reflector } from '@nestjs/core'; +import { ForbiddenException } from '@nestjs/common'; +import { ROLES_KEY } from 'src/shared/decorators/roles.decorator'; +import { ActorContextService } from 'src/shared/actor-context/actor-context.service'; import { CarsController } from './cars.controller'; function mkController() { @@ -170,11 +174,7 @@ describe('CarsController — Calendly opcional', () => { const { controller, carsService } = mkController(); await expect( - controller.update( - 'car-1', - { specialist_id: null } as any, - specialist, - ), + controller.update('car-1', { specialist_id: null } as any, specialist), ).rejects.toMatchObject({ status: 400 }); expect(carsService.update).not.toHaveBeenCalled(); }); @@ -202,3 +202,84 @@ describe('CarsController — Calendly opcional', () => { ); }); }); + +describe('CarsController — admin/all (Gestão de Produtos)', () => { + function mkListController() { + const carsService = { + getAllCars: jest.fn().mockResolvedValue({ + data: [], + count: 0, + filters: {}, + }), + } as any; + const prisma = { user: { findUnique: jest.fn() } } as any; + // ActorContextService real: é ele quem restringe o SPECIALIST a si mesmo. + const actorContext = new ActorContextService(prisma); + const controller = new (CarsController as any)( + carsService, + {} as any, + actorContext, + {} as any, + prisma, + ); + return { controller, carsService, prisma }; + } + + const owner = { + id: 'spec-1', + role: UserRole.SPECIALIST, + speciality: ProductType.CAR, + is_active: true, + name: 'Esp', + surname: 'Um', + } as any; + + it('libera ADMIN e SPECIALIST nos metadados de roles', () => { + const roles = new Reflector().get( + ROLES_KEY, + CarsController.prototype.getAllCarsForAdmin, + ); + expect(roles).toEqual( + expect.arrayContaining([UserRole.ADMIN, UserRole.SPECIALIST]), + ); + }); + + it('lista só os produtos do próprio especialista, incluindo inativos', async () => { + const { controller, carsService } = mkListController(); + + await controller.getAllCarsForAdmin( + { page: '2', perPage: '20', search: 'abc', specialist_id: 'spec-2' }, + owner, + ); + + expect(carsService.getAllCars).toHaveBeenCalledWith( + { + page: 2, + perPage: 20, + appliedFilters: { search: 'abc', specialist_id: 'spec-1' }, + }, + true, + ); + }); + + it('responde 403 se o especialista pedir outro target_specialist_id', async () => { + const { controller, carsService } = mkListController(); + + await expect( + controller.getAllCarsForAdmin({ target_specialist_id: 'spec-2' }, owner), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(carsService.getAllCars).not.toHaveBeenCalled(); + }); + + it('responde 403 se a especialidade não corresponder ao recurso', async () => { + const { controller, carsService } = mkListController(); + + await expect( + controller.getAllCarsForAdmin( + {}, + { ...owner, speciality: ProductType.BOAT }, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(carsService.getAllCars).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/features/cars/cars.controller.ts b/backend/src/features/cars/cars.controller.ts index b415380..4b9697b 100644 --- a/backend/src/features/cars/cars.controller.ts +++ b/backend/src/features/cars/cars.controller.ts @@ -39,6 +39,7 @@ import { PrismaService } from 'src/prisma/prisma.service'; import { randomUUID } from 'node:crypto'; import { TransferProductDto } from '../products/dto/transfer-product.dto'; import { transferProductAsAdmin } from '../products/product-transfer'; +import { parsePaginationParams } from 'src/shared/helpers/pagination-params.helper'; @Controller('cars') export class CarsController { @@ -171,8 +172,9 @@ export class CarsController { async getAllCars(@Query() query: any) { // Extrai paginação e considera o restante como filtros let { page, perPage, ...rawFilters } = query; - page = Number(page); - perPage = Number(perPage); + // Rota pública (sem login): limita perPage para ninguém pedir o catálogo + // inteiro de uma vez, com uma URL do S3 assinada por imagem. + ({ page, perPage } = parsePaginationParams(page, perPage)); const appliedFilters: FiltersCarMeta = rawFilters; @@ -193,7 +195,7 @@ export class CarsController { // Atualiza os metadados de paginação const pagination = new PaginationDto(); pagination.current_page = page; - pagination.total_pages = count / perPage; + pagination.total_pages = Math.ceil(count / perPage); pagination.has_next = skip + perPage < count; pagination.has_prev = skip > 0; pagination.total = count; @@ -213,15 +215,17 @@ export class CarsController { }; } + // SPECIALIST também acessa (tela "Gestão de Produtos", inclui inativos): + // o ActorContextService força specialistId = próprio id e responde 403 se + // target_specialist_id for de outro especialista ou a especialidade divergir. @Get('admin/all') - @Roles(UserRole.ADMIN) + @Roles(UserRole.ADMIN, UserRole.SPECIALIST) async getAllCarsForAdmin( @Query() query: any, @CurrentUser() user: UserEntity, ) { let { page, perPage, target_specialist_id, ...rawFilters } = query; - page = Number(page) || 1; - perPage = Number(perPage) || 20; + ({ page, perPage } = parsePaginationParams(page, perPage)); const context = await this.actorContextService.resolve( user, target_specialist_id, diff --git a/backend/src/features/cars/cars.service.spec.ts b/backend/src/features/cars/cars.service.spec.ts index a8ff938..fbdebac 100644 --- a/backend/src/features/cars/cars.service.spec.ts +++ b/backend/src/features/cars/cars.service.spec.ts @@ -11,11 +11,7 @@ describe('CarsService — UUID do produto', () => { currency: ProductCurrency.BRL, images: [], }); - const service = new CarsService( - { car: { findUnique } } as any, - {} as any, - {} as any, - ); + const service = new CarsService({ car: { findUnique } } as any, {} as any); const result = await service.findOne(carId); @@ -62,3 +58,123 @@ describe('CarsService — UUID do produto', () => { }); }); }); + +describe('CarsService — getAllCars (busca e ordenação)', () => { + function mkService() { + const findMany = jest.fn().mockResolvedValue([]); + const count = jest.fn().mockResolvedValue(0); + const prisma = { + car: { findMany, count }, + $transaction: jest.fn((ops: Promise[]) => Promise.all(ops)), + } as any; + const service = new CarsService(prisma, {} as any); + return { service, findMany, count }; + } + + it('ordena por created_at desc e id asc para paginação estável', async () => { + const { service, findMany } = mkService(); + + await service.getAllCars({ page: 2, perPage: 20, appliedFilters: {} }); + + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + skip: 20, + take: 20, + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], + }), + ); + }); + + it('busca em marca/modelo (insensitive) sem ano quando o termo não é um ano', async () => { + const { service, findMany, count } = mkService(); + + await service.getAllCars( + { + page: 1, + perPage: 20, + appliedFilters: { search: ' Fer ', specialist_id: 'spec-1' }, + }, + true, + ); + + const expectedWhere = { + specialist_id: 'spec-1', + OR: [ + { marca: { contains: 'Fer', mode: 'insensitive' } }, + { modelo: { contains: 'Fer', mode: 'insensitive' } }, + + { estado: { contains: 'Fer', mode: 'insensitive' } }, + ], + }; + expect(findMany.mock.calls[0][0].where).toEqual(expectedWhere); + expect(count).toHaveBeenCalledWith({ where: expectedWhere }); + }); + + it('inclui ano exato quando o termo tem 4 dígitos', async () => { + const { service, findMany } = mkService(); + + await service.getAllCars({ + page: 1, + perPage: 20, + appliedFilters: { search: '2021' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + OR: [ + { marca: { contains: '2021', mode: 'insensitive' } }, + { modelo: { contains: '2021', mode: 'insensitive' } }, + + { estado: { contains: '2021', mode: 'insensitive' } }, + { ano: 2021 }, + ], + }); + }); + + it('ignora busca vazia ou só com espaços', async () => { + const { service, findMany } = mkService(); + + await service.getAllCars({ + page: 1, + perPage: 20, + appliedFilters: { search: ' ' }, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ is_active: true }); + }); + + it('limita o termo de busca a 100 caracteres', async () => { + const { service, findMany } = mkService(); + + await service.getAllCars({ + page: 1, + perPage: 20, + appliedFilters: { search: 'x'.repeat(150) }, + }); + + expect(findMany.mock.calls[0][0].where.OR[0].marca.contains).toHaveLength( + 100, + ); + }); + + it('converte faixas da query em número e filtra preço em `valor`', async () => { + const { service, findMany } = mkService(); + + await service.getAllCars({ + page: 1, + perPage: 20, + appliedFilters: { + ano_min: '2019', + preco_max: '900000', + km_max: '30000', + } as any, + }); + + expect(findMany.mock.calls[0][0].where).toEqual({ + is_active: true, + ano: { gte: 2019 }, + valor: { lte: 900000 }, + km: { lte: 30000 }, + }); + }); +}); diff --git a/backend/src/features/cars/cars.service.ts b/backend/src/features/cars/cars.service.ts index c7df451..28f5fe7 100644 --- a/backend/src/features/cars/cars.service.ts +++ b/backend/src/features/cars/cars.service.ts @@ -14,7 +14,6 @@ import { ContainsCarFilters, ExactCarFilters, FiltersCarMeta, - RangeCarFilters, } from 'src/shared/dto/filters.dto'; import { updateProductWithMonetaryLock } from '../products/product-monetary-lock'; import { publicCarSelect } from 'src/shared/selects/public-catalog.select'; @@ -25,6 +24,8 @@ import { PreparedProductImage, ProductImageInput, } from '../products/product-image-preparation'; +import { buildProductSearchConditions } from 'src/shared/helpers/product-search.helper'; +import { applyRangeFilters } from 'src/shared/helpers/product-range.helper'; @Injectable() export class CarsService { @@ -138,43 +139,39 @@ export class CarsService { } } - // Range - const rangeFilters: RangeCarFilters = { - ano_max: appliedFilters?.ano_max, - ano_min: appliedFilters?.ano_min, - km_max: appliedFilters?.km_max, - preco_max: appliedFilters?.preco_max, - preco_min: appliedFilters?.preco_min, - }; - // Cria um objeto para orientar um where que usa gte e lte - const rangeMap = { - preco: { gte: rangeFilters.preco_min, lte: rangeFilters.preco_max }, - ano: { gte: rangeFilters.ano_min, lte: rangeFilters.ano_max }, - km: { gte: undefined, lte: rangeFilters.km_max }, - }; - // Insere a filtragem que são um intervalo na variável where - for (const [key, { gte, lte }] of Object.entries(rangeMap)) { - const hasGte = gte !== undefined && gte !== null; - const hasLte = lte !== undefined && lte !== null; - // Crie o objeto caso tenha lte ou gte - if (hasGte || hasLte) { - where[key] = {}; - if (hasGte) where[key].gte = gte; - if (hasLte) where[key].lte = lte; - } - } + // Range: coluna de preço é `valor`; valores da query chegam como texto. + applyRangeFilters(where, { + valor: { min: appliedFilters?.preco_min, max: appliedFilters?.preco_max }, + ano: { + min: appliedFilters?.ano_min, + max: appliedFilters?.ano_max, + integer: true, + }, + km: { min: undefined, max: appliedFilters?.km_max, integer: true }, + }); // Filtro por especialista (usado na tela "Meus Produtos") if (appliedFilters?.specialist_id) { where.specialist_id = appliedFilters.specialist_id; } + // Busca textual (marca/modelo/estado e ano exato) — usada na "Gestão de Produtos". + // Nenhum outro filtro usa `OR`; se passar a usar, combinar via `AND`. + const searchConditions = buildProductSearchConditions( + appliedFilters?.search, + ); + if (searchConditions) { + where.OR = searchConditions; + } + // Agrupamento de operações para serem realizadas no banco de dados const [cars, total] = await this.prismaService.$transaction([ this.prismaService.car.findMany({ skip: skip, take: take, where: where, + // Ordem estável para a paginação não repetir/pular itens. + orderBy: [{ created_at: 'desc' }, { id: 'asc' }], select: publicCarSelect, }), this.prismaService.car.count({ where }), diff --git a/backend/src/shared/dto/filters.dto.ts b/backend/src/shared/dto/filters.dto.ts index 419a406..1652c8d 100644 --- a/backend/src/shared/dto/filters.dto.ts +++ b/backend/src/shared/dto/filters.dto.ts @@ -45,13 +45,6 @@ export class ExactCarFilters { cambio?: cambioCarValues; combustivel?: combustivelCarValues; } -export class RangeCarFilters { - ano_min?: number; - ano_max?: number; - preco_min?: number; - preco_max?: number; - km_max?: number; -} // Barco export type combustivelBoatValues = [ @@ -63,6 +56,7 @@ export type combustivelBoatValues = [ export type tipoEmbarcacaoBoatValues = string; export type tamanhoBoatValues = ['ate_30_pes', '30_50_pes', 'acima_50_pes']; export class FiltersBoatMeta { + search?: string; marca?: string; modelo?: string; ano_min?: number; @@ -91,16 +85,11 @@ export class ContainsBoatFilters { fabricante?: string; motor?: string; } -export class RangeBoatFilters { - ano_min?: number; - ano_max?: number; - preco_min?: number; - preco_max?: number; -} // Aeronaves export type tipoAeronaveValues = string; export class FiltersAircraftMeta { + search?: string; marca?: string; modelo?: string; ano_min?: number; @@ -124,14 +113,6 @@ export class ContainsAircraftFilters { modelo?: string; categoria?: string; } -export class RangeAircraftFilters { - ano_min?: number; - ano_max?: number; - preco_min?: number; - preco_max?: number; - assentos_min?: number; - assentos_max?: number; -} // MetaData de filtros export class FiltersDto { diff --git a/backend/src/shared/helpers/pagination-params.helper.spec.ts b/backend/src/shared/helpers/pagination-params.helper.spec.ts new file mode 100644 index 0000000..5d3952f --- /dev/null +++ b/backend/src/shared/helpers/pagination-params.helper.spec.ts @@ -0,0 +1,26 @@ +import { parsePaginationParams } from './pagination-params.helper'; + +describe('parsePaginationParams', () => { + it('converte a query e mantém valores válidos', () => { + expect(parsePaginationParams('3', '20')).toEqual({ page: 3, perPage: 20 }); + }); + + it('usa página 1 e 20 itens quando ausente ou inválido', () => { + expect(parsePaginationParams(undefined, undefined)).toEqual({ + page: 1, + perPage: 20, + }); + expect(parsePaginationParams('-1', '0')).toEqual({ page: 1, perPage: 20 }); + expect(parsePaginationParams('2.5', 'abc')).toEqual({ + page: 1, + perPage: 20, + }); + }); + + it('limita perPage a 100', () => { + expect(parsePaginationParams('1', '100000')).toEqual({ + page: 1, + perPage: 100, + }); + }); +}); diff --git a/backend/src/shared/helpers/pagination-params.helper.ts b/backend/src/shared/helpers/pagination-params.helper.ts new file mode 100644 index 0000000..0f84dba --- /dev/null +++ b/backend/src/shared/helpers/pagination-params.helper.ts @@ -0,0 +1,23 @@ +export const MAX_PER_PAGE = 100; +const DEFAULT_PER_PAGE = 20; + +function toPositiveInt(value: unknown): number | undefined { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed >= 1 ? parsed : undefined; +} + +/** + * Normaliza `page`/`perPage` vindos da query: página inteira >= 1 e até + * MAX_PER_PAGE itens por página. + * Evita `skip` negativo (erro do Prisma) e páginas gigantes, que assinariam + * uma URL do S3 por imagem de cada produto numa só requisição. + */ +export function parsePaginationParams( + page: unknown, + perPage: unknown, +): { page: number; perPage: number } { + return { + page: toPositiveInt(page) ?? 1, + perPage: Math.min(toPositiveInt(perPage) ?? DEFAULT_PER_PAGE, MAX_PER_PAGE), + }; +} diff --git a/backend/src/shared/helpers/product-range.helper.spec.ts b/backend/src/shared/helpers/product-range.helper.spec.ts new file mode 100644 index 0000000..288e257 --- /dev/null +++ b/backend/src/shared/helpers/product-range.helper.spec.ts @@ -0,0 +1,59 @@ +import { + applyRangeFilters, + buildRangeCondition, + toFilterNumber, +} from './product-range.helper'; + +describe('product-range.helper', () => { + it('converte texto numérico da query em número', () => { + expect(toFilterNumber('2020')).toBe(2020); + expect(toFilterNumber(' 1500000.5 ')).toBe(1500000.5); + expect(toFilterNumber(42)).toBe(42); + }); + + it('descarta vazio, não numérico, infinito e valores repetidos', () => { + expect(toFilterNumber('')).toBeUndefined(); + expect(toFilterNumber(' ')).toBeUndefined(); + expect(toFilterNumber('abc')).toBeUndefined(); + expect(toFilterNumber('Infinity')).toBeUndefined(); + expect(toFilterNumber(Number.NaN)).toBeUndefined(); + expect(toFilterNumber(['1', '2'])).toBeUndefined(); + expect(toFilterNumber(undefined)).toBeUndefined(); + expect(toFilterNumber(null)).toBeUndefined(); + }); + + it('monta gte a partir do mínimo e lte a partir do máximo', () => { + expect(buildRangeCondition('2018', '2022')).toEqual({ + gte: 2018, + lte: 2022, + }); + expect(buildRangeCondition('2018', undefined)).toEqual({ gte: 2018 }); + expect(buildRangeCondition(undefined, '2022')).toEqual({ lte: 2022 }); + expect(buildRangeCondition('', 'x')).toBeUndefined(); + }); + + it('aplica só as faixas com algum limite válido', () => { + const where: Record = { is_active: true }; + applyRangeFilters(where, { + ano: { min: '2018', max: undefined }, + valor: { min: '', max: '' }, + }); + expect(where).toEqual({ is_active: true, ano: { gte: 2018 } }); + }); +}); + +describe('product-range.helper — colunas Int', () => { + it('ignora decimal e valor fora do int32 quando a coluna é Int', () => { + expect(buildRangeCondition('2020.5', '2022', true)).toEqual({ lte: 2022 }); + expect(buildRangeCondition('1e12', undefined, true)).toBeUndefined(); + expect(buildRangeCondition('2147483647', undefined, true)).toEqual({ + gte: 2147483647, + }); + }); + + it('mantém decimais para colunas Decimal (valor)', () => { + expect(buildRangeCondition('1500000.50', undefined)).toEqual({ + gte: 1500000.5, + }); + }); +}); diff --git a/backend/src/shared/helpers/product-range.helper.ts b/backend/src/shared/helpers/product-range.helper.ts new file mode 100644 index 0000000..68c0982 --- /dev/null +++ b/backend/src/shared/helpers/product-range.helper.ts @@ -0,0 +1,64 @@ +/** + * Filtros de faixa das listagens de produtos (carros, lanchas e aeronaves). + * + * Os valores chegam da query string como texto (`@Query() query: any` não + * passa por DTO, então o ValidationPipe não converte nada). O Prisma rejeita + * texto em colunas Int/Decimal, por isso a conversão acontece aqui. + */ + +/** + * Converte um valor de query em número finito. Vazio, não numérico ou repetido + * (`?ano_min=1&ano_min=2` chega como array) vira `undefined` e o filtro é + * ignorado, em vez de derrubar a listagem com erro do Prisma. + */ +export function toFilterNumber(value: unknown): number | undefined { + if (typeof value === 'number') { + return Number.isFinite(value) ? value : undefined; + } + if (typeof value !== 'string') return undefined; + const trimmed = value.trim(); + if (!trimmed) return undefined; + const parsed = Number(trimmed); + return Number.isFinite(parsed) ? parsed : undefined; +} + +const INT32_MIN = -2147483648; +const INT32_MAX = 2147483647; + +// Colunas Int do Postgres não aceitam decimal nem valor fora do int32: o +// Prisma rejeitaria a query inteira, então o limite é ignorado. +function toIntFilterNumber(value: unknown): number | undefined { + const parsed = toFilterNumber(value); + if (parsed === undefined || !Number.isInteger(parsed)) return undefined; + return parsed >= INT32_MIN && parsed <= INT32_MAX ? parsed : undefined; +} + +/** + * Monta `{ gte: min, lte: max }` para o Prisma; `undefined` quando nenhum + * limite válido foi informado. `integer` para colunas Int (ano, km, assentos). + */ +export function buildRangeCondition( + min: unknown, + max: unknown, + integer = false, +): { gte?: number; lte?: number } | undefined { + const parse = integer ? toIntFilterNumber : toFilterNumber; + const gte = parse(min); + const lte = parse(max); + if (gte === undefined && lte === undefined) return undefined; + return { + ...(gte !== undefined ? { gte } : {}), + ...(lte !== undefined ? { lte } : {}), + }; +} + +/** Aplica cada faixa válida em `where[campo]`. */ +export function applyRangeFilters( + where: Record, + ranges: Record, +): void { + for (const [field, { min, max, integer }] of Object.entries(ranges)) { + const condition = buildRangeCondition(min, max, integer); + if (condition) where[field] = condition; + } +} diff --git a/backend/src/shared/helpers/product-search.helper.ts b/backend/src/shared/helpers/product-search.helper.ts new file mode 100644 index 0000000..96f5de7 --- /dev/null +++ b/backend/src/shared/helpers/product-search.helper.ts @@ -0,0 +1,27 @@ +export const PRODUCT_SEARCH_MAX_LENGTH = 100; + +/** + * Monta as condições de busca textual das listagens de produtos (carros, + * lanchas e aeronaves): `marca`/`modelo`/`estado` por `contains` sem diferenciar + * maiúsculas e, quando o termo for um número de 4 dígitos, `ano` exato. + * + * Retorna `undefined` quando não há termo útil (ausente, vazio, só espaços + * ou não-string — ex.: `?search=a&search=b` chega como array). + */ +export function buildProductSearchConditions( + search: unknown, +): Record[] | undefined { + if (typeof search !== 'string') return undefined; + const term = search.trim().slice(0, PRODUCT_SEARCH_MAX_LENGTH).trim(); + if (!term) return undefined; + + const conditions: Record[] = [ + { marca: { contains: term, mode: 'insensitive' } }, + { modelo: { contains: term, mode: 'insensitive' } }, + { estado: { contains: term, mode: 'insensitive' } }, + ]; + if (/^\d{4}$/.test(term)) { + conditions.push({ ano: Number(term) }); + } + return conditions; +} diff --git a/docs/e2e-evidence/specialist-products-pagination/antes-fim-da-lista.jpg b/docs/e2e-evidence/specialist-products-pagination/antes-fim-da-lista.jpg new file mode 100644 index 0000000..4965077 Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/antes-fim-da-lista.jpg differ diff --git a/docs/e2e-evidence/specialist-products-pagination/antes-topo.jpg b/docs/e2e-evidence/specialist-products-pagination/antes-topo.jpg new file mode 100644 index 0000000..5038f73 Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/antes-topo.jpg differ diff --git a/docs/e2e-evidence/specialist-products-pagination/depois-busca.jpg b/docs/e2e-evidence/specialist-products-pagination/depois-busca.jpg new file mode 100644 index 0000000..f537e6e Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/depois-busca.jpg differ diff --git a/docs/e2e-evidence/specialist-products-pagination/depois-desativar.jpg b/docs/e2e-evidence/specialist-products-pagination/depois-desativar.jpg new file mode 100644 index 0000000..c8a94cc Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/depois-desativar.jpg differ diff --git a/docs/e2e-evidence/specialist-products-pagination/depois-fim-da-pagina.jpg b/docs/e2e-evidence/specialist-products-pagination/depois-fim-da-pagina.jpg new file mode 100644 index 0000000..64f0807 Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/depois-fim-da-pagina.jpg differ diff --git a/docs/e2e-evidence/specialist-products-pagination/depois-topo.jpg b/docs/e2e-evidence/specialist-products-pagination/depois-topo.jpg new file mode 100644 index 0000000..ab66008 Binary files /dev/null and b/docs/e2e-evidence/specialist-products-pagination/depois-topo.jpg differ diff --git a/frontend/src/components/specialist/ResponsiveProductList.test.tsx b/frontend/src/components/specialist/ResponsiveProductList.test.tsx index 580fb92..19e6018 100644 --- a/frontend/src/components/specialist/ResponsiveProductList.test.tsx +++ b/frontend/src/components/specialist/ResponsiveProductList.test.tsx @@ -57,7 +57,7 @@ describe("ResponsiveProductList", () => { expect(screen.getAllByText("US$ 120.000,00")).toHaveLength(2); }); - it("mantém ações de editar e excluir acessíveis nos cartões", () => { + it("mantém ações de editar e desativar acessíveis nos cartões", () => { const onEdit = vi.fn(); const onDelete = vi.fn(); @@ -76,11 +76,35 @@ describe("ResponsiveProductList", () => { ); fireEvent.click( screen.getAllByRole("button", { - name: "Excluir Aurum Sedan 120", + name: "Desativar Aurum Sedan 120", })[0], ); expect(onEdit).toHaveBeenCalledWith("brl"); expect(onDelete).toHaveBeenCalledWith("brl"); }); + + it("marca produto inativo e não oferece desativá-lo de novo", () => { + render( + , + ); + + // Cartão + tabela renderizam juntos; o CSS escolhe qual aparece. + expect(screen.getAllByText("Inativo")).toHaveLength(2); + expect( + screen.queryAllByRole("button", { name: "Desativar Aurum Sedan 120" }), + ).toHaveLength(0); + expect( + screen.getAllByRole("button", { name: "Editar Aurum Sedan 120" }), + ).toHaveLength(2); + expect( + screen.getAllByRole("button", { + name: "Desativar Aurum Grand Tourer 120", + }), + ).toHaveLength(2); + }); }); diff --git a/frontend/src/components/specialist/ResponsiveProductList.tsx b/frontend/src/components/specialist/ResponsiveProductList.tsx index 58347b8..76b1055 100644 --- a/frontend/src/components/specialist/ResponsiveProductList.tsx +++ b/frontend/src/components/specialist/ResponsiveProductList.tsx @@ -12,6 +12,8 @@ export interface ProductListItem { estado?: string; descricao?: string; imageUrl?: string; + // Ausente = ativo (listas antigas não mandam o campo). + is_active?: boolean; } interface ResponsiveProductListProps { @@ -32,6 +34,20 @@ function CurrencyBadge({ currency }: { currency: ProductCurrency }) { ); } +function isInactive(product: ProductListItem) { + return product.is_active === false; +} + +// Desativar não apaga: o produto sai do catálogo público mas continua na +// lista do especialista, por isso o selo e a ausência do botão de desativar. +function InactiveBadge() { + return ( + + Inativo + + ); +} + function ProductImage({ product, className, @@ -89,6 +105,7 @@ export default function ResponsiveProductList({ {productName} + {isInactive(product) && }

{formatCurrency(product.valor, product.currency)} @@ -117,21 +134,23 @@ export default function ResponsiveProductList({ - + {!isInactive(product) && ( + + )} ); @@ -179,6 +198,7 @@ export default function ResponsiveProductList({ {productName} + {isInactive(product) && } @@ -203,15 +223,21 @@ export default function ResponsiveProductList({ > - + {/* Espaço do botão ausente mantém o lápis alinhado. */} + {isInactive(product) && ( + + )} + {!isInactive(product) && ( + + )} diff --git a/frontend/src/pages/specialist/ProductsPage.test.tsx b/frontend/src/pages/specialist/ProductsPage.test.tsx new file mode 100644 index 0000000..dcde2c5 --- /dev/null +++ b/frontend/src/pages/specialist/ProductsPage.test.tsx @@ -0,0 +1,274 @@ +// @vitest-environment jsdom + +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import ProductsPage from "./ProductsPage"; +import { + getAdminSpecialistProducts, + type AdminCatalogProduct, +} from "../../services/admin-specialist-journey.service"; +import type { PaginationMeta } from "../../types/types"; +import { deleteBoat } from "../../services/boats.service"; + +const authState: { user: Record | null } = { user: null }; + +vi.mock("../../store/authStateManager", () => ({ + useAuth: (selector: (state: typeof authState) => unknown) => + selector(authState), +})); + +vi.mock("../../services/admin-specialist-journey.service", () => ({ + getAdminSpecialistProducts: vi.fn(), +})); + +vi.mock("../../services/cars.service", () => ({ deleteCar: vi.fn() })); +vi.mock("../../services/boats.service", () => ({ deleteBoat: vi.fn() })); +vi.mock("../../services/aircrafts.service", () => ({ + deleteAircraft: vi.fn(), +})); + +const getProducts = vi.mocked(getAdminSpecialistProducts); + +function boat(id: string, modelo: string, isActive = true): AdminCatalogProduct { + return { + id, + marca: "Azimut", + modelo, + ano: 2024, + valor: 1000000, + currency: "BRL", + estado: "novo", + imageUrl: "", + specialist_id: "paulo", + is_active: isActive, + } as unknown as AdminCatalogProduct; +} + +function pageResult( + products: AdminCatalogProduct[], + pagination: Partial, +) { + return { + products, + pagination: { + current_page: 1, + per_page: 20, + total: products.length, + total_pages: 1, + has_next: false, + has_prev: false, + ...pagination, + } as PaginationMeta, + }; +} + +function renderPage() { + const utils = render( + + + , + ); + return { + ...utils, + setSearch: (term: string) => + fireEvent.change(screen.getByLabelText("Buscar produtos"), { + target: { value: term }, + }), + }; +} + +beforeEach(() => { + authState.user = { id: "paulo", role: "SPECIALIST", speciality: "BOAT" }; +}); + +afterEach(() => { + cleanup(); + vi.clearAllMocks(); + vi.restoreAllMocks(); +}); + +describe("ProductsPage (especialista)", () => { + it("pagina no servidor só os produtos do especialista, incluindo inativos", async () => { + getProducts + .mockResolvedValueOnce( + pageResult([boat("b1", "Flybridge 68"), boat("b2", "S7", false)], { + total: 45, + total_pages: 3, + has_next: true, + }), + ) + .mockResolvedValueOnce( + pageResult([boat("b21", "Magellano 60")], { + current_page: 2, + total: 45, + total_pages: 3, + has_next: true, + has_prev: true, + }), + ); + + renderPage(); + + expect(await screen.findAllByText("Azimut Flybridge 68")).toHaveLength(2); + expect(getProducts).toHaveBeenCalledWith("BOAT", 1, 20, ""); + expect(screen.getByText("45 produtos")).toBeTruthy(); + expect(screen.getAllByText("Inativo")).toHaveLength(2); + expect(screen.getByText(/Página/).textContent).toContain("1 de 3"); + + fireEvent.click(screen.getByTitle("Próxima")); + + expect(await screen.findAllByText("Azimut Magellano 60")).toHaveLength(2); + expect(getProducts).toHaveBeenLastCalledWith("BOAT", 2, 20, ""); + expect(screen.getByText(/Página/).textContent).toContain("2 de 3"); + }); + + it("envia a busca ao servidor com debounce e volta para a primeira página", async () => { + getProducts + .mockResolvedValueOnce( + pageResult([boat("b21", "Magellano 60")], { + current_page: 1, + total: 45, + total_pages: 3, + }), + ) + .mockResolvedValueOnce(pageResult([boat("b7", "S7")], {})); + + const { setSearch } = renderPage(); + await screen.findAllByText("Azimut Magellano 60"); + + setSearch(" s7 "); + + expect(await screen.findAllByText("Azimut S7")).toHaveLength(2); + expect(getProducts).toHaveBeenCalledTimes(2); + expect(getProducts).toHaveBeenLastCalledWith("BOAT", 1, 20, "s7"); + expect(screen.queryByText(/Página/)).toBeNull(); + }); + + it("ignora resposta antiga que chega depois da busca mais recente", async () => { + let resolveFirst: (value: ReturnType) => void = () => {}; + getProducts + .mockImplementationOnce( + () => new Promise((resolve) => (resolveFirst = resolve)), + ) + .mockResolvedValueOnce(pageResult([boat("b7", "S7")], {})); + + const { setSearch } = renderPage(); + setSearch("S7"); + + expect(await screen.findAllByText("Azimut S7")).toHaveLength(2); + + await act(async () => { + resolveFirst(pageResult([boat("old", "Antigo")], {})); + }); + + expect(screen.queryByText("Azimut Antigo")).toBeNull(); + expect(screen.getAllByText("Azimut S7")).toHaveLength(2); + }); + + it("avisa quando o especialista não tem especialidade e não chama a API", async () => { + authState.user = { id: "paulo", role: "SPECIALIST" }; + + renderPage(); + + expect(screen.getByText(/não tem uma especialidade definida/)).toBeTruthy(); + await waitFor(() => expect(getProducts).not.toHaveBeenCalled()); + }); + + it("mostra erro amigável quando a listagem falha", async () => { + getProducts.mockRejectedValueOnce({ friendlyMessage: "Sem permissão." }); + + renderPage(); + + expect(await screen.findByText("Sem permissão.")).toBeTruthy(); + expect(screen.queryByText("Nenhum produto cadastrado")).toBeNull(); + }); + + it("confirma a desativação e marca o item como inativo sem recarregar", async () => { + vi.spyOn(window, "confirm").mockReturnValue(true); + vi.mocked(deleteBoat).mockResolvedValueOnce(undefined as never); + getProducts.mockResolvedValueOnce( + pageResult([boat("b1", "Flybridge 68")], {}), + ); + + renderPage(); + await screen.findAllByText("Azimut Flybridge 68"); + + fireEvent.click( + screen.getAllByRole("button", { name: "Desativar Azimut Flybridge 68" })[0], + ); + + expect(await screen.findByRole("status")).toBeTruthy(); + expect(screen.getByRole("status").textContent).toContain( + "Produto desativado", + ); + expect(deleteBoat).toHaveBeenCalledWith("b1"); + expect(getProducts).toHaveBeenCalledTimes(1); + expect(screen.getAllByText("Inativo")).toHaveLength(2); + expect(screen.queryByRole("alert", { name: /Não foi possível/ })).toBeNull(); + }); + + it("não sobrescreve uma busca feita enquanto a desativação está em andamento", async () => { + vi.spyOn(window, "confirm").mockReturnValue(true); + let resolveDelete: () => void = () => {}; + vi.mocked(deleteBoat).mockImplementationOnce( + () => new Promise((resolve) => (resolveDelete = () => resolve(undefined as never))), + ); + getProducts + .mockResolvedValueOnce( + pageResult([boat("b1", "Flybridge 68"), boat("b2", "S7")], {}), + ) + .mockResolvedValueOnce(pageResult([boat("b2", "S7")], {})); + + const { setSearch } = renderPage(); + await screen.findAllByText("Azimut Flybridge 68"); + + fireEvent.click( + screen.getAllByRole("button", { name: "Desativar Azimut Flybridge 68" })[0], + ); + setSearch("s7"); + await waitFor(() => + expect(getProducts).toHaveBeenLastCalledWith("BOAT", 1, 20, "s7"), + ); + await waitFor(() => + expect(screen.queryByText("Azimut Flybridge 68")).toBeNull(), + ); + + await act(async () => resolveDelete()); + + expect(await screen.findByRole("status")).toBeTruthy(); + // Nenhuma nova listagem com o termo antigo depois do DELETE. + expect(getProducts).toHaveBeenCalledTimes(2); + expect(screen.queryByText("Azimut Flybridge 68")).toBeNull(); + expect(screen.getAllByText("Azimut S7")).toHaveLength(2); + expect(screen.queryByText("Inativo")).toBeNull(); + }); + + it("bloqueia a paginação enquanto a busca digitada ainda não foi aplicada", async () => { + getProducts.mockResolvedValue( + pageResult([boat("b1", "Flybridge 68")], { + total: 45, + total_pages: 3, + has_next: true, + }), + ); + + const { setSearch } = renderPage(); + await screen.findAllByText("Azimut Flybridge 68"); + const next = screen.getByTitle("Próxima") as HTMLButtonElement; + expect(next.disabled).toBe(false); + + setSearch("bmw"); + + expect((screen.getByTitle("Próxima") as HTMLButtonElement).disabled).toBe( + true, + ); + }); +}); diff --git a/frontend/src/pages/specialist/ProductsPage.tsx b/frontend/src/pages/specialist/ProductsPage.tsx index 166b5b6..bf70637 100644 --- a/frontend/src/pages/specialist/ProductsPage.tsx +++ b/frontend/src/pages/specialist/ProductsPage.tsx @@ -1,123 +1,153 @@ -import { useState, useEffect, useContext } from "react"; +import { useState, useEffect, useRef, useCallback } from "react"; import { useNavigate } from "react-router-dom"; -import { Plus } from "lucide-react"; +import { ChevronLeft, ChevronRight, Plus, Search } from "lucide-react"; import { useAuth } from "../../store/authStateManager"; -import { AppContext } from "../../contexts/AppContext"; -import { getCars, deleteCar } from "../../services/cars.service"; -import { getBoats, deleteBoat } from "../../services/boats.service"; -import { getAircrafts, deleteAircraft } from "../../services/aircrafts.service"; +import { deleteCar } from "../../services/cars.service"; +import { deleteBoat } from "../../services/boats.service"; +import { deleteAircraft } from "../../services/aircrafts.service"; +import { + getAdminSpecialistProducts, + type AdminCatalogProduct, +} from "../../services/admin-specialist-journey.service"; import type { SpecialityType } from "../../types/types"; import Button from "../../components/ui/button"; import { Alert } from "../../components/ui/alert"; import { Card } from "../../components/ui/card"; +import { Input } from "../../components/ui/input"; import { PageHeader } from "../../components/patterns/PageHeader"; -import ResponsiveProductList, { - type ProductListItem, -} from "../../components/specialist/ResponsiveProductList"; +import ResponsiveProductList from "../../components/specialist/ResponsiveProductList"; -type ProductType = "cars" | "boats" | "aircrafts"; +const PRODUCTS_PER_PAGE = 20; +const SEARCH_DEBOUNCE_MS = 300; -// Mapeia especialidade para tipo de produto -const specialityToProductType: Record = { +const productTypeRoute: Record = { CAR: "cars", BOAT: "boats", AIRCRAFT: "aircrafts", }; +const productTypeLabel: Record = { + CAR: "Carros", + BOAT: "Lanchas", + AIRCRAFT: "Aeronaves", +}; + +/** + * Gestão de produtos do especialista. + * + * Lista paginada no servidor via `/{tipo}/admin/all`, que o backend restringe + * aos produtos do próprio especialista e inclui os inativos. Antes a tela + * pegava os 100 primeiros produtos da plataforma inteira e filtrava no + * navegador, então quem tinha itens fora desse recorte não os via. + */ export default function ProductsPage() { const navigate = useNavigate(); const user = useAuth((state) => state.user); - const userSpeciality = user?.speciality as SpecialityType; - const { searchTerm } = useContext(AppContext); + const speciality = user?.speciality as SpecialityType | undefined; - // Define o tipo de produto inicial baseado na especialidade do usuário - const initialProductType = userSpeciality - ? specialityToProductType[userSpeciality] - : "cars"; + const [products, setProducts] = useState([]); + const [page, setPage] = useState(1); + const [totalPages, setTotalPages] = useState(1); + const [total, setTotal] = useState(0); + const [loading, setLoading] = useState(Boolean(speciality)); + const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); + // A busca é local: o header do especialista não tem campo de pesquisa, e o + // searchTerm do AppContext nunca era preenchido nesta tela. + const [searchInput, setSearchInput] = useState(""); + const [search, setSearch] = useState(""); - const [productType, setProductType] = useState(initialProductType); - const [products, setProducts] = useState([]); - const [loading, setLoading] = useState(true); + // Só a resposta da última requisição vale: digitar rápido dispara várias e + // elas podem voltar fora de ordem. + const latestRequest = useRef(0); useEffect(() => { - loadProducts(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [productType]); + const timer = setTimeout( + () => setSearch(searchInput.trim()), + SEARCH_DEBOUNCE_MS, + ); + return () => clearTimeout(timer); + }, [searchInput]); - const loadProducts = async () => { - setLoading(true); - try { - if (productType === "cars") { - const { cars } = await getCars(1, 100); - setProducts( - user?.role === "SPECIALIST" && user.id - ? cars.filter((car: any) => car.specialist_id === user.id) - : cars - ); - } else if (productType === "boats") { - const { boats } = await getBoats(1, 100); - setProducts( - user?.role === "SPECIALIST" && user.id - ? boats.filter((boat: any) => boat.specialist_id === user.id) - : boats - ); - } else if (productType === "aircrafts") { - const { aircrafts } = await getAircrafts(1, 100); - setProducts( - user?.role === "SPECIALIST" && user.id - ? aircrafts.filter((aircraft: any) => aircraft.specialist_id === user.id) - : aircrafts + const loadProducts = useCallback( + async (targetPage: number) => { + if (!speciality) return; + const requestId = ++latestRequest.current; + setLoading(true); + setError(null); + try { + const { products: pageProducts, pagination } = + await getAdminSpecialistProducts( + speciality, + targetPage, + PRODUCTS_PER_PAGE, + search, + ); + if (requestId !== latestRequest.current) return; + setProducts(pageProducts); + setPage(pagination.current_page); + setTotal(pagination.total); + setTotalPages(Math.max(1, Math.ceil(pagination.total_pages))); + } catch (caught) { + if (requestId !== latestRequest.current) return; + console.error("Erro ao carregar produtos:", caught); + setProducts([]); + setError( + (caught as { friendlyMessage?: string })?.friendlyMessage ?? + "Não foi possível carregar seus produtos.", ); + } finally { + if (requestId === latestRequest.current) setLoading(false); } - } catch (error) { - console.error("Erro ao carregar produtos:", error); - setProducts([]); - } finally { - setLoading(false); - } - }; + }, + [speciality, search], + ); + + // Busca nova sempre recomeça da primeira página. + useEffect(() => { + void loadProducts(1); + }, [loadProducts]); const handleDelete = async (id: string) => { - if (!window.confirm("Tem certeza que deseja excluir este produto?")) { + if ( + !window.confirm( + "Desativar este produto? Ele sai do catálogo e continua na sua lista como inativo.", + ) + ) { return; } + setNotice(null); try { - if (productType === "cars") { - await deleteCar(id); - } else if (productType === "boats") { - await deleteBoat(id); - } else if (productType === "aircrafts") { - await deleteAircraft(id); - } - window.alert("Produto excluído com sucesso!"); - loadProducts(); - } catch (error) { - console.error("Erro ao excluir produto:", error); - window.alert("Erro ao excluir produto"); + if (speciality === "CAR") await deleteCar(id); + else if (speciality === "BOAT") await deleteBoat(id); + else await deleteAircraft(id); + // Atualiza só o item, sem recarregar: um reload aqui usaria a busca e a + // página do momento do clique e poderia sobrescrever uma busca feita + // enquanto o DELETE estava em andamento (e um erro do reload apareceria + // junto com a mensagem de sucesso). Se o item já saiu da lista, nada muda. + setProducts((current) => + current.map((product) => + product.id === id ? { ...product, is_active: false } : product, + ), + ); + setNotice("Produto desativado. Ele continua na lista como inativo."); + } catch (caught) { + console.error("Erro ao desativar produto:", caught); + window.alert("Erro ao desativar produto"); } }; - const handleEdit = (id: string) => { - navigate(`/specialist/products/edit/${productType}/${id}`); - }; + // Enquanto a busca digitada não foi aplicada (debounce), trocar de página + // carregaria o resultado do termo antigo e logo voltaria para a página 1. + const searchPending = searchInput.trim() !== search; - const getProductTypeLabel = () => { - if (productType === "cars") return "Carros"; - if (productType === "boats") return "Lanchas"; - return "Aeronaves"; - }; - - // Filtra produtos baseado no termo de pesquisa - const filteredProducts = products.filter((product) => { - const searchLower = searchTerm.toLowerCase(); - return ( - product.marca?.toLowerCase().includes(searchLower) || - product.modelo?.toLowerCase().includes(searchLower) || - product.ano?.toString().includes(searchLower) || - product.estado?.toLowerCase().includes(searchLower) + const handleEdit = (id: string) => { + if (!speciality) return; + navigate( + `/specialist/products/edit/${productTypeRoute[speciality]}/${id}`, ); - }); + }; return (

@@ -131,70 +161,114 @@ export default function ProductsPage() { } /> - {/* Filtro de Tipo (apenas se não tiver especialidade definida) */} - {!userSpeciality && ( -
- - - -
- )} - - {/* Mostra a especialidade do usuário (se tiver) */} - {userSpeciality && ( - -

- Sua especialidade:{" "} - {getProductTypeLabel()} -

+ {!speciality ? ( + + Sua conta não tem uma especialidade definida, então não é possível + listar seus produtos. Peça ao administrador para configurá-la. - )} + ) : ( + <> + +

+ Sua especialidade:{" "} + {productTypeLabel[speciality]} +

+
- {/* Lista de Produtos */} - -

{getProductTypeLabel()}

- - {loading ? ( -

Carregando...

- ) : filteredProducts.length === 0 ? ( -

- {searchTerm ? "Nenhum produto encontrado com esse termo de pesquisa" : "Nenhum produto cadastrado"} -

- ) : ( - - )} -
+ {notice && ( + + {notice} + + )} + + {error && ( + + {error} + + )} + + +
+

+ {productTypeLabel[speciality]} +

+ {!loading && !error && ( + + {total === 1 ? "1 produto" : `${total} produtos`} + + )} +
+ +
+ + { + setNotice(null); + setSearchInput(event.target.value); + }} + placeholder="Buscar por marca, modelo, estado ou ano" + aria-label="Buscar produtos" + className="pl-9" + /> +
+ + {loading ? ( +

Carregando...

+ ) : products.length === 0 ? ( + !error && ( +

+ {search + ? "Nenhum produto encontrado com esse termo de pesquisa" + : "Nenhum produto cadastrado"} +

+ ) + ) : ( + + )} + + {!loading && totalPages > 1 && ( +
+
+ Página {page} de{" "} + {totalPages} +
+
+ + +
+
+ )} +
+ + )}
); } diff --git a/frontend/src/services/admin-specialist-journey.service.ts b/frontend/src/services/admin-specialist-journey.service.ts index d15ad87..6c7dff8 100644 --- a/frontend/src/services/admin-specialist-journey.service.ts +++ b/frontend/src/services/admin-specialist-journey.service.ts @@ -34,15 +34,26 @@ export async function getAdminClientOptions( return response.data; } +// Catálogo de gestão (ativos + inativos) de um especialista. Serve à jornada +// do admin (o interceptor injeta target_specialist_id) e à tela "Gestão de +// Produtos" do próprio especialista (o backend força o id dele). export async function getAdminSpecialistProducts( productType: JourneyProductType, page: number, perPage: number, + search?: string, ): Promise<{ products: AdminCatalogProduct[]; pagination: PaginationMeta }> { const resource = resourceByType[productType]; + const trimmedSearch = search?.trim(); const response = await api.get>>( `/${resource}/admin/all`, - { params: { page, perPage } }, + { + params: { + page, + perPage, + ...(trimmedSearch ? { search: trimmedSearch } : {}), + }, + }, ); const products = response.data.data.map((raw) => ({ ...raw,