feat(listings): AI advisor on listing detail — valuation + qualitative advice
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 5s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 38s
Deploy / Build API Image (push) Failing after 23s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 9s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 30s
Security Scanning / Trivy Scan — Web Image (push) Failing after 25s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 20s
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Security Scanning / Trivy Filesystem Scan (push) Failing after 29s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 2s
Deploy / Rollback Production (push) Has been skipped
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 5s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 38s
Deploy / Build API Image (push) Failing after 23s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 9s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 30s
Security Scanning / Trivy Scan — Web Image (push) Failing after 25s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 20s
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Security Scanning / Trivy Filesystem Scan (push) Failing after 29s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 2s
Deploy / Rollback Production (push) Has been skipped
New endpoint POST /analytics/listings/:id/ai-advice (JwtAuthGuard).
Orchestrates a single-listing AI analysis in Vietnamese via Anthropic
Claude, using the key/URL/model configured in admin settings.
Backend
-------
- New CQRS: get-listing-ai-advice/{query,handler}.ts under analytics.
Injects LISTING_REPOSITORY, QueryBus (for nearby POIs + neighborhood
score), SystemSettingsService (from @modules/admin), LoggerService.
- Controller @Post('listings/:id/ai-advice') in analytics.controller.ts.
- analytics.module.ts now imports ListingsModule + AdminModule.
- Anthropic call: native fetch to ${apiUrl}/messages with
x-api-key + anthropic-version: 2023-06-01 +
anthropic-beta: prompt-caching-2024-07-31. System block marked
cache_control:{type:'ephemeral'} for cheap subsequent cache hits.
30s AbortController timeout.
- Response validation without adding zod to the API workspace —
lightweight isRecord/asInt/asString/asStringArray helpers.
Strips ```json fences before JSON.parse.
- Error handling:
* 503 AI_NOT_CONFIGURED when the admin hasn't saved an API key.
* 502 AI_PROVIDER_ERROR on non-2xx, parse failure, or timeout.
* Key never logged.
* POI / score fetch failures are soft — prompt is built without
them and the model still runs.
- New error codes AI_NOT_CONFIGURED / AI_PROVIDER_ERROR in
shared/domain/error-codes.ts.
Response shape (returned unchanged to the client):
```
{
valuation: { estimateVND, lowVND, highVND, confidence, rationale },
advice: { summary, pros[], cons[], suitableFor[] },
model, cacheHit
}
```
Frontend
--------
- analytics-api.ts: exports AiConfidence, ListingAiValuation,
ListingAiAdviceBody, ListingAiAdvice + getListingAiAdvice(id).
- New components/listings/ai-advice-cards.tsx.
* Default state: outline <Button><Sparkles/> Xem phân tích AI</Button>
* On click: useMutation fires + skeleton with Sparkles spinner.
* On success: two sidebar cards:
- "AI định giá" — big mid VND, low–high range, Low/Medium/High
confidence badge, rationale with line-clamp-3.
- "AI nhận định" — 2-sentence summary + two-column Pros/Cons
(Check / AlertTriangle icons) + "AI gợi ý" chips for extra
personas, plus a "Làm mới" link that re-triggers the mutation.
* 503 → amber banner. ADMIN users see a link to /admin/settings/ai.
* Other errors → red banner with retry.
- listing-detail-client.tsx mounts <AiAdviceCards listingId=... /> in
the sidebar between the social-share card and the stats block.
Existing <AiEstimateButton> kept untouched next to it.
Constraints preserved
---------------------
- No new npm packages; no @anthropic-ai/sdk.
- Runtime imports for NestJS DI classes.
- API key read at request time only — nothing persists it outside
SystemSetting.
Verification
------------
- API typecheck clean; 1975 / 1975 tests pass.
- Web typecheck clean in touched files; 624 / 624 tests pass.
- AiAdviceCards spec-mocked in listing-detail-client.spec so
QueryClientProvider isn't required.
User can now set their Anthropic key via /admin/settings/ai and click
"Xem phân tích AI" on any listing detail to get valuation + advice.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CqrsModule } from '@nestjs/cqrs';
|
||||
import { AdminModule } from '@modules/admin';
|
||||
import { ListingsModule } from '@modules/listings';
|
||||
import { GenerateReportHandler } from './application/commands/generate-report/generate-report.handler';
|
||||
import { TrackEventHandler } from './application/commands/track-event/track-event.handler';
|
||||
import { UpdateMarketIndexHandler } from './application/commands/update-market-index/update-market-index.handler';
|
||||
@@ -8,6 +10,7 @@ import { BatchValuationHandler } from './application/queries/batch-valuation/bat
|
||||
import { IndustrialValuationHandler } from './application/queries/industrial-valuation/industrial-valuation.handler';
|
||||
import { GetDistrictStatsHandler } from './application/queries/get-district-stats/get-district-stats.handler';
|
||||
import { GetHeatmapHandler } from './application/queries/get-heatmap/get-heatmap.handler';
|
||||
import { GetListingAiAdviceHandler } from './application/queries/get-listing-ai-advice/get-listing-ai-advice.handler';
|
||||
import { GetMarketReportHandler } from './application/queries/get-market-report/get-market-report.handler';
|
||||
import { GetNearbyPOIsHandler } from './application/queries/get-nearby-pois/get-nearby-pois.handler';
|
||||
import { GetNeighborhoodScoreHandler } from './application/queries/get-neighborhood-score/get-neighborhood-score.handler';
|
||||
@@ -54,6 +57,7 @@ const QueryHandlers = [
|
||||
GetNeighborhoodScoreHandler,
|
||||
GetNearbyPOIsHandler,
|
||||
IndustrialValuationHandler,
|
||||
GetListingAiAdviceHandler,
|
||||
];
|
||||
|
||||
const EventHandlers = [
|
||||
@@ -61,7 +65,7 @@ const EventHandlers = [
|
||||
];
|
||||
|
||||
@Module({
|
||||
imports: [CqrsModule],
|
||||
imports: [CqrsModule, ListingsModule, AdminModule],
|
||||
controllers: [AnalyticsController, AvmController],
|
||||
providers: [
|
||||
// AI service client
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
import { HttpStatus, Inject } from '@nestjs/common';
|
||||
import { QueryBus, QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
|
||||
import { DomainException, ErrorCode, LoggerService } from '@modules/shared';
|
||||
import { SystemSettingsService } from '@modules/admin';
|
||||
import {
|
||||
LISTING_REPOSITORY,
|
||||
type IListingRepository,
|
||||
} from '@modules/listings';
|
||||
import { type ListingDetailData } from '../../../../listings/domain/repositories/listing-read.dto';
|
||||
import {
|
||||
type NearbyPOIDto,
|
||||
type NearbyPOIsResultDto,
|
||||
} from '../get-nearby-pois/get-nearby-pois.handler';
|
||||
import { GetNearbyPOIsQuery } from '../get-nearby-pois/get-nearby-pois.query';
|
||||
import { type NeighborhoodScoreResult } from '../../../domain/services/neighborhood-score.service';
|
||||
import { GetNeighborhoodScoreQuery } from '../get-neighborhood-score/get-neighborhood-score.query';
|
||||
import { GetListingAiAdviceQuery } from './get-listing-ai-advice.query';
|
||||
|
||||
/** Shape returned by Anthropic (parsed from first content block). */
|
||||
export type AiConfidence = 'low' | 'medium' | 'high';
|
||||
|
||||
export interface ListingAiValuation {
|
||||
estimateVND: number;
|
||||
lowVND: number;
|
||||
highVND: number;
|
||||
confidence: AiConfidence;
|
||||
rationale: string;
|
||||
}
|
||||
|
||||
export interface ListingAiAdvice {
|
||||
summary: string;
|
||||
pros: string[];
|
||||
cons: string[];
|
||||
suitableFor: string[];
|
||||
}
|
||||
|
||||
export interface ListingAiAdviceResponse {
|
||||
valuation: ListingAiValuation;
|
||||
advice: ListingAiAdvice;
|
||||
model: string;
|
||||
cacheHit: boolean;
|
||||
cacheUsage?: {
|
||||
input: number;
|
||||
cacheCreation: number;
|
||||
cacheRead: number;
|
||||
output: number;
|
||||
};
|
||||
}
|
||||
|
||||
// System prompt: Vietnamese real-estate persona. Short, stable, cacheable.
|
||||
const SYSTEM_PROMPT = `Bạn là chuyên gia thẩm định bất động sản Việt Nam (HCM & Hà Nội). Dựa trên dữ liệu được cung cấp, hãy đưa ra (1) ước tính giá trị hợp lý bằng VND và (2) nhận định ngắn gọn về điểm mạnh/yếu của BĐS.
|
||||
|
||||
Bối cảnh thị trường:
|
||||
- Đơn vị tiền tệ: VND (không dùng USD).
|
||||
- Giá/m² tham khảo ở HCM: Quận 1/3 ~ 200–350 tr, Bình Thạnh/Phú Nhuận ~ 70–130 tr, Quận 7 ~ 60–100 tr, vùng ven ~ 30–55 tr. Hà Nội: Hoàn Kiếm/Ba Đình ~ 250–400 tr, Cầu Giấy/Thanh Xuân ~ 60–120 tr.
|
||||
- Giá giao dịch có thể lệch ±15% so với giá niêm yết tuỳ pháp lý, nội thất, view, hướng.
|
||||
|
||||
Bắt buộc trả về **JSON thuần** đúng schema, KHÔNG bọc markdown, KHÔNG giải thích thêm:
|
||||
{
|
||||
"valuation": {
|
||||
"estimateVND": <số nguyên VND>,
|
||||
"lowVND": <số nguyên VND>,
|
||||
"highVND": <số nguyên VND>,
|
||||
"confidence": "low" | "medium" | "high",
|
||||
"rationale": "<1-2 câu tiếng Việt>"
|
||||
},
|
||||
"advice": {
|
||||
"summary": "<≤ 2 câu tổng quan tiếng Việt>",
|
||||
"pros": ["<cụm ngắn>", ...], // 3-5 mục
|
||||
"cons": ["<cụm ngắn>", ...], // 2-4 mục
|
||||
"suitableFor": ["<nhãn persona>", ...] // 2-4 mục, tiếng Việt
|
||||
}
|
||||
}
|
||||
|
||||
Đưa ra estimateVND nằm giữa lowVND và highVND. Dải low/high nên phản ánh độ bất định: confidence=high dải ~±8%, medium ~±15%, low ~±25%.`;
|
||||
|
||||
interface AnthropicMessage {
|
||||
type: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
interface AnthropicResponse {
|
||||
content?: AnthropicMessage[];
|
||||
usage?: {
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
cache_creation_input_tokens?: number;
|
||||
cache_read_input_tokens?: number;
|
||||
};
|
||||
}
|
||||
|
||||
const ANTHROPIC_TIMEOUT_MS = 30_000;
|
||||
|
||||
@QueryHandler(GetListingAiAdviceQuery)
|
||||
export class GetListingAiAdviceHandler
|
||||
implements IQueryHandler<GetListingAiAdviceQuery, ListingAiAdviceResponse>
|
||||
{
|
||||
constructor(
|
||||
@Inject(LISTING_REPOSITORY)
|
||||
private readonly listingRepo: IListingRepository,
|
||||
private readonly queryBus: QueryBus,
|
||||
private readonly systemSettings: SystemSettingsService,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
async execute(
|
||||
query: GetListingAiAdviceQuery,
|
||||
): Promise<ListingAiAdviceResponse> {
|
||||
const listing = await this.listingRepo.findByIdWithProperty(query.listingId);
|
||||
if (!listing) {
|
||||
throw new DomainException(
|
||||
ErrorCode.LISTING_NOT_FOUND,
|
||||
`Không tìm thấy tin đăng ${query.listingId}`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch enrichments in parallel (both tolerate missing data).
|
||||
const [poisResult, score] = await Promise.all([
|
||||
this.fetchPois(listing),
|
||||
this.fetchScore(listing),
|
||||
]);
|
||||
|
||||
const settings = await this.systemSettings.getAiSettings();
|
||||
if (!settings.apiKey) {
|
||||
throw new DomainException(
|
||||
ErrorCode.AI_NOT_CONFIGURED,
|
||||
'Quản trị viên chưa cấu hình Claude API. Vào /admin/settings/ai để thiết lập.',
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
);
|
||||
}
|
||||
|
||||
const userPrompt = buildUserPrompt(listing, poisResult, score);
|
||||
|
||||
const raw = await this.callAnthropic({
|
||||
apiUrl: settings.apiUrl,
|
||||
apiKey: settings.apiKey,
|
||||
model: settings.model,
|
||||
userPrompt,
|
||||
});
|
||||
|
||||
const parsed = parseAndValidate(raw);
|
||||
|
||||
const cacheRead = raw.usage?.cache_read_input_tokens ?? 0;
|
||||
const cacheCreation = raw.usage?.cache_creation_input_tokens ?? 0;
|
||||
|
||||
return {
|
||||
valuation: parsed.valuation,
|
||||
advice: parsed.advice,
|
||||
model: settings.model,
|
||||
cacheHit: cacheRead > 0,
|
||||
cacheUsage: {
|
||||
input: raw.usage?.input_tokens ?? 0,
|
||||
cacheCreation,
|
||||
cacheRead,
|
||||
output: raw.usage?.output_tokens ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchPois(
|
||||
listing: ListingDetailData,
|
||||
): Promise<NearbyPOIsResultDto | null> {
|
||||
const { latitude, longitude } = listing.property;
|
||||
if (latitude == null || longitude == null) return null;
|
||||
try {
|
||||
return await this.queryBus.execute<
|
||||
GetNearbyPOIsQuery,
|
||||
NearbyPOIsResultDto
|
||||
>(new GetNearbyPOIsQuery(latitude, longitude, 2000, 30));
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`[ai-advice] fetchPois failed: ${err instanceof Error ? err.message : err}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchScore(
|
||||
listing: ListingDetailData,
|
||||
): Promise<NeighborhoodScoreResult | null> {
|
||||
const { district, city } = listing.property;
|
||||
if (!district || !city) return null;
|
||||
try {
|
||||
return await this.queryBus.execute<
|
||||
GetNeighborhoodScoreQuery,
|
||||
NeighborhoodScoreResult | null
|
||||
>(new GetNeighborhoodScoreQuery(district, city));
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`[ai-advice] fetchScore failed: ${err instanceof Error ? err.message : err}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async callAnthropic(args: {
|
||||
apiUrl: string;
|
||||
apiKey: string;
|
||||
model: string;
|
||||
userPrompt: string;
|
||||
}): Promise<AnthropicResponse> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), ANTHROPIC_TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(`${args.apiUrl.replace(/\/$/, '')}/messages`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': args.apiKey,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'anthropic-beta': 'prompt-caching-2024-07-31',
|
||||
},
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
model: args.model,
|
||||
max_tokens: 1024,
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: SYSTEM_PROMPT,
|
||||
cache_control: { type: 'ephemeral' },
|
||||
},
|
||||
],
|
||||
messages: [{ role: 'user', content: args.userPrompt }],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const bodySnippet = await res.text().catch(() => '');
|
||||
this.logger.error(
|
||||
`[ai-advice] Anthropic non-2xx ${res.status}: ${bodySnippet.slice(0, 500)}`,
|
||||
);
|
||||
throw new DomainException(
|
||||
ErrorCode.AI_PROVIDER_ERROR,
|
||||
'Không gọi được dịch vụ AI. Vui lòng thử lại sau.',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
return (await res.json()) as AnthropicResponse;
|
||||
} catch (err) {
|
||||
if (err instanceof DomainException) throw err;
|
||||
const isAbort =
|
||||
err instanceof Error &&
|
||||
(err.name === 'AbortError' || /aborted/i.test(err.message));
|
||||
this.logger.error(
|
||||
`[ai-advice] fetch failed (${isAbort ? 'timeout' : 'network'}): ${err instanceof Error ? err.message : err}`,
|
||||
);
|
||||
throw new DomainException(
|
||||
ErrorCode.AI_PROVIDER_ERROR,
|
||||
isAbort
|
||||
? 'AI không phản hồi kịp. Vui lòng thử lại.'
|
||||
: 'Không gọi được dịch vụ AI. Vui lòng thử lại sau.',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Prompt construction
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
function buildUserPrompt(
|
||||
listing: ListingDetailData,
|
||||
poisResult: NearbyPOIsResultDto | null,
|
||||
score: NeighborhoodScoreResult | null,
|
||||
): string {
|
||||
const p = listing.property;
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('### THÔNG TIN TIN ĐĂNG');
|
||||
lines.push(`- Loại giao dịch: ${listing.transactionType}`);
|
||||
lines.push(`- Giá niêm yết: ${listing.priceVND} VND`);
|
||||
if (listing.pricePerM2 != null) {
|
||||
lines.push(`- Giá / m²: ${listing.pricePerM2.toLocaleString('vi-VN')} VND`);
|
||||
}
|
||||
lines.push(`- Diện tích: ${p.areaM2} m²`);
|
||||
if (p.bedrooms != null) lines.push(`- Phòng ngủ: ${p.bedrooms}`);
|
||||
if (p.bathrooms != null) lines.push(`- Phòng tắm: ${p.bathrooms}`);
|
||||
lines.push(`- Loại BĐS: ${p.propertyType}`);
|
||||
lines.push(`- Địa chỉ: ${p.address}, ${p.ward ?? ''}, ${p.district}, ${p.city}`);
|
||||
if (p.direction) lines.push(`- Hướng: ${p.direction}`);
|
||||
if (p.yearBuilt) lines.push(`- Năm xây: ${p.yearBuilt}`);
|
||||
if (p.legalStatus) lines.push(`- Pháp lý: ${p.legalStatus}`);
|
||||
if (p.furnishing) lines.push(`- Nội thất: ${p.furnishing}`);
|
||||
if (p.propertyCondition) lines.push(`- Tình trạng: ${p.propertyCondition}`);
|
||||
if (p.metroDistanceM != null) {
|
||||
lines.push(`- Cách metro: ${p.metroDistanceM} m`);
|
||||
}
|
||||
if (p.suitableFor && p.suitableFor.length > 0) {
|
||||
lines.push(`- Người đăng gợi ý phù hợp: ${p.suitableFor.join(', ')}`);
|
||||
}
|
||||
if (p.whyThisLocation) {
|
||||
lines.push(`- Ghi chú vị trí (người đăng): ${p.whyThisLocation}`);
|
||||
}
|
||||
|
||||
if (poisResult && poisResult.pois.length > 0) {
|
||||
const counts = countByCategory(poisResult.pois);
|
||||
const closest = poisResult.pois.slice(0, 5);
|
||||
lines.push('');
|
||||
lines.push('### ĐIỂM QUAN TÂM LÂN CẬN (bán kính 2km)');
|
||||
const countLine = Object.entries(counts)
|
||||
.map(([cat, n]) => `${cat}: ${n}`)
|
||||
.join(', ');
|
||||
lines.push(`- Số lượng theo nhóm: ${countLine}`);
|
||||
lines.push('- 5 điểm gần nhất:');
|
||||
for (const poi of closest) {
|
||||
lines.push(
|
||||
` • ${poi.name} (${poi.category}) — ${Math.round(poi.distance)} m`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (score) {
|
||||
lines.push('');
|
||||
lines.push('### ĐIỂM KHU VỰC (thang 0–10)');
|
||||
lines.push(`- Giáo dục: ${score.educationScore.toFixed(1)}`);
|
||||
lines.push(`- Y tế: ${score.healthcareScore.toFixed(1)}`);
|
||||
lines.push(`- Giao thông: ${score.transportScore.toFixed(1)}`);
|
||||
lines.push(`- Mua sắm: ${score.shoppingScore.toFixed(1)}`);
|
||||
lines.push(`- Môi trường: ${score.greeneryScore.toFixed(1)}`);
|
||||
lines.push(`- An ninh: ${score.safetyScore.toFixed(1)}`);
|
||||
lines.push(`- Tổng: ${score.totalScore.toFixed(1)}`);
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
lines.push('Hãy trả về JSON đúng schema đã quy định.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function countByCategory(pois: NearbyPOIDto[]): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const p of pois) {
|
||||
out[p.category] = (out[p.category] ?? 0) + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Response parsing / validation (lightweight — no new deps)
|
||||
// --------------------------------------------------------------------------
|
||||
|
||||
function parseAndValidate(raw: AnthropicResponse): {
|
||||
valuation: ListingAiValuation;
|
||||
advice: ListingAiAdvice;
|
||||
} {
|
||||
const block = raw.content?.find((c) => c.type === 'text');
|
||||
const text = block?.text?.trim();
|
||||
if (!text) {
|
||||
throw new DomainException(
|
||||
ErrorCode.AI_PROVIDER_ERROR,
|
||||
'AI trả về nội dung trống.',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
const jsonText = stripJsonFence(text);
|
||||
let obj: unknown;
|
||||
try {
|
||||
obj = JSON.parse(jsonText);
|
||||
} catch {
|
||||
throw new DomainException(
|
||||
ErrorCode.AI_PROVIDER_ERROR,
|
||||
'AI trả về JSON không hợp lệ.',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
|
||||
if (!isRecord(obj)) throw jsonShapeError();
|
||||
const valuation = parseValuation(obj['valuation']);
|
||||
const advice = parseAdvice(obj['advice']);
|
||||
return { valuation, advice };
|
||||
}
|
||||
|
||||
function parseValuation(v: unknown): ListingAiValuation {
|
||||
if (!isRecord(v)) throw jsonShapeError('valuation');
|
||||
const estimateVND = asInt(v['estimateVND']);
|
||||
const lowVND = asInt(v['lowVND']);
|
||||
const highVND = asInt(v['highVND']);
|
||||
const rationale = asString(v['rationale']);
|
||||
const confidenceRaw = v['confidence'];
|
||||
const confidence: AiConfidence =
|
||||
confidenceRaw === 'low' || confidenceRaw === 'medium' || confidenceRaw === 'high'
|
||||
? confidenceRaw
|
||||
: 'medium';
|
||||
if (
|
||||
estimateVND == null ||
|
||||
lowVND == null ||
|
||||
highVND == null ||
|
||||
rationale == null
|
||||
) {
|
||||
throw jsonShapeError('valuation');
|
||||
}
|
||||
return { estimateVND, lowVND, highVND, confidence, rationale };
|
||||
}
|
||||
|
||||
function parseAdvice(v: unknown): ListingAiAdvice {
|
||||
if (!isRecord(v)) throw jsonShapeError('advice');
|
||||
const summary = asString(v['summary']);
|
||||
const pros = asStringArray(v['pros']);
|
||||
const cons = asStringArray(v['cons']);
|
||||
const suitableFor = asStringArray(v['suitableFor']);
|
||||
if (summary == null || !pros || !cons || !suitableFor) {
|
||||
throw jsonShapeError('advice');
|
||||
}
|
||||
return { summary, pros, cons, suitableFor };
|
||||
}
|
||||
|
||||
function stripJsonFence(text: string): string {
|
||||
const fenceMatch = text.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);
|
||||
if (fenceMatch && fenceMatch[1]) return fenceMatch[1].trim();
|
||||
return text;
|
||||
}
|
||||
|
||||
function isRecord(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v != null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function asInt(v: unknown): number | null {
|
||||
if (typeof v === 'number' && Number.isFinite(v)) return Math.round(v);
|
||||
if (typeof v === 'string') {
|
||||
const n = Number(v.replace(/[^\d.-]/g, ''));
|
||||
if (Number.isFinite(n)) return Math.round(n);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function asString(v: unknown): string | null {
|
||||
if (typeof v === 'string' && v.trim().length > 0) return v.trim();
|
||||
return null;
|
||||
}
|
||||
|
||||
function asStringArray(v: unknown): string[] | null {
|
||||
if (!Array.isArray(v)) return null;
|
||||
const out: string[] = [];
|
||||
for (const item of v) {
|
||||
if (typeof item === 'string' && item.trim().length > 0) out.push(item.trim());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function jsonShapeError(field?: string): DomainException {
|
||||
return new DomainException(
|
||||
ErrorCode.AI_PROVIDER_ERROR,
|
||||
field
|
||||
? `AI trả về sai cấu trúc trường '${field}'.`
|
||||
: 'AI trả về sai cấu trúc JSON.',
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export class GetListingAiAdviceQuery {
|
||||
constructor(public readonly listingId: string) {}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ import { type DistrictStatsDto } from '../../application/queries/get-district-st
|
||||
import { GetDistrictStatsQuery } from '../../application/queries/get-district-stats/get-district-stats.query';
|
||||
import { type HeatmapDto } from '../../application/queries/get-heatmap/get-heatmap.handler';
|
||||
import { GetHeatmapQuery } from '../../application/queries/get-heatmap/get-heatmap.query';
|
||||
import {
|
||||
type ListingAiAdviceResponse,
|
||||
} from '../../application/queries/get-listing-ai-advice/get-listing-ai-advice.handler';
|
||||
import { GetListingAiAdviceQuery } from '../../application/queries/get-listing-ai-advice/get-listing-ai-advice.query';
|
||||
import { type MarketReportDto } from '../../application/queries/get-market-report/get-market-report.handler';
|
||||
import { GetMarketReportQuery } from '../../application/queries/get-market-report/get-market-report.query';
|
||||
import { type NearbyPOIsResultDto } from '../../application/queries/get-nearby-pois/get-nearby-pois.handler';
|
||||
@@ -259,4 +263,24 @@ export class AnalyticsController {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ApiBearerAuth('JWT')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('listings/:id/ai-advice')
|
||||
@ApiOperation({
|
||||
summary: 'AI nhận định + định giá cho một tin đăng (Claude)',
|
||||
description:
|
||||
'Gọi Claude API (Anthropic) để trả về JSON gồm ước tính giá và phân tích điểm mạnh/yếu. API key do admin cấu hình trong System Settings.',
|
||||
})
|
||||
@ApiParam({ name: 'id', description: 'Listing ID' })
|
||||
@ApiResponse({ status: 200, description: 'AI advice generated' })
|
||||
@ApiResponse({ status: 401, description: 'Chưa xác thực' })
|
||||
@ApiResponse({ status: 404, description: 'Listing not found' })
|
||||
@ApiResponse({ status: 502, description: 'AI provider error' })
|
||||
@ApiResponse({ status: 503, description: 'AI chưa được cấu hình' })
|
||||
async getListingAiAdvice(
|
||||
@Param('id') id: string,
|
||||
): Promise<ListingAiAdviceResponse> {
|
||||
return this.queryBus.execute(new GetListingAiAdviceQuery(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,4 +62,8 @@ export enum ErrorCode {
|
||||
SUBSCRIPTION_ALREADY_CANCELLED = 'SUBSCRIPTION_ALREADY_CANCELLED',
|
||||
SUBSCRIPTION_INACTIVE = 'SUBSCRIPTION_INACTIVE',
|
||||
QUOTA_EXCEEDED = 'QUOTA_EXCEEDED',
|
||||
|
||||
// AI / Claude integration
|
||||
AI_NOT_CONFIGURED = 'AI_NOT_CONFIGURED',
|
||||
AI_PROVIDER_ERROR = 'AI_PROVIDER_ERROR',
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user