import { BETTING_STATUS_INFO, CURRENT_PAGE_DEFAULT, TOTAL_PAGE_DEFAULT, } from '#lib/constants' import type { BettingItem, HistoryClassStatus, TransactionParams, } from '#lib/types' /** * Import types from Nadal. */ import type { TransactionBetHistoriesRequestPayload, TransactionBetHistoriesResponseData, } from '@kira-dancer/nadal' import { ref, computed } from 'vue' import { useNadal } from '#lib/composables' /** * Custom composable for managing betting history. * @namespace */ export function useBettingHistory() { /** * Nadal transaction instance. */ const { transaction } = useNadal() /** * Flag indicating if the betting history is currently being loaded. */ const isLoading = ref(false) /** * Total number of posts. */ const totalPost = ref(TOTAL_PAGE_DEFAULT) /** * Limit of items per page. */ const limit = ref(0) /** * Current page number. */ const currentPage = ref(CURRENT_PAGE_DEFAULT) /** * Array of betting histories. */ const bettingHistories = ref([]) /** * Computed property indicating if there is a next page. */ const isNextPage = computed(() => { return totalPost.value > limit.value * currentPage.value }) /** * Get the status of a betting item. * @param bettingItem - The betting item. * @returns The status information. */ const getStatus = (bettingItem: BettingItem): HistoryClassStatus => { const BETTING_STATUS_DEFAULT = { statusText: '', statusClass: '', } const status = bettingItem.ticket_status ?? bettingItem.type return ( BETTING_STATUS_INFO[ status.toUpperCase() as keyof typeof BETTING_STATUS_INFO ] ?? BETTING_STATUS_DEFAULT ) } /** * Get the betting history. * TransactionBetHistoriesRequestPayload type is imported from the Nadal module. * TransactionBetHistoriesResponseData type is imported from the Nadal module. * @param payload - The transaction parameters. * @returns A promise that resolves to an array of betting histories. */ const fetchBetHistory = async ( payload: TransactionParams, ): Promise => { try { isLoading.value = true limit.value = payload.limit const response = await transaction.betHistories< TransactionBetHistoriesRequestPayload, TransactionBetHistoriesResponseData[] >(payload) if (response?.data) { totalPost.value = Number(response.total) const { data } = response bettingHistories.value = data return data } return [] } catch (ex) { console.error(' ~ fetchBetHistory ~ ex:', ex) return [] } finally { isLoading.value = false } } /** * Handle pagination change. * @param data - The new page number. * @param payload - The transaction parameters. * @returns A promise that resolves when the betting history is updated. */ const onChangePagination = async ( data: number, payload: TransactionParams, ): Promise => { currentPage.value = data void fetchBetHistory(payload) } return { isLoading, currentPage, isNextPage, limit, totalPost, bettingHistories, onChangePagination, fetchBetHistory, getStatus, } }