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
2 changes: 2 additions & 0 deletions backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module';
import { AuthModule } from './auth/auth.module';
import { AssetsExtendedModule } from './assets/assets-extended.module';
import { AssetsOpsModule } from './assets/assets-ops.module';
import { CheckinModule } from './checkin/checkin.module';
import { AssetsModule } from './assets/assets.module';
Expand Down Expand Up @@ -64,6 +65,7 @@ import { CacheService } from './cache/cache.service';
},
}),

AssetsExtendedModule,
AssetsOpsModule,
CheckinModule,
AssetsModule,
Expand Down
56 changes: 56 additions & 0 deletions backend/src/assets/assets-extended.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { Controller, Post, Get, Patch, Delete, Param, Body, Query, Req, UseGuards, UseInterceptors, UploadedFile } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FileInterceptor } from '@nestjs/platform-express';
import { AssetsExtendedService } from './assets-extended.service';
import { TransferAssetDto } from './dtos/transfer-asset.dto';
import { CreateMaintenanceDto } from './dtos/create-maintenance.dto';
import { UpdateMaintenanceDto } from './dtos/update-maintenance.dto';
import { HistoryQueryDto } from './dtos/history-query.dto';

@Controller('assets')
@UseGuards(AuthGuard('jwt'))
export class AssetsExtendedController {
constructor(private readonly assetsExtendedService: AssetsExtendedService) {}

@Post(':id/transfer')
async transfer(@Param('id') id: string, @Body() dto: TransferAssetDto, @Req() req: any) {
return this.assetsExtendedService.transfer(id, dto, req.user?.id);
}

@Get(':id/history')
async getHistory(@Param('id') id: string, @Query() query: HistoryQueryDto) {
return this.assetsExtendedService.getHistory(id, query);
}

@Post(':id/documents')
@UseInterceptors(FileInterceptor('file'))
async uploadDocument(@Param('id') id: string, @UploadedFile() file: Express.Multer.File, @Req() req: any) {
return this.assetsExtendedService.addDocument(id, file, req.user?.id);
}

@Get(':id/documents')
async listDocuments(@Param('id') id: string) {
return this.assetsExtendedService.listDocuments(id);
}

@Delete(':id/documents/:documentId')
async deleteDocument(@Param('id') id: string, @Param('documentId') documentId: string) {
await this.assetsExtendedService.deleteDocument(id, documentId);
return { message: 'Document deleted' };
}

@Post(':id/maintenance')
async createMaintenance(@Param('id') id: string, @Body() dto: CreateMaintenanceDto, @Req() req: any) {
return this.assetsExtendedService.createMaintenance(id, dto, req.user?.id);
}

@Get(':id/maintenance')
async getMaintenanceRecords(@Param('id') id: string) {
return this.assetsExtendedService.getMaintenanceRecords(id);
}

@Patch(':id/maintenance/:recordId')
async updateMaintenance(@Param('id') id: string, @Param('recordId') recordId: string, @Body() dto: UpdateMaintenanceDto) {
return this.assetsExtendedService.updateMaintenance(id, recordId, dto);
}
}
16 changes: 16 additions & 0 deletions backend/src/assets/assets-extended.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Asset } from './entities/asset.entity';
import { AssetHistory } from './entities/asset-history.entity';
import { AssetDocument } from './entities/asset-document.entity';
import { MaintenanceRecord } from './entities/maintenance-record.entity';
import { AssetsExtendedService } from './assets-extended.service';
import { AssetsExtendedController } from './assets-extended.controller';

@Module({
imports: [TypeOrmModule.forFeature([Asset, AssetHistory, AssetDocument, MaintenanceRecord])],
controllers: [AssetsExtendedController],
providers: [AssetsExtendedService],
exports: [AssetsExtendedService],
})
export class AssetsExtendedModule {}
147 changes: 147 additions & 0 deletions backend/src/assets/assets-extended.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Asset } from './entities/asset.entity';
import { AssetHistory } from './entities/asset-history.entity';
import { AssetDocument } from './entities/asset-document.entity';
import { MaintenanceRecord } from './entities/maintenance-record.entity';
import { TransferAssetDto } from './dtos/transfer-asset.dto';
import { CreateMaintenanceDto } from './dtos/create-maintenance.dto';
import { UpdateMaintenanceDto } from './dtos/update-maintenance.dto';
import { HistoryQueryDto } from './dtos/history-query.dto';

@Injectable()
export class AssetsExtendedService {
constructor(
@InjectRepository(Asset)
private readonly assetRepository: Repository<Asset>,
@InjectRepository(AssetHistory)
private readonly historyRepository: Repository<AssetHistory>,
@InjectRepository(AssetDocument)
private readonly documentRepository: Repository<AssetDocument>,
@InjectRepository(MaintenanceRecord)
private readonly maintenanceRepository: Repository<MaintenanceRecord>,
) {}

async transfer(id: string, dto: TransferAssetDto, userId?: string): Promise<Asset> {
const asset = await this.assetRepository.findOne({ where: { id }, relations: ['assignedTo'] });
if (!asset) throw new NotFoundException('Asset not found');

const previousValue: Record<string, unknown> = {
assignedToId: asset.assignedToId,
departmentId: asset.departmentId,
location: asset.location,
};
const newValue: Record<string, unknown> = { ...dto };

Object.assign(asset, dto);
asset.updatedById = userId;
await this.assetRepository.save(asset);

await this.historyRepository.save(
this.historyRepository.create({
assetId: id,
action: 'TRANSFERRED',
description: dto.notes || 'Asset transferred',
previousValue: previousValue as Record<string, unknown>,
newValue: newValue as Record<string, unknown>,
performedById: userId,
}),
);

return asset;
}

async getHistory(assetId: string, query: HistoryQueryDto) {
const qb = this.historyRepository.createQueryBuilder('h')
.leftJoinAndSelect('h.performedBy', 'performedBy')
.where('h.assetId = :assetId', { assetId })
.orderBy('h.createdAt', 'DESC');

if (query.action) qb.andWhere('h.action = :action', { action: query.action });
if (query.startDate) qb.andWhere('h.createdAt >= :startDate', { startDate: query.startDate });
if (query.endDate) qb.andWhere('h.createdAt <= :endDate', { endDate: query.endDate });
if (query.search) qb.andWhere('h.description ILIKE :search', { search: `%${query.search}%` });

return qb.getMany();
}

async addDocument(assetId: string, file: Express.Multer.File, userId?: string): Promise<AssetDocument> {
const asset = await this.assetRepository.findOne({ where: { id: assetId } });
if (!asset) throw new NotFoundException('Asset not found');

const doc = this.documentRepository.create({
assetId,
name: file.originalname,
type: file.mimetype,
url: '', // Will be set after S3 upload
s3Key: `${assetId}/${Date.now()}-${file.originalname}`,
size: file.size,
uploadedById: userId,
});
await this.documentRepository.save(doc);

await this.historyRepository.save(
this.historyRepository.create({
assetId,
action: 'DOCUMENT_UPLOADED',
description: `Document "${file.originalname}" uploaded`,
performedById: userId,
}),
);

return doc;
}

async listDocuments(assetId: string) {
return this.documentRepository.find({
where: { assetId },
relations: ['uploadedBy'],
order: { createdAt: 'DESC' },
});
}

async deleteDocument(assetId: string, documentId: string): Promise<void> {
const doc = await this.documentRepository.findOne({ where: { id: documentId, assetId } });
if (!doc) throw new NotFoundException('Document not found');
await this.documentRepository.remove(doc);
}

async createMaintenance(assetId: string, dto: CreateMaintenanceDto, userId?: string): Promise<MaintenanceRecord> {
const asset = await this.assetRepository.findOne({ where: { id: assetId } });
if (!asset) throw new NotFoundException('Asset not found');

const record = this.maintenanceRepository.create({
assetId,
...dto,
performedById: userId,
});
await this.maintenanceRepository.save(record);

await this.historyRepository.save(
this.historyRepository.create({
assetId,
action: 'MAINTENANCE',
description: `Maintenance scheduled: ${dto.description}`,
performedById: userId,
}),
);

return record;
}

async getMaintenanceRecords(assetId: string) {
return this.maintenanceRepository.find({
where: { assetId },
relations: ['performedBy'],
order: { scheduledDate: 'DESC' },
});
}

async updateMaintenance(assetId: string, recordId: string, dto: UpdateMaintenanceDto): Promise<MaintenanceRecord> {
const record = await this.maintenanceRepository.findOne({ where: { id: recordId, assetId } });
if (!record) throw new NotFoundException('Maintenance record not found');
Object.assign(record, dto);
return this.maintenanceRepository.save(record);
}
}
16 changes: 16 additions & 0 deletions backend/src/assets/dtos/create-maintenance.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { IsString, IsOptional, IsNumber } from 'class-validator';

export class CreateMaintenanceDto {
@IsString()
type: string;

@IsString()
description: string;

@IsString()
scheduledDate: string;

@IsOptional()
@IsString()
notes?: string;
}
19 changes: 19 additions & 0 deletions backend/src/assets/dtos/history-query.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IsOptional, IsString } from 'class-validator';

export class HistoryQueryDto {
@IsOptional()
@IsString()
action?: string;

@IsOptional()
@IsString()
startDate?: string;

@IsOptional()
@IsString()
endDate?: string;

@IsOptional()
@IsString()
search?: string;
}
19 changes: 19 additions & 0 deletions backend/src/assets/dtos/transfer-asset.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { IsOptional, IsString } from 'class-validator';

export class TransferAssetDto {
@IsOptional()
@IsString()
assignedToId?: string;

@IsOptional()
@IsString()
departmentId?: string;

@IsOptional()
@IsString()
location?: string;

@IsOptional()
@IsString()
notes?: string;
}
23 changes: 23 additions & 0 deletions backend/src/assets/dtos/update-maintenance.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { IsOptional, IsString, IsNumber } from 'class-validator';

export class UpdateMaintenanceDto {
@IsOptional()
@IsString()
status?: string;

@IsOptional()
@IsString()
completedDate?: string;

@IsOptional()
@IsNumber()
cost?: number;

@IsOptional()
@IsString()
notes?: string;

@IsOptional()
@IsString()
performedById?: string;
}
41 changes: 41 additions & 0 deletions backend/src/assets/entities/asset-document.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import { Asset } from './asset.entity';
import { User } from '../../users/entities/user.entity';

@Entity('asset_documents')
export class AssetDocument {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column()
assetId: string;

@ManyToOne(() => Asset, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'assetId' })
asset: Asset;

@Column()
name: string;

@Column()
type: string;

@Column()
url: string;

@Column({ nullable: true })
s3Key: string;

@Column({ type: 'int', nullable: true })
size: number;

@Column({ nullable: true })
uploadedById: string;

@ManyToOne(() => User, { nullable: true })
@JoinColumn({ name: 'uploadedById' })
uploadedBy: User;

@CreateDateColumn()
createdAt: Date;
}
38 changes: 38 additions & 0 deletions backend/src/assets/entities/asset-history.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, ManyToOne, JoinColumn } from 'typeorm';
import { Asset } from './asset.entity';
import { User } from '../../users/entities/user.entity';

@Entity('asset_history')
export class AssetHistory {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column()
assetId: string;

@ManyToOne(() => Asset, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'assetId' })
asset: Asset;

@Column()
action: string;

@Column({ nullable: true, type: 'text' })
description: string;

@Column({ nullable: true, type: 'jsonb' })
previousValue: Record<string, unknown>;

@Column({ nullable: true, type: 'jsonb' })
newValue: Record<string, unknown>;

@Column({ nullable: true })
performedById: string;

@ManyToOne(() => User, { nullable: true })
@JoinColumn({ name: 'performedById' })
performedBy: User;

@CreateDateColumn()
createdAt: Date;
}
Loading
Loading