feat(industrial): OSM bulk import + bbox map + admin review (PR 2-4/4)
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 10s
CI / E2E Tests (push) Has been skipped
CI / AI Services (Python) — Smoke (push) Failing after 4s
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 49s
Deploy / Build API Image (push) Failing after 9s
Deploy / Build Web Image (push) Failing after 4s
Deploy / Build AI Services Image (push) Failing after 6s
E2E Tests / Playwright E2E (push) Failing after 8s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 51s
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
Deploy / Deploy to Production (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Failing after 44s
Security Scanning / Trivy Filesystem Scan (push) Has been cancelled
Security Scanning / Security Gate (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has started running

Pulls every `landuse=industrial` feature from OpenStreetMap into the
IndustrialPark catalog and surfaces it on the public KCN map. Admins can
promote raw OSM rows into the public catalog or lock individual fields
to protect them from the monthly reconciliation sync.

PR 2 — Bulk import script (scripts/sync-osm-industrial-parks.ts):
  • Splits Vietnam into 4 chunks (north / northCentral / southCentral /
    south) to stay under Overpass 504 timeouts.
  • Posts to overpass-api.de with form-encoded body, converts via
    osmtogeojson, derives centroid + area via @turf/centroid + @turf/area.
  • Upsert keyed on osmId. Honours `osmLocked` (skip row entirely) and
    `lockedFields[]` (skip individual columns) so admin edits survive.
  • Inserts use $executeRawUnsafe with ST_SetSRID(ST_MakePoint, 4326)
    because Prisma can't manage the Unsupported geometry NOT NULL column.
  • CLI flags: --dry-run, --chunk=NAME.

PR 3 — Bbox spatial API + Mapbox layer:
  • GET /industrial/parks/by-bbox returns a GeoJSON FeatureCollection
    filtered by ST_MakeEnvelope. Sends Point-only at zoom < 12,
    MultiPolygon outline at zoom >= 12 to keep payloads light.
  • Public consumers see MANUAL + OSM_PROMOTED only; admins can pass
    includeOsmRaw=true to also see raw OSM imports.
  • OsmParkBboxMap component drives Mapbox from viewport moveend with
    AbortController-debounced fetches, clusters at zoom < 12, expands
    via getClusterExpansionZoom (callback-style API).
  • /khu-cong-nghiep page now uses the bbox map in map + split views.

PR 4 — Admin review queue + monthly cron:
  • Commands: PromoteOsmPark (OSM → OSM_PROMOTED + isPublic=true,
    optional lockFields), LockOsmPark (toggle row-level skip flag).
  • Query: ListOsmPending lists rows with dataSource='OSM' for review.
  • OsmSyncCronService runs `0 2 1 * *` Asia/Ho_Chi_Minh and spawns
    sync-osm-industrial-parks.ts per chunk. Skipped unless
    OSM_SYNC_ENABLED=true so dev never accidentally hits Overpass.
  • New admin page /admin/industrial/osm-review: searchable table,
    promote dialog with quick-pick lock fields (name, developer,
    description, etc.) plus a free-text fallback, lock/unlock toggle,
    deep-link to openstreetmap.org for verification.

Repository changes:
  • PrismaIndustrialParkRepository now filters public queries to
    `isPublic = true AND dataSource IN (MANUAL, OSM_PROMOTED)` so raw
    OSM rows stay hidden from end users.
  • Added *.rdb to .gitignore (Redis dump local artefact).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ho Ngoc Hai
2026-04-29 19:22:32 +07:00
parent 99f305f6ba
commit b3143991ce
22 changed files with 2179 additions and 8 deletions

View File

@@ -0,0 +1,11 @@
/**
* Toggle the `osmLocked` flag on a park. When locked, the OSM sync cron
* skips this row entirely — useful when admin has curated values that
* conflict with what OSM contributors keep changing.
*/
export class LockOsmParkCommand {
constructor(
public readonly parkId: string,
public readonly locked: boolean,
) {}
}

View File

@@ -0,0 +1,24 @@
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { LoggerService, PrismaService } from '@modules/shared';
import { LockOsmParkCommand } from './lock-osm-park.command';
@CommandHandler(LockOsmParkCommand)
export class LockOsmParkHandler implements ICommandHandler<LockOsmParkCommand> {
constructor(
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async execute(cmd: LockOsmParkCommand): Promise<{ id: string; locked: boolean }> {
const park = await this.prisma.industrialPark.update({
where: { id: cmd.parkId },
data: { osmLocked: cmd.locked },
select: { id: true, osmLocked: true },
});
this.logger.log(
`Park ${park.id} osmLocked → ${park.osmLocked}`,
this.constructor.name,
);
return { id: park.id, locked: park.osmLocked };
}
}

View File

@@ -0,0 +1,15 @@
/**
* Promote a raw OSM-imported industrial park to the public catalogue.
*
* - Flips `dataSource` from `OSM` → `OSM_PROMOTED`
* - Sets `isPublic = true`
* - Optionally locks fields the admin has just curated so the next OSM
* sync doesn't overwrite them.
*/
export class PromoteOsmParkCommand {
constructor(
public readonly parkId: string,
/** Field names to add to `lockedFields`. Empty array = no lock. */
public readonly lockFields: string[] = [],
) {}
}

View File

@@ -0,0 +1,44 @@
import { HttpStatus } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { DomainException, ErrorCode, LoggerService, PrismaService } from '@modules/shared';
import { PromoteOsmParkCommand } from './promote-osm-park.command';
@CommandHandler(PromoteOsmParkCommand)
export class PromoteOsmParkHandler implements ICommandHandler<PromoteOsmParkCommand> {
constructor(
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async execute(cmd: PromoteOsmParkCommand): Promise<{ id: string }> {
const park = await this.prisma.industrialPark.findUnique({
where: { id: cmd.parkId },
select: { id: true, dataSource: true, lockedFields: true },
});
if (!park) {
throw new DomainException(
ErrorCode.NOT_FOUND,
`Không tìm thấy KCN ${cmd.parkId}`,
HttpStatus.NOT_FOUND,
);
}
if (park.dataSource === 'MANUAL') {
// Already in the public catalog as a manual seed; nothing to promote.
return { id: park.id };
}
const newLocked = Array.from(new Set([...park.lockedFields, ...cmd.lockFields]));
await this.prisma.industrialPark.update({
where: { id: cmd.parkId },
data: {
dataSource: 'OSM_PROMOTED',
isPublic: true,
lockedFields: newLocked,
},
});
this.logger.log(
`Promoted park ${cmd.parkId} from OSM → OSM_PROMOTED (locked: ${newLocked.join(', ')})`,
this.constructor.name,
);
return { id: park.id };
}
}

View File

@@ -0,0 +1,140 @@
import { InternalServerErrorException } from '@nestjs/common';
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import type { Feature, FeatureCollection } from 'geojson';
import { LoggerService, PrismaService } from '@modules/shared';
import { GetIndustrialParksByBboxQuery } from './get-industrial-parks-by-bbox.query';
interface BboxRow {
id: string;
slug: string;
name: string;
status: string;
province: string;
data_source: string;
occupancy_rate: number;
total_area_ha: number;
tenant_count: number;
point: string; // GeoJSON Point as text (ST_AsGeoJSON)
polygon: string | null; // GeoJSON MultiPolygon, only when zoom >= 12
}
export interface IndustrialParksGeoCollection extends FeatureCollection {
/** Quick metadata so the client can show "showing N of M parks" */
meta: {
count: number;
truncated: boolean;
zoom: number;
};
}
/** Zoom threshold above which the boundary polygon is included. Below this
* we send only the centroid Point — enough to cluster + render dots. */
const BOUNDARY_ZOOM = 12;
@QueryHandler(GetIndustrialParksByBboxQuery)
export class GetIndustrialParksByBboxHandler
implements IQueryHandler<GetIndustrialParksByBboxQuery, IndustrialParksGeoCollection>
{
constructor(
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async execute(
q: GetIndustrialParksByBboxQuery,
): Promise<IndustrialParksGeoCollection> {
try {
const { south, west, north, east } = q.bbox;
const includeBoundary = q.zoom >= BOUNDARY_ZOOM;
const limit = Math.min(Math.max(q.limit, 1), 5000);
// Filter out raw OSM imports for public consumers; admins pass
// includeOsmRaw=true to see them.
const dataSourceFilter = q.includeOsmRaw
? `'MANUAL', 'OSM', 'OSM_PROMOTED'`
: `'MANUAL', 'OSM_PROMOTED'`;
// Single PostGIS query: bbox filter + optional polygon column.
// && is the bbox-intersect operator and uses the GiST index.
const rows = await this.prisma.$queryRawUnsafe<BboxRow[]>(
`
SELECT
id,
slug,
name,
status::text,
province,
"dataSource"::text AS data_source,
"occupancyRate" AS occupancy_rate,
"totalAreaHa" AS total_area_ha,
"tenantCount" AS tenant_count,
ST_AsGeoJSON(location) AS point,
${includeBoundary ? `ST_AsGeoJSON(boundary)` : `NULL::text`} AS polygon
FROM "IndustrialPark"
WHERE "isPublic" = true
AND "dataSource"::text IN (${dataSourceFilter})
AND location && ST_MakeEnvelope($1, $2, $3, $4, 4326)
ORDER BY "totalAreaHa" DESC NULLS LAST
LIMIT ${limit + 1}
`,
west,
south,
east,
north,
);
const truncated = rows.length > limit;
const trimmed = truncated ? rows.slice(0, limit) : rows;
const features: Feature[] = trimmed.flatMap((r) => {
const properties = {
id: r.id,
slug: r.slug,
name: r.name,
status: r.status,
province: r.province,
dataSource: r.data_source,
occupancyRate: Number(r.occupancy_rate),
totalAreaHa: Number(r.total_area_ha),
tenantCount: Number(r.tenant_count),
};
const out: Feature[] = [];
if (r.point) {
out.push({
type: 'Feature',
id: `${r.id}:point`,
geometry: JSON.parse(r.point),
properties: { ...properties, _kind: 'point' },
});
}
if (r.polygon) {
out.push({
type: 'Feature',
id: `${r.id}:polygon`,
geometry: JSON.parse(r.polygon),
properties: { ...properties, _kind: 'polygon' },
});
}
return out;
});
return {
type: 'FeatureCollection',
features,
meta: {
count: trimmed.length,
truncated,
zoom: q.zoom,
},
};
} catch (err) {
this.logger.error(
`Failed to query parks by bbox: ${err instanceof Error ? err.message : err}`,
err instanceof Error ? err.stack : undefined,
this.constructor.name,
);
throw new InternalServerErrorException(
'Không thể tải KCN theo khu vực. Vui lòng thử lại sau.',
);
}
}
}

View File

@@ -0,0 +1,20 @@
/**
* Spatial bbox query for the public KCN map. Returns a GeoJSON
* FeatureCollection of industrial parks intersecting the given viewport.
*
* - At low zoom we return Point centroids only (cluster on the client).
* - At high zoom (>= 12) we also include the MultiPolygon `boundary`
* so Mapbox can render the park outline.
*
* Visibility is filtered to MANUAL + OSM_PROMOTED rows by default
* (`includeOsmRaw=false`); admin tooling can pass `true` to see the raw
* OSM-imported parks awaiting review.
*/
export class GetIndustrialParksByBboxQuery {
constructor(
public readonly bbox: { south: number; west: number; north: number; east: number },
public readonly zoom: number,
public readonly includeOsmRaw: boolean = false,
public readonly limit: number = 1000,
) {}
}

View File

@@ -0,0 +1,132 @@
import { QueryHandler, type IQueryHandler } from '@nestjs/cqrs';
import { LoggerService, PrismaService } from '@modules/shared';
import { ListOsmPendingQuery } from './list-osm-pending.query';
export interface OsmPendingItem {
id: string;
slug: string;
name: string;
nameEn: string | null;
province: string;
district: string;
region: string;
status: string;
osmId: string;
osmType: string | null;
osmTags: unknown;
totalAreaHa: number;
developer: string;
operator: string | null;
osmLocked: boolean;
lastSyncedAt: Date | null;
latitude: number | null;
longitude: number | null;
}
export interface ListOsmPendingResult {
data: OsmPendingItem[];
total: number;
page: number;
limit: number;
totalPages: number;
}
@QueryHandler(ListOsmPendingQuery)
export class ListOsmPendingHandler implements IQueryHandler<ListOsmPendingQuery> {
constructor(
private readonly prisma: PrismaService,
private readonly logger: LoggerService,
) {}
async execute(q: ListOsmPendingQuery): Promise<ListOsmPendingResult> {
const limit = Math.min(Math.max(q.limit, 1), 200);
const offset = (Math.max(q.page, 1) - 1) * limit;
const conditions: string[] = [`"dataSource"::text = 'OSM'`];
const values: unknown[] = [];
let p = 1;
if (q.province) {
conditions.push(`province = $${p++}`);
values.push(q.province);
}
if (q.query) {
conditions.push(
`(name ILIKE $${p} OR "nameEn" ILIKE $${p} OR developer ILIKE $${p})`,
);
values.push(`%${q.query}%`);
p += 1;
}
const where = conditions.join(' AND ');
const [{ count }] = await this.prisma.$queryRawUnsafe<[{ count: bigint }]>(
`SELECT COUNT(*)::bigint AS count FROM "IndustrialPark" WHERE ${where}`,
...values,
);
const total = Number(count);
const rows = await this.prisma.$queryRawUnsafe<
Array<{
id: string;
slug: string;
name: string;
nameEn: string | null;
province: string;
district: string;
region: string;
status: string;
osmId: bigint;
osmType: string | null;
osmTags: unknown;
totalAreaHa: number;
developer: string;
operator: string | null;
osmLocked: boolean;
lastSyncedAt: Date | null;
lat: number | null;
lng: number | null;
}>
>(
`SELECT
id, slug, name, "nameEn", province, district,
region::text AS region, status::text AS status,
"osmId", "osmType"::text AS "osmType", "osmTags",
"totalAreaHa", developer, operator, "osmLocked", "lastSyncedAt",
ST_Y(location::geometry) AS lat, ST_X(location::geometry) AS lng
FROM "IndustrialPark"
WHERE ${where}
ORDER BY "lastSyncedAt" DESC NULLS LAST, "totalAreaHa" DESC NULLS LAST
LIMIT $${p++} OFFSET $${p}`,
...values,
limit,
offset,
);
return {
data: rows.map((r) => ({
id: r.id,
slug: r.slug,
name: r.name,
nameEn: r.nameEn,
province: r.province,
district: r.district,
region: r.region,
status: r.status,
osmId: r.osmId.toString(),
osmType: r.osmType,
osmTags: r.osmTags,
totalAreaHa: Number(r.totalAreaHa),
developer: r.developer,
operator: r.operator,
osmLocked: r.osmLocked,
lastSyncedAt: r.lastSyncedAt,
latitude: r.lat,
longitude: r.lng,
})),
total,
page: q.page,
limit,
totalPages: Math.ceil(total / limit),
};
}
}

View File

@@ -0,0 +1,12 @@
/**
* Admin OSM review queue — list raw OSM-imported parks that haven't yet
* been promoted to the public catalogue.
*/
export class ListOsmPendingQuery {
constructor(
public readonly page: number = 1,
public readonly limit: number = 50,
public readonly query?: string,
public readonly province?: string,
) {}
}

View File

@@ -5,6 +5,8 @@ import { CreateIndustrialListingHandler } from './application/commands/create-in
import { CreateIndustrialParkHandler } from './application/commands/create-industrial-park/create-industrial-park.handler';
import { DeleteIndustrialListingHandler } from './application/commands/delete-industrial-listing/delete-industrial-listing.handler';
import { DeleteIndustrialParkHandler } from './application/commands/delete-industrial-park/delete-industrial-park.handler';
import { LockOsmParkHandler } from './application/commands/lock-osm-park/lock-osm-park.handler';
import { PromoteOsmParkHandler } from './application/commands/promote-osm-park/promote-osm-park.handler';
import { UpdateIndustrialListingHandler } from './application/commands/update-industrial-listing/update-industrial-listing.handler';
import { UpdateIndustrialParkHandler } from './application/commands/update-industrial-park/update-industrial-park.handler';
import { AnalyzeIndustrialLocationHandler } from './application/queries/analyze-industrial-location/analyze-industrial-location.handler';
@@ -12,12 +14,15 @@ import { CompareIndustrialParksHandler } from './application/queries/compare-ind
import { EstimateIndustrialRentHandler } from './application/queries/estimate-industrial-rent/estimate-industrial-rent.handler';
import { GetIndustrialListingHandler } from './application/queries/get-industrial-listing/get-industrial-listing.handler';
import { GetIndustrialParkHandler } from './application/queries/get-industrial-park/get-industrial-park.handler';
import { GetIndustrialParksByBboxHandler } from './application/queries/get-industrial-parks-by-bbox/get-industrial-parks-by-bbox.handler';
import { IndustrialMarketHandler } from './application/queries/industrial-market/industrial-market.handler';
import { IndustrialParkStatsHandler } from './application/queries/industrial-park-stats/industrial-park-stats.handler';
import { ListIndustrialListingsHandler } from './application/queries/list-industrial-listings/list-industrial-listings.handler';
import { ListIndustrialParksHandler } from './application/queries/list-industrial-parks/list-industrial-parks.handler';
import { ListOsmPendingHandler } from './application/queries/list-osm-pending/list-osm-pending.handler';
import { INDUSTRIAL_LISTING_REPOSITORY } from './domain/repositories/industrial-listing.repository';
import { INDUSTRIAL_PARK_REPOSITORY } from './domain/repositories/industrial-park.repository';
import { OsmSyncCronService } from './infrastructure/cron/osm-sync-cron.service';
import { PrismaIndustrialListingRepository } from './infrastructure/repositories/prisma-industrial-listing.repository';
import { PrismaIndustrialParkRepository } from './infrastructure/repositories/prisma-industrial-park.repository';
import { TypesenseIndustrialService } from './infrastructure/services/typesense-industrial.service';
@@ -31,18 +36,22 @@ const CommandHandlers = [
CreateIndustrialListingHandler,
UpdateIndustrialListingHandler,
DeleteIndustrialListingHandler,
PromoteOsmParkHandler,
LockOsmParkHandler,
];
const QueryHandlers = [
AnalyzeIndustrialLocationHandler,
EstimateIndustrialRentHandler,
GetIndustrialParkHandler,
GetIndustrialParksByBboxHandler,
ListIndustrialParksHandler,
CompareIndustrialParksHandler,
IndustrialParkStatsHandler,
IndustrialMarketHandler,
GetIndustrialListingHandler,
ListIndustrialListingsHandler,
ListOsmPendingHandler,
];
@Module({
@@ -52,6 +61,7 @@ const QueryHandlers = [
{ provide: INDUSTRIAL_PARK_REPOSITORY, useClass: PrismaIndustrialParkRepository },
{ provide: INDUSTRIAL_LISTING_REPOSITORY, useClass: PrismaIndustrialListingRepository },
TypesenseIndustrialService,
OsmSyncCronService,
...CommandHandlers,
...QueryHandlers,
],

View File

@@ -0,0 +1,96 @@
import { spawn } from 'node:child_process';
import * as path from 'node:path';
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { LoggerService } from '@modules/shared';
/**
* Monthly OSM industrial-park reconciliation. Schedules the same script
* we run manually for the bulk import (`scripts/sync-osm-industrial-parks.ts`)
* — this keeps the import logic in one place. The cron is a thin
* orchestrator that:
*
* • Spawns the sync script (one chunk at a time to avoid Overpass 504s)
* • Logs stdout/stderr line-by-line into the application logger
* • Skips entirely if `OSM_SYNC_ENABLED !== 'true'` so dev environments
* don't accidentally call Overpass
*
* Because the script uses upsert keyed on `osmId` and respects the
* `osmLocked` / `lockedFields` columns from PR 1, replays are safe — new
* OSM entities are added, removed entities stay in the DB (admin can
* delete them via the review UI), and admin-edited fields are preserved.
*/
@Injectable()
export class OsmSyncCronService {
constructor(private readonly logger: LoggerService) {}
/** Run on the 1st of each month at 02:00 ICT. */
@Cron('0 2 1 * *', { timeZone: 'Asia/Ho_Chi_Minh' })
async monthlySync(): Promise<void> {
if (process.env['OSM_SYNC_ENABLED'] !== 'true') {
this.logger.log(
'OSM_SYNC_ENABLED != true — skipping monthly sync.',
'OsmSyncCronService',
);
return;
}
this.logger.log('Starting monthly OSM sync…', 'OsmSyncCronService');
const chunks = ['north', 'northCentral', 'southCentral', 'south'];
for (const chunk of chunks) {
try {
await this.runChunk(chunk);
} catch (err) {
this.logger.error(
`OSM sync chunk "${chunk}" failed: ${err instanceof Error ? err.message : err}`,
err instanceof Error ? err.stack : undefined,
'OsmSyncCronService',
);
// Continue with the next chunk — partial success is better than
// failing the whole pass.
}
}
this.logger.log('Monthly OSM sync complete.', 'OsmSyncCronService');
}
private runChunk(chunk: string): Promise<void> {
return new Promise((resolve, reject) => {
const scriptPath = path.resolve(
__dirname,
'../../../../../../..',
'scripts/sync-osm-industrial-parks.ts',
);
const child = spawn(
'pnpm',
['tsx', scriptPath, `--chunk=${chunk}`],
{
cwd: path.resolve(__dirname, '../../../../../../..'),
env: {
...process.env,
NODE_OPTIONS: '-r dotenv/config',
DOTENV_CONFIG_PATH: '.env',
},
},
);
child.stdout?.on('data', (b) => {
for (const line of b.toString().split('\n')) {
if (line.trim()) {
this.logger.log(`[${chunk}] ${line.trim()}`, 'OsmSyncCronService');
}
}
});
child.stderr?.on('data', (b) => {
for (const line of b.toString().split('\n')) {
if (line.trim()) {
this.logger.warn(`[${chunk}] ${line.trim()}`, 'OsmSyncCronService');
}
}
});
child.on('error', reject);
child.on('exit', (code) => {
if (code === 0) resolve();
else reject(new Error(`sync-osm-industrial-parks exited ${code}`));
});
});
}
}

View File

@@ -160,6 +160,11 @@ export class PrismaIndustrialParkRepository implements IIndustrialParkRepository
if (params.ownerId) {
conditions.push(`"ownerId" = $${paramIndex++}`);
values.push(params.ownerId);
} else {
// Public list: hide raw OSM imports until an admin reviews + promotes
// them. MANUAL rows + OSM_PROMOTED rows stay visible.
conditions.push(`"isPublic" = true`);
conditions.push(`"dataSource"::text IN ('MANUAL', 'OSM_PROMOTED')`);
}
if (params.query) {
conditions.push(`(name ILIKE $${paramIndex} OR "nameEn" ILIKE $${paramIndex} OR developer ILIKE $${paramIndex} OR province ILIKE $${paramIndex})`);

View File

@@ -6,18 +6,23 @@ import { CurrentUser, JwtAuthGuard, Roles, RolesGuard, type JwtPayload } from '
import { NotFoundException } from '@modules/shared';
import { CreateIndustrialParkCommand } from '../../application/commands/create-industrial-park/create-industrial-park.command';
import { DeleteIndustrialParkCommand } from '../../application/commands/delete-industrial-park/delete-industrial-park.command';
import { LockOsmParkCommand } from '../../application/commands/lock-osm-park/lock-osm-park.command';
import { PromoteOsmParkCommand } from '../../application/commands/promote-osm-park/promote-osm-park.command';
import { UpdateIndustrialParkCommand } from '../../application/commands/update-industrial-park/update-industrial-park.command';
import { AnalyzeIndustrialLocationQuery } from '../../application/queries/analyze-industrial-location/analyze-industrial-location.query';
import { CompareIndustrialParksQuery } from '../../application/queries/compare-industrial-parks/compare-industrial-parks.query';
import { EstimateIndustrialRentQuery } from '../../application/queries/estimate-industrial-rent/estimate-industrial-rent.query';
import { GetIndustrialParkQuery } from '../../application/queries/get-industrial-park/get-industrial-park.query';
import { GetIndustrialParksByBboxQuery } from '../../application/queries/get-industrial-parks-by-bbox/get-industrial-parks-by-bbox.query';
import { IndustrialMarketQuery } from '../../application/queries/industrial-market/industrial-market.query';
import { IndustrialParkStatsQuery } from '../../application/queries/industrial-park-stats/industrial-park-stats.query';
import { ListIndustrialParksQuery } from '../../application/queries/list-industrial-parks/list-industrial-parks.query';
import { ListOsmPendingQuery } from '../../application/queries/list-osm-pending/list-osm-pending.query';
import { AnalyzeIndustrialLocationDto } from '../dto/analyze-industrial-location.dto';
import { CompareIndustrialParksDto } from '../dto/compare-industrial-parks.dto';
import { CreateIndustrialParkDto } from '../dto/create-industrial-park.dto';
import { EstimateIndustrialRentDto } from '../dto/estimate-industrial-rent.dto';
import { IndustrialParksBboxDto } from '../dto/parks-bbox.dto';
import { SearchIndustrialParksDto } from '../dto/search-industrial-parks.dto';
import { UpdateIndustrialParkDto } from '../dto/update-industrial-park.dto';
@@ -50,6 +55,24 @@ export class IndustrialParksController {
);
}
@ApiOperation({
summary: 'KCN trong viewport bản đồ',
description:
'Trả về GeoJSON FeatureCollection của KCN nằm trong bbox. Zoom < 12 chỉ trả centroid Point, zoom >= 12 kèm MultiPolygon outline.',
})
@ApiResponse({ status: 200, description: 'GeoJSON FeatureCollection + meta' })
@Get('parks/by-bbox')
async parksByBbox(@Query() dto: IndustrialParksBboxDto) {
return this.queryBus.execute(
new GetIndustrialParksByBboxQuery(
{ south: dto.south, west: dto.west, north: dto.north, east: dto.east },
dto.zoom,
dto.includeOsmRaw ?? false,
dto.limit ?? 1000,
),
);
}
// ── Park Operator endpoints ───────────────────────────────────────
@ApiOperation({
@@ -261,4 +284,68 @@ export class IndustrialParksController {
);
return { success: true };
}
// ── OSM review & promote (admin only) ────────────────────────────────
@ApiOperation({
summary: 'Hàng đợi review OSM (admin)',
description:
'Liệt kê các KCN có dataSource=OSM (chưa được duyệt). Admin có thể promote → public hoặc lock để bảo vệ.',
})
@ApiResponse({ status: 200, description: 'Danh sách KCN đang chờ review' })
@ApiBearerAuth('JWT')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@Get('parks/osm/pending')
async listOsmPending(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('q') q?: string,
@Query('province') province?: string,
) {
return this.queryBus.execute(
new ListOsmPendingQuery(
page ? parseInt(page, 10) : 1,
limit ? parseInt(limit, 10) : 50,
q,
province,
),
);
}
@ApiOperation({
summary: 'Promote KCN từ OSM (admin)',
description:
'Chuyển dataSource OSM → OSM_PROMOTED và set isPublic=true. Có thể lock các field admin vừa edit.',
})
@ApiResponse({ status: 200, description: 'Đã promote' })
@ApiResponse({ status: 404, description: 'Không tìm thấy KCN' })
@ApiBearerAuth('JWT')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@Post('parks/:id/osm/promote')
async promoteOsm(
@Param('id') id: string,
@Body() body: { lockFields?: string[] },
) {
return this.commandBus.execute(
new PromoteOsmParkCommand(id, body.lockFields ?? []),
);
}
@ApiOperation({
summary: 'Lock/unlock OSM sync cho KCN (admin)',
description: 'Khi locked=true, sync cron sẽ bỏ qua row này hoàn toàn.',
})
@ApiResponse({ status: 200, description: 'Đã cập nhật trạng thái lock' })
@ApiBearerAuth('JWT')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@Post('parks/:id/osm/lock')
async lockOsm(
@Param('id') id: string,
@Body() body: { locked: boolean },
) {
return this.commandBus.execute(new LockOsmParkCommand(id, body.locked));
}
}

View File

@@ -0,0 +1,63 @@
import { ApiProperty } from '@nestjs/swagger';
import { Transform, Type } from 'class-transformer';
import { IsBoolean, IsInt, IsNumber, Max, Min } from 'class-validator';
/**
* Query params for `GET /industrial/parks/by-bbox`.
*
* The bbox covers the user's current Mapbox viewport. `zoom` controls
* whether the response includes polygon boundaries (zoom >= 12) or just
* Point centroids.
*/
export class IndustrialParksBboxDto {
@ApiProperty({ example: 8.0, description: 'Southern (min) latitude of the viewport' })
@Type(() => Number)
@IsNumber()
@Min(-90)
@Max(90)
south!: number;
@ApiProperty({ example: 102.0, description: 'Western (min) longitude of the viewport' })
@Type(() => Number)
@IsNumber()
@Min(-180)
@Max(180)
west!: number;
@ApiProperty({ example: 23.5, description: 'Northern (max) latitude of the viewport' })
@Type(() => Number)
@IsNumber()
@Min(-90)
@Max(90)
north!: number;
@ApiProperty({ example: 110.0, description: 'Eastern (max) longitude of the viewport' })
@Type(() => Number)
@IsNumber()
@Min(-180)
@Max(180)
east!: number;
@ApiProperty({ example: 8, description: 'Mapbox zoom level (0-22)' })
@Type(() => Number)
@IsInt()
@Min(0)
@Max(22)
zoom!: number;
@ApiProperty({
required: false,
default: false,
description: 'Include raw OSM imports (admin only). Default: false.',
})
@Transform(({ value }) => value === 'true' || value === true)
@IsBoolean()
includeOsmRaw?: boolean = false;
@ApiProperty({ required: false, default: 1000 })
@Type(() => Number)
@IsInt()
@Min(1)
@Max(5000)
limit?: number = 1000;
}

View File

@@ -0,0 +1,500 @@
'use client';
import {
CheckCircle,
Lock,
LockOpen,
RefreshCw,
ChevronLeft,
ChevronRight,
ExternalLink,
X,
Search,
AlertTriangle,
} from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table';
import { Link } from '@/i18n/navigation';
import {
industrialApi,
type OsmPendingItem,
type OsmPendingResult,
} from '@/lib/khu-cong-nghiep-api';
/**
* Admin OSM review queue. Lists parks with `dataSource = 'OSM'` (raw imports
* from the monthly Overpass sync). Admins decide what to do with each row:
*
* - Promote → flips `dataSource` to `OSM_PROMOTED` and `isPublic = true`,
* so the row shows up in the public catalog. Optionally lock specific
* fields so the next sync run won't overwrite them.
* - Lock / Unlock → toggles `osmLocked`. When locked, the row is skipped
* entirely by the sync cron.
*
* Fields that admins commonly want to lock after edits: `name`, `developer`,
* `description`, `targetIndustries`. We surface these as quick-pick checkboxes
* in the promote dialog, plus a free-text fallback for anything else.
*/
const PAGE_SIZE = 50;
const QUICK_LOCK_FIELDS: { key: string; label: string }[] = [
{ key: 'name', label: 'Tên KCN' },
{ key: 'developer', label: 'Chủ đầu tư' },
{ key: 'description', label: 'Mô tả' },
{ key: 'targetIndustries', label: 'Ngành mục tiêu' },
{ key: 'totalAreaHa', label: 'Diện tích' },
{ key: 'status', label: 'Trạng thái' },
];
function formatTags(tags: Record<string, string> | null): string {
if (!tags) return '—';
// Surface the most useful keys first, then anything else, capped to keep
// the cell readable. Tag values are user-generated on OSM so we trim hard.
const priorityKeys = ['name', 'name:vi', 'name:en', 'operator', 'website'];
const ordered = [
...priorityKeys.filter((k) => k in tags),
...Object.keys(tags).filter((k) => !priorityKeys.includes(k)),
];
return ordered
.slice(0, 4)
.map((k) => `${k}=${String(tags[k]).slice(0, 30)}`)
.join(', ');
}
export default function AdminOsmReviewPage() {
const [result, setResult] = useState<OsmPendingResult | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [page, setPage] = useState(1);
// Filters
const [searchInput, setSearchInput] = useState('');
const [search, setSearch] = useState('');
const [provinceFilter, setProvinceFilter] = useState('');
// Promote dialog state
const [promoteTarget, setPromoteTarget] = useState<OsmPendingItem | null>(null);
const [lockFields, setLockFields] = useState<Set<string>>(new Set());
const [extraField, setExtraField] = useState('');
const [actionLoading, setActionLoading] = useState(false);
const fetchQueue = useCallback(async () => {
setLoading(true);
setError(null);
try {
const data = await industrialApi.listOsmPending({
page,
limit: PAGE_SIZE,
q: search || undefined,
province: provinceFilter || undefined,
});
setResult(data);
} catch (e) {
setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi OSM');
} finally {
setLoading(false);
}
}, [page, search, provinceFilter]);
useEffect(() => {
fetchQueue();
}, [fetchQueue]);
const submitSearch = (e: React.FormEvent) => {
e.preventDefault();
setPage(1);
setSearch(searchInput.trim());
};
const handleToggleLock = async (item: OsmPendingItem) => {
setActionError(null);
try {
await industrialApi.lockOsm(item.id, !item.osmLocked);
fetchQueue();
} catch (e) {
setActionError(e instanceof Error ? e.message : 'Không thể cập nhật trạng thái lock');
}
};
const openPromoteDialog = (item: OsmPendingItem) => {
setPromoteTarget(item);
// Default: lock the name (so the next OSM sync doesn't rename it back to
// whatever Overpass has). Admins can uncheck if they want OSM to win.
setLockFields(new Set(['name']));
setExtraField('');
setActionError(null);
};
const closePromoteDialog = () => {
setPromoteTarget(null);
setLockFields(new Set());
setExtraField('');
};
const handlePromote = async () => {
if (!promoteTarget) return;
setActionLoading(true);
setActionError(null);
try {
const fields = Array.from(lockFields);
const extras = extraField
.split(',')
.map((s) => s.trim())
.filter(Boolean);
await industrialApi.promoteOsm(promoteTarget.id, [...fields, ...extras]);
closePromoteDialog();
fetchQueue();
} catch (e) {
setActionError(e instanceof Error ? e.message : 'Promote thất bại. Vui lòng thử lại.');
} finally {
setActionLoading(false);
}
};
const toggleLockField = (key: string) => {
setLockFields((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
return (
<div className="flex flex-col gap-4">
{actionError && (
<div className="flex items-center justify-between rounded-md border border-destructive/50 bg-destructive/10 px-4 py-2 text-sm text-destructive">
<span>{actionError}</span>
<button onClick={() => setActionError(null)} className="ml-2" aria-label="Đóng">
<X className="h-4 w-4" />
</button>
</div>
)}
{/* Header */}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-heading-md font-semibold tracking-tight">Review KCN từ OpenStreetMap</h1>
<p className="text-sm text-foreground-muted">
Xét duyệt các KCN nhập từ OSM (chưa public). Promote public catalog hoặc lock đ giữ nguyên dữ liệu.
</p>
</div>
<Button variant="outline" size="sm" onClick={fetchQueue} disabled={loading}>
<RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
Làm mới
</Button>
</div>
{/* Filters */}
<Card className="shadow-elevation-1">
<CardContent className="p-4">
<form className="flex flex-wrap items-end gap-3" onSubmit={submitSearch}>
<div className="flex-1 min-w-[200px]">
<label className="mb-1 block text-xs text-foreground-dim">Tìm kiếm</label>
<Input
placeholder="Tên KCN, chủ đầu tư..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="h-8 text-sm"
/>
</div>
<div className="w-40">
<label className="mb-1 block text-xs text-foreground-dim">Tỉnh / TP</label>
<Input
placeholder="Bắc Ninh, Đồng Nai..."
value={provinceFilter}
onChange={(e) => {
setPage(1);
setProvinceFilter(e.target.value);
}}
className="h-8 text-sm"
/>
</div>
<Button type="submit" size="sm">
<Search className="mr-1.5 h-3.5 w-3.5" />
Tìm
</Button>
{(search || provinceFilter) && (
<Button
type="button"
size="sm"
variant="outline"
onClick={() => {
setSearchInput('');
setSearch('');
setProvinceFilter('');
setPage(1);
}}
>
<X className="mr-1 h-3 w-3" />
Xóa bộ lọc
</Button>
)}
</form>
</CardContent>
</Card>
{/* Table */}
<Card className="shadow-elevation-1 overflow-hidden">
<CardContent className="p-0">
{loading ? (
<div className="flex h-48 items-center justify-center">
<RefreshCw className="h-5 w-5 animate-spin text-foreground-muted" />
</div>
) : error ? (
<div className="flex h-48 flex-col items-center justify-center gap-2">
<p className="text-sm text-destructive">{error}</p>
<Button variant="outline" size="sm" onClick={fetchQueue}>
Thử lại
</Button>
</div>
) : !result || result.data.length === 0 ? (
<div className="flex h-48 flex-col items-center justify-center gap-2">
<CheckCircle className="h-8 w-8 text-signal-up" />
<p className="text-sm text-foreground-muted">Không KCN nào trong hàng đi</p>
</div>
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader className="sticky top-0 z-sticky-header bg-background-elevated">
<TableRow className="border-b border-border-strong">
<TableHead className="text-heading-xs uppercase text-foreground-muted">
Tên KCN
</TableHead>
<TableHead className="hidden sm:table-cell text-heading-xs uppercase text-foreground-muted">
Tỉnh
</TableHead>
<TableHead className="hidden md:table-cell text-heading-xs uppercase text-foreground-muted text-right">
Diện tích (ha)
</TableHead>
<TableHead className="hidden lg:table-cell text-heading-xs uppercase text-foreground-muted">
OSM
</TableHead>
<TableHead className="hidden xl:table-cell text-heading-xs uppercase text-foreground-muted">
Tags
</TableHead>
<TableHead className="text-heading-xs uppercase text-foreground-muted">
Trạng thái
</TableHead>
<TableHead className="text-right text-heading-xs uppercase text-foreground-muted">
Hành đng
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{result.data.map((item) => (
<TableRow
key={item.id}
className="h-row-compact border-b border-border hover:bg-background-surface transition-colors"
>
<TableCell>
<div className="font-medium max-w-[280px] truncate text-sm">
{item.name}
</div>
{item.nameEn && (
<div className="text-xs text-foreground-dim max-w-[280px] truncate">
{item.nameEn}
</div>
)}
</TableCell>
<TableCell className="hidden sm:table-cell text-sm text-foreground-muted">
{item.province}
</TableCell>
<TableCell className="hidden md:table-cell font-mono text-data-sm tabular-nums text-right">
{item.totalAreaHa
? new Intl.NumberFormat('vi-VN', {
maximumFractionDigits: 1,
}).format(item.totalAreaHa)
: '—'}
</TableCell>
<TableCell className="hidden lg:table-cell font-mono text-data-sm">
<div className="flex items-center gap-1 text-foreground-dim">
{item.osmType?.toLowerCase() ?? '—'}/{item.osmId}
{item.latitude != null && item.longitude != null && (
<a
href={`https://www.openstreetmap.org/${(item.osmType ?? 'way').toLowerCase()}/${item.osmId}`}
target="_blank"
rel="noopener noreferrer"
className="hover:text-foreground"
aria-label="Mở trên openstreetmap.org"
>
<ExternalLink className="h-3 w-3" />
</a>
)}
</div>
</TableCell>
<TableCell className="hidden xl:table-cell text-xs text-foreground-dim max-w-[260px] truncate">
{formatTags(item.osmTags)}
</TableCell>
<TableCell>
{item.osmLocked ? (
<span className="inline-flex items-center gap-1 rounded-pill bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-800 ring-1 ring-inset ring-amber-200">
<Lock className="h-3 w-3" />
Locked
</span>
) : (
<span className="inline-flex items-center gap-1 rounded-pill bg-background-surface px-2 py-0.5 text-xs font-medium text-foreground-muted ring-1 ring-inset ring-border">
Pending
</span>
)}
</TableCell>
<TableCell>
<div className="flex justify-end gap-1">
{item.latitude != null && item.longitude != null && (
<Link
href={`/khu-cong-nghiep/${item.slug}` as never}
target="_blank"
className="rounded p-1 text-foreground-muted hover:bg-background-surface transition-colors"
aria-label={`Xem KCN: ${item.name}`}
title="Mở trang chi tiết"
>
<ExternalLink className="h-4 w-4" />
</Link>
)}
<button
title={item.osmLocked ? 'Bỏ khóa OSM sync' : 'Khóa OSM sync'}
onClick={() => handleToggleLock(item)}
className="rounded p-1 text-foreground-muted hover:bg-background-surface transition-colors"
aria-label={
item.osmLocked ? `Bỏ khóa: ${item.name}` : `Khóa: ${item.name}`
}
>
{item.osmLocked ? (
<LockOpen className="h-4 w-4" />
) : (
<Lock className="h-4 w-4" />
)}
</button>
<button
title="Promote → public"
onClick={() => openPromoteDialog(item)}
className="rounded p-1 text-signal-up hover:bg-signal-up/10 transition-colors"
aria-label={`Promote KCN: ${item.name}`}
>
<CheckCircle className="h-4 w-4" />
</button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{result.totalPages > 1 && (
<div className="flex items-center justify-between border-t border-border px-4 py-2.5">
<span className="font-mono text-data-sm text-foreground-muted">
Trang {result.page}/{result.totalPages} · {result.total} KCN
</span>
<div className="flex gap-1">
<Button
variant="outline"
size="icon"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
disabled={page >= result.totalPages}
onClick={() => setPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
</div>
)}
</CardContent>
</Card>
{/* Promote dialog */}
<Dialog
open={!!promoteTarget}
onOpenChange={(open) => {
if (!open) closePromoteDialog();
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Promote KCN từ OSM</DialogTitle>
<DialogDescription>
<span className="flex items-start gap-2 text-sm">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<span>
KCN <strong>{promoteTarget?.name}</strong> sẽ đưc chuyển sang trạng thái public
(OSM_PROMOTED). Chọn các trường muốn khóa đ bảo vệ chúng khỏi OSM sync sau này.
</span>
</span>
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div>
<p className="mb-2 text-xs font-medium text-foreground-muted">Khóa các trường:</p>
<div className="grid grid-cols-2 gap-2">
{QUICK_LOCK_FIELDS.map(({ key, label }) => (
<label
key={key}
className="flex items-center gap-2 rounded-md border border-border px-2 py-1.5 text-sm cursor-pointer hover:bg-background-surface"
>
<input
type="checkbox"
checked={lockFields.has(key)}
onChange={() => toggleLockField(key)}
className="rounded border-border"
/>
{label}
</label>
))}
</div>
</div>
<div>
<p className="mb-1 text-xs font-medium text-foreground-muted">
Trường tùy chỉnh (cách nhau bởi dấu phẩy)
</p>
<Input
placeholder="vd: occupancyRate, leasableAreaHa"
value={extraField}
onChange={(e) => setExtraField(e.target.value)}
className="h-8 text-sm"
/>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={closePromoteDialog} disabled={actionLoading}>
Hủy
</Button>
<Button onClick={handlePromote} disabled={actionLoading}>
{actionLoading ? 'Đang xử lý...' : 'Promote'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -37,6 +37,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
{ href: '/admin/audit-log' as const, label: 'Nhật ký kiểm toán', icon: ScrollText },
{ href: '/admin/accounts/developers' as const, label: 'Tài khoản CĐT', icon: Building2 },
{ href: '/admin/accounts/park-operators' as const, label: 'Tài khoản KCN', icon: Factory },
{ href: '/admin/industrial/osm-review' as const, label: 'Review OSM (KCN)', icon: Factory },
{ href: '/admin/settings/ai' as const, label: t('adminNav.aiSettings'), icon: Sparkles },
];

View File

@@ -2,9 +2,9 @@
import { Factory, Map as MapIcon, List, Columns } from 'lucide-react';
import * as React from 'react';
import { OsmParkBboxMap } from '@/components/khu-cong-nghiep/osm-park-bbox-map';
import { ParkCard } from '@/components/khu-cong-nghiep/park-card';
import { ParkFilterBar } from '@/components/khu-cong-nghiep/park-filter-bar';
import { ParkMap } from '@/components/khu-cong-nghiep/park-map';
import { Button } from '@/components/ui/button';
import { useIndustrialParksSearch } from '@/lib/hooks/use-khu-cong-nghiep';
import type { SearchIndustrialParksParams } from '@/lib/khu-cong-nghiep-api';
@@ -111,12 +111,12 @@ export default function KhuCongNghiepPage() {
{data.total} khu công nghiệp đưc tìm thấy
</p>
{/* Map-only view */}
{/* Map-only view — bbox-driven, loads ALL parks in viewport */}
{viewMode === 'map' && (
<ParkMap parks={data.data} className="h-[calc(100vh-260px)]" />
<OsmParkBboxMap className="h-[calc(100vh-260px)]" />
)}
{/* Split view: list left, sticky map right (lg+ only) */}
{/* Split view: list left, sticky bbox map right (lg+ only) */}
{viewMode === 'split' && (
<div className="grid gap-4 lg:grid-cols-2">
<div className="overflow-auto" style={{ maxHeight: 'calc(100vh - 220px)' }}>
@@ -127,10 +127,7 @@ export default function KhuCongNghiepPage() {
</div>
</div>
<div className="hidden lg:block">
<ParkMap
parks={data.data}
className="sticky top-20 h-[calc(100vh-220px)]"
/>
<OsmParkBboxMap className="sticky top-20 h-[calc(100vh-220px)]" />
</div>
</div>
)}

View File

@@ -0,0 +1,288 @@
'use client';
/* eslint-disable import-x/no-named-as-default-member */
import mapboxgl from 'mapbox-gl';
import * as React from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';
import { useMapboxStyle } from '@/lib/mapbox-style';
const VN_CENTER: [number, number] = [106.0, 16.0];
const DEFAULT_ZOOM = 5;
const SOURCE_ID = 'osm-parks';
const CLUSTER_LAYER_ID = 'osm-parks-clusters';
const CLUSTER_COUNT_LAYER_ID = 'osm-parks-cluster-count';
const POINT_LAYER_ID = 'osm-parks-points';
const BOUNDARY_FILL_LAYER_ID = 'osm-parks-boundaries-fill';
const BOUNDARY_LINE_LAYER_ID = 'osm-parks-boundaries-line';
interface OsmParkBboxMapProps {
className?: string;
/** Override the bbox API path. Default = `${NEXT_PUBLIC_API_URL}/industrial/parks/by-bbox`. */
apiPath?: string;
/** Show raw OSM-imported parks (admin tools). Default false. */
includeOsmRaw?: boolean;
}
/**
* Viewport-driven KCN map. Pulls parks from the bbox endpoint as the user
* pans/zooms — clusters at low zoom (<12), shows polygon outlines at
* high zoom. Designed for the public catalog where we have ~2000 OSM
* imports + 50 curated rows; loading the entire dataset eagerly would
* be wasteful.
*/
export function OsmParkBboxMap({
className,
apiPath,
includeOsmRaw = false,
}: OsmParkBboxMapProps) {
const containerRef = React.useRef<HTMLDivElement>(null);
const mapRef = React.useRef<mapboxgl.Map | null>(null);
const fetchAbortRef = React.useRef<AbortController | null>(null);
const mapStyle = useMapboxStyle();
const apiBase = React.useMemo(() => {
if (apiPath) return apiPath;
const apiUrl = process.env['NEXT_PUBLIC_API_URL'] ?? 'http://localhost:3201/api/v1';
return `${apiUrl}/industrial/parks/by-bbox`;
}, [apiPath]);
// Capture the current includeOsmRaw value via a ref so the moveend
// handler always sees the latest without re-binding the listener.
const includeOsmRawRef = React.useRef(includeOsmRaw);
React.useEffect(() => {
includeOsmRawRef.current = includeOsmRaw;
}, [includeOsmRaw]);
React.useEffect(() => {
if (!containerRef.current) return;
const token = process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
if (!token) return;
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({
container: containerRef.current,
style: mapStyle,
center: VN_CENTER,
zoom: DEFAULT_ZOOM,
attributionControl: false,
});
map.addControl(new mapboxgl.NavigationControl(), 'top-right');
map.addControl(
new mapboxgl.AttributionControl({ compact: true, customAttribution: 'Data © OSM' }),
'bottom-right',
);
mapRef.current = map;
const fetchParks = async () => {
try {
// Cancel any in-flight request — only the latest viewport matters.
fetchAbortRef.current?.abort();
const controller = new AbortController();
fetchAbortRef.current = controller;
const bounds = map.getBounds();
if (!bounds) return;
const sw = bounds.getSouthWest();
const ne = bounds.getNorthEast();
const zoom = Math.round(map.getZoom());
const params = new URLSearchParams({
south: sw.lat.toString(),
west: sw.lng.toString(),
north: ne.lat.toString(),
east: ne.lng.toString(),
zoom: zoom.toString(),
...(includeOsmRawRef.current ? { includeOsmRaw: 'true' } : {}),
});
const res = await fetch(`${apiBase}?${params}`, {
credentials: 'include',
signal: controller.signal,
});
if (!res.ok) return;
const fc = (await res.json()) as GeoJSON.FeatureCollection;
const src = map.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource | undefined;
if (src) src.setData(fc);
} catch (err) {
if (err instanceof Error && err.name === 'AbortError') return;
console.warn('[osm-park-bbox-map] fetch failed:', err);
}
};
map.on('load', () => {
// Empty source — populated by the first fetchParks() call below.
map.addSource(SOURCE_ID, {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] },
cluster: true,
clusterRadius: 50,
clusterMaxZoom: 11,
clusterProperties: {
// No extra metrics yet — total count is built-in.
},
});
// Cluster bubbles. Mapbox color parser only accepts literal colors,
// so we use hex constants matching our design-system primary token.
map.addLayer({
id: CLUSTER_LAYER_ID,
type: 'circle',
source: SOURCE_ID,
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step',
['get', 'point_count'],
'#22c55e', // primary
10,
'#f59e0b',
50,
'#ef4444',
],
'circle-radius': [
'step',
['get', 'point_count'],
16,
10,
22,
50,
30,
],
'circle-stroke-width': 2,
'circle-stroke-color': '#ffffff',
'circle-opacity': 0.9,
},
});
map.addLayer({
id: CLUSTER_COUNT_LAYER_ID,
type: 'symbol',
source: SOURCE_ID,
filter: ['has', 'point_count'],
layout: {
'text-field': ['get', 'point_count_abbreviated'],
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12,
},
paint: { 'text-color': '#ffffff' },
});
// Individual park markers (centroid Points) when not clustered.
map.addLayer({
id: POINT_LAYER_ID,
type: 'circle',
source: SOURCE_ID,
filter: [
'all',
['!', ['has', 'point_count']],
['==', ['get', '_kind'], 'point'],
],
paint: {
'circle-color': '#22c55e',
'circle-radius': 6,
'circle-stroke-color': '#ffffff',
'circle-stroke-width': 1.5,
},
});
// Polygon outlines — only present when zoom >= 12 (server omits them
// at lower zoom). Fill layer for hit-test, line layer for stroke.
map.addLayer({
id: BOUNDARY_FILL_LAYER_ID,
type: 'fill',
source: SOURCE_ID,
filter: ['==', ['get', '_kind'], 'polygon'],
paint: {
'fill-color': '#22c55e',
'fill-opacity': 0.18,
},
});
map.addLayer({
id: BOUNDARY_LINE_LAYER_ID,
type: 'line',
source: SOURCE_ID,
filter: ['==', ['get', '_kind'], 'polygon'],
paint: {
'line-color': '#22c55e',
'line-width': 2,
'line-opacity': 0.6,
},
});
// Click handler on point/polygon → navigate to detail.
const onClick = (e: mapboxgl.MapLayerMouseEvent) => {
const f = e.features?.[0];
if (!f) return;
const slug = (f.properties as Record<string, unknown> | null)?.['slug'];
if (typeof slug === 'string' && slug.length > 0) {
window.location.href = `/vi/khu-cong-nghiep/${slug}`;
}
};
map.on('click', POINT_LAYER_ID, onClick);
map.on('click', BOUNDARY_FILL_LAYER_ID, onClick);
// Cursor feedback
for (const layerId of [POINT_LAYER_ID, BOUNDARY_FILL_LAYER_ID, CLUSTER_LAYER_ID]) {
map.on('mouseenter', layerId, () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', layerId, () => {
map.getCanvas().style.cursor = '';
});
}
// Cluster click — zoom in
map.on('click', CLUSTER_LAYER_ID, (e) => {
const features = map.queryRenderedFeatures(e.point, { layers: [CLUSTER_LAYER_ID] });
const clusterFeature = features[0];
if (!clusterFeature) return;
const clusterId = clusterFeature.properties?.['cluster_id'];
const src = map.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource;
if (typeof clusterId === 'number') {
src.getClusterExpansionZoom(
clusterId,
(err: Error | null | undefined, zoom: number | null | undefined) => {
if (err || zoom == null) return;
const geom = clusterFeature.geometry;
if (geom.type === 'Point') {
map.easeTo({ center: geom.coordinates as [number, number], zoom });
}
},
);
}
});
// Initial fetch + listen to viewport changes.
void fetchParks();
});
map.on('moveend', () => {
void fetchParks();
});
return () => {
fetchAbortRef.current?.abort();
map.remove();
mapRef.current = null;
};
// We intentionally do NOT depend on includeOsmRaw — the ref-based
// approach avoids tearing down the map on every prop tick.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [apiBase]);
// Sync mapStyle (theme switch) without rebuilding the map.
React.useEffect(() => {
const map = mapRef.current;
if (!map) return;
map.setStyle(mapStyle);
}, [mapStyle]);
const hasToken = typeof process !== 'undefined' && process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
return (
<div className={`relative overflow-hidden rounded-lg border ${className || 'h-[600px]'}`}>
<div ref={containerRef} className="h-full w-full" />
{!hasToken && (
<div className="absolute inset-0 flex items-center justify-center bg-muted text-sm text-muted-foreground">
Thiết lập NEXT_PUBLIC_MAPBOX_TOKEN đ hiển thị bản đ
</div>
)}
</div>
);
}

View File

@@ -233,6 +233,46 @@ export interface SearchIndustrialParksParams {
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;
}
// ─── Labels ─────────────────────────────────────────────
export const PARK_STATUS_LABELS: Record<IndustrialParkStatus, string> = {
@@ -328,4 +368,31 @@ export const industrialApi = {
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 },
),
};