diff --git a/apps/web/app/[locale]/(public)/listings/[id]/page.tsx b/apps/web/app/[locale]/(public)/listings/[id]/page.tsx index 129e31b..759a8dd 100644 --- a/apps/web/app/[locale]/(public)/listings/[id]/page.tsx +++ b/apps/web/app/[locale]/(public)/listings/[id]/page.tsx @@ -1,349 +1,128 @@ -'use client'; +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; +import { ListingDetailClient } from '@/components/listings/listing-detail-client'; +import { + JsonLd, + generateBreadcrumbJsonLd, + generateListingJsonLd, +} from '@/components/seo/json-ld'; +import { fetchListingById } from '@/lib/listings-server'; +import { PROPERTY_TYPES, TRANSACTION_TYPES } from '@/lib/validations/listings'; -import dynamic from 'next/dynamic'; -import Link from 'next/link'; -import { useParams } from 'next/navigation'; -import * as React from 'react'; -import { ImageGallery } from '@/components/listings/image-gallery'; -import { Badge } from '@/components/ui/badge'; -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { AiEstimateButton } from '@/components/valuation/ai-estimate-button'; -import { listingsApi, type ListingDetail } from '@/lib/listings-api'; -import { PROPERTY_TYPES, DIRECTIONS, TRANSACTION_TYPES } from '@/lib/validations/listings'; +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- -const ListingMap = dynamic( - () => import('@/components/map/listing-map').then((mod) => mod.ListingMap), - { - ssr: false, - loading: () => ( -
-

Đang tải bản đồ...

-
- ), - }, -); - -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'); -} +const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn'; function getLabel(list: readonly { value: string; label: string }[], value: string | null) { if (!value) return null; return list.find((item) => item.value === value)?.label ?? value; } -export default function PublicListingDetailPage() { - const { id } = useParams<{ id: string }>(); - const [listing, setListing] = React.useState(null); - const [loading, setLoading] = React.useState(true); - const [error, setError] = React.useState(null); +function formatPriceShort(priceVND: string): string { + const num = Number(priceVND); + if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} t\u1ef7`; + if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} tri\u1ec7u`; + return num.toLocaleString('vi-VN'); +} - React.useEffect(() => { - listingsApi - .getById(id) - .then(setListing) - .catch((err) => setError(err instanceof Error ? err.message : 'Không tải được tin đăng')) - .finally(() => setLoading(false)); - }, [id]); +// --------------------------------------------------------------------------- +// Metadata (runs server-side, provides , <meta>, OG, canonical) +// --------------------------------------------------------------------------- - if (loading) { - return ( - <div className="mx-auto max-w-6xl px-4 py-8"> - {/* Skeleton loader */} - <div className="animate-pulse space-y-6"> - <div className="h-8 w-2/3 rounded bg-muted" /> - <div className="aspect-video rounded-lg bg-muted" /> - <div className="grid gap-6 lg:grid-cols-3"> - <div className="space-y-4 lg:col-span-2"> - <div className="h-40 rounded-lg bg-muted" /> - <div className="h-32 rounded-lg bg-muted" /> - </div> - <div className="h-48 rounded-lg bg-muted" /> - </div> - </div> - </div> - ); +interface PageProps { + params: { locale: string; id: string }; +} + +export async function generateMetadata({ params }: PageProps): Promise<Metadata> { + const listing = await fetchListingById(params.id); + if (!listing) { + return { title: 'Kh\u00f4ng t\u00ecm th\u1ea5y tin \u0111\u0103ng' }; } - if (error || !listing) { - return ( - <div className="flex min-h-[400px] flex-col items-center justify-center space-y-4"> - <svg className="h-12 w-12 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /> - </svg> - <p className="text-destructive">{error || 'Không tìm thấy tin đăng'}</p> - <Link href="/search"> - <Button variant="outline">Quay lại tìm kiếm</Button> - </Link> - </div> - ); - } - - const { property, seller, agent } = listing; - const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType); + const { property } = listing; const propertyTypeLabel = getLabel(PROPERTY_TYPES, property.propertyType); + const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType); + const priceStr = formatPriceShort(listing.priceVND); + const fullAddress = [property.address, property.ward, property.district, property.city] + .filter(Boolean) + .join(', '); - return ( - <div className="mx-auto max-w-6xl px-4 py-6"> - {/* Breadcrumb */} - <nav className="mb-4 flex items-center gap-1.5 text-sm text-muted-foreground"> - <Link href="/" className="hover:text-foreground">Trang chủ</Link> - <span>/</span> - <Link href="/search" className="hover:text-foreground">Tìm kiếm</Link> - <span>/</span> - <span className="truncate text-foreground">{property.title}</span> - </nav> + const title = `${property.title} - ${priceStr} VND`; + const description = [ + transactionLabel, + propertyTypeLabel, + `${property.areaM2} m\u00b2`, + property.bedrooms != null ? `${property.bedrooms} PN` : null, + fullAddress, + `Gi\u00e1: ${priceStr} VND`, + ] + .filter(Boolean) + .join(' | '); - {/* Header */} - <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between"> - <div className="min-w-0 flex-1"> - <div className="mb-2 flex flex-wrap items-center gap-2"> - {transactionLabel && ( - <Badge variant={listing.transactionType === 'SALE' ? 'default' : 'secondary'}> - {transactionLabel} - </Badge> - )} - {propertyTypeLabel && <Badge variant="outline">{propertyTypeLabel}</Badge>} - </div> - <h1 className="text-2xl font-bold md:text-3xl">{property.title}</h1> - <p className="mt-1 flex items-center gap-1 text-muted-foreground"> - <svg className="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /> - </svg> - {property.address}, {property.ward}, {property.district}, {property.city} - </p> - </div> - <div className="shrink-0 text-right"> - <p className="text-2xl font-bold text-primary md:text-3xl">{formatPrice(listing.priceVND)} VND</p> - {listing.pricePerM2 != null && ( - <p className="text-sm text-muted-foreground"> - ~{listing.pricePerM2.toLocaleString('vi-VN')} VND/m² - </p> - )} - {listing.rentPriceMonthly && ( - <p className="text-sm text-muted-foreground"> - Thuê: {formatPrice(listing.rentPriceMonthly)}/tháng - </p> - )} - </div> - </div> + const canonicalUrl = `${siteUrl}/${params.locale}/listings/${params.id}`; + const firstImage = property.media.find((m) => m.type === 'image'); - {/* Image gallery */} - <ImageGallery media={property.media} /> - - {/* Quick specs bar */} - <div className="my-6 flex flex-wrap gap-4 rounded-lg border bg-card p-4"> - <QuickStat icon="area" label="Diện tích" value={`${property.areaM2} m\u00B2`} /> - {property.bedrooms != null && ( - <QuickStat icon="bed" label="Phòng ngủ" value={`${property.bedrooms}`} /> - )} - {property.bathrooms != null && ( - <QuickStat icon="bath" label="Phòng tắm" value={`${property.bathrooms}`} /> - )} - {property.floors != null && ( - <QuickStat icon="floors" label="Số tầng" value={`${property.floors}`} /> - )} - {property.direction && ( - <QuickStat icon="compass" label="Hướng" value={getLabel(DIRECTIONS, property.direction) || ''} /> - )} - </div> - - <div className="grid gap-6 lg:grid-cols-3"> - {/* Main content */} - <div className="space-y-6 lg:col-span-2"> - {/* Description */} - <Card> - <CardHeader> - <CardTitle>Mô tả</CardTitle> - </CardHeader> - <CardContent> - <p className="whitespace-pre-wrap text-sm leading-relaxed">{property.description}</p> - </CardContent> - </Card> - - {/* Details */} - <Card> - <CardHeader> - <CardTitle>Thông tin chi tiết</CardTitle> - </CardHeader> - <CardContent> - <div className="grid grid-cols-2 gap-4 sm:grid-cols-3"> - <InfoItem label="Loại BĐS" value={propertyTypeLabel || '---'} /> - <InfoItem label="Diện tích" value={`${property.areaM2} m\u00B2`} /> - <InfoItem label="Phòng ngủ" value={property.bedrooms != null ? `${property.bedrooms}` : '---'} /> - <InfoItem label="Phòng tắm" value={property.bathrooms != null ? `${property.bathrooms}` : '---'} /> - <InfoItem label="Số tầng" value={property.floors != null ? `${property.floors}` : '---'} /> - <InfoItem label="Hướng" value={getLabel(DIRECTIONS, property.direction) || '---'} /> - <InfoItem label="Năm xây" value={property.yearBuilt ? `${property.yearBuilt}` : '---'} /> - <InfoItem label="Pháp lý" value={property.legalStatus || '---'} /> - <InfoItem label="Dự án" value={property.projectName || '---'} /> - </div> - </CardContent> - </Card> - - {/* Amenities */} - {property.amenities && property.amenities.length > 0 && ( - <Card> - <CardHeader> - <CardTitle>Tiện ích</CardTitle> - </CardHeader> - <CardContent> - <div className="flex flex-wrap gap-2"> - {property.amenities.map((a) => ( - <Badge key={a} variant="secondary"> - {a} - </Badge> - ))} - </div> - </CardContent> - </Card> - )} - - {/* Map */} - <Card> - <CardHeader> - <CardTitle>Vị trí trên bản đồ</CardTitle> - </CardHeader> - <CardContent> - <ListingMap - listings={[listing]} - className="h-[300px]" - /> - </CardContent> - </Card> - </div> - - {/* Sidebar */} - <div className="space-y-6"> - {/* Contact card */} - <Card className="sticky top-20"> - <CardHeader> - <CardTitle>Liên hệ</CardTitle> - </CardHeader> - <CardContent className="space-y-4"> - <div className="flex items-center gap-3"> - <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary"> - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /> - </svg> - </div> - <div> - <p className="font-medium">{seller.fullName}</p> - <p className="text-sm text-muted-foreground">{seller.phone}</p> - </div> - </div> - - <a href={`tel:${seller.phone}`}> - <Button className="w-full gap-2"> - <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /> - </svg> - Gọi ngay - </Button> - </a> - <Button variant="outline" className="w-full gap-2"> - <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /> - </svg> - Nhắn tin - </Button> - - {agent && ( - <div className="border-t pt-3"> - <p className="text-xs text-muted-foreground">Môi giới</p> - {agent.agency && <p className="text-sm font-medium">{agent.agency}</p>} - {listing.commissionPct != null && ( - <p className="text-xs text-muted-foreground">Hoa hồng: {listing.commissionPct}%</p> - )} - </div> - )} - </CardContent> - </Card> - - {/* AI Estimate */} - <AiEstimateButton listingId={listing.id} /> - - {/* Stats */} - <Card> - <CardContent className="pt-6"> - <div className="grid grid-cols-3 gap-4 text-center"> - <div> - <p className="text-lg font-bold">{listing.viewCount}</p> - <p className="text-xs text-muted-foreground">Lượt xem</p> - </div> - <div> - <p className="text-lg font-bold">{listing.saveCount}</p> - <p className="text-xs text-muted-foreground">Lượt lưu</p> - </div> - <div> - <p className="text-lg font-bold">{listing.inquiryCount}</p> - <p className="text-xs text-muted-foreground">Liên hệ</p> - </div> - </div> - {listing.publishedAt && ( - <p className="mt-3 border-t pt-3 text-center text-xs text-muted-foreground"> - Đăng ngày {new Date(listing.publishedAt).toLocaleDateString('vi-VN')} - </p> - )} - </CardContent> - </Card> - </div> - </div> - </div> - ); -} - -function QuickStat({ icon, label, value }: { icon: string; label: string; value: string }) { - const icons: Record<string, React.ReactNode> = { - area: ( - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" /> - </svg> - ), - bed: ( - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7v11m0-7h18M3 18h18M6 14h.01M6 10a2 2 0 012-2h8a2 2 0 012 2v0H6z" /> - </svg> - ), - bath: ( - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 12h16M4 12a2 2 0 00-2 2v2a4 4 0 004 4h12a4 4 0 004-4v-2a2 2 0 00-2-2M4 12V7a3 3 0 013-3h1" /> - </svg> - ), - floors: ( - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /> - </svg> - ), - compass: ( - <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> - <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 9l3 3m0 0l3-3m-3 3V6m0 6l-3 3m3-3l3 3m-3-3v6" /> - </svg> - ), + return { + title, + description, + alternates: { + canonical: canonicalUrl, + languages: { + vi: `${siteUrl}/vi/listings/${params.id}`, + en: `${siteUrl}/en/listings/${params.id}`, + }, + }, + openGraph: { + type: 'article', + locale: params.locale === 'vi' ? 'vi_VN' : 'en_US', + url: canonicalUrl, + title, + description, + siteName: 'GoodGo', + images: firstImage + ? [{ url: firstImage.url, width: 1200, height: 630, alt: property.title }] + : [{ url: '/og-image.png', width: 1200, height: 630, alt: 'GoodGo' }], + }, + twitter: { + card: 'summary_large_image', + title, + description, + images: firstImage ? [firstImage.url] : ['/og-image.png'], + }, }; - - return ( - <div className="flex items-center gap-2"> - <div className="text-muted-foreground">{icons[icon]}</div> - <div> - <p className="text-xs text-muted-foreground">{label}</p> - <p className="text-sm font-semibold">{value}</p> - </div> - </div> - ); } -function InfoItem({ label, value }: { label: string; value: string }) { +// --------------------------------------------------------------------------- +// Page (Server Component) +// --------------------------------------------------------------------------- + +export default async function PublicListingDetailPage({ params }: PageProps) { + const listing = await fetchListingById(params.id); + + if (!listing) { + notFound(); + } + + const { property } = listing; + + // Build JSON-LD structured data + const listingJsonLd = generateListingJsonLd(listing, siteUrl); + const breadcrumbJsonLd = generateBreadcrumbJsonLd([ + { name: 'Trang ch\u1ee7', url: siteUrl }, + { name: 'T\u00ecm ki\u1ebfm', url: `${siteUrl}/search` }, + { name: property.title, url: `${siteUrl}/${params.locale}/listings/${params.id}` }, + ]); + return ( - <div> - <p className="text-xs text-muted-foreground">{label}</p> - <p className="font-medium">{value}</p> - </div> + <> + {/* Structured data for search engines */} + <JsonLd data={listingJsonLd} /> + <JsonLd data={breadcrumbJsonLd} /> + + {/* Interactive client component */} + <ListingDetailClient listing={listing} /> + </> ); } diff --git a/apps/web/app/[locale]/layout.tsx b/apps/web/app/[locale]/layout.tsx index 07db790..42de710 100644 --- a/apps/web/app/[locale]/layout.tsx +++ b/apps/web/app/[locale]/layout.tsx @@ -5,6 +5,8 @@ import { getMessages, getTranslations } from 'next-intl/server'; import { AuthProvider } from '@/components/providers/auth-provider'; import { QueryProvider } from '@/components/providers/query-provider'; import { ThemeProvider } from '@/components/providers/theme-provider'; +import { WebVitals } from '@/components/providers/web-vitals'; +import { JsonLd, generateWebsiteJsonLd } from '@/components/seo/json-ld'; import type { Locale } from '@/i18n/config'; import { routing } from '@/i18n/routing'; import '../globals.css'; @@ -99,6 +101,7 @@ export default async function LocaleLayout({ return ( <html lang={locale} suppressHydrationWarning> <body> + <JsonLd data={generateWebsiteJsonLd(siteUrl)} /> <a href="#main-content" className="fixed left-2 top-2 z-[100] -translate-y-16 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-lg transition-transform focus:translate-y-0" @@ -108,7 +111,10 @@ export default async function LocaleLayout({ <NextIntlClientProvider messages={messages}> <ThemeProvider> <QueryProvider> - <AuthProvider>{children}</AuthProvider> + <AuthProvider> + <WebVitals /> + {children} + </AuthProvider> </QueryProvider> </ThemeProvider> </NextIntlClientProvider> diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index 6e798b2..65f23bf 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -1,16 +1,28 @@ import type { MetadataRoute } from 'next'; -export default function robots(): MetadataRoute.Robots { - const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn'; +const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn'; +export default function robots(): MetadataRoute.Robots { return { rules: [ { userAgent: '*', allow: '/', - disallow: ['/dashboard/', '/admin/', '/auth/', '/api/'], + disallow: [ + '/dashboard/', + '/admin/', + '/auth/', + '/api/', + '/*?sort=', // avoid indexing duplicate sort-order pages + '/*?page=', // avoid indexing deep pagination pages + ], + }, + { + userAgent: 'GPTBot', + disallow: ['/'], // block AI crawlers if desired }, ], sitemap: `${siteUrl}/sitemap.xml`, + host: siteUrl, }; } diff --git a/apps/web/app/sitemap.ts b/apps/web/app/sitemap.ts index f325785..5ca1c77 100644 --- a/apps/web/app/sitemap.ts +++ b/apps/web/app/sitemap.ts @@ -1,32 +1,87 @@ import type { MetadataRoute } from 'next'; +import { locales } from '@/i18n/config'; +import { fetchActiveListings } from '@/lib/listings-server'; -export default function sitemap(): MetadataRoute.Sitemap { - const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn'; +const siteUrl = process.env['NEXT_PUBLIC_SITE_URL'] || 'https://goodgo.vn'; - return [ - { - url: siteUrl, - lastModified: new Date(), - changeFrequency: 'daily', - priority: 1, - }, - { - url: `${siteUrl}/search`, - lastModified: new Date(), - changeFrequency: 'daily', - priority: 0.9, - }, - { - url: `${siteUrl}/login`, - lastModified: new Date(), - changeFrequency: 'monthly', - priority: 0.3, - }, - { - url: `${siteUrl}/register`, - lastModified: new Date(), - changeFrequency: 'monthly', - priority: 0.3, - }, - ]; +/** + * Dynamic sitemap that includes: + * - Static pages (home, search, login, register) per locale + * - All active property listings per locale + * + * ISR: the server-side fetch in fetchActiveListings uses `next: { revalidate: 3600 }` + * so the sitemap is regenerated roughly every hour. + */ +export default async function sitemap(): Promise<MetadataRoute.Sitemap> { + // ------------------------------------------------------------------ + // 1. Static pages + // ------------------------------------------------------------------ + const staticRoutes: MetadataRoute.Sitemap = []; + + for (const locale of locales) { + staticRoutes.push( + { + url: `${siteUrl}/${locale}`, + lastModified: new Date(), + changeFrequency: 'daily', + priority: 1, + }, + { + url: `${siteUrl}/${locale}/search`, + lastModified: new Date(), + changeFrequency: 'daily', + priority: 0.9, + }, + { + url: `${siteUrl}/${locale}/login`, + lastModified: new Date(), + changeFrequency: 'monthly', + priority: 0.3, + }, + { + url: `${siteUrl}/${locale}/register`, + lastModified: new Date(), + changeFrequency: 'monthly', + priority: 0.3, + }, + ); + } + + // ------------------------------------------------------------------ + // 2. Dynamic listing pages + // ------------------------------------------------------------------ + const listingRoutes: MetadataRoute.Sitemap = []; + + try { + // Fetch up to 1000 listings per page, paginate if needed. + // For very large catalogs this could be split into multiple sitemap + // indices, but for the current scale (<50k) a single file is fine. + let page = 1; + let totalPages = 1; + + do { + const result = await fetchActiveListings({ page, limit: 1000 }); + totalPages = result.totalPages; + + for (const listing of result.data) { + for (const locale of locales) { + listingRoutes.push({ + url: `${siteUrl}/${locale}/listings/${listing.id}`, + lastModified: listing.publishedAt + ? new Date(listing.publishedAt) + : new Date(listing.createdAt), + changeFrequency: 'weekly', + priority: 0.8, + }); + } + } + + page++; + } while (page <= totalPages); + } catch { + // If the API is unreachable, return static pages only. + // The sitemap will be retried on the next request (ISR). + } + + return [...staticRoutes, ...listingRoutes]; } diff --git a/apps/web/components/listings/listing-detail-client.tsx b/apps/web/components/listings/listing-detail-client.tsx new file mode 100644 index 0000000..7f7b8cc --- /dev/null +++ b/apps/web/components/listings/listing-detail-client.tsx @@ -0,0 +1,306 @@ +'use client'; + +import dynamic from 'next/dynamic'; +import Link from 'next/link'; +import * as React from 'react'; +import { ImageGallery } from '@/components/listings/image-gallery'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { AiEstimateButton } from '@/components/valuation/ai-estimate-button'; +import type { ListingDetail } from '@/lib/listings-api'; +import { PROPERTY_TYPES, DIRECTIONS, TRANSACTION_TYPES } from '@/lib/validations/listings'; + +const ListingMap = dynamic( + () => import('@/components/map/listing-map').then((mod) => mod.ListingMap), + { + ssr: false, + loading: () => ( + <div className="flex h-[300px] items-center justify-center rounded-lg bg-muted"> + <p className="text-sm text-muted-foreground">{'\u0110ang t\u1ea3i b\u1ea3n \u0111\u1ed3...'}</p> + </div> + ), + }, +); + +function formatPrice(priceVND: string): string { + const num = Number(priceVND); + if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} t\u1ef7`; + if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} tri\u1ec7u`; + return num.toLocaleString('vi-VN'); +} + +function getLabel(list: readonly { value: string; label: string }[], value: string | null) { + if (!value) return null; + return list.find((item) => item.value === value)?.label ?? value; +} + +interface ListingDetailClientProps { + listing: ListingDetail; +} + +export function ListingDetailClient({ listing }: ListingDetailClientProps) { + const { property, seller, agent } = listing; + const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType); + const propertyTypeLabel = getLabel(PROPERTY_TYPES, property.propertyType); + + return ( + <div className="mx-auto max-w-6xl px-4 py-6"> + {/* Breadcrumb */} + <nav className="mb-4 flex items-center gap-1.5 text-sm text-muted-foreground"> + <Link href="/" className="hover:text-foreground">Trang ch\u1ee7</Link> + <span>/</span> + <Link href="/search" className="hover:text-foreground">T\u00ecm ki\u1ebfm</Link> + <span>/</span> + <span className="truncate text-foreground">{property.title}</span> + </nav> + + {/* Header */} + <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between"> + <div className="min-w-0 flex-1"> + <div className="mb-2 flex flex-wrap items-center gap-2"> + {transactionLabel && ( + <Badge variant={listing.transactionType === 'SALE' ? 'default' : 'secondary'}> + {transactionLabel} + </Badge> + )} + {propertyTypeLabel && <Badge variant="outline">{propertyTypeLabel}</Badge>} + </div> + <h1 className="text-2xl font-bold md:text-3xl">{property.title}</h1> + <p className="mt-1 flex items-center gap-1 text-muted-foreground"> + <svg className="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" /> + </svg> + {property.address}, {property.ward}, {property.district}, {property.city} + </p> + </div> + <div className="shrink-0 text-right"> + <p className="text-2xl font-bold text-primary md:text-3xl">{formatPrice(listing.priceVND)} VND</p> + {listing.pricePerM2 != null && ( + <p className="text-sm text-muted-foreground"> + ~{listing.pricePerM2.toLocaleString('vi-VN')} VND/m² + </p> + )} + {listing.rentPriceMonthly && ( + <p className="text-sm text-muted-foreground"> + Thu\u00ea: {formatPrice(listing.rentPriceMonthly)}/th\u00e1ng + </p> + )} + </div> + </div> + + {/* Image gallery */} + <ImageGallery media={property.media} /> + + {/* Quick specs bar */} + <div className="my-6 flex flex-wrap gap-4 rounded-lg border bg-card p-4"> + <QuickStat icon="area" label="Di\u1ec7n t\u00edch" value={`${property.areaM2} m\u00B2`} /> + {property.bedrooms != null && ( + <QuickStat icon="bed" label="Ph\u00f2ng ng\u1ee7" value={`${property.bedrooms}`} /> + )} + {property.bathrooms != null && ( + <QuickStat icon="bath" label="Phòng tắm" value={`${property.bathrooms}`} /> + )} + {property.floors != null && ( + <QuickStat icon="floors" label="Số tầng" value={`${property.floors}`} /> + )} + {property.direction && ( + <QuickStat icon="compass" label="Hướng" value={getLabel(DIRECTIONS, property.direction) || ''} /> + )} + </div> + + <div className="grid gap-6 lg:grid-cols-3"> + {/* Main content */} + <div className="space-y-6 lg:col-span-2"> + {/* Description */} + <Card> + <CardHeader> + <CardTitle>Mô tả</CardTitle> + </CardHeader> + <CardContent> + <p className="whitespace-pre-wrap text-sm leading-relaxed">{property.description}</p> + </CardContent> + </Card> + + {/* Details */} + <Card> + <CardHeader> + <CardTitle>Thông tin chi tiết</CardTitle> + </CardHeader> + <CardContent> + <div className="grid grid-cols-2 gap-4 sm:grid-cols-3"> + <InfoItem label="Loại BĐS" value={propertyTypeLabel || '---'} /> + <InfoItem label="Diện tích" value={`${property.areaM2} m\u00B2`} /> + <InfoItem label="Phòng ngủ" value={property.bedrooms != null ? `${property.bedrooms}` : '---'} /> + <InfoItem label="Phòng tắm" value={property.bathrooms != null ? `${property.bathrooms}` : '---'} /> + <InfoItem label="Số tầng" value={property.floors != null ? `${property.floors}` : '---'} /> + <InfoItem label="Hướng" value={getLabel(DIRECTIONS, property.direction) || '---'} /> + <InfoItem label="Năm xây" value={property.yearBuilt ? `${property.yearBuilt}` : '---'} /> + <InfoItem label="Pháp lý" value={property.legalStatus || '---'} /> + <InfoItem label="Dự án" value={property.projectName || '---'} /> + </div> + </CardContent> + </Card> + + {/* Amenities */} + {property.amenities && property.amenities.length > 0 && ( + <Card> + <CardHeader> + <CardTitle>Tiện ích</CardTitle> + </CardHeader> + <CardContent> + <div className="flex flex-wrap gap-2"> + {property.amenities.map((a) => ( + <Badge key={a} variant="secondary"> + {a} + </Badge> + ))} + </div> + </CardContent> + </Card> + )} + + {/* Map */} + <Card> + <CardHeader> + <CardTitle>Vị trí trên bản đồ</CardTitle> + </CardHeader> + <CardContent> + <ListingMap + listings={[listing]} + className="h-[300px]" + /> + </CardContent> + </Card> + </div> + + {/* Sidebar */} + <div className="space-y-6"> + {/* Contact card */} + <Card className="lg:sticky lg:top-20"> + <CardHeader> + <CardTitle>Liên hệ</CardTitle> + </CardHeader> + <CardContent className="space-y-4"> + <div className="flex items-center gap-3"> + <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary"> + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /> + </svg> + </div> + <div> + <p className="font-medium">{seller.fullName}</p> + <p className="text-sm text-muted-foreground">{seller.phone}</p> + </div> + </div> + + <a href={`tel:${seller.phone}`}> + <Button className="w-full gap-2"> + <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" /> + </svg> + Gọi ngay + </Button> + </a> + <Button variant="outline" className="w-full gap-2"> + <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /> + </svg> + Nhắn tin + </Button> + + {agent && ( + <div className="border-t pt-3"> + <p className="text-xs text-muted-foreground">Môi giới</p> + {agent.agency && <p className="text-sm font-medium">{agent.agency}</p>} + {listing.commissionPct != null && ( + <p className="text-xs text-muted-foreground">Hoa hồng: {listing.commissionPct}%</p> + )} + </div> + )} + </CardContent> + </Card> + + {/* AI Estimate */} + <AiEstimateButton listingId={listing.id} /> + + {/* Stats */} + <Card> + <CardContent className="pt-6"> + <div className="grid grid-cols-3 gap-4 text-center"> + <div> + <p className="text-lg font-bold">{listing.viewCount}</p> + <p className="text-xs text-muted-foreground">Lượt xem</p> + </div> + <div> + <p className="text-lg font-bold">{listing.saveCount}</p> + <p className="text-xs text-muted-foreground">Lượt lưu</p> + </div> + <div> + <p className="text-lg font-bold">{listing.inquiryCount}</p> + <p className="text-xs text-muted-foreground">Liên hệ</p> + </div> + </div> + {listing.publishedAt && ( + <p className="mt-3 border-t pt-3 text-center text-xs text-muted-foreground"> + Đăng ngày {new Date(listing.publishedAt).toLocaleDateString('vi-VN')} + </p> + )} + </CardContent> + </Card> + </div> + </div> + </div> + ); +} + +function QuickStat({ icon, label, value }: { icon: string; label: string; value: string }) { + const icons: Record<string, React.ReactNode> = { + area: ( + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" /> + </svg> + ), + bed: ( + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7v11m0-7h18M3 18h18M6 14h.01M6 10a2 2 0 012-2h8a2 2 0 012 2v0H6z" /> + </svg> + ), + bath: ( + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 12h16M4 12a2 2 0 00-2 2v2a4 4 0 004 4h12a4 4 0 004-4v-2a2 2 0 00-2-2M4 12V7a3 3 0 013-3h1" /> + </svg> + ), + floors: ( + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /> + </svg> + ), + compass: ( + <svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> + <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 9l3 3m0 0l3-3m-3 3V6m0 6l-3 3m3-3l3 3m-3-3v6" /> + </svg> + ), + }; + + return ( + <div className="flex items-center gap-2"> + <div className="text-muted-foreground">{icons[icon]}</div> + <div> + <p className="text-xs text-muted-foreground">{label}</p> + <p className="text-sm font-semibold">{value}</p> + </div> + </div> + ); +} + +function InfoItem({ label, value }: { label: string; value: string }) { + return ( + <div> + <p className="text-xs text-muted-foreground">{label}</p> + <p className="font-medium">{value}</p> + </div> + ); +} diff --git a/apps/web/components/seo/json-ld.tsx b/apps/web/components/seo/json-ld.tsx new file mode 100644 index 0000000..e759a7e --- /dev/null +++ b/apps/web/components/seo/json-ld.tsx @@ -0,0 +1,188 @@ +import type { ListingDetail } from '@/lib/listings-api'; +import { PROPERTY_TYPES, TRANSACTION_TYPES } from '@/lib/validations/listings'; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +function getLabel(list: readonly { value: string; label: string }[], value: string | null) { + if (!value) return null; + return list.find((item) => item.value === value)?.label ?? value; +} + +function formatPriceNumber(priceVND: string): number { + return Number(priceVND); +} + +// --------------------------------------------------------------------------- +// JSON-LD generator for a single listing +// --------------------------------------------------------------------------- + +export function generateListingJsonLd(listing: ListingDetail, siteUrl: string) { + const { property } = listing; + + const propertyTypeLabel = getLabel(PROPERTY_TYPES, property.propertyType) ?? property.propertyType; + const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType) ?? listing.transactionType; + + const fullAddress = [property.address, property.ward, property.district, property.city] + .filter(Boolean) + .join(', '); + + const images = property.media + .filter((m) => m.type === 'image') + .map((m) => m.url); + + const priceNum = formatPriceNumber(listing.priceVND); + + // Schema.org RealEstateListing + // https://schema.org/RealEstateListing + const jsonLd: Record<string, unknown> = { + '@context': 'https://schema.org', + '@type': 'RealEstateListing', + name: property.title, + description: property.description?.slice(0, 500), + url: `${siteUrl}/listings/${listing.id}`, + datePosted: listing.publishedAt ?? listing.createdAt, + ...(images.length > 0 && { image: images }), + + // Offer + offers: { + '@type': 'Offer', + price: priceNum, + priceCurrency: 'VND', + availability: listing.status === 'ACTIVE' + ? 'https://schema.org/InStock' + : 'https://schema.org/SoldOut', + ...(listing.transactionType === 'RENT' && listing.rentPriceMonthly && { + priceSpecification: { + '@type': 'UnitPriceSpecification', + price: Number(listing.rentPriceMonthly), + priceCurrency: 'VND', + unitText: 'MONTH', + }, + }), + }, + + // Location + contentLocation: { + '@type': 'Place', + name: fullAddress, + address: { + '@type': 'PostalAddress', + streetAddress: property.address, + addressLocality: property.district, + addressRegion: property.city, + addressCountry: 'VN', + }, + ...(property.latitude != null && property.longitude != null && { + geo: { + '@type': 'GeoCoordinates', + latitude: property.latitude, + longitude: property.longitude, + }, + }), + }, + + // Additional property details via additionalProperty + additionalProperty: [ + { + '@type': 'PropertyValue', + name: 'Loại BDS', + value: propertyTypeLabel, + }, + { + '@type': 'PropertyValue', + name: 'Loại giao dich', + value: transactionLabel, + }, + { + '@type': 'PropertyValue', + name: 'Dien tich', + value: `${property.areaM2} m²`, + unitCode: 'MTK', + }, + ...(property.bedrooms != null + ? [{ + '@type': 'PropertyValue' as const, + name: 'Phong ngu', + value: property.bedrooms, + }] + : []), + ...(property.bathrooms != null + ? [{ + '@type': 'PropertyValue' as const, + name: 'Phong tam', + value: property.bathrooms, + }] + : []), + ...(property.floors != null + ? [{ + '@type': 'PropertyValue' as const, + name: 'So tang', + value: property.floors, + }] + : []), + ], + }; + + return jsonLd; +} + +// --------------------------------------------------------------------------- +// BreadcrumbList JSON-LD +// --------------------------------------------------------------------------- + +export function generateBreadcrumbJsonLd( + items: { name: string; url: string }[], +) { + return { + '@context': 'https://schema.org', + '@type': 'BreadcrumbList', + itemListElement: items.map((item, index) => ({ + '@type': 'ListItem', + position: index + 1, + name: item.name, + item: item.url, + })), + }; +} + +// --------------------------------------------------------------------------- +// Website (Organization) JSON-LD — for the root layout +// --------------------------------------------------------------------------- + +export function generateWebsiteJsonLd(siteUrl: string) { + return { + '@context': 'https://schema.org', + '@type': 'WebSite', + name: 'GoodGo', + url: siteUrl, + description: 'Nen tang bat dong san thong minh tai Viet Nam', + potentialAction: { + '@type': 'SearchAction', + target: { + '@type': 'EntryPoint', + urlTemplate: `${siteUrl}/search?q={search_term_string}`, + }, + 'query-input': 'required name=search_term_string', + }, + inLanguage: ['vi', 'en'], + }; +} + +// --------------------------------------------------------------------------- +// React component that renders <script type="application/ld+json"> +// --------------------------------------------------------------------------- + +interface JsonLdProps { + data: Record<string, unknown> | Record<string, unknown>[]; +} + +export function JsonLd({ data }: JsonLdProps) { + return ( + <script + type="application/ld+json" + dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }} + /> + ); +} diff --git a/apps/web/lib/listings-server.ts b/apps/web/lib/listings-server.ts new file mode 100644 index 0000000..eeb0ba8 --- /dev/null +++ b/apps/web/lib/listings-server.ts @@ -0,0 +1,51 @@ +/** + * Server-side listing data fetching for Next.js Server Components. + * + * This module uses `fetch` directly (no browser-only helpers) so it can run + * inside `generateMetadata`, `generateStaticParams`, `sitemap()`, etc. + */ + +import type { ListingDetail, PaginatedResult } from './listings-api'; + +const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001/api/v1'; + +/** + * Fetch a single listing by ID — server-only. + * Returns `null` when the listing is not found (404) so callers can `notFound()`. + */ +export async function fetchListingById(id: string): Promise<ListingDetail | null> { + try { + const res = await fetch(`${API_BASE_URL}/listings/${id}`, { + next: { revalidate: 300 }, // ISR: re-validate every 5 min + }); + + if (!res.ok) return null; + return (await res.json()) as ListingDetail; + } catch { + return null; + } +} + +/** + * Fetch active listings — server-only, used by the dynamic sitemap. + */ +export async function fetchActiveListings(params: { + page?: number; + limit?: number; +}): Promise<PaginatedResult<ListingDetail>> { + const query = new URLSearchParams({ + status: 'ACTIVE', + page: String(params.page ?? 1), + limit: String(params.limit ?? 100), + }); + + const res = await fetch(`${API_BASE_URL}/listings?${query}`, { + next: { revalidate: 3600 }, // re-validate every hour for sitemap + }); + + if (!res.ok) { + return { data: [], total: 0, page: 1, limit: 100, totalPages: 0 }; + } + + return (await res.json()) as PaginatedResult<ListingDetail>; +}