feat(web): add i18n locale routes and language switcher component
Add locale-prefixed routes for admin, auth, dashboard, and public pages. Add error, loading, and not-found pages for locale context. Add language switcher UI component for Vietnamese/English toggle. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
131
apps/web/app/[locale]/(dashboard)/listings/[id]/edit/page.tsx
Normal file
131
apps/web/app/[locale]/(dashboard)/listings/[id]/edit/page.tsx
Normal file
@@ -0,0 +1,131 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import * as React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
StepBasicInfo,
|
||||
StepLocation,
|
||||
StepDetails,
|
||||
StepPricing,
|
||||
} from '@/components/listings/listing-form-steps';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import { listingsApi, type ListingDetail } from '@/lib/listings-api';
|
||||
import {
|
||||
createListingSchema,
|
||||
type CreateListingFormData,
|
||||
} from '@/lib/validations/listings';
|
||||
|
||||
export default function EditListingPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [listing, setListing] = React.useState<ListingDetail | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [activeTab, setActiveTab] = React.useState('basic');
|
||||
|
||||
const {
|
||||
register,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<CreateListingFormData>({
|
||||
resolver: zodResolver(createListingSchema),
|
||||
mode: 'onTouched',
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
listingsApi
|
||||
.getById(id)
|
||||
.then((data) => {
|
||||
setListing(data);
|
||||
const { property } = data;
|
||||
reset({
|
||||
transactionType: data.transactionType,
|
||||
propertyType: property.propertyType,
|
||||
title: property.title,
|
||||
description: property.description,
|
||||
address: property.address,
|
||||
ward: property.ward,
|
||||
district: property.district,
|
||||
city: property.city,
|
||||
areaM2: String(property.areaM2),
|
||||
bedrooms: property.bedrooms != null ? String(property.bedrooms) : '',
|
||||
bathrooms: property.bathrooms != null ? String(property.bathrooms) : '',
|
||||
floors: property.floors != null ? String(property.floors) : '',
|
||||
direction: property.direction ?? '',
|
||||
yearBuilt: property.yearBuilt != null ? String(property.yearBuilt) : '',
|
||||
legalStatus: property.legalStatus ?? '',
|
||||
projectName: property.projectName ?? '',
|
||||
amenities: property.amenities?.join(', ') ?? '',
|
||||
priceVND: data.priceVND,
|
||||
rentPriceMonthly: data.rentPriceMonthly ?? '',
|
||||
commissionPct: data.commissionPct != null ? String(data.commissionPct) : '',
|
||||
});
|
||||
})
|
||||
.catch(() => setListing(null))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id, reset]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex min-h-[400px] items-center justify-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!listing) {
|
||||
return (
|
||||
<div className="flex min-h-[400px] flex-col items-center justify-center space-y-4">
|
||||
<p className="text-destructive">Không tìm thấy tin đăng</p>
|
||||
<Button variant="outline" onClick={() => router.push('/listings')}>
|
||||
Quay lại
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Chỉnh sửa tin đăng</h1>
|
||||
<Button variant="outline" onClick={() => router.push(`/listings/${id}`)}>
|
||||
Xem tin
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Chức năng chỉnh sửa sẽ được hoàn thiện khi backend API hỗ trợ PATCH /listings/:id.
|
||||
Hiện tại bạn có thể xem lại thông tin đã nhập.
|
||||
</p>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList className="grid w-full grid-cols-4">
|
||||
<TabsTrigger value="basic">Cơ bản</TabsTrigger>
|
||||
<TabsTrigger value="location">Vị trí</TabsTrigger>
|
||||
<TabsTrigger value="details">Chi tiết</TabsTrigger>
|
||||
<TabsTrigger value="pricing">Giá cả</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<Card className="mt-4">
|
||||
<CardContent className="pt-6">
|
||||
<TabsContent value="basic">
|
||||
<StepBasicInfo register={register} errors={errors} />
|
||||
</TabsContent>
|
||||
<TabsContent value="location">
|
||||
<StepLocation register={register} errors={errors} />
|
||||
</TabsContent>
|
||||
<TabsContent value="details">
|
||||
<StepDetails register={register} errors={errors} />
|
||||
</TabsContent>
|
||||
<TabsContent value="pricing">
|
||||
<StepPricing register={register} errors={errors} />
|
||||
</TabsContent>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/* eslint-disable import-x/order */
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const mockPush = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/listings-api', () => ({
|
||||
listingsApi: {
|
||||
create: vi.fn(),
|
||||
uploadMedia: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/components/listings/image-upload', () => ({
|
||||
ImageUpload: ({ onChange }: { onChange: (imgs: unknown[]) => void }) => (
|
||||
<div data-testid="image-upload">
|
||||
<button type="button" onClick={() => onChange([])}>Upload Mock</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
import { listingsApi } from '@/lib/listings-api';
|
||||
import CreateListingPage from '../new/page';
|
||||
|
||||
const _mockedListingsApi = vi.mocked(listingsApi);
|
||||
|
||||
describe('CreateListingPage', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the page title and step indicators', () => {
|
||||
render(<CreateListingPage />);
|
||||
|
||||
expect(screen.getByText('Đăng tin mới')).toBeInTheDocument();
|
||||
expect(screen.getByText('Thông tin')).toBeInTheDocument();
|
||||
expect(screen.getByText('Vị trí')).toBeInTheDocument();
|
||||
expect(screen.getByText('Chi tiết')).toBeInTheDocument();
|
||||
expect(screen.getByText('Giá cả')).toBeInTheDocument();
|
||||
expect(screen.getByText('Hình ảnh')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders step 1 (basic info) initially', () => {
|
||||
render(<CreateListingPage />);
|
||||
|
||||
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/loại giao dịch/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/loại bất động sản/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/tiêu đề/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/mô tả/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('has back button disabled on first step', () => {
|
||||
render(<CreateListingPage />);
|
||||
expect(screen.getByRole('button', { name: /quay lại/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('navigates to step 2 when basic info is filled and next is clicked', async () => {
|
||||
render(<CreateListingPage />);
|
||||
|
||||
// Fill step 1
|
||||
await userEvent.selectOptions(screen.getByLabelText(/loại giao dịch/i), 'SALE');
|
||||
await userEvent.selectOptions(screen.getByLabelText(/loại bất động sản/i), 'APARTMENT');
|
||||
await userEvent.type(screen.getByLabelText(/tiêu đề/i), 'Bán căn hộ 2PN tại Quận 7');
|
||||
await userEvent.type(screen.getByLabelText(/mô tả/i), 'Căn hộ view sông tuyệt đẹp, nội thất cao cấp');
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/địa chỉ/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows validation errors when required fields are empty on step 1', async () => {
|
||||
render(<CreateListingPage />);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
|
||||
|
||||
// Step should not advance - still showing basic info
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('navigates back to previous step', async () => {
|
||||
render(<CreateListingPage />);
|
||||
|
||||
// Fill step 1 and go to step 2
|
||||
await userEvent.selectOptions(screen.getByLabelText(/loại giao dịch/i), 'SALE');
|
||||
await userEvent.selectOptions(screen.getByLabelText(/loại bất động sản/i), 'APARTMENT');
|
||||
await userEvent.type(screen.getByLabelText(/tiêu đề/i), 'Test listing title here');
|
||||
await userEvent.type(screen.getByLabelText(/mô tả/i), 'A detailed description of the property for sale');
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText(/địa chỉ/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Go back
|
||||
await userEvent.click(screen.getByRole('button', { name: /quay lại/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
221
apps/web/app/[locale]/(dashboard)/listings/new/page.tsx
Normal file
221
apps/web/app/[locale]/(dashboard)/listings/new/page.tsx
Normal file
@@ -0,0 +1,221 @@
|
||||
'use client';
|
||||
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import * as React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ImageUpload, type ImageFile } from '@/components/listings/image-upload';
|
||||
import {
|
||||
StepBasicInfo,
|
||||
StepLocation,
|
||||
StepDetails,
|
||||
StepPricing,
|
||||
} from '@/components/listings/listing-form-steps';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { listingsApi, type CreateListingPayload, type Direction } from '@/lib/listings-api';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
createListingSchema,
|
||||
listingBasicSchema,
|
||||
listingLocationSchema,
|
||||
listingDetailsSchema,
|
||||
listingPricingSchema,
|
||||
type CreateListingFormData,
|
||||
} from '@/lib/validations/listings';
|
||||
|
||||
const STEPS = [
|
||||
{ title: 'Thông tin', schemaKeys: Object.keys(listingBasicSchema.shape) },
|
||||
{ title: 'Vị trí', schemaKeys: Object.keys(listingLocationSchema.shape) },
|
||||
{ title: 'Chi tiết', schemaKeys: Object.keys(listingDetailsSchema.shape) },
|
||||
{ title: 'Giá cả', schemaKeys: Object.keys(listingPricingSchema.shape) },
|
||||
{ title: 'Hình ảnh', schemaKeys: null },
|
||||
];
|
||||
|
||||
function toNum(val: string | undefined): number | undefined {
|
||||
if (!val) return undefined;
|
||||
const n = Number(val);
|
||||
return isNaN(n) ? undefined : n;
|
||||
}
|
||||
|
||||
export default function CreateListingPage() {
|
||||
const router = useRouter();
|
||||
const [currentStep, setCurrentStep] = React.useState(0);
|
||||
const [images, setImages] = React.useState<ImageFile[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
trigger,
|
||||
formState: { errors },
|
||||
} = useForm<CreateListingFormData>({
|
||||
resolver: zodResolver(createListingSchema),
|
||||
mode: 'onTouched',
|
||||
});
|
||||
|
||||
const goNext = async () => {
|
||||
const step = STEPS[currentStep];
|
||||
if (step?.schemaKeys) {
|
||||
const valid = await trigger(step.schemaKeys as Array<keyof CreateListingFormData>);
|
||||
if (!valid) return;
|
||||
}
|
||||
setCurrentStep((s) => Math.min(s + 1, STEPS.length - 1));
|
||||
};
|
||||
|
||||
const goBack = () => setCurrentStep((s) => Math.max(s - 1, 0));
|
||||
|
||||
const onSubmit = async (data: CreateListingFormData) => {
|
||||
setIsSubmitting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const payload: CreateListingPayload = {
|
||||
transactionType: data.transactionType,
|
||||
propertyType: data.propertyType,
|
||||
title: data.title,
|
||||
description: data.description,
|
||||
address: data.address,
|
||||
ward: data.ward,
|
||||
district: data.district,
|
||||
city: data.city,
|
||||
latitude: toNum(data.latitude) ?? 0,
|
||||
longitude: toNum(data.longitude) ?? 0,
|
||||
areaM2: Number(data.areaM2),
|
||||
priceVND: data.priceVND,
|
||||
};
|
||||
|
||||
const usableAreaM2 = toNum(data.usableAreaM2);
|
||||
if (usableAreaM2 != null) payload.usableAreaM2 = usableAreaM2;
|
||||
const bedrooms = toNum(data.bedrooms);
|
||||
if (bedrooms != null) payload.bedrooms = bedrooms;
|
||||
const bathrooms = toNum(data.bathrooms);
|
||||
if (bathrooms != null) payload.bathrooms = bathrooms;
|
||||
const floors = toNum(data.floors);
|
||||
if (floors != null) payload.floors = floors;
|
||||
const floor = toNum(data.floor);
|
||||
if (floor != null) payload.floor = floor;
|
||||
const totalFloors = toNum(data.totalFloors);
|
||||
if (totalFloors != null) payload.totalFloors = totalFloors;
|
||||
if (data.direction) payload.direction = data.direction as Direction;
|
||||
const yearBuilt = toNum(data.yearBuilt);
|
||||
if (yearBuilt != null) payload.yearBuilt = yearBuilt;
|
||||
if (data.legalStatus) payload.legalStatus = data.legalStatus;
|
||||
if (data.projectName) payload.projectName = data.projectName;
|
||||
if (data.amenities) {
|
||||
payload.amenities = data.amenities.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
if (data.rentPriceMonthly) payload.rentPriceMonthly = data.rentPriceMonthly;
|
||||
const commissionPct = toNum(data.commissionPct);
|
||||
if (commissionPct != null) payload.commissionPct = commissionPct;
|
||||
|
||||
const result = await listingsApi.create(payload);
|
||||
|
||||
for (const img of images) {
|
||||
try {
|
||||
await listingsApi.uploadMedia(result.listingId, img.file);
|
||||
} catch {
|
||||
// Continue with remaining images
|
||||
}
|
||||
}
|
||||
|
||||
router.push(`/listings/${result.listingId}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Có lỗi xảy ra');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl">
|
||||
<h1 className="mb-6 text-2xl font-bold">Đăng tin mới</h1>
|
||||
|
||||
{/* Step indicators */}
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
{STEPS.map((step, index) => (
|
||||
<div key={step.title} className="flex items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => index < currentStep && setCurrentStep(index)}
|
||||
className={cn(
|
||||
'flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium transition-colors',
|
||||
index === currentStep
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: index < currentStep
|
||||
? 'bg-primary/20 text-primary cursor-pointer'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{index < currentStep ? '\u2713' : index + 1}
|
||||
</button>
|
||||
<span
|
||||
className={cn(
|
||||
'ml-2 hidden text-sm sm:inline',
|
||||
index === currentStep ? 'font-medium' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{step.title}
|
||||
</span>
|
||||
{index < STEPS.length - 1 && (
|
||||
<div
|
||||
className={cn(
|
||||
'mx-3 h-px w-8 sm:w-12',
|
||||
index < currentStep ? 'bg-primary' : 'bg-muted',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
|
||||
{error}
|
||||
<button className="ml-2 font-medium underline" onClick={() => setError(null)}>
|
||||
Đóng
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
{currentStep === 0 && <StepBasicInfo register={register} errors={errors} />}
|
||||
{currentStep === 1 && <StepLocation register={register} errors={errors} />}
|
||||
{currentStep === 2 && <StepDetails register={register} errors={errors} />}
|
||||
{currentStep === 3 && <StepPricing register={register} errors={errors} />}
|
||||
{currentStep === 4 && (
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-semibold">Hình ảnh</h3>
|
||||
<ImageUpload images={images} onChange={setImages} />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="mt-6 flex justify-between">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={goBack}
|
||||
disabled={currentStep === 0}
|
||||
>
|
||||
Quay lại
|
||||
</Button>
|
||||
|
||||
{currentStep < STEPS.length - 1 ? (
|
||||
<Button type="button" onClick={goNext}>
|
||||
Tiếp theo
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Đang đăng...' : 'Đăng tin'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
345
apps/web/app/[locale]/(dashboard)/listings/page.tsx
Normal file
345
apps/web/app/[locale]/(dashboard)/listings/page.tsx
Normal file
@@ -0,0 +1,345 @@
|
||||
'use client';
|
||||
|
||||
import Image from 'next/image';
|
||||
import Link from 'next/link';
|
||||
import * as React from 'react';
|
||||
import { ListingStatusBadge } from '@/components/listings/listing-status-badge';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Select } from '@/components/ui/select';
|
||||
import { useListingsSearch } from '@/lib/hooks/use-listings';
|
||||
import type { ListingDetail as _ListingDetail } from '@/lib/listings-api';
|
||||
import { PROPERTY_TYPES, TRANSACTION_TYPES, LISTING_STATUSES } from '@/lib/validations/listings';
|
||||
function formatPrice(priceVND: string): string {
|
||||
const num = Number(priceVND);
|
||||
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} tỷ`;
|
||||
if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} triệu`;
|
||||
return num.toLocaleString('vi-VN');
|
||||
}
|
||||
|
||||
function formatDate(dateStr: string | null): string {
|
||||
if (!dateStr) return 'N/A';
|
||||
return new Date(dateStr).toLocaleDateString('vi-VN', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
type ViewMode = 'grid' | 'table';
|
||||
|
||||
export default function ListingsPage() {
|
||||
const [viewMode, setViewMode] = React.useState<ViewMode>('grid');
|
||||
const [filters, setFilters] = React.useState({
|
||||
transactionType: '',
|
||||
propertyType: '',
|
||||
status: '' as string,
|
||||
page: 1,
|
||||
});
|
||||
|
||||
const searchParams = React.useMemo(() => {
|
||||
const params: Record<string, string | number> = { page: filters.page, limit: 12 };
|
||||
if (filters.transactionType) params['transactionType'] = filters.transactionType;
|
||||
if (filters.propertyType) params['propertyType'] = filters.propertyType;
|
||||
if (filters.status) params['status'] = filters.status;
|
||||
return params;
|
||||
}, [filters]);
|
||||
|
||||
const { data: result, isLoading: loading } = useListingsSearch(searchParams);
|
||||
|
||||
// Stats from current page data
|
||||
const stats = React.useMemo(() => {
|
||||
if (!result) return { total: 0, active: 0, pending: 0, views: 0 };
|
||||
return {
|
||||
total: result.total,
|
||||
active: result.data.filter((l) => l.status === 'ACTIVE').length,
|
||||
pending: result.data.filter((l) => l.status === 'PENDING_REVIEW').length,
|
||||
views: result.data.reduce((s, l) => s + l.viewCount, 0),
|
||||
};
|
||||
}, [result]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Quản lý tin đăng</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Quản lý, theo dõi và cập nhật các tin đăng của bạn
|
||||
</p>
|
||||
</div>
|
||||
<Link href="/listings/new">
|
||||
<Button>Đăng tin mới</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid gap-3 sm:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Tổng tin đăng</CardDescription>
|
||||
<CardTitle className="text-xl">{loading ? '...' : stats.total}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Đang hoạt động</CardDescription>
|
||||
<CardTitle className="text-xl text-green-600">
|
||||
{loading ? '...' : stats.active}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Chờ duyệt</CardDescription>
|
||||
<CardTitle className="text-xl text-yellow-600">
|
||||
{loading ? '...' : stats.pending}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardDescription>Tổng lượt xem</CardDescription>
|
||||
<CardTitle className="text-xl">{loading ? '...' : stats.views}</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Filters + View Toggle */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select
|
||||
value={filters.transactionType}
|
||||
onChange={(e) =>
|
||||
setFilters((f) => ({ ...f, transactionType: e.target.value, page: 1 }))
|
||||
}
|
||||
className="w-40"
|
||||
>
|
||||
<option value="">Tất cả giao dịch</option>
|
||||
{TRANSACTION_TYPES.map((t) => (
|
||||
<option key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
value={filters.propertyType}
|
||||
onChange={(e) =>
|
||||
setFilters((f) => ({ ...f, propertyType: e.target.value, page: 1 }))
|
||||
}
|
||||
className="w-44"
|
||||
>
|
||||
<option value="">Tất cả loại BĐS</option>
|
||||
{PROPERTY_TYPES.map((t) => (
|
||||
<option key={t.value} value={t.value}>
|
||||
{t.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
<Select
|
||||
value={filters.status}
|
||||
onChange={(e) => setFilters((f) => ({ ...f, status: e.target.value, page: 1 }))}
|
||||
className="w-40"
|
||||
>
|
||||
<option value="">Tất cả trạng thái</option>
|
||||
{Object.entries(LISTING_STATUSES).map(([key, { label }]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<div className="ml-auto flex gap-1">
|
||||
<Button
|
||||
variant={viewMode === 'grid' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('grid')}
|
||||
>
|
||||
Lưới
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === 'table' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('table')}
|
||||
>
|
||||
Bảng
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{loading ? (
|
||||
<div className="flex min-h-[300px] items-center justify-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
|
||||
</div>
|
||||
) : !result || result.data.length === 0 ? (
|
||||
<div className="flex min-h-[300px] flex-col items-center justify-center text-muted-foreground">
|
||||
<p>Chưa có tin đăng nào</p>
|
||||
<Link href="/listings/new" className="mt-2">
|
||||
<Button variant="outline" size="sm">
|
||||
Đăng tin đầu tiên
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
) : viewMode === 'grid' ? (
|
||||
/* Grid View */
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{result.data.map((listing) => (
|
||||
<Link key={listing.id} href={`/listings/${listing.id}`}>
|
||||
<Card className="h-full overflow-hidden transition-shadow hover:shadow-md">
|
||||
<div className="relative aspect-[4/3] bg-muted">
|
||||
{listing.property.media.length > 0 ? (
|
||||
<Image
|
||||
src={listing.property.media[0]?.url ?? ''}
|
||||
alt={listing.property.title}
|
||||
fill
|
||||
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-muted-foreground">
|
||||
Chưa có ảnh
|
||||
</div>
|
||||
)}
|
||||
<div className="absolute left-2 top-2">
|
||||
<ListingStatusBadge status={listing.status} />
|
||||
</div>
|
||||
</div>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-lg font-bold text-primary">
|
||||
{formatPrice(listing.priceVND)} VND
|
||||
</p>
|
||||
<h3 className="mt-1 line-clamp-1 font-medium">{listing.property.title}</h3>
|
||||
<p className="mt-1 line-clamp-1 text-sm text-muted-foreground">
|
||||
{listing.property.district}, {listing.property.city}
|
||||
</p>
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{listing.property.areaM2} m²
|
||||
</Badge>
|
||||
{listing.property.bedrooms != null && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{listing.property.bedrooms} PN
|
||||
</Badge>
|
||||
)}
|
||||
{listing.property.bathrooms != null && listing.property.bathrooms > 0 && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{listing.property.bathrooms} PT
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-3 flex gap-3 text-xs text-muted-foreground">
|
||||
<span>{listing.viewCount} lượt xem</span>
|
||||
<span>{listing.inquiryCount} liên hệ</span>
|
||||
<span>{listing.saveCount} đã lưu</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
/* Table View */
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b text-left">
|
||||
<th className="p-3 font-medium">Tin đăng</th>
|
||||
<th className="p-3 font-medium">Loại</th>
|
||||
<th className="p-3 font-medium text-right">Giá</th>
|
||||
<th className="p-3 font-medium text-right">Diện tích</th>
|
||||
<th className="p-3 font-medium text-center">Trạng thái</th>
|
||||
<th className="p-3 font-medium text-right">Lượt xem</th>
|
||||
<th className="p-3 font-medium text-right">Liên hệ</th>
|
||||
<th className="p-3 font-medium text-right">Ngày đăng</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.data.map((listing) => (
|
||||
<tr
|
||||
key={listing.id}
|
||||
className="border-b last:border-0 transition-colors hover:bg-accent/50"
|
||||
>
|
||||
<td className="p-3">
|
||||
<Link
|
||||
href={`/listings/${listing.id}`}
|
||||
className="group flex items-center gap-3"
|
||||
>
|
||||
<div className="relative h-10 w-14 flex-shrink-0 overflow-hidden rounded bg-muted">
|
||||
{listing.property.media.length > 0 ? (
|
||||
<Image
|
||||
src={listing.property.media[0]?.url ?? ''}
|
||||
alt={listing.property.title}
|
||||
fill
|
||||
sizes="56px"
|
||||
className="object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-xs text-muted-foreground">
|
||||
N/A
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-medium group-hover:text-primary">
|
||||
{listing.property.title}
|
||||
</p>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{listing.property.district}, {listing.property.city}
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="p-3 text-xs text-muted-foreground">
|
||||
{listing.property.propertyType}
|
||||
</td>
|
||||
<td className="p-3 text-right font-medium text-primary">
|
||||
{formatPrice(listing.priceVND)}
|
||||
</td>
|
||||
<td className="p-3 text-right">{listing.property.areaM2} m²</td>
|
||||
<td className="p-3 text-center">
|
||||
<ListingStatusBadge status={listing.status} />
|
||||
</td>
|
||||
<td className="p-3 text-right">{listing.viewCount}</td>
|
||||
<td className="p-3 text-right">{listing.inquiryCount}</td>
|
||||
<td className="p-3 text-right text-xs text-muted-foreground">
|
||||
{formatDate(listing.publishedAt ?? listing.createdAt)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
{result && result.totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={filters.page <= 1}
|
||||
onClick={() => setFilters((f) => ({ ...f, page: f.page - 1 }))}
|
||||
>
|
||||
Trước
|
||||
</Button>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Trang {result.page} / {result.totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={filters.page >= result.totalPages}
|
||||
onClick={() => setFilters((f) => ({ ...f, page: f.page + 1 }))}
|
||||
>
|
||||
Tiếp
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user