All files / src/features/transaction/hooks use-transactions.ts

85.18% Statements 46/54
55.55% Branches 5/9
77.77% Functions 21/27
88% Lines 44/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                            3x   2x   1x 2x 1x   21x                               3x 29x 29x 29x     29x 3x 3x     29x 2x 2x         29x 16x   16x 1x                       29x 2x     1x 1x       1x     1x 1x               29x 2x     2x     2x     2x         2x     2x                           2x   2x     1x             1x 1x       1x     1x                       1x 1x             29x                                                                                    
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { startTransition } from 'react';
import { useToast } from '@/hooks/use-toast';
import { useNotifications } from '@/hooks/use-store-sync';
import { usePagination } from '@/hooks/use-pagination';
import {
  fetchTransactionsPaginated,
  createTransaction as apiCreateTransaction,
  deleteTransaction as apiDeleteTransaction,
  type TransactionPaginationParams,
} from '../services/transaction.service';
import type { Transaction } from '../components/transaction-table';
 
// Query keys for React Query
export const transactionKeys = {
  all: ['transactions'] as const,
  lists: () => [...transactionKeys.all, 'list'] as const,
  list: (filters: Record<string, any>) =>
    [...transactionKeys.lists(), { filters }] as const,
  details: () => [...transactionKeys.all, 'detail'] as const,
  detail: (id: string) => [...transactionKeys.details(), id] as const,
  paginated: (params: TransactionPaginationParams) =>
    [...transactionKeys.all, 'paginated', params] as const,
};
 
interface CreateTransactionData {
  type: 'B' | 'card';
  name: string;
  value: string;
  return?: string;
  status?: 'Completed' | 'Failed' | 'In Progress';
  date?: string;
  transactionId?: string;
}
 
/**
 * Hook for paginated transactions using the reusable pagination system
 */
export const useTransactions = (initialPageSize: number = 10) => {
  const { successToast, errorToast } = useToast();
  const { notifySuccess, notifyError } = useNotifications();
  const queryClient = useQueryClient();
 
  // Helper functions for UI feedback - wrapped in transitions for React 19
  const showSuccess = (message: string) => {
    startTransition(() => {
      successToast(message);
    });
  };
  const showError = (message: string) => {
    startTransition(() => {
      errorToast(message);
    });
  };
 
  // Use the reusable pagination hook
  const pagination = usePagination<Transaction, TransactionPaginationParams>({
    queryKey: params => transactionKeys.paginated(params),
    queryFn: async params => {
      const result = await fetchTransactionsPaginated(params);
      return {
        data: result.transactions,
        pagination: result.pagination,
      };
    },
    initialParams: {
      pageSize: initialPageSize,
      sort: 'date:desc',
    },
  });
 
  // Create transaction mutation
  const createMutation = useMutation({
    mutationFn: (data: CreateTransactionData) => apiCreateTransaction(data),
    onSuccess: (data, variables) => {
      // Reset to first page and refresh data
      pagination.reset();
      notifySuccess(
        'Transaction Created',
        `Your ${variables.type} transaction has been created successfully.`
      );
      showSuccess('Transaction created successfully');
    },
    onError: () => {
      showError('Failed to create transaction');
      notifyError(
        'Transaction Failed',
        'Unable to create transaction. Please try again.'
      );
    },
  });
 
  // Delete transaction mutation
  const deleteMutation = useMutation({
    mutationFn: (id: string) => apiDeleteTransaction(id),
    onMutate: async (id: string) => {
      // Cancel any outgoing refetches
      await queryClient.cancelQueries({ queryKey: transactionKeys.all });
 
      // Store the previous data for rollback
      const previousData = pagination.data;
 
      // Optimistically remove the transaction from the local data
      pagination.updateData((currentData: Transaction[]) =>
        currentData.filter(transaction => transaction.id !== id)
      );
 
      // Update React Query cache as well for consistency
      queryClient.setQueryData(
        transactionKeys.paginated(pagination.params),
        (oldData: any) => {
          Eif (!oldData) return oldData;
          return {
            ...oldData,
            data: oldData.data.filter(
              (transaction: Transaction) => transaction.id !== id
            ),
            pagination: {
              ...oldData.pagination,
              total: Math.max(0, oldData.pagination.total - 1),
            },
          };
        }
      );
 
      showSuccess('Transaction deleted');
 
      return { previousData, id };
    },
    onSuccess: () => {
      notifySuccess(
        'Transaction Deleted',
        'Transaction has been deleted successfully.'
      );
    },
    onError: (error, variables, context) => {
      // Rollback: restore the previous data
      Eif (context?.previousData) {
        pagination.updateData(() => context.previousData);
      }
 
      // Rollback React Query cache as well
      queryClient.setQueryData(
        transactionKeys.paginated(pagination.params),
        (oldData: any) => {
          Eif (!oldData || !context?.previousData) return oldData;
          return {
            ...oldData,
            data: context.previousData,
            pagination: {
              ...oldData.pagination,
              total: oldData.pagination.total + 1,
            },
          };
        }
      );
 
      showError('Failed to delete transaction');
      notifyError(
        'Delete Failed',
        'Unable to delete transaction. Please try again.'
      );
    },
  });
 
  return {
    // Data from pagination hook
    transactions: pagination.data,
    pagination: pagination.pagination,
 
    // Loading states
    isLoading: pagination.isLoading,
    isLoadingMore: pagination.isLoadingMore,
    isCreating: createMutation.isPending,
    isDeleting: deleteMutation.isPending,
 
    // Error states
    error: pagination.error,
 
    // Pagination actions
    loadMore: pagination.loadMore,
    refresh: pagination.refresh,
    reset: pagination.reset,
 
    // Pagination state
    hasNextPage: pagination.hasNextPage,
    currentPage: pagination.currentPage,
    totalPages: pagination.totalPages,
    totalItems: pagination.totalItems,
 
    // CRUD actions
    createTransaction: createMutation.mutate,
    deleteTransaction: deleteMutation.mutate,
 
    // Filters and parameters
    setFilters: (filters: Partial<TransactionPaginationParams>) => {
      pagination.setParams({ ...pagination.params, ...filters, page: 1 });
    },
    clearFilters: () => {
      pagination.setParams({
        pageSize: initialPageSize,
        sort: 'date:desc',
      });
    },
    params: pagination.params,
  };
};