mirror of
https://github.com/khoaliber/LetterFeed.git
synced 2026-03-02 21:19:13 +00:00
feat: authentication
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { AuthProvider } from "@/contexts/AuthContext"
|
||||
import type { Metadata } from "next"
|
||||
import { Geist, Geist_Mono } from "next/font/google"
|
||||
import "./globals.css"
|
||||
@@ -28,8 +29,10 @@ export default function RootLayout({
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
<Toaster />
|
||||
<AuthProvider>
|
||||
{children}
|
||||
<Toaster />
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
89
frontend/src/app/login/__tests__/page.test.tsx
Normal file
89
frontend/src/app/login/__tests__/page.test.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import LoginPage from "@/app/login/page"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { toast } from "sonner"
|
||||
|
||||
jest.mock("@/hooks/useAuth")
|
||||
jest.mock("sonner", () => ({
|
||||
toast: {
|
||||
error: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockedUseAuth = useAuth as jest.Mock
|
||||
const mockedToast = toast as jest.Mocked<typeof toast>
|
||||
|
||||
describe("LoginPage", () => {
|
||||
const login = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
mockedUseAuth.mockReturnValue({ login })
|
||||
})
|
||||
|
||||
it("renders the login page", () => {
|
||||
render(<LoginPage />)
|
||||
expect(screen.getByText("LetterFeed")).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Username")).toBeInTheDocument()
|
||||
expect(screen.getByLabelText("Password")).toBeInTheDocument()
|
||||
expect(screen.getByRole("button", { name: "Sign In" })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("allows typing in the username and password fields", () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
expect(usernameInput).toHaveValue("test-user")
|
||||
expect(passwordInput).toHaveValue("test-password")
|
||||
})
|
||||
|
||||
it("calls login on form submission with username and password", async () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(login).toHaveBeenCalledWith("test-user", "test-password")
|
||||
})
|
||||
})
|
||||
|
||||
it("does not show an error if login fails, as it is handled by the api layer", async () => {
|
||||
login.mockRejectedValue(new Error("Invalid username or password"))
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(usernameInput, { target: { value: "wrong-user" } })
|
||||
fireEvent.change(passwordInput, { target: { value: "wrong-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(login).toHaveBeenCalled()
|
||||
expect(mockedToast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error if username is not provided", async () => {
|
||||
render(<LoginPage />)
|
||||
const passwordInput = screen.getByLabelText("Password")
|
||||
fireEvent.change(passwordInput, { target: { value: "test-password" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(mockedToast.error).toHaveBeenCalledWith("Please fill in all fields")
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error if password is not provided", async () => {
|
||||
render(<LoginPage />)
|
||||
const usernameInput = screen.getByLabelText("Username")
|
||||
fireEvent.change(usernameInput, { target: { value: "test-user" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In" }))
|
||||
await waitFor(() => {
|
||||
expect(mockedToast.error).toHaveBeenCalledWith("Please fill in all fields")
|
||||
})
|
||||
})
|
||||
})
|
||||
83
frontend/src/app/login/page.tsx
Normal file
83
frontend/src/app/login/page.tsx
Normal file
@@ -0,0 +1,83 @@
|
||||
"use client"
|
||||
|
||||
import type React from "react"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent } from "@/components/ui/card"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import Image from "next/image"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { toast } from "sonner"
|
||||
|
||||
export default function LoginPage() {
|
||||
const [username, setUsername] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const { login } = useAuth()
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!username || !password) {
|
||||
toast.error("Please fill in all fields")
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await login(username, password)
|
||||
} catch {
|
||||
// The error is already toasted by the API layer,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<div className="max-w-md w-full space-y-8 p-8">
|
||||
<div className="text-center">
|
||||
<div className="flex justify-center mb-4">
|
||||
<Image
|
||||
src="/logo.png"
|
||||
alt="LetterFeed Logo"
|
||||
width={48}
|
||||
height={48}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
<h2 className="text-3xl font-bold text-gray-900">LetterFeed</h2>
|
||||
<p className="mt-2 text-gray-600">Sign in to your account</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-6">
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="Enter your username"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="Enter your password"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect, useCallback } from "react"
|
||||
|
||||
import withAuth from "@/components/withAuth"
|
||||
import {
|
||||
getNewsletters,
|
||||
getSettings,
|
||||
@@ -15,7 +17,7 @@ import { EmptyState } from "@/components/letterfeed/EmptyState"
|
||||
import { NewsletterDialog } from "@/components/letterfeed/NewsletterDialog"
|
||||
import { SettingsDialog } from "@/components/letterfeed/SettingsDialog"
|
||||
|
||||
export default function LetterFeedApp() {
|
||||
function LetterFeedApp() {
|
||||
const [newsletters, setNewsletters] = useState<Newsletter[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [settings, setSettings] = useState<AppSettings | null>(null)
|
||||
@@ -103,3 +105,5 @@ export default function LetterFeedApp() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default withAuth(LetterFeedApp)
|
||||
|
||||
20
frontend/src/components/letterfeed/EmptyState.tsx
Normal file
20
frontend/src/components/letterfeed/EmptyState.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Plus, Rss } from "lucide-react"
|
||||
|
||||
interface EmptyStateProps {
|
||||
onAddNewsletter: () => void
|
||||
}
|
||||
|
||||
export function EmptyState({ onAddNewsletter }: EmptyStateProps) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<Rss className="w-12 h-12 text-gray-400 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-2">No newsletters registered</h3>
|
||||
<p className="text-gray-600 mb-4">Get started by adding your first newsletter</p>
|
||||
<Button onClick={onAddNewsletter}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Your First Newsletter
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
72
frontend/src/components/letterfeed/Header.tsx
Normal file
72
frontend/src/components/letterfeed/Header.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
"use client"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { processEmails } from "@/lib/api"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { LogOut, Mail, Plus, Settings } from "lucide-react"
|
||||
import Image from "next/image"
|
||||
import { toast } from "sonner"
|
||||
|
||||
interface HeaderProps {
|
||||
onOpenAddNewsletter: () => void
|
||||
onOpenSettings: () => void
|
||||
}
|
||||
|
||||
export function Header({ onOpenAddNewsletter, onOpenSettings }: HeaderProps) {
|
||||
const { logout } = useAuth()
|
||||
const handleProcessEmails = async () => {
|
||||
try {
|
||||
await processEmails()
|
||||
toast.success("Email processing started successfully!")
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "An unexpected error occurred."
|
||||
console.error(error)
|
||||
toast.error(message)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col md:flex-row items-center justify-between mb-8">
|
||||
<div className="flex items-center gap-4 mb-4 md:mb-0">
|
||||
<Image
|
||||
src="/logo.png"
|
||||
alt="LetterFeed Logo"
|
||||
width={48}
|
||||
height={48}
|
||||
className="rounded-lg"
|
||||
/>
|
||||
<div>
|
||||
<h1 className="text-2xl md:text-3xl font-bold text-gray-900">LetterFeed</h1>
|
||||
<p className="text-gray-600 mt-1 hidden md:block">
|
||||
Newsletters as RSS feeds
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button onClick={onOpenAddNewsletter}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Newsletter
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" onClick={handleProcessEmails}>
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
Process Now
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" onClick={onOpenSettings}>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
|
||||
<Button variant="outline" onClick={logout}>
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
Logout
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
9
frontend/src/components/letterfeed/LoadingSpinner.tsx
Normal file
9
frontend/src/components/letterfeed/LoadingSpinner.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
export function LoadingSpinner() {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||
<Loader2 className="w-12 h-12 text-gray-400 animate-spin" data-testid="loading-spinner" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
63
frontend/src/components/letterfeed/NewsletterCard.tsx
Normal file
63
frontend/src/components/letterfeed/NewsletterCard.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Rss, Mail, ExternalLink, Edit } from "lucide-react"
|
||||
import { Newsletter, getFeedUrl } from "@/lib/api"
|
||||
|
||||
interface NewsletterCardProps {
|
||||
newsletter: Newsletter
|
||||
onEdit: (newsletter: Newsletter) => void
|
||||
}
|
||||
|
||||
export function NewsletterCard({ newsletter, onEdit }: NewsletterCardProps) {
|
||||
const feedUrl = getFeedUrl(newsletter.id)
|
||||
|
||||
return (
|
||||
<Card className="hover:shadow-md transition-shadow flex flex-col">
|
||||
<CardHeader>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Rss className="w-5 h-5 text-orange-500" />
|
||||
{newsletter.name}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{newsletter.entries_count} entr{newsletter.entries_count !== 1 ? "ies" : "y"}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" onClick={() => onEdit(newsletter)} aria-label="Edit Newsletter">
|
||||
<Edit className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 flex-grow">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center gap-1">
|
||||
<Mail className="w-4 h-4" />
|
||||
Email Addresses
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{newsletter.senders.map((sender) => (
|
||||
<Badge key={sender.id} variant="secondary" className="text-xs">
|
||||
{sender.email}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-gray-700 mb-2">RSS Feed</h4>
|
||||
<a
|
||||
href={feedUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800 hover:underline"
|
||||
>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
{feedUrl}
|
||||
</a>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
210
frontend/src/components/letterfeed/NewsletterDialog.tsx
Normal file
210
frontend/src/components/letterfeed/NewsletterDialog.tsx
Normal file
@@ -0,0 +1,210 @@
|
||||
import { useState, useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Plus } from "lucide-react"
|
||||
import { Newsletter, createNewsletter, updateNewsletter, deleteNewsletter } from "@/lib/api"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
interface NewsletterDialogProps {
|
||||
newsletter?: Newsletter | null
|
||||
isOpen: boolean
|
||||
folderOptions: string[]
|
||||
onOpenChange: (isOpen: boolean) => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
const getInitialState = (newsletter: Newsletter | null | undefined) => {
|
||||
if (newsletter) {
|
||||
return {
|
||||
name: newsletter.name,
|
||||
emails: newsletter.senders.map((s) => s.email),
|
||||
move_to_folder: newsletter.move_to_folder || "",
|
||||
extract_content: newsletter.extract_content,
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: "",
|
||||
emails: [""],
|
||||
move_to_folder: "",
|
||||
extract_content: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function NewsletterDialog({ newsletter, isOpen, folderOptions, onOpenChange, onSuccess }: NewsletterDialogProps) {
|
||||
const isEditMode = !!newsletter
|
||||
const [formData, setFormData] = useState(getInitialState(newsletter))
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setFormData(getInitialState(newsletter))
|
||||
}
|
||||
}, [isOpen, newsletter])
|
||||
|
||||
const handleEmailChange = (index: number, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
emails: prev.emails.map((email, i) => (i === index ? value : email)),
|
||||
}))
|
||||
}
|
||||
|
||||
const handleAddEmail = () => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
emails: [...prev.emails, ""],
|
||||
}))
|
||||
}
|
||||
|
||||
const handleRemoveEmail = (index: number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
emails: prev.emails.filter((_, i) => i !== index),
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formData.name || !formData.emails.some((email) => email.trim())) {
|
||||
return
|
||||
}
|
||||
|
||||
const payload = {
|
||||
name: formData.name,
|
||||
sender_emails: formData.emails.filter((email) => email.trim()),
|
||||
move_to_folder: formData.move_to_folder,
|
||||
extract_content: formData.extract_content,
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEditMode) {
|
||||
await updateNewsletter(newsletter.id, payload)
|
||||
} else {
|
||||
await createNewsletter(payload)
|
||||
}
|
||||
onOpenChange(false)
|
||||
onSuccess()
|
||||
} catch (error) {
|
||||
console.error(`Failed to ${isEditMode ? "update" : "create"} newsletter:`, error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (isEditMode && window.confirm(`Are you sure you want to delete the "${newsletter.name}" newsletter?`)) {
|
||||
try {
|
||||
await deleteNewsletter(newsletter.id)
|
||||
onOpenChange(false)
|
||||
onSuccess()
|
||||
} catch (error) {
|
||||
console.error("Failed to delete newsletter:", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{isEditMode ? "Edit" : "Register New"} Newsletter</DialogTitle>
|
||||
<DialogDescription>
|
||||
{isEditMode ? `Update the details for ${newsletter.name}.` : "Add a new newsletter."}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">Newsletter Name</Label>
|
||||
<Input
|
||||
id="name"
|
||||
value={formData.name}
|
||||
onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
|
||||
placeholder="Enter newsletter name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="move_to_folder">Move To Folder</Label>
|
||||
<Select
|
||||
value={formData.move_to_folder || "None"}
|
||||
onValueChange={(value) =>
|
||||
setFormData((prev) => ({ ...prev, move_to_folder: value === "None" ? "" : value }))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select folder or leave empty" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="None">Default (use global setting)</SelectItem>
|
||||
{folderOptions.map((folder) => (
|
||||
<SelectItem key={folder} value={folder}>
|
||||
{folder}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Email Addresses</Label>
|
||||
{formData.emails.map((email, index) => (
|
||||
<div key={index} className="flex gap-2">
|
||||
<Input
|
||||
value={email}
|
||||
onChange={(e) => handleEmailChange(index, e.target.value)}
|
||||
placeholder="Enter email address"
|
||||
type="email"
|
||||
/>
|
||||
{formData.emails.length > 1 && (
|
||||
<Button variant="outline" size="sm" onClick={() => handleRemoveEmail(index)}>
|
||||
Remove
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<Button variant="outline" size="sm" onClick={handleAddEmail} className="w-full bg-transparent">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Add Another Email
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="extract-content"
|
||||
checked={formData.extract_content}
|
||||
onCheckedChange={(checked) =>
|
||||
setFormData((prev) => ({ ...prev, extract_content: !!checked }))
|
||||
}
|
||||
/>
|
||||
<Label htmlFor="extract-content">Extract main content from emails</Label>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter className={isEditMode ? "sm:justify-between" : ""}>
|
||||
{isEditMode && (
|
||||
<Button variant="destructive" onClick={handleDelete}>
|
||||
Delete Newsletter
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSubmit}>
|
||||
{isEditMode ? "Save Changes" : "Register Newsletter"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
17
frontend/src/components/letterfeed/NewsletterList.tsx
Normal file
17
frontend/src/components/letterfeed/NewsletterList.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Newsletter } from "@/lib/api"
|
||||
import { NewsletterCard } from "./NewsletterCard"
|
||||
|
||||
interface NewsletterListProps {
|
||||
newsletters: Newsletter[]
|
||||
onEditNewsletter: (newsletter: Newsletter) => void
|
||||
}
|
||||
|
||||
export function NewsletterList({ newsletters, onEditNewsletter }: NewsletterListProps) {
|
||||
return (
|
||||
<div className="grid gap-4 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3">
|
||||
{newsletters.map((newsletter) => (
|
||||
<NewsletterCard key={newsletter.id} newsletter={newsletter} onEdit={onEditNewsletter} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
290
frontend/src/components/letterfeed/SettingsDialog.tsx
Normal file
290
frontend/src/components/letterfeed/SettingsDialog.tsx
Normal file
@@ -0,0 +1,290 @@
|
||||
import { useState, useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Loader2, CheckCircle, XCircle } from "lucide-react"
|
||||
import {
|
||||
Settings as AppSettings,
|
||||
SettingsCreate,
|
||||
updateSettings,
|
||||
testImapConnection,
|
||||
} from "@/lib/api"
|
||||
import { toast } from "sonner"
|
||||
|
||||
interface SettingsDialogProps {
|
||||
settings: AppSettings
|
||||
folderOptions: string[]
|
||||
isOpen: boolean
|
||||
onOpenChange: (isOpen: boolean) => void
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function SettingsDialog({
|
||||
settings,
|
||||
folderOptions,
|
||||
isOpen,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
}: SettingsDialogProps) {
|
||||
const [currentSettings, setCurrentSettings] = useState<SettingsCreate | null>(
|
||||
null
|
||||
)
|
||||
const [testConnectionStatus, setTestConnectionStatus] = useState<
|
||||
"idle" | "loading" | "success" | "error"
|
||||
>("idle")
|
||||
const [testConnectionMessage, setTestConnectionMessage] = useState("")
|
||||
|
||||
useEffect(() => {
|
||||
if (settings) {
|
||||
setCurrentSettings({ ...settings, imap_password: "" })
|
||||
}
|
||||
}, [settings])
|
||||
|
||||
if (!currentSettings) return null
|
||||
|
||||
const handleSettingsChange = <K extends keyof SettingsCreate>(
|
||||
key: K,
|
||||
value: SettingsCreate[K]
|
||||
) => {
|
||||
setCurrentSettings((prev) => (prev ? { ...prev, [key]: value } : null))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!currentSettings) return
|
||||
try {
|
||||
await updateSettings(currentSettings)
|
||||
toast.success("Settings saved successfully!")
|
||||
onOpenChange(false)
|
||||
onSuccess()
|
||||
} catch (error) {
|
||||
console.error("Failed to save settings:", error)
|
||||
toast.error("Failed to save settings.")
|
||||
}
|
||||
}
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
if (!currentSettings) return
|
||||
setTestConnectionStatus("loading")
|
||||
try {
|
||||
await updateSettings(currentSettings)
|
||||
const result = await testImapConnection()
|
||||
setTestConnectionStatus("success")
|
||||
setTestConnectionMessage(result.message)
|
||||
} catch (error: unknown) {
|
||||
setTestConnectionStatus("error")
|
||||
if (error instanceof Error) {
|
||||
setTestConnectionMessage(error.message || "Connection failed")
|
||||
} else {
|
||||
setTestConnectionMessage("An unknown error occurred")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Fields are locked if they are set by environment variables.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-6 py-4">
|
||||
{/* IMAP Configuration */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-medium col-span-1 md:col-span-2">
|
||||
IMAP Configuration
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="imap-server">IMAP Server</Label>
|
||||
<Input
|
||||
id="imap-server"
|
||||
value={currentSettings.imap_server}
|
||||
onChange={(e) =>
|
||||
handleSettingsChange("imap_server", e.target.value)
|
||||
}
|
||||
placeholder="imap.gmail.com"
|
||||
disabled={settings.locked_fields.includes("imap_server")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="imap-username">IMAP Username</Label>
|
||||
<Input
|
||||
id="imap-username"
|
||||
value={currentSettings.imap_username}
|
||||
onChange={(e) =>
|
||||
handleSettingsChange("imap_username", e.target.value)
|
||||
}
|
||||
placeholder="your-email@gmail.com"
|
||||
disabled={settings.locked_fields.includes("imap_username")}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="imap-password">IMAP Password</Label>
|
||||
<Input
|
||||
id="imap-password"
|
||||
type="password"
|
||||
value={currentSettings.imap_password}
|
||||
onChange={(e) =>
|
||||
handleSettingsChange("imap_password", e.target.value)
|
||||
}
|
||||
placeholder="Your password or app password"
|
||||
disabled={settings.locked_fields.includes("imap_password")}
|
||||
/>
|
||||
</div>
|
||||
<div className="pt-2">
|
||||
<Button
|
||||
onClick={handleTestConnection}
|
||||
disabled={testConnectionStatus === "loading"}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
{testConnectionStatus === "loading" && (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
)}
|
||||
Test Connection
|
||||
</Button>
|
||||
{testConnectionStatus !== "idle" && (
|
||||
<div
|
||||
data-testid="connection-status"
|
||||
className={`mt-2 flex items-center text-sm ${
|
||||
testConnectionStatus === "success"
|
||||
? "text-green-600"
|
||||
: "text-red-600"
|
||||
}`}
|
||||
>
|
||||
{testConnectionStatus === "success" && (
|
||||
<CheckCircle className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{testConnectionStatus === "error" && (
|
||||
<XCircle className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{testConnectionMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email Processing */}
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-medium col-span-1 md:col-span-2">
|
||||
Email Processing
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="search-folder">Folder to Search</Label>
|
||||
<Select
|
||||
value={currentSettings.search_folder}
|
||||
onValueChange={(value) =>
|
||||
handleSettingsChange("search_folder", value)
|
||||
}
|
||||
disabled={settings.locked_fields.includes("search_folder")}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select folder" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{folderOptions.map((folder) => (
|
||||
<SelectItem key={folder} value={folder}>
|
||||
{folder}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="move-folder">Move to Folder</Label>
|
||||
<Select
|
||||
value={currentSettings.move_to_folder || "None"}
|
||||
onValueChange={(value) =>
|
||||
handleSettingsChange(
|
||||
"move_to_folder",
|
||||
value === "None" ? null : value
|
||||
)
|
||||
}
|
||||
disabled={settings.locked_fields.includes("move_to_folder")}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select folder or leave empty" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="None">None (Don't move)</SelectItem>
|
||||
{folderOptions.map((folder) => (
|
||||
<SelectItem key={folder} value={folder}>
|
||||
{folder}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="check-interval">Check Interval (minutes)</Label>
|
||||
<Input
|
||||
id="check-interval"
|
||||
type="number"
|
||||
min="1"
|
||||
max="1440"
|
||||
value={currentSettings.email_check_interval}
|
||||
onChange={(e) =>
|
||||
handleSettingsChange(
|
||||
"email_check_interval",
|
||||
Number.parseInt(e.target.value) || 15
|
||||
)
|
||||
}
|
||||
placeholder="15"
|
||||
disabled={settings.locked_fields.includes("email_check_interval")}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 pt-2">
|
||||
<Checkbox
|
||||
id="mark-read"
|
||||
checked={currentSettings.mark_as_read}
|
||||
onCheckedChange={(checked) =>
|
||||
handleSettingsChange("mark_as_read", !!checked)
|
||||
}
|
||||
disabled={settings.locked_fields.includes("mark_as_read")}
|
||||
/>
|
||||
<Label htmlFor="mark-read" className="text-sm font-normal">
|
||||
Mark emails as read
|
||||
</Label>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
id="auto-add"
|
||||
checked={currentSettings.auto_add_new_senders}
|
||||
onCheckedChange={(checked) =>
|
||||
handleSettingsChange("auto_add_new_senders", !!checked)
|
||||
}
|
||||
disabled={settings.locked_fields.includes("auto_add_new_senders")}
|
||||
/>
|
||||
<Label htmlFor="auto-add" className="text-sm font-normal">
|
||||
Auto-add new senders
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>Save Settings</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { EmptyState } from "../EmptyState"
|
||||
|
||||
describe("EmptyState", () => {
|
||||
it("renders the correct content", () => {
|
||||
render(<EmptyState onAddNewsletter={() => {}} />)
|
||||
|
||||
expect(screen.getByText("No newsletters registered")).toBeInTheDocument()
|
||||
expect(screen.getByText("Get started by adding your first newsletter")).toBeInTheDocument()
|
||||
expect(screen.getByRole("button", { name: /Add Your First Newsletter/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("calls onAddNewsletter when the button is clicked", () => {
|
||||
const handleAddNewsletter = jest.fn()
|
||||
render(<EmptyState onAddNewsletter={handleAddNewsletter} />)
|
||||
|
||||
const addButton = screen.getByRole("button", { name: /Add Your First Newsletter/i })
|
||||
fireEvent.click(addButton)
|
||||
|
||||
expect(handleAddNewsletter).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
130
frontend/src/components/letterfeed/__tests__/Header.test.tsx
Normal file
130
frontend/src/components/letterfeed/__tests__/Header.test.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import { Header } from "../Header"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
import { toast } from "sonner"
|
||||
import * as api from "@/lib/api"
|
||||
import { AuthProvider } from "@/contexts/AuthContext"
|
||||
|
||||
jest.mock("@/lib/api")
|
||||
jest.mock("next/navigation", () => ({
|
||||
useRouter: () => ({
|
||||
push: jest.fn(),
|
||||
}),
|
||||
}))
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
|
||||
// Mock the toast functions
|
||||
jest.mock("sonner", () => {
|
||||
const original = jest.requireActual("sonner")
|
||||
return {
|
||||
...original,
|
||||
toast: {
|
||||
success: jest.fn(),
|
||||
error: jest.fn(),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe("Header", () => {
|
||||
const onOpenAddNewsletter = jest.fn()
|
||||
const onOpenSettings = jest.fn()
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
const renderWithAuthProvider = (component: React.ReactElement) => {
|
||||
return render(<AuthProvider>{component}</AuthProvider>)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
consoleError.mockClear()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it("renders the header with title and buttons", () => {
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText("LetterFeed")).toBeInTheDocument()
|
||||
expect(screen.getByText("Add Newsletter")).toBeInTheDocument()
|
||||
expect(screen.getByText("Settings")).toBeInTheDocument()
|
||||
expect(screen.getByText("Process Now")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onOpenAddNewsletter when "Add Newsletter" button is clicked', () => {
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
)
|
||||
fireEvent.click(screen.getByText("Add Newsletter"))
|
||||
expect(onOpenAddNewsletter).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls onOpenSettings when "Settings" button is clicked', () => {
|
||||
renderWithAuthProvider(
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
)
|
||||
fireEvent.click(screen.getByText("Settings"))
|
||||
expect(onOpenSettings).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('calls the process emails API when "Process Now" button is clicked and shows success toast', async () => {
|
||||
mockedApi.processEmails.mockResolvedValue({ message: "Success" })
|
||||
|
||||
renderWithAuthProvider(
|
||||
<>
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
<Toaster />
|
||||
</>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText("Process Now"))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.processEmails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.success).toHaveBeenCalledWith(
|
||||
"Email processing started successfully!"
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error toast if the process emails API call fails", async () => {
|
||||
mockedApi.processEmails.mockRejectedValue(new Error("Failed to process"))
|
||||
|
||||
renderWithAuthProvider(
|
||||
<>
|
||||
<Header
|
||||
onOpenAddNewsletter={onOpenAddNewsletter}
|
||||
onOpenSettings={onOpenSettings}
|
||||
/>
|
||||
<Toaster />
|
||||
</>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByText("Process Now"))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.processEmails).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to process")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import React from "react"
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { LoadingSpinner } from "../LoadingSpinner"
|
||||
|
||||
describe("LoadingSpinner", () => {
|
||||
it("renders the spinner with the correct animation class", () => {
|
||||
render(<LoadingSpinner />)
|
||||
const spinner = screen.getByTestId("loading-spinner")
|
||||
expect(spinner).toBeInTheDocument()
|
||||
expect(spinner).toHaveClass("animate-spin")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { NewsletterCard } from "../NewsletterCard"
|
||||
import { Newsletter } from "@/lib/api"
|
||||
|
||||
// Mock the getFeedUrl function
|
||||
jest.mock("@/lib/api", () => ({
|
||||
...jest.requireActual("@/lib/api"), // import and retain all actual implementations
|
||||
getFeedUrl: jest.fn((id) => `http://mock-api/feeds/${id}`),
|
||||
}))
|
||||
|
||||
const mockNewsletter: Newsletter = {
|
||||
id: 1,
|
||||
name: "Tech Weekly",
|
||||
is_active: true,
|
||||
senders: [
|
||||
{ id: 1, email: "contact@techweekly.com", newsletter_id: 1 },
|
||||
{ id: 2, email: "updates@techweekly.com", newsletter_id: 1 },
|
||||
],
|
||||
entries_count: 42,
|
||||
}
|
||||
|
||||
describe("NewsletterCard", () => {
|
||||
it("renders newsletter details correctly", () => {
|
||||
const handleEdit = jest.fn()
|
||||
render(<NewsletterCard newsletter={mockNewsletter} onEdit={handleEdit} />)
|
||||
|
||||
// Check for the title
|
||||
expect(screen.getByText("Tech Weekly")).toBeInTheDocument()
|
||||
|
||||
// Check for the entries count
|
||||
expect(screen.getByText("42 entries")).toBeInTheDocument()
|
||||
|
||||
// Check for sender emails
|
||||
expect(screen.getByText("contact@techweekly.com")).toBeInTheDocument()
|
||||
expect(screen.getByText("updates@techweekly.com")).toBeInTheDocument()
|
||||
|
||||
// Check for the RSS feed link
|
||||
const feedLink = screen.getByRole("link")
|
||||
expect(feedLink).toHaveAttribute("href", "http://mock-api/feeds/1")
|
||||
expect(feedLink).toHaveTextContent("http://mock-api/feeds/1")
|
||||
})
|
||||
|
||||
it('calls the onEdit function with the correct newsletter when the edit button is clicked', () => {
|
||||
const handleEdit = jest.fn()
|
||||
render(<NewsletterCard newsletter={mockNewsletter} onEdit={handleEdit} />)
|
||||
|
||||
const editButton = screen.getByRole("button", { name: /edit newsletter/i })
|
||||
fireEvent.click(editButton)
|
||||
|
||||
expect(handleEdit).toHaveBeenCalledTimes(1)
|
||||
expect(handleEdit).toHaveBeenCalledWith(mockNewsletter)
|
||||
})
|
||||
|
||||
it('displays "entry" for a single entry', () => {
|
||||
const singleEntryNewsletter = { ...mockNewsletter, entries_count: 1 }
|
||||
const handleEdit = jest.fn()
|
||||
render(<NewsletterCard newsletter={singleEntryNewsletter} onEdit={handleEdit} />)
|
||||
|
||||
expect(screen.getByText("1 entry")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { NewsletterDialog } from "../NewsletterDialog"
|
||||
import { Newsletter } from "@/lib/api"
|
||||
import * as api from "@/lib/api"
|
||||
|
||||
// Mock the API module
|
||||
jest.mock("@/lib/api", () => ({
|
||||
...jest.requireActual("@/lib/api"),
|
||||
createNewsletter: jest.fn(),
|
||||
updateNewsletter: jest.fn(),
|
||||
deleteNewsletter: jest.fn(),
|
||||
}))
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
|
||||
const mockNewsletter: Newsletter = {
|
||||
id: "1",
|
||||
name: "Existing Newsletter",
|
||||
is_active: true,
|
||||
extract_content: false,
|
||||
senders: [{ id: "1", email: "current@example.com" }],
|
||||
entries_count: 5,
|
||||
move_to_folder: "",
|
||||
}
|
||||
|
||||
describe("NewsletterDialog", () => {
|
||||
const handleOpenChange = jest.fn()
|
||||
const handleSuccess = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
window.confirm = jest.fn(() => true)
|
||||
})
|
||||
|
||||
describe("Add Mode", () => {
|
||||
it("allows user to fill out the form and submit", async () => {
|
||||
mockedApi.createNewsletter.mockResolvedValueOnce({
|
||||
id: "2",
|
||||
name: "My New Newsletter",
|
||||
is_active: true,
|
||||
extract_content: false,
|
||||
senders: [{ id: "2", email: "test@example.com" }],
|
||||
entries_count: 0,
|
||||
})
|
||||
|
||||
render(<NewsletterDialog isOpen={true} folderOptions={["INBOX", "Archive"]} onOpenChange={handleOpenChange} onSuccess={handleSuccess} />)
|
||||
|
||||
expect(screen.getByText("Register New Newsletter")).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/Newsletter Name/i), { target: { value: "My New Newsletter" } })
|
||||
fireEvent.change(screen.getByPlaceholderText(/Enter email address/i), { target: { value: "test@example.com" } })
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Register Newsletter/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.createNewsletter).toHaveBeenCalledWith({
|
||||
name: "My New Newsletter",
|
||||
sender_emails: ["test@example.com"],
|
||||
move_to_folder: "",
|
||||
extract_content: false,
|
||||
})
|
||||
expect(handleSuccess).toHaveBeenCalledTimes(1)
|
||||
expect(handleOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
|
||||
it("allows adding and removing email fields", () => {
|
||||
render(<NewsletterDialog isOpen={true} folderOptions={[]} onOpenChange={() => {}} onSuccess={() => {}} />)
|
||||
expect(screen.getAllByPlaceholderText(/Enter email address/i)).toHaveLength(1)
|
||||
fireEvent.click(screen.getByRole("button", { name: /Add Another Email/i }))
|
||||
expect(screen.getAllByPlaceholderText(/Enter email address/i)).toHaveLength(2)
|
||||
fireEvent.click(screen.getAllByRole("button", { name: /Remove/i })[0])
|
||||
expect(screen.getAllByPlaceholderText(/Enter email address/i)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe("Edit Mode", () => {
|
||||
it("renders with initial newsletter data and allows updates", async () => {
|
||||
mockedApi.updateNewsletter.mockResolvedValueOnce({ ...mockNewsletter, name: "Updated Name" })
|
||||
|
||||
render(
|
||||
<NewsletterDialog
|
||||
newsletter={mockNewsletter}
|
||||
isOpen={true}
|
||||
folderOptions={["INBOX", "Archive"]}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText("Edit Newsletter")).toBeInTheDocument()
|
||||
const nameInput = screen.getByLabelText(/Newsletter Name/i)
|
||||
expect(nameInput).toHaveValue("Existing Newsletter")
|
||||
expect(screen.getByDisplayValue("current@example.com")).toBeInTheDocument()
|
||||
|
||||
fireEvent.change(nameInput, { target: { value: "Updated Name" } })
|
||||
fireEvent.click(screen.getByRole("button", { name: /Save Changes/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.updateNewsletter).toHaveBeenCalledWith("1", {
|
||||
name: "Updated Name",
|
||||
sender_emails: ["current@example.com"],
|
||||
move_to_folder: "",
|
||||
extract_content: false,
|
||||
})
|
||||
expect(handleSuccess).toHaveBeenCalledTimes(1)
|
||||
expect(handleOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
|
||||
it("calls deleteNewsletter when delete button is clicked and confirmed", async () => {
|
||||
mockedApi.deleteNewsletter.mockResolvedValueOnce(undefined)
|
||||
|
||||
render(
|
||||
<NewsletterDialog
|
||||
newsletter={mockNewsletter}
|
||||
isOpen={true}
|
||||
folderOptions={["INBOX", "Archive"]}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Delete Newsletter/i }))
|
||||
expect(window.confirm).toHaveBeenCalledWith('Are you sure you want to delete the "Existing Newsletter" newsletter?')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.deleteNewsletter).toHaveBeenCalledWith("1")
|
||||
expect(handleSuccess).toHaveBeenCalledTimes(1)
|
||||
expect(handleOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import React from "react"
|
||||
import { render, screen } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { NewsletterList } from "../NewsletterList"
|
||||
import { Newsletter } from "@/lib/api"
|
||||
|
||||
// Mock the child component to isolate the list component's behavior
|
||||
jest.mock("../NewsletterCard", () => ({
|
||||
NewsletterCard: ({ newsletter }: { newsletter: Newsletter }) => (
|
||||
<div data-testid={`newsletter-card-${newsletter.id}`}>{newsletter.name}</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const mockNewsletters: Newsletter[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Newsletter One",
|
||||
is_active: true,
|
||||
senders: [],
|
||||
entries_count: 10,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Newsletter Two",
|
||||
is_active: true,
|
||||
senders: [],
|
||||
entries_count: 5,
|
||||
},
|
||||
]
|
||||
|
||||
describe("NewsletterList", () => {
|
||||
it("renders a list of newsletter cards", () => {
|
||||
render(<NewsletterList newsletters={mockNewsletters} onEditNewsletter={() => {}} />)
|
||||
|
||||
// Check that both newsletters are rendered
|
||||
expect(screen.getByText("Newsletter One")).toBeInTheDocument()
|
||||
expect(screen.getByText("Newsletter Two")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("newsletter-card-1")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("newsletter-card-2")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders nothing when the newsletter list is empty", () => {
|
||||
const { container } = render(<NewsletterList newsletters={[]} onEditNewsletter={() => {}} />)
|
||||
// The main div should be empty
|
||||
expect(container.firstChild).toBeEmptyDOMElement()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { SettingsDialog } from "../SettingsDialog"
|
||||
import { Settings } from "@/lib/api"
|
||||
import * as api from "@/lib/api"
|
||||
import { toast } from "sonner"
|
||||
|
||||
// Mock the API module
|
||||
jest.mock("@/lib/api", () => ({
|
||||
...jest.requireActual("@/lib/api"),
|
||||
updateSettings: jest.fn(),
|
||||
testImapConnection: jest.fn(),
|
||||
}))
|
||||
|
||||
// Mock the toast module
|
||||
jest.mock("sonner", () => ({
|
||||
toast: {
|
||||
success: jest.fn(),
|
||||
error: jest.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
|
||||
const mockSettings: Settings = {
|
||||
id: 1,
|
||||
imap_server: "imap.example.com",
|
||||
imap_username: "user@example.com",
|
||||
search_folder: "INBOX",
|
||||
move_to_folder: "Archive",
|
||||
mark_as_read: true,
|
||||
email_check_interval: 30,
|
||||
auto_add_new_senders: false,
|
||||
locked_fields: ["imap_server"], // Mock a locked field
|
||||
}
|
||||
|
||||
const mockFolderOptions = ["INBOX", "Sent", "Archive", "Spam"]
|
||||
|
||||
describe("SettingsDialog", () => {
|
||||
const handleOpenChange = jest.fn()
|
||||
const handleSuccess = jest.fn()
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
consoleError.mockClear()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it("renders settings and respects locked fields", () => {
|
||||
render(
|
||||
<SettingsDialog
|
||||
settings={mockSettings}
|
||||
folderOptions={mockFolderOptions}
|
||||
isOpen={true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
// Check that a locked field is disabled
|
||||
expect(screen.getByLabelText(/IMAP Server/i)).toBeDisabled()
|
||||
// Check that a non-locked field is enabled
|
||||
expect(screen.getByLabelText(/IMAP Username/i)).toBeEnabled()
|
||||
|
||||
// Check that values are set correctly
|
||||
expect(screen.getByLabelText(/IMAP Username/i)).toHaveValue(
|
||||
mockSettings.imap_username
|
||||
)
|
||||
expect(screen.getByLabelText(/Mark emails as read/i)).toBeChecked()
|
||||
})
|
||||
|
||||
it("allows updating and saving settings, showing success toast", async () => {
|
||||
mockedApi.updateSettings.mockResolvedValueOnce(mockSettings)
|
||||
|
||||
render(
|
||||
<SettingsDialog
|
||||
settings={mockSettings}
|
||||
folderOptions={mockFolderOptions}
|
||||
isOpen={true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
// Change a setting
|
||||
fireEvent.change(screen.getByLabelText(/IMAP Username/i), {
|
||||
target: { value: "new.user@example.com" },
|
||||
})
|
||||
|
||||
// Save
|
||||
fireEvent.click(screen.getByRole("button", { name: /Save Settings/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.updateSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
imap_username: "new.user@example.com",
|
||||
})
|
||||
)
|
||||
expect(toast.success).toHaveBeenCalledWith("Settings saved successfully!")
|
||||
expect(handleSuccess).toHaveBeenCalledTimes(1)
|
||||
expect(handleOpenChange).toHaveBeenCalledWith(false)
|
||||
})
|
||||
})
|
||||
|
||||
it("shows an error toast if saving settings fails", async () => {
|
||||
mockedApi.updateSettings.mockRejectedValueOnce(new Error("Failed to save"))
|
||||
|
||||
render(
|
||||
<SettingsDialog
|
||||
settings={mockSettings}
|
||||
folderOptions={mockFolderOptions}
|
||||
isOpen={true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Save Settings/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to save settings.")
|
||||
expect(handleSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it("handles successful connection test", async () => {
|
||||
mockedApi.testImapConnection.mockResolvedValueOnce({
|
||||
message: "Connection successful!",
|
||||
})
|
||||
|
||||
render(
|
||||
<SettingsDialog
|
||||
settings={mockSettings}
|
||||
folderOptions={mockFolderOptions}
|
||||
isOpen={true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Test Connection/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Connection successful!")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("connection-status")).toHaveClass(
|
||||
"text-green-600"
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it("handles failed connection test", async () => {
|
||||
mockedApi.testImapConnection.mockRejectedValueOnce(
|
||||
new Error("Authentication failed")
|
||||
)
|
||||
|
||||
render(
|
||||
<SettingsDialog
|
||||
settings={mockSettings}
|
||||
folderOptions={mockFolderOptions}
|
||||
isOpen={true}
|
||||
onOpenChange={handleOpenChange}
|
||||
onSuccess={handleSuccess}
|
||||
/>
|
||||
)
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /Test Connection/i }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Authentication failed")).toBeInTheDocument()
|
||||
expect(screen.getByTestId("connection-status")).toHaveClass("text-red-600")
|
||||
})
|
||||
})
|
||||
})
|
||||
46
frontend/src/components/ui/badge.tsx
Normal file
46
frontend/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
59
frontend/src/components/ui/button.tsx
Normal file
59
frontend/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
92
frontend/src/components/ui/card.tsx
Normal file
92
frontend/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
32
frontend/src/components/ui/checkbox.tsx
Normal file
32
frontend/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
21
frontend/src/components/ui/components.json
Normal file
21
frontend/src/components/ui/components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
143
frontend/src/components/ui/dialog.tsx
Normal file
143
frontend/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
21
frontend/src/components/ui/input.tsx
Normal file
21
frontend/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
22
frontend/src/components/ui/label.tsx
Normal file
22
frontend/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
183
frontend/src/components/ui/select.tsx
Normal file
183
frontend/src/components/ui/select.tsx
Normal file
@@ -0,0 +1,183 @@
|
||||
import * as React from "react"
|
||||
import * as SelectPrimitive from "@radix-ui/react-select"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default"
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
}
|
||||
27
frontend/src/components/ui/sonner.tsx
Normal file
27
frontend/src/components/ui/sonner.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
"use client"
|
||||
|
||||
import { Toaster as Sonner } from "sonner"
|
||||
|
||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
return (
|
||||
<Sonner
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
31
frontend/src/components/withAuth.tsx
Normal file
31
frontend/src/components/withAuth.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
import { LoadingSpinner } from "@/components/letterfeed/LoadingSpinner"
|
||||
|
||||
const withAuth = <P extends object>(
|
||||
WrappedComponent: React.ComponentType<P>
|
||||
) => {
|
||||
const WithAuthComponent = (props: P) => {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated) {
|
||||
router.push("/login")
|
||||
}
|
||||
}, [isAuthenticated, isLoading, router])
|
||||
|
||||
if (isLoading || !isAuthenticated) {
|
||||
return <LoadingSpinner />
|
||||
}
|
||||
|
||||
return <WrappedComponent {...props} />
|
||||
}
|
||||
|
||||
return WithAuthComponent
|
||||
}
|
||||
|
||||
export default withAuth
|
||||
74
frontend/src/contexts/AuthContext.tsx
Normal file
74
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useState, useEffect, ReactNode } from "react"
|
||||
import { getAuthStatus, login as apiLogin, getSettings } from "@/lib/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
interface AuthContextType {
|
||||
isAuthenticated: boolean
|
||||
login: (username: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
const checkAuth = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const { auth_enabled } = await getAuthStatus();
|
||||
if (!auth_enabled) {
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
// If a token exists, verify it by making a protected API call.
|
||||
// getSettings is a good candidate. If it fails with a 401,
|
||||
// the fetcher will remove the token and throw, which we catch here.
|
||||
await getSettings();
|
||||
setIsAuthenticated(true);
|
||||
} else {
|
||||
setIsAuthenticated(false);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// This will catch errors from getAuthStatus or getSettings.
|
||||
// If it was a 401, the token is already removed by the fetcher.
|
||||
setIsAuthenticated(false);
|
||||
console.error("Authentication check failed", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
await apiLogin(username, password)
|
||||
setIsAuthenticated(true)
|
||||
router.push("/")
|
||||
} catch (error) {
|
||||
console.error("Login failed", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem("authToken")
|
||||
setIsAuthenticated(false)
|
||||
router.push("/login")
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isAuthenticated, login, logout, isLoading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
163
frontend/src/contexts/__tests__/AuthContext.test.tsx
Normal file
163
frontend/src/contexts/__tests__/AuthContext.test.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import React from "react"
|
||||
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
|
||||
import "@testing-library/jest-dom"
|
||||
import { AuthProvider, AuthContext } from "@/contexts/AuthContext"
|
||||
import * as api from "@/lib/api"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
jest.mock("@/lib/api")
|
||||
jest.mock("next/navigation", () => ({
|
||||
useRouter: jest.fn(),
|
||||
}))
|
||||
|
||||
const mockedApi = api as jest.Mocked<typeof api>
|
||||
const mockedUseRouter = useRouter as jest.Mock
|
||||
|
||||
describe("AuthContext", () => {
|
||||
const push = jest.fn()
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation(() => {})
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
localStorage.clear()
|
||||
mockedUseRouter.mockReturnValue({ push })
|
||||
consoleError.mockClear()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it("authenticates if auth is not enabled", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: false })
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("authenticates if auth is enabled and token is valid", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockResolvedValue({} as api.Settings) // Mock a successful protected call
|
||||
localStorage.setItem("authToken", "valid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("does not authenticate if auth is enabled and no token", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("does not authenticate if token is invalid", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockRejectedValue(new Error("Invalid token")) // Mock a failed protected call
|
||||
localStorage.setItem("authToken", "invalid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it("login works correctly", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.login.mockResolvedValue()
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<>
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
<button onClick={() => value?.login("testuser", "password")}>Login</button>
|
||||
</>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.click(screen.getByText("Login"))
|
||||
await waitFor(() => {
|
||||
expect(mockedApi.login).toHaveBeenCalledWith("testuser", "password")
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
expect(push).toHaveBeenCalledWith("/")
|
||||
})
|
||||
})
|
||||
|
||||
it("logout works correctly", async () => {
|
||||
mockedApi.getAuthStatus.mockResolvedValue({ auth_enabled: true })
|
||||
mockedApi.getSettings.mockResolvedValue({} as api.Settings)
|
||||
localStorage.setItem("authToken", "valid-token")
|
||||
render(
|
||||
<AuthProvider>
|
||||
<AuthContext.Consumer>
|
||||
{(value) => (
|
||||
<>
|
||||
<span>
|
||||
Is Authenticated: {value?.isAuthenticated.toString()}
|
||||
</span>
|
||||
<button onClick={() => value?.logout()}>Logout</button>
|
||||
</>
|
||||
)}
|
||||
</AuthContext.Consumer>
|
||||
</AuthProvider>
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: true")).toBeInTheDocument()
|
||||
})
|
||||
fireEvent.click(screen.getByText("Logout"))
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Is Authenticated: false")).toBeInTheDocument()
|
||||
expect(push).toHaveBeenCalledWith("/login")
|
||||
expect(localStorage.getItem("authToken")).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
12
frontend/src/hooks/useAuth.ts
Normal file
12
frontend/src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client"
|
||||
|
||||
import { useContext } from "react"
|
||||
import { AuthContext } from "@/contexts/AuthContext"
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext)
|
||||
if (context === undefined) {
|
||||
throw new Error("useAuth must be used within an AuthProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
testImapConnection,
|
||||
processEmails,
|
||||
getFeedUrl,
|
||||
login,
|
||||
NewsletterCreate,
|
||||
NewsletterUpdate,
|
||||
SettingsCreate,
|
||||
@@ -25,19 +26,21 @@ jest.mock("sonner", () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
const mockFetch = (data: any, ok = true, statusText = "OK") => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const mockFetch = <T,>(data: T, ok = true, statusText = "OK") => {
|
||||
;(fetch as jest.Mock).mockResolvedValueOnce({
|
||||
ok,
|
||||
json: () => Promise.resolve(data),
|
||||
statusText,
|
||||
status: ok ? 200 : 400,
|
||||
})
|
||||
}
|
||||
|
||||
const mockFetchError = (data: any = {}, statusText = "Bad Request") => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const mockFetchError = (data: any = {}, statusText = "Bad Request", status = 400) => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
;(fetch as jest.Mock).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: () => Promise.resolve(data),
|
||||
statusText,
|
||||
status,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -48,37 +51,53 @@ describe("API Functions", () => {
|
||||
// Reset the mock before each test
|
||||
;(fetch as jest.Mock).mockClear()
|
||||
;(toast.error as jest.Mock).mockClear()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe("login", () => {
|
||||
it("should login successfully and store the token", async () => {
|
||||
const mockToken = { access_token: "test-token", token_type: "bearer" }
|
||||
mockFetch(mockToken)
|
||||
|
||||
await login("user", "pass")
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({ username: "user", password: "pass" }),
|
||||
})
|
||||
expect(localStorage.getItem("authToken")).toBe("test-token")
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and clear token if login fails", async () => {
|
||||
mockFetchError({ detail: "Incorrect username or password" }, "Unauthorized", 401)
|
||||
localStorage.setItem("authToken", "old-token")
|
||||
|
||||
await expect(login("user", "wrong-pass")).rejects.toThrow("Incorrect username or password")
|
||||
expect(localStorage.getItem("authToken")).toBeNull()
|
||||
expect(toast.error).toHaveBeenCalledWith("Incorrect username or password")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getNewsletters", () => {
|
||||
it("should fetch newsletters successfully", async () => {
|
||||
const mockNewsletters = [
|
||||
{ id: 1, name: "Newsletter 1", is_active: true, senders: [], entries_count: 5 },
|
||||
{ id: 2, name: "Newsletter 2", is_active: false, senders: [], entries_count: 10 },
|
||||
]
|
||||
it("should fetch newsletters successfully with auth token", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockNewsletters = [{ id: 1, name: "Newsletter 1" }]
|
||||
mockFetch(mockNewsletters)
|
||||
|
||||
const newsletters = await getNewsletters()
|
||||
expect(newsletters).toEqual(mockNewsletters)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching newsletters fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Not Found")
|
||||
await expect(getNewsletters()).rejects.toThrow("Failed to fetch newsletters: Not Found")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch newsletters: Not Found")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching newsletters fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(getNewsletters()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("createNewsletter", () => {
|
||||
it("should create a newsletter successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: ["test@example.com"], extract_content: false }
|
||||
const createdNewsletter = {
|
||||
id: 3,
|
||||
@@ -93,36 +112,23 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(createdNewsletter)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(newNewsletter),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if creating newsletter fails with HTTP error", async () => {
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: [], extract_content: false }
|
||||
mockFetchError({}, "Conflict")
|
||||
await expect(createNewsletter(newNewsletter)).rejects.toThrow("Failed to create newsletter: Conflict")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to create newsletter: Conflict")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if creating newsletter fails with network error", async () => {
|
||||
const newNewsletter: NewsletterCreate = { name: "New Newsletter", sender_emails: [], extract_content: false }
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(createNewsletter(newNewsletter)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateNewsletter", () => {
|
||||
it("should update a newsletter successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: ["updated@example.com"], extract_content: true }
|
||||
const newsletterId = 1
|
||||
const newsletterId = "1"
|
||||
const returnedNewsletter = {
|
||||
id: newsletterId,
|
||||
...updatedNewsletter,
|
||||
is_active: true,
|
||||
senders: [{ id: 1, email: "updated@example.com", newsletter_id: newsletterId }],
|
||||
senders: [{ id: "1", email: "updated@example.com" }],
|
||||
entries_count: 12,
|
||||
}
|
||||
mockFetch(returnedNewsletter)
|
||||
@@ -131,58 +137,31 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(returnedNewsletter)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters/${newsletterId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(updatedNewsletter),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating newsletter fails with HTTP error", async () => {
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: [], extract_content: true }
|
||||
const newsletterId = 1
|
||||
mockFetchError({}, "Bad Request")
|
||||
await expect(updateNewsletter(newsletterId, updatedNewsletter)).rejects.toThrow("Failed to update newsletter: Bad Request")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to update newsletter: Bad Request")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating newsletter fails with network error", async () => {
|
||||
const updatedNewsletter: NewsletterUpdate = { name: "Updated Newsletter", sender_emails: [], extract_content: true }
|
||||
const newsletterId = 1
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(updateNewsletter(newsletterId, updatedNewsletter)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("deleteNewsletter", () => {
|
||||
it("should delete a newsletter successfully", async () => {
|
||||
const newsletterId = 1
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newsletterId = "1"
|
||||
mockFetch({}, true) // Successful deletion might not have a body
|
||||
|
||||
await deleteNewsletter(newsletterId)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/newsletters/${newsletterId}`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if deleting newsletter fails with HTTP error", async () => {
|
||||
const newsletterId = 1
|
||||
mockFetchError({}, "Forbidden")
|
||||
await expect(deleteNewsletter(newsletterId)).rejects.toThrow("Failed to delete newsletter: Forbidden")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to delete newsletter: Forbidden")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if deleting newsletter fails with network error", async () => {
|
||||
const newsletterId = 1
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(deleteNewsletter(newsletterId)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getSettings", () => {
|
||||
it("should fetch settings successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockSettings = {
|
||||
id: 1,
|
||||
imap_server: "imap.example.com",
|
||||
@@ -198,25 +177,16 @@ describe("API Functions", () => {
|
||||
|
||||
const settings = await getSettings()
|
||||
expect(settings).toEqual(mockSettings)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching settings fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Unauthorized")
|
||||
await expect(getSettings()).rejects.toThrow("Failed to fetch settings: Unauthorized")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch settings: Unauthorized")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if fetching settings fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(getSettings()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateSettings", () => {
|
||||
it("should update settings successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
@@ -234,69 +204,31 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(updatedSettings)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/settings`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: { "Content-Type": "application/json", Authorization: "Bearer test-token" },
|
||||
body: JSON.stringify(newSettings),
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating settings fails with HTTP error", async () => {
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
search_folder: "Archive",
|
||||
mark_as_read: false,
|
||||
email_check_interval: 120,
|
||||
auto_add_new_senders: true,
|
||||
}
|
||||
mockFetchError({}, "Internal Server Error")
|
||||
await expect(updateSettings(newSettings)).rejects.toThrow("Failed to update settings: Internal Server Error")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to update settings: Internal Server Error")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if updating settings fails with network error", async () => {
|
||||
const newSettings: SettingsCreate = {
|
||||
imap_server: "new.imap.com",
|
||||
imap_username: "newuser@example.com",
|
||||
search_folder: "Archive",
|
||||
mark_as_read: false,
|
||||
email_check_interval: 120,
|
||||
auto_add_new_senders: true,
|
||||
}
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(updateSettings(newSettings)).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getImapFolders", () => {
|
||||
it("should fetch IMAP folders successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockFolders = ["INBOX", "Sent", "Archive"]
|
||||
mockFetch(mockFolders)
|
||||
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual(mockFolders)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/folders`, {})
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/folders`, {
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should return an empty array and show toast if fetching IMAP folders fails with HTTP error", async () => {
|
||||
mockFetchError({}, "Forbidden")
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual([])
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to fetch IMAP folders: Forbidden")
|
||||
})
|
||||
|
||||
it("should return an empty array and show toast if fetching IMAP folders fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
const folders = await getImapFolders()
|
||||
expect(folders).toEqual([])
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("testImapConnection", () => {
|
||||
it("should test IMAP connection successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockResponse = { message: "Connection successful" }
|
||||
mockFetch(mockResponse)
|
||||
|
||||
@@ -304,32 +236,15 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(mockResponse)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/test`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error with detail and show toast if testing IMAP connection fails with HTTP error", async () => {
|
||||
const errorMessage = "Invalid credentials"
|
||||
mockFetchError({ detail: errorMessage }, "Unauthorized")
|
||||
await expect(testImapConnection()).rejects.toThrow(errorMessage)
|
||||
expect(toast.error).toHaveBeenCalledWith(errorMessage)
|
||||
})
|
||||
|
||||
it("should throw a generic error and show toast if testing IMAP connection fails without detail with HTTP error", async () => {
|
||||
mockFetchError({}, "Bad Gateway")
|
||||
await expect(testImapConnection()).rejects.toThrow("Failed to test IMAP connection: Bad Gateway")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to test IMAP connection: Bad Gateway")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if testing IMAP connection fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(testImapConnection()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("processEmails", () => {
|
||||
it("should process emails successfully", async () => {
|
||||
localStorage.setItem("authToken", "test-token")
|
||||
const mockResponse = { message: "Emails processed" }
|
||||
mockFetch(mockResponse)
|
||||
|
||||
@@ -337,43 +252,18 @@ describe("API Functions", () => {
|
||||
expect(result).toEqual(mockResponse)
|
||||
expect(fetch).toHaveBeenCalledWith(`${API_BASE_URL}/imap/process`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer test-token" },
|
||||
})
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("should throw an error with detail and show toast if processing emails fails with HTTP error", async () => {
|
||||
const errorMessage = "IMAP not configured"
|
||||
mockFetchError({ detail: errorMessage }, "Bad Request")
|
||||
await expect(processEmails()).rejects.toThrow(errorMessage)
|
||||
expect(toast.error).toHaveBeenCalledWith(errorMessage)
|
||||
})
|
||||
|
||||
it("should throw a generic error and show toast if processing emails fails without detail with HTTP error", async () => {
|
||||
mockFetchError({}, "Service Unavailable")
|
||||
await expect(processEmails()).rejects.toThrow("Failed to process emails: Service Unavailable")
|
||||
expect(toast.error).toHaveBeenCalledWith("Failed to process emails: Service Unavailable")
|
||||
})
|
||||
|
||||
it("should throw an error and show toast if processing emails fails with network error", async () => {
|
||||
;(fetch as jest.Mock).mockRejectedValueOnce(new TypeError("Network request failed"))
|
||||
await expect(processEmails()).rejects.toThrow("Network request failed")
|
||||
expect(toast.error).toHaveBeenCalledWith("Network error: Could not connect to the backend.")
|
||||
})
|
||||
})
|
||||
|
||||
describe("getFeedUrl", () => {
|
||||
it("should return the correct feed URL", () => {
|
||||
const newsletterId = 123
|
||||
const newsletterId = "123"
|
||||
const expectedUrl = `${API_BASE_URL}/feeds/${newsletterId}`
|
||||
const url = getFeedUrl(newsletterId)
|
||||
expect(url).toBe(expectedUrl)
|
||||
})
|
||||
|
||||
it("should handle newsletterId being 0", () => {
|
||||
const newsletterId = 0
|
||||
const expectedUrl = `${API_BASE_URL}/feeds/0`
|
||||
const url = getFeedUrl(newsletterId)
|
||||
expect(url).toBe(expectedUrl)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,14 @@ async function fetcher<T>(
|
||||
returnEmptyArrayOnFailure: boolean = false
|
||||
): Promise<T> {
|
||||
try {
|
||||
const token = localStorage.getItem("authToken");
|
||||
if (token) {
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
'Authorization': `Bearer ${token}`,
|
||||
};
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
if (!response.ok) {
|
||||
let errorText = `${errorMessagePrefix}: ${response.statusText}`;
|
||||
@@ -74,12 +82,22 @@ async function fetcher<T>(
|
||||
} catch (e) { // eslint-disable-line @typescript-eslint/no-unused-vars
|
||||
// ignore error if response is not JSON
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
localStorage.removeItem("authToken");
|
||||
// Do not redirect here. The AuthContext will handle it.
|
||||
}
|
||||
|
||||
toast.error(errorText);
|
||||
if (returnEmptyArrayOnFailure) {
|
||||
return [] as T;
|
||||
}
|
||||
throw new Error(errorText);
|
||||
}
|
||||
// For login or delete, we might not have a body
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
return response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof TypeError) {
|
||||
@@ -92,6 +110,34 @@ async function fetcher<T>(
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAuthStatus(): Promise<{ auth_enabled: boolean }> {
|
||||
return fetcher<{ auth_enabled: boolean }>(`${API_BASE_URL}/auth/status`, {}, "Failed to fetch auth status");
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string): Promise<void> {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('username', username);
|
||||
formData.append('password', password);
|
||||
|
||||
try {
|
||||
const response = await fetcher<{ access_token: string }>(`${API_BASE_URL}/auth/login`, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
}, "Login failed");
|
||||
|
||||
if (response.access_token) {
|
||||
localStorage.setItem("authToken", response.access_token);
|
||||
}
|
||||
} catch (error) {
|
||||
localStorage.removeItem("authToken");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function getNewsletters(): Promise<Newsletter[]> {
|
||||
return fetcher<Newsletter[]>(`${API_BASE_URL}/newsletters`, {}, "Failed to fetch newsletters");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user