fix: issues in inventory adjustments service.

This commit is contained in:
a.bouhuolia
2021-01-10 13:37:02 +02:00
parent 36f2068474
commit 097b9fdb3a
7 changed files with 172 additions and 58 deletions

View File

@@ -2,8 +2,8 @@ import { Inject, Service } from 'typedi';
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { check, param } from 'express-validator'; import { check, param } from 'express-validator';
import { ServiceError } from 'exceptions'; import { ServiceError } from 'exceptions';
import BaseController from "../BaseController"; import BaseController from '../BaseController';
import InventoryAdjustmentService from "services/Inventory/InventoryAdjustmentService"; import InventoryAdjustmentService from 'services/Inventory/InventoryAdjustmentService';
@Service() @Service()
export default class InventoryAdjustmentsController extends BaseController { export default class InventoryAdjustmentsController extends BaseController {
@@ -18,12 +18,10 @@ export default class InventoryAdjustmentsController extends BaseController {
router.delete( router.delete(
'/:id', '/:id',
[ [param('id').exists().isNumeric().toInt()],
param('id').exists().isNumeric().toInt(),
],
this.validationResult, this.validationResult,
this.asyncMiddleware(this.deleteInventoryAdjustment.bind(this)), this.asyncMiddleware(this.deleteInventoryAdjustment.bind(this)),
this.handleServiceErrors, this.handleServiceErrors
); );
router.post( router.post(
'/quick', '/quick',
@@ -46,14 +44,24 @@ export default class InventoryAdjustmentsController extends BaseController {
get validatateQuickAdjustment() { get validatateQuickAdjustment() {
return [ return [
check('date').exists().isISO8601(), check('date').exists().isISO8601(),
check('type').exists().isIn(['increment', 'decrement', 'value_adjustment']), check('type')
.exists()
.isIn(['increment', 'decrement', 'value_adjustment']),
check('reference_no').exists(), check('reference_no').exists(),
check('adjustment_account_id').exists().isInt().toInt(), check('adjustment_account_id').exists().isInt().toInt(),
check('reason').exists().isString().exists(), check('reason').exists().isString().exists(),
check('description').optional().isString(), check('description').optional().isString(),
check('item_id').exists().isInt().toInt(), check('item_id').exists().isInt().toInt(),
check('new_quantity').optional().isInt(), check('quantity')
check('new_value').optional().toFloat(), .if(check('type').exists().isIn(['increment', 'decrement']))
.exists()
.isInt()
.toInt(),
check('cost')
.if(check('type').exists().isIn(['increment']))
.exists()
.isFloat()
.toInt(),
]; ];
} }
@@ -63,15 +71,24 @@ export default class InventoryAdjustmentsController extends BaseController {
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async createQuickInventoryAdjustment(req: Request, res: Response, next: NextFunction) { async createQuickInventoryAdjustment(
const { tenantId } = req; req: Request,
res: Response,
next: NextFunction
) {
const { tenantId, user } = req;
const quickInventoryAdjustment = this.matchedBodyData(req); const quickInventoryAdjustment = this.matchedBodyData(req);
console.log(quickInventoryAdjustment);
try { try {
await this.inventoryAdjustmentService const inventoryAdjustment = await this.inventoryAdjustmentService.createQuickAdjustment(
.createQuickAdjustment(tenantId, quickInventoryAdjustment); tenantId,
quickInventoryAdjustment,
user
);
return res.status(200).send({ return res.status(200).send({
id: inventoryAdjustment.id,
message: 'The inventory adjustment has been created successfully.', message: 'The inventory adjustment has been created successfully.',
}); });
} catch (error) { } catch (error) {
@@ -85,14 +102,20 @@ export default class InventoryAdjustmentsController extends BaseController {
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async deleteInventoryAdjustment(req: Request, res: Response, next: NextFunction) { async deleteInventoryAdjustment(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req; const { tenantId } = req;
const { id: adjustmentId } = req.params; const { id: adjustmentId } = req.params;
try { try {
await this.inventoryAdjustmentService await this.inventoryAdjustmentService.deleteInventoryAdjustment(
.deleteInventoryAdjustment(tenantId, adjustmentId); tenantId,
adjustmentId
);
return res.status(200).send({ return res.status(200).send({
message: 'The inventory adjustment has been deleted successfully.', message: 'The inventory adjustment has been deleted successfully.',
}); });
@@ -103,11 +126,15 @@ export default class InventoryAdjustmentsController extends BaseController {
/** /**
* Retrieve the inventory adjustments paginated list. * Retrieve the inventory adjustments paginated list.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async getInventoryAdjustments(req: Request, res: Response, next: NextFunction) { async getInventoryAdjustments(
req: Request,
res: Response,
next: NextFunction
) {
const { tenantId } = req; const { tenantId } = req;
const filter = { const filter = {
page: 1, page: 1,
@@ -119,9 +146,11 @@ export default class InventoryAdjustmentsController extends BaseController {
const { const {
pagination, pagination,
inventoryAdjustments, inventoryAdjustments,
} = await this.inventoryAdjustmentService } = await this.inventoryAdjustmentService.getInventoryAdjustments(
.getInventoryAdjustments(tenantId, filter); tenantId,
filter
);
return res.status(200).send({ return res.status(200).send({
inventoy_adjustments: inventoryAdjustments, inventoy_adjustments: inventoryAdjustments,
pagination: this.transfromToResponse(pagination), pagination: this.transfromToResponse(pagination),
@@ -147,7 +176,11 @@ export default class InventoryAdjustmentsController extends BaseController {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'INVENTORY_ADJUSTMENT_NOT_FOUND') { if (error.errorType === 'INVENTORY_ADJUSTMENT_NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'INVENTORY_ADJUSTMENT.NOT.FOUND', code: 100 }], errors: [{
type: 'INVENTORY_ADJUSTMENT.NOT.FOUND',
code: 100,
message: 'The inventory adjustment not found.'
}],
}); });
} }
if (error.errorType === 'NOT_FOUND') { if (error.errorType === 'NOT_FOUND') {
@@ -163,10 +196,10 @@ export default class InventoryAdjustmentsController extends BaseController {
if (error.errorType === 'ITEM_SHOULD_BE_INVENTORY_TYPE') { if (error.errorType === 'ITEM_SHOULD_BE_INVENTORY_TYPE') {
return res.boom.badRequest( return res.boom.badRequest(
'You could not make adjustment on item has no inventory type.', 'You could not make adjustment on item has no inventory type.',
{ errors: [{ type: 'ITEM_SHOULD_BE_INVENTORY_TYPE', code: 300 }], } { errors: [{ type: 'ITEM_SHOULD_BE_INVENTORY_TYPE', code: 300 }] }
); );
} }
} }
next(error); next(error);
} }
} }

View File

@@ -4,9 +4,12 @@ exports.up = function(knex) {
table.increments(); table.increments();
table.date('date').index(); table.date('date').index();
table.string('type').index(); table.string('type').index();
table.integer('adjustment_account_id').unsigned().references('id').inTable('accounts');
table.string('reason'); table.string('reason');
table.string('reference_no').index(); table.string('reference_no').index();
table.string('description'); table.string('description');
table.integer('user_id').unsigned();
table.timestamps();
}); });
}; };

View File

@@ -5,8 +5,9 @@ exports.up = function(knex) {
table.integer('adjustment_id').unsigned().index().references('id').inTable('inventory_adjustments'); table.integer('adjustment_id').unsigned().index().references('id').inTable('inventory_adjustments');
table.integer('index').unsigned(); table.integer('index').unsigned();
table.integer('item_id').unsigned().index().references('id').inTable('items'); table.integer('item_id').unsigned().index().references('id').inTable('items');
table.decimal('new_quantity').unsigned(); table.integer('quantity');
table.decimal('new_cost').unsigned(); table.decimal('cost').unsigned();
table.decimal('value').unsigned();
}); });
}; };

View File

@@ -9,8 +9,8 @@ export interface IQuickInventoryAdjustmentDTO {
description: string; description: string;
referenceNo: string; referenceNo: string;
itemId: number; itemId: number;
newQuantity: number; quantity: number;
newValue: number; cost: number;
}; };
export interface IInventoryAdjustment { export interface IInventoryAdjustment {
@@ -20,7 +20,8 @@ export interface IInventoryAdjustment {
reason: string; reason: string;
description: string; description: string;
referenceNo: string; referenceNo: string;
entries: IInventoryAdjustmentEntry[] entries: IInventoryAdjustmentEntry[];
userId: number;
}; };
export interface IInventoryAdjustmentEntry { export interface IInventoryAdjustmentEntry {
@@ -28,9 +29,10 @@ export interface IInventoryAdjustmentEntry {
adjustmentId?: number, adjustmentId?: number,
index: number, index: number,
itemId: number; itemId: number;
newQuantity: number; quantity?: number;
newValue: number; cost?: number;
} value?: number;
};
export interface IInventoryAdjustmentsFilter{ export interface IInventoryAdjustmentsFilter{
page: number, page: number,

View File

@@ -9,21 +9,44 @@ export default class InventoryAdjustment extends TenantModel {
return 'inventory_adjustments'; return 'inventory_adjustments';
} }
/**
* Timestamps columns.
*/
get timestamps() {
return ['created_at'];
}
/** /**
* Relationship mapping. * Relationship mapping.
*/ */
static get relationMappings() { static get relationMappings() {
const Account = require('models/InventoryAdjustmentEntry'); const InventoryAdjustmentEntry = require('models/InventoryAdjustmentEntry');
const Account = require('models/Account');
return { return {
/**
* Adjustment entries.
*/
entries: { entries: {
relation: Model.BelongsToOneRelation, relation: Model.HasManyRelation,
modelClass: Account.default, modelClass: InventoryAdjustmentEntry.default,
join: { join: {
from: 'inventory_adjustments.id', from: 'inventory_adjustments.id',
to: 'inventory_adjustments_entries.adjustmentId', to: 'inventory_adjustments_entries.adjustmentId',
}, },
}, },
/**
* Inventory adjustment account.
*/
adjustmentAccount: {
relation: Model.BelongsToOneRelation,
modelClass: Account.default,
join: {
from: 'inventory_adjustments.adjustmentAccountId',
to: 'accounts.id',
},
},
}; };
} }
} }

View File

@@ -3,7 +3,7 @@ import TenantModel from 'models/TenantModel';
export default class InventoryAdjustmentEntry extends TenantModel { export default class InventoryAdjustmentEntry extends TenantModel {
/** /**
* Table name * Table name.
*/ */
static get tableName() { static get tableName() {
return 'inventory_adjustments_entries'; return 'inventory_adjustments_entries';
@@ -13,17 +13,30 @@ export default class InventoryAdjustmentEntry extends TenantModel {
* Relationship mapping. * Relationship mapping.
*/ */
static get relationMappings() { static get relationMappings() {
const Account = require('models/InventoryAdjustment'); const InventoryAdjustment = require('models/InventoryAdjustment');
const Item = require('models/Item');
return { return {
entries: { inventoryAdjustment: {
relation: Model.BelongsToOneRelation, relation: Model.BelongsToOneRelation,
modelClass: Account.default, modelClass: InventoryAdjustment.default,
join: { join: {
from: 'inventory_adjustments_entries.adjustmentId', from: 'inventory_adjustments_entries.adjustmentId',
to: 'inventory_adjustments.id', to: 'inventory_adjustments.id',
}, },
}, },
/**
* Entry item.
*/
item: {
relation: Model.BelongsToOneRelation,
modelClass: Item.default,
join: {
from: 'inventory_adjustments_entries.itemId',
to: 'items.id',
},
},
}; };
} }
} }

View File

@@ -9,7 +9,8 @@ import {
IQuickInventoryAdjustmentDTO, IQuickInventoryAdjustmentDTO,
IInventoryAdjustment, IInventoryAdjustment,
IPaginationMeta, IPaginationMeta,
IInventoryAdjustmentsFilter IInventoryAdjustmentsFilter,
ISystemUser,
} from 'interfaces'; } from 'interfaces';
import events from 'subscribers/events'; import events from 'subscribers/events';
import AccountsService from 'services/Accounts/AccountsService'; import AccountsService from 'services/Accounts/AccountsService';
@@ -44,16 +45,26 @@ export default class InventoryAdjustmentService {
* @return {IInventoryAdjustment} * @return {IInventoryAdjustment}
*/ */
transformQuickAdjToModel( transformQuickAdjToModel(
adjustmentDTO: IQuickInventoryAdjustmentDTO adjustmentDTO: IQuickInventoryAdjustmentDTO,
authorizedUser: ISystemUser
): IInventoryAdjustment { ): IInventoryAdjustment {
return { return {
...omit(adjustmentDTO, ['newQuantity', 'newCost', 'itemId']), ...omit(adjustmentDTO, ['quantity', 'cost', 'itemId']),
userId: authorizedUser.id,
entries: [ entries: [
{ {
index: 1, index: 1,
itemId: adjustmentDTO.itemId, itemId: adjustmentDTO.itemId,
newQuantity: adjustmentDTO.newQuantity, ...(['increment', 'decrement'].indexOf(adjustmentDTO.type) !== -1
newCost: adjustmentDTO.newCost, ? {
quantity: adjustmentDTO.quantity,
}
: {}),
...('increment' === adjustmentDTO.type
? {
cost: adjustmentDTO.cost,
}
: {}),
}, },
], ],
}; };
@@ -97,10 +108,18 @@ export default class InventoryAdjustmentService {
*/ */
async createQuickAdjustment( async createQuickAdjustment(
tenantId: number, tenantId: number,
quickAdjustmentDTO: IQuickInventoryAdjustmentDTO quickAdjustmentDTO: IQuickInventoryAdjustmentDTO,
) { authorizedUser: ISystemUser
): Promise<IInventoryAdjustment> {
const { InventoryAdjustment } = this.tenancy.models(tenantId); const { InventoryAdjustment } = this.tenancy.models(tenantId);
this.logger.info(
'[inventory_adjustment] trying to create quick adjustment..',
{
tenantId,
quickAdjustmentDTO,
}
);
// Retrieve the adjustment account or throw not found error. // Retrieve the adjustment account or throw not found error.
const adjustmentAccount = await this.accountsService.getAccountOrThrowError( const adjustmentAccount = await this.accountsService.getAccountOrThrowError(
tenantId, tenantId,
@@ -116,10 +135,10 @@ export default class InventoryAdjustmentService {
// Transform the DTO to inventory adjustment model. // Transform the DTO to inventory adjustment model.
const invAdjustmentObject = this.transformQuickAdjToModel( const invAdjustmentObject = this.transformQuickAdjToModel(
quickAdjustmentDTO quickAdjustmentDTO,
authorizedUser
); );
const inventoryAdjustment = await InventoryAdjustment.query().upsertGraph({
await InventoryAdjustment.query().upsertGraph({
...invAdjustmentObject, ...invAdjustmentObject,
}); });
// Triggers `onInventoryAdjustmentQuickCreated` event. // Triggers `onInventoryAdjustmentQuickCreated` event.
@@ -129,6 +148,14 @@ export default class InventoryAdjustmentService {
tenantId, tenantId,
} }
); );
this.logger.info(
'[inventory_adjustment] quick adjustment created successfully.',
{
tenantId,
quickAdjustmentDTO,
}
);
return inventoryAdjustment;
} }
/** /**
@@ -150,6 +177,10 @@ export default class InventoryAdjustmentService {
InventoryAdjustment, InventoryAdjustment,
} = this.tenancy.models(tenantId); } = this.tenancy.models(tenantId);
this.logger.info('[inventory_adjustment] trying to delete adjustment.', {
tenantId,
inventoryAdjustmentId,
});
// Deletes the inventory adjustment entries. // Deletes the inventory adjustment entries.
await InventoryAdjustmentEntry.query() await InventoryAdjustmentEntry.query()
.where('adjustment_id', inventoryAdjustmentId) .where('adjustment_id', inventoryAdjustmentId)
@@ -162,12 +193,19 @@ export default class InventoryAdjustmentService {
await this.eventDispatcher.dispatch(events.inventoryAdjustment.onDeleted, { await this.eventDispatcher.dispatch(events.inventoryAdjustment.onDeleted, {
tenantId, tenantId,
}); });
this.logger.info(
'[inventory_adjustment] the adjustment deleted successfully.',
{
tenantId,
inventoryAdjustmentId,
}
);
} }
/** /**
* Retrieve the inventory adjustments paginated list. * Retrieve the inventory adjustments paginated list.
* @param {number} tenantId * @param {number} tenantId
* @param {IInventoryAdjustmentsFilter} adjustmentsFilter * @param {IInventoryAdjustmentsFilter} adjustmentsFilter
*/ */
async getInventoryAdjustments( async getInventoryAdjustments(
tenantId: number, tenantId: number,
@@ -179,7 +217,8 @@ export default class InventoryAdjustmentService {
const { InventoryAdjustment } = this.tenancy.models(tenantId); const { InventoryAdjustment } = this.tenancy.models(tenantId);
const { results, pagination } = await InventoryAdjustment.query() const { results, pagination } = await InventoryAdjustment.query()
.withGraphFetched('entries') .withGraphFetched('entries.item')
.withGraphFetched('adjustmentAccount')
.pagination(adjustmentsFilter.page - 1, adjustmentsFilter.pageSize); .pagination(adjustmentsFilter.page - 1, adjustmentsFilter.pageSize);
return { return {