@@ -37,13 +37,20 @@ export const onGroupWrite = onDocumentWritten(
37
37
{ document : 'groups/{groupId}' } ,
38
38
async ( event ) => {
39
39
try {
40
+ const DEFAULT_CURRENCY = 'INR' ;
41
+
40
42
// Extract 'before' and 'after' data from the event
41
43
const beforeData = event . data ?. before ?. data ( ) as { balances : GroupMemberBalance [ ] , is_active : boolean } | undefined ;
42
44
const afterData = event . data ?. after ?. data ( ) as { balances : GroupMemberBalance [ ] , is_active : boolean } | undefined ;
43
45
44
46
// Initialize a Firestore batch to group all write operations
45
47
const batch = db . batch ( ) ;
46
48
49
+ // Helper function to round currency to 2 decimal places
50
+ const roundCurrency = ( amount : number ) : number => {
51
+ return Number ( amount . toFixed ( 2 ) ) ;
52
+ } ;
53
+
47
54
// Helper function to process balances and update user totals
48
55
const processBalances = async ( balances : GroupMemberBalance [ ] , multiplier : number ) => {
49
56
if ( balances . length === 0 ) return ; // Skip if balances are empty
@@ -72,8 +79,14 @@ export const onGroupWrite = onDocumentWritten(
72
79
// Iterate over each currency in the balance_by_currency
73
80
const { balance_by_currency } = balances [ index ] ;
74
81
for ( const [ currency , currencyBalance ] of Object . entries ( balance_by_currency ) ) {
75
- const currentBalance = updatedTotal [ currency ] || 0 ;
76
- updatedTotal [ currency ] = currentBalance + multiplier * currencyBalance . balance ;
82
+ const currencyKey = currency || DEFAULT_CURRENCY ;
83
+ const currentBalance = updatedTotal [ currencyKey ] || 0 ;
84
+ updatedTotal [ currencyKey ] = roundCurrency ( currentBalance + multiplier * currencyBalance . balance ) ;
85
+ }
86
+
87
+ // Ensure at least the default currency is present
88
+ if ( ! updatedTotal [ DEFAULT_CURRENCY ] ) {
89
+ updatedTotal [ DEFAULT_CURRENCY ] = 0 ;
77
90
}
78
91
79
92
// Add the update to the batch
@@ -115,7 +128,7 @@ export const onGroupWrite = onDocumentWritten(
115
128
const afterCurrencyBalance = balance_by_currency [ currency ] ?. balance || 0 ;
116
129
const beforeCurrencyBalance = oldBalances [ currency ] ?. balance || 0 ;
117
130
const diff = afterCurrencyBalance - beforeCurrencyBalance ;
118
- diffs [ currency ] = { balance : diff } ;
131
+ diffs [ currency ] = { balance : roundCurrency ( diff ) } ;
119
132
}
120
133
121
134
return { id, balance_by_currency : diffs } ;
0 commit comments