faber-finances/server/api/balances/index.put.js

43 lines
No EOL
1.4 KiB
JavaScript

import { getCollection } from '../../utils/db.js'
export default defineEventHandler(async (event) => {
try {
const body = await readBody(event)
const collection = await getCollection('balances')
// Get existing balance document to preserve timestamp data
const existingBalance = await collection.findOne({ type: 'current' })
const balanceData = {
type: 'current',
currentBalance: body.currentBalance,
accountBalances: {
manual: body.accountBalances?.manual || {},
wise: body.accountBalances?.wise || { jennie: [], henry: [] },
// Preserve existing timestamps if not explicitly provided
lastWiseFetch: body.accountBalances?.lastWiseFetch || existingBalance?.accountBalances?.lastWiseFetch || null,
lastManualUpdate: body.accountBalances?.lastManualUpdate || existingBalance?.accountBalances?.lastManualUpdate || null
},
updatedAt: new Date()
}
// Upsert the balance record
const result = await collection.replaceOne(
{ type: 'current' },
balanceData,
{ upsert: true }
)
return {
success: true,
modifiedCount: result.modifiedCount,
upsertedCount: result.upsertedCount
}
} catch (error) {
console.error('Error updating balances:', error)
throw createError({
statusCode: 500,
statusMessage: 'Failed to update balances'
})
}
})