File size: 2,458 Bytes
8a6248c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import Record from "../models/record.model.js";
import MonthlySummary from'../models/monthlySummary.model.js'

export const addRecord = async(req,res)=>{
  try {
    console.log(req.body);
    const { date, expenditure, earnings } = req.body;
    const parsedDate = new Date(date);
    const month = parsedDate.getMonth() + 1; // JS months are 0-indexed, so add 1
    const year = parsedDate.getFullYear();
    const userId = req.userId;

    const record = new Record({
      date: parsedDate,
      expenditure,
      earnings,
      month,
      year,
      user: userId,
    });

    await record.save();
    res.status(201).json({ message: 'Record added successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Failed to add record', details: error.message });
  }
}

export const getMonthlySummary = async (req, res) => {
  try {
    const { year } = req.params;
    const userId = req.userId;
    const summaries = await MonthlySummary.find({ year, user: userId });

    res.status(200).json(summaries);
  } catch (error) {
    res.status(500).json({ error: 'Failed to retrieve monthly summaries' });
  }
};

export const calculateMonthlySummary = async(req,res)=>{
  try {
      const { month, year } = req.body;
      const userId = req.userId;
  
      const records = await Record.find({ month, year, user: userId });
  
      const totalEarnings = records.reduce((sum, record) => sum + record.earnings, 0);
      const totalExpenditure = records.reduce((sum, record) => sum + record.expenditure, 0);
      const revenue = totalEarnings - totalExpenditure;
  
      // Check if a summary already exists for this month and year
      let monthlySummary = await MonthlySummary.findOne({ month, year, user: userId });
      if (monthlySummary) {
        // Update existing summary
        monthlySummary.totalEarnings = totalEarnings;
        monthlySummary.totalExpenditure = totalExpenditure;
        monthlySummary.revenue = revenue;
      } else {
        // Create a new summary
        monthlySummary = new MonthlySummary({
          month,
          year,
          totalEarnings,
          totalExpenditure,
          revenue,
          user: userId,
        });
      }
  
      await monthlySummary.save();
      res.status(200).json({ message: 'Monthly summary calculated and saved successfully', monthlySummary });
    } catch (error) {
      res.status(500).json({ error: 'Failed to calculate monthly summary' });
    }
}