Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnPetros committed Nov 29, 2024
2 parents 16d4d3a + 9bb6587 commit 47b88bd
Show file tree
Hide file tree
Showing 13 changed files with 166 additions and 17 deletions.
3 changes: 2 additions & 1 deletion apps/server/src/api/controllers/locations/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { RegisterLocationController } from './register-location-controller'
export { DeleteLocationsController } from './delete-locations-controller'
export { DeleteLocationsController } from './delete-locations-controller'
export { UpdateLocationController } from './update-location-controller'
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { IHttp } from '@stocker/core/interfaces'
import { ListLocationsUseCase } from '@stocker/core/use-cases'

import { locationsRepository } from '@/database'
import { HTTP_STATUS_CODE } from '@stocker/core/constants'

type RouteParams = {
page: string
}

export class ListLocationsController {
async handle(http: IHttp) {
const { companyId } = await http.getUser()
const { page } = http.getQueryParams<RouteParams>()
const pageNumber = parseInt(page || '1', 10)

const useCase = new ListLocationsUseCase(locationsRepository)
const response = await useCase.execute({ page: pageNumber, companyId: companyId })

return http.send(response, HTTP_STATUS_CODE.ok)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { LocationDto } from "@stocker/core/dtos";
import type { IHttp } from "@stocker/core/interfaces";

import { locationsRepository } from "@/database";
import { UpdateLocationUseCase } from "@stocker/core/use-cases";
import { HTTP_STATUS_CODE } from "@stocker/core/constants";
import { User } from "@stocker/core/entities";

type RouteParams = {
locationId: string
}

export class UpdateLocationController {
async handle(http: IHttp) {
const { locationId } = http.getRouteParams<RouteParams>()
const {companyId} = await http.getUser()
const locationDto = http.getBody<Partial<LocationDto>>()

const useCase = new UpdateLocationUseCase(locationsRepository)
await useCase.execute({ locationId, locationDto, companyId })

return http.send(companyId, HTTP_STATUS_CODE.ok)
}
}
14 changes: 14 additions & 0 deletions apps/server/src/app/fastify/routes/locations-routes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { DeleteLocationsController, RegisterLocationController } from "@/api/controllers/locations";
import type { FastifyInstance } from "fastify";
import { FastifyHttp } from "../fastify-http";
import { UpdateLocationController } from "@/api/controllers/locations/update-location-controller";
import { ListLocationsController } from "@/api/controllers/locations/list-locations-controller";

export const LocationsRoutes = async (app: FastifyInstance) => {
const registerLocationController = new RegisterLocationController()
const deleteLocationsController = new DeleteLocationsController()
const updateLocationController = new UpdateLocationController()
const listLocationsController = new ListLocationsController()

app.post('/', async (request, response) => {
const http = new FastifyHttp(request, response)
Expand All @@ -15,4 +19,14 @@ export const LocationsRoutes = async (app: FastifyInstance) => {
const http = new FastifyHttp(request, response)
return deleteLocationsController.handle(http)
})

app.put('/:locationId', async (request, response) => {
const http = new FastifyHttp(request, response)
return updateLocationController.handle(http)
})

app.get('/', async (request, response) => {
const http = new FastifyHttp(request, response)
return listLocationsController.handle(http)
})
}
4 changes: 3 additions & 1 deletion apps/web/src/api/services/products-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export const ProductsService = (apiClient: IApiClient): IProductsService => {
return await apiClient.get<ProductDto>(`/products/${productId}`)
},

async listProducts({ page }) {
async listProducts({ page,name,categoryId }) {
apiClient.setParam('categoryId',String(categoryId))
apiClient.setParam('name',String(name))
apiClient.setParam('page', String(page))
return await apiClient.get<PaginationResponse<ProductDto>>('/products')
},
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/ui/components/commons/category-select/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ type CategorySelectProps = {
defeaultCategoryId?: string
className?: string
onSelectChange: (categoryId: string) => void
value?:string
}

export const CategorySelect = ({
className,
value,
defeaultCategoryId,
onSelectChange,
}: CategorySelectProps) => {
Expand All @@ -38,7 +40,7 @@ export const CategorySelect = ({
size='2xl'
trigger={
<Select className={className}>
{selectedCategoryName ? selectedCategoryName : 'Selecione categoria'}
{value ? selectedCategoryName ? selectedCategoryName : 'Selecione categoria' : "Selecione categoria"}
</Select>
}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function useRegisterLocationForm({
companyId: companyId,
subLocations: [],
})
console.log(location)
const response = await locationsService.registerLocation(location)
if (response.isFailure) {
showError(response.errorMessage)
Expand Down
31 changes: 26 additions & 5 deletions apps/web/src/ui/components/pages/products/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ import { useProductsPage } from './use-products-page'
import { Search } from '../../commons/search'
import { AlertDialog } from '../../commons/alert-dialog'
import { useAuthContext } from '../../contexts/auth-context'
import { CategorySelect } from '../../commons/category-select'
import { Icon } from '../../commons/icon'

export const ProductsPage = () => {
const {
categoryId,
handleCategoryIdSearchChange,
isFetching,
isDeleting,
page,
Expand All @@ -32,13 +36,30 @@ export const ProductsPage = () => {
const hasValidRole = user?.hasValidRole('manager')
return (
<>
<div className='flex flex-col gap-3 md:flex-row md:gap-0 justify-between'>
<div className='flex-1 w-full max-w-96 space-y-2'>
<div className='flex flex-col gap-3 md:flex-row md:gap-0 items-center justify-between'>
<div className='flex-1 w-full max-w-96 space-y-2 '>
<h1 className='text-3xl font-black'>Produtos</h1>
<Search value={filterByNameValue} onSearchChange={handleSearchChange} />
<div className='flex flex-row gap-4 w-screen items-center '>
<Search value={filterByNameValue} onSearchChange={handleSearchChange} />
<div className=' flex flex-row items-center justify-center gap-4'>
<CategorySelect
value={categoryId}
onSelectChange={handleCategoryIdSearchChange}
/>
{categoryId && (
<button
type='button'
onClick={() => handleCategoryIdSearchChange('')}
className='flex justify-center items-center gap-2 text-sm text-gray-400'
>
Remover Filtro
<Icon name='close' className='size-4' />{' '}
</button>
)}
</div>
</div>
</div>

<div className='flex items-center gap-1'>
<div className='flex items-center gap-1'>
{selectedProductsIds.length > 0 && (
<AlertDialog
trigger={
Expand Down
21 changes: 14 additions & 7 deletions apps/web/src/ui/components/pages/products/use-products-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ export function useProductsPage() {
const { showSuccess, showError } = useToast()
const [selectedProductsIds, setSelectedProductsIds] = useState<string[]>([])
const [page, setPage] = useUrlParamNumber('page', 1)
const [filterByNameValueState, setFilterByNameValue] = useUrlParamString('name')
const [filterByName, setFilterByNameValue] = useUrlParamString('name')
const [categoryId, setCategoryIdValue] = useUrlParamString('categoryId')
const [isDeleting, setIsDeleting] = useState(false)
const filterByNameValue = filterByNameValueState ?? ''

async function fetchProducts() {
const response = await productsService.listProducts({ page })
const response = await productsService.listProducts({
page,
name: filterByName,
categoryId,
})

if (response.isFailure) {
showError(response.errorMessage)
Expand All @@ -37,14 +41,15 @@ export function useProductsPage() {
function handleSearchChange(value: string) {
setFilterByNameValue(value ?? '')
}

function handleCategoryIdSearchChange(categoryId: string) {
setCategoryIdValue(categoryId ?? '')
}
const { data, isFetching, refetch } = useCache({
fetcher: fetchProducts,
key: CACHE.productsList.key,
dependencies: [page],
dependencies: [page, filterByName,categoryId],
})


const products = data ? data.items.map(Product.create) : []
const itemsCount = data ? data.itemsCount : 0

Expand Down Expand Up @@ -78,8 +83,10 @@ export function useProductsPage() {
}

return {
categoryId,
handleCategoryIdSearchChange,
page,
filterByNameValue,
filterByNameValue: filterByName,
isFetching,
isDeleting,
products,
Expand Down
1 change: 0 additions & 1 deletion apps/web/src/ui/hooks/use-websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export function useWebSocket({ url, onError, onResponse }: UseWebSocketProps) {
(message: MessageEvent) => {
if (!onResponse) return
const response = RealtimeResponse.parseMessage(message.data)
console.log('useChatSocket', response)

onResponse(response)
},
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/use-cases/locations/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export { RegisterLocationUseCase } from './register-location-use-case'
export { DeleteLocationsUseCase } from './delete-locations-use-case'
export { DeleteLocationsUseCase } from './delete-locations-use-case'
export { UpdateLocationUseCase } from './update-location-use-case'
export { ListLocationsUseCase } from './list-locations-use-case'
20 changes: 20 additions & 0 deletions packages/core/src/use-cases/locations/list-locations-use-case.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { ILocationsRepository } from '../../interfaces'
import { PaginationResponse } from '../../responses'

type Request = {
page: number
companyId: string
}

export class ListLocationsUseCase {
private readonly locationsRepository: ILocationsRepository

constructor(locationsRepository: ILocationsRepository) {
this.locationsRepository = locationsRepository
}

async execute({ page, companyId }: Request) {
const locations = await this.locationsRepository.findMany({ page, companyId })
return new PaginationResponse(locations)
}
}
34 changes: 34 additions & 0 deletions packages/core/src/use-cases/locations/update-location-use-case.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { string } from "zod";
import { Company } from "../../domain/entities";
import type { LocationDto } from "../../dtos";
import { ConflictError, NotFoundError } from "../../errors";
import type { ILocationsRepository } from "../../interfaces";

type Request = {
locationDto: Partial<LocationDto>
locationId: string
companyId: string
}

export class UpdateLocationUseCase {
private readonly locationsRepository: ILocationsRepository

constructor(locationsRepository: ILocationsRepository) {
this.locationsRepository = locationsRepository
}
async execute({ locationDto, locationId, companyId }: Request) {
const location = await this.locationsRepository.findById(locationId)

if (!location) {
throw new NotFoundError('Localização não encontrada')
}
if (locationDto.name) {
const locationName = await this.locationsRepository.findByName(locationDto.name)
if (locationName !== null && locationName.dto.companyId === companyId) {
throw new ConflictError('Nome já em uso por outra localização no sistema')
}
}
const updatedLocation = location.update(locationDto)
await this.locationsRepository.update(updatedLocation, locationId)
}
}

0 comments on commit 47b88bd

Please sign in to comment.