Files
ghatreh_user/src/composables/useWalletAssets.ts
T
2026-06-29 22:43:28 +03:30

71 lines
2.1 KiB
TypeScript

import { ref } from 'vue'
import { getWalletAssets } from '@/api/wallet'
import { getProductsCatalog, getProductsCatalogRef } from '@/composables/useProductsCatalog'
import { useWalletStore } from '@/store/walletStore'
import type { WalletAssetsSummary } from '@/models/walletAssets'
import { enrichInventoryCardsWithCatalog } from '@/utils/productAssets'
const assetsSummary = ref<WalletAssetsSummary | null>(null)
let assetsPromise: Promise<WalletAssetsSummary> | null = null
function enrichAssetsSummary(data: WalletAssetsSummary): WalletAssetsSummary {
const catalog = getProductsCatalogRef().value
return {
...data,
inventory_cards: enrichInventoryCardsWithCatalog(data.inventory_cards ?? [], catalog ?? []),
count_products: enrichInventoryCardsWithCatalog(data.count_products ?? [], catalog ?? []),
}
}
function syncWalletStoreFromAssets(data: WalletAssetsSummary) {
const walletStore = useWalletStore()
if (!walletStore.walletInfo) {
return
}
const goldMetal = data.metal_totals?.find((metal) => metal.metal_id === 1) ?? data.metal_totals?.[0]
walletStore.walletInfo.cash = data.cash_wallet ?? walletStore.walletInfo.cash
if (goldMetal) {
walletStore.walletInfo.gold = goldMetal.melted_weight ?? walletStore.walletInfo.gold
walletStore.walletInfo.gold_sum = goldMetal.total_weight ?? walletStore.walletInfo.gold_sum
}
}
export function useWalletAssets() {
async function loadWalletAssets(force = false) {
if (!force && assetsSummary.value) {
return assetsSummary.value
}
if (!force && assetsPromise) {
return assetsPromise
}
assetsPromise = Promise.all([getWalletAssets(), getProductsCatalog(force)])
.then(([data]) => {
assetsSummary.value = enrichAssetsSummary(data)
syncWalletStoreFromAssets(assetsSummary.value)
return assetsSummary.value
})
.finally(() => {
assetsPromise = null
})
return assetsPromise
}
function clearWalletAssets() {
assetsSummary.value = null
assetsPromise = null
}
return {
assetsSummary,
loadWalletAssets,
clearWalletAssets,
}
}