File size: 8,564 Bytes
89496fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// =======================
// Load members into accounting dropdown
// =======================
async function loadMembersForAccounting() {
  try {
    const res = await fetch('/api/members');
    if (!res.ok) throw new Error('Failed to fetch members');
    
    const members = await res.json();
    const select = document.getElementById('memberSelect');
    select.innerHTML = '<option value="">Select Member</option>';
    
    members.forEach(m => {
      const opt = document.createElement('option');
      opt.value = m.id;
      opt.textContent = `${m.name} (#${m.id})`;
      select.appendChild(opt);
    });
  } catch (error) {
    console.error(error);
  }
}

// =======================
// Show/hide payerName input based on payer type
// =======================
document.getElementById('payerType').addEventListener('change', (e) => {
  const isNonMember = e.target.value === 'non-member';
  document.getElementById('payerName').style.display = isNonMember ? 'inline-block' : 'none';
});

// =======================
// Load transactions and apply filters
// =======================
async function loadTransactions() {
  try {
    const res = await fetch('/api/accounting');
    if (!res.ok) throw new Error('Failed to fetch transactions');
    
    let transactions = await res.json();

    // Apply filters (assumes filters object exists with start/end properties)
    if (filters?.start || filters?.end) {
      transactions = transactions.filter(tx => {
        const txDate = new Date(tx.month + "-01");
        const start = filters.start ? new Date(filters.start + "-01") : null;
        const end = filters.end ? new Date(filters.end + "-01") : null;
        return (!start || txDate >= start) && (!end || txDate <= end);
      });
    }

    const tbody = document.getElementById('accountingBody');
tbody.innerHTML = transactions.map((t, i) => `

  <tr class="${t.category === 'expense' ? 'expense' : 'income'}">

    <td>${i + 1}</td>

    <td>${t.payerType === 'member' ? t.memberId : t.payerName}</td>

    <td>${t.payerType}</td>

    <td>${t.month}</td>

    <td>${t.amount}</td>

    <td>${t.category}</td>

    <td>${t.description || ''}</td>

    <td>

      <button class="btn btn-sm btn-primary" onclick="openActionModal(${t.id})">Actions</button>

    </td>

  </tr>

`).join('');

    // Update summary and charts with the filtered transactions
    updateAccountingSummary(transactions);
    renderMonthlyChart(transactions);
    renderIncomeExpenseChart(transactions);

  } catch (error) {
    console.error(error);
  }
}

// =======================
// Update accounting summary table
// =======================
async function updateAccountingSummary(transactionsParam = null) {
  try {
    const transactions = transactionsParam || await (await fetch('/api/accounting')).json();

    const summary = {
      contribution: 0,
      donation: 0,
      sale: 0,
      expense: 0,
      memberIncome: 0,
      nonMemberIncome: 0
    };

    transactions.forEach(tx => {
      if (tx.category === 'contribution') summary.contribution += tx.amount;
      else if (tx.category === 'donation') summary.donation += tx.amount;
      else if (tx.category === 'sale') summary.sale += tx.amount;
      else if (tx.category === 'expense') summary.expense += tx.amount;

      if (tx.payerType === 'member' && tx.category !== 'expense') summary.memberIncome += tx.amount;
      if (tx.payerType === 'non-member' && tx.category !== 'expense') summary.nonMemberIncome += tx.amount;
    });

    const tbody = document.getElementById('summaryBody');
    tbody.innerHTML = `

      <tr class="income-summary"><td>Contribution (Income)</td><td>${summary.contribution}</td></tr>

      <tr class="income-summary"><td>Donation (Income)</td><td>${summary.donation}</td></tr>

      <tr class="income-summary"><td>Sales (Income)</td><td>${summary.sale}</td></tr>

      <tr class="income-summary"><td>Total Income from Members</td><td>${summary.memberIncome}</td></tr>

      <tr class="income-summary"><td>Total Income from Non-Members</td><td>${summary.nonMemberIncome}</td></tr>

      <tr class="expense-summary"><td>Total Expenses</td><td>${summary.expense}</td></tr>

      <tr class="income-summary"><td>Net Total</td><td>${(summary.contribution + summary.donation + summary.sale) - summary.expense}</td></tr>

    `;
  } catch (error) {
    console.error(error);
  }
}

// =======================
// Handle transaction form submission
// =======================
document.getElementById('transactionForm').addEventListener('submit', async (e) => {
  e.preventDefault();

  const category = document.getElementById('transactionCategory').value;

  const transaction = {
    payerType: document.getElementById('payerType').value,
    memberId: document.getElementById('memberSelect').value || null,
    payerName: document.getElementById('payerName').value || null,
    month: document.getElementById('transactionMonth').value,
    amount: parseFloat(document.getElementById('transactionAmount').value),
    category,
    type: category === 'expense' ? 'expense' : 'income', // additional field for convenience
    description: document.getElementById('transactionDesc').value.trim()
  };

  try {
    const res = await fetch('/api/accounting', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(transaction)
    });

    if (!res.ok) throw new Error('Failed to add transaction');

    document.getElementById('transactionForm').reset();
    loadTransactions();
    updateAccountingSummary();
    renderMonthlyChart();

  } catch (error) {
    console.error(error);
    alert('Failed to save transaction');
  }
});

// =======================
// Export accounting data as JSON
// =======================
document.getElementById('exportAccounting').addEventListener('click', () => {
  window.location.href = '/api/accounting/export';
});

// =======================
// Initial data load
// =======================
loadMembersForAccounting();
loadTransactions();
updateAccountingSummary();



let selectedTransaction = null;

// Open modal and load transaction data
window.openActionModal = async function (id) {
  const res = await fetch('/api/accounting');
  const transactions = await res.json();
  selectedTransaction = transactions.find(t => t.id === id);
  if (!selectedTransaction) return alert('Transaction not found');

  // Fill the form
  document.getElementById('editTransactionId').value = selectedTransaction.id;
  document.getElementById('editTransactionMonth').value = selectedTransaction.month;
  document.getElementById('editTransactionAmount').value = selectedTransaction.amount;
  document.getElementById('editTransactionCategory').value = selectedTransaction.category;
  document.getElementById('editTransactionDesc').value = selectedTransaction.description || '';

  // Show modal
  document.getElementById('transactionModal').classList.remove('hidden');
};

window.closeModal = function () {
  document.getElementById('transactionModal').classList.add('hidden');
  selectedTransaction = null;
};

// Save edited transaction
document.getElementById('editTransactionForm').addEventListener('submit', async function (e) {
  e.preventDefault();
  const id = document.getElementById('editTransactionId').value;

  const updatedTx = {
    ...selectedTransaction,
    month: document.getElementById('editTransactionMonth').value,
    amount: parseFloat(document.getElementById('editTransactionAmount').value),
    category: document.getElementById('editTransactionCategory').value,
    description: document.getElementById('editTransactionDesc').value
  };

  const res = await fetch(`/api/accounting/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updatedTx)
  });

  if (!res.ok) {
    alert('Failed to update transaction');
    return;
  }

  closeModal();
  loadTransactions();
});

// Delete transaction
window.deleteTransaction = async function () {
  const id = document.getElementById('editTransactionId').value;

  if (!confirm('Are you sure you want to delete this transaction?')) return;

  const res = await fetch(`/api/accounting/${id}`, {
    method: 'DELETE'
  });

  if (!res.ok) {
    alert('Failed to delete transaction');
    return;
  }

  closeModal();
  loadTransactions();
};