Skip to content

feat(analytics): add export to CSV and PDF functionality#238

Open
Kritika200520 wants to merge 2 commits into
vishnukothakapu:mainfrom
Kritika200520:feat/export-analytics
Open

feat(analytics): add export to CSV and PDF functionality#238
Kritika200520 wants to merge 2 commits into
vishnukothakapu:mainfrom
Kritika200520:feat/export-analytics

Conversation

@Kritika200520

@Kritika200520 Kritika200520 commented May 26, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds the ability for authenticated users to export their analytics data directly from the dashboard as a CSV file or a PDF report.

Closes #[222]


Changes Made

app/dashboard/AnalyticsOverview.tsx

  • Added an Export dropdown button (with a download icon) to the Analytics overview section
  • Dropdown contains two options: Export CSV and Export PDF
  • Export button only appears when analytics data has loaded (not shown during loading state)
  • CSV export triggers a download via the new /api/analytics/export endpoint
  • PDF export opens a styled printable report in a new browser window using window.print()

app/api/analytics/export/route.ts (new file)

  • New authenticated GET endpoint at /api/analytics/export
  • Returns 401 Unauthorized if the user is not logged in
  • Accepts ?format=csv query param (defaults to csv)
  • CSV includes columns: Timestamp, Platform Link, Referrer, Location, Device, Browser, OS
  • Properly escapes CSV special characters to prevent injection
  • Falls back to JSON format for future extensibility

How to Test

  1. Log in to your dashboard
  2. Navigate to the Analytics section
  3. Wait for data to load — an Export button will appear top-right
  4. Click Export CSV → a .csv file downloads with your full click history
  5. Click Export PDF → a styled print dialog opens with your analytics summary

Acceptance Criteria Met

  • Authenticated API endpoint /api/analytics/export returns formatted data
  • Export controls (CSV and PDF) added to AnalyticsOverview.tsx
  • CSV export downloads click history (timestamps, platform links, referrers, locations)
  • PDF export triggers a structured printable layout
  • Returns 401 if user has no session (security enforced)
  • [x]

Summary by CodeRabbit

  • New Features

    • Export analytics data to CSV (download) and PDF (print-friendly) from the Analytics overview.
    • Export dropdown added to quickly access CSV/PDF export when analytics are loaded.
  • UI

    • Header and card layout adjustments in the Analytics overview.
    • Loading placeholder changed from "..." to "—".

Review Change Stack

@vercel

vercel Bot commented May 26, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the vishnukothakapu's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 76d831dd-aeba-4567-81c5-e6d72f46295f

📥 Commits

Reviewing files that changed from the base of the PR and between 7b1b8c2 and 4a84eb9.

📒 Files selected for processing (2)
  • app/api/analytics/export/route.ts
  • app/dashboard/AnalyticsOverview.tsx

📝 Walkthrough

Walkthrough

Adds a GET API at app/api/analytics/export/route.ts that returns user click events as CSV or JSON, and integrates CSV/PDF export controls into app/dashboard/AnalyticsOverview.tsx with client-side download and printable HTML report generation.

Changes

Analytics Export

Layer / File(s) Summary
Export API Handler
app/api/analytics/export/route.ts
New GET handler authenticates via getServerSession, queries user's click events (including link) ordered by createdAt, and returns CSV (fixed header, per-row mapping, escaping) as an attachment or JSON based on format query param.
Dashboard export UI and helpers
app/dashboard/AnalyticsOverview.tsx
Adds import updates and icons for an Export dropdown, implements exportToCSV (fetches CSV endpoint and triggers download) and exportToPDF (opens a new window, writes printable HTML, calls print()), and conditionally renders the Export menu in the header; minor loading/markup adjustments.

Sequence Diagram

sequenceDiagram
  participant User as User
  participant Dashboard as AnalyticsOverview
  participant ExportAPI as Export API
  participant Prisma as Prisma
  User->>Dashboard: Open AnalyticsOverview
  Dashboard->>ExportAPI: GET /api/analytics/export?format=csv
  ExportAPI->>Prisma: Query click events for user (include link)
  Prisma-->>ExportAPI: Return click records
  ExportAPI-->>Dashboard: Return CSV attachment (or JSON)
  Dashboard-->>User: Trigger CSV download or open printable PDF window
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related Issues

Suggested Reviewers

  • vedhapprakashni

Poem

🐰
I hopped through clicks and trails,
Spun CSVs and printable tales,
Thirty days in tidy rows,
A PDF breeze, the export goes,
Hooray — the dashboard happily grows!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(analytics): add export to CSV and PDF functionality' accurately and concisely summarizes the main changes: adding CSV and PDF export capabilities to the Analytics dashboard. It is specific, clear, and directly reflects the primary objective of the PR.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/api/analytics/export/route.ts`:
- Around line 6-17: The current auth check only tests for a truthy session but
getSession can return an empty session object; update the guard after calling
getSession(req) to verify session.user and session.user.id (e.g., if (!session
|| !session.user || !session.user.id) return new NextResponse("Unauthorized", {
status: 401 })), so the route returns 401 for invalidated/deleted tokens instead
of proceeding and throwing later; modify the logic around getSession and the
NextResponse creation to use this stronger check.
- Around line 30-37: The CSV generation in route.ts builds fields (url, referer,
country, device, browser, os) from user-controlled click values but only escapes
quotes, leaving cells that start with =, +, -, or @ vulnerable to CSV formula
injection; update the sanitization used before appending to csvContent so each
field first strips/escapes internal quotes as currently done and then, if the
raw value begins with any of the dangerous prefix characters, prepend a safe
prefix (for example a single quote) to neutralize spreadsheet formulas before
wrapping in quotes; apply this same fix to the variables url, referer, country,
device, browser, and os used when constructing csvContent.
- Around line 15-35: The code queries prisma.click and reads fields that don't
exist; change the delegate to prisma.clickEvent.findMany and include the related
link (include: { link: true }) so you can access link data; then update CSV
generation to use the ClickEvent schema fields: use
click.createdAt.toISOString(), platform/link value from click.link?.url or
fallback to click.linkId, referrer from click.referrer, location from
click.country, device from click.deviceType, and browser/os from click.userAgent
(or parse userAgent later if needed); also keep the same CSV quoting/replace
logic but applied to those ClickEvent properties and update the header names to
match.

In `@app/dashboard/AnalyticsOverview.tsx`:
- Around line 147-152: Replace the onClick handlers on the Radix
DropdownMenuItem instances so they use the onSelect activation prop instead (for
the items that call exportToCSV and exportToPDF). Locate the DropdownMenuItem
elements that reference exportToCSV and exportToPDF and change their prop from
onClick={...} to onSelect={...} (ensuring the handlers still invoke the same
functions or wrap them in an arrow function if necessary) so keyboard activation
(Enter/Space) triggers the exports.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: cac5ddf5-9e8e-4214-8f5e-b26b476bc202

📥 Commits

Reviewing files that changed from the base of the PR and between 0685853 and 7b1b8c2.

📒 Files selected for processing (2)
  • app/api/analytics/export/route.ts
  • app/dashboard/AnalyticsOverview.tsx

Comment thread app/api/analytics/export/route.ts Outdated
Comment thread app/api/analytics/export/route.ts Outdated
Comment thread app/api/analytics/export/route.ts Outdated
Comment thread app/dashboard/AnalyticsOverview.tsx Outdated
@vercel

vercel Bot commented May 27, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
linkid Ready Ready Preview, Comment Jun 1, 2026 9:41am

@vishnukothakapu

Copy link
Copy Markdown
Owner

Hi @Kritika200520,
The Vercel build is currently failing due to two import issues in "app/api/analytics/export/route.ts".

Issues

  1. "@/lib/db" module cannot be found:

import { prisma } from "@/lib/db";

  1. "getSession" is not exported from "@/lib/auth":

import { getSession } from "@/lib/auth";

The error suggests that "getSession" does not exist in "lib/auth.ts".

Please:

  • verify the correct Prisma import path
  • use the correct auth/session helper exported by "lib/auth.ts"
  • update the imports accordingly

Then push the updated changes.

Comment thread app/api/analytics/export/route.ts Outdated
Comment thread app/api/analytics/export/route.ts Outdated

@Anushreebasics Anushreebasics left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrapping fields in double quotes and escaping internal quotes is fine. Ensure fields with newlines are quoted too (current approach does this).

Comment thread app/dashboard/AnalyticsOverview.tsx
Comment thread app/dashboard/AnalyticsOverview.tsx
Comment thread app/dashboard/AnalyticsOverview.tsx Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants