-
-
Save dreadjr/5f21a32e231b55b2139757433b46491d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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