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',
|
||||
}
|
||||
|
||||
@@ -43,15 +43,39 @@ vi.mock('@/components/valuation/ai-estimate-button', () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock AiAdviceCards (pulls in @tanstack/react-query which needs a provider)
|
||||
vi.mock('@/components/listings/ai-advice-cards', () => ({
|
||||
AiAdviceCards: ({ listingId }: { listingId: string }) => (
|
||||
<button data-testid={`ai-advice-${listingId}`}>AI Advice</button>
|
||||
),
|
||||
}));
|
||||
|
||||
// Mock InquiryModal
|
||||
vi.mock('@/components/listings/inquiry-modal', () => ({
|
||||
InquiryModal: () => null,
|
||||
}));
|
||||
|
||||
// Mock analytics API (used for nearby POIs fetch)
|
||||
// Mock analytics API (used for nearby POIs fetch + AI advice)
|
||||
vi.mock('@/lib/analytics-api', () => ({
|
||||
analyticsApi: {
|
||||
getNearbyPOIs: vi.fn().mockResolvedValue({ pois: [], center: { lat: 0, lng: 0 } }),
|
||||
getListingAiAdvice: vi.fn().mockResolvedValue({
|
||||
valuation: {
|
||||
estimateVND: 3_500_000_000,
|
||||
lowVND: 3_000_000_000,
|
||||
highVND: 4_000_000_000,
|
||||
confidence: 'medium',
|
||||
rationale: 'Giá hợp lý cho khu vực',
|
||||
},
|
||||
advice: {
|
||||
summary: 'Tổng quan AI',
|
||||
pros: ['Vị trí đẹp'],
|
||||
cons: ['Giá cao hơn trung bình'],
|
||||
suitableFor: ['Gia đình trẻ'],
|
||||
},
|
||||
model: 'claude-opus-4-5',
|
||||
cacheHit: false,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
257
apps/web/components/listings/ai-advice-cards.tsx
Normal file
257
apps/web/components/listings/ai-advice-cards.tsx
Normal file
@@ -0,0 +1,257 @@
|
||||
'use client';
|
||||
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { AlertTriangle, Check, RefreshCw, Sparkles } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import * as React from 'react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { ApiError } from '@/lib/api-client';
|
||||
import { analyticsApi } from '@/lib/analytics-api';
|
||||
import type { AiConfidence, ListingAiAdvice } from '@/lib/analytics-api';
|
||||
import { useAuthStore } from '@/lib/auth-store';
|
||||
import { formatPrice } from '@/lib/currency';
|
||||
|
||||
interface AiAdviceCardsProps {
|
||||
listingId: string;
|
||||
/** suitableFor labels already shown by the PersonaFitCard — used to de-dupe. */
|
||||
existingPersonas?: string[];
|
||||
}
|
||||
|
||||
const CONFIDENCE_STYLE: Record<AiConfidence, { label: string; variant: 'success' | 'warning' | 'destructive' }> = {
|
||||
high: { label: 'Độ tin cậy cao', variant: 'success' },
|
||||
medium: { label: 'Độ tin cậy trung bình', variant: 'warning' },
|
||||
low: { label: 'Độ tin cậy thấp', variant: 'destructive' },
|
||||
};
|
||||
|
||||
export function AiAdviceCards({ listingId, existingPersonas = [] }: AiAdviceCardsProps) {
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const isAdmin = user?.role === 'ADMIN';
|
||||
|
||||
const mutation = useMutation<ListingAiAdvice, unknown, void>({
|
||||
mutationFn: () => analyticsApi.getListingAiAdvice(listingId),
|
||||
});
|
||||
|
||||
const { data, error, isPending, isSuccess } = mutation;
|
||||
|
||||
// Not loaded yet — show trigger button.
|
||||
if (!isSuccess && !isPending && !error) {
|
||||
return (
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardContent className="py-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="w-full gap-2"
|
||||
onClick={() => mutation.mutate()}
|
||||
>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Xem phân tích AI
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Loading — skeleton.
|
||||
if (isPending) {
|
||||
return (
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Sparkles className="h-4 w-4 animate-pulse text-primary" />
|
||||
AI đang phân tích…
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="h-6 w-3/4 animate-pulse rounded bg-muted" />
|
||||
<div className="h-4 w-1/2 animate-pulse rounded bg-muted" />
|
||||
<div className="h-3 w-full animate-pulse rounded bg-muted" />
|
||||
<div className="h-3 w-5/6 animate-pulse rounded bg-muted" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state.
|
||||
if (error) {
|
||||
const apiErr = error instanceof ApiError ? error : null;
|
||||
const status = apiErr?.status ?? 0;
|
||||
const notConfigured = status === 503;
|
||||
|
||||
if (notConfigured) {
|
||||
return (
|
||||
<Card className="border-amber-200 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/40">
|
||||
<CardContent className="space-y-2 py-4">
|
||||
<p className="flex items-start gap-2 text-sm">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
|
||||
<span>AI chưa được cấu hình. Liên hệ quản trị viên.</span>
|
||||
</p>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
href="/admin/settings/ai"
|
||||
className="inline-flex items-center gap-1 text-xs font-medium text-primary underline"
|
||||
>
|
||||
Cấu hình Claude API →
|
||||
</Link>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="border-destructive/40 bg-destructive/5">
|
||||
<CardContent className="space-y-2 py-4">
|
||||
<p className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>
|
||||
Không lấy được phân tích AI. {apiErr?.message ?? 'Vui lòng thử lại.'}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
onClick={() => mutation.mutate()}
|
||||
>
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
Thử lại
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Success — render the two cards.
|
||||
if (!data) return null;
|
||||
|
||||
const { valuation, advice } = data;
|
||||
const confStyle = CONFIDENCE_STYLE[valuation.confidence] ?? CONFIDENCE_STYLE.medium;
|
||||
const extraPersonas = advice.suitableFor.filter(
|
||||
(p) => !existingPersonas.includes(p),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Card 1 — AI định giá */}
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Sparkles className="h-4 w-4 text-primary" />
|
||||
AI định giá
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="text-center">
|
||||
<p className="text-2xl font-bold text-primary md:text-3xl">
|
||||
{formatPrice(valuation.estimateVND)} VND
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Khoảng {formatPrice(valuation.lowVND)} – {formatPrice(valuation.highVND)} VND
|
||||
</p>
|
||||
<div className="mt-2 flex justify-center">
|
||||
<Badge variant={confStyle.variant}>{confStyle.label}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{valuation.rationale && (
|
||||
<p
|
||||
className="text-xs leading-relaxed text-muted-foreground"
|
||||
style={{
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 3,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{valuation.rationale}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Card 2 — AI nhận định */}
|
||||
<Card className="border-primary/30 bg-primary/5">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Sparkles className="h-4 w-4 text-primary" />
|
||||
AI nhận định
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{advice.summary && (
|
||||
<p className="text-sm leading-relaxed">{advice.summary}</p>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{advice.pros.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Điểm mạnh
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{advice.pros.map((p, i) => (
|
||||
<li key={`pro-${i}`} className="flex items-start gap-1.5 text-sm">
|
||||
<Check className="mt-0.5 h-4 w-4 shrink-0 text-green-600" />
|
||||
<span>{p}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{advice.cons.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Cần cân nhắc
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{advice.cons.map((c, i) => (
|
||||
<li key={`con-${i}`} className="flex items-start gap-1.5 text-sm">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600" />
|
||||
<span>{c}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{extraPersonas.length > 0 && (
|
||||
<div>
|
||||
<p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
Phù hợp với
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{extraPersonas.map((p) => (
|
||||
<div
|
||||
key={`ai-persona-${p}`}
|
||||
className="inline-flex items-center gap-1.5 rounded-full border border-primary/40 bg-primary/10 px-3 py-1 text-xs"
|
||||
>
|
||||
<span className="font-medium">{p}</span>
|
||||
<span className="rounded bg-primary/20 px-1 py-0.5 text-[9px] uppercase tracking-wide text-primary">
|
||||
AI gợi ý
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t pt-2 text-right">
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => mutation.mutate()}
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
Làm mới
|
||||
</button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import dynamic from 'next/dynamic';
|
||||
import Link from 'next/link';
|
||||
import * as React from 'react';
|
||||
import { AddToCompareButton } from '@/components/comparison/add-to-compare-button';
|
||||
import { AiAdviceCards } from '@/components/listings/ai-advice-cards';
|
||||
import { ImageGallery } from '@/components/listings/image-gallery';
|
||||
import { InquiryModal } from '@/components/listings/inquiry-modal';
|
||||
import { PriceHistoryChart } from '@/components/listings/price-history-chart';
|
||||
@@ -436,9 +437,15 @@ export function ListingDetailClient({ listing }: ListingDetailClientProps) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* AI Estimate */}
|
||||
{/* AI Estimate (legacy AVM — preserved) */}
|
||||
<AiEstimateButton listingId={listing.id} />
|
||||
|
||||
{/* AI advisor (Claude — analysis + valuation) */}
|
||||
<AiAdviceCards
|
||||
listingId={listing.id}
|
||||
existingPersonas={property.suitableFor ?? []}
|
||||
/>
|
||||
|
||||
{/* Stats */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
|
||||
@@ -91,6 +91,36 @@ export interface NearbyPOIsResponse {
|
||||
center: { lat: number; lng: number };
|
||||
}
|
||||
|
||||
export type AiConfidence = 'low' | 'medium' | 'high';
|
||||
|
||||
export interface ListingAiValuation {
|
||||
estimateVND: number;
|
||||
lowVND: number;
|
||||
highVND: number;
|
||||
confidence: AiConfidence;
|
||||
rationale: string;
|
||||
}
|
||||
|
||||
export interface ListingAiAdviceBody {
|
||||
summary: string;
|
||||
pros: string[];
|
||||
cons: string[];
|
||||
suitableFor: string[];
|
||||
}
|
||||
|
||||
export interface ListingAiAdvice {
|
||||
valuation: ListingAiValuation;
|
||||
advice: ListingAiAdviceBody;
|
||||
model: string;
|
||||
cacheHit: boolean;
|
||||
cacheUsage?: {
|
||||
input: number;
|
||||
cacheCreation: number;
|
||||
cacheRead: number;
|
||||
output: number;
|
||||
};
|
||||
}
|
||||
|
||||
export const analyticsApi = {
|
||||
getMarketReport: (city: string, period: string, propertyType?: string) => {
|
||||
const params = new URLSearchParams({ city, period });
|
||||
@@ -117,4 +147,7 @@ export const analyticsApi = {
|
||||
apiClient.get<NearbyPOIsResponse>(
|
||||
`/analytics/pois/nearby?lat=${lat}&lng=${lng}&radius=${radius}&limit=${limit}`,
|
||||
),
|
||||
|
||||
getListingAiAdvice: (listingId: string) =>
|
||||
apiClient.post<ListingAiAdvice>(`/analytics/listings/${listingId}/ai-advice`),
|
||||
};
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user