Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | 9x 626x 234x 626x 534x 354x 476x 476x 119x 119x 119x 119x 119x 119x 119x 119x 119x 133x 92x 202x 168x 150x | import { Eye, MousePointerClick, TrendingUp } from "lucide-react";
import type { ReactNode } from "react";
import { useProStats } from "../../hooks/queries/useProQueries";
import { useAdminProStats } from "../../hooks/queries/useAdminQueries";
import { WorkBand } from "../today/WorkQueue";
import { Alert } from "../ui/alert";
import { Card } from "../ui/card";
import {
Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../ui/table";
import { AnalyticsEmptyState } from "./AnalyticsEmptyState";
import { BreakdownBar } from "./BreakdownBar";
import { RankedListItem } from "./RankedListItem";
/**
* The marketplace half of Insights — one component, two contexts.
*
* WHY
* `pages/insights.tsx` (what a pro sees about their own listing) and
* `pages/admin/pro-analytics.tsx` (what an operator sees about ONE pro's
* listing) rendered the same six panels off the same `ProStats` shape, from two
* near-identical files. Same figures, same daily trend, same top projects,
* sources, devices and cities — only the link targets and the data hook
* differed. Two copies meant every change to the marketplace panels was two
* edits, and they had already drifted (one dropped `unknown` cities, the other
* did not; one formatted figures `en-IN`, the other did not).
*
* THE PATTERN
* `components/projects/ProjectDetailContainer.tsx` already solves exactly this
* in this codebase: one component, a `context: "pro" | "admin"` prop, and the
* context picks the data source. This follows it rather than inventing a second
* shape for the same problem.
*
* Both hooks are called on every render — that is deliberate and required by
* the rules of hooks. Each is `enabled`-gated on a non-null pro id, so the one
* the context did not pick is never fetched.
*
* THE IDIOM
* The Job Book: ruled `.label` band heads instead of card titles, figures
* tabular and right-aligned with their window printed underneath, the daily
* trend on the `Table` family at the dense tier, hairlines rather than boxes.
*/
export type MarketplaceTrafficContext = "pro" | "admin";
export interface MarketplaceTrafficProps {
context: MarketplaceTrafficContext;
proId: string | null;
/** Printed on the band above the figures. */
bandTitle?: string;
/** Rendered on the band's right — the CSV export, typically. */
bandAction?: ReactNode;
/** Printed on an error band when the figures cannot be loaded. */
errorMessage?: string;
}
const LABEL = "text-xs font-semibold uppercase tracking-wider";
/**
* Breakdown objects (`{ mobile: 12, desktop: 3 }`) to a sorted top five with
* percentages. `unknown` is dropped: a bucket the tracker could not classify
* is not a device, a city or a referrer anyone can act on.
*/
export function toBreakdownArray(obj: Record<string, number>) {
const total = Object.values(obj).reduce((sum, value) => sum + value, 0);
return Object.entries(obj)
.filter(([key]) => key !== "unknown")
.map(([key, count]) => ({
name: key,
count,
percentage: total > 0 ? Math.round((count / total) * 100) : 0,
}))
.sort((a, b) => b.count - a.count)
.slice(0, 5);
}
/** A figure with its window printed under it. Tabular and right-aligned. */
export function TrafficFigure({
label,
value,
window,
isLoading,
}: {
label: string;
value: number;
window: string;
isLoading: boolean;
}) {
return (
<div className="border-b-2 border-border-strong pt-2 pb-1.5">
<span className={`${LABEL} block text-foreground-muted`}>{label}</span>
{isLoading ? (
<div className="mt-1 h-6 w-16 animate-pulse rounded bg-background-muted" />
) : (
<span className="mt-0.5 block text-right text-2xl font-bold tabular-nums text-foreground-default">
{value.toLocaleString("en-IN")}
</span>
)}
<span className="block text-xs text-foreground-subtle">{window}</span>
</div>
);
}
/** A ruled panel: a `.label` head, a hairline, then its rows. */
export function TrafficPanel({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
return (
<Card className="overflow-hidden">
<div className="border-b border-border-default px-4 py-2.5">
<span className={`${LABEL} text-foreground-muted`}>{title}</span>
</div>
<div className="space-y-4 px-4 py-3.5">{children}</div>
</Card>
);
}
export function MarketplaceTraffic({
context,
proId,
bandTitle = "Marketplace",
bandAction,
errorMessage = "Marketplace figures could not be loaded.",
}: MarketplaceTrafficProps) {
// One of these two is always disabled — see the header.
const proQuery = useProStats(context === "pro" ? proId : null);
const adminQuery = useAdminProStats(context === "admin" ? proId : null);
const { data: stats, isLoading, isError } =
context === "pro" ? proQuery : adminQuery;
const projectBase = context === "admin" ? "/admin/projects" : "/projects";
const trafficSources = stats?.sources ? toBreakdownArray(stats.sources) : [];
const deviceBreakdown = stats?.devices ? toBreakdownArray(stats.devices) : [];
const cityBreakdown = stats?.cities ? toBreakdownArray(stats.cities) : [];
const dailyRows = stats?.daily ? stats.daily.slice(-7).reverse() : [];
return (
<section className="space-y-3">
{bandAction ? (
<div className="flex flex-wrap items-end justify-between gap-3">
<WorkBand title={bandTitle} quiet className="grow" />
{bandAction}
</div>
) : (
<WorkBand title={bandTitle} quiet />
)}
{isError && <Alert variant="error">{errorMessage}</Alert>}
<div className="grid grid-cols-2 gap-x-4 sm:grid-cols-4">
<TrafficFigure
label="Profile views"
value={stats?.summary?.views7d ?? 0}
window="last 7 days"
isLoading={isLoading}
/>
<TrafficFigure
label="Project clicks"
value={stats?.summary?.clicks7d ?? 0}
window="last 7 days"
isLoading={isLoading}
/>
<TrafficFigure
label="WhatsApp clicks"
value={stats?.summary?.totalWhatsappClicks ?? 0}
window="all time"
isLoading={isLoading}
/>
<TrafficFigure
label="Leads"
value={stats?.summary?.totalInquiries ?? 0}
window="all time"
isLoading={isLoading}
/>
</div>
<Card className="overflow-hidden">
<div className="flex items-center gap-2 border-b border-border-default px-4 py-2.5">
<TrendingUp
aria-hidden="true"
className="size-4 text-foreground-muted"
/>
<span className={`${LABEL} text-foreground-muted`}>
Views & clicks, last 7 days
</span>
</div>
{isLoading ? (
<div className="h-48 animate-pulse bg-background-subtle" />
) : dailyRows.length > 0 ? (
<Table density="dense">
<TableCaption>
Daily marketplace page views, clicks and unique sessions for the
last seven days.
</TableCaption>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead numeric>Views</TableHead>
<TableHead numeric>Clicks</TableHead>
<TableHead numeric>Sessions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{dailyRows.map((day) => (
<TableRow key={day.date}>
<TableCell>
{new Date(day.date).toLocaleDateString("en-IN", {
month: "short",
day: "numeric",
})}
</TableCell>
<TableCell numeric>{day.pageViews}</TableCell>
<TableCell numeric>
{day.projectClicks + day.whatsappClicks + day.callClicks}
</TableCell>
<TableCell numeric>{day.uniqueSessions}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
) : (
<div className="flex h-48 items-center justify-center">
<AnalyticsEmptyState icon={Eye} />
</div>
)}
</Card>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
<TrafficPanel title="Top projects">
{stats?.topProjects && stats.topProjects.length > 0 ? (
stats.topProjects.map((project, index) => (
<RankedListItem
key={project.id}
rank={index + 1}
label={project.title}
value={`${project.views.toLocaleString("en-IN")} views`}
href={`${projectBase}/${project.id}`}
/>
))
) : (
<AnalyticsEmptyState icon={Eye} />
)}
</TrafficPanel>
<TrafficPanel title="Traffic sources">
{trafficSources.length > 0 ? (
trafficSources.map((source) => (
<BreakdownBar
key={source.name}
name={source.name}
percentage={source.percentage}
color="bg-info"
/>
))
) : (
<AnalyticsEmptyState icon={TrendingUp} />
)}
</TrafficPanel>
<TrafficPanel title="Devices">
{deviceBreakdown.length > 0 ? (
deviceBreakdown.map((device) => (
<BreakdownBar
key={device.name}
name={device.name}
percentage={device.percentage}
color="bg-primary-600"
/>
))
) : (
<AnalyticsEmptyState icon={MousePointerClick} />
)}
</TrafficPanel>
</div>
<TrafficPanel title="Top cities">
{cityBreakdown.length > 0 ? (
cityBreakdown.map((city, index) => (
<RankedListItem
key={city.name}
rank={index + 1}
label={city.name}
value={`${city.count.toLocaleString("en-IN")} visits`}
/>
))
) : (
<AnalyticsEmptyState icon={Eye} />
)}
</TrafficPanel>
</section>
);
}
|