Skip to content

Commit

Permalink
(cron job) add cron email componet to main reports
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremielodi committed Jul 10, 2019
1 parent 84b5af0 commit 3b21bfb
Show file tree
Hide file tree
Showing 16 changed files with 393 additions and 1,470 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,14 @@ <h3 class="text-capitalize" translate>REPORT.CLIENTS.TITLE</h3>
</div>
</div>
</div>

<div class="col-md-6">
<bh-cron-email-report
report-id="17"
report-form="ConfigForm"
report-details="ReportConfigCtrl.reportDetails"
on-select-report="ReportConfigCtrl.onSelectCronReport(report)">
</bh-cron-email-report>
</div>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ function AnnualClientsReportController($state, $sce, Notify, AppCache, SavedRepo
vm.reportDetails.fiscalId = fiscal.id;
};

vm.onSelectCronReport = report => {
vm.reportDetails = angular.copy(report);
};

vm.onSelectCurrency = currencyId => {
vm.reportDetails.currencyId = currencyId;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ function CashFlowConfigController($sce, Notify, SavedReports, AppCache, reportDa
vm.previewResult = null;
};

vm.onSelectCronReport = report => {
vm.reportDetails = angular.copy(report);
};

vm.requestSaveAs = function requestSaveAs() {
const options = {
url : reportUrl,
Expand Down
9 changes: 9 additions & 0 deletions client/src/modules/reports/generate/cashflow/cashflow.html
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,14 @@ <h3 class="text-capitalize" translate>REPORT.CASHFLOW.TITLE</h3>
</div>
</div>
</div>

<div class="col-md-6">
<bh-cron-email-report
report-id="1"
report-form="ConfigForm"
report-details="ReportConfigCtrl.reportDetails"
on-select-report="ReportConfigCtrl.onSelectCronReport(report)">
</bh-cron-email-report>
</div>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ angular.module('bhima.controllers')
.controller('stock_valueController', StockValueConfigController);

StockValueConfigController.$inject = [
'$sce', 'NotifyService', 'BaseReportService', 'AppCache', 'reportData', '$state',
'LanguageService', 'moment',
'$sce', 'NotifyService', 'BaseReportService',
'AppCache', 'reportData', '$state',
'LanguageService', 'moment', 'util',
];

function StockValueConfigController($sce, Notify, SavedReports, AppCache, reportData, $state, Languages, moment) {
function StockValueConfigController($sce, Notify, SavedReports,
AppCache, reportData, $state, Languages, moment, util) {
const vm = this;
const cache = new AppCache('configure_stock_value_report');
const reportUrl = 'reports/stock/value';
Expand All @@ -24,8 +26,12 @@ function StockValueConfigController($sce, Notify, SavedReports, AppCache, report

vm.onSelectDepot = function onSelectDepot(depot) {
vm.depot = depot;
formatData();
};

vm.onSelectCronReport = report => {
vm.reportDetails = angular.copy(report);
};

vm.clear = function clear(key) {
delete vm[key];
Expand All @@ -35,24 +41,20 @@ function StockValueConfigController($sce, Notify, SavedReports, AppCache, report
vm.previewGenerated = false;
vm.previewResult = null;
};

vm.onSelectCurrency = (currencyId) => {
vm.reportDetails.currency_id = currencyId;
vm.currency_id = currencyId;
formatData();
};

vm.preview = function preview(form) {
if (form.$invalid) { return 0; }

function formatData() {
const params = {
depot_uuid : vm.depot.uuid,
dateTo : vm.dateTo,
currency_id : vm.currency_id,
};

// update cached configuration
cache.reportDetails = angular.copy(params);

// format date for the server
params.dateTo = moment(params.dateTo).format('YYYY-MM-DD');

const options = {
Expand All @@ -61,6 +63,13 @@ function StockValueConfigController($sce, Notify, SavedReports, AppCache, report
};

vm.reportDetails = options;
return vm.reportDetails;
}

vm.preview = function preview(form) {
if (form.$invalid) { return 0; }

vm.reportDetails = formatData();

return SavedReports.requestPreview(reportUrl, reportData.id, angular.copy(vm.reportDetails))
.then((result) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,14 @@ <h3 translate>REPORT.STOCK_VALUE.TITLE</h3>
</div>
</div>
</div>

<div class="col-md-6">
<bh-cron-email-report
report-id="25"
report-form="ConfigForm"
report-details="ReportConfigCtrl.reportDetails"
on-select-report="ReportConfigCtrl.onSelectCronReport(report)">
</bh-cron-email-report>
</div>
</div>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ function UnbalancedInvoicePaymentsConfigController($sce, Notify, SavedReports, A
vm.reportDetails.debtorGroupUuid = debtorGroup.uuid;
};

vm.onSelectCronReport = report => {
vm.reportDetails = angular.copy(report);
};

vm.onClear = () => {
delete vm.reportDetails.debtorGroupName;
delete vm.reportDetails.debtorGroupUuid;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,15 @@ <h3 class="text-capitalize" translate>REPORT.UNPAID_INVOICE_PAYMENTS_REPORT.TITL
</div>
</div>
</div>

<div class="col-md-6">
<bh-cron-email-report
report-id="23"
report-form="ConfigForm"
report-details="ReportConfigCtrl.reportDetails"
on-select-report="ReportConfigCtrl.onSelectCronReport(report)">
</bh-cron-email-report>
</div>
</div>
</div>
</div>
182 changes: 179 additions & 3 deletions server/controllers/finance/reports/cashflow/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const TEMPLATE_BY_SERVICE = './server/controllers/finance/reports/cashflow/repor
// expose to the API
exports.report = report;
exports.byService = reportByService;

exports.printingReport = printingReport;
/**
* This function creates a cashflow report by service, reporting the realized income
* for the hospital services.
Expand Down Expand Up @@ -361,6 +361,8 @@ function report(req, res, next) {
* @param {*} source
* @param {*} sourceTotalByTextKeys
*/

// eslint-disable-next-line no-shadow
function aggregateTotalByTextKeys(source = {}) {
const sourceTotalByTextKeys = {};

Expand All @@ -376,7 +378,7 @@ function report(req, res, next) {
});
return sourceTotalByTextKeys;
}

// eslint-disable-next-line no-shadow
function aggregateTotal(source = {}) {
const totals = {};
const dataset = _.values(source);
Expand All @@ -385,7 +387,7 @@ function report(req, res, next) {
});
return totals;
}

// eslint-disable-next-line no-shadow
function totalPeriods(incomeTotal, expenseTotal, transferTotal) {
const total = {};
data.periods.forEach(periodId => {
Expand All @@ -395,6 +397,180 @@ function report(req, res, next) {
}
}

/**
* aggregateTotalByKeys
*
* this function process totals for incomes or expense by transaction type
* @param {*} source
* @param {*} sourceTotalByTextKeys
*/

function aggregateTotalByTextKeys(data, source = {}) {
const sourceTotalByTextKeys = {};

_.keys(source).forEach((index) => {
const currentTransactionText = source[index] || [];
sourceTotalByTextKeys[index] = {};

// loop for each periods
data.periods.forEach(periodId => {
sourceTotalByTextKeys[index][periodId] = _.sumBy(currentTransactionText, periodId);
});
});
return sourceTotalByTextKeys;
}

function aggregateTotal(data, source = {}) {
const totals = {};
const dataset = _.values(source);
data.periods.forEach(periodId => {
totals[periodId] = _.sumBy(dataset, periodId);
});
return totals;
}

function totalPeriods(data, incomeTotal, expenseTotal, transferTotal) {
const total = {};
data.periods.forEach(periodId => {
total[periodId] = incomeTotal[periodId] + expenseTotal[periodId] + transferTotal[periodId];
});
return total;
}

async function printingReport(options, session) {
try {
const dateFrom = new Date(options.dateFrom);
const dateTo = new Date(options.dateTo);
const data = {};

// convert cashboxesIds parameters in array format ['', '', ...]
// this parameter can be sent as a string or an array we force the conversion into an array
const cashboxesIds = _.values(options.cashboxesIds);

_.extend(options, { orientation : 'landscape' });

// catch missing required parameters
if (!dateFrom || !dateTo || !cashboxesIds.length) {
throw new BadRequest(
'ERRORS.BAD_REQUEST',
'There are some missing information among dateFrom, dateTo or cashboxesId'
);
}

const serviceReport = new ReportManager(TEMPLATE, session, options);

data.dateFrom = dateFrom;
data.dateTo = dateTo;

data.cashboxes = await getCashboxesDetails(cashboxesIds);
data.cashAccountIds = data.cashboxes.map(cashbox => cashbox.account_id);

data.cashLabels = _.chain(data.cashboxes)
.map(cashbox => `${cashbox.label}`).uniq().join(' | ')
.value();

data.cashLabelSymbol = _.chain(data.cashboxes)
.map(cashbox => cashbox.symbol).uniq().join(' + ');

data.cashLabelDetails = data.cashboxes.map(cashbox => `${cashbox.account_number} - ${cashbox.account_label}`);

// build periods columns from calculated period
const periods = await Fiscal.getPeriodsFromDateRange(data.dateFrom, data.dateTo);
data.periodDates = periods.map(p => p.start_date);
data.periods = periods.map(p => p.id);
data.colspan = data.periods.length + 1;
// build periods string for query
const periodParams = [];
const periodString = data.periods.length ? data.periods.map(periodId => {
periodParams.push(periodId, periodId);
return `SUM(IF(source.period_id = ?, source.balance, 0)) AS "?"`;
}).join(',') : '"NO_PERIOD" AS period';

const query = `
SELECT
source.transaction_text, source.account_label, ${periodString},
source.transaction_type, source.transaction_type_id, source.account_id
FROM (
SELECT
a.number AS account_number, a.label AS account_label,
SUM(gl.debit_equiv - gl.credit_equiv) AS balance,
gl.transaction_type_id, tt.type AS transaction_type, tt.text AS transaction_text,
gl.account_id, gl.period_id
FROM general_ledger AS gl
JOIN account AS a ON a.id = gl.account_id
JOIN transaction_type AS tt ON tt.id = gl.transaction_type_id
WHERE gl.account_id IN ? AND ((DATE(gl.trans_date) >= DATE(?)) AND (DATE(gl.trans_date) <= DATE(?)))
AND gl.transaction_type_id <> 10 AND gl.record_uuid NOT IN (
SELECT DISTINCT gl.record_uuid
FROM general_ledger AS gl
WHERE gl.record_uuid IN (
SELECT rev.uuid
FROM (
SELECT v.uuid FROM voucher v WHERE v.reversed = 1
AND DATE(v.date) >= DATE(?) AND DATE(v.date) <= DATE(?) UNION
SELECT c.uuid FROM cash c WHERE c.reversed = 1
AND DATE(c.date) >= DATE(?) AND DATE(c.date) <= DATE(?) UNION
SELECT i.uuid FROM invoice i WHERE i.reversed = 1
AND DATE(i.date) >= DATE(?) AND DATE(i.date) <= DATE(?)
) AS rev
)
) GROUP BY gl.transaction_type_id, gl.account_id, gl.period_id
) AS source
GROUP BY transaction_type_id, account_id;
`;

const params = [...periodParams,
[data.cashAccountIds],
data.dateFrom,
data.dateTo,
data.dateFrom,
data.dateTo,
data.dateFrom,
data.dateTo,
data.dateFrom,
data.dateTo];
const rows = await db.exec(query, params);

// split incomes from expenses
const incomes = _.chain(rows).filter({ transaction_type : 'income' }).groupBy('transaction_text').value();
const expenses = _.chain(rows).filter({ transaction_type : 'expense' }).groupBy('transaction_text').value();
const others = _.chain(rows).filter({ transaction_type : 'other' }).groupBy('transaction_text').value();

const incomeTextKeys = _.keys(incomes);
const expenseTextKeys = _.keys(expenses);
const otherTextKeys = _.keys(others);

const incomeTotalByTextKeys = aggregateTotalByTextKeys(data, incomes);
const expenseTotalByTextKeys = aggregateTotalByTextKeys(data, expenses);
const otherTotalByTextKeys = aggregateTotalByTextKeys(data, others);

const incomeTotal = aggregateTotal(data, incomeTotalByTextKeys);
const expenseTotal = aggregateTotal(data, expenseTotalByTextKeys);
const otherTotal = aggregateTotal(data, otherTotalByTextKeys);
const totalPeriodColumn = totalPeriods(data, incomeTotal, expenseTotal, otherTotal);

_.extend(data, {
incomes,
expenses,
others,
incomeTextKeys,
expenseTextKeys,
incomeTotalByTextKeys,
expenseTotalByTextKeys,
otherTotalByTextKeys,
incomeTotal,
expenseTotal,
otherTextKeys,
otherTotal,
totalPeriodColumn,
});

return serviceReport.render(data);
} catch (error) {
throw error;
}
}

/**
* getCashboxesDetails
*
Expand Down
Loading

0 comments on commit 3b21bfb

Please sign in to comment.