first commit
This commit is contained in:
235
frontend/app/admin/categories/category-dialog.tsx
Normal file
235
frontend/app/admin/categories/category-dialog.tsx
Normal file
@@ -0,0 +1,235 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import * as z from "zod"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Category } from "@/types/category"
|
||||
import { categoryService } from "@/services/categoryService"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(2, {
|
||||
message: "Başlık en az 2 karakter olmalıdır.",
|
||||
}),
|
||||
slug: z.string().min(2, {
|
||||
message: "Slug en az 2 karakter olmalıdır.",
|
||||
}),
|
||||
description: z.string().optional(),
|
||||
parent_id: z.string().optional(), // Select value is string, will convert to number
|
||||
})
|
||||
|
||||
interface CategoryDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
category?: Category | null
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
function slugify(text: string) {
|
||||
const trMap: { [key: string]: string } = {
|
||||
'ç': 'c', 'Ç': 'c',
|
||||
'ğ': 'g', 'Ğ': 'g',
|
||||
'ş': 's', 'Ş': 's',
|
||||
'ü': 'u', 'Ü': 'u',
|
||||
'ı': 'i', 'İ': 'i',
|
||||
'ö': 'o', 'Ö': 'o'
|
||||
};
|
||||
return text
|
||||
.replace(/[çÇğĞşŞüÜıİöÖ]/g, (char) => trMap[char] || char)
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, '') // Remove non-alphanumeric chars (except space and hyphen)
|
||||
.trim()
|
||||
.replace(/\s+/g, '-') // Replace spaces with hyphens
|
||||
.replace(/-+/g, '-'); // Remove duplicate hyphens
|
||||
}
|
||||
|
||||
export function CategoryDialog({ open, onOpenChange, category, onSuccess }: CategoryDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [categories, setCategories] = useState<Category[]>([])
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
title: "",
|
||||
slug: "",
|
||||
description: "",
|
||||
parent_id: "0",
|
||||
},
|
||||
})
|
||||
|
||||
// Watch title to auto-generate slug
|
||||
const titleValue = form.watch("title")
|
||||
useEffect(() => {
|
||||
if (!category && titleValue) { // Only auto-generate if creating new category
|
||||
const slug = slugify(titleValue)
|
||||
form.setValue("slug", slug)
|
||||
}
|
||||
}, [titleValue, category, form])
|
||||
|
||||
// Fetch categories for check parent selection
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
categoryService.getCategories(1, 100, "", "active") // Get active categories
|
||||
.then(res => {
|
||||
// Ensure we don't list the current category (recursion check)
|
||||
const validCategories = category
|
||||
? (res.items || []).filter(c => c.id !== category.id)
|
||||
: (res.items || []);
|
||||
setCategories(validCategories)
|
||||
})
|
||||
.catch(err => console.error(err))
|
||||
}
|
||||
}, [open, category])
|
||||
|
||||
useEffect(() => {
|
||||
if (category) {
|
||||
form.reset({
|
||||
title: category.title,
|
||||
slug: category.slug,
|
||||
description: category.description || "",
|
||||
parent_id: category.parent_id ? category.parent_id.toString() : "0",
|
||||
})
|
||||
} else {
|
||||
form.reset({
|
||||
title: "",
|
||||
slug: "",
|
||||
description: "",
|
||||
parent_id: "0",
|
||||
})
|
||||
}
|
||||
}, [category, form, open])
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const payload: Partial<Category> = {
|
||||
title: values.title,
|
||||
slug: values.slug,
|
||||
description: values.description,
|
||||
parent_id: values.parent_id && values.parent_id !== "0" ? parseInt(values.parent_id) : null,
|
||||
}
|
||||
|
||||
if (category) {
|
||||
await categoryService.updateCategory(category.id, payload)
|
||||
toast.success("Kategori güncellendi")
|
||||
} else {
|
||||
await categoryService.createCategory(payload)
|
||||
toast.success("Kategori oluşturuldu")
|
||||
}
|
||||
onOpenChange(false)
|
||||
if (onSuccess) {
|
||||
onSuccess()
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
toast.error((error as Error).message || "Bir hata oluştu")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{category ? "Kategori Düzenle" : "Yeni Kategori Ekle"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Başlık</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Kategori Başlığı" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slug"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Slug (URL)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="kategori-slug" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="parent_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Üst Kategori</FormLabel>
|
||||
<Select
|
||||
onValueChange={field.onChange}
|
||||
value={field.value} // Remove defaultValue to avoid conflicts
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Üst Kategori Seçin" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="0">Yok (Ana Kategori)</SelectItem>
|
||||
{categories.map((c) => (
|
||||
<SelectItem key={c.id} value={c.id.toString()}>
|
||||
{c.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Açıklama</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="Kategori açıklaması..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
141
frontend/app/admin/categories/category-row-actions.tsx
Normal file
141
frontend/app/admin/categories/category-row-actions.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Row } from "@tanstack/react-table"
|
||||
import { MoreHorizontal, Pencil, Trash, RefreshCcw } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Category } from "@/types/category"
|
||||
import { categoryService } from "@/services/categoryService"
|
||||
import { CategoryDialog } from "./category-dialog"
|
||||
import Swal from 'sweetalert2'
|
||||
import withReactContent from 'sweetalert2-react-content'
|
||||
|
||||
const MySwal = withReactContent(Swal)
|
||||
|
||||
interface DataTableRowActionsProps<TData> {
|
||||
row: Row<TData>
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
export function DataTableRowActions<TData>({
|
||||
row,
|
||||
onRefresh,
|
||||
}: DataTableRowActionsProps<TData>) {
|
||||
const category = row.original as Category
|
||||
const [showEditDialog, setShowEditDialog] = useState(false)
|
||||
const isDeleted = !!category.deleted_at
|
||||
|
||||
const handleDelete = async () => {
|
||||
const result = await MySwal.fire({
|
||||
title: 'Emin misiniz?',
|
||||
text: "Bu kategori silinecek!",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Evet, sil!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await categoryService.deleteCategory(category.id)
|
||||
MySwal.fire(
|
||||
'Silindi!',
|
||||
'Kategori başarıyla silindi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
} catch {
|
||||
MySwal.fire(
|
||||
'Hata!',
|
||||
'Bir hata oluştu.',
|
||||
'error'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async () => {
|
||||
const result = await MySwal.fire({
|
||||
title: 'Geri Yükle?',
|
||||
text: "Bu kategori geri yüklenecek!",
|
||||
icon: 'question',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Evet, geri yükle!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await categoryService.restoreCategory(category.id)
|
||||
MySwal.fire(
|
||||
'Geri Yüklendi!',
|
||||
'Kategori başarıyla geri yüklendi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
} catch {
|
||||
MySwal.fire(
|
||||
'Hata!',
|
||||
'Bir hata oluştu.',
|
||||
'error'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CategoryDialog
|
||||
open={showEditDialog}
|
||||
onOpenChange={setShowEditDialog}
|
||||
category={category}
|
||||
onSuccess={onRefresh}
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Menü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>İşlemler</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigator.clipboard.writeText(category.id.toString())}
|
||||
>
|
||||
ID Kopyala
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
{!isDeleted && (
|
||||
<DropdownMenuItem onClick={() => setShowEditDialog(true)}>
|
||||
<Pencil className="mr-2 h-4 w-4" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{isDeleted ? (
|
||||
<DropdownMenuItem onClick={handleRestore}>
|
||||
<RefreshCcw className="mr-2 h-4 w-4 text-green-600" /> Geri Yükle
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
|
||||
<Trash className="mr-2 h-4 w-4" /> Sil
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)
|
||||
}
|
||||
70
frontend/app/admin/categories/columns.tsx
Normal file
70
frontend/app/admin/categories/columns.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
"use client"
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Category } from "@/types/category"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
import { DataTableRowActions } from "./category-row-actions"
|
||||
|
||||
export const getColumns = (onRefresh: () => void, categories: Category[]): ColumnDef<Category>[] => [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
ID
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
Başlık
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "slug",
|
||||
header: "Slug",
|
||||
},
|
||||
{
|
||||
accessorKey: "parent_id",
|
||||
header: "Üst Kategori",
|
||||
cell: ({ row }) => {
|
||||
const pid = row.original.parent_id
|
||||
if (!pid || pid === 0) return "-"
|
||||
|
||||
const parent = categories.find(c => c.id === pid)
|
||||
return parent ? parent.title : pid
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "deleted_at",
|
||||
header: "Durum",
|
||||
cell: ({ row }) => {
|
||||
const deletedAt = row.original.deleted_at
|
||||
return deletedAt ? (
|
||||
<Badge variant="destructive">Silindi</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">Aktif</Badge>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => <DataTableRowActions row={row} onRefresh={onRefresh} />,
|
||||
},
|
||||
]
|
||||
91
frontend/app/admin/categories/data-table.tsx
Normal file
91
frontend/app/admin/categories/data-table.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
SortingState,
|
||||
getSortedRowModel,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
|
||||
// eslint-disable-next-line
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
onSortingChange: setSorting,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
sorting,
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columns.length} className="h-24 text-center">
|
||||
Sonuç bulunamadı.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
115
frontend/app/admin/categories/page.tsx
Normal file
115
frontend/app/admin/categories/page.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { DataTable } from "./data-table"
|
||||
import { getColumns } from "./columns"
|
||||
import { Category } from "@/types/category"
|
||||
import { categoryService } from "@/services/categoryService"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus } from "lucide-react"
|
||||
import { CategoryDialog } from "./category-dialog"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
export default function CategoriesPage() {
|
||||
const [data, setData] = useState<Category[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [perPage] = useState(20)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("with") // "with", "active", "only"
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const apiSoftFilter = statusFilter === "active" ? "" : statusFilter
|
||||
const res = await categoryService.getCategories(page, perPage, search, apiSoftFilter)
|
||||
setData(res.items || [])
|
||||
setTotal(res.total || 0)
|
||||
} catch (error) {
|
||||
console.error("Categories fetch error:", error)
|
||||
setData([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [page, perPage, search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
|
||||
return (
|
||||
<div className="p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Kategori Yönetimi</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Kategorileri oluşturun, düzenleyin veya silin.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowCreateDialog(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Yeni Kategori
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center py-4 gap-4">
|
||||
<Input
|
||||
placeholder="Kategori ara..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="with">Tümü (Kategoriler)</SelectItem>
|
||||
<SelectItem value="active">Sadece Aktif</SelectItem>
|
||||
<SelectItem value="only">Sadece Silinenler</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable columns={getColumns(fetchData, data)} data={data} />
|
||||
|
||||
<div className="flex items-center justify-end space-x-2 py-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => Math.max(old - 1, 1))}
|
||||
disabled={page === 1 || loading}
|
||||
>
|
||||
Önceki
|
||||
</Button>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Sayfa {page} / {totalPages || 1}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => (data.length === perPage ? old + 1 : old))}
|
||||
disabled={page >= totalPages || loading}
|
||||
>
|
||||
Sonraki
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<CategoryDialog
|
||||
open={showCreateDialog}
|
||||
onOpenChange={setShowCreateDialog}
|
||||
onSuccess={fetchData}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
59
frontend/app/admin/heroes/_components/columns.tsx
Normal file
59
frontend/app/admin/heroes/_components/columns.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
"use client"
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Hero } from "@/types/hero"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { HeroRowActions } from "./hero-row-actions"
|
||||
|
||||
export const getColumns = (onSuccess: () => void): ColumnDef<Hero>[] => [
|
||||
{
|
||||
accessorKey: "image",
|
||||
header: "Görsel",
|
||||
cell: ({ row }) => {
|
||||
const imagePath = row.getValue("image") as string
|
||||
if (!imagePath) return <div className="w-16 h-9 bg-gray-100 rounded" />
|
||||
|
||||
return (
|
||||
<div className="w-24 h-14 relative rounded overflow-hidden border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={`${process.env.NEXT_PUBLIC_API_URL}${imagePath}`}
|
||||
alt={row.original.title}
|
||||
className="object-cover w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: "Başlık",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: "Durum",
|
||||
cell: ({ row }) => {
|
||||
const isActive = row.getValue("is_active") as boolean
|
||||
return (
|
||||
<Badge variant={isActive ? "default" : "secondary"}>
|
||||
{isActive ? "Aktif" : "Pasif"}
|
||||
</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "DeletedAt",
|
||||
header: "Silinme Durumu",
|
||||
cell: ({ row }) => {
|
||||
const deletedAt = row.getValue("DeletedAt")
|
||||
if (deletedAt) {
|
||||
return <Badge variant="destructive">Silinmiş</Badge>
|
||||
}
|
||||
return null
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => <HeroRowActions row={row} onSuccess={onSuccess} />,
|
||||
},
|
||||
]
|
||||
82
frontend/app/admin/heroes/_components/data-table.tsx
Normal file
82
frontend/app/admin/heroes/_components/data-table.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
// eslint-disable-next-line react-hooks/incompatible-library
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columns.length} className="h-24 text-center">
|
||||
Sonuç bulunamadı.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
384
frontend/app/admin/heroes/_components/hero-dialog.tsx
Normal file
384
frontend/app/admin/heroes/_components/hero-dialog.tsx
Normal file
@@ -0,0 +1,384 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import * as z from "zod"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
FormDescription,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Hero } from "@/types/hero"
|
||||
import { heroService } from "@/services/heroService"
|
||||
import { toast } from "sonner"
|
||||
|
||||
// Zod Schema
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(2, "Başlık en az 2 karakter olmalıdır"),
|
||||
text1: z.string().optional(),
|
||||
text2: z.string().optional(),
|
||||
text4: z.string().optional(),
|
||||
text5: z.string().optional(),
|
||||
color: z.string().optional(),
|
||||
is_active: z.boolean(),
|
||||
width: z.coerce.number().min(1, "Genişlik 0'dan büyük olmalıdır"),
|
||||
height: z.coerce.number().min(1, "Yükseklik 0'dan büyük olmalıdır"),
|
||||
quality: z.coerce.number().min(1).max(100).default(85),
|
||||
format: z.string().optional().default("avif"),
|
||||
image: z.any().optional(),
|
||||
})
|
||||
|
||||
interface HeroDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
hero?: Hero | null
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function HeroDialog({ open, onOpenChange, hero, onSuccess }: HeroDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
title: "",
|
||||
text1: "",
|
||||
text2: "",
|
||||
text4: "",
|
||||
text5: "",
|
||||
color: "#000000",
|
||||
is_active: true,
|
||||
width: 0,
|
||||
height: 0,
|
||||
quality: 85,
|
||||
format: "webp",
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (hero) {
|
||||
form.reset({
|
||||
title: hero.title,
|
||||
text1: hero.text1 || "",
|
||||
text2: hero.text2 || "",
|
||||
text4: hero.text4 || "",
|
||||
text5: hero.text5 || "",
|
||||
color: hero.color || "#000000",
|
||||
is_active: !!hero.is_active,
|
||||
width: hero.width || 0,
|
||||
height: hero.height || 0,
|
||||
quality: hero.quality || 85,
|
||||
format: hero.format || "avif",
|
||||
})
|
||||
// Existing image preview
|
||||
// Backend returns relative path usually, ensure full URL if needed or use as is
|
||||
// Assuming backend/frontend serve static files correctly
|
||||
setPreview(hero.image ? `${process.env.NEXT_PUBLIC_API_URL}${hero.image}` : null)
|
||||
} else {
|
||||
form.reset({
|
||||
title: "",
|
||||
text1: "",
|
||||
text2: "",
|
||||
text4: "",
|
||||
text5: "",
|
||||
color: "#000000",
|
||||
is_active: true,
|
||||
width: 0,
|
||||
height: 0,
|
||||
quality: 85,
|
||||
format: "avif",
|
||||
})
|
||||
setPreview(null)
|
||||
}
|
||||
}, [hero, form, open])
|
||||
|
||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
form.setValue("image", file)
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
setPreview(reader.result as string)
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
setLoading(true)
|
||||
const formData = new FormData()
|
||||
formData.append("title", values.title)
|
||||
if (values.text1) formData.append("text1", values.text1)
|
||||
if (values.text2) formData.append("text2", values.text2)
|
||||
if (values.text4) formData.append("text4", values.text4)
|
||||
if (values.text5) formData.append("text5", values.text5)
|
||||
if (values.color) formData.append("color", values.color)
|
||||
formData.append("is_active", String(values.is_active))
|
||||
|
||||
// New fields
|
||||
formData.append("width", String(values.width))
|
||||
formData.append("height", String(values.height))
|
||||
formData.append("quality", String(values.quality))
|
||||
if (values.format) formData.append("format", values.format)
|
||||
|
||||
if (values.image instanceof File) {
|
||||
formData.append("image", values.image)
|
||||
}
|
||||
|
||||
try {
|
||||
if (hero) {
|
||||
await heroService.updateHero(hero.ID, formData)
|
||||
toast.success("Hero başarıyla güncellendi")
|
||||
} else {
|
||||
await heroService.createHero(formData)
|
||||
toast.success("Hero başarıyla oluşturuldu")
|
||||
}
|
||||
onOpenChange(false)
|
||||
if (onSuccess) onSuccess()
|
||||
} catch (error: unknown) {
|
||||
console.error("Hero save error:", error)
|
||||
toast.error((error as Error).message || "Bir hata oluştu")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{hero ? "Hero Düzenle" : "Yeni Hero Ekle"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Başlık</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Başlık" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="text1"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Text 1</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Text 1" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="text2"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Text 2</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Text 2" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="text4"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Text 4</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Text 4" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="text5"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Text 5</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Text 5" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="width"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Genişlik (px)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="height"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Yükseklik (px)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="quality"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Kalite (1-100)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" min="1" max="100" placeholder="80" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="format"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Format</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Format Seçin" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="avif">AVIF (Önerilen)</SelectItem>
|
||||
<SelectItem value="webp">WebP</SelectItem>
|
||||
<SelectItem value="jpeg">JPEG</SelectItem>
|
||||
<SelectItem value="png">PNG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="color"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Renk (Hex)</FormLabel>
|
||||
<div className="flex gap-2">
|
||||
<FormControl>
|
||||
<Input type="color" className="w-12 h-10 p-1" {...field} />
|
||||
</FormControl>
|
||||
<FormControl>
|
||||
<Input placeholder="#000000" {...field} />
|
||||
</FormControl>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="is_active"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel>Aktif</FormLabel>
|
||||
<FormDescription>
|
||||
Bu hero banner sitede görüntülensin mi?
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormItem>
|
||||
<FormLabel>Görsel</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleImageChange}
|
||||
/>
|
||||
</FormControl>
|
||||
{preview && (
|
||||
<div className="mt-2 relative w-full h-40 border rounded-md overflow-hidden">
|
||||
{/* Note: Using standard img for now to avoid Next.js Image Config issues with localhost */}
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={preview}
|
||||
alt="Preview"
|
||||
className="object-cover w-full h-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</FormItem>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
122
frontend/app/admin/heroes/_components/hero-row-actions.tsx
Normal file
122
frontend/app/admin/heroes/_components/hero-row-actions.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Row } from "@tanstack/react-table"
|
||||
import { MoreHorizontal, Pencil, Trash, Undo } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Hero } from "@/types/hero"
|
||||
import { heroService } from "@/services/heroService"
|
||||
import { toast } from "sonner"
|
||||
import { HeroDialog } from "./hero-dialog"
|
||||
import Swal from "sweetalert2"
|
||||
|
||||
interface DataTableRowActionsProps<TData> {
|
||||
row: Row<TData>
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export function HeroRowActions<TData extends Hero>({
|
||||
row,
|
||||
onSuccess,
|
||||
}: DataTableRowActionsProps<TData>) {
|
||||
const hero = row.original
|
||||
const [showEditDialog, setShowEditDialog] = useState(false)
|
||||
|
||||
const handleDelete = async () => {
|
||||
const result = await Swal.fire({
|
||||
title: "Emin misiniz?",
|
||||
text: "Bu hero silinecek! (Geri alabilirsiniz)",
|
||||
icon: "warning",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, sil",
|
||||
cancelButtonText: "İptal",
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await heroService.deleteHero(hero.ID)
|
||||
toast.success("Hero başarıyla silindi")
|
||||
onSuccess()
|
||||
} catch {
|
||||
toast.error("Silme işlemi başarısız")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async () => {
|
||||
const result = await Swal.fire({
|
||||
title: "Geri yüklemek istiyor musunuz?",
|
||||
text: "Bu hero tekrar aktif listeye alınacak.",
|
||||
icon: "question",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, geri yükle",
|
||||
cancelButtonText: "İptal",
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await heroService.restoreHero(hero.ID)
|
||||
toast.success("Hero başarıyla geri yüklendi")
|
||||
onSuccess()
|
||||
} catch {
|
||||
toast.error("Geri yükleme işlemi başarısız")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isDeleted = !!hero.DeletedAt
|
||||
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Menüyü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>İşlemler</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigator.clipboard.writeText(hero.ID.toString())}
|
||||
>
|
||||
Hero ID Kopyala
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
{!isDeleted && (
|
||||
<>
|
||||
<DropdownMenuItem onClick={() => setShowEditDialog(true)}>
|
||||
<Pencil className="mr-2 h-3.5 w-3.5" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
|
||||
<Trash className="mr-2 h-3.5 w-3.5" /> Sil
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{isDeleted && (
|
||||
<DropdownMenuItem onClick={handleRestore} className="text-green-600">
|
||||
<Undo className="mr-2 h-3.5 w-3.5" /> Geri Yükle
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<HeroDialog
|
||||
open={showEditDialog}
|
||||
onOpenChange={setShowEditDialog}
|
||||
hero={hero}
|
||||
onSuccess={onSuccess}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
122
frontend/app/admin/heroes/page.tsx
Normal file
122
frontend/app/admin/heroes/page.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { DataTable } from "./_components/data-table"
|
||||
import { getColumns } from "./_components/columns"
|
||||
import { Hero } from "@/types/hero"
|
||||
import { heroService } from "@/services/heroService"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus } from "lucide-react"
|
||||
import { HeroDialog } from "./_components/hero-dialog"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
export default function HeroesPage() {
|
||||
const [data, setData] = useState<Hero[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [perPage] = useState(20)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("with") // "with" shows active + deleted
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
// API expects "active" logic differently perhaps?
|
||||
// checking task.md/heroService docs:
|
||||
// heroService.getHeroes(page, perPage, search, soft)
|
||||
// soft: 'only' | 'with' | empty (defaults to active in some apis, but checking service impl)
|
||||
|
||||
// From service: soft param defaults to "with".
|
||||
const apiSoftFilter = statusFilter === "active" ? "" : statusFilter
|
||||
|
||||
const res = await heroService.getHeroes(page, perPage, search, apiSoftFilter)
|
||||
setData(res.items || [])
|
||||
setTotal(res.total || 0)
|
||||
} catch (error) {
|
||||
console.error("Heroes fetch error:", error)
|
||||
setData([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [page, perPage, search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
|
||||
return (
|
||||
<div className="p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Hero Banner Yönetimi</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Ana sayfa banner alanlarını yönetin.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowCreateDialog(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Yeni Hero
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center py-4 gap-4">
|
||||
<Input
|
||||
placeholder="Başlık ara..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="with">Tümü (Dahil)</SelectItem>
|
||||
<SelectItem value="active">Sadece Aktif</SelectItem>
|
||||
<SelectItem value="only">Sadece Silinenler</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable columns={getColumns(fetchData)} data={data} />
|
||||
|
||||
<div className="flex items-center justify-end space-x-2 py-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => Math.max(old - 1, 1))}
|
||||
disabled={page === 1 || loading}
|
||||
>
|
||||
Önceki
|
||||
</Button>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Sayfa {page} / {totalPages || 1}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => (data.length === perPage || page < totalPages ? old + 1 : old))}
|
||||
disabled={page >= totalPages || loading}
|
||||
>
|
||||
Sonraki
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<HeroDialog
|
||||
open={showCreateDialog}
|
||||
onOpenChange={setShowCreateDialog}
|
||||
onSuccess={fetchData}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
22
frontend/app/admin/layout.tsx
Normal file
22
frontend/app/admin/layout.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import { AdminHeader } from "@/components/admin/AdminHeader"
|
||||
import { AdminSidebar } from "@/components/admin/AdminSidebar"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full bg-muted/40 font-sans">
|
||||
<AdminSidebar />
|
||||
<div className="flex flex-col flex-1 w-full">
|
||||
<AdminHeader />
|
||||
<main className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
<Toaster />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
50
frontend/app/admin/page.tsx
Normal file
50
frontend/app/admin/page.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
"use client"
|
||||
|
||||
import { useSession, signOut } from "next-auth/react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const { data: session, status } = useSession()
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "unauthenticated") {
|
||||
router.push("/auth/login?callbackUrl=/admin")
|
||||
}
|
||||
}, [status, router])
|
||||
|
||||
if (status === "loading") {
|
||||
return <div className="flex h-screen items-center justify-center">Yükleniyor...</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<h1 className="text-3xl font-bold">Yönetici Paneli</h1>
|
||||
<div className="flex items-center gap-4">
|
||||
<span>Merhaba, {session?.user?.name || session?.user?.email}</span>
|
||||
<Button variant="outline" onClick={() => signOut({ callbackUrl: "/auth/login" })}>
|
||||
Çıkış Yap
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div className="p-6 bg-white rounded-lg shadow dark:bg-gray-800">
|
||||
<h3 className="text-lg font-semibold mb-2">Toplam Kullanıcı</h3>
|
||||
<p className="text-3xl font-bold">0</p>
|
||||
</div>
|
||||
<div className="p-6 bg-white rounded-lg shadow dark:bg-gray-800">
|
||||
<h3 className="text-lg font-semibold mb-2">Toplam Satış</h3>
|
||||
<p className="text-3xl font-bold">₺0.00</p>
|
||||
</div>
|
||||
<div className="p-6 bg-white rounded-lg shadow dark:bg-gray-800">
|
||||
<h3 className="text-lg font-semibold mb-2">Aktif Siparişler</h3>
|
||||
<p className="text-3xl font-bold">0</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
132
frontend/app/admin/posts/_components/columns.tsx
Normal file
132
frontend/app/admin/posts/_components/columns.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
"use client"
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Post } from "@/types/post"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Edit, Trash, RotateCcw } from "lucide-react"
|
||||
|
||||
interface PostColumnsProps {
|
||||
onEdit: (post: Post) => void
|
||||
onDelete: (id: number) => void
|
||||
onRestore: (id: number) => void
|
||||
statusFilter: string
|
||||
deletedIds: number[]
|
||||
}
|
||||
|
||||
export const getPostColumns = ({ onEdit, onDelete, onRestore, statusFilter, deletedIds }: PostColumnsProps): ColumnDef<Post>[] => [
|
||||
{
|
||||
accessorKey: "images",
|
||||
header: "Görsel",
|
||||
cell: ({ row }) => {
|
||||
const rawImages = row.original.images
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080"
|
||||
|
||||
// Backend tarafında "images" alanı virgülle ayrılmış birden fazla path içerebilir.
|
||||
// Liste görünümünde ilk path'i küçük görsel için kullanalım.
|
||||
const firstImage = rawImages
|
||||
? rawImages
|
||||
.split(",")
|
||||
.map(p => p.trim())
|
||||
.filter(Boolean)[0]
|
||||
: null
|
||||
|
||||
const fullUrl = firstImage
|
||||
? (firstImage.startsWith("http") ? firstImage : `${apiUrl}${firstImage}`)
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="w-16 h-10 bg-gray-100 rounded overflow-hidden flex items-center justify-center">
|
||||
{fullUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={fullUrl} alt={row.original.title} className="w-full h-full object-cover" />
|
||||
) : (
|
||||
<span className="text-xs text-gray-400">Yok</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: "Başlık",
|
||||
},
|
||||
{
|
||||
accessorKey: "categories",
|
||||
header: "Kategoriler",
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{row.original.categories?.map((cat, index) => (
|
||||
<span key={cat.id || cat.title || index} className="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
|
||||
{cat.title}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "tags",
|
||||
header: "Etiketler",
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{row.original.tags?.map((tag, index) => (
|
||||
<span key={tag.id || tag.name || index} className="px-2 py-1 bg-gray-100 text-gray-800 text-xs rounded-full">
|
||||
{tag.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "updated_at",
|
||||
header: "Son Güncelleme",
|
||||
cell: ({ row }) => {
|
||||
const updatedAt = row.original.updated_at || row.original.UpdatedAt
|
||||
return updatedAt ? new Date(updatedAt).toLocaleDateString("tr-TR") : "-"
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => {
|
||||
const id = row.original.id || row.original.ID
|
||||
const inDeletedList = typeof id === "number" && deletedIds.includes(id)
|
||||
|
||||
// "Sadece Silinenler" filtresinde hepsi silinmiş kabul edilir.
|
||||
// "Tümü (Dahil)" filtresinde ise deletedIds listesine bakılır.
|
||||
const isDeleted = statusFilter === "only" || inDeletedList
|
||||
return (
|
||||
<div className="flex gap-2 justify-end">
|
||||
{isDeleted ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onRestore(row.original.id || row.original.ID!)}
|
||||
className="h-8 w-8 p-0 text-green-600 hover:text-green-700 hover:bg-green-50"
|
||||
title="Geri Yükle"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onEdit(row.original)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => onDelete(row.original.id || row.original.ID!)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
437
frontend/app/admin/posts/_components/post-dialog.tsx
Normal file
437
frontend/app/admin/posts/_components/post-dialog.tsx
Normal file
@@ -0,0 +1,437 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import * as z from "zod"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Post } from "@/types/post"
|
||||
import { categoryService } from "@/services/categoryService"
|
||||
import { postService } from "@/services/postService"
|
||||
import { tagService } from "@/services/tagService"
|
||||
import { Category } from "@/types/category"
|
||||
import { Tag } from "@/types/tag"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { useSlug } from "@/hooks/useSlug"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
|
||||
// MultiSelect component specifically for Shadcn UI
|
||||
// Since Shadcn doesn't have a native MultiSelect, we'll use a simple implementation or standard select with multiple
|
||||
// For better UI, using a basic select list for now, ideally should use a proper MultiSelect component
|
||||
const MultiSelect = ({
|
||||
options,
|
||||
selected,
|
||||
onChange
|
||||
}: {
|
||||
options: { label: string; value: string }[]
|
||||
selected: string[]
|
||||
onChange: (values: string[]) => void
|
||||
}) => {
|
||||
return (
|
||||
<div className="border rounded-md p-2 max-h-40 overflow-y-auto">
|
||||
{options.map((option) => (
|
||||
<div key={option.value} className="flex items-center gap-2 mb-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
id={`opt-${option.value}`}
|
||||
checked={selected.includes(option.value)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
onChange([...selected, option.value])
|
||||
} else {
|
||||
onChange(selected.filter((v) => v !== option.value))
|
||||
}
|
||||
}}
|
||||
className="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
|
||||
/>
|
||||
<label htmlFor={`opt-${option.value}`} className="text-sm cursor-pointer select-none">
|
||||
{option.label}
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
{options.length === 0 && <p className="text-sm text-gray-500 py-2 text-center">Veri bulunamadı.</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(2, "Başlık en az 2 karakter olmalı"),
|
||||
slug: z.string().min(2, "Slug en az 2 karakter olmalı"),
|
||||
content: z.string().min(10, "İçerik en az 10 karakter olmalı"),
|
||||
category_ids: z.array(z.string()).min(1, "En az bir kategori seçilmelidir"),
|
||||
tag_names: z.array(z.string()).optional(), // Changed to array for MultiSelect
|
||||
|
||||
// Image Config
|
||||
images: z.any().optional(),
|
||||
width: z.coerce.number().min(1).default(800),
|
||||
height: z.coerce.number().min(1).default(600),
|
||||
quality: z.coerce.number().min(1).max(100).default(85),
|
||||
format: z.string().default("webp"),
|
||||
})
|
||||
|
||||
interface PostDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
post?: Post | null
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function PostDialog({ open, onOpenChange, post, onSuccess }: PostDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [categories, setCategories] = useState<Category[]>([])
|
||||
const [tags, setTags] = useState<Tag[]>([])
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
const { slugify } = useSlug()
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
title: "",
|
||||
slug: "",
|
||||
content: "",
|
||||
category_ids: [],
|
||||
tag_names: [],
|
||||
width: 800,
|
||||
height: 600,
|
||||
quality: 85,
|
||||
format: "webp",
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const catRes = await categoryService.getCategories(1, 100)
|
||||
setCategories(catRes.items || [])
|
||||
|
||||
const tagRes = await tagService.getTags(1, 100)
|
||||
setTags(tagRes.items || [])
|
||||
|
||||
} catch (error) {
|
||||
console.error("Failed to load categories/tags", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (open) {
|
||||
loadData()
|
||||
}
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (post) {
|
||||
const categoryIds =
|
||||
post.categories
|
||||
?.map(c => {
|
||||
const id = c.id ?? c.ID
|
||||
return id != null ? id.toString() : null
|
||||
})
|
||||
.filter((id): id is string => !!id) || []
|
||||
|
||||
form.reset({
|
||||
title: post.title,
|
||||
slug: post.slug,
|
||||
content: post.content,
|
||||
category_ids: categoryIds,
|
||||
tag_names: post.tags?.map(t => t.name) || [],
|
||||
width: post.width || 800,
|
||||
height: post.height || 600,
|
||||
quality: post.quality || 85,
|
||||
format: post.format || "webp",
|
||||
})
|
||||
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080"
|
||||
if (post.images) {
|
||||
// Backend \"images\" alanı birden fazla path'i virgülle birleştirebiliyor.
|
||||
// Dialog önizlemesi için ilk path'i kullan.
|
||||
const firstImage = post.images
|
||||
.split(",")
|
||||
.map(p => p.trim())
|
||||
.filter(Boolean)[0]
|
||||
|
||||
if (firstImage) {
|
||||
setPreview(firstImage.startsWith("http") ? firstImage : `${apiUrl}${firstImage}`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
form.reset({
|
||||
title: "",
|
||||
slug: "",
|
||||
content: "",
|
||||
category_ids: [],
|
||||
tag_names: [],
|
||||
width: 800,
|
||||
height: 600,
|
||||
quality: 85,
|
||||
format: "webp",
|
||||
})
|
||||
setPreview(null)
|
||||
}
|
||||
}, [post, form, open])
|
||||
|
||||
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const title = e.target.value
|
||||
form.setValue("title", title)
|
||||
if (!post) { // Only auto-slug on create
|
||||
form.setValue("slug", slugify(title))
|
||||
}
|
||||
}
|
||||
|
||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
form.setValue("images", file)
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
setPreview(reader.result as string)
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
setLoading(true)
|
||||
const formData = new FormData()
|
||||
|
||||
formData.append("title", values.title)
|
||||
formData.append("slug", values.slug)
|
||||
formData.append("content", values.content)
|
||||
|
||||
// Append categories - Backend likely expects multiple fields with same name or comma separated
|
||||
// Based on curl example: -F 'category_ids=1'
|
||||
// If multiple, standard is usually repeating the field
|
||||
values.category_ids.forEach(id => {
|
||||
formData.append("category_ids", id)
|
||||
})
|
||||
|
||||
// Tags - Backend, dokümana göre tekrar eden 'tag_names' alanlarını bekliyor:
|
||||
// -F 'tag_names=tag1' -F 'tag_names=tag2'
|
||||
if (values.tag_names && values.tag_names.length > 0) {
|
||||
values.tag_names.forEach(name => {
|
||||
formData.append("tag_names", name)
|
||||
})
|
||||
}
|
||||
|
||||
// Image config
|
||||
formData.append("width", values.width.toString())
|
||||
formData.append("height", values.height.toString())
|
||||
formData.append("quality", values.quality.toString())
|
||||
formData.append("format", values.format)
|
||||
|
||||
if (values.images instanceof File) {
|
||||
formData.append("images", values.images)
|
||||
}
|
||||
|
||||
try {
|
||||
if (post) {
|
||||
await postService.updatePost(post.id || post.ID!, formData)
|
||||
toast.success("Yazı başarıyla güncellendi")
|
||||
} else {
|
||||
await postService.createPost(formData)
|
||||
toast.success("Yazı başarıyla oluşturuldu")
|
||||
}
|
||||
onOpenChange(false)
|
||||
if (onSuccess) onSuccess()
|
||||
} catch (error: unknown) {
|
||||
console.error("Post save error:", error)
|
||||
toast.error((error as Error).message || "Bir hata oluştu")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[800px] h-[90vh] overflow-y-auto flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{post ? "Yazı Düzenle" : "Yeni Yazı Ekle"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto py-2">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<Tabs defaultValue="content" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="content">İçerik</TabsTrigger>
|
||||
<TabsTrigger value="media">Medya & SEO</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* CONTENT TAB */}
|
||||
<TabsContent value="content" className="space-y-4 pt-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Başlık</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Yazı Başlığı" {...field} onChange={handleTitleChange} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slug"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>SEO URL (Slug)</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="yazi-basligi" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="category_ids"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Kategoriler</FormLabel>
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={categories.map(c => ({ label: c.title, value: c.id.toString() }))}
|
||||
selected={field.value}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="tag_names"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Etiketler</FormLabel>
|
||||
<FormControl>
|
||||
<MultiSelect
|
||||
options={tags.map(t => ({ label: t.name, value: t.name }))}
|
||||
selected={field.value || []}
|
||||
onChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="content"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>İçerik</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea className="min-h-[300px]" placeholder="Yazı içeriği..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* MEDIA TAB */}
|
||||
<TabsContent value="media" className="space-y-4 pt-4">
|
||||
<div className="border p-4 rounded-md space-y-4">
|
||||
<h3 className="font-semibold text-lg">Öne Çıkan Görsel</h3>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="width"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Genişlik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="height"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Yükseklik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="quality"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Kalite</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="format"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Format</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger><SelectValue placeholder="Format" /></SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="webp">WebP</SelectItem>
|
||||
<SelectItem value="avif">AVIF</SelectItem>
|
||||
<SelectItem value="jpeg">JPEG</SelectItem>
|
||||
<SelectItem value="png">PNG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormItem>
|
||||
<FormLabel>Görsel Dosyası</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="file" accept="image/*" onChange={handleImageChange} />
|
||||
</FormControl>
|
||||
{preview && (
|
||||
<div className="mt-2 w-full h-48 bg-gray-100 rounded flex items-center justify-center overflow-hidden border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={preview} alt="Preview" className="h-full object-contain" />
|
||||
</div>
|
||||
)}
|
||||
</FormItem>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
238
frontend/app/admin/posts/page.tsx
Normal file
238
frontend/app/admin/posts/page.tsx
Normal file
@@ -0,0 +1,238 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { DataTable } from "@/components/ui/data-table"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus } from "lucide-react"
|
||||
import { postService } from "@/services/postService"
|
||||
import { Post } from "@/types/post"
|
||||
import { PostDialog } from "./_components/post-dialog"
|
||||
import { getPostColumns } from "./_components/columns"
|
||||
import { toast } from "sonner"
|
||||
import Swal from "sweetalert2"
|
||||
import withReactContent from "sweetalert2-react-content"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
const MySwal = withReactContent(Swal)
|
||||
|
||||
export default function PostsPage() {
|
||||
const { data: session } = useSession()
|
||||
const [posts, setPosts] = useState<Post[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [perPage] = useState(10)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("with") // "with" | "only" (backend defaults to active if not with/only)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [deletedIds, setDeletedIds] = useState<number[]>([])
|
||||
const [selectedPost, setSelectedPost] = useState<Post | null>(null)
|
||||
|
||||
const fetchPosts = useCallback(async () => {
|
||||
try {
|
||||
const res = await postService.getPosts(page, perPage, search, statusFilter)
|
||||
|
||||
// Liste verisini al
|
||||
const baseItems = res.items || []
|
||||
|
||||
// images alanı boş olanlar için, detay endpoint'inden gerçek images değerini çek
|
||||
const itemsWithImages = await Promise.all(
|
||||
baseItems.map(async (p) => {
|
||||
if (p.images && p.images.trim() !== "") {
|
||||
return p
|
||||
}
|
||||
const id = p.id || p.ID
|
||||
if (!id) {
|
||||
return p
|
||||
}
|
||||
try {
|
||||
const detail = await postService.getPost(id)
|
||||
return {
|
||||
...p,
|
||||
images: detail.data.images,
|
||||
}
|
||||
} catch {
|
||||
return p
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
setPosts(itemsWithImages)
|
||||
setTotal(res.total)
|
||||
|
||||
// Silinmiş post ID'lerini ayrıca takip et:
|
||||
if (statusFilter === "only") {
|
||||
const ids = itemsWithImages
|
||||
.map(p => p.id || p.ID)
|
||||
.filter((id): id is number => typeof id === "number")
|
||||
setDeletedIds(ids)
|
||||
} else if (statusFilter === "with") {
|
||||
// 'with' görünümünde, silinmişleri ayrı bir çağrı ile çekelim
|
||||
try {
|
||||
const deletedRes = await postService.getPosts(1, 200, search, "only")
|
||||
const ids = (deletedRes.items || [])
|
||||
.map(p => p.id || p.ID)
|
||||
.filter((id): id is number => typeof id === "number")
|
||||
setDeletedIds(ids)
|
||||
} catch (e) {
|
||||
console.error("Silinmiş yazılar alınamadı:", e)
|
||||
setDeletedIds([])
|
||||
}
|
||||
} else {
|
||||
// Sadece aktif filtresinde silinmiş saymayalım
|
||||
setDeletedIds([])
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error("Yazılar yüklenirken hata oluştu")
|
||||
console.error(error)
|
||||
}
|
||||
}, [page, perPage, search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
fetchPosts()
|
||||
}
|
||||
}, [session, fetchPosts])
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
const result = await MySwal.fire({
|
||||
title: "Emin misiniz?",
|
||||
text: "Bu yazıyı silmek istediğinize emin misiniz?",
|
||||
icon: "warning",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, Sil",
|
||||
cancelButtonText: "İptal",
|
||||
customClass: {
|
||||
popup: "dark:bg-gray-800 dark:text-white",
|
||||
title: "dark:text-white",
|
||||
},
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await postService.deletePost(id)
|
||||
toast.success("Yazı başarıyla silindi")
|
||||
fetchPosts()
|
||||
} catch (error) {
|
||||
toast.error("Silme işlemi başarısız oldu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async (id: number) => {
|
||||
const result = await MySwal.fire({
|
||||
title: "Geri Yükle?",
|
||||
text: "Bu yazıyı geri yüklemek istediğinize emin misiniz?",
|
||||
icon: "question",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, Geri Yükle",
|
||||
cancelButtonText: "İptal",
|
||||
customClass: {
|
||||
popup: "dark:bg-gray-800 dark:text-white",
|
||||
title: "dark:text-white",
|
||||
},
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await postService.restorePost(id)
|
||||
toast.success("Yazı başarıyla geri yüklendi")
|
||||
fetchPosts()
|
||||
} catch (error) {
|
||||
toast.error("Geri yükleme başarısız oldu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = async (post: Post) => {
|
||||
try {
|
||||
const id = post.id || post.ID
|
||||
if (!id) {
|
||||
toast.error("Yazı ID'si bulunamadı")
|
||||
return
|
||||
}
|
||||
|
||||
// Detay endpoint'inden güncel veriyi çek
|
||||
const res = await postService.getPost(id)
|
||||
setSelectedPost(res.data)
|
||||
setDialogOpen(true)
|
||||
} catch (error) {
|
||||
console.error("Yazı detayı alınamadı:", error)
|
||||
toast.error("Yazı detayı alınamadı")
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreate = () => {
|
||||
setSelectedPost(null)
|
||||
setDialogOpen(true)
|
||||
}
|
||||
|
||||
const columns = getPostColumns({
|
||||
onEdit: handleEdit,
|
||||
onDelete: handleDelete,
|
||||
onRestore: handleRestore,
|
||||
statusFilter,
|
||||
deletedIds,
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Blog Yazıları</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Blog içeriğini, kategorileri ve etiketleri yönetin.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={handleCreate}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Yeni Yazı
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center py-4 gap-4">
|
||||
<Input
|
||||
placeholder="Başlık ara..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="with">Tümü (Dahil)</SelectItem>
|
||||
{/* Backend logic: empty 'soft' param usually means active only, 'only' means deleted only */}
|
||||
<SelectItem value="active">Sadece Aktif</SelectItem>
|
||||
<SelectItem value="only">Sadece Silinenler</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={posts}
|
||||
pageCount={Math.ceil(total / perPage)}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
|
||||
<PostDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
post={selectedPost}
|
||||
onSuccess={fetchPosts}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
582
frontend/app/admin/settings/_components/setting-dialog.tsx
Normal file
582
frontend/app/admin/settings/_components/setting-dialog.tsx
Normal file
@@ -0,0 +1,582 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import * as z from "zod"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
FormDescription,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" // Assume these exist or need verify
|
||||
import { Setting } from "@/types/setting"
|
||||
import { settingService } from "@/services/settingService"
|
||||
import { toast } from "sonner"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(2, "Başlık en az 2 karakter olmalı"),
|
||||
slogan: z.string().optional(),
|
||||
url: z.string().url("Geçerli bir URL giriniz").optional().or(z.literal("")),
|
||||
email: z.string().email("Geçerli bir e-posta giriniz").optional().or(z.literal("")),
|
||||
phone: z.string().optional(),
|
||||
address: z.string().optional(),
|
||||
copyright: z.string().optional(),
|
||||
map_embed: z.string().optional(),
|
||||
meta_title: z.string().optional(),
|
||||
meta_description: z.string().optional(),
|
||||
|
||||
// Social
|
||||
facebook: z.string().url().optional().or(z.literal("")),
|
||||
x: z.string().url().optional().or(z.literal("")),
|
||||
instagram: z.string().url().optional().or(z.literal("")),
|
||||
whatsapp: z.string().optional(), // clean number usually
|
||||
linkedin: z.string().url().optional().or(z.literal("")),
|
||||
pinterest: z.string().url().optional().or(z.literal("")),
|
||||
|
||||
// Config
|
||||
is_active: z.boolean().default(false),
|
||||
|
||||
// Images W Logo
|
||||
w_logo: z.any().optional(),
|
||||
w_width: z.coerce.number().min(1).default(100),
|
||||
w_height: z.coerce.number().min(1).default(100),
|
||||
w_quality: z.coerce.number().min(1).max(100).default(85),
|
||||
w_format: z.string().default("avif"),
|
||||
|
||||
// Images B Logo
|
||||
b_logo: z.any().optional(),
|
||||
b_width: z.coerce.number().min(1).default(100),
|
||||
b_height: z.coerce.number().min(1).default(100),
|
||||
b_quality: z.coerce.number().min(1).max(100).default(85),
|
||||
b_format: z.string().default("avif"),
|
||||
})
|
||||
|
||||
interface SettingDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
setting?: Setting | null
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function SettingDialog({ open, onOpenChange, setting, onSuccess }: SettingDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [wPreview, setWPreview] = useState<string | null>(null)
|
||||
const [bPreview, setBPreview] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
resolver: zodResolver(formSchema) as any,
|
||||
defaultValues: {
|
||||
title: "",
|
||||
slogan: "",
|
||||
url: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
address: "",
|
||||
copyright: "",
|
||||
map_embed: "",
|
||||
meta_title: "",
|
||||
meta_description: "",
|
||||
facebook: "",
|
||||
x: "",
|
||||
instagram: "",
|
||||
whatsapp: "",
|
||||
linkedin: "",
|
||||
pinterest: "",
|
||||
is_active: false,
|
||||
w_width: 100,
|
||||
w_height: 100,
|
||||
w_quality: 85,
|
||||
w_format: "avif",
|
||||
b_width: 100,
|
||||
b_height: 100,
|
||||
b_quality: 85,
|
||||
b_format: "avif",
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (setting) {
|
||||
form.reset({
|
||||
title: setting.title,
|
||||
slogan: setting.slogan || "",
|
||||
url: setting.url || "",
|
||||
email: setting.email || "",
|
||||
phone: setting.phone || "",
|
||||
address: setting.address || "",
|
||||
copyright: setting.copyright || "",
|
||||
map_embed: setting.map_embed || "",
|
||||
meta_title: setting.meta_title || "",
|
||||
meta_description: setting.meta_description || "",
|
||||
facebook: setting.facebook || "",
|
||||
x: setting.x || "",
|
||||
instagram: setting.instagram || "",
|
||||
whatsapp: setting.whatsapp || "",
|
||||
linkedin: setting.linkedin || "",
|
||||
pinterest: setting.pinterest || "",
|
||||
is_active: !!setting.is_active,
|
||||
w_width: setting.w_width || 100,
|
||||
w_height: setting.w_height || 100,
|
||||
w_quality: setting.w_quality || 85,
|
||||
w_format: setting.w_format || "avif",
|
||||
b_width: setting.b_width || 100,
|
||||
b_height: setting.b_height || 100,
|
||||
b_quality: setting.b_quality || 85,
|
||||
b_format: setting.b_format || "avif",
|
||||
})
|
||||
|
||||
// Set previews
|
||||
// Assuming backend serves images from a static path, need env URL
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8080"
|
||||
if (setting.w_logo) {
|
||||
// Check if it's already a full URL or relative
|
||||
setWPreview(setting.w_logo.startsWith("http") ? setting.w_logo : `${apiUrl}${setting.w_logo}`)
|
||||
}
|
||||
if (setting.b_logo) {
|
||||
setBPreview(setting.b_logo.startsWith("http") ? setting.b_logo : `${apiUrl}${setting.b_logo}`)
|
||||
}
|
||||
|
||||
} else {
|
||||
form.reset({
|
||||
title: "",
|
||||
slogan: "",
|
||||
url: "",
|
||||
email: "",
|
||||
phone: "",
|
||||
address: "",
|
||||
copyright: "",
|
||||
map_embed: "",
|
||||
meta_title: "",
|
||||
meta_description: "",
|
||||
facebook: "",
|
||||
x: "",
|
||||
instagram: "",
|
||||
whatsapp: "",
|
||||
linkedin: "",
|
||||
pinterest: "",
|
||||
is_active: false,
|
||||
w_width: 100,
|
||||
w_height: 100,
|
||||
w_quality: 85,
|
||||
w_format: "avif",
|
||||
b_width: 100,
|
||||
b_height: 100,
|
||||
b_quality: 85,
|
||||
b_format: "avif",
|
||||
})
|
||||
setWPreview(null)
|
||||
setBPreview(null)
|
||||
}
|
||||
}, [setting, form, open])
|
||||
|
||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>, fieldName: "w_logo" | "b_logo") => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
form.setValue(fieldName, file)
|
||||
const reader = new FileReader()
|
||||
reader.onloadend = () => {
|
||||
if (fieldName === "w_logo") setWPreview(reader.result as string)
|
||||
else setBPreview(reader.result as string)
|
||||
}
|
||||
reader.readAsDataURL(file)
|
||||
}
|
||||
}
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
setLoading(true)
|
||||
const formData = new FormData()
|
||||
|
||||
// Append basic fields
|
||||
Object.entries(values).forEach(([key, value]) => {
|
||||
if (key !== "w_logo" && key !== "b_logo") {
|
||||
formData.append(key, String(value))
|
||||
}
|
||||
})
|
||||
|
||||
// Append images if they are files
|
||||
if (values.w_logo instanceof File) {
|
||||
formData.append("w_logo", values.w_logo)
|
||||
}
|
||||
if (values.b_logo instanceof File) {
|
||||
formData.append("b_logo", values.b_logo)
|
||||
}
|
||||
|
||||
try {
|
||||
if (setting) {
|
||||
await settingService.updateSetting(setting.ID, formData)
|
||||
toast.success("Ayar başarıyla güncellendi")
|
||||
} else {
|
||||
await settingService.createSetting(formData)
|
||||
toast.success("Ayar başarıyla oluşturuldu")
|
||||
}
|
||||
onOpenChange(false)
|
||||
if (onSuccess) onSuccess()
|
||||
} catch (error: unknown) {
|
||||
console.error("Setting save error:", error)
|
||||
toast.error((error as Error).message || "Bir hata oluştu")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[800px] h-[90vh] overflow-y-auto flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{setting ? "Ayar Düzenle" : "Yeni Ayar Ekle"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto py-2">
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<Tabs defaultValue="general" className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-4">
|
||||
<TabsTrigger value="general">Genel</TabsTrigger>
|
||||
<TabsTrigger value="contact">İletişim</TabsTrigger>
|
||||
<TabsTrigger value="social">Sosyal Medya</TabsTrigger>
|
||||
<TabsTrigger value="images">Görseller</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* GENERAL TAB */}
|
||||
<TabsContent value="general" className="space-y-4 pt-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Site Başlığı</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Site Başlığı" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="slogan"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Slogan</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Slogan" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="meta_title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Meta Başlığı</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="SEO için Başlık" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="meta_description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Meta Açıklama</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="SEO için Açıklama" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="is_active"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm bg-destructive/10">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="font-bold text-destructive">Aktif Ayar</FormLabel>
|
||||
<FormDescription>
|
||||
Bu ayarı aktif yaparsanız, diğer tüm ayarlar otomatik olarak pasif duruma geçer.
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* CONTACT TAB */}
|
||||
<TabsContent value="contact" className="space-y-4 pt-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>E-posta</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="ornek@site.com" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Telefon</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="+90 555 ..." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="url"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Site URL</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="https://site.com" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="address"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Adres</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="Adres bilgisi" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="map_embed"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Harita Embed Kodu (Iframe)</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder='<iframe src="..." ...></iframe>' {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="copyright"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Telif Hakkı Metni</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="© 2024 Tüm hakları saklıdır." {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* SOCIAL TAB */}
|
||||
<TabsContent value="social" className="space-y-4 pt-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField control={form.control} name="facebook" render={({ field }) => (
|
||||
<FormItem><FormLabel>Facebook</FormLabel><FormControl><Input placeholder="URL" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="x" render={({ field }) => (
|
||||
<FormItem><FormLabel>X (Twitter)</FormLabel><FormControl><Input placeholder="URL" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="instagram" render={({ field }) => (
|
||||
<FormItem><FormLabel>Instagram</FormLabel><FormControl><Input placeholder="URL" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="linkedin" render={({ field }) => (
|
||||
<FormItem><FormLabel>LinkedIn</FormLabel><FormControl><Input placeholder="URL" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="pinterest" render={({ field }) => (
|
||||
<FormItem><FormLabel>Pinterest</FormLabel><FormControl><Input placeholder="URL" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="whatsapp" render={({ field }) => (
|
||||
<FormItem><FormLabel>Whatsapp</FormLabel><FormControl><Input placeholder="Numara" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
{/* IMAGES TAB */}
|
||||
<TabsContent value="images" className="space-y-4 pt-4">
|
||||
{/* White Logo Config */}
|
||||
<div className="border p-4 rounded-md space-y-4">
|
||||
<h3 className="font-semibold text-lg">Beyaz Yazılı Logo (w_logo)</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="w_width"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Genişlik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="w_height"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Yükseklik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="w_quality"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Kalite</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="w_format"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Format</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger><SelectValue placeholder="Format" /></SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="avif">AVIF</SelectItem>
|
||||
<SelectItem value="webp">WebP</SelectItem>
|
||||
<SelectItem value="png">PNG</SelectItem>
|
||||
<SelectItem value="jpeg">JPEG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormItem>
|
||||
<FormLabel>Logo Dosyası</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="file" accept="image/*" onChange={(e) => handleImageChange(e, "w_logo")} />
|
||||
</FormControl>
|
||||
{wPreview && (
|
||||
<div className="mt-2 w-full h-20 bg-gray-100 rounded flex items-center justify-center overflow-hidden border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={wPreview} alt="W Logo Preview" className="h-full object-contain" />
|
||||
</div>
|
||||
)}
|
||||
</FormItem>
|
||||
</div>
|
||||
|
||||
{/* Black Logo Config */}
|
||||
<div className="border p-4 rounded-md space-y-4">
|
||||
<h3 className="font-semibold text-lg">Siyah Yazılı Logo (b_logo)</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="b_width"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Genişlik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="b_height"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Yükseklik</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="b_quality"
|
||||
render={({ field }) => (
|
||||
<FormItem><FormLabel>Kalite</FormLabel><FormControl><Input type="number" {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="b_format"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Format</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger><SelectValue placeholder="Format" /></SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="avif">AVIF</SelectItem>
|
||||
<SelectItem value="webp">WebP</SelectItem>
|
||||
<SelectItem value="png">PNG</SelectItem>
|
||||
<SelectItem value="jpeg">JPEG</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<FormItem>
|
||||
<FormLabel>Logo Dosyası</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="file" accept="image/*" onChange={(e) => handleImageChange(e, "b_logo")} />
|
||||
</FormControl>
|
||||
{bPreview && (
|
||||
<div className="mt-2 w-full h-20 bg-gray-100 rounded flex items-center justify-center overflow-hidden border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={bPreview} alt="B Logo Preview" className="h-full object-contain" />
|
||||
</div>
|
||||
)}
|
||||
</FormItem>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
229
frontend/app/admin/settings/page.tsx
Normal file
229
frontend/app/admin/settings/page.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { DataTable } from "@/components/ui/data-table"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus, Edit, Trash, RotateCcw } from "lucide-react"
|
||||
import { settingService } from "@/services/settingService"
|
||||
import { Setting } from "@/types/setting"
|
||||
import { SettingDialog } from "./_components/setting-dialog"
|
||||
import { toast } from "sonner"
|
||||
import Swal from "sweetalert2"
|
||||
import withReactContent from "sweetalert2-react-content"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
const MySwal = withReactContent(Swal)
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { data: session } = useSession()
|
||||
const [settings, setSettings] = useState<Setting[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(1)
|
||||
const [perPage] = useState(10)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("with") // "with" | "active" | "only"
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [selectedSetting, setSelectedSetting] = useState<Setting | null>(null)
|
||||
|
||||
const fetchSettings = useCallback(async () => {
|
||||
try {
|
||||
// "active" -> "" (backend default?), "with" -> "with", "only" -> "only"
|
||||
const apiSoftFilter = statusFilter === "active" ? "" : statusFilter
|
||||
const res = await settingService.getSettings(page, perPage, search, apiSoftFilter)
|
||||
setSettings(res.items || [])
|
||||
setTotal(res.total)
|
||||
} catch (error) {
|
||||
toast.error("Ayarlar yüklenirken hata oluştu")
|
||||
console.error(error)
|
||||
}
|
||||
}, [page, perPage, search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
fetchSettings()
|
||||
}
|
||||
}, [session, fetchSettings])
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
const result = await MySwal.fire({
|
||||
title: "Emin misiniz?",
|
||||
text: "Bu ayarı silmek istediğinize emin misiniz?",
|
||||
icon: "warning",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, Sil",
|
||||
cancelButtonText: "İptal",
|
||||
customClass: {
|
||||
popup: "dark:bg-gray-800 dark:text-white",
|
||||
title: "dark:text-white",
|
||||
},
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await settingService.deleteSetting(id)
|
||||
toast.success("Ayar başarıyla silindi")
|
||||
fetchSettings()
|
||||
} catch (error) {
|
||||
toast.error("Silme işlemi başarısız oldu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async (id: number) => {
|
||||
const result = await MySwal.fire({
|
||||
title: "Geri Yükle?",
|
||||
text: "Bu ayarı geri yüklemek istediğinize emin misiniz?",
|
||||
icon: "question",
|
||||
showCancelButton: true,
|
||||
confirmButtonText: "Evet, Geri Yükle",
|
||||
cancelButtonText: "İptal",
|
||||
customClass: {
|
||||
popup: "dark:bg-gray-800 dark:text-white",
|
||||
title: "dark:text-white",
|
||||
},
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await settingService.restoreSetting(id)
|
||||
toast.success("Ayar başarıyla geri yüklendi")
|
||||
fetchSettings()
|
||||
} catch (error) {
|
||||
toast.error("Geri yükleme başarısız oldu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{
|
||||
accessorKey: "title",
|
||||
header: "Başlık",
|
||||
},
|
||||
{
|
||||
accessorKey: "is_active",
|
||||
header: "Durum",
|
||||
cell: ({ row }: { row: { original: Setting } }) => (
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs ${row.original.is_active ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"
|
||||
}`}
|
||||
>
|
||||
{row.original.is_active ? "Aktif" : "Pasif"}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "UpdatedAt",
|
||||
header: "Son Güncelleme",
|
||||
cell: ({ row }: { row: { original: Setting } }) => {
|
||||
return new Date(row.original.UpdatedAt).toLocaleDateString("tr-TR")
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }: { row: { original: Setting } }) => {
|
||||
const isDeleted = !!row.original.DeletedAt
|
||||
return (
|
||||
<div className="flex gap-2 justify-end">
|
||||
{isDeleted ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleRestore(row.original.ID)}
|
||||
className="h-8 w-8 p-0 text-green-600 hover:text-green-700 hover:bg-green-50"
|
||||
title="Geri Yükle"
|
||||
>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setSelectedSetting(row.original)
|
||||
setDialogOpen(true)
|
||||
}}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Edit className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(row.original.ID)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Site Ayarları</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Genel site ayarlarını ve SEO yapılandırmalarını yönetin.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => {
|
||||
setSelectedSetting(null)
|
||||
setDialogOpen(true)
|
||||
}}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Yeni Ayar
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center py-4 gap-4">
|
||||
<Input
|
||||
placeholder="Başlık ara..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="with">Tümü (Dahil)</SelectItem>
|
||||
<SelectItem value="active">Sadece Aktif</SelectItem>
|
||||
<SelectItem value="only">Sadece Silinenler</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={settings}
|
||||
pageCount={Math.ceil(total / perPage)}
|
||||
page={page}
|
||||
onPageChange={setPage}
|
||||
/>
|
||||
|
||||
<SettingDialog
|
||||
open={dialogOpen}
|
||||
onOpenChange={setDialogOpen}
|
||||
setting={selectedSetting}
|
||||
onSuccess={fetchSettings}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
55
frontend/app/admin/tags/columns.tsx
Normal file
55
frontend/app/admin/tags/columns.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
"use client"
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table"
|
||||
import { Tag } from "@/types/tag"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
import { DataTableRowActions } from "./tag-row-actions"
|
||||
|
||||
export const getColumns = (onRefresh: () => void): ColumnDef<Tag>[] => [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
ID
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
Tag Adı
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "deleted_at",
|
||||
header: "Durum",
|
||||
cell: ({ row }) => {
|
||||
const deletedAt = row.original.deleted_at
|
||||
return deletedAt ? (
|
||||
<Badge variant="destructive">Silindi</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">Aktif</Badge>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }) => <DataTableRowActions row={row} onRefresh={onRefresh} />,
|
||||
},
|
||||
]
|
||||
91
frontend/app/admin/tags/data-table.tsx
Normal file
91
frontend/app/admin/tags/data-table.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
SortingState,
|
||||
getSortedRowModel,
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
|
||||
// eslint-disable-next-line
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
onSortingChange: setSorting,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
sorting,
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columns.length} className="h-24 text-center">
|
||||
Sonuç bulunamadı.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
115
frontend/app/admin/tags/page.tsx
Normal file
115
frontend/app/admin/tags/page.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback } from "react"
|
||||
import { DataTable } from "./data-table"
|
||||
import { getColumns } from "./columns"
|
||||
import { Tag } from "@/types/tag"
|
||||
import { tagService } from "@/services/tagService"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Plus } from "lucide-react"
|
||||
import { TagDialog } from "./tag-dialog"
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
|
||||
export default function TagsPage() {
|
||||
const [data, setData] = useState<Tag[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [perPage] = useState(20)
|
||||
const [search, setSearch] = useState("")
|
||||
const [statusFilter, setStatusFilter] = useState("with") // "with" shows active + deleted
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false)
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const apiSoftFilter = statusFilter === "active" ? "" : statusFilter
|
||||
const res = await tagService.getTags(page, perPage, search, apiSoftFilter)
|
||||
setData(res.items || [])
|
||||
setTotal(res.total || 0)
|
||||
} catch (error) {
|
||||
console.error("Tags fetch error:", error)
|
||||
setData([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [page, perPage, search, statusFilter])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
|
||||
return (
|
||||
<div className="p-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Tag Yönetimi</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Tagları oluşturun, düzenleyin veya silin.
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowCreateDialog(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" /> Yeni Tag
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center py-4 gap-4">
|
||||
<Input
|
||||
placeholder="Tag ara..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="with">Tümü (Tags)</SelectItem>
|
||||
<SelectItem value="active">Sadece Aktif</SelectItem>
|
||||
<SelectItem value="only">Sadece Silinenler</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<DataTable columns={getColumns(fetchData)} data={data} />
|
||||
|
||||
<div className="flex items-center justify-end space-x-2 py-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => Math.max(old - 1, 1))}
|
||||
disabled={page === 1 || loading}
|
||||
>
|
||||
Önceki
|
||||
</Button>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
Sayfa {page} / {totalPages || 1}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setPage((old) => (data.length === perPage ? old + 1 : old))}
|
||||
disabled={page >= totalPages || loading}
|
||||
>
|
||||
Sonraki
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<TagDialog
|
||||
open={showCreateDialog}
|
||||
onOpenChange={setShowCreateDialog}
|
||||
onSuccess={fetchData}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
110
frontend/app/admin/tags/tag-dialog.tsx
Normal file
110
frontend/app/admin/tags/tag-dialog.tsx
Normal file
@@ -0,0 +1,110 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import * as z from "zod"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Tag } from "@/types/tag"
|
||||
import { tagService } from "@/services/tagService"
|
||||
import { toast } from "sonner"
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(2, {
|
||||
message: "Tag adı en az 2 karakter olmalıdır.",
|
||||
}),
|
||||
})
|
||||
|
||||
interface TagDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
tag?: Tag | null // Editing if provided
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function TagDialog({ open, onOpenChange, tag, onSuccess }: TagDialogProps) {
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: "",
|
||||
},
|
||||
})
|
||||
|
||||
// Reset form when dialog opens or tag changes
|
||||
useEffect(() => {
|
||||
if (tag) {
|
||||
form.reset({
|
||||
name: tag.name,
|
||||
})
|
||||
} else {
|
||||
form.reset({
|
||||
name: "",
|
||||
})
|
||||
}
|
||||
}, [tag, form, open])
|
||||
|
||||
const onSubmit = async (values: z.infer<typeof formSchema>) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
if (tag) {
|
||||
await tagService.updateTag(tag.id, values.name)
|
||||
toast.success("Tag başarıyla güncellendi")
|
||||
} else {
|
||||
await tagService.createTag(values.name)
|
||||
toast.success("Tag başarıyla oluşturuldu")
|
||||
}
|
||||
onOpenChange(false)
|
||||
if (onSuccess) {
|
||||
onSuccess()
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
toast.error((error as Error).message || "Bir hata oluştu")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{tag ? "Tag Düzenle" : "Yeni Tag Ekle"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Tag Adı</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Teknoloji" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
141
frontend/app/admin/tags/tag-row-actions.tsx
Normal file
141
frontend/app/admin/tags/tag-row-actions.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Row } from "@tanstack/react-table"
|
||||
import { MoreHorizontal, Pencil, Trash, RefreshCcw } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Tag } from "@/types/tag"
|
||||
import { tagService } from "@/services/tagService"
|
||||
import { TagDialog } from "./tag-dialog"
|
||||
import Swal from 'sweetalert2'
|
||||
import withReactContent from 'sweetalert2-react-content'
|
||||
|
||||
const MySwal = withReactContent(Swal)
|
||||
|
||||
interface DataTableRowActionsProps<TData> {
|
||||
row: Row<TData>
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
export function DataTableRowActions<TData>({
|
||||
row,
|
||||
onRefresh,
|
||||
}: DataTableRowActionsProps<TData>) {
|
||||
const tag = row.original as Tag
|
||||
const [showEditDialog, setShowEditDialog] = useState(false)
|
||||
const isDeleted = !!tag.deleted_at
|
||||
|
||||
const handleDelete = async () => {
|
||||
const result = await MySwal.fire({
|
||||
title: 'Emin misiniz?',
|
||||
text: "Bu tag silinecek!",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Evet, sil!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await tagService.deleteTag(tag.id)
|
||||
MySwal.fire(
|
||||
'Silindi!',
|
||||
'Tag başarıyla silindi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
} catch {
|
||||
MySwal.fire(
|
||||
'Hata!',
|
||||
'Bir hata oluştu.',
|
||||
'error'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async () => {
|
||||
const result = await MySwal.fire({
|
||||
title: 'Geri Yükle?',
|
||||
text: "Bu tag geri yüklenecek!",
|
||||
icon: 'question',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Evet, geri yükle!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
await tagService.restoreTag(tag.id)
|
||||
MySwal.fire(
|
||||
'Geri Yüklendi!',
|
||||
'Tag başarıyla geri yüklendi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
} catch {
|
||||
MySwal.fire(
|
||||
'Hata!',
|
||||
'Bir hata oluştu.',
|
||||
'error'
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<TagDialog
|
||||
open={showEditDialog}
|
||||
onOpenChange={setShowEditDialog}
|
||||
tag={tag}
|
||||
onSuccess={onRefresh}
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Menü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuLabel>İşlemler</DropdownMenuLabel>
|
||||
<DropdownMenuItem
|
||||
onClick={() => navigator.clipboard.writeText(tag.id.toString())}
|
||||
>
|
||||
Tag ID Kopyala
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
{!isDeleted && (
|
||||
<DropdownMenuItem onClick={() => setShowEditDialog(true)}>
|
||||
<Pencil className="mr-2 h-4 w-4" /> Düzenle
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{isDeleted ? (
|
||||
<DropdownMenuItem onClick={handleRestore}>
|
||||
<RefreshCcw className="mr-2 h-4 w-4 text-green-600" /> Geri Yükle
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
|
||||
<Trash className="mr-2 h-4 w-4" /> Sil
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)
|
||||
}
|
||||
94
frontend/app/admin/users/columns.tsx
Normal file
94
frontend/app/admin/users/columns.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client"
|
||||
|
||||
import { ColumnDef, HeaderContext, CellContext } from "@tanstack/react-table"
|
||||
import { User } from "@/types/user"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Check, X } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { ArrowUpDown } from "lucide-react"
|
||||
|
||||
// Actions cell component will be added later or inline if simple
|
||||
import { DataTableRowActions } from "./user-row-actions"
|
||||
|
||||
export const getColumns = (onRefresh: () => void): ColumnDef<User>[] => [
|
||||
{
|
||||
accessorKey: "id",
|
||||
header: ({ column }: HeaderContext<User, unknown>) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
ID
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "username",
|
||||
header: ({ column }: HeaderContext<User, unknown>) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
Kullanıcı Adı
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
header: ({ column }: HeaderContext<User, unknown>) => {
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
|
||||
>
|
||||
Email
|
||||
<ArrowUpDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "email_verified",
|
||||
header: "Doğrulandı",
|
||||
cell: ({ row }: CellContext<User, unknown>) => {
|
||||
return row.getValue("email_verified") ? (
|
||||
<Badge variant="secondary" className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300"><Check className="w-3 h-3 mr-1" /> Evet</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-gray-500"><X className="w-3 h-3 mr-1" /> Hayır</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "deleted_at",
|
||||
header: "Durum",
|
||||
cell: ({ row }) => {
|
||||
const deletedAt = row.original.deleted_at
|
||||
return deletedAt ? (
|
||||
<Badge variant="destructive">Silindi</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">Aktif</Badge>
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
accessorKey: "is_admin",
|
||||
header: "Rol",
|
||||
cell: ({ row }: CellContext<User, unknown>) => {
|
||||
return row.getValue("is_admin") ? (
|
||||
<Badge variant="default">Admin</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">User</Badge>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
cell: ({ row }: CellContext<User, unknown>) => <DataTableRowActions row={row} onRefresh={onRefresh} />,
|
||||
},
|
||||
]
|
||||
100
frontend/app/admin/users/data-table.tsx
Normal file
100
frontend/app/admin/users/data-table.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ColumnDef,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
SortingState,
|
||||
getSortedRowModel,
|
||||
HeaderGroup,
|
||||
Header,
|
||||
Row,
|
||||
Cell
|
||||
} from "@tanstack/react-table"
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table"
|
||||
|
||||
interface DataTableProps<TData, TValue> {
|
||||
columns: ColumnDef<TData, TValue>[]
|
||||
data: TData[]
|
||||
}
|
||||
|
||||
export function DataTable<TData, TValue>({
|
||||
columns,
|
||||
data,
|
||||
}: DataTableProps<TData, TValue>) {
|
||||
const [sorting, setSorting] = React.useState<SortingState>([])
|
||||
|
||||
// eslint-disable-next-line react-hooks/incompatible-library
|
||||
const table = useReactTable({
|
||||
data,
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
// Pagination is handled server-side in the main page, so we don't strictly need client-side pagination here
|
||||
// unless we mix both. For now, let's keep it simple and just render rows.
|
||||
// If we pass 20 items, it renders 20 items.
|
||||
// getPaginationRowModel: getPaginationRowModel(),
|
||||
onSortingChange: setSorting,
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
sorting,
|
||||
},
|
||||
manualPagination: true, // Tell table we handle pagination manually
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup: HeaderGroup<TData>) => (
|
||||
<TableRow key={headerGroup.id}>
|
||||
{headerGroup.headers.map((header: Header<TData, unknown>) => {
|
||||
return (
|
||||
<TableHead key={header.id}>
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</TableHead>
|
||||
)
|
||||
})}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{table.getRowModel().rows?.length ? (
|
||||
table.getRowModel().rows.map((row: Row<TData>) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
>
|
||||
{row.getVisibleCells().map((cell: Cell<TData, unknown>) => (
|
||||
<TableCell key={cell.id}>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={columns.length} className="h-24 text-center">
|
||||
Sonuç bulunamadı.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
151
frontend/app/admin/users/page.tsx
Normal file
151
frontend/app/admin/users/page.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { useEffect, useState, Suspense } from "react"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { useRouter, useSearchParams } from "next/navigation"
|
||||
import { getColumns } from "./columns"
|
||||
import { DataTable } from "./data-table"
|
||||
import { User } from "@/types/user"
|
||||
import { userService } from "@/services/userService"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Loader2 } from "lucide-react"
|
||||
|
||||
function UsersPageContent() {
|
||||
const { data: session, status } = useSession()
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const [data, setData] = useState<User[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
// Filters
|
||||
const page = Number(searchParams.get("page")) || 1
|
||||
const perPage = Number(searchParams.get("per_page")) || 20
|
||||
const soft = searchParams.get("soft") || "" // "", "only", "with"
|
||||
|
||||
const fetchData = React.useCallback(async () => {
|
||||
if (!session?.user?.accessToken) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const response = await userService.getUsers(session.user.accessToken, page, perPage, soft)
|
||||
setData(response.items || [])
|
||||
setTotal(response.total)
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users:", error)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
setError((error as any).message || "Kullanıcılar getirilirken bir hata oluştu")
|
||||
setData([])
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [session, page, perPage, soft])
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "loading") return
|
||||
|
||||
if (status === "unauthenticated" || !session?.user?.accessToken) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
fetchData()
|
||||
}, [fetchData, status, session])
|
||||
|
||||
const columns = React.useMemo(() => getColumns(fetchData), [fetchData])
|
||||
|
||||
const handleFilterChange = (value: string) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (value && value !== "active") {
|
||||
params.set("soft", value)
|
||||
} else {
|
||||
params.delete("soft")
|
||||
}
|
||||
params.set("page", "1")
|
||||
router.push(`/admin/users?${params.toString()}`)
|
||||
}
|
||||
|
||||
const handlePageChange = (newPage: number) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
params.set("page", newPage.toString())
|
||||
router.push(`/admin/users?${params.toString()}`)
|
||||
}
|
||||
|
||||
const totalPages = Math.ceil(total / perPage)
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-10">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Kullanıcı Yönetimi</h1>
|
||||
<div className="flex gap-4">
|
||||
<Select
|
||||
value={soft || "active"}
|
||||
onValueChange={handleFilterChange}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Durum Seç" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="active">Aktif Kullanıcılar</SelectItem>
|
||||
<SelectItem value="only">Silinmişler (Çöp Kutusu)</SelectItem>
|
||||
<SelectItem value="with">Tümü (Aktif + Silinmiş)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-destructive/15 text-destructive p-4 rounded-md mb-6">
|
||||
Hata: {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && data.length === 0 ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<DataTable columns={columns} data={data} />
|
||||
{/* Pagination Controls */}
|
||||
<div className="flex items-center justify-end space-x-2 py-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(page - 1)}
|
||||
disabled={page <= 1}
|
||||
>
|
||||
Önceki
|
||||
</Button>
|
||||
<div className="text-sm">
|
||||
Sayfa {page} / {totalPages || 1}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(page + 1)}
|
||||
disabled={page >= totalPages}
|
||||
>
|
||||
Sonraki
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function UsersPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="flex justify-center p-10"><Loader2 className="h-8 w-8 animate-spin" /></div>}>
|
||||
<UsersPageContent />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
123
frontend/app/admin/users/user-dialog.tsx
Normal file
123
frontend/app/admin/users/user-dialog.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
"use client"
|
||||
|
||||
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 { User, UserPayload } from "@/types/user"
|
||||
import { useState } from "react"
|
||||
import { userService } from "@/services/userService"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
|
||||
interface UserDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
user: User
|
||||
onSuccess?: () => void
|
||||
}
|
||||
|
||||
export function UserDialog({ open, onOpenChange, user, onSuccess }: UserDialogProps) {
|
||||
const { data: session } = useSession()
|
||||
const router = useRouter()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [formData, setFormData] = useState<UserPayload>({
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
is_admin: user.is_admin,
|
||||
password: "",
|
||||
})
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!session?.user?.accessToken) return
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
// Create a payload copy to manipulate
|
||||
const payload = { ...formData }
|
||||
// Remove password if it's empty so we don't overwrite with empty string
|
||||
if (!payload.password || payload.password.trim() === "") {
|
||||
delete payload.password
|
||||
}
|
||||
|
||||
await userService.updateUser(session.user.accessToken, user.id, payload)
|
||||
toast.success("Kullanıcı güncellendi")
|
||||
onOpenChange(false)
|
||||
if (onSuccess) onSuccess() // Trigger parent refresh
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast.error("Kullanıcı güncellenirken bir hata oluştu")
|
||||
console.error(error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Kullanıcı Düzenle</DialogTitle>
|
||||
<DialogDescription>
|
||||
Kullanıcı bilgilerini buradan güncelleyebilirsiniz. Şifre alanını boş bırakırsanız değişmez.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="username" className="text-right">
|
||||
Kullanıcı Adı
|
||||
</Label>
|
||||
<Input
|
||||
id="username"
|
||||
value={formData.username}
|
||||
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="email" className="text-right">
|
||||
Email
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label htmlFor="password" className="text-right">
|
||||
Yeni Şifre
|
||||
</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Değişmeyecekse boş bırakın"
|
||||
value={formData.password || ""}
|
||||
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||
className="col-span-3"
|
||||
/>
|
||||
</div>
|
||||
{/* Admin role toggle could be added here if needed */}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading ? "Kaydediliyor..." : "Kaydet"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
132
frontend/app/admin/users/user-row-actions.tsx
Normal file
132
frontend/app/admin/users/user-row-actions.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
import { Row } from "@tanstack/react-table"
|
||||
import { MoreHorizontal, Pen, Trash, RotateCcw } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { User } from "@/types/user"
|
||||
import { useState } from "react"
|
||||
import { UserDialog } from "./user-dialog"
|
||||
import { userService } from "@/services/userService"
|
||||
import { useSession } from "next-auth/react"
|
||||
import { toast } from "sonner"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Swal from 'sweetalert2'
|
||||
import withReactContent from 'sweetalert2-react-content'
|
||||
|
||||
const MySwal = withReactContent(Swal)
|
||||
|
||||
interface DataTableRowActionsProps<TData> {
|
||||
row: Row<TData>
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
export function DataTableRowActions<TData extends User>({
|
||||
row,
|
||||
onRefresh,
|
||||
}: DataTableRowActionsProps<TData>) {
|
||||
const user = row.original as User
|
||||
const [showEditDialog, setShowEditDialog] = useState(false)
|
||||
const { data: session } = useSession()
|
||||
const router = useRouter()
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!session?.user?.accessToken) return
|
||||
|
||||
const result = await MySwal.fire({
|
||||
title: 'Emin misiniz?',
|
||||
text: "Bu kullanıcıyı silmek istediğinize emin misiniz? Bu işlem geri alınabilir (Soft Delete).",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#d33',
|
||||
cancelButtonColor: '#3085d6',
|
||||
confirmButtonText: 'Evet, Sil!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (!result.isConfirmed) return
|
||||
|
||||
try {
|
||||
await userService.deleteUser(session.user.accessToken, user.id)
|
||||
MySwal.fire(
|
||||
'Silindi!',
|
||||
'Kullanıcı başarıyla silindi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast.error("Kullanıcı silinirken bir hata oluştu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = async () => {
|
||||
if (!session?.user?.accessToken) return
|
||||
|
||||
const result = await MySwal.fire({
|
||||
title: 'Geri Yükle?',
|
||||
text: "Bu kullanıcıyı geri yüklemek istediğinize emin misiniz?",
|
||||
icon: 'question',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Evet, Geri Yükle!',
|
||||
cancelButtonText: 'İptal'
|
||||
})
|
||||
|
||||
if (!result.isConfirmed) return
|
||||
|
||||
try {
|
||||
await userService.restoreUser(session.user.accessToken, user.id)
|
||||
MySwal.fire(
|
||||
'Geri Yüklendi!',
|
||||
'Kullanıcı başarıyla geri yüklendi.',
|
||||
'success'
|
||||
)
|
||||
onRefresh()
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast.error("Kullanıcı geri yüklenirken bir hata oluştu")
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<UserDialog
|
||||
open={showEditDialog}
|
||||
onOpenChange={setShowEditDialog}
|
||||
user={user}
|
||||
onSuccess={onRefresh} // Trigger refresh on success
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="h-8 w-8 p-0">
|
||||
<span className="sr-only">Menü aç</span>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setShowEditDialog(true)}>
|
||||
<Pen className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
|
||||
Düzenle
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
|
||||
<Trash className="mr-2 h-3.5 w-3.5" />
|
||||
Sil
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={handleRestore}>
|
||||
<RotateCcw className="mr-2 h-3.5 w-3.5" />
|
||||
Geri Yükle
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</>
|
||||
)
|
||||
}
|
||||
10
frontend/app/api/admin/heroes/[id]/route.ts
Normal file
10
frontend/app/api/admin/heroes/[id]/route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { NextRequest } from "next/server"
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy"
|
||||
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await context.params
|
||||
return handleImageProxyRequest(req, `/admin/heroes/${id}`)
|
||||
}
|
||||
6
frontend/app/api/admin/heroes/route.ts
Normal file
6
frontend/app/api/admin/heroes/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { NextRequest } from "next/server"
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy"
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
return handleImageProxyRequest(req, "/admin/heroes")
|
||||
}
|
||||
11
frontend/app/api/admin/posts/[id]/route.ts
Normal file
11
frontend/app/api/admin/posts/[id]/route.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy";
|
||||
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await context.params;
|
||||
console.log("API Route PUT called with id:", id);
|
||||
return handleImageProxyRequest(req, `/admin/posts/${id}`);
|
||||
}
|
||||
6
frontend/app/api/admin/posts/route.ts
Normal file
6
frontend/app/api/admin/posts/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
return handleImageProxyRequest(req, "/admin/posts");
|
||||
}
|
||||
10
frontend/app/api/admin/settings/[id]/route.ts
Normal file
10
frontend/app/api/admin/settings/[id]/route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { NextRequest } from "next/server"
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy"
|
||||
|
||||
export async function PUT(
|
||||
req: NextRequest,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const { id } = await context.params
|
||||
return handleImageProxyRequest(req, `/admin/settings/${id}`)
|
||||
}
|
||||
6
frontend/app/api/admin/settings/route.ts
Normal file
6
frontend/app/api/admin/settings/route.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { NextRequest } from "next/server"
|
||||
import { handleImageProxyRequest } from "@/lib/api-proxy"
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
return handleImageProxyRequest(req, "/admin/settings")
|
||||
}
|
||||
187
frontend/app/api/auth/[...nextauth]/route.ts
Normal file
187
frontend/app/api/auth/[...nextauth]/route.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import NextAuth, { NextAuthOptions } from "next-auth";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import GitHubProvider from "next-auth/providers/github";
|
||||
import GoogleProvider from "next-auth/providers/google";
|
||||
import { JWT } from "next-auth/jwt";
|
||||
|
||||
// Helper to get API URL consistently
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || process.env.BASE_API_URL || "http://localhost:8080/api";
|
||||
|
||||
/**
|
||||
* Refresh token ile yeni access token al
|
||||
*/
|
||||
async function refreshAccessToken(token: JWT) {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/v1/auth/refresh`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refresh_token: token.refreshToken,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to refresh token");
|
||||
}
|
||||
|
||||
const refreshedTokens = await response.json();
|
||||
|
||||
return {
|
||||
...token,
|
||||
accessToken: refreshedTokens.access_token,
|
||||
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken,
|
||||
accessTokenExpires: Date.now() + 15 * 60 * 1000, // 15 dakika (Time should ideally come from backend)
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error refreshing access token:", error);
|
||||
return {
|
||||
...token,
|
||||
error: "RefreshAccessTokenError",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const authOptions: NextAuthOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
// Optional: used if redirecting from a separate auth flow
|
||||
accessToken: { label: "Access Token", type: "text" },
|
||||
refreshToken: { label: "Refresh Token", type: "text" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
// 1. External Token Flow (if tokens are passed directly, e.g. from OAuth on backend)
|
||||
if (credentials?.accessToken && credentials?.refreshToken) {
|
||||
try {
|
||||
// Validate token and get user info
|
||||
const meResponse = await fetch(`${API_URL}/api/v1/auth/me`, {
|
||||
headers: {
|
||||
"Authorization": `Bearer ${credentials.accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!meResponse.ok) return null;
|
||||
|
||||
const userData = await meResponse.json();
|
||||
|
||||
return {
|
||||
id: userData.id?.toString(),
|
||||
email: userData.email,
|
||||
name: userData.username,
|
||||
username: userData.username, // Added to satisfy User interface
|
||||
is_admin: userData.is_admin, // Capture is_admin
|
||||
accessToken: credentials.accessToken,
|
||||
refreshToken: credentials.refreshToken,
|
||||
accessTokenExpires: Date.now() + 15 * 60 * 1000,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Standard Email/Password Flow
|
||||
if (!credentials?.email || !credentials?.password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/api/v1/auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: credentials.email,
|
||||
password: credentials.password,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Structure matches user's provided JSON example
|
||||
return {
|
||||
id: data.user.id.toString(),
|
||||
email: data.user.email,
|
||||
name: data.user.username,
|
||||
username: data.user.username, // Added to satisfy User interface
|
||||
is_admin: data.user.is_admin, // Capture is_admin
|
||||
accessToken: data.access_token,
|
||||
refreshToken: data.refresh_token,
|
||||
accessTokenExpires: Date.now() + 15 * 60 * 1000,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
}),
|
||||
// Keep existing providers if they are configured
|
||||
GitHubProvider({
|
||||
clientId: process.env.GITHUB_CLIENT_ID || "",
|
||||
clientSecret: process.env.GITHUB_CLIENT_SECRET || "",
|
||||
}),
|
||||
GoogleProvider({
|
||||
clientId: process.env.GOOGLE_CLIENT_ID || "",
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
|
||||
}),
|
||||
],
|
||||
pages: {
|
||||
signIn: "/auth/login",
|
||||
signOut: "/auth/login",
|
||||
error: "/auth/login",
|
||||
},
|
||||
callbacks: {
|
||||
async jwt({ token, user }) {
|
||||
// Initial sign in
|
||||
if (user) {
|
||||
token.id = user.id;
|
||||
token.email = user.email;
|
||||
token.name = user.name || undefined;
|
||||
token.username = user.username;
|
||||
token.accessToken = user.accessToken;
|
||||
token.refreshToken = user.refreshToken;
|
||||
token.roles = user.roles;
|
||||
token.is_admin = user.is_admin;
|
||||
token.accessTokenExpires = user.accessTokenExpires;
|
||||
}
|
||||
|
||||
// Return previous token if the access token has not expired yet
|
||||
if (Date.now() < (token.accessTokenExpires as number)) {
|
||||
return token;
|
||||
}
|
||||
|
||||
// Access token has expired, try to update it
|
||||
return refreshAccessToken(token);
|
||||
},
|
||||
async session({ session, token }) {
|
||||
if (token) {
|
||||
session.user.id = token.id as string;
|
||||
session.user.email = token.email as string;
|
||||
session.user.name = token.name as string;
|
||||
session.user.username = token.username as string;
|
||||
session.user.is_admin = token.is_admin as boolean; // Expose is_admin to session
|
||||
session.accessToken = token.accessToken as string;
|
||||
session.user.accessToken = token.accessToken as string;
|
||||
session.error = token.error as string;
|
||||
}
|
||||
return session;
|
||||
},
|
||||
},
|
||||
session: {
|
||||
strategy: "jwt",
|
||||
},
|
||||
secret: process.env.NEXTAUTH_SECRET, // Ensure this matches .env
|
||||
};
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
|
||||
export { handler as GET, handler as POST };
|
||||
156
frontend/app/auth/login/page.tsx
Normal file
156
frontend/app/auth/login/page.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
"use client"
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { loginSchema, LoginInput } from '@/lib/auth-schema'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Turnstile } from 'nextjs-turnstile'
|
||||
import { signIn } from 'next-auth/react'
|
||||
import Swal from 'sweetalert2'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
|
||||
const LoginPage = () => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<LoginInput>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
})
|
||||
|
||||
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITEKEY
|
||||
|
||||
const onSubmit = async (data: LoginInput) => {
|
||||
if (siteKey && !turnstileToken) {
|
||||
Swal.fire({
|
||||
icon: 'warning',
|
||||
title: 'Güvenlik Doğrulaması',
|
||||
text: 'Lütfen robot olmadığınızı doğrulayın.',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const result = await signIn('credentials', {
|
||||
redirect: false,
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
})
|
||||
|
||||
if (result?.error) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
|
||||
if (result?.ok) {
|
||||
Swal.fire({
|
||||
icon: 'success',
|
||||
title: 'Giriş Başarılı',
|
||||
text: 'Yönlendiriliyorsunuz...',
|
||||
timer: 1500,
|
||||
showConfirmButton: false,
|
||||
}).then(() => {
|
||||
const callbackUrl = new URLSearchParams(window.location.search).get("callbackUrl") || "/"
|
||||
router.push(callbackUrl)
|
||||
router.refresh()
|
||||
})
|
||||
}
|
||||
|
||||
} catch {
|
||||
Swal.fire({
|
||||
icon: 'error',
|
||||
title: 'Giriş Başarısız',
|
||||
text: 'E-posta veya şifre hatalı olabilir.',
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-100 p-4 dark:bg-gray-900">
|
||||
<Card className="w-full max-w-md shadow-xl">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">Giriş Yap</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Hesabınıza erişmek için bilgilerinizi girin
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-posta</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="ornek@domain.com"
|
||||
{...register('email')}
|
||||
className={errors.email ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-red-500">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">Şifre</Label>
|
||||
<Link
|
||||
href="/auth/forgot-password"
|
||||
className="text-sm text-blue-600 hover:underline"
|
||||
>
|
||||
Şifremi Unuttum?
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="********"
|
||||
{...register('password')}
|
||||
className={errors.password ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-red-500">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{siteKey && (
|
||||
<div className="flex justify-center my-4">
|
||||
<Turnstile
|
||||
siteKey={siteKey}
|
||||
onSuccess={(token) => setTurnstileToken(token)}
|
||||
onError={() => setTurnstileToken(null)}
|
||||
onExpire={() => setTurnstileToken(null)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? 'Giriş Yapılıyor...' : 'Giriş Yap'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
<CardFooter className="justify-center">
|
||||
<p className="text-sm text-gray-500">
|
||||
Hesabınız yok mu?{' '}
|
||||
<Link href="/auth/register" className="text-blue-600 hover:underline">
|
||||
Kayıt Ol
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginPage
|
||||
176
frontend/app/auth/register/page.tsx
Normal file
176
frontend/app/auth/register/page.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
"use client"
|
||||
|
||||
import React, { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { registerSchema, RegisterInput } from '@/lib/auth-schema'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import Link from 'next/link'
|
||||
import Swal from 'sweetalert2'
|
||||
import { Turnstile } from 'nextjs-turnstile'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
const RegisterPage = () => {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||
const router = useRouter()
|
||||
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITEKEY
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<RegisterInput>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
})
|
||||
|
||||
const onSubmit = async (data: RegisterInput) => {
|
||||
if (siteKey && !turnstileToken) {
|
||||
Swal.fire({
|
||||
icon: 'warning',
|
||||
title: 'Güvenlik Doğrulaması',
|
||||
text: 'Lütfen robot olmadığınızı doğrulayın.',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: data.username,
|
||||
email: data.email,
|
||||
password: data.password
|
||||
}),
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || result.message || 'Kayıt işlemi başarısız oldu.')
|
||||
}
|
||||
|
||||
Swal.fire({
|
||||
title: 'Başarılı!',
|
||||
text: 'Kayıt işlemi başarıyla tamamlandı. Lütfen e-posta adresinizi doğrulayın.',
|
||||
icon: 'success',
|
||||
confirmButtonText: 'Giriş Yap',
|
||||
}).then(() => {
|
||||
router.push('/auth/login')
|
||||
})
|
||||
|
||||
} catch (error: any) { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
Swal.fire({
|
||||
title: 'Hata!',
|
||||
text: error.message || 'Bir sorun oluştu.',
|
||||
icon: 'error',
|
||||
confirmButtonText: 'Tamam',
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-100 p-4 dark:bg-gray-900">
|
||||
<Card className="w-full max-w-md shadow-xl">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">Kayıt Ol</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Yeni bir hesap oluşturmak için bilgilerinizi girin
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Kullanıcı Adı</Label>
|
||||
<Input
|
||||
id="username"
|
||||
placeholder="johndoe"
|
||||
{...register('username')}
|
||||
className={errors.username ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.username && (
|
||||
<p className="text-sm text-red-500">{errors.username.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-posta</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="ornek@domain.com"
|
||||
{...register('email')}
|
||||
className={errors.email ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p className="text-sm text-red-500">{errors.email.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Şifre</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="********"
|
||||
{...register('password')}
|
||||
className={errors.password ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p className="text-sm text-red-500">{errors.password.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">Şifre Tekrar</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
placeholder="********"
|
||||
{...register('confirmPassword')}
|
||||
className={errors.confirmPassword ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<p className="text-sm text-red-500">{errors.confirmPassword.message}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{siteKey && (
|
||||
<div className="flex justify-center my-4">
|
||||
<Turnstile
|
||||
siteKey={siteKey}
|
||||
onSuccess={(token) => setTurnstileToken(token)}
|
||||
onError={() => setTurnstileToken(null)}
|
||||
onExpire={() => setTurnstileToken(null)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? 'Kaydediliyor...' : 'Kayıt Ol'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
<CardFooter className="justify-center">
|
||||
<p className="text-sm text-gray-500">
|
||||
Zaten hesabınız var mı?{' '}
|
||||
<Link href="/auth/login" className="text-blue-600 hover:underline">
|
||||
Giriş Yap
|
||||
</Link>
|
||||
</p>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default RegisterPage
|
||||
126
frontend/app/auth/verify-email/page.tsx
Normal file
126
frontend/app/auth/verify-email/page.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
"use client"
|
||||
|
||||
import React, { useEffect, useState, Suspense } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2, CheckCircle2, XCircle, AlertCircle } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
const VerifyEmailContent = () => {
|
||||
const searchParams = useSearchParams()
|
||||
const token = searchParams.get('token')
|
||||
const [status, setStatus] = useState<'loading' | 'success' | 'error' | 'invalid'>(token ? 'loading' : 'invalid')
|
||||
const [message, setMessage] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
return
|
||||
}
|
||||
|
||||
const verifyEmail = async () => {
|
||||
try {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8080'
|
||||
const response = await fetch(`${apiUrl}/api/v1/auth/verify-email?token=${token}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Accept': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
// Backend responses might modify status
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (response.ok) {
|
||||
setStatus('success')
|
||||
setMessage(data.message || 'E-posta adresiniz başarıyla doğrulandı.')
|
||||
} else {
|
||||
setStatus('error')
|
||||
setMessage(data.error || data.message || 'Doğrulama işlemi başarısız oldu. Link süresi dolmuş veya geçersiz olabilir.')
|
||||
}
|
||||
} catch {
|
||||
setStatus('error')
|
||||
setMessage('Sunucu ile iletişim kurulurken bir hata oluştu.')
|
||||
}
|
||||
}
|
||||
|
||||
verifyEmail()
|
||||
}, [token])
|
||||
|
||||
return (
|
||||
<Card className="w-full max-w-md shadow-xl">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl font-bold text-center">E-posta Doğrulama</CardTitle>
|
||||
<CardDescription className="text-center">
|
||||
Hesap aktivasyon durumu
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col items-center justify-center py-6 space-y-4">
|
||||
{status === 'loading' && (
|
||||
<>
|
||||
<Loader2 className="h-16 w-16 animate-spin text-blue-500" />
|
||||
<p className="text-gray-500">Doğrulanıyor, lütfen bekleyin...</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'success' && (
|
||||
<>
|
||||
<CheckCircle2 className="h-16 w-16 text-green-500" />
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-xl font-semibold text-green-600">Başarılı!</h3>
|
||||
<p className="text-gray-600">{message}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'error' && (
|
||||
<>
|
||||
<XCircle className="h-16 w-16 text-red-500" />
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-xl font-semibold text-red-600">Hata!</h3>
|
||||
<p className="text-gray-600">{message}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status === 'invalid' && (
|
||||
<>
|
||||
<AlertCircle className="h-16 w-16 text-amber-500" />
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-xl font-semibold text-amber-600">Geçersiz Bağlantı</h3>
|
||||
<p className="text-gray-600">Doğrulama bağlantısı geçersiz veya eksik.</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter className="justify-center">
|
||||
{status === 'loading' ? (
|
||||
<Button disabled variant="outline" className="w-full">İşlem Sürüyor</Button>
|
||||
) : (
|
||||
<Link href="/auth/login" className="w-full">
|
||||
<Button className="w-full">
|
||||
{status === 'success' ? 'Giriş Yap' : 'Giriş Sayfasına Dön'}
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const VerifyEmailPage = () => {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-100 p-4 dark:bg-gray-900">
|
||||
<Suspense fallback={
|
||||
<div className="flex items-center space-x-2">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<span>Yükleniyor...</span>
|
||||
</div>
|
||||
}>
|
||||
<VerifyEmailContent />
|
||||
</Suspense>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VerifyEmailPage
|
||||
BIN
frontend/app/favicon.ico
Normal file
BIN
frontend/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
126
frontend/app/globals.css
Normal file
126
frontend/app/globals.css
Normal file
@@ -0,0 +1,126 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--radius-2xl: calc(var(--radius) + 8px);
|
||||
--radius-3xl: calc(var(--radius) + 12px);
|
||||
--radius-4xl: calc(var(--radius) + 16px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
45
frontend/app/layout.tsx
Normal file
45
frontend/app/layout.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { NextAuthProvider } from "@/components/providers/NextAuthProvider";
|
||||
import { ThemeProvider } from "@/components/providers/ThemeProvider";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
<NextAuthProvider>
|
||||
<ThemeProvider
|
||||
attribute="class"
|
||||
defaultTheme="system"
|
||||
enableSystem
|
||||
disableTransitionOnChange
|
||||
>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
</NextAuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
8
frontend/app/page.tsx
Normal file
8
frontend/app/page.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Button } from "@/components/ui/button"
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<Button>Click me</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user