Files
goodgo-platform/apps/web/lib/listings-api.ts
Ho Ngoc Hai ba0bf97426
Some checks failed
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m15s
Deploy / Build API Image (push) Failing after 20s
Deploy / Build AI Services Image (push) Failing after 12s
E2E Tests / Playwright E2E (push) Failing after 16s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 35s
Security Scanning / Trivy Filesystem Scan (push) Failing after 30s
Backup Verification / Backup Restore Verification (push) Failing after 14m37s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m4s
Security Scanning / Trivy Scan — Web Image (push) Failing after 36s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 11m6s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Smoke Test Staging (push) Has been skipped
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
Security Scanning / Security Gate (push) Has been cancelled
feat: dashboard CRUD for Projects + Industrial Parks, listings delete, BĐS homepage card
Backend — DELETE endpoints (hard delete, ADMIN or owner):
- DELETE /projects/:id (Admin) — new DeleteProjectCommand/Handler,
  repository.delete() adapter, module wiring.
- DELETE /industrial/parks/:id (Admin) — same pattern.
- DELETE /listings/:id (JWT + owner-or-Admin check in handler).

Frontend — API clients:
- lib/du-an-api.ts: add create/update/delete + CreateProjectPayload,
  UpdateProjectPayload types.
- lib/khu-cong-nghiep-api.ts: add createPark/updatePark/deletePark +
  Create/Update payload types.
- lib/listings-api.ts: add delete().

Dashboard pages — new:
- /projects (Quản lý dự án): list with filters + edit/delete actions,
  /projects/new form (sectioned Cards, zod-validated), /projects/[id]/edit
  with danger-zone delete.
- /industrial-parks (Quản lý KCN): same triad. Fix occupancy-rate display
  (percentage already 0-100, no need to *100).

Dashboard listings page:
- Add Edit/Delete row actions with confirm + useMutation; error banner
  on mutation failure. Table view gains a "Thao tác" column; list view
  gains a footer action bar below each card.

Dashboard nav:
- Catalog group: /du-an → /projects (Quản lý dự án), /khu-cong-nghiep
  → /industrial-parks (Quản lý KCN). Desktop primaryNav updated too.

Public homepage:
- Add "Bất động sản" as a 5th feature card/tab → /search, using
  listingsApi for the "Featured listings" section.
- Bump grid to lg:grid-cols-5, update features subtitle copy ("Năm/Five
  core services").

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

225 lines
5.7 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';
// ─── 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;
bedrooms: number | null;
bathrooms: number | null;
floors: number | null;
direction: Direction | null;
yearBuilt: number | null;
legalStatus: string | null;
amenities: string[] | null;
projectName: string | null;
latitude: number | null;
longitude: number | 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;
}
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)}`,
),
};