BillTracker/client/hooks/usePaymentActions.js

43 lines
1.4 KiB
JavaScript
Raw Normal View History

import { useMutation } from '@tanstack/react-query';
import { toast } from 'sonner';
import { api } from '@/api.js';
import { fmt } from '@/lib/utils';
import { useInvalidateTrackerData } from '@/hooks/useQueries';
// Quick-pay a tracker row (record a payment for `val` on `paidDate`) with a
// reversible Undo toast. A React Query mutation: `isPending` comes for free and
// the tracker/badge caches are invalidated on settle. Shared by the desktop and
// mobile tracker rows so the flow lives in one place.
export function useQuickPay() {
const invalidate = useInvalidateTrackerData();
const mutation = useMutation({
mutationFn: (payload) => api.quickPay(payload),
onSettled: () => invalidate(),
});
const run = (row, val, paidDate) => mutation.mutate(
{ bill_id: row.id, amount: val, paid_date: paidDate },
{
onSuccess: (payment) => {
toast.success(`${row.name}${fmt(val)} paid`, {
action: {
label: 'Undo',
onClick: async () => {
try {
await api.deletePayment(payment.id);
toast.success('Payment removed');
invalidate();
} catch (err) {
toast.error(err.message || 'Failed to undo payment.');
}
},
},
});
},
onError: (err) => toast.error(err.message || 'Failed to add payment.'),
},
);
return { run, isPending: mutation.isPending };
}