New Proje
This commit is contained in:
73
src/app/employees/actions.ts
Normal file
73
src/app/employees/actions.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
'use server'
|
||||
|
||||
import { createClient } from '@/utils/supabase/server'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
|
||||
export async function addEmployee(formData: FormData) {
|
||||
const supabase = await createClient()
|
||||
|
||||
// 1. Get Form Data
|
||||
const firstName = formData.get('first_name') as string
|
||||
const lastName = formData.get('last_name') as string
|
||||
const email = formData.get('email') as string
|
||||
const companyId = formData.get('company_id') as string
|
||||
|
||||
if (!email || !companyId) {
|
||||
return { error: 'E-posta ve Şirket seçimi zorunludur.' }
|
||||
}
|
||||
|
||||
// Admin creating users manually currently requires an admin API setup or the user registering themselves
|
||||
// In a robust HRMS, the Superadmin uses the Supabase Admin API to `createUser`.
|
||||
// For the sake of this prototype, we'll assume the user must register first via valid credentials,
|
||||
// or we can insert an unauthenticated ghost user into `public.users` (which breaks reference to auth.users if not careful).
|
||||
//
|
||||
// Let's implement the standard approach: we check if the user exists in `auth.users` via `public.users`
|
||||
|
||||
let { data: existingUser } = await supabase
|
||||
.from('users')
|
||||
.select('id')
|
||||
.eq('email', email)
|
||||
.single()
|
||||
|
||||
if (!existingUser) {
|
||||
return { error: 'Bu e-posta adresine sahip bir kullanıcı bulunamadı. Kullanıcının önce sisteme kayıt olması gerekmektedir.' }
|
||||
}
|
||||
|
||||
// 2. Insert into Employees table
|
||||
const { error: employeeError } = await supabase
|
||||
.from('employees')
|
||||
.insert([{
|
||||
user_id: existingUser.id,
|
||||
company_id: companyId,
|
||||
department: formData.get('department'),
|
||||
title: formData.get('title'),
|
||||
status: 'active'
|
||||
}])
|
||||
|
||||
if (employeeError) {
|
||||
// Catch unique constraint violation
|
||||
if (employeeError.code === '23505') {
|
||||
return { error: 'Bu kullanıcı zaten bu şirkete eklenmiş.' }
|
||||
}
|
||||
return { error: 'Çalışan eklenirken hata: ' + employeeError.message }
|
||||
}
|
||||
|
||||
revalidatePath('/employees')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
export async function deleteEmployee(id: string) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { error } = await supabase
|
||||
.from('employees')
|
||||
.delete()
|
||||
.eq('id', id)
|
||||
|
||||
if (error) {
|
||||
return { error: 'Çalışan silinirken hata oluştu: ' + error.message }
|
||||
}
|
||||
|
||||
revalidatePath('/employees')
|
||||
return { success: true }
|
||||
}
|
||||
Reference in New Issue
Block a user