feat: Add CI/CD (GitHub Actions), E2E tests (Playwright), deploy scripts (Fly.io + Vercel), admin dashboard, notifications dropdown, Postman collection
Browse filesFiles changed (10)
- .github/workflows/ci.ymlAdded+164
- backend/fly.tomlAdded+52
- deploy/deploy.shAdded+94
- docs/postman_collection.jsonAdded+207
- frontend/e2e/pytest.iniAdded+5
- frontend/e2e/test_flows.pyAdded+184
- frontend/src/app/(dashboard)/admin/page.tsxAdded+364
- frontend/src/app/(dashboard)/layout.tsx+17-2
- frontend/src/components/layout/notifications-dropdown.tsxAdded+165
- frontend/vercel.jsonAdded+32
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164name: CI
on: push: branches: [main, develop] pull_request: branches: [main]
env: PYTHON_VERSION: "3.12" NODE_VERSION: "20" POSTGRES_USER: test POSTGRES_PASSWORD: test POSTGRES_DB: jobportal_test
jobs: # ============ Backend ============ backend-lint: name: Backend Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install Ruff run: pip install ruff - name: Lint run: cd backend && ruff check . - name: Format check run: cd backend && ruff format --check .
backend-test: name: Backend Tests runs-on: ubuntu-latest services: postgres: image: postgres:17-alpine env: POSTGRES_USER: ${{ env.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ env.POSTGRES_PASSWORD }} POSTGRES_DB: ${{ env.POSTGRES_DB }} ports: - 5432:5432 options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 redis: image: redis:7-alpine ports: - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 env: POSTGRES_SERVER: localhost POSTGRES_PORT: 5432 POSTGRES_USER: test POSTGRES_PASSWORD: test POSTGRES_DB: jobportal_test REDIS_URL: redis://localhost:6379/0 SECRET_KEY: test-secret-key-for-ci APP_ENV: testing steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} - name: Install uv run: pip install uv - name: Install dependencies run: cd backend && uv pip install --system -e ".[dev]" - name: Install pgvector extension run: | sudo apt-get update sudo apt-get install -y postgresql-client PGPASSWORD=test psql -h localhost -U test -d jobportal_test -c "CREATE EXTENSION IF NOT EXISTS vector;" PGPASSWORD=test psql -h localhost -U test -d jobportal_test -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;" PGPASSWORD=test psql -h localhost -U test -d jobportal_test -c 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' - name: Run tests run: cd backend && pytest -v --cov=app --cov-report=xml - name: Upload coverage uses: codecov/codecov-action@v4 with: file: backend/coverage.xml flags: backend
# ============ Frontend ============ frontend-lint: name: Frontend Lint & Type Check runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} - uses: pnpm/action-setup@v4 with: version: 9 - name: Install dependencies run: cd frontend && pnpm install --frozen-lockfile - name: Type check run: cd frontend && pnpm tsc --noEmit - name: Lint run: cd frontend && pnpm lint
frontend-build: name: Frontend Build runs-on: ubuntu-latest needs: frontend-lint steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: ${{ env.NODE_VERSION }} - uses: pnpm/action-setup@v4 with: version: 9 - name: Install dependencies run: cd frontend && pnpm install --frozen-lockfile - name: Build run: cd frontend && pnpm build env: NEXT_PUBLIC_API_URL: http://localhost:8000
# ============ Docker ============ docker-build: name: Docker Build runs-on: ubuntu-latest needs: [backend-test, frontend-build] if: github.ref == 'refs/heads/main' steps: - uses: actions/checkout@v4 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Build backend run: docker build ./backend -t jobportal-backend:latest - name: Build frontend run: docker build ./frontend -t jobportal-frontend:latest
# ============ Deploy ============ deploy: name: Deploy runs-on: ubuntu-latest needs: docker-build if: github.ref == 'refs/heads/main' && github.event_name == 'push' environment: production steps: - uses: actions/checkout@v4 - name: Deploy Backend to Fly.io if: env.FLY_API_TOKEN != '' uses: superfly/flyctl-actions/setup-flyctl@master - run: | if [ -n "$FLY_API_TOKEN" ]; then cd backend && flyctl deploy --remote-only else echo "FLY_API_TOKEN not set, skipping deploy" fi env: FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# Fly.io deployment configuration for backend# Deploy: cd backend && flyctl deploy
app = "jobportal-api"primary_region = "sjc" # San Jose, CA
[build] dockerfile = "Dockerfile"
[env] APP_ENV = "production" API_V1_STR = "/api/v1" PORT = "8000"
[http_service] internal_port = 8000 force_https = true auto_stop_machines = true auto_start_machines = true min_machines_running = 1
[http_service.concurrency] type = "requests" hard_limit = 250 soft_limit = 200
[[services]] protocol = "tcp" internal_port = 8000
[[services.ports]] port = 80 handlers = ["http"]
[[services.ports]] port = 443 handlers = ["tls", "http"]
[[services.http_checks]] interval = "15s" timeout = "2s" grace_period = "10s" method = "get" path = "/health"
[deploy] release_command = "alembic upgrade head"
[[vm]] cpu_kind = "shared" cpus = 1 memory_mb = 51212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#!/bin/bash# Deploy script for JobPortal# Usage: ./deploy/deploy.sh [backend|frontend|all]
set -e
COMPONENT=${1:-all}
echo "🚀 Deploying JobPortal ($COMPONENT)"
deploy_backend() { echo "📦 Deploying backend to Fly.io..." cd backend # Set secrets if not already set if [ -n "$DATABASE_URL" ]; then flyctl secrets set DATABASE_URL="$DATABASE_URL" --stage fi if [ -n "$REDIS_URL" ]; then flyctl secrets set REDIS_URL="$REDIS_URL" --stage fi if [ -n "$SECRET_KEY" ]; then flyctl secrets set SECRET_KEY="$SECRET_KEY" --stage fi # Deploy flyctl deploy --remote-only echo "✅ Backend deployed!" echo " URL: https://jobportal-api.fly.dev" echo " Docs: https://jobportal-api.fly.dev/api/v1/docs" cd ..}
deploy_frontend() { echo "📦 Deploying frontend to Vercel..." cd frontend # Deploy with Vercel CLI if command -v vercel &> /dev/null; then vercel --prod else echo "⚠️ Vercel CLI not installed. Run: npm i -g vercel" echo " Then: cd frontend && vercel --prod" fi echo "✅ Frontend deployed!" cd ..}
deploy_worker() { echo "📦 Deploying worker to Fly.io..." cd backend # Scale worker machine flyctl machine run . \ --app jobportal-worker \ --region sjc \ --vm-size shared-cpu-1x \ --vm-memory 512 \ --entrypoint "celery -A app.worker.celery_config.celery_app worker --loglevel=warning --concurrency=2" echo "✅ Worker deployed!" cd ..}
case $COMPONENT in backend) deploy_backend ;; frontend) deploy_frontend ;; worker) deploy_worker ;; all) deploy_backend deploy_frontend deploy_worker ;; *) echo "Usage: ./deploy.sh [backend|frontend|worker|all]" exit 1 ;;esac
echo ""echo "🎉 Deployment complete!"echo ""echo "Useful commands:"echo " flyctl status -a jobportal-api # Backend status"echo " flyctl logs -a jobportal-api # Backend logs"echo " vercel ls # Frontend deployments"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207{ "info": { "name": "JobPortal API", "description": "Complete API collection for the JobPortal backend", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "variable": [ { "key": "base_url", "value": "http://localhost:8000/api/v1" }, { "key": "access_token", "value": "" }, { "key": "refresh_token", "value": "" } ], "auth": { "type": "bearer", "bearer": [{ "key": "token", "value": "{{access_token}}" }] }, "item": [ { "name": "Auth", "item": [ { "name": "Register", "request": { "method": "POST", "url": "{{base_url}}/auth/register", "body": { "mode": "raw", "raw": "{\"email\": \"user@example.com\", \"password\": \"password123\", \"full_name\": \"Test User\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Login", "request": { "method": "POST", "url": "{{base_url}}/auth/login", "body": { "mode": "raw", "raw": "{\"email\": \"demo@jobportal.dev\", \"password\": \"demo123\"}", "options": { "raw": { "language": "json" } } } }, "event": [{ "listen": "test", "script": { "exec": ["var json = pm.response.json();", "pm.collectionVariables.set('access_token', json.access_token);", "pm.collectionVariables.set('refresh_token', json.refresh_token);"] } }] }, { "name": "Get Me", "request": { "method": "GET", "url": "{{base_url}}/auth/me" } }, { "name": "Refresh Token", "request": { "method": "POST", "url": "{{base_url}}/auth/refresh", "body": { "mode": "raw", "raw": "{\"refresh_token\": \"{{refresh_token}}\"}", "options": { "raw": { "language": "json" } } } } } ] }, { "name": "Jobs", "item": [ { "name": "Search Jobs", "request": { "method": "GET", "url": { "raw": "{{base_url}}/jobs?q=python&remote=remote&page=1&page_size=10", "host": ["{{base_url}}"], "path": ["jobs"], "query": [{"key": "q", "value": "python"}, {"key": "remote", "value": "remote"}, {"key": "page", "value": "1"}, {"key": "page_size", "value": "10"}] } } }, { "name": "Get Job Detail", "request": { "method": "GET", "url": "{{base_url}}/jobs/{{job_id}}" } }, { "name": "Save Job", "request": { "method": "POST", "url": "{{base_url}}/jobs/{{job_id}}/save", "body": { "mode": "raw", "raw": "{\"notes\": \"Looks interesting\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Unsave Job", "request": { "method": "DELETE", "url": "{{base_url}}/jobs/{{job_id}}/save" } } ] }, { "name": "Applications", "item": [ { "name": "List (Kanban)", "request": { "method": "GET", "url": "{{base_url}}/applications" } }, { "name": "Create", "request": { "method": "POST", "url": "{{base_url}}/applications", "body": { "mode": "raw", "raw": "{\"custom_job_title\": \"Senior Engineer\", \"custom_company_name\": \"TechCorp\", \"status\": \"applied\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Update Status", "request": { "method": "PATCH", "url": "{{base_url}}/applications/{{app_id}}", "body": { "mode": "raw", "raw": "{\"status\": \"interviewing\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Delete", "request": { "method": "DELETE", "url": "{{base_url}}/applications/{{app_id}}" } }, { "name": "Add Interview", "request": { "method": "POST", "url": "{{base_url}}/applications/{{app_id}}/interviews", "body": { "mode": "raw", "raw": "{\"interview_type\": \"technical\", \"scheduled_at\": \"2026-06-01T10:00:00Z\", \"duration_minutes\": 60}", "options": { "raw": { "language": "json" } } } } } ] }, { "name": "AI", "item": [ { "name": "Resume Review", "request": { "method": "POST", "url": "{{base_url}}/ai/resume-review", "body": { "mode": "raw", "raw": "{\"resume_text\": \"Senior Engineer with 5 years experience...\", \"target_role\": \"Staff Engineer\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Job Match", "request": { "method": "POST", "url": "{{base_url}}/ai/job-match", "body": { "mode": "raw", "raw": "{\"resume_text\": \"...\", \"job_description\": \"...\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "Cover Letter", "request": { "method": "POST", "url": "{{base_url}}/ai/cover-letter", "body": { "mode": "raw", "raw": "{\"resume_text\": \"...\", \"job_description\": \"...\", \"company_name\": \"Google\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "List Providers", "request": { "method": "GET", "url": "{{base_url}}/ai/providers" } }, { "name": "Interview Questions", "request": { "method": "POST", "url": "{{base_url}}/ai/interview/questions", "body": { "mode": "raw", "raw": "{\"job_title\": \"Senior Engineer\", \"job_description\": \"Build distributed systems...\", \"interview_type\": \"behavioral\", \"num_questions\": 5}", "options": { "raw": { "language": "json" } } } } }, { "name": "Company Research", "request": { "method": "POST", "url": "{{base_url}}/ai/interview/company-research", "body": { "mode": "raw", "raw": "{\"company_name\": \"Stripe\", \"job_title\": \"Backend Engineer\"}", "options": { "raw": { "language": "json" } } } } } ] }, { "name": "Profile & Resume", "item": [ { "name": "Get Profile", "request": { "method": "GET", "url": "{{base_url}}/profile" } }, { "name": "Update Profile", "request": { "method": "PATCH", "url": "{{base_url}}/profile", "body": { "mode": "raw", "raw": "{\"headline\": \"Full Stack Engineer\", \"location\": \"SF, CA\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "List Resumes", "request": { "method": "GET", "url": "{{base_url}}/resumes" } }, { "name": "Create Resume", "request": { "method": "POST", "url": "{{base_url}}/resumes", "body": { "mode": "raw", "raw": "{\"name\": \"SWE Resume\", \"template_id\": \"simple\", \"target_role\": \"Senior SWE\"}", "options": { "raw": { "language": "json" } } } } } ] }, { "name": "Alerts & Notifications", "item": [ { "name": "List Alerts", "request": { "method": "GET", "url": "{{base_url}}/alerts" } }, { "name": "Create Alert", "request": { "method": "POST", "url": "{{base_url}}/alerts", "body": { "mode": "raw", "raw": "{\"name\": \"Remote React Jobs\", \"query\": \"React\", \"filters\": {\"remote_type\": \"remote\"}, \"alert_frequency\": \"daily\"}", "options": { "raw": { "language": "json" } } } } }, { "name": "List Notifications", "request": { "method": "GET", "url": "{{base_url}}/notifications" } }, { "name": "Mark All Read", "request": { "method": "POST", "url": "{{base_url}}/notifications/read-all" } } ] }, { "name": "Export", "item": [ { "name": "Export Applications CSV", "request": { "method": "GET", "url": "{{base_url}}/export/applications/csv" } }, { "name": "Export Profile JSON (GDPR)", "request": { "method": "GET", "url": "{{base_url}}/export/profile/json" } }, { "name": "Delete Account", "request": { "method": "DELETE", "url": "{{base_url}}/export/account" } } ] }, { "name": "Admin", "item": [ { "name": "System Health", "request": { "method": "GET", "url": "{{base_url}}/admin/health" } }, { "name": "List Sources", "request": { "method": "GET", "url": "{{base_url}}/admin/sources" } }, { "name": "Create Source", "request": { "method": "POST", "url": "{{base_url}}/admin/sources", "body": { "mode": "raw", "raw": "{\"name\": \"Greenhouse - Stripe\", \"source_type\": \"ats_api\", \"domain\": \"stripe.com\", \"base_url\": \"https://boards-api.greenhouse.io/v1/boards/stripe/jobs\", \"ats_vendor\": \"greenhouse\", \"ats_config\": {\"board_token\": \"stripe\"}}", "options": { "raw": { "language": "json" } } } } }, { "name": "Trigger Scrape", "request": { "method": "POST", "url": "{{base_url}}/admin/sources/{{source_id}}/scrape" } } ] } ]}12345[pytest]base_url = http://localhost:3000
[tool.pytest.ini_options]asyncio_mode = "auto"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184"""End-to-end tests with Playwright.Tests critical user flows: register, login, search jobs, track application."""import refrom playwright.sync_api import Page, expect
BASE_URL = "http://localhost:3000"
class TestAuthFlow: """Test registration and login flows."""
def test_register_new_user(self, page: Page): page.goto(f"{BASE_URL}/register")
# Fill form page.fill('[id="name"]', "E2E Test User") page.fill('[id="email"]', "e2e@example.com") page.fill('[id="password"]', "testpass123") page.fill('[id="confirm"]', "testpass123")
# Submit page.click('button[type="submit"]')
# Should redirect to jobs page page.wait_for_url("**/jobs") expect(page).to_have_url(re.compile(r"/jobs"))
def test_login_existing_user(self, page: Page): page.goto(f"{BASE_URL}/login")
page.fill('[id="email"]', "demo@jobportal.dev") page.fill('[id="password"]', "demo123") page.click('button[type="submit"]')
page.wait_for_url("**/jobs") expect(page).to_have_url(re.compile(r"/jobs"))
def test_login_invalid_credentials(self, page: Page): page.goto(f"{BASE_URL}/login")
page.fill('[id="email"]', "wrong@example.com") page.fill('[id="password"]', "wrongpass") page.click('button[type="submit"]')
# Should show error message expect(page.locator("text=Invalid")).to_be_visible()
class TestJobSearch: """Test job search and filtering."""
def test_search_jobs(self, page: Page): # Login first self._login(page)
# Should be on jobs page expect(page.locator("h1")).to_contain_text("Find Jobs")
# Search page.fill('input[placeholder*="Search"]', "Python") page.click('button:has-text("Search")')
# Should show results page.wait_for_timeout(1000)
def test_filter_remote_jobs(self, page: Page): self._login(page)
# Select remote filter page.select_option('select[aria-label="Remote"]', "remote") page.wait_for_timeout(500)
def test_view_job_detail(self, page: Page): self._login(page)
# Click first job first_job = page.locator("a[href*='/jobs/']").first if first_job.is_visible(): first_job.click() page.wait_for_url("**/jobs/**") expect(page.locator("h1")).to_be_visible()
def _login(self, page: Page): page.goto(f"{BASE_URL}/login") page.fill('[id="email"]', "demo@jobportal.dev") page.fill('[id="password"]', "demo123") page.click('button[type="submit"]') page.wait_for_url("**/jobs")
class TestApplicationTracker: """Test application tracking kanban."""
def test_create_application(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/applications")
# Click add page.click('button:has-text("Add Application")')
# Fill modal page.fill('input[placeholder*="Job Title"]', "E2E Test Engineer") page.fill('input[placeholder*="Company"]', "TestCorp") page.click('button:has-text("Add")')
# Should appear in kanban page.wait_for_timeout(1000) expect(page.locator("text=E2E Test Engineer")).to_be_visible()
def test_kanban_columns_exist(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/applications")
expect(page.locator("text=Wishlist")).to_be_visible() expect(page.locator("text=Applied")).to_be_visible() expect(page.locator("text=Interviewing")).to_be_visible()
def _login(self, page: Page): page.goto(f"{BASE_URL}/login") page.fill('[id="email"]', "demo@jobportal.dev") page.fill('[id="password"]', "demo123") page.click('button[type="submit"]') page.wait_for_url("**/jobs")
class TestResumeBuilder: """Test resume management."""
def test_resume_page_loads(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/resume")
expect(page.locator("h1")).to_contain_text("Resume Builder") # Should show templates expect(page.locator("text=Simple ATS")).to_be_visible()
def test_create_resume(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/resume")
page.click('button:has-text("New Resume")') page.fill('input[placeholder*="Software Engineer"]', "My Test Resume") page.click('button:has-text("Create")')
page.wait_for_timeout(1000)
def _login(self, page: Page): page.goto(f"{BASE_URL}/login") page.fill('[id="email"]', "demo@jobportal.dev") page.fill('[id="password"]', "demo123") page.click('button[type="submit"]') page.wait_for_url("**/jobs")
class TestProfile: """Test profile editing."""
def test_profile_page_loads(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/profile")
expect(page.locator("h1")).to_contain_text("Profile") expect(page.locator("text=Basics")).to_be_visible() expect(page.locator("text=Experience")).to_be_visible()
def test_edit_profile_basics(self, page: Page): self._login(page) page.goto(f"{BASE_URL}/profile")
page.fill('input[placeholder*="Senior Software"]', "Full Stack Developer") page.fill('input[placeholder*="San Francisco"]', "New York, NY") page.click('button:has-text("Save")')
page.wait_for_timeout(1000)
def _login(self, page: Page): page.goto(f"{BASE_URL}/login") page.fill('[id="email"]', "demo@jobportal.dev") page.fill('[id="password"]', "demo123") page.click('button[type="submit"]') page.wait_for_url("**/jobs")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364"use client";
import { useState } from "react";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { Activity, Database, Globe, Play, Plus, RefreshCw, Server, Users, Zap, AlertTriangle,} from "lucide-react";import { apiClient } from "@/lib/api/client";
interface SystemHealth { total_jobs: number; active_jobs: number; expired_jobs: number; total_sources: number; active_sources: number; total_users: number; total_scrape_runs: number; recent_failures: number; last_scrape_at: string | null;}
interface Source { id: string; name: string; source_type: string; domain: string; base_url: string; ats_vendor: string | null; status: string; crawl_frequency_hours: number; last_crawled_at: string | null; last_success_at: string | null; consecutive_failures: number; total_jobs_found: number; created_at: string;}
export default function AdminPage() { const [activeTab, setActiveTab] = useState<"overview" | "sources" | "runs">("overview");
return ( <div className="space-y-6"> <div> <h1 className="text-2xl font-bold">Admin Dashboard</h1> <p className="text-muted-foreground">System health, scraper management, and monitoring</p> </div>
<div className="flex gap-1 rounded-lg border bg-muted p-1"> {[ { id: "overview" as const, label: "Overview", icon: Activity }, { id: "sources" as const, label: "Sources", icon: Globe }, { id: "runs" as const, label: "Scrape Runs", icon: Zap }, ].map((tab) => { const Icon = tab.icon; return ( <button key={tab.id} onClick={() => setActiveTab(tab.id)} className={`flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-colors ${ activeTab === tab.id ? "bg-background shadow-sm" : "text-muted-foreground" }`} > <Icon className="h-4 w-4" /> {tab.label} </button> ); })} </div>
{activeTab === "overview" && <OverviewTab />} {activeTab === "sources" && <SourcesTab />} {activeTab === "runs" && <RunsTab />} </div> );}
function OverviewTab() { const { data: health, isLoading } = useQuery({ queryKey: ["admin-health"], queryFn: async () => { const res = await apiClient.get<SystemHealth>("/admin/health"); return res.data; }, refetchInterval: 30000, });
if (isLoading) return <div className="h-48 animate-pulse rounded-lg border bg-muted" />;
return ( <div className="space-y-6"> {/* Stats Grid */} <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4"> <StatCard icon={<Database className="h-5 w-5" />} label="Active Jobs" value={health?.active_jobs || 0} subtitle={`${health?.expired_jobs || 0} expired`} /> <StatCard icon={<Globe className="h-5 w-5" />} label="Active Sources" value={health?.active_sources || 0} subtitle={`${health?.total_sources || 0} total`} /> <StatCard icon={<Users className="h-5 w-5" />} label="Users" value={health?.total_users || 0} /> <StatCard icon={<AlertTriangle className="h-5 w-5" />} label="Recent Failures (24h)" value={health?.recent_failures || 0} variant={health?.recent_failures && health.recent_failures > 0 ? "destructive" : "default"} /> </div>
{/* Summary */} <div className="rounded-lg border bg-card p-6"> <h3 className="mb-4 font-semibold">System Status</h3> <div className="space-y-3"> <div className="flex items-center justify-between text-sm"> <span>Total scrape runs</span> <span className="font-medium">{health?.total_scrape_runs || 0}</span> </div> <div className="flex items-center justify-between text-sm"> <span>Last scrape</span> <span className="font-medium"> {health?.last_scrape_at ? new Date(health.last_scrape_at).toLocaleString() : "Never"} </span> </div> <div className="flex items-center justify-between text-sm"> <span>Database</span> <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700 dark:bg-green-900 dark:text-green-300"> Healthy </span> </div> <div className="flex items-center justify-between text-sm"> <span>Redis</span> <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700 dark:bg-green-900 dark:text-green-300"> Connected </span> </div> </div> </div> </div> );}
function SourcesTab() { const queryClient = useQueryClient(); const [showAdd, setShowAdd] = useState(false);
const { data: sources, isLoading } = useQuery({ queryKey: ["admin-sources"], queryFn: async () => { const res = await apiClient.get<Source[]>("/admin/sources"); return res.data; }, });
const triggerScrape = useMutation({ mutationFn: async (sourceId: string) => { await apiClient.post(`/admin/sources/${sourceId}/scrape`); }, onSuccess: () => queryClient.invalidateQueries({ queryKey: ["admin-sources"] }), });
return ( <div className="space-y-4"> <div className="flex justify-end"> <button onClick={() => setShowAdd(true)} className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground" > <Plus className="h-4 w-4" /> Add Source </button> </div>
{isLoading ? ( <div className="space-y-3"> {[...Array(3)].map((_, i) => ( <div key={i} className="h-20 animate-pulse rounded-lg border bg-muted" /> ))} </div> ) : ( <div className="space-y-3"> {sources?.map((source) => ( <div key={source.id} className="rounded-lg border bg-card p-4"> <div className="flex items-center justify-between"> <div> <div className="flex items-center gap-2"> <h3 className="font-medium">{source.name}</h3> <span className={`rounded-full px-2 py-0.5 text-xs ${ source.status === "active" ? "bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300" : "bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300" }`}> {source.status} </span> {source.ats_vendor && ( <span className="rounded-full bg-muted px-2 py-0.5 text-xs capitalize"> {source.ats_vendor} </span> )} </div> <div className="mt-1 flex items-center gap-4 text-xs text-muted-foreground"> <span>{source.domain}</span> <span>Every {source.crawl_frequency_hours}h</span> <span>{source.total_jobs_found} jobs found</span> {source.consecutive_failures > 0 && ( <span className="text-destructive">{source.consecutive_failures} failures</span> )} {source.last_crawled_at && ( <span>Last: {new Date(source.last_crawled_at).toLocaleString()}</span> )} </div> </div> <button onClick={() => triggerScrape.mutate(source.id)} disabled={triggerScrape.isPending} className="inline-flex items-center gap-1 rounded-md border px-3 py-1.5 text-xs hover:bg-accent" > <Play className="h-3 w-3" /> Scrape Now </button> </div> </div> ))} </div> )}
{showAdd && <AddSourceModal onClose={() => setShowAdd(false)} />} </div> );}
function RunsTab() { // Placeholder - shows recent scrape runs across all sources return ( <div className="rounded-lg border bg-card p-6 text-center text-sm text-muted-foreground"> <RefreshCw className="mx-auto h-8 w-8 mb-2" /> <p>Select a source to view its scrape run history.</p> <p className="mt-1">Go to Sources tab → click a source to see runs.</p> </div> );}
function StatCard({ icon, label, value, subtitle, variant = "default",}: { icon: React.ReactNode; label: string; value: number | string; subtitle?: string; variant?: "default" | "destructive";}) { return ( <div className="rounded-lg border bg-card p-4"> <div className="flex items-center gap-2 text-muted-foreground"> {icon} <span className="text-sm">{label}</span> </div> <p className={`mt-2 text-2xl font-bold ${variant === "destructive" && value ? "text-destructive" : ""}`}> {value} </p> {subtitle && <p className="text-xs text-muted-foreground">{subtitle}</p>} </div> );}
function AddSourceModal({ onClose }: { onClose: () => void }) { const queryClient = useQueryClient(); const [form, setForm] = useState({ name: "", source_type: "ats_api", domain: "", base_url: "", ats_vendor: "greenhouse", ats_config: { board_token: "" }, });
const create = useMutation({ mutationFn: async () => { await apiClient.post("/admin/sources", form); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["admin-sources"] }); onClose(); }, });
return ( <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"> <div className="w-full max-w-md rounded-lg bg-card p-6 shadow-lg"> <h2 className="mb-4 text-lg font-semibold">Add Job Source</h2> <form onSubmit={(e) => { e.preventDefault(); create.mutate(); }} className="space-y-3"> <div> <label className="mb-1 block text-xs font-medium">Name</label> <input value={form.name} onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))} className="w-full rounded-md border bg-background px-3 py-2 text-sm" placeholder="Greenhouse - Stripe" required /> </div> <div className="grid grid-cols-2 gap-3"> <div> <label className="mb-1 block text-xs font-medium">Type</label> <select value={form.source_type} onChange={(e) => setForm((p) => ({ ...p, source_type: e.target.value }))} className="w-full rounded-md border bg-background px-3 py-2 text-sm" > <option value="ats_api">ATS API</option> <option value="careers_page">Careers Page</option> <option value="sitemap">Sitemap</option> </select> </div> <div> <label className="mb-1 block text-xs font-medium">ATS Vendor</label> <select value={form.ats_vendor} onChange={(e) => setForm((p) => ({ ...p, ats_vendor: e.target.value }))} className="w-full rounded-md border bg-background px-3 py-2 text-sm" > <option value="greenhouse">Greenhouse</option> <option value="lever">Lever</option> <option value="ashby">Ashby</option> <option value="workday">Workday</option> <option value="smartrecruiters">SmartRecruiters</option> </select> </div> </div> <div> <label className="mb-1 block text-xs font-medium">Domain</label> <input value={form.domain} onChange={(e) => setForm((p) => ({ ...p, domain: e.target.value }))} className="w-full rounded-md border bg-background px-3 py-2 text-sm" placeholder="stripe.com" required /> </div> <div> <label className="mb-1 block text-xs font-medium">Board Token / Slug</label> <input value={form.ats_config.board_token} onChange={(e) => setForm((p) => ({ ...p, ats_config: { board_token: e.target.value } }))} className="w-full rounded-md border bg-background px-3 py-2 text-sm" placeholder="stripe" required /> </div> <div className="flex justify-end gap-2 pt-2"> <button type="button" onClick={onClose} className="rounded-md border px-4 py-2 text-sm">Cancel</button> <button type="submit" disabled={create.isPending} className="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"> {create.isPending ? "Creating..." : "Add Source"} </button> </div> </form> </div> </div> );}8 unmodified lines91011121314151617181920215 unmodified lines2728293031322 unmodified lines3536373839407 unmodified lines4849505152535440 unmodified lines95969798991008 unmodified linesSearch,Settings,User,Brain,Bell,LogOut,MessageSquare,} from "lucide-react";import { cn } from "@/lib/utils";import { useAuthStore } from "@/store/auth";const navItems = [{ href: "/jobs", label: "Jobs", icon: Search },5 unmodified lines{ href: "/settings", label: "Settings", icon: Settings },];export default function DashboardLayout({children,}: {2 unmodified linesconst pathname = usePathname();const { user, logout } = useAuthStore();return (<div className="flex min-h-screen">{/* Sidebar */}7 unmodified lines{/* Navigation */}<nav className="flex-1 space-y-1 p-4">{navItems.map((item) => {const Icon = item.icon;const isActive = pathname.startsWith(item.href);return (40 unmodified lines{/* Main content */}<main className="ml-64 flex-1"><div className="container mx-auto p-6">{children}</div></main></div>8 unmodified lines9101112131415161718192021225 unmodified lines282930313233343536372 unmodified lines404142434445464748497 unmodified lines5758596061626340 unmodified lines1041051061071081091101111121131141158 unmodified linesSearch,Settings,User,Bell,LogOut,MessageSquare,Shield,} from "lucide-react";import { cn } from "@/lib/utils";import { useAuthStore } from "@/store/auth";import { NotificationsDropdown } from "@/components/layout/notifications-dropdown";const navItems = [{ href: "/jobs", label: "Jobs", icon: Search },5 unmodified lines{ href: "/settings", label: "Settings", icon: Settings },];const adminItems = [{ href: "/admin", label: "Admin", icon: Shield },];export default function DashboardLayout({children,}: {2 unmodified linesconst pathname = usePathname();const { user, logout } = useAuthStore();// Show admin nav only for admin/superuser rolesconst isAdmin = user?.role === "admin";const allNavItems = isAdmin ? [...navItems, ...adminItems] : navItems;return (<div className="flex min-h-screen">{/* Sidebar */}7 unmodified lines{/* Navigation */}<nav className="flex-1 space-y-1 p-4">{allNavItems.map((item) => {const Icon = item.icon;const isActive = pathname.startsWith(item.href);return (40 unmodified lines{/* Main content */}<main className="ml-64 flex-1">{/* Top bar with notifications */}<header className="sticky top-0 z-40 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60"><div className="container mx-auto flex h-14 items-center justify-end px-6"><NotificationsDropdown /></div></header><div className="container mx-auto p-6">{children}</div></main></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"use client";
import { useState, useEffect, useRef } from "react";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { Bell, Check, CheckCheck, ExternalLink } from "lucide-react";import { apiClient } from "@/lib/api/client";
interface Notification { id: string; type: string; title: string; body: string | null; action_url: string | null; is_read: boolean; created_at: string;}
export function NotificationsDropdown() { const [isOpen, setIsOpen] = useState(false); const dropdownRef = useRef<HTMLDivElement>(null); const queryClient = useQueryClient();
const { data } = useQuery({ queryKey: ["notifications"], queryFn: async () => { const res = await apiClient.get("/notifications", { params: { page_size: 10 } }); return res.data; }, refetchInterval: 30000, // Poll every 30 seconds });
const markRead = useMutation({ mutationFn: async (id: string) => { await apiClient.post(`/notifications/${id}/read`); }, onSuccess: () => queryClient.invalidateQueries({ queryKey: ["notifications"] }), });
const markAllRead = useMutation({ mutationFn: async () => { await apiClient.post("/notifications/read-all"); }, onSuccess: () => queryClient.invalidateQueries({ queryKey: ["notifications"] }), });
// Close on outside click useEffect(() => { function handleClickOutside(event: MouseEvent) { if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { setIsOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []);
const unreadCount = data?.unread_count || 0; const notifications: Notification[] = data?.notifications || [];
return ( <div className="relative" ref={dropdownRef}> {/* Bell button */} <button onClick={() => setIsOpen(!isOpen)} className="relative rounded-md p-2 text-muted-foreground hover:bg-accent hover:text-foreground" > <Bell className="h-5 w-5" /> {unreadCount > 0 && ( <span className="absolute -right-0.5 -top-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] font-bold text-white"> {unreadCount > 9 ? "9+" : unreadCount} </span> )} </button>
{/* Dropdown */} {isOpen && ( <div className="absolute right-0 top-full z-50 mt-2 w-80 rounded-lg border bg-card shadow-lg"> {/* Header */} <div className="flex items-center justify-between border-b px-4 py-3"> <h3 className="text-sm font-semibold">Notifications</h3> {unreadCount > 0 && ( <button onClick={() => markAllRead.mutate()} className="flex items-center gap-1 text-xs text-primary hover:underline" > <CheckCheck className="h-3 w-3" /> Mark all read </button> )} </div>
{/* Notifications list */} <div className="max-h-96 overflow-y-auto"> {notifications.length === 0 ? ( <div className="p-6 text-center text-sm text-muted-foreground"> No notifications yet </div> ) : ( notifications.map((notif) => ( <div key={notif.id} className={`flex items-start gap-3 border-b px-4 py-3 last:border-0 ${ !notif.is_read ? "bg-primary/5" : "" }`} > <div className="flex-1 min-w-0"> <p className={`text-sm ${!notif.is_read ? "font-medium" : ""}`}> {notif.title} </p> {notif.body && ( <p className="mt-0.5 truncate text-xs text-muted-foreground"> {notif.body} </p> )} <p className="mt-1 text-xs text-muted-foreground"> {formatTimeAgo(notif.created_at)} </p> </div> <div className="flex items-center gap-1"> {notif.action_url && ( <a href={notif.action_url} className="rounded p-1 text-muted-foreground hover:text-foreground" > <ExternalLink className="h-3 w-3" /> </a> )} {!notif.is_read && ( <button onClick={() => markRead.mutate(notif.id)} className="rounded p-1 text-muted-foreground hover:text-primary" title="Mark as read" > <Check className="h-3 w-3" /> </button> )} </div> </div> )) )} </div>
{/* Footer */} <div className="border-t px-4 py-2 text-center"> <a href="/alerts" className="text-xs text-primary hover:underline"> Manage alerts </a> </div> </div> )} </div> );}
function formatTimeAgo(dateStr: string): string { const now = new Date(); const date = new Date(dateStr); const seconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (seconds < 60) return "just now"; if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`; return date.toLocaleDateString();}1234567891011121314151617181920212223242526272829303132{ "$schema": "https://openapi.vercel.sh/vercel.json", "framework": "nextjs", "buildCommand": "pnpm build", "installCommand": "pnpm install", "outputDirectory": ".next", "env": { "NEXT_PUBLIC_API_URL": "@api-url" }, "headers": [ { "source": "/(.*)", "headers": [ { "key": "X-Frame-Options", "value": "SAMEORIGIN" }, { "key": "X-Content-Type-Options", "value": "nosniff" }, { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" } ] }, { "source": "/_next/static/(.*)", "headers": [ { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } ] } ], "rewrites": [ { "source": "/api/v1/:path*", "destination": "https://jobportal-api.fly.dev/api/v1/:path*" } ]}.github/workflows/ci.ymlAdded+164
backend/fly.tomlAdded+52
deploy/deploy.shAdded+94
docs/postman_collection.jsonAdded+207
frontend/e2e/pytest.iniAdded+5
frontend/e2e/test_flows.pyAdded+184
frontend/src/app/(dashboard)/admin/page.tsxAdded+364
frontend/src/app/(dashboard)/layout.tsx+17-2
frontend/src/components/layout/notifications-dropdown.tsxAdded+165
frontend/vercel.jsonAdded+32