2026-07-23 05:11:16 +02:00
|
|
|
/**
|
|
|
|
|
* User CRUD hooks.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
|
|
|
import { apiGet, apiPost, apiPatch, apiDelete } from './client';
|
|
|
|
|
import { PaginatedResponse } from './types';
|
|
|
|
|
|
2026-07-24 14:23:28 +02:00
|
|
|
// ── Types matching backend schemas ──
|
|
|
|
|
|
|
|
|
|
export interface UserResponse {
|
|
|
|
|
id: string;
|
|
|
|
|
email: string;
|
|
|
|
|
name: string;
|
|
|
|
|
role: string;
|
|
|
|
|
role_id: string | null;
|
|
|
|
|
is_active: boolean;
|
|
|
|
|
tenant_id: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface UserCreate {
|
|
|
|
|
email: string;
|
|
|
|
|
name: string;
|
|
|
|
|
password: string;
|
|
|
|
|
role?: string;
|
|
|
|
|
role_id?: string | null;
|
|
|
|
|
is_active?: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface UserUpdate {
|
|
|
|
|
name?: string;
|
|
|
|
|
role?: string;
|
|
|
|
|
role_id?: string | null;
|
|
|
|
|
is_active?: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 05:11:16 +02:00
|
|
|
export function useUsers(page = 1, pageSize = 25) {
|
|
|
|
|
return useQuery({
|
|
|
|
|
queryKey: ['users', page, pageSize],
|
|
|
|
|
queryFn: () =>
|
2026-07-24 14:23:28 +02:00
|
|
|
apiGet<PaginatedResponse<UserResponse>>(`/users?page=${page}&page_size=${pageSize}`),
|
2026-07-23 05:11:16 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useUser(id?: string) {
|
|
|
|
|
return useQuery({
|
|
|
|
|
queryKey: ['users', id],
|
2026-07-24 14:23:28 +02:00
|
|
|
queryFn: () => apiGet<UserResponse>(`/users/${id}`),
|
2026-07-23 05:11:16 +02:00
|
|
|
enabled: !!id,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useCreateUser() {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
return useMutation({
|
2026-07-24 14:23:28 +02:00
|
|
|
mutationFn: (data: UserCreate) => apiPost('/users', data),
|
2026-07-23 05:11:16 +02:00
|
|
|
onSuccess: () => {
|
|
|
|
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useUpdateUser() {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
return useMutation({
|
2026-07-24 14:23:28 +02:00
|
|
|
mutationFn: ({ id, data }: { id: string; data: UserUpdate }) =>
|
2026-07-23 05:11:16 +02:00
|
|
|
apiPatch(`/users/${id}`, data),
|
|
|
|
|
onSuccess: () => {
|
|
|
|
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useDeleteUser() {
|
|
|
|
|
const queryClient = useQueryClient();
|
|
|
|
|
return useMutation({
|
|
|
|
|
mutationFn: (id: string) => apiDelete(`/users/${id}`),
|
|
|
|
|
onSuccess: () => {
|
|
|
|
|
queryClient.invalidateQueries({ queryKey: ['users'] });
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
}
|