60 lines
1.8 KiB
TypeScript
60 lines
1.8 KiB
TypeScript
|
|
import type { Client, PaginatedResponse } from '~/types'
|
||
|
|
|
||
|
|
export const useClient = () => {
|
||
|
|
const clients = useState<Client[]>('clients.list', () => [])
|
||
|
|
const searchQuery = ref('')
|
||
|
|
|
||
|
|
const getXsrfToken = (): string => {
|
||
|
|
const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/)
|
||
|
|
return match ? decodeURIComponent(match[1]) : ''
|
||
|
|
}
|
||
|
|
|
||
|
|
const fetchClients = async (): Promise<void> => {
|
||
|
|
const response = await $fetch<PaginatedResponse<Client>>('/api/clients', {
|
||
|
|
credentials: 'include',
|
||
|
|
})
|
||
|
|
clients.value = response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
const search = async (q: string): Promise<void> => {
|
||
|
|
if (!q.trim()) {
|
||
|
|
await fetchClients()
|
||
|
|
return
|
||
|
|
}
|
||
|
|
const response = await $fetch<{ data: Client[] }>('/api/search', {
|
||
|
|
query: { q },
|
||
|
|
credentials: 'include',
|
||
|
|
})
|
||
|
|
clients.value = response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
const fetchClient = async (id: number): Promise<Client> => {
|
||
|
|
const response = await $fetch<{ data: Client }>(`/api/clients/${id}`, {
|
||
|
|
credentials: 'include',
|
||
|
|
})
|
||
|
|
return response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
const createClient = async (payload: { client_number: string; name: string; notes?: Record<string, string> }): Promise<Client> => {
|
||
|
|
const response = await $fetch<{ data: Client }>('/api/clients', {
|
||
|
|
method: 'POST',
|
||
|
|
body: payload,
|
||
|
|
credentials: 'include',
|
||
|
|
headers: { 'X-XSRF-TOKEN': getXsrfToken() },
|
||
|
|
})
|
||
|
|
return response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
const updateClient = async (id: number, payload: Partial<Pick<Client, 'name' | 'notes'>>): Promise<Client> => {
|
||
|
|
const response = await $fetch<{ data: Client }>(`/api/clients/${id}`, {
|
||
|
|
method: 'PUT',
|
||
|
|
body: payload,
|
||
|
|
credentials: 'include',
|
||
|
|
headers: { 'X-XSRF-TOKEN': getXsrfToken() },
|
||
|
|
})
|
||
|
|
return response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
return { clients, searchQuery, fetchClients, search, fetchClient, createClient, updateClient }
|
||
|
|
}
|