feat(rfa-ai): Complete RFA Approval Refactor and AI Model Revision
This commit is contained in:
@@ -8,12 +8,12 @@ import { JwtModule } from '@nestjs/jwt';
|
||||
import { PassportModule } from '@nestjs/passport';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AuthService } from './auth.service.js';
|
||||
import { AuthController } from './auth.controller.js';
|
||||
import { SessionController } from './session.controller.js';
|
||||
import { UserModule } from '../../modules/user/user.module.js';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy.js';
|
||||
import { JwtRefreshStrategy } from './strategies/jwt-refresh.strategy.js';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { SessionController } from './session.controller';
|
||||
import { UserModule } from '../../modules/user/user.module';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { JwtRefreshStrategy } from './strategies/jwt-refresh.strategy';
|
||||
import { User } from '../../modules/user/entities/user.entity';
|
||||
import { RefreshToken } from './entities/refresh-token.entity'; // [P2-2]
|
||||
import { CaslModule } from './casl/casl.module';
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ConfigService } from '@nestjs/config';
|
||||
import { CACHE_MANAGER } from '@nestjs/cache-manager';
|
||||
import type { Cache } from 'cache-manager';
|
||||
import { Request } from 'express';
|
||||
import { UserService } from '../../../modules/user/user.service.js';
|
||||
import { UserService } from '../../../modules/user/user.service';
|
||||
|
||||
// Interface สำหรับ Payload ใน Token
|
||||
export interface JwtPayload {
|
||||
|
||||
@@ -47,6 +47,14 @@ export class Attachment extends UuidBaseEntity {
|
||||
@Column({ name: 'reference_date', type: 'date', nullable: true })
|
||||
referenceDate?: Date;
|
||||
|
||||
@Column({
|
||||
name: 'ai_processing_status',
|
||||
type: 'enum',
|
||||
enum: ['PENDING', 'PROCESSING', 'DONE', 'FAILED'],
|
||||
default: 'PENDING',
|
||||
})
|
||||
aiProcessingStatus!: 'PENDING' | 'PROCESSING' | 'DONE' | 'FAILED';
|
||||
|
||||
// ADR-021: FK ไปยัง workflow_histories สำหรับไฟล์แนบประจำ Step
|
||||
// NULL = ไฟล์แนบหลัก (Main Document), NOT NULL = ไฟล์ประจำ Workflow Step
|
||||
@Column({ name: 'workflow_history_id', nullable: true })
|
||||
|
||||
@@ -2,18 +2,26 @@ import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { ScheduleModule } from '@nestjs/schedule'; // ✅ Import
|
||||
import { FileStorageService } from './file-storage.service.js';
|
||||
import { FileStorageController } from './file-storage.controller.js';
|
||||
import { FileCleanupService } from './file-cleanup.service.js'; // ✅ Import
|
||||
import { FileStorageService } from './file-storage.service';
|
||||
import { FileStorageController } from './file-storage.controller';
|
||||
import { FileCleanupService } from './file-cleanup.service'; // ✅ Import
|
||||
import { Attachment } from './entities/attachment.entity';
|
||||
import { UserModule } from '../../modules/user/user.module';
|
||||
import {
|
||||
QUEUE_AI_BATCH,
|
||||
QUEUE_AI_REALTIME,
|
||||
} from '../../modules/common/constants/queue.constants';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([Attachment]),
|
||||
ScheduleModule.forRoot(), // ✅ เปิดใช้งาน Cron Job],
|
||||
UserModule,
|
||||
BullModule.registerQueue({ name: 'rag-ocr' }),
|
||||
BullModule.registerQueue(
|
||||
{ name: 'rag-ocr' },
|
||||
{ name: QUEUE_AI_REALTIME },
|
||||
{ name: QUEUE_AI_BATCH }
|
||||
),
|
||||
],
|
||||
controllers: [FileStorageController],
|
||||
providers: [
|
||||
|
||||
@@ -17,6 +17,10 @@ import * as crypto from 'crypto';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { Attachment } from './entities/attachment.entity';
|
||||
import { ForbiddenException } from '@nestjs/common'; // ✅ Import เพิ่ม
|
||||
import {
|
||||
QUEUE_AI_BATCH,
|
||||
QUEUE_AI_REALTIME,
|
||||
} from '../../modules/common/constants/queue.constants';
|
||||
|
||||
@Injectable()
|
||||
export class FileStorageService {
|
||||
@@ -28,7 +32,13 @@ export class FileStorageService {
|
||||
@InjectRepository(Attachment)
|
||||
private attachmentRepository: Repository<Attachment>,
|
||||
private configService: ConfigService,
|
||||
@Optional() @InjectQueue('rag-ocr') private readonly ragOcrQueue?: Queue
|
||||
@Optional() @InjectQueue('rag-ocr') private readonly ragOcrQueue?: Queue,
|
||||
@Optional()
|
||||
@InjectQueue(QUEUE_AI_REALTIME)
|
||||
private readonly aiRealtimeQueue?: Queue,
|
||||
@Optional()
|
||||
@InjectQueue(QUEUE_AI_BATCH)
|
||||
private readonly aiBatchQueue?: Queue
|
||||
) {
|
||||
// ใช้ env vars จาก docker-compose สำหรับ Production
|
||||
// ถ้าไม่ได้กำหนดจะ fallback เป็น ./uploads/temp และ ./uploads/permanent
|
||||
@@ -185,6 +195,13 @@ export class FileStorageService {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (options?.ragMeta?.projectPublicId) {
|
||||
await this.enqueueAiJobsForCommittedAttachment(
|
||||
saved,
|
||||
options.ragMeta.projectPublicId
|
||||
);
|
||||
}
|
||||
} else {
|
||||
this.logger.error(`File missing during commit: ${oldPath}`);
|
||||
throw new NotFoundException(
|
||||
@@ -279,6 +296,57 @@ export class FileStorageService {
|
||||
return crypto.createHash('sha256').update(buffer).digest('hex');
|
||||
}
|
||||
|
||||
private async enqueueAiJobsForCommittedAttachment(
|
||||
attachment: Attachment,
|
||||
projectPublicId: string
|
||||
): Promise<void> {
|
||||
const commonPayload = {
|
||||
documentPublicId: attachment.publicId,
|
||||
projectPublicId,
|
||||
payload: { pdfPath: attachment.filePath },
|
||||
};
|
||||
const suggestResult = await this.aiRealtimeQueue
|
||||
?.add(
|
||||
'ai-suggest',
|
||||
{
|
||||
...commonPayload,
|
||||
jobType: 'ai-suggest',
|
||||
idempotencyKey: `suggest:${attachment.publicId}`,
|
||||
},
|
||||
{ jobId: `suggest:${attachment.publicId}` }
|
||||
)
|
||||
.then(() => true)
|
||||
.catch((err: unknown) => {
|
||||
this.logger.warn(
|
||||
`AI job queue failed, document saved without AI: ${attachment.publicId} (${err instanceof Error ? err.message : String(err)})`
|
||||
);
|
||||
return false;
|
||||
});
|
||||
const embedResult = await this.aiBatchQueue
|
||||
?.add(
|
||||
'embed-document',
|
||||
{
|
||||
...commonPayload,
|
||||
jobType: 'embed-document',
|
||||
idempotencyKey: `embed:${attachment.publicId}`,
|
||||
},
|
||||
{ jobId: `embed:${attachment.publicId}` }
|
||||
)
|
||||
.then(() => true)
|
||||
.catch((err: unknown) => {
|
||||
this.logger.warn(
|
||||
`AI job queue failed, document saved without AI: ${attachment.publicId} (${err instanceof Error ? err.message : String(err)})`
|
||||
);
|
||||
return false;
|
||||
});
|
||||
if (suggestResult === false || embedResult === false) {
|
||||
await this.attachmentRepository.update(
|
||||
{ publicId: attachment.publicId },
|
||||
{ aiProcessingStatus: 'FAILED' }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ✅ NEW: Import Staging File (For Legacy Migration)
|
||||
* ย้ายไฟล์จาก staging_ai ไปยัง permanent storage โดยตรง
|
||||
|
||||
Reference in New Issue
Block a user