feat: add client management module
This commit is contained in:
61
src/app/(modules)/clients/hooks/useClientMutations.ts
Normal file
61
src/app/(modules)/clients/hooks/useClientMutations.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
'use client';
|
||||
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
import { clientService } from '@/services/api';
|
||||
import type { Client } from '@/types';
|
||||
import { clientKeys } from '../queries/clientKeys';
|
||||
import type { ClientFormValues } from './useClientForm';
|
||||
|
||||
function optionalValue(value: string) {
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
export function useSaveClientMutation({ onSaved }: { onSaved: () => void }) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (values: ClientFormValues) =>
|
||||
clientService.saveClient({
|
||||
id: values.id,
|
||||
name: values.name.trim(),
|
||||
email: values.email.trim(),
|
||||
landline_number: values.landline_number.trim(),
|
||||
address: values.address.trim(),
|
||||
gst: optionalValue(values.gst),
|
||||
pan: optionalValue(values.pan),
|
||||
tan: optionalValue(values.tan),
|
||||
contact_name: values.contact_name.trim(),
|
||||
contact_phone_number: values.contact_phone_number.trim(),
|
||||
contact_email: values.contact_email.trim(),
|
||||
is_active: values.is_active,
|
||||
}),
|
||||
onSuccess: (_data, values) => {
|
||||
toast.success(values.id ? 'Client updated' : 'Client created');
|
||||
onSaved();
|
||||
queryClient.invalidateQueries({ queryKey: clientKeys.all });
|
||||
},
|
||||
onError: (_error, values) => {
|
||||
toast.error(values.id ? 'Failed to update client' : 'Failed to create client');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useClientStatusMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
const mutation = useMutation({
|
||||
mutationFn: (client: Client) => clientService.updateClientStatus(client.id, !client.is_active),
|
||||
onSuccess: () => {
|
||||
toast.success('Client status updated');
|
||||
queryClient.invalidateQueries({ queryKey: clientKeys.all });
|
||||
},
|
||||
onError: () => toast.error('Failed to update client status'),
|
||||
});
|
||||
|
||||
return {
|
||||
...mutation,
|
||||
pendingClientId: mutation.isPending ? mutation.variables?.id : undefined,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user