Files
goodgo-platform/apps/web/lib/khu-cong-nghiep-api.ts
Ho Ngoc Hai c15bdcc6bf
Some checks failed
CI / E2E Tests (push) Has been skipped
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 9s
CI / AI Services (Python) — Smoke (push) Failing after 7s
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m7s
Deploy / Build API Image (push) Failing after 16s
Deploy / Build Web Image (push) Failing after 6s
Deploy / Build AI Services Image (push) Failing after 7s
E2E Tests / Playwright E2E (push) Failing after 15s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 5s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m13s
Security Scanning / Trivy Scan — Web Image (push) Failing after 49s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 40s
Security Scanning / Trivy Filesystem Scan (push) Failing after 40s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (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
fix(industrial): improve OSM review UX + public map visibility
Four UX issues surfaced when reviewing the new OSM-sync pipeline against
the actual 2,193 imports — fixed in this commit:

1. Admin queue surfaced noise first.
   `ListOsmPendingHandler` now sorts by `totalAreaHa DESC` (real KCN
   first, single-factory `landuse=industrial` polygons last) and accepts
   `minAreaHa` (default 50 ha) plus a `region` filter. The admin page
   exposes both as dropdowns — "Tất cả / ≥ 5 / ≥ 50 / ≥ 200 / ≥ 500 ha".
   Top-of-queue is now Bàu Bàng (2,597 ha) and Nhơn Trạch (2,535 ha).

2. Promote dialog said "KCN KCN Đại An" — duplicate prefix.
   Reworded to "Sắp promote: <name>" so the row name stands on its own.

3. Province was "Chưa xác định" on 2,107 of 2,193 OSM rows.
   The OSM tags lacked any addr:* hint, so the importer never had
   anything to write. Added `scripts/data/vn-province-centroids.ts` (63
   provinces with capital-city coords) and a `nearestProvince(lat, lng)`
   fallback in `parseFeature()`. Shipped a one-shot backfill script
   `scripts/backfill-osm-provinces.ts` and ran it — every existing OSM
   row now has a province (Hồ Chí Minh: 408, Lạng Sơn: 232,
   Quảng Ninh: 220, Hà Nội: 172, Hải Phòng: 105, …). Admin can correct
   on promote if the nearest-centroid heuristic picked the wrong
   neighbour for a long-thin province.

4. Public map looked empty — only 20 curated parks visible.
   Added an opt-in toggle "Hiển thị KCN OSM" with a small legend above
   the map. When on, the bbox endpoint returns OSM raw rows too; markers
   render in amber (vs. green for curated) at slightly smaller radius
   and lower opacity, so the visual hierarchy stays clear. Refetch is
   wired through a ref so the toggle takes effect without remounting
   the map.

Verified in browser preview: zoom-out shows clusters of 320 / 71 / etc.
across the country with the toggle on, and just three small clusters
(20 curated parks) when off.

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

402 lines
12 KiB
TypeScript

import { apiClient } from './api-client';
// ─── Types ──────────────────────────────────────────────
export type IndustrialParkStatus =
| 'PLANNING'
| 'UNDER_CONSTRUCTION'
| 'OPERATIONAL'
| 'FULL';
export type VietnamRegion = 'NORTH' | 'CENTRAL' | 'SOUTH';
export interface IndustrialParkListItem {
id: string;
name: string;
nameEn: string | null;
slug: string;
developer: string;
status: IndustrialParkStatus;
province: string;
region: VietnamRegion;
totalAreaHa: number;
occupancyRate: number;
remainingAreaHa: number;
tenantCount: number;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
landRentUsdM2Year: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
rbfRentUsdM2Month: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
rbwRentUsdM2Month: string | null;
targetIndustries: string[];
latitude: number;
longitude: number;
}
export interface IndustrialParkDetail {
id: string;
name: string;
nameEn: string | null;
slug: string;
developer: string;
operator: string | null;
status: IndustrialParkStatus;
latitude: number;
longitude: number;
address: string;
district: string;
province: string;
region: VietnamRegion;
totalAreaHa: number;
leasableAreaHa: number;
occupancyRate: number;
remainingAreaHa: number;
tenantCount: number;
establishedYear: number | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
landRentUsdM2Year: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
rbfRentUsdM2Month: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
rbwRentUsdM2Month: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
managementFeeUsd: string | null;
infrastructure: Record<string, string> | null;
connectivity: Record<string, { name: string; distanceKm: number }> | null;
incentives: Record<string, unknown> | null;
targetIndustries: string[];
existingTenants: { name: string; country: string; industry: string }[] | null;
certifications: string[] | null;
media: { url: string; type: string; caption?: string }[] | null;
documents: { url: string; name: string }[] | null;
description: string | null;
descriptionEn: string | null;
isVerified: boolean;
listingCount: number;
createdAt: string;
updatedAt: string;
}
export interface IndustrialParkStats {
totalParks: number;
totalAreaHa: number;
avgOccupancyRate: number;
totalTenants: number;
byRegion: { region: string; count: number; avgOccupancy: number }[];
byStatus: { status: string; count: number }[];
topProvinces: { province: string; count: number; avgRent: number | null }[];
}
export interface IndustrialMarketData {
totalParks: number;
avgOccupancyRate: number;
/** AVG(numeric) serialised as string by PostgreSQL. */
avgLandRentUsdM2: string | null;
/** AVG(numeric) serialised as string by PostgreSQL. */
avgRbfRentUsdM2: string | null;
rentByRegion: { region: string; avgLandRent: string | null; avgRbfRent: string | null; parkCount: number }[];
rentByProvince: { province: string; avgLandRent: string | null; avgRbfRent: string | null; parkCount: number }[];
}
// ─── Industrial Listing Types ───────────────────────────
export type IndustrialPropertyType =
| 'INDUSTRIAL_LAND'
| 'READY_BUILT_FACTORY'
| 'READY_BUILT_WAREHOUSE'
| 'LOGISTICS_CENTER'
| 'OFFICE_IN_PARK'
| 'DATA_CENTER';
export type IndustrialLeaseType =
| 'LAND_LEASE'
| 'FACTORY_LEASE'
| 'WAREHOUSE_LEASE'
| 'SUBLEASE';
export type IndustrialListingStatus =
| 'DRAFT'
| 'ACTIVE'
| 'RESERVED'
| 'LEASED'
| 'EXPIRED';
export interface IndustrialListingItem {
id: string;
parkId: string;
parkName: string;
parkSlug: string;
propertyType: IndustrialPropertyType;
leaseType: IndustrialLeaseType;
status: IndustrialListingStatus;
title: string;
description: string | null;
areaM2: number;
ceilingHeightM: number | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
priceUsdM2: string | null;
pricingUnit: string | null;
/** Decimal(18,4) serialised as string. Use parseFloat() for arithmetic. */
totalLeasePrice: string | null;
minLeaseYears: number | null;
maxLeaseYears: number | null;
availableFrom: string | null;
media: { url: string; type: string; caption?: string }[] | null;
viewCount: number;
publishedAt: string | null;
}
export interface SearchIndustrialListingsParams {
parkId?: string;
propertyType?: IndustrialPropertyType;
leaseType?: IndustrialLeaseType;
minAreaM2?: number;
maxAreaM2?: number;
minPriceUsdM2?: number;
maxPriceUsdM2?: number;
q?: string;
page?: number;
limit?: number;
}
export interface CreateIndustrialParkPayload {
name: string;
nameEn?: string;
slug: string;
developer: string;
operator?: string;
status: IndustrialParkStatus;
latitude: number;
longitude: number;
address: string;
district: string;
province: string;
region: VietnamRegion;
totalAreaHa: number;
leasableAreaHa: number;
occupancyRate: number;
remainingAreaHa: number;
tenantCount?: number;
establishedYear?: number;
landRentUsdM2Year?: number;
rbfRentUsdM2Month?: number;
rbwRentUsdM2Month?: number;
managementFeeUsd?: number;
infrastructure?: Record<string, unknown>;
connectivity?: Record<string, unknown>;
incentives?: Record<string, unknown>;
targetIndustries: string[];
description?: string;
descriptionEn?: string;
}
export interface UpdateIndustrialParkPayload {
name?: string;
nameEn?: string;
developer?: string;
operator?: string;
status?: IndustrialParkStatus;
occupancyRate?: number;
remainingAreaHa?: number;
tenantCount?: number;
landRentUsdM2Year?: number;
rbfRentUsdM2Month?: number;
rbwRentUsdM2Month?: number;
managementFeeUsd?: number;
infrastructure?: Record<string, unknown>;
connectivity?: Record<string, unknown>;
incentives?: Record<string, unknown>;
targetIndustries?: string[];
description?: string;
descriptionEn?: string;
isVerified?: boolean;
}
export interface PaginatedResult<T> {
data: T[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export interface SearchIndustrialParksParams {
q?: string;
province?: string;
region?: VietnamRegion;
status?: IndustrialParkStatus;
minAreaHa?: number;
maxRentUsdM2?: number;
targetIndustry?: string;
page?: number;
limit?: number;
}
// ─── OSM Admin Types ────────────────────────────────────
export interface OsmPendingItem {
id: string;
slug: string;
name: string;
nameEn: string | null;
province: string;
district: string;
region: string;
status: string;
/** OSM relation/way/node id, serialised as string (BigInt). */
osmId: string;
osmType: 'NODE' | 'WAY' | 'RELATION' | null;
/** Raw OSM tags object — varies wildly per row. */
osmTags: Record<string, string> | null;
totalAreaHa: number;
developer: string;
operator: string | null;
osmLocked: boolean;
lastSyncedAt: string | null;
latitude: number | null;
longitude: number | null;
}
export interface OsmPendingResult {
data: OsmPendingItem[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export interface ListOsmPendingParams {
page?: number;
limit?: number;
q?: string;
province?: string;
/** Diện tích tối thiểu (ha). Default backend = 50 để lọc bớt nhà máy lẻ. */
minAreaHa?: number;
region?: VietnamRegion;
}
// ─── Labels ─────────────────────────────────────────────
export const PARK_STATUS_LABELS: Record<IndustrialParkStatus, string> = {
PLANNING: 'Quy hoạch',
UNDER_CONSTRUCTION: 'Đang xây dựng',
OPERATIONAL: 'Đang hoạt động',
FULL: 'Đã lấp đầy',
};
export const PARK_STATUS_COLORS: Record<IndustrialParkStatus, string> = {
PLANNING: 'bg-blue-100 text-blue-800',
UNDER_CONSTRUCTION: 'bg-amber-100 text-amber-800',
OPERATIONAL: 'bg-green-100 text-green-800',
FULL: 'bg-red-100 text-red-800',
};
export const REGION_LABELS: Record<VietnamRegion, string> = {
NORTH: 'Miền Bắc',
CENTRAL: 'Miền Trung',
SOUTH: 'Miền Nam',
};
export const PROPERTY_TYPE_LABELS: Record<IndustrialPropertyType, string> = {
INDUSTRIAL_LAND: 'Đất công nghiệp',
READY_BUILT_FACTORY: 'Nhà xưởng xây sẵn',
READY_BUILT_WAREHOUSE: 'Kho bãi xây sẵn',
LOGISTICS_CENTER: 'Trung tâm logistics',
OFFICE_IN_PARK: 'Văn phòng trong KCN',
DATA_CENTER: 'Trung tâm dữ liệu',
};
export const LEASE_TYPE_LABELS: Record<IndustrialLeaseType, string> = {
LAND_LEASE: 'Thuê đất',
FACTORY_LEASE: 'Thuê nhà xưởng',
WAREHOUSE_LEASE: 'Thuê kho bãi',
SUBLEASE: 'Cho thuê lại',
};
// ─── API Functions ──────────────────────────────────────
export const industrialApi = {
search: (params: SearchIndustrialParksParams = {}) => {
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<IndustrialParkListItem>>(
`/industrial/parks${qs ? `?${qs}` : ''}`,
);
},
/** PARK_OPERATOR / ADMIN only — returns KCN owned by the current user. */
searchMine: (params: SearchIndustrialParksParams = {}) => {
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<IndustrialParkListItem>>(
`/industrial/parks/mine/list${qs ? `?${qs}` : ''}`,
);
},
getBySlug: (slug: string) =>
apiClient.get<IndustrialParkDetail>(`/industrial/parks/${slug}`),
compare: (ids: string[]) =>
apiClient.post<IndustrialParkDetail[]>('/industrial/parks/compare', { ids }),
getStats: () =>
apiClient.get<IndustrialParkStats>('/industrial/parks/stats'),
getMarket: () =>
apiClient.get<IndustrialMarketData>('/industrial/market'),
searchListings: (params: SearchIndustrialListingsParams = {}) => {
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<IndustrialListingItem>>(
`/industrial/listings${qs ? `?${qs}` : ''}`,
);
},
createPark: (payload: CreateIndustrialParkPayload) =>
apiClient.post<IndustrialParkDetail>('/industrial/parks', payload),
updatePark: (id: string, payload: UpdateIndustrialParkPayload) =>
apiClient.patch<IndustrialParkDetail>(`/industrial/parks/${id}`, payload),
deletePark: (id: string) =>
apiClient.delete<{ success: boolean }>(`/industrial/parks/${id}`),
// ─── OSM admin endpoints (ADMIN role only) ───────────
listOsmPending: (params: ListOsmPendingParams = {}) => {
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<OsmPendingResult>(
`/industrial/parks/osm/pending${qs ? `?${qs}` : ''}`,
);
},
/** Promote OSM row → public OSM_PROMOTED. Optionally lock fields the admin
* just edited so the next sync run leaves them alone. */
promoteOsm: (id: string, lockFields: string[] = []) =>
apiClient.post<{ id: string }>(`/industrial/parks/${id}/osm/promote`, {
lockFields,
}),
/** Toggle the row-level OSM lock. When `true`, sync skips this row entirely. */
lockOsm: (id: string, locked: boolean) =>
apiClient.post<{ id: string; locked: boolean }>(
`/industrial/parks/${id}/osm/lock`,
{ locked },
),
};