Skip to content

Commit

Permalink
fix(invoices): mv credit note logic into reversed
Browse files Browse the repository at this point in the history
This commit adds the reversed column which now is the basis for credit
note logic.  This reduces the need for an expensive LEFT JOIN on the
invoices table on every registry load.

There is also a slight performance improvement on the client side as it
is no longer necessary to do a few comparisons.

The `reversed` tag is updated when a credit note is created via the
`ReverseTransaction()` stored procedure.

Partially addressed #1336.
  • Loading branch information
Jonathan Niles authored and jniles committed Mar 11, 2017
1 parent 13cfee8 commit 9c17913
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 35 deletions.
30 changes: 14 additions & 16 deletions client/src/partials/patient_invoice/registry/registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ angular.module('bhima.controllers')

InvoiceRegistryController.$inject = [
'PatientInvoiceService', 'bhConstants', 'NotifyService',
'SessionService', 'ReceiptModal', 'appcache',
'uiGridConstants', 'ModalService', 'CashService', 'GridSortingService', '$state'
'SessionService', 'ReceiptModal', 'appcache', 'uiGridConstants',
'ModalService', 'CashService', 'GridSortingService', '$state',
];

/**
Expand All @@ -18,7 +18,7 @@ function InvoiceRegistryController(Invoices, bhConstants, Notify, Session, Recei
var cache = AppCache('InvoiceRegistry');

// Background color for make the difference betwen the valid and cancel invoice
var reversedBackgroundColor = {'background-color': '#ffb3b3' };
var reversedBackgroundColor = { 'background-color': '#ffb3b3'};
var regularBackgroundColor = { 'background-color': 'none' };
var FILTER_BAR_HEIGHT = bhConstants.grid.FILTER_BAR_HEIGHT;

Expand Down Expand Up @@ -49,12 +49,12 @@ function InvoiceRegistryController(Invoices, bhConstants, Notify, Session, Recei
{ field : 'cost',
displayName : 'TABLE.COLUMNS.COST',
headerCellFilter : 'translate',
cellTemplate: '/partials/patient_invoice/registry/templates/cost.cell.tmpl.html',
cellFilter: 'currency:' + Session.enterprise.currency_id,
aggregationType: uiGridConstants.aggregationTypes.sum,
aggregationHideLabel : true,
footerCellClass : 'text-right',
type: 'number',
footerCellFilter: 'currency:' + Session.enterprise.currency_id
footerCellFilter: 'currency:' + Session.enterprise.currency_id,
},
{ field : 'serviceName', displayName : 'TABLE.COLUMNS.SERVICE', headerCellFilter : 'translate' },
{ field : 'display_name', displayName : 'TABLE.COLUMNS.BY', headerCellFilter : 'translate' },
Expand All @@ -63,14 +63,14 @@ function InvoiceRegistryController(Invoices, bhConstants, Notify, Session, Recei

//setting columns names
vm.uiGridOptions = {
appScopeProvider : vm,
showColumnFooter : true,
appScopeProvider : vm,
showColumnFooter : true,
enableColumnMenus : false,
enableSorting : true,
fastWatch: true,
flatEntityAccess : true,
columnDefs : columnDefs,
rowTemplate : '/partials/patient_invoice/templates/grid.creditNote.tmpl.html'
enableSorting : true,
fastWatch : true,
flatEntityAccess : true,
columnDefs : columnDefs,
rowTemplate : '/partials/patient_invoice/templates/grid.creditNote.tmpl.html',
};

function handler(error) {
Expand Down Expand Up @@ -99,10 +99,8 @@ function InvoiceRegistryController(Invoices, bhConstants, Notify, Session, Recei
// hook the returned patients up to the grid.
request.then(function (invoices) {
invoices.forEach(function (invoice) {
invoice._backgroundColor =
(invoice.type_id === bhConstants.transactionType.CREDIT_NOTE) ? reversedBackgroundColor : regularBackgroundColor;

invoice._is_cancelled = (invoice.type_id === bhConstants.transactionType.CREDIT_NOTE);
invoice._backgroundColor = invoice.reversed ? reversedBackgroundColor : regularBackgroundColor
invoice._is_cancelled = invoice.reversed;
});

// put data in the grid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.uid"
ui-grid-one-bind-id-grid="rowRenderIndex + '-' + col.uid + '-cell'"
class="ui-grid-cell"
ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader, 'strike' : row.entity.type_id === grid.appScope.bhConstants.transactionType.CREDIT_NOTE }"
ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader, 'strike' : row.entity.reversed }"
data-vals="{{col.isRowHeader}}"
role="{{col.isRowHeader ? 'rowheader' : 'gridcell'}}"
ng-style="row.entity._backgroundColor"
Expand Down
2 changes: 1 addition & 1 deletion server/config/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ exports.configure = function configure(app) {
app.get('/inventory/metadata/search', inventory.searchInventoryItems);
app.get('/inventory/metadata/:uuid', inventory.getInventoryItemsById);
app.put('/inventory/metadata/:uuid', inventory.updateInventoryItems);

// route for inventory list receipt

/**
Expand Down
10 changes: 7 additions & 3 deletions server/controllers/finance/journal/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -524,10 +524,14 @@ function transformColumns(rows, newRecord) {
* POST /journal/:uuid/reverse
*/
function reverse(req, res, next) {

const voucherUuid = uuid.v4();
const recordUuid = db.bid(req.params.uuid);
const params = [ recordUuid, req.session.user.id, req.body.description, db.bid(voucherUuid) ];
const recordUuid = db.bid(req.params.uuid);
const params = [
recordUuid,
req.session.user.id,
req.body.description,
db.bid(voucherUuid),
];

/**
* Check already cancelled
Expand Down
19 changes: 8 additions & 11 deletions server/controllers/finance/patientInvoice.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,45 +203,42 @@ function find(options) {
// ensure expected options are parsed as binary
db.convert(options, ['patientUuid']);

let filters = new FilterParser(options, { tableAlias : 'invoice' });
const filters = new FilterParser(options, { tableAlias : 'invoice' });

// @FIXME Remove this with client side filter design
delete options.patientNames;

let sql =`
const sql = `
SELECT BUID(invoice.uuid) as uuid, invoice.project_id, invoice.date,
patient.display_name as patientName, invoice.cost, BUID(invoice.debtor_uuid) as debtor_uuid,
CONCAT_WS('.', '${identifiers.INVOICE.key}', project.abbr, invoice.reference) AS reference,
CONCAT_WS('.', '${identifiers.PATIENT.key}', project.abbr, patient.reference) AS patientReference,
service.name as serviceName, user.display_name, enterprise.currency_id, voucher.type_id,
invoice.user_id
service.name as serviceName, user.display_name, invoice.user_id, invoice.reversed
FROM invoice
LEFT JOIN patient ON invoice.debtor_uuid = patient.debtor_uuid
LEFT JOIN voucher ON voucher.reference_uuid = invoice.uuid
JOIN service ON service.id = invoice.service_id
JOIN user ON user.id = invoice.user_id
JOIN project ON project.id = invoice.project_id
JOIN enterprise ON enterprise.id = project.enterprise_id
`;

filters.equals('patientUuid', 'uuid', 'patient');
filters.dateFrom('billingDateFrom', 'date');
filters.dateTo('billingDateTo', 'date');

// support credit note toggle
filters.reversed('reversed');
// filters.reversed('reversed');

let referenceStatement = `CONCAT_WS('.', '${identifiers.INVOICE.key}', project.abbr, invoice.reference) = ?`;
const referenceStatement = `CONCAT_WS('.', '${identifiers.INVOICE.key}', project.abbr, invoice.reference) = ?`;
filters.custom('reference', referenceStatement);

let patientReferenceStatement = `CONCAT_WS('.', '${identifiers.PATIENT.key}', project.abbr, patient.reference) = ?`;
const patientReferenceStatement = `CONCAT_WS('.', '${identifiers.PATIENT.key}', project.abbr, patient.reference) = ?`;
filters.custom('patientReference', patientReferenceStatement);

// @TODO Support ordering query (reference support for limit)?
filters.setOrder('ORDER BY invoice.date DESC, invoice.reference DESC');

let query = filters.applyQuery(sql);
let parameters = filters.parameters();
const query = filters.applyQuery(sql);
const parameters = filters.parameters();
return db.exec(query, parameters);
}

Expand Down
16 changes: 14 additions & 2 deletions server/models/procedures.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1125,13 +1125,19 @@ CREATE PROCEDURE ReverseTransaction(
)
BEGIN
-- NOTE: someone should check that the record_uuid is not used as a reference_uuid somewhere
-- This is done in JS currently, but could be done here.
DECLARE isInvoice BOOLEAN;
DECLARE reversalType INT;

SET reversalType = 10;

SET isInvoice = (SELECT IFNULL((SELECT 1 FROM invoice WHERE invoice.uuid = uuid), 0));

-- the voucher type is credit note (id: 10)
-- @fixme - why do we have `amount` in the voucher table?
-- @todo - make only one type of reversal (not cash, credit, or voucher)

INSERT INTO voucher (uuid, date, project_id, currency_id, amount, description, user_id, type_id, reference_uuid)
SELECT voucher_uuid, NOW(), zz.project_id, enterprise.currency_id, 0, CONCAT_WS(' ', '(REVERSAL)', description), user_id, 10, uuid
SELECT voucher_uuid, NOW(), zz.project_id, enterprise.currency_id, 0, CONCAT_WS(' ', '(REVERSAL)', description), user_id, reversalType, uuid
FROM (
SELECT pj.project_id, pj.description FROM posting_journal AS pj WHERE pj.record_uuid = uuid
UNION ALL
Expand All @@ -1152,7 +1158,13 @@ BEGIN
FROM general_ledger AS gl WHERE gl.record_uuid = uuid
) AS zz;

-- make sure we update the invoice with the fact that it got reversed.
IF (isInvoice) THEN
UPDATE invoice SET reversed = 1 WHERE invoice.uuid = uuid;
END IF;

CALL PostVoucher(voucher_uuid);

END $$


Expand Down
1 change: 1 addition & 0 deletions server/models/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1508,6 +1508,7 @@ CREATE TABLE `invoice` (
`user_id` SMALLINT(5) UNSIGNED NOT NULL,
`date` DATETIME NOT NULL,
`description` TEXT NOT NULL,
`reversed` TINYINT NOT NULL DEFAULT 0,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uuid`),
UNIQUE KEY `invoice_1` (`project_id`, `reference`),
Expand Down
1 change: 0 additions & 1 deletion test/integration/journal.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/* global expect, chai, agent */

const helpers = require('./helpers');
Expand Down

0 comments on commit 9c17913

Please sign in to comment.