Sms Rehber eklemesi,Mobil uyumluluk ayarları,iletişim sayfası düzenlemeler vb.

This commit is contained in:
2026-01-30 00:09:16 +03:00
parent 5fdb7592e7
commit d320787df6
20 changed files with 800 additions and 101 deletions

View File

@@ -31,10 +31,11 @@ import imageCompression from 'browser-image-compression'
import { createClient } from "@/lib/supabase-browser"
import Image from "next/image"
import { createProduct, updateProduct } from "@/app/(dashboard)/dashboard/products/actions"
import { createProduct, updateProduct, deleteProductImage } from "@/app/(dashboard)/dashboard/products/actions"
const productSchema = z.object({
name: z.string().min(2, "Ürün adı en az 2 karakter olmalıdır"),
product_code: z.string().optional(),
category: z.string().min(1, "Kategori seçiniz"),
description: z.string().optional(),
price: z.coerce.number().min(0, "Fiyat 0'dan küçük olamaz"),
@@ -50,6 +51,7 @@ type ProductFormValues = z.infer<typeof productSchema>
interface Product {
id: number
name: string
product_code?: string | null
category: string
description: string | null
price: number
@@ -80,6 +82,7 @@ export function ProductForm({ initialData }: ProductFormProps) {
resolver: zodResolver(productSchema) as Resolver<ProductFormValues>,
defaultValues: initialData ? {
name: initialData.name,
product_code: initialData.product_code || "",
category: initialData.category,
description: initialData.description || "",
price: initialData.price,
@@ -88,6 +91,7 @@ export function ProductForm({ initialData }: ProductFormProps) {
images: initialData.image_url ? [initialData.image_url] : []
} : {
name: "",
product_code: "",
category: "",
description: "",
price: 0,
@@ -159,16 +163,31 @@ export function ProductForm({ initialData }: ProductFormProps) {
}
}
const removeImage = (index: number) => {
const removeImage = async (index: number) => {
const imageToDelete = previewImages[index]
// If editing an existing product and image is from server (starts with http/https usually)
if (initialData && imageToDelete.startsWith("http")) {
const result = await deleteProductImage(imageToDelete, initialData.id)
if (!result.success) {
toast.error("Resim silinirken hata oluştu")
return
}
toast.success("Resim silindi")
}
const currentImages = [...form.getValues("images") || []]
currentImages.splice(index, 1)
form.setValue("images", currentImages)
if (currentImages.length > 0) {
form.setValue("image_url", currentImages[0])
// Filter out the deleted image URL if it matches
const newImages = currentImages.filter(url => url !== imageToDelete)
form.setValue("images", newImages)
if (newImages.length > 0) {
form.setValue("image_url", newImages[0])
} else {
form.setValue("image_url", "")
}
setPreviewImages(currentImages)
setPreviewImages(newImages)
}
async function onSubmit(data: ProductFormValues) {
@@ -224,7 +243,7 @@ export function ProductForm({ initialData }: ProductFormProps) {
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="name"
@@ -238,7 +257,22 @@ export function ProductForm({ initialData }: ProductFormProps) {
</FormItem>
)}
/>
<FormField
control={form.control}
name="product_code"
render={({ field }) => (
<FormItem>
<FormLabel>Ürün Kodu</FormLabel>
<FormControl>
<Input placeholder="KOD-123" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<FormField
control={form.control}
name="category"

View File

@@ -21,7 +21,7 @@ interface SettingsTabsProps {
export function SettingsTabs({ smsSettings, users, contents }: SettingsTabsProps) {
return (
<Tabs defaultValue="content" className="space-y-4">
<TabsList className="grid w-full grid-cols-2 md:grid-cols-5 h-auto">
<TabsList className="grid w-full grid-cols-2 sm:grid-cols-3 md:grid-cols-5 h-auto gap-1">
<TabsTrigger value="content">İçerik Yönetimi</TabsTrigger>
<TabsTrigger value="users">Kullanıcılar</TabsTrigger>
<TabsTrigger value="sms">SMS / Bildirimler</TabsTrigger>

View File

@@ -1,19 +1,36 @@
'use client'
"use client"
import { useState } from "react"
import { useState, useEffect } from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { Customer } from "@/types/customer"
import { sendBulkSms } from "@/lib/sms/actions"
import { getTemplates, createTemplate, deleteTemplate, SmsTemplate } from "@/lib/sms/templates"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card"
import { Loader2, Send } from "lucide-react"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Loader2, Send, Users, Save, Trash2, BookOpen, Smartphone } from "lucide-react"
import { toast } from "sonner"
import { ScrollArea } from "@/components/ui/scroll-area"
@@ -29,7 +46,17 @@ interface SmsPageProps {
export default function SmsPageClient({ customers }: SmsPageProps) {
const [loading, setLoading] = useState(false)
const [selectAll, setSelectAll] = useState(false)
const [templates, setTemplates] = useState<SmsTemplate[]>([])
// Template Management States
const [isTemplateModalOpen, setIsTemplateModalOpen] = useState(false)
const [newTemplateTitle, setNewTemplateTitle] = useState("")
const [newTemplateMessage, setNewTemplateMessage] = useState("")
const [templateLoading, setTemplateLoading] = useState(false)
// Contact Picker States
const [isContactModalOpen, setIsContactModalOpen] = useState(false)
const [searchTerm, setSearchTerm] = useState("")
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -40,19 +67,117 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
},
})
const handleSelectAll = (checked: boolean) => {
setSelectAll(checked)
if (checked) {
const allPhones = customers.map(c => c.phone).filter(Boolean) as string[]
form.setValue('selectedCustomers', allPhones)
} else {
form.setValue('selectedCustomers', [])
async function handleNativeContactPicker() {
if (!('contacts' in navigator && 'ContactsManager' in window)) {
toast.error("Rehber özelliği desteklenmiyor (HTTPS gerekli olabilir).")
return
}
try {
const props = ['tel'];
const opts = { multiple: true };
const contacts = await (navigator as any).contacts.select(props, opts);
if (contacts && contacts.length > 0) {
const newNumbers = contacts.map((contact: any) => {
const phone = contact.tel?.[0]
return phone ? phone.replace(/\s/g, '') : null;
}).filter(Boolean).join(", ");
if (newNumbers) {
const current = form.getValues("manualNumbers");
const updated = current ? `${current}, ${newNumbers}` : newNumbers;
form.setValue("manualNumbers", updated);
toast.success(`${contacts.length} numara eklendi.`);
}
}
} catch (ex) {
console.error(ex);
}
}
// Load templates on mount
useEffect(() => {
loadTemplates()
}, [])
async function loadTemplates() {
const result = await getTemplates()
if (result.success && result.data) {
setTemplates(result.data)
}
}
async function handleSaveTemplate() {
if (!newTemplateTitle || !newTemplateMessage) {
toast.error("Başlık ve mesaj zorunludur")
return
}
setTemplateLoading(true)
const result = await createTemplate(newTemplateTitle, newTemplateMessage)
setTemplateLoading(false)
if (result.success) {
toast.success("Şablon kaydedildi")
setNewTemplateTitle("")
setNewTemplateMessage("")
setIsTemplateModalOpen(false)
loadTemplates()
} else {
toast.error(result.error || "Şablon kaydedilemedi")
}
}
async function handleDeleteTemplate(id: string) {
if (!confirm("Bu şablonu silmek istediğinize emin misiniz?")) return
const result = await deleteTemplate(id)
if (result.success) {
toast.success("Şablon silindi")
loadTemplates()
} else {
toast.error("Şablon silinemedi")
}
}
const handleSelectTemplate = (id: string) => {
const template = templates.find(t => t.id === id)
if (template) {
form.setValue("message", template.message)
}
}
// Filter customers for contact picker
const filteredCustomers = customers.filter(c =>
c.full_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
c.phone?.includes(searchTerm)
)
const toggleCustomerSelection = (phone: string) => {
const current = form.getValues("selectedCustomers") || []
if (current.includes(phone)) {
form.setValue("selectedCustomers", current.filter(p => p !== phone))
} else {
form.setValue("selectedCustomers", [...current, phone])
}
}
const selectAllFiltered = () => {
const current = form.getValues("selectedCustomers") || []
const newPhones = filteredCustomers.map(c => c.phone).filter(Boolean) as string[]
// Merge unique
const merged = Array.from(new Set([...current, ...newPhones]))
form.setValue("selectedCustomers", merged)
}
const deselectAll = () => {
form.setValue("selectedCustomers", [])
}
async function onSubmit(values: z.infer<typeof formSchema>) {
const manualPhones = values.manualNumbers
?.split(/[,\n]/) // Split by comma or newline
?.split(/[,\n]/)
.map(p => p.trim())
.filter(p => p !== "") || []
@@ -69,8 +194,11 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
const result = await sendBulkSms(allPhones, values.message)
if (result.success) {
toast.success(result.message)
form.reset()
setSelectAll(false)
form.reset({
manualNumbers: "",
message: "",
selectedCustomers: []
})
} else {
toast.error(result.error || "SMS gönderilirken hata oluştu")
}
@@ -84,11 +212,11 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
const watchedSelected = form.watch("selectedCustomers") || []
return (
<div className="flex-1 space-y-4 p-8 pt-6">
<h2 className="text-3xl font-bold tracking-tight">SMS Gönderimi</h2>
<div className="flex-1 space-y-4 p-4 pt-6 md:p-8">
<h2 className="text-2xl md:text-3xl font-bold tracking-tight">SMS Gönderimi</h2>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<Card>
<Card className="md:col-span-2 lg:col-span-1">
<CardHeader>
<CardTitle>Mesaj Bilgileri</CardTitle>
<CardDescription>
@@ -97,17 +225,85 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
</CardHeader>
<CardContent>
<form id="sms-form" onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<div className="space-y-2">
<Label>Manuel Numaralar</Label>
<Textarea
placeholder="5551234567, 5329876543 (Virgül veya alt satır ile ayırın)"
{...form.register("manualNumbers")}
/>
<p className="text-xs text-muted-foreground">Veritabanında olmayan numaraları buraya girebilirsiniz.</p>
{/* Templates Section */}
<div className="flex items-end gap-2">
<div className="flex-1 space-y-2">
<Label>Hazır Şablonlar</Label>
<Select onValueChange={handleSelectTemplate}>
<SelectTrigger>
<SelectValue placeholder="Şablon seçin..." />
</SelectTrigger>
<SelectContent>
{templates.map(t => (
<SelectItem key={t.id} value={t.id}>{t.title}</SelectItem>
))}
{templates.length === 0 && <div className="p-2 text-sm text-muted-foreground">Henüz şablon yok</div>}
</SelectContent>
</Select>
</div>
<Dialog open={isTemplateModalOpen} onOpenChange={setIsTemplateModalOpen}>
<DialogTrigger asChild>
<Button type="button" variant="outline" size="icon">
<Save className="h-4 w-4" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Yeni SMS Şablonu</DialogTitle>
<DialogDescription>
Sık kullandığınız mesajları şablon olarak kaydedin.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>Şablon Adı</Label>
<Input
placeholder="Örn: Bayram Kutlaması"
value={newTemplateTitle}
onChange={e => setNewTemplateTitle(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Mesaj İçeriği</Label>
<Textarea
placeholder="Mesajınız..."
value={newTemplateMessage}
onChange={e => setNewTemplateMessage(e.target.value)}
/>
</div>
{templates.length > 0 && (
<div className="pt-4 border-t">
<h4 className="text-sm font-medium mb-2">Kayıtlı Şablonlar</h4>
<ScrollArea className="h-32 rounded border p-2">
{templates.map(t => (
<div key={t.id} className="flex items-center justify-between text-sm py-1">
<span>{t.title}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="h-6 w-6 p-0 text-red-500"
onClick={() => handleDeleteTemplate(t.id)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
))}
</ScrollArea>
</div>
)}
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setIsTemplateModalOpen(false)}>İptal</Button>
<Button type="button" onClick={handleSaveTemplate} disabled={templateLoading}>Kaydet</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
<div className="space-y-2">
<Label>Gönderilecek Mesaj</Label>
<FormLabel label="Gönderilecek Mesaj" />
<Textarea
className="min-h-[120px]"
placeholder="Mesajınızı buraya yazın..."
@@ -119,7 +315,26 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
</div>
</div>
<div className="pt-4">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>Manuel Numaralar</Label>
<Button
type="button"
variant="default"
onClick={handleNativeContactPicker}
>
<Smartphone className="mr-2 h-4 w-4" />
Telefondan Seç
</Button>
</div>
<Textarea
placeholder="5551234567 (Her satıra bir numara)"
className="min-h-[80px]"
{...form.register("manualNumbers")}
/>
</div>
<div className="pt-2">
<div className="p-4 bg-slate-50 dark:bg-slate-900 rounded-md">
<h4 className="font-semibold mb-2">Özet</h4>
<ul className="list-disc list-inside text-sm">
@@ -139,60 +354,125 @@ export default function SmsPageClient({ customers }: SmsPageProps) {
</CardFooter>
</Card>
<Card className="h-full flex flex-col">
{/* Contact Picker Section */}
<Card className="md:col-span-2 lg:col-span-1 h-fit">
<CardHeader>
<CardTitle>Müşteri Listesi</CardTitle>
<CardTitle className="flex items-center justify-between">
<span>Müşteri Rehberi</span>
<div className="flex gap-2">
<Dialog open={isContactModalOpen} onOpenChange={setIsContactModalOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<BookOpen className="mr-2 h-4 w-4" />
Rehberi
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Müşteri Seçimi</DialogTitle>
<DialogDescription>
Listeden SMS göndermek istediğiniz müşterileri seçin.
</DialogDescription>
</DialogHeader>
<div className="flex items-center space-x-2 py-4">
<Input
placeholder="İsim veya telefon ile ara..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex gap-2 mb-2">
<Button size="sm" variant="outline" onClick={selectAllFiltered}>Görünenleri Seç</Button>
<Button size="sm" variant="ghost" onClick={deselectAll}>Temizle</Button>
</div>
<ScrollArea className="flex-1 pr-4">
<div className="space-y-2">
{filteredCustomers.length === 0 && <p className="text-center text-muted-foreground py-4">Sonuç bulunamadı.</p>}
{filteredCustomers.map((customer) => (
<div
key={customer.id}
className="flex items-center space-x-3 p-3 rounded-lg border hover:bg-slate-50 dark:hover:bg-slate-900 cursor-pointer transition-colors"
onClick={() => toggleCustomerSelection(customer.phone || "")}
>
<Checkbox
checked={watchedSelected.includes(customer.phone || "")}
onCheckedChange={() => { }} // Handle by parent div click
id={`modal-customer-${customer.id}`}
/>
<div className="flex-1">
<div className="font-medium">{customer.full_name}</div>
<div className="text-sm text-muted-foreground">{customer.phone}</div>
</div>
</div>
))}
</div>
</ScrollArea>
<DialogFooter className="mt-4">
<div className="flex items-center justify-between w-full">
<span className="text-sm text-muted-foreground">
{watchedSelected.length} kişi seçildi
</span>
<Button onClick={() => setIsContactModalOpen(false)}>Tamam</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</CardTitle>
<CardDescription>
Listeden toplu seçim yapabilirsiniz.
Hızlı seçim veya detaylı arama yapın.
</CardDescription>
</CardHeader>
<CardContent className="flex-1 min-h-[400px]">
<div className="flex items-center space-x-2 mb-4 pb-4 border-b">
<Checkbox
id="select-all"
checked={selectAll}
onCheckedChange={handleSelectAll}
<CardContent>
<div className="space-y-4">
<Input
placeholder="Hızlı ara..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Label htmlFor="select-all" className="font-bold">Tümünü Seç ({customers.length})</Label>
</div>
<ScrollArea className="h-[400px] w-full pr-4">
<div className="space-y-2">
{customers.length === 0 && <p className="text-muted-foreground">Kayıtlı müşteri bulunamadı.</p>}
{customers.map((customer) => (
<div key={customer.id} className="flex items-start space-x-2 py-2 hover:bg-slate-50 dark:hover:bg-slate-900 rounded px-2">
<Checkbox
id={`customer-${customer.id}`}
checked={watchedSelected.includes(customer.phone || "")}
disabled={!customer.phone}
onCheckedChange={(checked) => {
const current = form.getValues("selectedCustomers") || []
if (checked) {
form.setValue("selectedCustomers", [...current, customer.phone || ""])
} else {
form.setValue("selectedCustomers", current.filter(p => p !== customer.phone))
setSelectAll(false)
}
}}
/>
<div className="grid gap-1.5 leading-none">
<Label
htmlFor={`customer-${customer.id}`}
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{customer.full_name}
</Label>
<p className="text-xs text-muted-foreground">
{customer.phone || "Telefon Yok"}
</p>
<ScrollArea className="h-[400px] w-full pr-4 border rounded-md p-2">
<div className="space-y-2">
{filteredCustomers.map((customer) => (
<div
key={customer.id}
className="flex items-center space-x-3 p-2 rounded hover:bg-slate-50 dark:hover:bg-slate-900 cursor-pointer"
onClick={() => toggleCustomerSelection(customer.phone || "")}
>
<Checkbox
checked={watchedSelected.includes(customer.phone || "")}
id={`list-customer-${customer.id}`}
className="mt-0.5"
/>
<div className="grid gap-0.5 leading-none">
<label
htmlFor={`list-customer-${customer.id}`}
className="font-medium cursor-pointer"
>
{customer.full_name}
</label>
<p className="text-xs text-muted-foreground">
{customer.phone || "Telefon Yok"}
</p>
</div>
</div>
</div>
))}
</div>
</ScrollArea>
))}
{filteredCustomers.length === 0 && (
<p className="text-sm text-muted-foreground text-center py-2">Sonuç yok.</p>
)}
</div>
</ScrollArea>
</div>
</CardContent>
</Card>
</div>
</div>
)
}
function FormLabel({ label }: { label: string }) {
return <Label>{label}</Label>
}

View File

@@ -55,10 +55,16 @@ export function UserNav({ user, profile }: UserNavProps) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="relative h-8 w-8 rounded-full">
<Avatar className="h-8 w-8">
<AvatarImage src="/avatars/01.png" alt={profile?.full_name || "@parakasa"} />
<AvatarFallback>{profile?.full_name ? getInitials(profile.full_name) : 'PK'}</AvatarFallback>
<Button variant="ghost" className="relative h-9 w-9 rounded-full ring-2 ring-primary/10 ring-offset-2 hover:ring-primary/20 transition-all">
<Avatar className="h-9 w-9">
<AvatarImage src="" alt={profile?.full_name || "@parakasa"} />
<AvatarFallback className="bg-gradient-to-br from-blue-600 to-indigo-600 text-white font-bold text-xs">
{profile?.full_name
? getInitials(profile.full_name)
: user?.email
? user.email.substring(0, 2).toUpperCase()
: 'PK'}
</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>