@@ -201,9 +201,25 @@ const getChartData = async (req, res) => {
201201 const thirtyDaysAgo = new Date ( ) ;
202202 thirtyDaysAgo . setDate ( thirtyDaysAgo . getDate ( ) - 30 ) ;
203203
204+ // Optional date range from query for category aggregations
205+ const { startDate, endDate } = req . query ;
206+ let dateMatch = { } ;
207+ if ( startDate || endDate ) {
208+ dateMatch . addedOn = { } ;
209+ if ( startDate ) dateMatch . addedOn . $gte = new Date ( startDate ) ;
210+ if ( endDate ) dateMatch . addedOn . $lte = new Date ( endDate ) ;
211+ }
212+
204213 // Data for Expenses by Category (Pie Chart)
205214 const expensesByCategory = await IncomeExpense . aggregate ( [
206- { $match : { user : userId , isIncome : false , isDeleted : false } } ,
215+ { $match : { user : userId , isIncome : false , isDeleted : false , ...( dateMatch . addedOn ? { addedOn : dateMatch . addedOn } : { } ) } } ,
216+ { $group : { _id : '$category' , total : { $sum : '$cost' } } } ,
217+ { $project : { name : '$_id' , total : 1 , _id : 0 } }
218+ ] ) ;
219+
220+ // Data for Income by Category (Pie Chart)
221+ const incomeByCategory = await IncomeExpense . aggregate ( [
222+ { $match : { user : userId , isIncome : true , isDeleted : false , ...( dateMatch . addedOn ? { addedOn : dateMatch . addedOn } : { } ) } } ,
207223 { $group : { _id : '$category' , total : { $sum : '$cost' } } } ,
208224 { $project : { name : '$_id' , total : 1 , _id : 0 } }
209225 ] ) ;
@@ -234,7 +250,7 @@ const getChartData = async (req, res) => {
234250 { $project : { date : '$_id' , total : 1 , _id : 0 } }
235251 ] ) ;
236252
237- res . json ( { expensesByCategory, expensesOverTime, incomeOverTime } ) ;
253+ res . json ( { expensesByCategory, incomeByCategory , expensesOverTime, incomeOverTime } ) ;
238254 } catch ( error ) {
239255 // Also log the error to the backend console for easier debugging
240256 console . error ( 'Error in getChartData:' , error ) ;
0 commit comments