Some checks failed
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m31s
Deploy / Build API Image (push) Failing after 25s
E2E Tests / Playwright E2E (push) Failing after 23s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Deploy / Build Web Image (push) Failing after 17s
Deploy / Build AI Services Image (push) Failing after 13s
Security Scanning / Trivy Scan — Web Image (push) Failing after 58s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 51s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m55s
Security Scanning / Trivy Filesystem Scan (push) Failing after 45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 3s
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 8s
CI / E2E Tests (push) Has been skipped
Closes the last gap from the tec-2725 branch: the valuation form's v2
extended-features section and POST endpoint can now submit real
predictions through to the Python ensemble model.
Backend
- New DTO apps/api/src/modules/analytics/presentation/dto/predict-valuation.dto.ts
with all v1 fields + 8 v2 fields (useV2 toggle, distanceToHospital/Park/
Mall in km, floodZoneRisk enum NONE|LOW|MEDIUM|HIGH, hasElevator/
Parking/Pool booleans).
- New CQRS handler apps/api/src/modules/analytics/application/queries/
predict-valuation/ that routes to AVM_SERVICE.estimateValue() with the
full request body.
- Extend AVMParams (domain) with the same v2 fields + inline v1 fields
(district, city, bedrooms, bathrooms, floors, frontage, roadWidth,
hasLegalPaper, projectId, imageUrl, description, deepAnalysis).
- HttpAVMService.estimateViaAi now branches on `useV2`: v2 calls the new
aiClient.predictV2() → POST /avm/v2/predict on the Python service,
mapping floodZoneRisk enum → 0..1 float and computing
building_age_years from yearBuilt. v1 path gets all the inline
descriptors wired through so non-propertyId calls no longer lose
context.
- AiServiceClient gets AiPredictV2Request / AiPredictV2Response types
mirroring libs/ai-services/app/models/avm_v2.py::AVMv2PredictRequest
(which already accepts all 7 numeric/boolean v2 fields — no Python
change needed).
- Register PredictValuationHandler in AnalyticsModule.
- New route POST /analytics/valuation on AnalyticsController:
JwtAuthGuard + QuotaGuard + EndpointRateLimitGuard (10/min),
@RequireQuota('analytics_queries'), full Swagger doc. Total endpoint
count 179 → 180.
Frontend
- Extend ValuationRequest with useV2, 3 distance-km fields,
floodZoneRisk, hasElevator/Parking/Pool + export FloodZoneRisk type
and FLOOD_RISK_OPTIONS.
- valuationApi.predict() body mapping now includes v2 fields and renames
'areaM2' → 'area' to match the backend DTO contract.
- valuationFormSchema gains matching optional Zod fields + exports
FLOOD_RISK_OPTIONS for the form.
- valuation-form.tsx gets:
* Image upload hardening: MIME+size validation (JPG/PNG ≤5MB) before
preview, role="progressbar" + aria-labels on the progress bar,
role="alert" + data-testid="image-upload-error" on errors. Matches
the upload-progress part of the task/tec-2725 commit 4ee0129 that
was previously parked as blocked.
* New Sparkles-branded "Mô hình v2 (Ensemble)" toggle alongside the
existing Bot-branded "Phân tích chuyên sâu" toggle.
* Collapsible "Đặc trưng mở rộng (AVM v2)" section with distance
inputs, flood-risk select, and three amenity checkboxes.
* handleFormSubmit passes all v2 fields through to onSubmit.
Python service unchanged — AVMv2PredictRequest already has every field
we send (distance_to_hospital_km, flood_zone_risk as float,
has_elevator/parking/pool, etc.).
Typecheck clean for the valuation surface. Pre-existing errors in
metadata.spec.ts and transfer-wizard-client.tsx are unrelated and left
for a follow-up.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
214 lines
7.2 KiB
TypeScript
214 lines
7.2 KiB
TypeScript
import { Inject, Injectable } from '@nestjs/common';
|
|
import { PrismaService, LoggerService } from '@modules/shared';
|
|
import {
|
|
type IAVMService,
|
|
type AVMParams,
|
|
type ValuationResult,
|
|
type Comparable,
|
|
type BatchValuationItem,
|
|
type BatchValuationResult,
|
|
} from '../../domain/services/avm-service';
|
|
import {
|
|
AI_SERVICE_CLIENT,
|
|
type IAiServiceClient,
|
|
type AiPredictRequest,
|
|
type AiPredictV2Request,
|
|
} from './ai-service.client';
|
|
|
|
/** Map string risk buckets to the 0..1 float the Python service expects. */
|
|
const FLOOD_RISK_TO_SCORE: Record<string, number> = {
|
|
NONE: 0,
|
|
LOW: 0.33,
|
|
MEDIUM: 0.66,
|
|
HIGH: 1,
|
|
};
|
|
import { PrismaAVMService } from './prisma-avm.service';
|
|
|
|
/** Max concurrency for batch AI calls to avoid overloading the Python service. */
|
|
const BATCH_CONCURRENCY = 5;
|
|
|
|
@Injectable()
|
|
export class HttpAVMService implements IAVMService {
|
|
constructor(
|
|
@Inject(AI_SERVICE_CLIENT) private readonly aiClient: IAiServiceClient,
|
|
private readonly fallback: PrismaAVMService,
|
|
private readonly prisma: PrismaService,
|
|
private readonly logger: LoggerService,
|
|
) {}
|
|
|
|
async estimateValue(params: AVMParams): Promise<ValuationResult> {
|
|
try {
|
|
return await this.estimateViaAi(params);
|
|
} catch (err) {
|
|
this.logger.warn(
|
|
`AI AVM service unavailable, falling back to comparables-based estimation: ${(err as Error).message}`,
|
|
'HttpAVMService',
|
|
);
|
|
return this.fallback.estimateValue(params);
|
|
}
|
|
}
|
|
|
|
async getComparables(propertyId: string, radiusMeters: number): Promise<Comparable[]> {
|
|
return this.fallback.getComparables(propertyId, radiusMeters);
|
|
}
|
|
|
|
async estimateBatch(items: BatchValuationItem[]): Promise<BatchValuationResult[]> {
|
|
const results: BatchValuationResult[] = [];
|
|
|
|
// Process in batches with limited concurrency
|
|
for (let i = 0; i < items.length; i += BATCH_CONCURRENCY) {
|
|
const chunk = items.slice(i, i + BATCH_CONCURRENCY);
|
|
const chunkResults = await Promise.allSettled(
|
|
chunk.map(async (item) => {
|
|
const valuation = await this.estimateValue({ propertyId: item.propertyId });
|
|
return { propertyId: item.propertyId, valuation } as BatchValuationResult;
|
|
}),
|
|
);
|
|
|
|
for (let j = 0; j < chunkResults.length; j++) {
|
|
const result = chunkResults[j]!;
|
|
const item = chunk[j]!;
|
|
if (result.status === 'fulfilled') {
|
|
results.push(result.value);
|
|
} else {
|
|
this.logger.warn(
|
|
`Batch valuation failed for property ${item.propertyId}: ${String(result.reason)}`,
|
|
'HttpAVMService',
|
|
);
|
|
results.push({
|
|
propertyId: item.propertyId,
|
|
valuation: null,
|
|
error: result.reason instanceof Error ? result.reason.message : 'Lỗi định giá',
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
private async estimateViaAi(params: AVMParams): Promise<ValuationResult> {
|
|
const propertyData = params.propertyId
|
|
? await this.getPropertyDetails(params.propertyId)
|
|
: null;
|
|
|
|
if (params.useV2) {
|
|
return this.estimateViaAiV2(params, propertyData);
|
|
}
|
|
|
|
const request: AiPredictRequest = {
|
|
area: params.areaM2 ?? propertyData?.areaM2 ?? 0,
|
|
district: params.district ?? propertyData?.district ?? '',
|
|
city: params.city ?? propertyData?.city ?? '',
|
|
property_type: (params.propertyType ?? propertyData?.propertyType ?? 'house').toLowerCase(),
|
|
bedrooms: params.bedrooms ?? propertyData?.bedrooms ?? 0,
|
|
bathrooms: params.bathrooms ?? propertyData?.bathrooms ?? 0,
|
|
floors: params.floors ?? propertyData?.floors ?? 0,
|
|
frontage: params.frontage ?? 0,
|
|
road_width: params.roadWidth ?? 0,
|
|
year_built: params.yearBuilt ?? propertyData?.yearBuilt,
|
|
has_legal_paper: params.hasLegalPaper ?? propertyData?.hasLegalPaper ?? true,
|
|
};
|
|
|
|
const aiResult = await this.aiClient.predict(request);
|
|
|
|
// Also fetch comparables from the local PostGIS service for context
|
|
let comparables: Comparable[] = [];
|
|
try {
|
|
if (params.propertyId) {
|
|
comparables = await this.fallback.getComparables(params.propertyId, 2000);
|
|
}
|
|
} catch {
|
|
// Comparables are supplementary — don't fail the valuation
|
|
}
|
|
|
|
return {
|
|
estimatedPrice: Math.round(aiResult.estimated_price_vnd).toString(),
|
|
confidence: aiResult.confidence,
|
|
pricePerM2: Math.round(aiResult.price_per_m2),
|
|
comparables,
|
|
modelVersion: 'ai-service-v1.0',
|
|
};
|
|
}
|
|
|
|
private async estimateViaAiV2(
|
|
params: AVMParams,
|
|
propertyData: Awaited<ReturnType<HttpAVMService['getPropertyDetails']>>,
|
|
): Promise<ValuationResult> {
|
|
const yearBuilt = params.yearBuilt ?? propertyData?.yearBuilt ?? null;
|
|
const now = new Date();
|
|
|
|
const v2Request: AiPredictV2Request = {
|
|
district: params.district ?? propertyData?.district ?? '',
|
|
city: params.city ?? propertyData?.city ?? '',
|
|
property_type: (params.propertyType ?? propertyData?.propertyType ?? 'house').toLowerCase(),
|
|
area_m2: params.areaM2 ?? propertyData?.areaM2 ?? 0,
|
|
distance_to_hospital_km: params.distanceToHospitalKm,
|
|
distance_to_park_km: params.distanceToParkKm,
|
|
distance_to_mall_km: params.distanceToMallKm,
|
|
flood_zone_risk:
|
|
params.floodZoneRisk != null ? FLOOD_RISK_TO_SCORE[params.floodZoneRisk] ?? 0 : undefined,
|
|
rooms: params.bedrooms ?? propertyData?.bedrooms,
|
|
total_floors: params.floors ?? propertyData?.floors,
|
|
building_age_years: yearBuilt != null ? Math.max(0, now.getFullYear() - yearBuilt) : undefined,
|
|
has_elevator: params.hasElevator,
|
|
has_parking: params.hasParking,
|
|
has_pool: params.hasPool,
|
|
has_legal_paper: params.hasLegalPaper ?? propertyData?.hasLegalPaper ?? true,
|
|
month: now.getMonth() + 1,
|
|
quarter: Math.floor(now.getMonth() / 3) + 1,
|
|
is_year_end: now.getMonth() >= 9,
|
|
};
|
|
|
|
const aiResult = await this.aiClient.predictV2(v2Request);
|
|
|
|
let comparables: Comparable[] = [];
|
|
try {
|
|
if (params.propertyId) {
|
|
comparables = await this.fallback.getComparables(params.propertyId, 2000);
|
|
}
|
|
} catch {
|
|
// Supplementary — don't fail
|
|
}
|
|
|
|
return {
|
|
estimatedPrice: Math.round(aiResult.estimated_price_vnd).toString(),
|
|
confidence: aiResult.confidence,
|
|
pricePerM2: Math.round(aiResult.price_per_m2_vnd),
|
|
comparables,
|
|
modelVersion: aiResult.model_version ?? 'ai-service-v2',
|
|
};
|
|
}
|
|
|
|
private async getPropertyDetails(propertyId: string) {
|
|
const row = await this.prisma.property.findUnique({
|
|
where: { id: propertyId },
|
|
select: {
|
|
areaM2: true,
|
|
district: true,
|
|
city: true,
|
|
propertyType: true,
|
|
bedrooms: true,
|
|
bathrooms: true,
|
|
floors: true,
|
|
yearBuilt: true,
|
|
legalStatus: true,
|
|
},
|
|
});
|
|
|
|
if (!row) return null;
|
|
|
|
return {
|
|
areaM2: row.areaM2,
|
|
district: row.district,
|
|
city: row.city,
|
|
propertyType: row.propertyType,
|
|
bedrooms: row.bedrooms ?? 0,
|
|
bathrooms: row.bathrooms ?? 0,
|
|
floors: row.floors ?? 0,
|
|
yearBuilt: row.yearBuilt,
|
|
hasLegalPaper: row.legalStatus === 'SO_DO' || row.legalStatus === 'SO_HONG',
|
|
};
|
|
}
|
|
}
|