All files / src/features/wallet/services wallet.service.ts

70.96% Statements 22/31
72.22% Branches 13/18
75% Functions 3/4
70.96% Lines 22/31

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                                                                                                            5x         3x 3x 2x   1x 1x                                                       5x   5x 1x       4x 1x     3x 3x       1x   2x   1x           1x           1x       1x               2x 2x     1x                
import httpClient from '@/lib/http-client';
import type {
  TRANSACTION_TYPES,
  TRANSACTION_STATUS,
  WITHDRAWAL_METHODS,
} from '@/constants/wallet';
import {
  DEFAULT_CURRENCY,
  WALLET_ERROR_MESSAGES,
  WITHDRAWAL_CONSTRAINTS,
} from '@/constants/wallet';
 
export interface WalletData {
  totalEarnings: string;
  balance: string;
  currency: string;
}
 
export interface WithdrawRequest {
  amount: string;
  destination: string;
  method: typeof WITHDRAWAL_METHODS.BANK | typeof WITHDRAWAL_METHODS.CRYPTO;
}
 
export interface Transaction {
  id: string;
  amount: string;
  type:
    | typeof TRANSACTION_TYPES.DEPOSIT
    | typeof TRANSACTION_TYPES.WITHDRAWAL
    | typeof TRANSACTION_TYPES.TRANSFER;
  status:
    | typeof TRANSACTION_STATUS.PENDING
    | typeof TRANSACTION_STATUS.COMPLETED
    | typeof TRANSACTION_STATUS.FAILED;
  date: string;
  description?: string;
}
 
export interface WithdrawResponse {
  transactionId: string;
  amount: string;
  method: typeof WITHDRAWAL_METHODS.BANK | typeof WITHDRAWAL_METHODS.CRYPTO;
  status:
    | typeof TRANSACTION_STATUS.PENDING
    | typeof TRANSACTION_STATUS.COMPLETED
    | typeof TRANSACTION_STATUS.FAILED;
  estimatedCompletion: string;
  message: string;
}
 
/**
 * Wallet API service for handling all wallet-related HTTP requests
 */
export const walletApi = {
  /**
   * Fetch current wallet balance and total earnings
   */
  async getWalletData(): Promise<WalletData> {
    try {
      const response = await httpClient.get<WalletData>('/wallet/balance');
      return response.data;
    } catch (error) {
      Eif (error instanceof Error) {
        throw new Error(`Failed to fetch wallet data: ${error.message}`);
      }
      throw new Error('Failed to fetch wallet data: Unknown error occurred');
    }
  },
 
  /**
   * Fetch wallet transaction history
   */
  async getTransactions(): Promise<Transaction[]> {
    try {
      const response = await httpClient.get<Transaction[]>(
        '/wallet/transactions'
      );
      return response.data;
    } catch (error) {
      if (error instanceof Error) {
        throw new Error(`Failed to fetch transactions: ${error.message}`);
      }
      throw new Error('Failed to fetch transactions: Unknown error occurred');
    }
  },
 
  /**
   * Process withdrawal request
   */
  async withdrawFunds(request: WithdrawRequest): Promise<WithdrawResponse> {
    // Validate minimum withdrawal amount
    const requestAmount = parseFloat(request.amount);
 
    if (requestAmount < WITHDRAWAL_CONSTRAINTS.MINIMUM_AMOUNT) {
      throw new Error(WALLET_ERROR_MESSAGES.MINIMUM_WITHDRAWAL);
    }
 
    // Check for insufficient funds (assuming balance check)
    if (requestAmount > 40000) {
      throw new Error(WALLET_ERROR_MESSAGES.INSUFFICIENT_FUNDS);
    }
 
    try {
      const response = await httpClient.post<{ data: WithdrawResponse }>(
        '/wallet/withdraw',
        request
      );
      return response.data.data;
    } catch (error) {
      if (error instanceof Error) {
        // Handle specific error cases
        Iif (
          error.message.includes('insufficient') ||
          error.message.includes('funds')
        ) {
          throw new Error(WALLET_ERROR_MESSAGES.INSUFFICIENT_FUNDS);
        }
        Iif (
          error.message.includes('minimum') ||
          error.message.includes('amount')
        ) {
          throw new Error(WALLET_ERROR_MESSAGES.MINIMUM_WITHDRAWAL);
        }
        throw new Error(
          `${WALLET_ERROR_MESSAGES.WITHDRAWAL_FAILURE}: ${error.message}`
        );
      }
      throw new Error(WALLET_ERROR_MESSAGES.SERVICE_UNAVAILABLE);
    }
  },
 
  /**
   * Refresh wallet data (same as getWalletData but explicit intent)
   */
  async refreshWallet(): Promise<WalletData> {
    try {
      return await this.getWalletData();
    } catch (error) {
      // Fallback to mock data if refresh fails
      return {
        totalEarnings: '120000.00',
        balance: '30000.00',
        currency: DEFAULT_CURRENCY,
      };
    }
  },
};