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 @@ -14,6 +14,7 @@ import { QueueModule } from './queue/queue.module';
import { RiskAssessmentModule } from './risk-assessment/risk-assessment.module';
import { StellarModule } from './stellar/stellar.module';
import { UsersModule } from './users/users.module';
import { TransfersModule } from './transfers/transfers.module';
import { VerificationModule } from './verification/verification.module';

@Module({
Expand Down Expand Up @@ -48,6 +49,7 @@ import { VerificationModule } from './verification/verification.module';
RiskAssessmentModule,
StellarModule,
VerificationModule,
TransfersModule,
MailModule,
QueueModule,
],
Expand Down
19 changes: 18 additions & 1 deletion backend/src/documents/documents.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
NotFoundException,
Param,
Post,
Query,
Req,
Res,
UploadedFile,
Expand All @@ -23,9 +24,10 @@ import * as multer from 'multer';
import { DocumentsService } from './documents.service';
import { DocumentStatus } from './entities/document.entity';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { User } from '../users/entities/user.entity';
import { User, UserRole } from '../users/entities/user.entity';
import { QueueService } from '../queue/queue.service';
import { VerificationService } from '../verification/verification.service';
import { QueryDocumentsDto } from './dto/query-documents.dto';

const ALLOWED_MIME_TYPES = ['application/pdf', 'image/png', 'image/jpeg'];
const MAX_FILE_SIZE_BYTES = 20 * 1024 * 1024;
Expand All @@ -49,6 +51,21 @@ export class DocumentsController {
private readonly verificationService: VerificationService,
) {}

@Get()
@UseGuards(JwtAuthGuard)
async listDocuments(
@Query() query: QueryDocumentsDto,
@Req() req: Request & { user?: User },
) {
const user = req.user;
if (!user) {
throw new BadRequestException('Authenticated user is required');
}

const isAdmin = user.role === UserRole.ADMIN;
return this.documentsService.findWithFilters(query, user.id, isAdmin);
}

@Post('upload')
@UseGuards(JwtAuthGuard)
@UseInterceptors(
Expand Down
53 changes: 53 additions & 0 deletions backend/src/documents/documents.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Document, DocumentStatus } from './entities/document.entity';
import { PaginatedDocumentsDto } from './dto/document.dto';
import { QueryDocumentsDto } from './dto/query-documents.dto';

@Injectable()
export class DocumentsService {
Expand Down Expand Up @@ -47,4 +49,55 @@ export class DocumentsService {
async delete(id: string): Promise<void> {
await this.documentRepository.delete(id);
}

async findWithFilters(
filters: QueryDocumentsDto,
requestingUserId: string,
isAdmin: boolean,
): Promise<PaginatedDocumentsDto> {
const page = filters.page ?? 1;
const limit = Math.min(filters.limit ?? 20, 100);
const skip = (page - 1) * limit;

const qb = this.documentRepository
.createQueryBuilder('document')
.orderBy('document.createdAt', 'DESC')
.skip(skip)
.take(limit);

// Scope: regular users only see their own documents
if (!isAdmin) {
qb.andWhere('document.owner_id = :ownerId', { ownerId: requestingUserId });
}

if (filters.status) {
qb.andWhere('document.status = :status', { status: filters.status });
}

if (filters.min_risk_score !== undefined) {
qb.andWhere('document.risk_score >= :minRiskScore', { minRiskScore: filters.min_risk_score });
}

if (filters.max_risk_score !== undefined) {
qb.andWhere('document.risk_score <= :maxRiskScore', { maxRiskScore: filters.max_risk_score });
}

if (filters.from_date) {
qb.andWhere('document.created_at >= :fromDate', { fromDate: new Date(filters.from_date) });
}

if (filters.to_date) {
qb.andWhere('document.created_at <= :toDate', { toDate: new Date(filters.to_date) });
}

if (filters.search) {
qb.andWhere('LOWER(document.title) LIKE :search', {
search: `%${filters.search.toLowerCase()}%`,
});
}

const [data, total] = await qb.getManyAndCount();

return { data, total, page, limit };
}
}
23 changes: 23 additions & 0 deletions backend/src/documents/dto/document.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { DocumentStatus } from '../entities/document.entity';

export class DocumentDto {
id: string;
ownerId: string;
title: string;
filePath: string;
fileHash: string;
fileSize: number;
mimeType: string;
status: DocumentStatus;
riskScore?: number | null;
riskFlags?: string[] | null;
createdAt: Date;
updatedAt: Date;
}

export class PaginatedDocumentsDto {
data: DocumentDto[];
total: number;
page: number;
limit: number;
}
46 changes: 46 additions & 0 deletions backend/src/documents/dto/query-documents.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { IsEnum, IsISO8601, IsNumber, IsOptional, IsString, Max, Min } from 'class-validator';
import { Type } from 'class-transformer';
import { DocumentStatus } from '../entities/document.entity';

export class QueryDocumentsDto {
@IsOptional()
@IsEnum(DocumentStatus)
status?: DocumentStatus;

@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
min_risk_score?: number;

@IsOptional()
@Type(() => Number)
@IsNumber()
@Max(100)
max_risk_score?: number;

@IsOptional()
@IsISO8601()
from_date?: string;

@IsOptional()
@IsISO8601()
to_date?: string;

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

@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(1)
page?: number = 1;

@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(1)
@Max(100)
limit?: number = 20;
}
20 changes: 20 additions & 0 deletions backend/src/transfers/dto/create-transfer.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { IsISO8601, IsOptional, IsString, IsUUID } from 'class-validator';

export class CreateTransferDto {
@IsUUID()
documentId: string;

@IsUUID()
fromUserId: string;

@IsUUID()
toUserId: string;

@IsOptional()
@IsISO8601()
transferredAt?: string;

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

@Entity('transfers')
export class Transfer {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ name: 'document_id' })
documentId: string;

@ManyToOne(() => Document, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'document_id' })
document: Document;

@Column({ name: 'from_user_id' })
fromUserId: string;

@ManyToOne(() => User, { onDelete: 'RESTRICT' })
@JoinColumn({ name: 'from_user_id' })
fromUser: User;

@Column({ name: 'to_user_id' })
toUserId: string;

@ManyToOne(() => User, { onDelete: 'RESTRICT' })
@JoinColumn({ name: 'to_user_id' })
toUser: User;

@Column({ name: 'stellar_tx_hash', nullable: true })
stellarTxHash?: string;

@Column({ name: 'transferred_at', type: 'timestamptz' })
transferredAt: Date;

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

@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
}
44 changes: 44 additions & 0 deletions backend/src/transfers/transfers.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
Body,
Controller,
Get,
NotFoundException,
Param,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { DocumentsService } from '../documents/documents.service';
import { CreateTransferDto } from './dto/create-transfer.dto';
import { TransfersService } from './transfers.service';

@Controller()
@UseGuards(JwtAuthGuard)
export class TransfersController {
constructor(
private readonly transfersService: TransfersService,
private readonly documentsService: DocumentsService,
) {}

/**
* POST /api/transfers
* Create a new ownership transfer, anchor it on Stellar, and persist the record.
*/
@Post('transfers')
async createTransfer(@Body() dto: CreateTransferDto) {
return this.transfersService.create(dto);
}

/**
* GET /api/documents/:id/transfers
* Return the full transfer history for a document in chronological order.
*/
@Get('documents/:id/transfers')
async getDocumentTransfers(@Param('id') id: string) {
const document = await this.documentsService.findById(id);
if (!document) {
throw new NotFoundException(`Document ${id} not found`);
}
return this.transfersService.findByDocument(id);
}
}
21 changes: 21 additions & 0 deletions backend/src/transfers/transfers.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { DocumentsModule } from '../documents/documents.module';
import { StellarModule } from '../stellar/stellar.module';
import { UsersModule } from '../users/users.module';
import { Transfer } from './entities/transfer.entity';
import { TransfersController } from './transfers.controller';
import { TransfersService } from './transfers.service';

@Module({
imports: [
TypeOrmModule.forFeature([Transfer]),
DocumentsModule,
UsersModule,
StellarModule,
],
controllers: [TransfersController],
providers: [TransfersService],
exports: [TransfersService],
})
export class TransfersModule {}
Loading
Loading