Files
goodgo-platform/apps/web/lib/listings-api.ts
Ho Ngoc Hai 88429a1e51
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 6s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m8s
Deploy / Build API Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 13s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 2s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m9s
Security Scanning / Trivy Scan — Web Image (push) Failing after 37s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 1m2s
Security Scanning / Trivy Filesystem Scan (push) Failing after 51s
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 1s
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Deploy / Build Web Image (push) Failing after 14s
Deploy / Build AI Services Image (push) Failing after 12s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
feat(listings): phase B — rich property fields + admin-authored personas
Schema (prisma/migrations/20260419000000_property_rich_fields)
--------------------------------------------------------------
New Prisma enums:
- Furnishing: FULLY_FURNISHED / BASIC_FURNISHED / UNFURNISHED
- PropertyCondition: NEW / LIKE_NEW / RENOVATED / USED

New Property columns (all optional / default empty, no data loss):
- furnishing, propertyCondition — enums above
- balconyDirection — reuses existing Direction enum
- maintenanceFeeVND BigInt (phí quản lý/tháng)
- parkingSlots Int
- viewType String[] (e.g. ["Sông","Thành phố"])
- petFriendly Boolean (null = unknown)
- suitableFor String[] — admin-chosen persona labels
- whyThisLocation Text — admin narrative

Backend wiring end-to-end
-------------------------
- Create/Update DTOs: @IsEnum/@IsString/@IsNumber/@IsBoolean/@IsArray
  validators; maintenanceFeeVND accepted as a numeric string, cast to
  BigInt on the way to Prisma. whyThisLocation capped at 2000 chars.
- Introduced a small `PropertyExtras` interface on the create/update
  commands so the constructor signature stays readable instead of
  ballooning to 30+ positional args. Handlers forward it to the repo.
- Prisma property repository writes all new columns via raw SQL
  INSERT/UPDATE and reads them on findById.
- ListingDetailData + findByIdWithProperty expose the 9 new fields
  (maintenanceFeeVND serialised as decimal string to avoid BigInt JSON).

Frontend
--------
- listings-api.ts: ListingDetail.property + CreateListingPayload carry
  the 9 new fields; Furnishing + PropertyCondition exported as string
  unions.
- validations/listings.ts: zod schema extended; FURNISHING_OPTIONS,
  PROPERTY_CONDITION_OPTIONS, VIEW_TYPE_OPTIONS label arrays added in
  the existing DIRECTIONS style (Vietnamese labels).
- listing-form-steps.tsx StepDetails: new "Nội thất & điều kiện"
  fieldset with selects/inputs for each field. viewType + suitableFor
  are comma-separated text (same convention as amenities).
  petFriendly is a 3-way select (không chọn / Có / Không).
- new/page.tsx + [id]/edit/page.tsx: submit handlers split CSV inputs
  into arrays, coerce petFriendly, prune empty selects.
- listing-detail-client.tsx Details card: new rows for furnishing,
  propertyCondition, balconyDirection, maintenanceFeeVND (VND
  formatted), parkingSlots, viewType (joined · ), petFriendly
  (Cho phép / Không cho phép / hide when null).
- PersonaFitCard now takes the listing directly and MERGES admin
  suitableFor (rendered first with a "Người đăng chọn" badge in primary
  accent) with the derived personas (deduped by label). When
  whyThisLocation is non-empty it overrides the derived narrative.

Tests
-----
- listing-detail-client.spec.tsx fixture gains all 9 nullable/empty
  defaults.
- listing-form-steps.spec.tsx direction-options duplication fixed.
- pnpm --filter @goodgo/api test --run: 1975/1975 pass.
- pnpm --filter @goodgo/web test --run: 624/624 pass.

Phase B of 4. Next: Phase E AI advisor via Anthropic Opus (URL+key to
be provided by the user).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 15:08:04 +07:00

252 lines
6.6 KiB
TypeScript

import { apiClient } from './api-client';
// ─── Enums ───────────────────────────────────────────────
export type TransactionType = 'SALE' | 'RENT';
export type PropertyType = 'APARTMENT' | 'HOUSE' | 'VILLA' | 'LAND' | 'OFFICE' | 'SHOPHOUSE';
export type ListingStatus =
| 'DRAFT'
| 'PENDING_REVIEW'
| 'ACTIVE'
| 'RESERVED'
| 'SOLD'
| 'RENTED'
| 'EXPIRED'
| 'REJECTED';
export type Direction =
| 'NORTH'
| 'SOUTH'
| 'EAST'
| 'WEST'
| 'NORTHEAST'
| 'NORTHWEST'
| 'SOUTHEAST'
| 'SOUTHWEST';
export type Furnishing = 'FULLY_FURNISHED' | 'BASIC_FURNISHED' | 'UNFURNISHED';
export type PropertyCondition = 'NEW' | 'LIKE_NEW' | 'RENOVATED' | 'USED';
// ─── Interfaces ──────────────────────────────────────────
export interface PropertyMedia {
id: string;
url: string;
type: 'image' | 'video';
order: number;
caption: string | null;
}
export interface ListingDetail {
id: string;
status: ListingStatus;
transactionType: TransactionType;
priceVND: string;
pricePerM2: number | null;
rentPriceMonthly: string | null;
commissionPct: number | null;
viewCount: number;
saveCount: number;
inquiryCount: number;
publishedAt: string | null;
createdAt: string;
property: {
id: string;
propertyType: PropertyType;
title: string;
description: string;
address: string;
ward: string;
district: string;
city: string;
areaM2: number;
usableAreaM2: number | null;
bedrooms: number | null;
bathrooms: number | null;
floors: number | null;
floor: number | null;
totalFloors: number | null;
direction: Direction | null;
yearBuilt: number | null;
legalStatus: string | null;
amenities: string[] | null;
nearbyPOIs: unknown;
metroDistanceM: number | null;
projectName: string | null;
latitude: number | null;
longitude: number | null;
furnishing: Furnishing | null;
propertyCondition: PropertyCondition | null;
balconyDirection: Direction | null;
maintenanceFeeVND: string | null;
parkingSlots: number | null;
viewType: string[];
petFriendly: boolean | null;
suitableFor: string[];
whyThisLocation: string | null;
media: PropertyMedia[];
thumbnail?: string | null;
};
seller: {
id: string;
fullName: string;
phone: string;
};
agent: {
id: string;
userId: string;
agency: string | null;
} | null;
}
export interface PaginatedResult<T> {
data: T[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export interface CreateListingPayload {
transactionType: TransactionType;
priceVND: string;
propertyType: PropertyType;
title: string;
description: string;
address: string;
ward: string;
district: string;
city: string;
latitude: number;
longitude: number;
areaM2: number;
usableAreaM2?: number;
bedrooms?: number;
bathrooms?: number;
floors?: number;
floor?: number;
totalFloors?: number;
direction?: Direction;
yearBuilt?: number;
legalStatus?: string;
amenities?: string[];
projectName?: string;
rentPriceMonthly?: string;
commissionPct?: number;
// Rich property fields (Phase B)
furnishing?: Furnishing;
propertyCondition?: PropertyCondition;
balconyDirection?: Direction;
maintenanceFeeVND?: string;
parkingSlots?: number;
viewType?: string[];
petFriendly?: boolean;
suitableFor?: string[];
whyThisLocation?: string;
}
export interface SearchListingsParams {
status?: ListingStatus;
transactionType?: TransactionType;
propertyType?: PropertyType;
city?: string;
district?: string;
minPrice?: string;
maxPrice?: string;
minArea?: number;
maxArea?: number;
bedrooms?: number;
page?: number;
limit?: number;
}
export interface PriceHistoryItem {
id: string;
oldPrice: string;
newPrice: string;
source: string;
changedAt: string;
}
export interface NeighborhoodScoreResult {
district: string;
city: string;
educationScore: number;
healthcareScore: number;
transportScore: number;
shoppingScore: number;
greeneryScore: number;
safetyScore: number;
totalScore: number;
poiCounts: Record<string, number>;
calculatedAt: string;
}
// ─── API Functions ───────────────────────────────────────
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001/api/v1';
export const listingsApi = {
create: (data: CreateListingPayload) =>
apiClient.post<{ listingId: string; propertyId: string; status: string }>(
'/listings',
data,
),
delete: (id: string) =>
apiClient.delete<{ success: boolean }>(`/listings/${id}`),
getById: (id: string) => apiClient.get<ListingDetail>(`/listings/${id}`),
search: (params: SearchListingsParams = {}) => {
const query = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== '') query.append(key, String(value));
});
const qs = query.toString();
return apiClient.get<PaginatedResult<ListingDetail>>(`/listings${qs ? `?${qs}` : ''}`);
},
updateStatus: (id: string, status: ListingStatus, moderationNotes?: string) =>
apiClient.post<{ status: string }>(`/listings/${id}/status`, {
status,
moderationNotes,
}),
uploadMedia: async (listingId: string, file: File, caption?: string) => {
const formData = new FormData();
formData.append('file', file);
if (caption) formData.append('caption', caption);
const csrfToken = typeof document !== 'undefined'
? document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/)?.[1]
: undefined;
const headers: HeadersInit = {};
if (csrfToken) {
headers['X-CSRF-Token'] = decodeURIComponent(csrfToken);
}
const res = await fetch(`${API_BASE_URL}/listings/${listingId}/media`, {
method: 'POST',
credentials: 'include',
headers,
body: formData,
});
if (!res.ok) {
const error = await res.json().catch(() => ({ message: res.statusText }));
throw new Error(error.message || 'Upload failed');
}
return res.json() as Promise<{ mediaId: string; url: string }>;
},
getPriceHistory: (listingId: string) =>
apiClient.get<PriceHistoryItem[]>(`/listings/${listingId}/price-history`),
getNeighborhoodScore: (district: string, city: string = 'Hồ Chí Minh') =>
apiClient.get<NeighborhoodScoreResult>(
`/analytics/neighborhoods/${encodeURIComponent(district)}/score?city=${encodeURIComponent(city)}`,
),
};