Skip to content

Commit

Permalink
Add warehouses value calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
MrBartusek committed Nov 25, 2023
1 parent 836fffb commit 1af0bac
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 10 deletions.
28 changes: 24 additions & 4 deletions apps/api/src/models/inventory/inventory.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import { ProductsService } from '../products/products.service';
import { WarehousesService } from '../warehouses/warehouses.service';
import { InventoryService } from './inventory.service';
import { InventoryItem } from './schemas/inventory-item.schema';
import { OrganizationsService } from '../organizations/organizations.service';
import { OrganizationDocument } from '../organizations/schemas/organization.schema';
import { WarehouseDocument } from '../warehouses/schemas/warehouse.schema';

@ApiTags('inventory')
@UseGuards(AuthenticatedGuard)
Expand All @@ -28,21 +31,27 @@ export class InventoryController {
private readonly inventoryService: InventoryService,
private readonly warehousesService: WarehousesService,
private readonly productService: ProductsService,
private readonly organizationService: OrganizationsService,
) {}

@Post()
async create(@Body(ValidationPipe) addInventoryItemDto: AddInventoryItemDto) {
const warehouseExist = this.warehousesService.exist(addInventoryItemDto.warehouseId as any);
if (!warehouseExist) {
const warehouse = await this.warehousesService.findById(addInventoryItemDto.warehouseId as any);
if (!warehouse) {
throw new BadRequestException("This warehouse doesn't exist");
}

const productExist = this.productService.exist(addInventoryItemDto.productId as any);
const productExist = await this.productService.exist(addInventoryItemDto.productId as any);
if (!productExist) {
throw new BadRequestException("This product doesn't exist");
}

const item = await this.inventoryService.create(addInventoryItemDto);

const organization = await this.organizationService.findByWarehouse(warehouse._id);

await this.updateWarehouseValue(organization, warehouse);

return InventoryItem.toBasicDto(item);
}

Expand All @@ -64,7 +73,7 @@ export class InventoryController {
async findAll(
@Param('id', ParseObjectIdPipe) warehouseId: Types.ObjectId,
): Promise<BasicInventoryItemDto[]> {
const items = await this.inventoryService.findAll(warehouseId);
const items = await this.inventoryService.findAllInWarehouse(warehouseId);

return items.map((i) => InventoryItem.toBasicDto(i));
}
Expand All @@ -79,4 +88,15 @@ export class InventoryController {

return InventoryItem.toDto(item);
}

async updateWarehouseValue(organization: OrganizationDocument, warehouse: WarehouseDocument) {
const items = await this.inventoryService.find({ warehouse: warehouse._id });
const strategy = organization.settings.valueCalculationStrategy;

const totalValue = items
.map((i) => i.product[strategy] * i.quantity)
.reduce((a, b) => a + b, 0);
console.log(items.map((i) => i.product[strategy] * i.quantity));
await this.warehousesService.updateTotalValue(warehouse.id, totalValue);
}
}
2 changes: 2 additions & 0 deletions apps/api/src/models/inventory/inventory.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import { InventoryController } from './inventory.controller';
import { InventoryRepository } from './inventory.repository';
import { InventoryService } from './inventory.service';
import { InventoryItem, InventoryItemSchema } from './schemas/inventory-item.schema';
import { OrganizationsModule } from '../organizations/organizations.module';

@Module({
imports: [
MongooseModule.forFeature([{ name: InventoryItem.name, schema: InventoryItemSchema }]),
ProductsModule,
WarehousesModule,
OrganizationsModule,
],
controllers: [InventoryController],
providers: [InventoryService, InventoryRepository],
Expand Down
6 changes: 5 additions & 1 deletion apps/api/src/models/inventory/inventory.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ export class InventoryService {
}
}

findAll(warehouseId: Types.ObjectId): Promise<InventoryItemDocument[]> {
find(query: FilterQuery<any>): Promise<InventoryItemDocument[]> {
return this.aggregateWithProduct(query);
}

findAllInWarehouse(warehouseId: Types.ObjectId): Promise<InventoryItemDocument[]> {
return this.aggregateWithProduct({ warehouse: warehouseId });
}

Expand Down
8 changes: 8 additions & 0 deletions apps/api/src/models/organizations/organizations.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ export class OrganizationsService {
return result.map((r) => r.warehouseDetails[0]);
}

async findByWarehouse(
warehouseId: mongoose.Types.ObjectId,
): Promise<OrganizationDocument | null> {
return this.organizationRepository.findOne({
'warehouses.id': warehouseId,
});
}

async updateAcl(
organizationId: mongoose.Types.ObjectId | string,
userId: mongoose.Types.ObjectId | string,
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/models/warehouses/schemas/warehouse.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ export class Warehouse {
@Prop()
address: string;

@Prop({ default: 0 })
totalValue: number;

public static toDto(entity: WarehouseDocument): WarehouseDto {
return {
id: entity._id,
name: entity.name,
address: entity.address,
totalValue: entity.totalValue,
};
}
}
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/models/warehouses/warehouses.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ export class WarehousesService {
findById(id: Types.ObjectId): Promise<WarehouseDocument | undefined> {
return this.warehouseRepository.findById(id);
}

updateTotalValue(id: Types.ObjectId, totalValue: number): Promise<WarehouseDocument | undefined> {
return this.warehouseRepository.findOneAndUpdate({ _id: id }, { totalValue });
}
}
12 changes: 8 additions & 4 deletions apps/client/src/components/WarehousesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { useNavigate } from 'react-router-dom';
import { WarehouseDto } from 'shared-types';
import Table from './Helpers/Table';
import WarehouseActions from './WarehouseActions';
import { Utils } from '../utils';
import { useContext } from 'react';
import { CurrentAppContext } from './Context/CurrentAppContext';

const columnHelper = createColumnHelper<WarehouseDto>();

Expand All @@ -12,6 +15,7 @@ export interface WarehousesTableProps {

function WarehousesTable({ warehouses }: WarehousesTableProps) {
const navigate = useNavigate();
const appContext = useContext(CurrentAppContext);

const columns = [
columnHelper.display({
Expand All @@ -27,10 +31,10 @@ function WarehousesTable({ warehouses }: WarehousesTableProps) {
header: 'Address',
cell: (info) => info.getValue(),
}),
// columnHelper.accessor('totalValue', {
// header: 'Total Stock Value',
// cell: (info) => Utils.humanizeCurrency(info.getValue(), appContext.organization.currency),
// }),
columnHelper.accessor('totalValue', {
header: 'Total Stock Value',
cell: (info) => Utils.humanizeCurrency(info.getValue(), appContext.organization.currency),
}),
columnHelper.display({
header: 'Actions',
id: 'actions',
Expand Down
7 changes: 6 additions & 1 deletion apps/client/src/utils.ts → apps/client/src/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ export class Utils {
}

public static humanizeCurrency(input?: number, currency?: string) {
return humanFormat(input || 0, { separator: '', decimals: 2 }) + ' ' + currency;
const value = humanFormat(input || 0, { separator: '', decimals: 2 });
return (
<div className="flex items-baseline gap-1">
{value} <div className="text-muted">{currency}</div>
</div>
);
}

public static dashboardUrl(
Expand Down
1 change: 1 addition & 0 deletions packages/shared-types/src/warehouse/WarehouseDto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import { BasicWarehouseDto } from "./BasicWarehouseDto";

export class WarehouseDto extends BasicWarehouseDto {
address: string;
totalValue: number;
}

0 comments on commit 1af0bac

Please sign in to comment.