Files
kavehhn 22b57eeae2 Add professor share calculation and financial reporting feature
Introduces per-class payout configuration (percentage or hourly rate,
plus an optional per-session expense allowance), pure calculation
utilities for professor payout/net profit/receivables, and a new
financial-reports API surface with per-class, per-session, and
date-range/monthly reports. Also adds full CRUD for institutional
expenses used in the range report, and wires up the new permissions
and roles. Fixes a pre-existing ReferenceError (missing
parseImportDate import) in paymentService that blocked creating
payments with dated transactions.
2026-08-21 12:19:09 +03:30

88 lines
3.1 KiB
JavaScript

// /components/expenses/expenseService.js
'use strict';
const Expense = require('./expenseModel');
const AppError = require('../../utils/AppError');
const { parsePaginationAndSort, buildFilterQuery, calculateMeta } = require('../../utils/pagination');
const { resolveDateRange } = require('../../utils/financialRange');
const sanitizePayload = (body = {}) => {
const payload = {
title: String(body.title || '').trim(),
category: body.category ? String(body.category).trim() : 'عمومی',
amount: Math.max(0, Number(body.amount) || 0),
date: body.date ? new Date(body.date) : new Date(),
notes: body.notes ? String(body.notes).trim().slice(0, 2000) : ''
};
return payload;
};
const createExpense = async (body, actorId = null) => {
const payload = sanitizePayload(body);
const expense = await Expense.create({ ...payload, recordedBy: actorId || undefined });
return expense;
};
const getAllExpenses = async (queryParams) => {
const { page, limit, skip, sort } = parsePaginationAndSort(queryParams, 'date', 'desc');
const filter = buildFilterQuery(queryParams, ['title', 'category', 'notes'], [
'page', 'limit', 'sortBy', 'sortOrder', 'q', 'search', 'lang', 'startDate', 'endDate'
]);
if (queryParams.startDate || queryParams.endDate) {
const { start, end } = resolveDateRange(queryParams);
filter.date = { $gte: start, $lte: end };
}
const [items, total] = await Promise.all([
Expense.find(filter).populate('recordedBy', 'name').sort(sort).skip(skip).limit(limit).lean(),
Expense.countDocuments(filter)
]);
return { data: items, meta: calculateMeta(total, page, limit) };
};
const getExpenseById = async (id) => {
const expense = await Expense.findById(id).populate('recordedBy', 'name').lean();
if (!expense) throw new AppError('EXPENSE_NOT_FOUND');
return expense;
};
const updateExpense = async (id, body) => {
const expense = await Expense.findById(id);
if (!expense) throw new AppError('EXPENSE_NOT_FOUND');
if (body.title !== undefined) expense.title = String(body.title).trim();
if (body.category !== undefined) expense.category = String(body.category).trim() || 'عمومی';
if (body.amount !== undefined) expense.amount = Math.max(0, Number(body.amount) || 0);
if (body.date !== undefined) expense.date = new Date(body.date);
if (body.notes !== undefined) expense.notes = String(body.notes).trim().slice(0, 2000);
await expense.save();
return expense;
};
const deleteExpense = async (id) => {
const expense = await Expense.findByIdAndDelete(id);
if (!expense) throw new AppError('EXPENSE_NOT_FOUND');
return null;
};
/** Sum of expense amounts whose `date` falls within [start, end] — used by date-range financial reports. */
const sumExpensesInRange = async (start, end) => {
const result = await Expense.aggregate([
{ $match: { date: { $gte: start, $lte: end } } },
{ $group: { _id: null, total: { $sum: '$amount' } } }
]);
return result[0]?.total || 0;
};
module.exports = {
createExpense,
getAllExpenses,
getExpenseById,
updateExpense,
deleteExpense,
sumExpensesInRange
};