Skip to content

Commit

Permalink
[back] 🐛 fix: list inventory movements
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnPetros committed Nov 30, 2024
1 parent 53e86d4 commit b0dbb49
Show file tree
Hide file tree
Showing 19 changed files with 107 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,30 @@ import { inventoryMovementsRepository } from '@/database'
type QueryParams = {
page?: string
productId?: string
employeeId?: string
responsibleId?: string
startDate?: string
endDate?: string
movementType?: 'inbound' | 'outbound'
}

export class ListInventoryMovementsController {
async handle(http: IHttp) {
const { page, productId, employeeId, startDate, endDate, movementType } =
const { page, productId, responsibleId, startDate, endDate, movementType } =
http.getQueryParams<QueryParams>()
const { companyId } = await http.getUser()
const useCase = new ListInventoryMovementsUseCase(inventoryMovementsRepository)

const params = {
page: page ? parseInt(page, 10) : undefined,
page: page ? Number(page) : 1,
companyId,
productId,
employeeId,
responsibleId,
movementType,
startDate: startDate ? new Date(startDate) : undefined,
endDate: endDate ? new Date(endDate) : undefined,
}
const result = await useCase.execute(params)

return http.send(result, HTTP_STATUS_CODE.ok)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ export class ListSuppliersController {
async handle(http: IHttp) {
const { companyId } = await http.getUser()
const { page, name } = http.getQueryParams<RouteParams>()
if (!companyId) {
return http.send(null, HTTP_STATUS_CODE.badRequest)
}
const pageNumber = parseInt(page || '1', 10)

console.log(page, name)

const useCase = new ListSuplliersUseCase(suppliersRepository)
const response = await useCase.execute({ page: pageNumber, name: name, companyId: companyId })
const response = await useCase.execute({
page: pageNumber,
name: name,
companyId: companyId,
})

return http.send(response, HTTP_STATUS_CODE.ok)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class PrismaInventoryMovementsMapper {
if (prismaInventoryMovement.User)
inventoryMovement.responsible = new PrismaUsersMapper().toDomain(
prismaInventoryMovement.User,
false,
)

return inventoryMovement
Expand Down
25 changes: 14 additions & 11 deletions apps/server/src/database/prisma/mappers/prisma-users-mapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,27 @@ import type { UserRole } from '@stocker/core/types'
import type { PrismaUser } from '../types'

export class PrismaUsersMapper {
toDomain(prismaUser: PrismaUser): User {
return User.create({
id: prismaUser.id,
name: prismaUser.name,
email: prismaUser.email,
password: prismaUser.password,
role: prismaUser.role.toLowerCase() as UserRole,
hasFirstPasswordReset: prismaUser.has_first_password_reset,
companyId: prismaUser.company_id,
})
toDomain(prismaUser: PrismaUser, includePassword = true): User {
return User.create(
{
id: prismaUser.id,
name: prismaUser.name,
email: prismaUser.email,
password: prismaUser.password,
role: prismaUser.role.toLowerCase() as UserRole,
hasFirstPasswordReset: prismaUser.has_first_password_reset,
companyId: prismaUser.company_id,
},
includePassword,
)
}

toPrisma(user: User): PrismaUser {
return {
id: user.id,
name: user.name,
email: user.email,
password: user.password,
password: String(user.password),
role: user.role.toUpperCase() as PrismaUserRole,
has_first_password_reset: user.hasFirstPasswordReset,
company_id: user.companyId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,12 +86,9 @@ export class PrismaInventoryMovementsRepository implements IInventoryMovementsRe
movementType,
productId,
companyId,
employeeId,
responsibleId,
}: InventoryMovementsListParams) {
try {
const whereCondition = productId ? { product_id: productId } : undefined
const count = await prisma.inventoryMovement.count({ where: whereCondition })

let paginationParams = {}

if (page) {
Expand Down Expand Up @@ -124,9 +121,9 @@ export class PrismaInventoryMovementsRepository implements IInventoryMovementsRe
productIdFilter = { product_id: productId }
}

let employeeIdFilter = {}
if (employeeId) {
employeeIdFilter = { user_id: employeeId }
let responsibleIdFilter = {}
if (responsibleId) {
responsibleIdFilter = { user_id: responsibleId }
}

const prismaInventoryMovements = await prisma.inventoryMovement.findMany({
Expand All @@ -135,7 +132,7 @@ export class PrismaInventoryMovementsRepository implements IInventoryMovementsRe
...productIdFilter,
...movementTypeFilter,
...dateRangeParams,
...employeeIdFilter,
...responsibleIdFilter,
Product: {
company_id: companyId,
},
Expand All @@ -154,10 +151,21 @@ export class PrismaInventoryMovementsRepository implements IInventoryMovementsRe
})

const inventoryMovements = prismaInventoryMovements.map(this.mapper.toDomain)
const count = await prisma.inventoryMovement.count({
where: {
...productIdFilter,
...movementTypeFilter,
...dateRangeParams,
...responsibleIdFilter,
Product: {
company_id: companyId,
},
},
})

return {
inventoryMovements,
count: page ? count : inventoryMovements.length,
count,
}
} catch (error) {
throw new PrismaError(error)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ export class PrismaSuppliersRepository implements ISuppliersRepository {
},
})

console.log({ page, name, companyId })

const suppliers = prismaSuppliers.map(this.mapper.toDomain)

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class PrismaUsersRepository implements IUsersRepository {
orderBy: { registered_at: 'desc' },
})

return prismaUsers.map(this.mapper.toDomain)
return prismaUsers.map((prismaUser) => this.mapper.toDomain(prismaUser))
} catch (error) {
throw new PrismaError(error)
}
Expand Down Expand Up @@ -106,7 +106,7 @@ export class PrismaUsersRepository implements IUsersRepository {
},
})

const users = prismaUsers.map(this.mapper.toDomain)
const users = prismaUsers.map((prismaUser) => this.mapper.toDomain(prismaUser))

return {
users,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/api/services/categories-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export const CategoriesService = (apiClient: IApiClient): ICategoriesService =>
return await apiClient.get<CategoryDto>(`/categories/${categoryId}`)
},

async listCategories({ page,name }) {
async listCategories({ page, name }) {
apiClient.setParam('page', String(page))
apiClient.setParam('name',String(name))
if (name) apiClient.setParam('name', String(name))
return await apiClient.get<PaginationResponse<CategoryDto>>('/categories')
},

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/api/services/suppliers-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export const SuppliersService = (apiClient: IApiClient): ISuppliersService => {
return await apiClient.get<SupplierDto>(`/suppliers/${supplierId}`)
},

async listSuppliers({ page,name }) {
async listSuppliers({ page = 1, name }) {
apiClient.setParam('page', String(page))
apiClient.setParam('name',String(name))
if (name) apiClient.setParam('name', String(name))
return await apiClient.get<PaginationResponse<SupplierDto>>('/suppliers')
},

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { CACHE } from '@/constants'
import { useApi, useCache, useToast, useUrlParamNumber } from '@/ui/hooks'
import { Supplier } from '@stocker/core/entities'
import { useEffect, useState } from 'react'
import { useState } from 'react'
import { useAuthContext } from '../../contexts/auth-context'

export function useSupplierSelect(
Expand Down Expand Up @@ -36,7 +36,6 @@ export function useSupplierSelect(

const response = await suppliersService.listSuppliers({
page,
companyId: company.id,
})
if (response.isFailure) {
showError(response.errorMessage)
Expand Down Expand Up @@ -68,6 +67,8 @@ export function useSupplierSelect(
}))
}

console.log(suppliersData)
console.log(company?.id)
const suppliers = suppliersData ? suppliersData.items.map(Supplier.create) : []
const itemsCount = suppliersData ? suppliersData.itemsCount : 0

Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/domain/entities/inventory-movement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class InventoryMovement extends Entity<MovementProps> {
if (dto.product.dto) inventoryMovement.product = Product.create(dto.product.dto)

if (dto.responsible.dto)
inventoryMovement.responsible = User.create(dto.responsible.dto)
inventoryMovement.responsible = User.create(dto.responsible.dto, false)

return inventoryMovement
}
Expand All @@ -61,8 +61,14 @@ export class InventoryMovement extends Entity<MovementProps> {
id: this.id,
movementType: this.props.movementType,
itemsCount: this.props.itemsCount,
responsible: this.props.responsible,
product: this.props.product,
responsible: {
id: this.props.responsible.id,
dto: this.props.responsible.entity?.dto,
},
product: {
id: this.props.product.id,
dto: this.props.product.entity?.dto,
},
registeredAt: this.props.registeredAt,
remark: this.props.remark ?? undefined,
}
Expand Down
17 changes: 12 additions & 5 deletions packages/core/src/domain/entities/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,39 @@ type UserProps = {
role: UserRole
email: string
name: string
password: string
password?: string
companyId: string
hasFirstPasswordReset: boolean
}

const DEAFAULT_PASSWORD = 'stocker@123'

export class User extends Entity<UserProps> {
static create(dto: UserDto): User {
static create(dto: UserDto, hasPassword = true): User {
const role = dto.role

if (!User.isUserRole(role)) {
throw new ValidationError(`${role} não é um tipo de usuário válido`)
}

return new User(
const user = new User(
{
name: dto.name,
email: dto.email,
password: dto.password ?? DEAFAULT_PASSWORD,
companyId: dto.companyId,
role: role,
hasFirstPasswordReset: dto.hasFirstPasswordReset ?? true,
},
dto.id,
)

if (hasPassword) {
user.password = dto.password ?? DEAFAULT_PASSWORD
}

console.log('password', hasPassword)

return user
}

static isUserRole(userRole: string): userRole is UserRole {
Expand Down Expand Up @@ -68,7 +75,7 @@ export class User extends Entity<UserProps> {
return this.props.email
}

get password(): string {
get password(): string | undefined {
return this.props.password
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types/inventory-movements-list-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export type InventoryMovementsListParams = {
companyId?: string
startDate?: Date
endDate?: Date
employeeId?: string
responsibleId?: string
movementType?: InventoryMovementType
productId?: string
}
2 changes: 1 addition & 1 deletion packages/core/src/types/suppliers-list-params.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export type SuppliersListParams = {
page: number
name?: string
companyId: string
companyId?: string
}
2 changes: 1 addition & 1 deletion packages/core/src/use-cases/auth/confirm-auth-use-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class ConfirmAuthUseCase {

const isPasswordValid = await this.cryptoProvider.validateHash(
password,
user.password,
String(user.password),
)

return isPasswordValid
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/use-cases/auth/login-use-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@ export class LoginUseCase {

const isPasswordValid = await this.cryptoProvider.validateHash(
password,
user.password,
String(user.password),
)

if (!isPasswordValid) {
throw new NotAllowedError('Credenciais inválidas')
}


return user.dto
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { InventoryMovementsListParams } from '../../types'
import type { IInventoryMovementsRepository } from '../../interfaces'
import type { InventoryMovement } from '../../domain/entities'
import { PaginationResponse } from '../../responses'

export class ListInventoryMovementsUseCase {
private readonly inventoryMovementsRepository: IInventoryMovementsRepository
Expand All @@ -9,11 +9,13 @@ export class ListInventoryMovementsUseCase {
this.inventoryMovementsRepository = inventoryMovementsRepository
}

async execute(
params: InventoryMovementsListParams,
): Promise<{ inventoryMovements: InventoryMovement[]; count: number }> {
async execute(params: InventoryMovementsListParams) {
const { inventoryMovements, count } =
await this.inventoryMovementsRepository.findMany(params)
return { inventoryMovements, count }

return new PaginationResponse({
items: inventoryMovements.map((movement) => movement.dto),
itemsCount: count,
})
}
}
Loading

0 comments on commit b0dbb49

Please sign in to comment.