Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/inventory/dto/inventory.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Min,
IsArray,
ValidateNested,
IsDateString,
} from 'class-validator';
import { ResponseBranchDTO } from 'src/branch/dto/branch.dto';
import { BaseDTO } from 'src/utils/dto/base.dto';
Expand Down Expand Up @@ -78,13 +79,27 @@ export class BulkUpdateInventoryItemDTO {
@IsNumber()
@IsNotEmpty()
quantity: number;

@ApiProperty({
description: 'Product presentation expiration date',
example: '2025-12-31T23:59:59Z',
})
@IsNotEmpty()
@IsDateString()
expirationDate: Date;
}

export class BulkUpdateInventoryDTO {
@ApiProperty({
description: 'List of inventory update items',
type: [BulkUpdateInventoryItemDTO],
example: [{ productPresentationId: 'uuid', quantity: 10 }],
example: [
{
productPresentationId: 'uuid',
quantity: 10,
expirationDate: '2025-12-31T23:59:59Z',
},
],
})
@IsArray()
@ValidateNested({ each: true })
Expand Down
21 changes: 21 additions & 0 deletions src/inventory/entities/inventory-movement.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { BaseModel } from 'src/utils/entity';
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
import { Inventory } from './inventory.entity';

export enum MovementType {
IN = 'in',
OUT = 'out',
}

@Entity('inventory_movement')
export class InventoryMovement extends BaseModel {
@ManyToOne(() => Inventory)
@JoinColumn({ name: 'inventory_id' })
inventory: Inventory;

@Column({ type: 'int', name: 'quantity' })
quantity: number;

@Column({ type: 'enum', enum: MovementType, name: 'type' })
type: MovementType;
}
8 changes: 7 additions & 1 deletion src/inventory/inventory.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import { State } from 'src/state/entities/state.entity';
import { Country } from 'src/country/entities/country.entity';
import { AuthModule } from 'src/auth/auth.module';
import { InventorySubscriber } from '../inventory/subscribers/inventory.subscriber';
import { InventoryMovement } from './entities/inventory-movement.entity';
import { InventoryMovementService } from './services/inventory-movement.service';
import { Lot } from 'src/products/entities/lot.entity';

@Module({
imports: [
Expand All @@ -24,6 +27,8 @@ import { InventorySubscriber } from '../inventory/subscribers/inventory.subscrib
City,
State,
Country,
InventoryMovement,
Lot,
]),
AuthModule,
],
Expand All @@ -35,7 +40,8 @@ import { InventorySubscriber } from '../inventory/subscribers/inventory.subscrib
StateService,
CountryService,
InventorySubscriber,
InventoryMovementService,
],
exports: [InventoryService, TypeOrmModule],
exports: [InventoryService, TypeOrmModule, InventoryMovementService],
})
export class InventoryModule {}
83 changes: 70 additions & 13 deletions src/inventory/inventory.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import { InjectRepository } from '@nestjs/typeorm';
import { ProductPresentation } from 'src/products/entities/product-presentation.entity';
import { BranchService } from 'src/branch/branch.service';
import { In } from 'typeorm';
import { Lot } from 'src/products/entities/lot.entity';
import {
InventoryMovement,
MovementType,
} from './entities/inventory-movement.entity';

@Injectable()
export class InventoryService {
Expand All @@ -23,6 +28,11 @@ export class InventoryService {
private readonly branchService: BranchService,
@InjectRepository(ProductPresentation)
private readonly productPresentationRepository: Repository<ProductPresentation>,
@InjectRepository(Lot)
private readonly lotRepository: Repository<Lot>,

@InjectRepository(InventoryMovement)
private readonly inventoryMovementRepository: Repository<InventoryMovement>,
) {}

async create(createInventoryDTO: CreateInventoryDTO): Promise<Inventory> {
Expand Down Expand Up @@ -80,6 +90,24 @@ export class InventoryService {
return inventory;
}

async findByPresentationAndBranch(
productPresentationId: string,
branchId: string,
): Promise<Inventory> {
const inventory = await this.inventoryRepository.findOne({
where: {
productPresentation: { id: productPresentationId },
branch: { id: branchId },
},
});
if (!inventory) {
throw new NotFoundException(
`Inventory with product presentation #${productPresentationId} not found`,
);
}
return inventory;
}

async update(
id: string,
updateInventoryDTO: UpdateInventoryDTO,
Expand Down Expand Up @@ -130,16 +158,47 @@ export class InventoryService {
bulkUpdateDto: BulkUpdateInventoryDTO,
inventoryMap: Record<string, Inventory>,
): Promise<Inventory[]> {
const toUpdate = bulkUpdateDto.inventories
.filter((item) => !!inventoryMap[item.productPresentationId])
.map((item) => {
const inv = inventoryMap[item.productPresentationId];
inv.stockQuantity = item.quantity;
return inv;
const inventoriesToSave: Inventory[] = [];
const movementsToSave: InventoryMovement[] = [];
//const lotsToSave: Lot[] = [];

for (const item of bulkUpdateDto.inventories) {
const inventory = inventoryMap[item.productPresentationId];
if (!inventory) continue;

inventory.stockQuantity = item.quantity;
inventoriesToSave.push(inventory);

const movement = this.inventoryMovementRepository.create({
inventory,
quantity: item.quantity,
type: MovementType.IN,
});
movementsToSave.push(movement);

// if (item.expirationDate) {
// const lot = this.lotRepository.create({
// productPresentation: { id: item.productPresentationId },
// branch: { id: branchId },
// quantity: item.quantity,
// expirationDate: new Date(item.expirationDate),
// });
// lotsToSave.push(lot);
// }
}

const updatedInventories =
await this.inventoryRepository.save(inventoriesToSave);
if (movementsToSave.length > 0) {
await this.inventoryMovementRepository.save(movementsToSave);
}
// if (lotsToSave.length > 0) {
// await this.lotRepository.save(lotsToSave);
// }

return this.inventoryRepository.save(toUpdate);
return updatedInventories;
}

async updateBulkByBranch(
branchId: string,
bulkUpdateDto: BulkUpdateInventoryDTO,
Expand Down Expand Up @@ -173,12 +232,10 @@ export class InventoryService {
branchId: string,
amount: number,
): Promise<void> {
const inv = await this.inventoryRepository.findOne({
where: {
productPresentation: { id: presentationId },
branch: { id: branchId },
},
});
const inv = await this.findByPresentationAndBranch(
presentationId,
branchId,
);
if (!inv || inv.stockQuantity < amount) {
throw new BadRequestException(
'Insufficient branch inventory to approve order',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateInventoryMovementMigration1745944360456
implements MigrationInterface
{
name = 'CreateInventoryMovementMigration1745944360456';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TYPE "public"."inventory_movement_type_enum" AS ENUM('in', 'out')`,
);
await queryRunner.query(
`CREATE TABLE "inventory_movement" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "created_at" TIMESTAMP NOT NULL DEFAULT now(), "updated_at" TIMESTAMP NOT NULL DEFAULT now(), "deleted_at" TIMESTAMP, "quantity" integer NOT NULL, "type" "public"."inventory_movement_type_enum" NOT NULL, "inventory_id" uuid, CONSTRAINT "PK_e17362693c889da517444ad8fb5" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`ALTER TABLE "inventory_movement" ADD CONSTRAINT "FK_74fa1a5f453f11694f77c036004" FOREIGN KEY ("inventory_id") REFERENCES "inventory"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "inventory_movement" DROP CONSTRAINT "FK_74fa1a5f453f11694f77c036004"`,
);
await queryRunner.query(`DROP TABLE "inventory_movement"`);
await queryRunner.query(
`DROP TYPE "public"."inventory_movement_type_enum"`,
);
}
}
30 changes: 30 additions & 0 deletions src/inventory/services/inventory-movement.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
InventoryMovement,
MovementType,
} from '../entities/inventory-movement.entity';
import { Repository } from 'typeorm';
import { Inventory } from '../entities/inventory.entity';

@Injectable()
export class InventoryMovementService {
constructor(
@InjectRepository(InventoryMovement)
private movementRepo: Repository<InventoryMovement>,
) {}

async createMovement(
inventory: Inventory,
quantity: number,
type: MovementType,
): Promise<InventoryMovement> {
const movement = this.movementRepo.create({
inventory,
quantity,
type,
});

return this.movementRepo.save(movement);
}
}
13 changes: 13 additions & 0 deletions src/order/order.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { UserAddress } from 'src/user/entities/user-address.entity';
import { UserService } from 'src/user/user.service';
import { CouponService } from 'src/discount/services/coupon.service';
import { InventoryService } from 'src/inventory/inventory.service';
import { InventoryMovementService } from 'src/inventory/services/inventory-movement.service';
import { MovementType } from 'src/inventory/entities/inventory-movement.entity';

@Injectable()
export class OrderService {
Expand All @@ -40,6 +42,8 @@ export class OrderService {
private userService: UserService,
private readonly inventoryService: InventoryService,
private couponService: CouponService,

private readonly inventoryMovementService: InventoryMovementService,
) {}

async create(user: User, createOrderDTO: CreateOrderDTO) {
Expand Down Expand Up @@ -213,11 +217,20 @@ export class OrderService {
}
if (status === OrderStatus.APPROVED) {
for (const detail of order.details) {
const inv = await this.inventoryService.findByPresentationAndBranch(
detail.productPresentation.id,
order.branch.id,
);
await this.inventoryService.decrementInventory(
detail.productPresentation.id,
order.branch.id,
detail.quantity,
);
await this.inventoryMovementService.createMovement(
inv,
detail.quantity,
MovementType.OUT,
);
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/products/entities/lot.entity.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Column, Entity, JoinColumn, ManyToOne } from 'typeorm';
import { BaseModel } from 'src/utils/entity';
import { ProductPresentation } from './product-presentation.entity';
import { Branch } from 'src/branch/entities/branch.entity';

@Entity('lot')
export class Lot extends BaseModel {
Expand All @@ -11,6 +12,13 @@ export class Lot extends BaseModel {
@JoinColumn({ name: 'product_presentation_id' })
productPresentation: ProductPresentation;

@Column({ type: 'int', name: 'quantity' })
quantity: number;

@ManyToOne(() => Branch)
@JoinColumn({ name: 'branch_id' })
branch: Branch;

@Column({ type: 'date', name: 'expiration_date' })
expirationDate: Date;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddBranchColumnInLotMigration1745985305444
implements MigrationInterface
{
name = 'AddBranchColumnInLotMigration1745985305444';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "lot" ADD "branch_id" uuid`);
await queryRunner.query(
`ALTER TABLE "lot" ADD CONSTRAINT "FK_7d53454b93e35a08f430262da15" FOREIGN KEY ("branch_id") REFERENCES "branch"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "lot" DROP CONSTRAINT "FK_7d53454b93e35a08f430262da15"`,
);
await queryRunner.query(`ALTER TABLE "lot" DROP COLUMN "branch_id"`);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddQuantityColumnInLotMigration1746026372925
implements MigrationInterface
{
name = 'AddQuantityColumnInLotMigration1746026372925';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "lot" ADD "quantity" integer NOT NULL`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "lot" DROP COLUMN "quantity"`);
}
}
Loading