Files
goodgo-platform/apps/web/lib/listings-api.ts
Ho Ngoc Hai 6b783c357d
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 10s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 2s
Security Scanning / Trivy Scan — API Image (push) Failing after 28s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 37s
Deploy / Build API Image (push) Failing after 12s
Deploy / Build Web Image (push) Failing after 10s
Deploy / Build AI Services Image (push) Failing after 9s
E2E Tests / Playwright E2E (push) Failing after 9s
Security Scanning / Trivy Scan — Web Image (push) Failing after 38s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 38s
Security Scanning / Trivy Filesystem Scan (push) Failing after 28s
Deploy / Deploy to Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 1s
feat(listings+projects): wire listing PATCH + project rich content parity
Two CRUD/parity gaps closed:

Listings edit — PATCH was dead-ended at the frontend
----------------------------------------------------
Backend PATCH /listings/:id existed and accepted Phase B fields but
the dashboard edit page was read-only with a disclaimer stub. Now:
- listings-api.ts exports UpdateListingPayload (Partial<CreatePayload>)
  and listingsApi.update(id, data).
- /listings/[id]/edit/page.tsx wires handleSubmit → maps the form to
  UpdateListingPayload (coerces numerics, splits CSV amenities/view/
  suitableFor, normalises petFriendly 3-way select), calls update,
  shows green success banner or red error banner. Removed the
  disclaimer text.
- Form footer now has Huỷ + Lưu thay đổi buttons.

Projects rich content — parity with Phase B listings
---------------------------------------------------
Same "Phù hợp với ai / Vì sao nên chọn dự án này" pattern now on
project detail.

Schema
- ProjectDevelopment: suitableFor String[] @default([]) +
  whyThisLocation String? @db.Text. Migration 20260419100000 applied
  via db:push.

Backend
- CreateProjectDto / UpdateProjectDto pick up optional suitableFor +
  whyThisLocation (MaxLength 2000).
- CreateProjectCommand / UpdateProjectCommand append the two trailing
  args; handlers forward them.
- ProjectDevelopment entity carries the props + updateDetails
  branches.
- ProjectListItem (inherited by ProjectDetailData) exposes both.
- Prisma repo writes them on raw INSERT/UPDATE and reads them in
  toDomain + toListItem. Controller passes dto → commands.

Frontend
- du-an-api.ts: ProjectDetail / CreateProjectPayload /
  UpdateProjectPayload gain suitableFor + whyThisLocation. duAnApi
  exports create / update / delete (already landed earlier, now in
  sync with the new fields).
- du-an-server.ts normalizer pulls the two fields safely (filter
  strings, default empty array / null).
- Dashboard /projects/new + /projects/[id]/edit: new "Phù hợp & lý
  do khu vực" form section (CSV split + 2000-char textarea). Submit
  handlers forward to create/update payloads.
- Public /du-an/[slug] detail (du-an-detail-client.tsx): two new
  cards just below the quick-stats grid —
  * ProjectPersonaFitCard: chips for each suitableFor label with a
    "Chủ đầu tư chọn" badge (bg-primary/10), plus a disabled
    <Button><Sparkles /> AI nhận định dự án (sắp ra mắt)</Button>
    teaser with a TODO pointing to a future project-AI advisor
    endpoint.
  * ProjectWhyLocationCard: renders whyThisLocation in
    whitespace-pre-wrap; skipped when the field is empty.

Verification
- API typecheck clean; 1975/1975 tests pass.
- Web typecheck clean in touched files; 624/624 tests pass.
- Lucide-only icons; Vietnamese labels; no new npm packages;
  runtime imports preserved for NestJS-DI classes.

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

260 lines
6.9 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 interface UpdateListingPayload extends Partial<CreateListingPayload> {}
export const listingsApi = {
create: (data: CreateListingPayload) =>
apiClient.post<{ listingId: string; propertyId: string; status: string }>(
'/listings',
data,
),
update: (id: string, data: UpdateListingPayload) =>
apiClient.patch<{ listingId: string; propertyId: string; status: string }>(
`/listings/${id}`,
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)}`,
),
};