Files
goodgo-platform/apps/web/lib/du-an-api.ts
Ho Ngoc Hai 33a5ff407b
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 16s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 50s
Deploy / Build API Image (push) Failing after 25s
Deploy / Build Web Image (push) Failing after 11s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 12s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 4s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m16s
Security Scanning / Trivy Scan — Web Image (push) Failing after 1m2s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 50s
Security Scanning / Trivy Filesystem Scan (push) Failing after 38s
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 0s
Deploy / Rollback Production (push) Has been skipped
Deploy / Rollback Staging (push) Failing after 10m50s
feat(auth): add DEVELOPER + PARK_OPERATOR roles with owner scoping (B2B accounts)
Two new B2B roles for CĐT (project developers) and KCN operators, provisioned by
admin. Each account owns a subset of ProjectDevelopment / IndustrialPark records
and can CRUD them from the dashboard; admin retains full access.

Phase 1 — Schema
- Extend UserRole enum with DEVELOPER + PARK_OPERATOR (before ADMIN)
- ProjectDevelopment.ownerId FK (User, ON DELETE SET NULL) + index
- IndustrialPark.ownerId FK + index
- Migration 20260420030000

Phase 2a — Backend authorization
- CreateProjectCommand + CreateIndustrialParkCommand accept ownerId; controllers
  auto-set it to the caller's user id when role=DEVELOPER / PARK_OPERATOR
- Update + Delete commands gain (requesterUserId, requesterRole) and enforce
  ADMIN-or-owner via ForbiddenException; reassigning ownerId is admin-only
- Search params gain optional ownerId filter wired through Prisma repos
- New endpoints: GET /projects/mine/list, GET /industrial/parks/mine/list
- user-rate-limit guard: add DEVELOPER + PARK_OPERATOR entries (300/window)

Phase 2b — Admin provision
- ProvisionDeveloperCommand/Handler: create user (role=DEVELOPER), pre-validate
  target projects have no existing owner, batch-assign ownerId
- ProvisionParkOperatorCommand/Handler: same for PARK_OPERATOR + IndustrialPark
- POST /admin/accounts/developers, POST /admin/accounts/park-operators (admin-only)
- DTOs with phone/password/fullName/email + optional {project,park}Ids[]

Phase 2c — Project stats for developer dashboard
- GetProjectStatsQuery + handler: aggregates linkedListingCount, activeListingCount,
  totalInquiries, unreadInquiries, savedByUsers via Property → Listing → Inquiry chain
- GET /projects/:id/stats — admin sees all, DEVELOPER only their own (403 otherwise)

Phase 3 — Frontend
- Dashboard layout role-aware: DEVELOPER sees "Dự án của tôi" + CRM + Profile (hides
  listings/analytics/subscription); PARK_OPERATOR sees "KCN của tôi" equivalent
- /projects dashboard page switches to duAnApi.searchMine() when role=DEVELOPER
- /industrial-parks page switches to industrialApi.searchMine() when role=PARK_OPERATOR
- Admin nav gains "Tài khoản CĐT" + "Tài khoản KCN" entries
- New pages /admin/accounts/developers + /admin/accounts/park-operators with
  checkbox-based multi-select for linking entities
- adminApi.provisionDeveloper + provisionParkOperator + types
- duAnApi.searchMine + getStats; industrialApi.searchMine
- Login demo accounts list includes CĐT Vingroup + KCN VSIP

Phase 4 — Seed (prisma/seed-b2b-accounts.ts)
- DEVELOPER "CĐT Vingroup" (+84912000001) owns 4 projects
- DEVELOPER "CĐT Masterise Homes" (+84912000003) owns 2 projects
- PARK_OPERATOR "Vận hành KCN VSIP" (+84912000002) owns 2 seeded KCN
- Password Velik@2026 for all

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

293 lines
7.8 KiB
TypeScript

import { apiClient } from './api-client';
import type { ListingDetail } from './listings-api';
// ─── Enums ───────────────────────────────────────────────
// Must match the Prisma enum `ProjectDevelopmentStatus` in
// `prisma/schema.prisma` — the backend rejects any other value.
export type ProjectStatus =
| 'PLANNING'
| 'UNDER_CONSTRUCTION'
| 'HANDOVER'
| 'COMPLETED';
export type ProjectPropertyType =
| 'APARTMENT'
| 'VILLA'
| 'TOWNHOUSE'
| 'SHOPHOUSE'
| 'LAND'
| 'MIXED';
// ─── Interfaces ──────────────────────────────────────────
export interface ProjectMedia {
id: string;
url: string;
type: 'image' | 'video' | 'master_plan' | 'document';
order: number;
caption: string | null;
}
export interface ProjectBlock {
id: string;
name: string;
totalUnits: number;
availableUnits: number;
floors: number;
}
export interface ProjectAmenity {
id: string;
name: string;
icon: string;
category: string;
}
export interface ProjectPriceRange {
propertyType: ProjectPropertyType;
minPrice: string;
maxPrice: string;
pricePerM2Min: number | null;
pricePerM2Max: number | null;
}
export interface ProjectPriceHistory {
period: string;
avgPricePerM2: number;
transactionCount: number;
}
export interface NeighborhoodScore {
category: string;
score: number;
label: string;
}
export interface ProjectPOI {
id: string;
name: string;
type: string;
distance: number;
latitude: number;
longitude: number;
}
export interface ProjectDeveloper {
id: string;
name: string;
logoUrl: string | null;
totalProjects: number;
}
export interface ProjectDocument {
id: string;
name: string;
url: string;
type: string;
sizeBytes: number;
}
export interface ProjectSummary {
id: string;
slug: string;
name: string;
status: ProjectStatus;
developer: ProjectDeveloper;
city: string;
district: string;
address: string;
latitude: number | null;
longitude: number | null;
thumbnailUrl: string | null;
totalArea: number;
totalUnits: number;
propertyTypes: ProjectPropertyType[];
minPrice: string | null;
maxPrice: string | null;
completionDate: string | null;
createdAt: string;
}
export interface ProjectDetail extends ProjectSummary {
description: string;
media: ProjectMedia[];
blocks: ProjectBlock[];
amenities: ProjectAmenity[];
priceRanges: ProjectPriceRange[];
priceHistory: ProjectPriceHistory[];
neighborhoodScores: NeighborhoodScore[];
pois: ProjectPOI[];
documents: ProjectDocument[];
linkedListingCount: number;
suitableFor?: string[];
whyThisLocation?: string | null;
}
export interface PaginatedResult<T> {
data: T[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export interface CreateProjectPayload {
name: string;
slug: string;
developer: string;
developerLogo?: string;
totalUnits: number;
status: string;
latitude: number;
longitude: number;
address: string;
ward: string;
district: string;
city: string;
description?: string;
amenities?: Record<string, unknown>;
masterPlanUrl?: string;
minPrice?: string;
maxPrice?: string;
pricePerM2Range?: Record<string, unknown>;
totalArea?: number;
buildingCount?: number;
floorCount?: number;
unitTypes?: Record<string, unknown>;
tags?: string[];
suitableFor?: string[];
whyThisLocation?: string;
startDate?: string;
completionDate?: string;
}
export interface UpdateProjectPayload {
name?: string;
developer?: string;
developerLogo?: string | null;
totalUnits?: number;
completedUnits?: number;
status?: string;
description?: string | null;
amenities?: Record<string, unknown> | null;
masterPlanUrl?: string | null;
minPrice?: string | null;
maxPrice?: string | null;
pricePerM2Range?: Record<string, unknown> | null;
totalArea?: number | null;
buildingCount?: number | null;
floorCount?: number | null;
unitTypes?: Record<string, unknown> | null;
media?: Record<string, unknown>[] | null;
documents?: Record<string, unknown>[] | null;
tags?: string[];
suitableFor?: string[];
whyThisLocation?: string | null;
isVerified?: boolean;
startDate?: string | null;
completionDate?: string | null;
}
export interface SearchProjectsParams {
city?: string;
district?: string;
developerId?: string;
status?: ProjectStatus;
propertyType?: ProjectPropertyType;
minPrice?: string;
maxPrice?: string;
sort?: string;
page?: number;
limit?: number;
q?: string;
}
// ─── Status Labels ───────────────────────────────────────
export const PROJECT_STATUS_LABELS: Record<ProjectStatus, string> = {
PLANNING: 'Đang quy hoạch',
UNDER_CONSTRUCTION: 'Đang xây dựng',
HANDOVER: 'Đang bàn giao',
COMPLETED: 'Đã hoàn thành',
};
export const PROJECT_STATUS_COLORS: Record<ProjectStatus, string> = {
PLANNING: 'bg-blue-100 text-blue-800',
UNDER_CONSTRUCTION: 'bg-amber-100 text-amber-800',
HANDOVER: 'bg-purple-100 text-purple-800',
COMPLETED: 'bg-gray-100 text-gray-800',
};
export const PROJECT_PROPERTY_TYPE_LABELS: Record<ProjectPropertyType, string> = {
APARTMENT: 'Căn hộ',
VILLA: 'Biệt thự',
TOWNHOUSE: 'Nhà phố',
SHOPHOUSE: 'Shophouse',
LAND: 'Đất nền',
MIXED: 'Tổng hợp',
};
// ─── API Functions ───────────────────────────────────────
export const duAnApi = {
search: (params: SearchProjectsParams = {}) => {
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<ProjectSummary>>(
`/projects${qs ? `?${qs}` : ''}`,
);
},
/** DEVELOPER / ADMIN only — returns projects owned by the current user. */
searchMine: (params: SearchProjectsParams = {}) => {
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<ProjectSummary>>(
`/projects/mine/list${qs ? `?${qs}` : ''}`,
);
},
/** Stats for the "Dự án của tôi" dashboard card — admin + owner only. */
getStats: (projectId: string) =>
apiClient.get<{
projectId: string;
linkedListingCount: number;
activeListingCount: number;
totalInquiries: number;
unreadInquiries: number;
savedByUsers: number;
}>(`/projects/${projectId}/stats`),
getBySlug: (slug: string) =>
apiClient.get<ProjectDetail>(`/projects/${slug}`),
getLinkedListings: (projectId: string, params: { page?: number; limit?: number } = {}) => {
const query = new URLSearchParams();
if (params.page) query.append('page', String(params.page));
if (params.limit) query.append('limit', String(params.limit));
const qs = query.toString();
return apiClient.get<PaginatedResult<ListingDetail>>(
`/projects/${projectId}/listings${qs ? `?${qs}` : ''}`,
);
},
submitInquiry: (projectId: string, data: { name: string; phone: string; message: string }) =>
apiClient.post<{ inquiryId: string }>(`/projects/${projectId}/inquiries`, data),
create: (payload: CreateProjectPayload) =>
apiClient.post<{ id: string; slug: string }>('/projects', payload),
update: (id: string, payload: UpdateProjectPayload) =>
apiClient.patch<ProjectDetail>(`/projects/${id}`, payload),
delete: (id: string) =>
apiClient.delete<{ success: boolean }>(`/projects/${id}`),
};