Skip to content

Commit

Permalink
fix asset id issue (#206)
Browse files Browse the repository at this point in the history
  • Loading branch information
domechn authored Dec 6, 2023
1 parent 2c31e5d commit 7bd3945
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 41 deletions.
12 changes: 9 additions & 3 deletions src/components/coin-analytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ const App = ({

const profit = useMemo(
() => calculateProfit(breakevenPrice),
[breakevenPrice, symbol]
[latestAsset, breakevenPrice, symbol]
);

const costPrice = useMemo(() => calculateCostPrice(actions), [actions]);
Expand Down Expand Up @@ -166,6 +166,13 @@ const App = ({
[latestAsset]
);

const profitStr = useMemo(
() =>
currency.symbol +
prettyNumberToLocaleString(currencyWrapper(currency)(profit)),
[currency, profit]
);

const profitRate = useMemo(
() =>
breakevenPrice === 0
Expand Down Expand Up @@ -391,8 +398,7 @@ const App = ({
</CardHeader>
<CardContent>
<div className="text-2xl font-bold overflow-hidden whitespace-nowrap overflow-ellipsis">
{currency.symbol +
prettyNumberToLocaleString(currencyWrapper(currency)(profit))}
{profitStr}
</div>
<p className="text-xs text-muted-foreground overflow-hidden whitespace-nowrap overflow-ellipsis">
current value: {currentValueStr}
Expand Down
17 changes: 3 additions & 14 deletions src/middlelayers/cloudsync.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Polybase } from '@polybase/client'
import { getDatabase } from './database'
import { getDatabase, saveModelsToDatabase } from './database'
import { v4 as uuidv4 } from 'uuid'
import { ASSETS_TABLE_NAME, queryAssetsAfterCreatedAt } from './charts'
import { AssetModel, CloudAssetModel, CloudSyncConfiguration } from './types'
Expand Down Expand Up @@ -318,19 +318,8 @@ async function removeAssetsInCloud(assets: AssetModel[]): Promise<number> {

// return updated how many records
async function writeAssetsToDB(d: Database, assets: AssetModel[]): Promise<number> {
const insertValuesStr = assets.map(() => `(?, ?, ?, ?, ?, ?, ?)`).join(", ")

await d.execute(`INSERT INTO ${ASSETS_TABLE_NAME} (uuid, createdAt, symbol, amount, value, price, wallet) VALUES ${insertValuesStr}`, _(assets).map((asset) => [
asset.uuid,
asset.createdAt,
asset.symbol,
asset.amount,
asset.value,
asset.price,
asset.wallet,
]).flatten().value())

return assets.length
const res = await saveModelsToDatabase(ASSETS_TABLE_NAME, _.map(assets, (obj) => _.omit(obj, "id")))
return res.length
}

async function updateLastSyncTime(d: Database, publicKey: string) {
Expand Down
54 changes: 32 additions & 22 deletions src/middlelayers/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ type ExportData = {
exportAt: string
configuration?: string
historicalData: Pick<HistoricalData, "createdAt" | "assets" | "total">[]
priceData?: AssetPriceModel[]
md5: string
}

Expand Down Expand Up @@ -83,15 +82,22 @@ export async function exportHistoricalData(exportConfiguration = false): Promise

const historicalData = await queryHistoricalData(-1, false)
const priceData = await queryAllAssetPrices()
const priceDataByAssetID = _(priceData).mapKeys("assetID").mapValues().value()

const exportAt = new Date().toISOString()

const cfg = exportConfiguration ? await exportConfigurationString() : undefined

const exportData = {
exportAt,
historicalData: _.map(historicalData, (obj) => _.omit(obj, "id")),
priceData: _.map(priceData, (obj) => _.omit(obj, "id")),
historicalData: _(historicalData).map(d => ({
createdAt: d.createdAt,
total: d.total,
assets: _(d.assets).map(a => ({
...a,
costPrice: priceDataByAssetID[a.id]?.price
})).value()
})).value(),
configuration: cfg
}

Expand Down Expand Up @@ -119,13 +125,13 @@ export async function importHistoricalData(): Promise<boolean> {
}
const contents = await readTextFile(selected as string)

const { exportAt, md5, configuration, historicalData, priceData } = JSON.parse(contents) as ExportData
const { exportAt, md5, configuration, historicalData } = JSON.parse(contents) as ExportData

// !compatible with older versions logic ( before 0.3.3 )
if (md5) {
// verify md5
// todo: use md5 in typescript
const currentMd5 = await invoke<string>("md5", { data: JSON.stringify({ exportAt, historicalData, priceData, configuration }) })
const currentMd5 = await invoke<string>("md5", { data: JSON.stringify({ exportAt, historicalData, configuration }) })
if (currentMd5 !== md5) {
throw new Error("invalid data, md5 check failed: errorCode 000")
}
Expand All @@ -149,15 +155,11 @@ export async function importHistoricalData(): Promise<boolean> {
await importRawConfiguration(configuration)
}

if (priceData) {
await saveAssetPricesToDatabase(priceData)
}

return true
}

// import historicalData from file
async function saveHistoricalDataAssets(assets: AssetModel[]) {
async function saveHistoricalDataAssets(assets: (AssetModel & { costPrice?: number })[]) {
const requiredKeys = ["uuid", "createdAt", "symbol", "amount", "value", "price"]
_(assets).forEach((asset) => {
_(requiredKeys).forEach(k => {
Expand All @@ -168,17 +170,25 @@ async function saveHistoricalDataAssets(assets: AssetModel[]) {
})

await saveModelsToDatabase(ASSETS_TABLE_NAME, assets)
}

// import asset prices from file
async function saveAssetPricesToDatabase(models: AssetPriceModel[]) {
const requiredKeys = ["uuid", "assetID", "symbol", "price", "createdAt", "price"]
_(models).forEach((asset) => {
_(requiredKeys).forEach(k => {
if (!_(asset).has(k)) {
throw new Error(`invalid data: errorCode 004`)
}
})
})
return saveModelsToDatabase(ASSETS_PRICE_TABLE_NAME, models)
// import asset prices
const importedAssets = _(await queryHistoricalData(-1, false)).map(d => d.assets).flatten().value()
const assetPriceModels = _(assets).filter(a => a.costPrice !== undefined).map(a => {
console.log(a);

const f = _(importedAssets).find(ia => ia.uuid === a.uuid && ia.symbol === a.symbol && ia.wallet === a.wallet)
if (!f) {
return
}
return {
uuid: a.uuid,
assetID: f.id,
symbol: a.symbol,
price: a.costPrice,
createdAt: a.createdAt
} as AssetPriceModel
}).compact().value()

await saveModelsToDatabase(ASSETS_PRICE_TABLE_NAME, assetPriceModels)

}
2 changes: 1 addition & 1 deletion src/middlelayers/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,4 @@ async function saveToDatabase<T extends object>(db: Database, table: string, mod
const values = _(models).map(m => _(keys).map(k => _(m).get(k)).value()).flatten().value()
await db.execute(insertSql, values)
return models
}
}
3 changes: 2 additions & 1 deletion src/middlelayers/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ export type CoinsAmountAndValueChangeData = {
export type HistoricalData = {
id: string
createdAt: string
assets: AssetModel[]
// costPrice only exists when exporting historical data
assets: (AssetModel & { costPrice?: number })[]

total: number
}
Expand Down

0 comments on commit 7bd3945

Please sign in to comment.