Skip to content

Instantly share code, notes, and snippets.

@bezysoftware
Last active March 24, 2017 22:57
Show Gist options
  • Save bezysoftware/45ce393aad09a198254294842e6d8329 to your computer and use it in GitHub Desktop.
Save bezysoftware/45ce393aad09a198254294842e6d8329 to your computer and use it in GitHub Desktop.
// change group currency task registration
export let changeGroupCurrency = functions
.database
.ref('/serverTasks/currencyChange/{taskId}')
.onWrite(event => changeGroupCurrency(event));
// function which changes group's currency and updates exchange rates of all expenses
async function changeGroupCurrency(event: Event<DeltaSnapshot>)
{
// prevent triggering this function after writing response code
if (event.data.previous.val() != null)
{
return;
}
let root = event.data.ref.root;
let adminRoot = event.data.adminRef.root;
let taskId = event.params['taskId'];
let groupId = event.data.child('request/groupId').val();
let groupCurrency = event.data.child('request/targetCurrency').val();
try
{
let transactions = (await root.child('transactions/' + groupId).once('value')).val();
let updates = {};
// iterate over all transactions within given group
for (let key in transactions)
{
let tx: Transaction = transactions[key];
let txCurrency = tx.currencyCode;
// if this expense doesn't have an exchange rate for this currency
if (!tx.exchangeRates || !(groupCurrency in tx.exchangeRates))
{
let ts = moment(tx.clientTimestamp);
let groupCurrencyRate = await getCurrencyRate(root, groupCurrency, ts);
let txCurrencyRate = await getCurrencyRate(root, txCurrency, ts);
// save the new exchange rate into a single 'updates' object
updates['transactions/' + groupId + '/' + key + '/' + 'exchangeRates/' + groupCurrency] = (groupCurrencyRate / txCurrencyRate).toString();
}
}
// check if task was deleted in the meantime, meaning user cancelled it
let task = (await root.child('serverTasks/currencyChange/' + taskId).once('value')).val();
if (task)
{
// update the exchange rates
await root.update(updates);
// update the group currency
await root.child('groups/' + groupId + '/convertedToCurrency').set(groupCurrency);
// write response code
await adminRoot.child('serverTasks/currencyChange/' + taskId + '/response/code').set('ok');
}
else
{
console.log("Task" + taskId + " was cancelled by the user.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment