Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

fix: improve year-in-review

Marc Seitzf9716075155f
diff --git a/components/yearly-recap/yearly-recap-banner.tsx b/components/yearly-recap/yearly-recap-banner.tsx
index 8f9336db..1cd5a73d 100644
--- a/components/yearly-recap/yearly-recap-banner.tsx
+++ b/components/yearly-recap/yearly-recap-banner.tsx
@@ -1,35 +1,81 @@
"use client";
-import { useState, useEffect } from "react";
import { useRouter } from "next/router";
-import { useTeam } from "@/context/team-context";
-import { Sparkles, ArrowRight } from "lucide-react";
-import useSWR from "swr";
+import { useEffect, useState } from "react";
-import { fetcher } from "@/lib/utils";
+import { useTeam } from "@/context/team-context";
+import { ArrowRight, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
+
import { YearlyRecapModal } from "./yearly-recap-modal";
// Decorative SVG Components
const DocumentStackSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 100 120" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="10" y="10" width="60" height="80" rx="2" fill="#FA7A02" opacity="0.4" />
- <rect x="15" y="20" width="60" height="80" rx="2" fill="#FA7A02" opacity="0.5" />
- <rect x="20" y="30" width="60" height="80" rx="2" fill="#FA7A02" opacity="0.6" />
+ <svg
+ className={className}
+ viewBox="0 0 100 120"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <rect
+ x="10"
+ y="10"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#FA7A02"
+ opacity="0.4"
+ />
+ <rect
+ x="15"
+ y="20"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#FA7A02"
+ opacity="0.5"
+ />
+ <rect
+ x="20"
+ y="30"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#FA7A02"
+ opacity="0.6"
+ />
</svg>
);
const PeachPaperSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M10 15 Q15 10, 20 15 L45 40 Q50 45, 45 50 L20 50 Q15 50, 10 45 Z" fill="#FFD4B3" opacity="0.6" />
- <path d="M10 15 Q12 12, 15 15 L40 40 Q42 42, 40 45 L15 45 Q12 45, 10 42 Z" fill="#FFD4B3" opacity="0.4" />
+ <svg
+ className={className}
+ viewBox="0 0 60 60"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M10 15 Q15 10, 20 15 L45 40 Q50 45, 45 50 L20 50 Q15 50, 10 45 Z"
+ fill="#FFD4B3"
+ opacity="0.6"
+ />
+ <path
+ d="M10 15 Q12 12, 15 15 L40 40 Q42 42, 40 45 L15 45 Q12 45, 10 42 Z"
+ fill="#FFD4B3"
+ opacity="0.4"
+ />
</svg>
);
const ScatterDotsSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <svg
+ className={className}
+ viewBox="0 0 100 100"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
<circle cx="25" cy="30" r="2" fill="#D3D3D3" opacity="0.5" />
<circle cx="45" cy="25" r="1.5" fill="#D3D3D3" opacity="0.5" />
<circle cx="65" cy="35" r="2" fill="#D3D3D3" opacity="0.5" />
@@ -39,32 +85,19 @@ const ScatterDotsSVG = ({ className }: { className?: string }) => (
</svg>
);
-interface YearlyRecapStats {
- year: number;
- totalViews: number;
- totalDocuments: number;
- totalDatarooms: number;
-}
-
export function YearlyRecapBanner() {
const teamInfo = useTeam();
const router = useRouter();
const currentYear = new Date().getFullYear();
const [showModal, setShowModal] = useState(false);
- const { data: stats } = useSWR<YearlyRecapStats>(
- teamInfo?.currentTeam?.id
- ? `/api/teams/${teamInfo.currentTeam.id}/yearly-recap`
- : null,
- fetcher,
- {
- revalidateOnFocus: false,
- },
- );
-
// Check if URL has openRecap parameter - open modal regardless of stats
useEffect(() => {
- if (router.isReady && router.query.openRecap === "true" && teamInfo?.currentTeam?.id) {
+ if (
+ router.isReady &&
+ router.query.openRecap === "true" &&
+ teamInfo?.currentTeam?.id
+ ) {
setShowModal(true);
// Remove the query parameter
const { openRecap, ...rest } = router.query;
@@ -72,7 +105,7 @@ export function YearlyRecapBanner() {
shallow: true,
});
}
- }, [router.isReady, router.query.openRecap, teamInfo?.currentTeam?.id, router]);
+ }, [router.isReady, router.query.openRecap, teamInfo?.currentTeam?.id]);
const handleOpenModal = () => {
setShowModal(true);
@@ -91,39 +124,41 @@ export function YearlyRecapBanner() {
onClose={() => setShowModal(false)}
teamId={teamInfo.currentTeam.id}
/>
-
+
{/* Banner - always shown */}
<div className="mx-2 my-2 mb-2">
- <div className="relative overflow-hidden rounded-xl p-6" style={{
- background: "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)"
- }}>
+ <div
+ className="relative overflow-hidden rounded-xl p-6"
+ style={{
+ background:
+ "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)",
+ }}
+ >
{/* Decorative elements */}
- <DocumentStackSVG className="absolute -top-2 -right-2 w-24 h-28" />
+ <DocumentStackSVG className="absolute -right-2 -top-2 h-28 w-24" />
{/* <PeachPaperSVG className="absolute bottom-2 left-2 w-16 h-16" /> */}
- <ScatterDotsSVG className="absolute top-2 left-1/4 w-20 h-20" />
+ <ScatterDotsSVG className="absolute left-1/4 top-2 h-20 w-20" />
<div className="relative z-10 flex items-center justify-between gap-4">
<div className="flex items-center gap-4">
- <div className="relative w-12 h-12 shrink-0">
+ <div className="relative h-12 w-12 shrink-0">
{/* <PeachPaperSVG className="absolute inset-0 w-full h-full opacity-60" /> */}
- <div className="absolute inset-0 w-12 h-12 rounded-full bg-orange-500/20 flex items-center justify-center">
+ <div className="absolute inset-0 flex h-12 w-12 items-center justify-center rounded-full bg-orange-500/20">
<Sparkles className="h-6 w-6 text-orange-500" />
</div>
</div>
<div>
- <h3 className="font-semibold text-gray-900 text-xl">Papermark Wrapped {currentYear}</h3>
- <p className="text-gray-600 text-sm">
- {stats ? (
- <>See your highlights: {stats.totalViews.toLocaleString()} views, {stats.totalDocuments} documents, {stats.totalDatarooms} datarooms</>
- ) : (
- "Your year in document sharing"
- )}
+ <h3 className="text-xl font-semibold text-gray-900">
+ Papermark Wrapped {currentYear}
+ </h3>
+ <p className="text-sm text-gray-600">
+ Your year in document sharing
</p>
</div>
</div>
- <Button
- onClick={handleOpenModal}
- className="bg-gray-900 hover:bg-black text-white gap-2 shrink-0"
+ <Button
+ onClick={handleOpenModal}
+ className="shrink-0 gap-2 bg-gray-900 text-white hover:bg-black"
>
See your Wrapped
<ArrowRight className="h-4 w-4" />
@@ -134,4 +169,3 @@ export function YearlyRecapBanner() {
</>
);
}
-
diff --git a/components/yearly-recap/yearly-recap-modal.tsx b/components/yearly-recap/yearly-recap-modal.tsx
index 3f4ce78e..16a26ebd 100644
--- a/components/yearly-recap/yearly-recap-modal.tsx
+++ b/components/yearly-recap/yearly-recap-modal.tsx
@@ -1,42 +1,39 @@
"use client";
-import { useState, useRef, useCallback } from "react";
+import { useCallback, useRef, useState } from "react";
import {
- Dialog,
- DialogContent,
-} from "@/components/ui/dialog";
-import { Button } from "@/components/ui/button";
-import {
- X,
- ChevronLeft,
- ChevronRight,
- Share2,
- Eye,
- Clock,
- FileText,
- Calendar,
- Users,
- Database,
ArrowRight,
- MapPin,
- Building2,
+ Calendar,
+ ChevronLeft,
+ ChevronRight,
+ Circle,
+ Clock,
Copy,
+ Database,
Download,
- Globe2,
+ Eye,
+ FileText,
Files,
Folder,
+ Globe2,
+ Grid3x3,
+ MapPin,
Paperclip,
+ Share2,
StickyNote,
- Grid3x3,
- Circle
+ Users,
+ X,
} from "lucide-react";
-import LinkedInIcon from "@/components/shared/icons/linkedin";
-import TwitterIcon from "@/components/shared/icons/twitter";
import { toast } from "sonner";
import useSWR from "swr";
-import { fetcher, cn } from "@/lib/utils";
+import { cn, fetcher } from "@/lib/utils";
+
+import LinkedInIcon from "@/components/shared/icons/linkedin";
+import TwitterIcon from "@/components/shared/icons/twitter";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
interface YearlyRecapStats {
year: number;
@@ -60,7 +57,7 @@ interface YearlyRecapStats {
} | null;
totalDuration: number;
uniqueCountries: string[];
- uniqueCities?: string[];
+ distanceTraveled: number;
}
interface YearlyRecapModalProps {
@@ -71,29 +68,92 @@ interface YearlyRecapModalProps {
// Decorative SVG Components
const DocumentStackSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 100 120" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="10" y="10" width="60" height="80" rx="2" fill="#F5F5F5" stroke="currentColor" strokeWidth="1.5" />
- <rect x="15" y="20" width="60" height="80" rx="2" fill="#F5F5F5" stroke="currentColor" strokeWidth="1.5" />
- <rect x="20" y="30" width="60" height="80" rx="2" fill="#F5F5F5" stroke="currentColor" strokeWidth="1.5" />
+ <svg
+ className={className}
+ viewBox="0 0 100 120"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <rect
+ x="10"
+ y="10"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#F5F5F5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <rect
+ x="15"
+ y="20"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#F5F5F5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
+ <rect
+ x="20"
+ y="30"
+ width="60"
+ height="80"
+ rx="2"
+ fill="#F5F5F5"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ />
</svg>
);
const FolderTabSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 100 80" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M10 20 L10 70 L70 70 L70 30 L45 30 L35 20 Z" fill="#FFB84D" opacity="0.4" stroke="#FFB84D" strokeWidth="1.5" />
+ <svg
+ className={className}
+ viewBox="0 0 100 80"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M10 20 L10 70 L70 70 L70 30 L45 30 L35 20 Z"
+ fill="#FFB84D"
+ opacity="0.4"
+ stroke="#FFB84D"
+ strokeWidth="1.5"
+ />
<path d="M10 20 L35 20 L45 30 L10 30 Z" fill="#FFB84D" opacity="0.6" />
</svg>
);
const StickyNoteSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
- <rect x="10" y="10" width="60" height="60" rx="2" fill="#90EE90" opacity="0.4" stroke="#90EE90" strokeWidth="1.5" />
+ <svg
+ className={className}
+ viewBox="0 0 80 80"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <rect
+ x="10"
+ y="10"
+ width="60"
+ height="60"
+ rx="2"
+ fill="#90EE90"
+ opacity="0.4"
+ stroke="#90EE90"
+ strokeWidth="1.5"
+ />
<path d="M10 10 L70 10 L60 20 L10 20 Z" fill="#90EE90" opacity="0.6" />
</svg>
);
const ScatterDotsSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <svg
+ className={className}
+ viewBox="0 0 100 100"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
<circle cx="25" cy="30" r="2" fill="#000000" opacity="0.5" />
<circle cx="45" cy="25" r="1.5" fill="#000000" opacity="0.5" />
<circle cx="65" cy="35" r="2" fill="#000000" opacity="0.5" />
@@ -104,8 +164,19 @@ const ScatterDotsSVG = ({ className }: { className?: string }) => (
);
const CurvedLineSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox="0 0 200 50" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M0 25 Q50 10, 100 25 T200 25" stroke="#D3D3D3" strokeWidth="2" fill="none" opacity="0.5" />
+ <svg
+ className={className}
+ viewBox="0 0 200 50"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M0 25 Q50 10, 100 25 T200 25"
+ stroke="#D3D3D3"
+ strokeWidth="2"
+ fill="none"
+ opacity="0.5"
+ />
</svg>
);
@@ -132,7 +203,7 @@ export function YearlyRecapModal({
const shareCardRef = useRef<HTMLDivElement>(null);
const { data: stats, isLoading } = useSWR<YearlyRecapStats>(
- teamId ? `/api/teams/${teamId}/yearly-recap` : null,
+ teamId && isOpen ? `/api/teams/${teamId}/yearly-recap` : null,
fetcher,
{
revalidateOnFocus: false,
@@ -163,7 +234,7 @@ export function YearlyRecapModal({
const captureImage = useCallback(async (): Promise<Blob | null> => {
if (!shareCardRef.current) return null;
-
+
try {
const html2canvas = (await import("html2canvas")).default;
const canvas = await html2canvas(shareCardRef.current, {
@@ -171,7 +242,7 @@ export function YearlyRecapModal({
backgroundColor: null,
useCORS: true,
});
-
+
return new Promise((resolve) => {
canvas.toBlob((blob) => {
resolve(blob);
@@ -216,10 +287,10 @@ export function YearlyRecapModal({
};
const getShareText = () => {
- const totalMinutes = Math.floor((stats?.totalDuration || 0) / 60);
+ const totalMinutes = Math.floor((stats?.totalDuration || 0) / 60_000); // from milliseconds to minutes
const countriesCount = stats?.uniqueCountries?.length || 0;
- const distanceTraveled = Math.round(countriesCount * 2500);
-
+ const distanceTraveled = stats?.distanceTraveled || 0;
+
return `· ${totalMinutes.toLocaleString()} min my docs were viewed
· ${distanceTraveled.toLocaleString()} km travelled my documents
· ${stats?.totalDocuments} documents
@@ -235,7 +306,7 @@ My Papermark Wrapped ${stats?.year}!
const text = getShareText();
window.open(
`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent("https://www.papermark.com/")}&summary=${encodeURIComponent(text)}`,
- "_blank"
+ "_blank",
);
};
@@ -243,18 +314,24 @@ My Papermark Wrapped ${stats?.year}!
const text = getShareText();
window.open(
`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}`,
- "_blank"
+ "_blank",
);
};
if (isLoading || !stats) {
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
- <DialogContent className="max-w-4xl p-0 overflow-hidden border-0" style={{
- background: "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)"
- }}>
+ <DialogContent
+ className="max-w-4xl overflow-hidden border-0 p-0"
+ style={{
+ background:
+ "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)",
+ }}
+ >
<div className="flex items-center justify-center p-8">
- <div className="text-center text-balance">Loading your recap...</div>
+ <div className="text-balance text-center">
+ Loading your recap...
+ </div>
</div>
</DialogContent>
</Dialog>
@@ -265,11 +342,11 @@ My Papermark Wrapped ${stats?.year}!
if (showShareView) {
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
- <DialogContent className="max-w-[700px] p-0 overflow-hidden border-0 bg-white">
+ <DialogContent className="max-w-[700px] overflow-hidden border-0 bg-white p-0">
{/* Close button */}
<button
onClick={() => setShowShareView(false)}
- className="absolute top-4 right-4 z-50 text-foreground/60 hover:text-foreground transition-colors"
+ className="absolute right-4 top-4 z-50 text-foreground/60 transition-colors hover:text-foreground"
>
<X className="h-5 w-5" />
</button>
@@ -277,32 +354,39 @@ My Papermark Wrapped ${stats?.year}!
{/* Shareable Card */}
<div className="p-6">
{(() => {
- const totalMinutes = Math.floor(stats.totalDuration / 60);
- const countriesCount = stats.uniqueCountries?.length || 0;
- const distanceTraveled = Math.round(countriesCount * 2500);
-
+ const totalMinutes = Math.floor(stats.totalDuration / 60_000); // from milliseconds to minutes
+ const distanceTraveled = stats.distanceTraveled || 0;
+
return (
<div
ref={shareCardRef}
- className="rounded-2xl overflow-hidden bg-gray-100 p-8 w-full max-w-[500px]"
+ className="w-full max-w-[500px] overflow-hidden rounded-2xl bg-gray-100 p-8"
>
{/* Stats Grid */}
- <div className="bg-white rounded-xl p-6 shadow-sm mb-6">
+ <div className="mb-6 rounded-xl bg-white p-6 shadow-sm">
<div className="grid grid-cols-2 gap-4">
<div className="text-center">
- <div className="text-4xl font-bold text-black mb-1">{totalMinutes.toLocaleString()}</div>
+ <div className="mb-1 text-4xl font-bold text-black">
+ {totalMinutes.toLocaleString()}
+ </div>
<p className="text-xs text-gray-600">minutes viewed</p>
</div>
<div className="text-center">
- <div className="text-4xl font-bold text-black mb-1">{distanceTraveled.toLocaleString()}</div>
+ <div className="mb-1 text-4xl font-bold text-black">
+ {distanceTraveled.toLocaleString()}
+ </div>
<p className="text-xs text-gray-600">km travelled</p>
</div>
<div className="text-center">
- <div className="text-4xl font-bold text-black mb-1">{stats.totalDocuments}</div>
+ <div className="mb-1 text-4xl font-bold text-black">
+ {stats.totalDocuments}
+ </div>
<p className="text-xs text-gray-600">documents</p>
</div>
<div className="text-center">
- <div className="text-4xl font-bold text-black mb-1">{stats.totalViews.toLocaleString()}</div>
+ <div className="mb-1 text-4xl font-bold text-black">
+ {stats.totalViews.toLocaleString()}
+ </div>
<p className="text-xs text-gray-600">views</p>
</div>
</div>
@@ -313,12 +397,16 @@ My Papermark Wrapped ${stats?.year}!
</div>
{/* Branding */}
- <div className="text-center mt-6">
+ <div className="mt-6 text-center">
<div className="inline-flex items-center gap-2">
- <span className="text-lg font-bold text-gray-900">Papermark</span>
- <span className="text-lg font-black text-gray-900">WRAPPED</span>
+ <span className="text-lg font-bold text-gray-900">
+ Papermark
+ </span>
+ <span className="text-lg font-black text-gray-900">
+ WRAPPED
+ </span>
</div>
- <p className="text-xs text-gray-500 mt-1">papermark.com</p>
+ <p className="mt-1 text-xs text-gray-500">papermark.com</p>
</div>
</div>
);
@@ -326,13 +414,16 @@ My Papermark Wrapped ${stats?.year}!
</div>
{/* $50 grant text */}
- <p className="px-6 text-sm text-muted-foreground text-center mb-4">
- Share your stats and receive <span className="font-semibold text-orange-600">$50</span> in credits on your papermark account, please send confirmation to <span className="font-medium">[email protected]</span> and include screenshot or link to your post.
-
+ <p className="mb-4 px-6 text-center text-sm text-muted-foreground">
+ Share your stats and receive{" "}
+ <span className="font-semibold text-orange-600">$50</span> in
+ credits on your papermark account, please send confirmation to{" "}
+ <span className="font-medium">[email protected]</span> and
+ include screenshot or link to your post.
</p>
{/* Share buttons */}
- <div className="px-6 pb-6 flex items-center justify-between">
+ <div className="flex items-center justify-between px-6 pb-6">
<div className="flex items-center gap-2">
<Button
onClick={handleCopyLink}
@@ -368,10 +459,10 @@ My Papermark Wrapped ${stats?.year}!
<Download className="h-4 w-4" />
</Button>
</div>
-
+
<Button
onClick={() => setShowShareView(false)}
- className="bg-gradient-to-r from-orange-500 to-orange-500 hover:from-orange-600 hover:to-orange-600 text-white gap-2 rounded-full"
+ className="gap-2 rounded-full bg-gradient-to-r from-orange-500 to-orange-500 text-white hover:from-orange-600 hover:to-orange-600"
>
Back to Wrapped
<ArrowRight className="h-4 w-4" />
@@ -384,18 +475,19 @@ My Papermark Wrapped ${stats?.year}!
return (
<Dialog open={isOpen} onOpenChange={handleClose}>
- <DialogContent className="max-w-[1100px] min-w-[700px] p-0 overflow-hidden border-0 [&>button]:hidden">
- <div
- className="relative min-h-[700px] rounded-3xl shadow-2xl overflow-hidden"
+ <DialogContent className="min-w-[700px] max-w-[1100px] overflow-hidden border-0 p-0 [&>button]:hidden">
+ <div
+ className="relative min-h-[700px] overflow-hidden rounded-3xl shadow-2xl"
style={{
- background: "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)"
+ background:
+ "linear-gradient(to right, rgba(249, 115, 22, 0.2) 0%, rgba(249, 115, 22, 0.1) 25%, #EEEFEB 50%, rgba(16, 185, 129, 0.1) 75%, rgba(16, 185, 129, 0.2) 100%)",
}}
>
{/* Decorative background elements - same as banner */}
{/* <DocumentStackSVG className="absolute top-16 -right-2 w-24 h-28 text-foreground opacity-50" /> */}
{/* <ScatterDotsSVG className="absolute top-1/4 left-1/4 w-20 h-20" /> */}
{/* <Paperclip className="absolute bottom-16 left-8 w-16 h-16 text-foreground/30" strokeWidth="1" /> */}
-
+
{/* Progress bar */}
<div className="relative z-10 flex gap-2 p-8">
{slides.map((_, index) => (
@@ -403,7 +495,9 @@ My Papermark Wrapped ${stats?.year}!
key={index}
className={cn(
"h-1.5 flex-1 rounded-full transition-all duration-300",
- index <= currentSlide ? "bg-foreground/40" : "bg-foreground/10"
+ index <= currentSlide
+ ? "bg-foreground/40"
+ : "bg-foreground/10",
)}
/>
))}
@@ -412,14 +506,16 @@ My Papermark Wrapped ${stats?.year}!
{/* Close button */}
<button
onClick={handleClose}
- className="absolute top-8 right-8 z-50 text-foreground/60 hover:text-foreground transition-colors"
+ className="absolute right-8 top-8 z-50 text-foreground/60 transition-colors hover:text-foreground"
>
<X className="h-6 w-6" />
</button>
{/* Slide content */}
<div className="relative z-10 px-16 pb-16 pt-4">
- {currentSlide === 0 && <IntroSlide stats={stats} onNext={nextSlide} />}
+ {currentSlide === 0 && (
+ <IntroSlide stats={stats} onNext={nextSlide} />
+ )}
{currentSlide === 1 && <GlobalFootprintSlide stats={stats} />}
{currentSlide === 2 && <MinutesSlide stats={stats} />}
{currentSlide === 3 && <ViewsStatsSlide stats={stats} />}
@@ -442,7 +538,7 @@ My Papermark Wrapped ${stats?.year}!
</Button>
<Button
onClick={handleShare}
- className="bg-foreground hover:bg-foreground/90 text-gray-100 gap-2 rounded-full px-6"
+ className="gap-2 rounded-full bg-foreground px-6 text-gray-100 hover:bg-foreground/90"
>
<Share2 className="h-4 w-4" />
Share
@@ -464,22 +560,29 @@ My Papermark Wrapped ${stats?.year}!
);
}
-function IntroSlide({ stats, onNext }: { stats: YearlyRecapStats; onNext: () => void }) {
+function IntroSlide({
+ stats,
+ onNext,
+}: {
+ stats: YearlyRecapStats;
+ onNext: () => void;
+}) {
return (
- <div className="flex flex-col items-center justify-center min-h-[520px] text-center relative">
- <h1 className="text-6xl font-semibold text-foreground mb-4 relative z-10 text-balance">
- Your {stats.year} with <span className="text-orange-500">Papermark</span>
+ <div className="relative flex min-h-[520px] flex-col items-center justify-center text-center">
+ <h1 className="relative z-10 mb-4 text-balance text-6xl font-semibold text-foreground">
+ Your {stats.year} with{" "}
+ <span className="text-orange-500">Papermark</span>
</h1>
- <p className="max-w-xl text-sm text-gray-500 mb-14 relative z-10">
- This review is personalised to your platform usage and contains your stats.
-
+ <p className="relative z-10 mb-14 max-w-xl text-sm text-gray-500">
+ This review is personalised to your platform usage and contains your
+ stats.
</p>
{/* Let's go button - only appears from bottom */}
<Button
onClick={onNext}
size="lg"
- className="bg-black hover:from-orange-600 hover:to-orange-600 text-white text-lg px-10 py-3 h-auto rounded-full shadow-xl animate-in slide-in-from-bottom-12 duration-700 relative z-10"
+ className="relative z-10 h-auto rounded-full bg-black px-10 py-3 text-lg text-white shadow-xl duration-700 animate-in slide-in-from-bottom-12 hover:from-orange-600 hover:to-orange-600"
>
Let&apos;s go
<ArrowRight className="ml-2 h-5 w-5" />
@@ -490,38 +593,33 @@ function IntroSlide({ stats, onNext }: { stats: YearlyRecapStats; onNext: () =>
function GlobalFootprintSlide({ stats }: { stats: YearlyRecapStats }) {
const countriesCount = stats.uniqueCountries.length;
- const citiesCount = stats.uniqueCities?.length || Math.round(countriesCount * 1.5);
- const distanceTraveled = Math.round(countriesCount * 2500);
-
+ const distanceTraveled = stats.distanceTraveled;
+
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center text-center">
+ <div className="flex min-h-[520px] flex-col items-center justify-center text-center">
{/* Title section - appears from top */}
- <div className="animate-in slide-in-from-top-8 duration-700">
+ <div className="duration-700 animate-in slide-in-from-top-8">
{/* Big number */}
- <h2 className="text-9xl font-bold text-foreground mb-4 text-balance">
- {distanceTraveled.toLocaleString()}
+ <h2 className="mb-4 text-balance text-9xl font-bold text-foreground">
+ {distanceTraveled.toLocaleString()}
<span className="text-2xl font-normal text-foreground">km</span>
</h2>
-
- <p className="text-2xl font-normal text-foreground mb-8 text-balance">
+
+ <p className="mb-8 text-balance text-2xl font-normal text-foreground">
your documents travelled this year
</p>
</div>
- {/* Two boxes side by side - appears from bottom */}
- <div className="flex gap-6 animate-in slide-in-from-bottom-8 duration-700">
- {/* Countries box */}
- <div className="bg-card rounded-2xl p-8 shadow-lg w-56">
- <MapPin className="h-8 w-8 text-orange-600 mx-auto mb-4" />
- <div className="text-5xl font-bold text-foreground">{countriesCount}</div>
- <p className="text-sm text-muted-foreground mt-2 text-balance">Countries</p>
- </div>
-
- {/* Cities box */}
- <div className="bg-card rounded-2xl p-8 shadow-lg w-56">
- <Building2 className="h-8 w-8 text-orange-600 mx-auto mb-4" />
- <div className="text-5xl font-bold text-foreground">{citiesCount}</div>
- <p className="text-sm text-muted-foreground mt-2 text-balance">Cities</p>
+ {/* Countries box - appears from bottom */}
+ <div className="duration-700 animate-in slide-in-from-bottom-8">
+ <div className="w-56 rounded-2xl bg-card p-8 shadow-lg">
+ <MapPin className="mx-auto mb-4 h-8 w-8 text-orange-600" />
+ <div className="text-5xl font-bold text-foreground">
+ {countriesCount}
+ </div>
+ <p className="mt-2 text-balance text-sm text-muted-foreground">
+ Countries
+ </p>
</div>
</div>
</div>
@@ -529,34 +627,46 @@ function GlobalFootprintSlide({ stats }: { stats: YearlyRecapStats }) {
}
function MinutesSlide({ stats }: { stats: YearlyRecapStats }) {
- const totalMinutes = Math.floor(stats.totalDuration / 60);
-
+ const totalMinutes = Math.floor(stats.totalDuration / 60_000); // from milliseconds to minutes
+
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center text-center">
+ <div className="flex min-h-[520px] flex-col items-center justify-center text-center">
{/* Header from top */}
- <div className="animate-in slide-in-from-top-8 duration-700">
- <p className="text-lg text-muted-foreground mb-2">Total time on your documents</p>
- <h2
- className="text-8xl font-bold text-orange-500 mb-2"
- style={{ WebkitTextStroke: '2px currentColor', WebkitTextFillColor: 'transparent' }}
+ <div className="duration-700 animate-in slide-in-from-top-8">
+ <p className="mb-2 text-lg text-muted-foreground">
+ Total time on your documents
+ </p>
+ <h2
+ className="mb-2 text-8xl font-bold text-orange-500"
+ style={{
+ WebkitTextStroke: "2px currentColor",
+ WebkitTextFillColor: "transparent",
+ }}
>
{totalMinutes.toLocaleString()}
</h2>
<p className="text-2xl font-medium text-foreground">minutes</p>
</div>
-
+
{/* Document card from left */}
{stats.mostViewedDocument && (
- <div className="bg-white/80 backdrop-blur rounded-xl p-5 shadow-sm animate-in slide-in-from-left-8 duration-700 mt-8 border border-foreground/5 max-w-xl w-full">
+ <div className="mt-8 w-full max-w-xl rounded-xl border border-foreground/5 bg-white/80 p-5 shadow-sm backdrop-blur duration-700 animate-in slide-in-from-left-8">
<div className="flex items-center gap-4">
- <div className="w-12 h-12 rounded-lg bg-orange-500/10 flex items-center justify-center flex-shrink-0">
+ <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-lg bg-orange-500/10">
<FileText className="h-6 w-6 text-orange-500" />
</div>
<div className="text-left">
- <span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">Most Viewed</span>
- <h3 className="font-semibold text-foreground mt-1">{stats.mostViewedDocument.documentName}</h3>
- <p className="text-sm text-muted-foreground mt-1">
- <span className="font-semibold text-orange-500">{stats.mostViewedDocument.viewCount.toLocaleString()}</span> views
+ <span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ Most Viewed
+ </span>
+ <h3 className="mt-1 font-semibold text-foreground">
+ {stats.mostViewedDocument.documentName}
+ </h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ <span className="font-semibold text-orange-500">
+ {stats.mostViewedDocument.viewCount.toLocaleString()}
+ </span>{" "}
+ views
</p>
</div>
</div>
@@ -568,28 +678,40 @@ function MinutesSlide({ stats }: { stats: YearlyRecapStats }) {
function ViewsStatsSlide({ stats }: { stats: YearlyRecapStats }) {
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center">
+ <div className="flex min-h-[520px] flex-col items-center justify-center">
{/* Header from left */}
- <h2 className="text-3xl font-bold text-foreground mb-8 animate-in slide-in-from-left-8 duration-700 text-center text-balance">
+ <h2 className="mb-8 text-balance text-center text-3xl font-bold text-foreground duration-700 animate-in slide-in-from-left-8">
Your {stats.year} activity on Papermark
</h2>
-
+
{/* Cards from right */}
- <div className="grid grid-cols-3 gap-5 w-full max-w-5xl animate-in slide-in-from-right-8 duration-700">
- <div className="bg-card rounded-2xl p-10 text-center shadow-lg">
- <Eye className="h-6 w-6 text-orange-500 mx-auto mb-4" />
- <span className="text-5xl font-bold text-foreground block">{stats.totalViews.toLocaleString()}</span>
- <p className="text-sm text-muted-foreground mt-3 font-medium text-balance">Views</p>
+ <div className="grid w-full max-w-5xl grid-cols-3 gap-5 duration-700 animate-in slide-in-from-right-8">
+ <div className="rounded-2xl bg-card p-10 text-center shadow-lg">
+ <Eye className="mx-auto mb-4 h-6 w-6 text-orange-500" />
+ <span className="block text-5xl font-bold text-foreground">
+ {stats.totalViews.toLocaleString()}
+ </span>
+ <p className="mt-3 text-balance text-sm font-medium text-muted-foreground">
+ Views
+ </p>
</div>
- <div className="bg-card rounded-2xl p-10 text-center shadow-lg">
- <FileText className="h-6 w-6 text-orange-500 mx-auto mb-4" />
- <span className="text-5xl font-bold text-foreground block">{stats.totalDocuments.toLocaleString()}</span>
- <p className="text-sm text-muted-foreground mt-3 font-medium text-balance">Documents</p>
+ <div className="rounded-2xl bg-card p-10 text-center shadow-lg">
+ <FileText className="mx-auto mb-4 h-6 w-6 text-orange-500" />
+ <span className="block text-5xl font-bold text-foreground">
+ {stats.totalDocuments.toLocaleString()}
+ </span>
+ <p className="mt-3 text-balance text-sm font-medium text-muted-foreground">
+ Documents
+ </p>
</div>
- <div className="bg-card rounded-2xl p-10 text-center shadow-lg">
- <Database className="h-6 w-6 text-orange-600 mx-auto mb-4" />
- <span className="text-5xl font-bold text-foreground block">{stats.totalDatarooms.toLocaleString()}</span>
- <p className="text-sm text-muted-foreground mt-3 font-medium text-balance">Datarooms</p>
+ <div className="rounded-2xl bg-card p-10 text-center shadow-lg">
+ <Database className="mx-auto mb-4 h-6 w-6 text-orange-600" />
+ <span className="block text-5xl font-bold text-foreground">
+ {stats.totalDatarooms.toLocaleString()}
+ </span>
+ <p className="mt-3 text-balance text-sm font-medium text-muted-foreground">
+ Datarooms
+ </p>
</div>
</div>
</div>
@@ -598,30 +720,35 @@ function ViewsStatsSlide({ stats }: { stats: YearlyRecapStats }) {
function MostActiveSlide({ stats }: { stats: YearlyRecapStats }) {
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center text-center">
- <h2 className="text-3xl font-bold text-foreground mb-2 text-balance">
+ <div className="flex min-h-[520px] flex-col items-center justify-center text-center">
+ <h2 className="mb-2 text-balance text-3xl font-bold text-foreground">
Your Most Active Viewer
</h2>
- <p className="text-muted-foreground text-lg mb-10 text-balance">
+ <p className="mb-10 text-balance text-lg text-muted-foreground">
Someone really loves your documents!
</p>
-
+
{/* Card appears from bottom only */}
{stats.mostActiveViewer ? (
- <div className="bg-card rounded-3xl p-12 shadow-lg animate-in slide-in-from-bottom-8 duration-700 max-w-xl w-full">
- <div className="w-24 h-24 rounded-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center mx-auto mb-6">
+ <div className="w-full max-w-xl rounded-3xl bg-card p-12 shadow-lg duration-700 animate-in slide-in-from-bottom-8">
+ <div className="mx-auto mb-6 flex h-24 w-24 items-center justify-center rounded-full bg-gradient-to-br from-primary/20 to-primary/40">
<Users className="h-12 w-12 text-primary" />
</div>
- <h3 className="text-2xl font-bold text-foreground text-balance">
+ <h3 className="text-balance text-2xl font-bold text-foreground">
{stats.mostActiveViewer.name || stats.mostActiveViewer.email}
</h3>
- <p className="text-muted-foreground mt-3 text-balance">
- Viewed your documents <span className="font-semibold text-primary">{stats.mostActiveViewer.viewCount.toLocaleString()} times</span>
+ <p className="mt-3 text-balance text-muted-foreground">
+ Viewed your documents{" "}
+ <span className="font-semibold text-primary">
+ {stats.mostActiveViewer.viewCount.toLocaleString()} times
+ </span>
</p>
</div>
) : (
- <div className="bg-card rounded-3xl p-12 shadow-lg">
- <p className="text-muted-foreground text-balance">No viewer data available</p>
+ <div className="rounded-3xl bg-card p-12 shadow-lg">
+ <p className="text-balance text-muted-foreground">
+ No viewer data available
+ </p>
</div>
)}
</div>
@@ -630,25 +757,28 @@ function MostActiveSlide({ stats }: { stats: YearlyRecapStats }) {
function SummarySlide({ stats }: { stats: YearlyRecapStats }) {
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center text-center">
- <h2 className="text-4xl font-bold text-foreground mb-4 text-balance">
+ <div className="flex min-h-[520px] flex-col items-center justify-center text-center">
+ <h2 className="mb-4 text-balance text-4xl font-bold text-foreground">
What a year! 🎉
</h2>
- <p className="text-muted-foreground text-lg max-w-xl text-balance">
- You&apos;ve made an impact with your documents. Here&apos;s to an even bigger {stats.year + 1}!
+ <p className="max-w-xl text-balance text-lg text-muted-foreground">
+ You&apos;ve made an impact with your documents. Here&apos;s to an even
+ bigger {stats.year + 1}!
</p>
-
+
{/* Busiest month */}
{stats.mostActiveMonth && (
- <div className="mt-8 bg-card rounded-2xl px-8 py-5 shadow-lg animate-in zoom-in-75 duration-700">
+ <div className="mt-8 rounded-2xl bg-card px-8 py-5 shadow-lg duration-700 animate-in zoom-in-75">
<div className="flex items-center gap-3 text-sm">
<Calendar className="h-5 w-5 text-orange-600" />
<span className="text-muted-foreground">Busiest month:</span>
- <span className="font-semibold text-foreground">{stats.mostActiveMonth.month}</span>
+ <span className="font-semibold text-foreground">
+ {stats.mostActiveMonth.month}
+ </span>
</div>
</div>
)}
-
+
{/* Numbers only */}
{/* <div className="flex items-center justify-center gap-8 mt-10">
<span className="text-5xl font-bold text-foreground animate-in zoom-in-75 duration-700" style={{ animationDelay: "0ms" }}>
@@ -667,25 +797,22 @@ function SummarySlide({ stats }: { stats: YearlyRecapStats }) {
function ShareOfferSlide({ stats }: { stats: YearlyRecapStats }) {
return (
- <div className="min-h-[520px] flex flex-col items-center justify-center text-center">
- <h2 className="text-3xl font-bold text-foreground mb-6 text-balance">
+ <div className="flex min-h-[520px] flex-col items-center justify-center text-center">
+ <h2 className="mb-6 text-balance text-3xl font-bold text-foreground">
Share your stats or experience with Papermark
</h2>
-
- <div className="animate-in zoom-in-50 duration-1000">
- <span className="text-8xl font-bold text-orange-500 mb-2">
-
- <h2
- className="text-8xl font-semibold text-black mb-2"
-
- >
- $50
- </h2>
+
+ <div className="duration-1000 animate-in zoom-in-50">
+ <span className="mb-2 block text-8xl font-bold text-orange-500">
+ $50
</span>
</div>
-
- <p className="text-sm text-muted-foreground mt-8 text-balance">
- You will receive $50 in credits on your papermark account, please send confirmation to <span className="font-medium">[email protected]</span> and include screenshot or link to your post.
+
+ <p className="mt-8 text-balance text-sm text-muted-foreground">
+ You will receive $50 in credits on your papermark account, please send
+ confirmation to{" "}
+ <span className="font-medium">[email protected]</span> and include
+ screenshot or link to your post.
</p>
</div>
);
diff --git a/lib/utils/geo.ts b/lib/utils/geo.ts
index dff501a9..4886e5ad 100644
--- a/lib/utils/geo.ts
+++ b/lib/utils/geo.ts
@@ -23,12 +23,12 @@ export function getGeoData(headers: {
}
export const LOCALHOST_GEO_DATA = {
- continent: "North America",
- city: "San Francisco",
- region: "CA",
- country: "US",
- latitude: "37.7749",
- longitude: "-122.4194",
+ continent: "Europe",
+ city: "Munich",
+ region: "BY",
+ country: "DE",
+ latitude: "48.1371",
+ longitude: "11.5761",
};
export const LOCALHOST_IP = "127.0.0.1";
diff --git a/lib/year-in-review/get-stats.ts b/lib/year-in-review/get-stats.ts
index e2da8a7c..34684835 100644
--- a/lib/year-in-review/get-stats.ts
+++ b/lib/year-in-review/get-stats.ts
@@ -5,65 +5,278 @@ import { getTotalTeamDuration } from "@/lib/tinybird/pipes";
import { COUNTRIES } from "../constants";
-export async function getYearInReviewStats(teamId: string, year?: number) {
+// Country centroids (latitude, longitude) for distance calculations
+const COUNTRY_CENTROIDS: { [key: string]: { lat: number; lng: number } } = {
+ AF: { lat: 33.94, lng: 67.71 },
+ AL: { lat: 41.15, lng: 20.17 },
+ DZ: { lat: 28.03, lng: 1.66 },
+ AD: { lat: 42.55, lng: 1.6 },
+ AO: { lat: -11.2, lng: 17.87 },
+ AR: { lat: -38.42, lng: -63.62 },
+ AM: { lat: 40.07, lng: 45.04 },
+ AU: { lat: -25.27, lng: 133.78 },
+ AT: { lat: 47.52, lng: 14.55 },
+ AZ: { lat: 40.14, lng: 47.58 },
+ BH: { lat: 25.93, lng: 50.64 },
+ BD: { lat: 23.68, lng: 90.36 },
+ BY: { lat: 53.71, lng: 27.95 },
+ BE: { lat: 50.5, lng: 4.47 },
+ BZ: { lat: 17.19, lng: -88.5 },
+ BJ: { lat: 9.31, lng: 2.32 },
+ BT: { lat: 27.51, lng: 90.43 },
+ BO: { lat: -16.29, lng: -63.59 },
+ BA: { lat: 43.92, lng: 17.68 },
+ BW: { lat: -22.33, lng: 24.68 },
+ BR: { lat: -14.24, lng: -51.93 },
+ BN: { lat: 4.54, lng: 114.73 },
+ BG: { lat: 42.73, lng: 25.49 },
+ BF: { lat: 12.24, lng: -1.56 },
+ BI: { lat: -3.37, lng: 29.92 },
+ KH: { lat: 12.57, lng: 104.99 },
+ CM: { lat: 7.37, lng: 12.35 },
+ CA: { lat: 56.13, lng: -106.35 },
+ CF: { lat: 6.61, lng: 20.94 },
+ TD: { lat: 15.45, lng: 18.73 },
+ CL: { lat: -35.68, lng: -71.54 },
+ CN: { lat: 35.86, lng: 104.2 },
+ CO: { lat: 4.57, lng: -74.3 },
+ CG: { lat: -0.23, lng: 15.83 },
+ CD: { lat: -4.04, lng: 21.76 },
+ CR: { lat: 9.75, lng: -83.75 },
+ CI: { lat: 7.54, lng: -5.55 },
+ HR: { lat: 45.1, lng: 15.2 },
+ CU: { lat: 21.52, lng: -77.78 },
+ CY: { lat: 35.13, lng: 33.43 },
+ CZ: { lat: 49.82, lng: 15.47 },
+ DK: { lat: 56.26, lng: 9.5 },
+ DO: { lat: 18.74, lng: -70.16 },
+ EC: { lat: -1.83, lng: -78.18 },
+ EG: { lat: 26.82, lng: 30.8 },
+ SV: { lat: 13.79, lng: -88.9 },
+ EE: { lat: 58.6, lng: 25.01 },
+ ET: { lat: 9.15, lng: 40.49 },
+ FI: { lat: 61.92, lng: 25.75 },
+ FR: { lat: 46.23, lng: 2.21 },
+ GA: { lat: -0.8, lng: 11.61 },
+ GE: { lat: 42.32, lng: 43.36 },
+ DE: { lat: 51.17, lng: 10.45 },
+ GH: { lat: 7.95, lng: -1.02 },
+ GR: { lat: 39.07, lng: 21.82 },
+ GT: { lat: 15.78, lng: -90.23 },
+ HN: { lat: 15.2, lng: -86.24 },
+ HK: { lat: 22.4, lng: 114.11 },
+ HU: { lat: 47.16, lng: 19.5 },
+ IS: { lat: 64.96, lng: -19.02 },
+ IN: { lat: 20.59, lng: 78.96 },
+ ID: { lat: -0.79, lng: 113.92 },
+ IR: { lat: 32.43, lng: 53.69 },
+ IQ: { lat: 33.22, lng: 43.68 },
+ IE: { lat: 53.41, lng: -8.24 },
+ IL: { lat: 31.05, lng: 34.85 },
+ IT: { lat: 41.87, lng: 12.57 },
+ JM: { lat: 18.11, lng: -77.3 },
+ JP: { lat: 36.2, lng: 138.25 },
+ JO: { lat: 30.59, lng: 36.24 },
+ KZ: { lat: 48.02, lng: 66.92 },
+ KE: { lat: -0.02, lng: 37.91 },
+ KR: { lat: 35.91, lng: 127.77 },
+ KW: { lat: 29.31, lng: 47.48 },
+ KG: { lat: 41.2, lng: 74.77 },
+ LA: { lat: 19.86, lng: 102.5 },
+ LV: { lat: 56.88, lng: 24.6 },
+ LB: { lat: 33.85, lng: 35.86 },
+ LY: { lat: 26.34, lng: 17.23 },
+ LT: { lat: 55.17, lng: 23.88 },
+ LU: { lat: 49.82, lng: 6.13 },
+ MO: { lat: 22.2, lng: 113.54 },
+ MK: { lat: 41.51, lng: 21.75 },
+ MG: { lat: -18.77, lng: 46.87 },
+ MY: { lat: 4.21, lng: 101.98 },
+ MV: { lat: 3.2, lng: 73.22 },
+ ML: { lat: 17.57, lng: -4.0 },
+ MT: { lat: 35.94, lng: 14.38 },
+ MX: { lat: 23.63, lng: -102.55 },
+ MD: { lat: 47.41, lng: 28.37 },
+ MN: { lat: 46.86, lng: 103.85 },
+ ME: { lat: 42.71, lng: 19.37 },
+ MA: { lat: 31.79, lng: -7.09 },
+ MZ: { lat: -18.67, lng: 35.53 },
+ MM: { lat: 21.91, lng: 95.96 },
+ NA: { lat: -22.96, lng: 18.49 },
+ NP: { lat: 28.39, lng: 84.12 },
+ NL: { lat: 52.13, lng: 5.29 },
+ NZ: { lat: -40.9, lng: 174.89 },
+ NI: { lat: 12.87, lng: -85.21 },
+ NE: { lat: 17.61, lng: 8.08 },
+ NG: { lat: 9.08, lng: 8.68 },
+ NO: { lat: 60.47, lng: 8.47 },
+ OM: { lat: 21.51, lng: 55.92 },
+ PK: { lat: 30.38, lng: 69.35 },
+ PA: { lat: 8.54, lng: -80.78 },
+ PY: { lat: -23.44, lng: -58.44 },
+ PE: { lat: -9.19, lng: -75.02 },
+ PH: { lat: 12.88, lng: 121.77 },
+ PL: { lat: 51.92, lng: 19.15 },
+ PT: { lat: 39.4, lng: -8.22 },
+ PR: { lat: 18.22, lng: -66.59 },
+ QA: { lat: 25.35, lng: 51.18 },
+ RO: { lat: 45.94, lng: 24.97 },
+ RU: { lat: 61.52, lng: 105.32 },
+ RW: { lat: -1.94, lng: 29.87 },
+ SA: { lat: 23.89, lng: 45.08 },
+ SN: { lat: 14.5, lng: -14.45 },
+ RS: { lat: 44.02, lng: 21.01 },
+ SG: { lat: 1.35, lng: 103.82 },
+ SK: { lat: 48.67, lng: 19.7 },
+ SI: { lat: 46.15, lng: 14.99 },
+ ZA: { lat: -30.56, lng: 22.94 },
+ ES: { lat: 40.46, lng: -3.75 },
+ LK: { lat: 7.87, lng: 80.77 },
+ SE: { lat: 60.13, lng: 18.64 },
+ CH: { lat: 46.82, lng: 8.23 },
+ TW: { lat: 23.7, lng: 120.96 },
+ TJ: { lat: 38.86, lng: 71.28 },
+ TZ: { lat: -6.37, lng: 34.89 },
+ TH: { lat: 15.87, lng: 100.99 },
+ TN: { lat: 33.89, lng: 9.54 },
+ TR: { lat: 38.96, lng: 35.24 },
+ TM: { lat: 38.97, lng: 59.56 },
+ UG: { lat: 1.37, lng: 32.29 },
+ UA: { lat: 48.38, lng: 31.17 },
+ AE: { lat: 23.42, lng: 53.85 },
+ GB: { lat: 55.38, lng: -3.44 },
+ US: { lat: 37.09, lng: -95.71 },
+ UY: { lat: -32.52, lng: -55.77 },
+ UZ: { lat: 41.38, lng: 64.59 },
+ VE: { lat: 6.42, lng: -66.59 },
+ VN: { lat: 14.06, lng: 108.28 },
+ YE: { lat: 15.55, lng: 48.52 },
+ ZM: { lat: -13.13, lng: 27.85 },
+ ZW: { lat: -19.02, lng: 29.15 },
+};
+
+// Haversine formula to calculate distance between two points on Earth
+function calculateDistance(
+ lat1: number,
+ lng1: number,
+ lat2: number,
+ lng2: number,
+): number {
+ const R = 6371; // Earth's radius in kilometers
+ const dLat = ((lat2 - lat1) * Math.PI) / 180;
+ const dLng = ((lng2 - lng1) * Math.PI) / 180;
+ const a =
+ Math.sin(dLat / 2) * Math.sin(dLat / 2) +
+ Math.cos((lat1 * Math.PI) / 180) *
+ Math.cos((lat2 * Math.PI) / 180) *
+ Math.sin(dLng / 2) *
+ Math.sin(dLng / 2);
+ const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+ return R * c;
+}
+
+// Default origin (San Francisco) used when user's location is not available
+const DEFAULT_ORIGIN = { lat: 37.77, lng: -122.42 };
+
+// Calculate total distance traveled based on unique countries
+// Uses the user's current location as the origin point
+function calculateTotalDistance(
+ countryCodes: string[],
+ origin: { lat: number; lng: number },
+): number {
+ let totalDistance = 0;
+
+ for (const code of countryCodes) {
+ const centroid = COUNTRY_CENTROIDS[code];
+ if (centroid) {
+ totalDistance += calculateDistance(
+ origin.lat,
+ origin.lng,
+ centroid.lat,
+ centroid.lng,
+ );
+ }
+ }
+
+ return Math.round(totalDistance);
+}
+
+export async function getYearInReviewStats(
+ teamId: string,
+ year?: number,
+ userGeo?: { latitude?: string; longitude?: string },
+) {
const currentYear = year || new Date().getFullYear();
const yearStart = new Date(`${currentYear}-01-01`);
const yearEnd = new Date(`${currentYear + 1}-01-01`);
+ console.log("yearStart", yearStart);
+ console.log("yearEnd", yearEnd);
+
+ // First, get team member emails to exclude from "most viewed" and "most active viewer"
+ const teamMembers = await prisma.userTeam.findMany({
+ where: { teamId },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ });
+
+ const teamMemberEmails = teamMembers
+ .map((member) => member.user.email)
+ .filter((email): email is string => email !== null);
+
// Run all queries in parallel for a specific team
const [
documents,
- teamCounts,
+ links,
+ views,
mostViewedDoc,
mostActiveMonth,
dataroomCounts,
mostActiveViewer,
] = await Promise.all([
- prisma.document.findMany({
- where: { teamId },
- select: { id: true },
- }),
+ prisma.document.findMany({
+ where: {
+ teamId,
+ createdAt: {
+ gte: yearStart,
+ lt: yearEnd,
+ },
+ },
+ select: {
+ id: true,
+ },
+ }),
- // 1. Total documents, links, and views for the year
- prisma.team.findUnique({
- where: { id: teamId },
- select: {
- _count: {
- select: {
- documents: {
- where: {
- createdAt: {
- gte: yearStart,
- lt: yearEnd,
- },
- },
- },
- links: {
- where: {
- createdAt: {
- gte: yearStart,
- lt: yearEnd,
- },
- },
- },
- views: {
- where: {
- viewedAt: {
- gte: yearStart,
- lt: yearEnd,
- },
- isArchived: false,
- },
- },
- },
- },
+ prisma.link.count({
+ where: {
+ teamId,
+ createdAt: {
+ gte: yearStart,
+ lt: yearEnd,
},
- }),
+ },
+ }),
+
+ prisma.view.count({
+ where: {
+ teamId,
+ viewedAt: {
+ gte: yearStart,
+ lt: yearEnd,
+ },
+ isArchived: false,
+ },
+ }),
- // 2. Most viewed document
- prisma.$queryRaw<
- Array<{ documentId: string; documentName: string; viewCount: number }>
- >(Prisma.sql`
+ // 2. Most viewed document
+ prisma.$queryRaw<
+ Array<{ documentId: string; documentName: string; viewCount: number }>
+ >(Prisma.sql`
WITH RankedDocuments AS (
SELECT
d."id" as "documentId",
@@ -88,8 +301,8 @@ export async function getYearInReviewStats(teamId: string, year?: number) {
LIMIT 1
`),
- // 3. Most active month
- prisma.$queryRaw<Array<{ month: Date; viewCount: number }>>(Prisma.sql`
+ // 3. Most active month
+ prisma.$queryRaw<Array<{ month: Date; viewCount: number }>>(Prisma.sql`
WITH MonthlyViews AS (
SELECT
DATE_TRUNC('month', "viewedAt") as month,
@@ -120,18 +333,19 @@ export async function getYearInReviewStats(teamId: string, year?: number) {
},
}),
- // 5. Most active viewer (person who viewed most)
- prisma.$queryRaw<
- Array<{
- viewerEmail: string;
- viewerName: string | null;
- viewCount: number;
- }>
- >(Prisma.sql`
+ // 5. Most active viewer (person who viewed most, excluding team members)
+ teamMemberEmails.length > 0
+ ? prisma.$queryRaw<
+ Array<{
+ viewerEmail: string;
+ viewerName: string | null;
+ viewCount: number;
+ }>
+ >(Prisma.sql`
WITH RankedViewers AS (
SELECT
v."viewerEmail",
- v."viewerName",
+ MAX(v."viewerName") as "viewerName",
COUNT(*) as "viewCount",
ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as rn
FROM "View" v
@@ -141,7 +355,38 @@ export async function getYearInReviewStats(teamId: string, year?: number) {
AND v."viewedAt" < ${yearEnd}
AND v."isArchived" = false
AND v."viewerEmail" IS NOT NULL
- GROUP BY v."viewerEmail", v."viewerName"
+ AND v."viewerEmail" NOT IN (${Prisma.join(teamMemberEmails)})
+ GROUP BY v."viewerEmail"
+ )
+ SELECT
+ "viewerEmail",
+ "viewerName",
+ "viewCount"
+ FROM RankedViewers
+ WHERE rn = 1
+ LIMIT 1
+ `)
+ : prisma.$queryRaw<
+ Array<{
+ viewerEmail: string;
+ viewerName: string | null;
+ viewCount: number;
+ }>
+ >(Prisma.sql`
+ WITH RankedViewers AS (
+ SELECT
+ v."viewerEmail",
+ MAX(v."viewerName") as "viewerName",
+ COUNT(*) as "viewCount",
+ ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as rn
+ FROM "View" v
+ WHERE
+ v."teamId" = ${teamId}
+ AND v."viewedAt" >= ${yearStart}
+ AND v."viewedAt" < ${yearEnd}
+ AND v."isArchived" = false
+ AND v."viewerEmail" IS NOT NULL
+ GROUP BY v."viewerEmail"
)
SELECT
"viewerEmail",
@@ -151,44 +396,88 @@ export async function getYearInReviewStats(teamId: string, year?: number) {
WHERE rn = 1
LIMIT 1
`),
- ]);
+ ]);
// skip if no documents
if (documents.length === 0) {
return {
year: currentYear,
- totalDocuments: teamCounts?._count.documents || 0,
- totalLinks: teamCounts?._count.links || 0,
- totalViews: teamCounts?._count.views || 0,
+ totalDocuments: documents.length || 0,
+ totalLinks: links || 0,
+ totalViews: views || 0,
totalDatarooms: dataroomCounts || 0,
mostViewedDocument: null,
mostActiveMonth: null,
mostActiveViewer: null,
totalDuration: 0,
uniqueCountries: [],
+ distanceTraveled: 0,
};
}
- // get total duration for all documents in the team
- const tinybirdData = await getTotalTeamDuration({
- documentIds: documents.map((doc) => doc.id).join(","),
- since: yearStart.getTime(),
- until: yearEnd.getTime(),
+ // Batch document IDs to avoid URL length limits (max ~100 IDs per request)
+ const BATCH_SIZE = 100;
+ const documentIds = documents.map((doc) => doc.id);
+ const batches: string[][] = [];
+
+ for (let i = 0; i < documentIds.length; i += BATCH_SIZE) {
+ batches.push(documentIds.slice(i, i + BATCH_SIZE));
+ }
+
+ // Fetch all batches in parallel
+ const tinybirdResults = await Promise.all(
+ batches.map((batch) =>
+ getTotalTeamDuration({
+ documentIds: batch.join(","),
+ since: yearStart.getTime(),
+ until: yearEnd.getTime(),
+ }),
+ ),
+ );
+
+ // Aggregate results from all batches
+ let totalDuration = 0;
+ const allCountries = new Set<string>();
+
+ for (const result of tinybirdResults) {
+ if (result.data[0]) {
+ totalDuration += result.data[0].total_duration || 0;
+ result.data[0].unique_countries?.forEach((country: string) =>
+ allCountries.add(country),
+ );
+ }
+ }
+
+ // Get country codes array for distance calculation
+ const countryCodes = Array.from(allCountries);
+
+ // Determine origin point from user's IP location or use default
+ const origin =
+ userGeo?.latitude && userGeo?.longitude
+ ? {
+ lat: parseFloat(userGeo.latitude),
+ lng: parseFloat(userGeo.longitude),
+ }
+ : DEFAULT_ORIGIN;
+
+ // Calculate total distance traveled based on IP locations
+ const distanceTraveled = calculateTotalDistance(countryCodes, origin);
+
+ // Write full name of countries for display
+ const uniqueCountries = countryCodes.map((country: string) => {
+ // Map country codes to full names using COUNTRIES constant
+ return COUNTRIES[country] || country;
});
- // write full name of countries
- const uniqueCountries = tinybirdData.data[0]?.unique_countries?.map(
- (country: string) => {
- // Map country codes to full names using COUNTRIES constant
- return COUNTRIES[country] || country;
- },
- ) || [];
+ console.log("uniqueCountries", uniqueCountries);
+ console.log("totalDuration", totalDuration);
+ console.log("distanceTraveled", distanceTraveled);
return {
year: currentYear,
- totalDocuments: teamCounts?._count.documents || 0,
- totalLinks: teamCounts?._count.links || 0,
- totalViews: teamCounts?._count.views || 0,
+ totalDocuments: documents.length || 0,
+ totalLinks: links || 0,
+ totalViews: views || 0,
totalDatarooms: dataroomCounts || 0,
mostViewedDocument: mostViewedDoc[0]
? {
@@ -212,7 +501,8 @@ export async function getYearInReviewStats(teamId: string, year?: number) {
viewCount: Number(mostActiveViewer[0].viewCount),
}
: null,
- totalDuration: tinybirdData.data[0]?.total_duration || 0,
- uniqueCountries: uniqueCountries,
+ totalDuration: totalDuration || 0,
+ uniqueCountries: uniqueCountries || [],
+ distanceTraveled: distanceTraveled || 0,
};
}
diff --git a/pages/api/teams/[teamId]/yearly-recap.ts b/pages/api/teams/[teamId]/yearly-recap.ts
index 8c306857..a71c0ccf 100644
--- a/pages/api/teams/[teamId]/yearly-recap.ts
+++ b/pages/api/teams/[teamId]/yearly-recap.ts
@@ -1,33 +1,62 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { LOCALHOST_GEO_DATA, getGeoData } from "@/lib/utils/geo";
import { getYearInReviewStats } from "@/lib/year-in-review/get-stats";
+import { authOptions } from "../../auth/[...nextauth]";
+
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ message: "Unauthorized" });
+ }
+
if (req.method !== "GET") {
return res.status(405).json({ message: "Method not allowed" });
}
const { teamId } = req.query as { teamId: string };
- const year = req.query.year
- ? parseInt(req.query.year as string)
- : undefined;
+ const year = req.query.year ? parseInt(req.query.year as string) : undefined;
if (!teamId) {
return res.status(400).json({ message: "Team ID is required" });
}
try {
- const stats = await getYearInReviewStats(teamId, year);
+ const userId = (session.user as CustomUser).id;
+
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: {
+ userId_teamId: {
+ userId,
+ teamId,
+ },
+ },
+ });
+ if (!teamAccess) {
+ return res.status(401).json({ message: "Unauthorized" });
+ }
+
+ // Get user's geo data from request IP for distance calculation
+ const geo = getGeoData(req.headers);
+ const userGeo = {
+ latitude: geo.latitude || LOCALHOST_GEO_DATA.latitude,
+ longitude: geo.longitude || LOCALHOST_GEO_DATA.longitude,
+ };
+
+ const stats = await getYearInReviewStats(teamId, year, userGeo);
return res.status(200).json(stats);
} catch (error) {
console.error("Error fetching yearly recap stats:", error);
return res.status(500).json({
message: "Internal server error",
- error: error instanceof Error ? error.message : "Unknown error",
});
}
}
-