61 lines
1.7 KiB
TypeScript
61 lines
1.7 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react'
|
|
import * as api from '@/services/api'
|
|
import type { PlannedLeaveDay } from '@/types'
|
|
|
|
interface UsePlannedDaysResult {
|
|
data: PlannedLeaveDay[] | null
|
|
isLoading: boolean
|
|
error: string | null
|
|
refresh: () => Promise<void>
|
|
add: (date: string, childId: string, leaveType: string) => Promise<PlannedLeaveDay>
|
|
remove: (id: string) => Promise<void>
|
|
}
|
|
|
|
export function usePlannedDays(workspaceId: string | null, childId?: string): UsePlannedDaysResult {
|
|
const [data, setData] = useState<PlannedLeaveDay[] | null>(null)
|
|
const [isLoading, setIsLoading] = useState(false)
|
|
const [error, setError] = useState<string | null>(null)
|
|
|
|
const fetch = useCallback(async () => {
|
|
if (!workspaceId || !childId) return
|
|
setIsLoading(true)
|
|
setError(null)
|
|
try {
|
|
const response = await api.getPlannedDays(workspaceId, childId)
|
|
setData(response)
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : 'Failed to fetch planned days')
|
|
setData(null)
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}, [workspaceId, childId])
|
|
|
|
const add = useCallback(
|
|
async (date: string, childId: string, leaveType: string) => {
|
|
if (!workspaceId) throw new Error('Workspace not selected')
|
|
const result = await api.createPlannedDay(workspaceId, childId, {
|
|
date,
|
|
day_type: leaveType,
|
|
})
|
|
await fetch()
|
|
return result
|
|
},
|
|
[workspaceId, fetch]
|
|
)
|
|
|
|
const remove = useCallback(
|
|
async (id: string) => {
|
|
await api.deletePlannedDay(id)
|
|
await fetch()
|
|
},
|
|
[fetch]
|
|
)
|
|
|
|
useEffect(() => {
|
|
fetch()
|
|
}, [fetch])
|
|
|
|
return { data, isLoading, error, refresh: fetch, add, remove }
|
|
}
|