Files
ghatreh_user/src/views/base/fund/info/composables/useFundInfoPage.ts
T
2026-06-29 22:43:28 +03:30

94 lines
2.6 KiB
TypeScript

import { computed, inject, provide, ref, watch, type InjectionKey } from 'vue'
import { useRoute } from 'vue-router'
import router from '@/router'
import { loading } from '@/utils'
import { getFundTransactionTable } from '@/api/fund'
import { getOneProductWallet } from '@/api/products'
import type { Product } from '@/models/products'
import type { TableInput, TableOutput } from '@/models/table'
import type { Transaction } from '@/models/transaction'
export interface FundInfoPageContext {
info: ReturnType<typeof ref<Product | undefined>>
items: ReturnType<typeof ref<Transaction[]>>
infoId: ReturnType<typeof computed<number | null>>
goBack: () => void
}
export const FUND_INFO_PAGE_KEY: InjectionKey<FundInfoPageContext> = Symbol('fundInfoPage')
function parseRouteProductId(raw: string | string[] | undefined): number | null {
const value = Array.isArray(raw) ? raw[0] : raw
if (value == null || value === '') return null
const id = Number.parseInt(String(value), 10)
return Number.isFinite(id) && id > 0 ? id : null
}
export function useFundInfoPage() {
const route = useRoute()
const info = ref<Product>()
const items = ref<Transaction[]>([])
const tableOutput = ref<TableOutput<Transaction> | null>(null)
const pagination = ref<TableInput>({})
const infoId = computed(() => parseRouteProductId(route.params.id))
async function initTable() {
if (!info.value?.wallet?.id) return
try {
loading.value = true
items.value = []
Object.assign(pagination.value, { wallet_id: info.value.wallet.id })
tableOutput.value = await getFundTransactionTable(pagination.value)
items.value.push(...(tableOutput.value?.rows ?? []))
} catch (e) {
console.log(e)
} finally {
loading.value = false
}
}
async function initInfo() {
const id = infoId.value
if (id == null) {
console.error('Invalid fund product id in route')
return
}
try {
loading.value = true
info.value = await getOneProductWallet(id)
await initTable()
} catch (e) {
console.log(e)
} finally {
loading.value = false
}
}
watch(infoId, (id) => {
if (id != null) void initInfo()
}, { immediate: true })
function goBack() {
router.back()
}
const context: FundInfoPageContext = {
info,
items,
infoId,
goBack,
}
provide(FUND_INFO_PAGE_KEY, context)
return context
}
export function useFundInfoPageContext() {
const context = inject(FUND_INFO_PAGE_KEY)
if (!context) throw new Error('useFundInfoPageContext must be used within useFundInfoPage')
return context
}