fix: delete item from the storage.

This commit is contained in:
a.bouhuolia
2020-12-16 16:38:18 +02:00
parent 42c2e583ed
commit 3ac6d8897e
2 changed files with 226 additions and 92 deletions

View File

@@ -186,7 +186,7 @@ export default class ItemsController extends BaseController {
*/ */
get validateBulkSelectSchema(): ValidationChain[] { get validateBulkSelectSchema(): ValidationChain[] {
return [ return [
query('ids').isArray({ min: 2 }), query('ids').isArray({ min: 1 }),
query('ids.*').isNumeric().toInt(), query('ids.*').isNumeric().toInt(),
]; ];
} }
@@ -318,6 +318,8 @@ export default class ItemsController extends BaseController {
return res.status(200).send({ item: storedItem }); return res.status(200).send({ item: storedItem });
} catch (error) { } catch (error) {
console.log(error);
next(error) next(error)
} }
} }
@@ -369,7 +371,11 @@ export default class ItemsController extends BaseController {
try { try {
await this.itemsService.bulkDeleteItems(tenantId, itemsIds); await this.itemsService.bulkDeleteItems(tenantId, itemsIds);
return res.status(200).send({ ids: itemsIds });
return res.status(200).send({
ids: itemsIds,
message: 'Items have been deleted successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }

View File

@@ -1,9 +1,9 @@
import { defaultTo, difference } from "lodash"; import { defaultTo, difference } from 'lodash';
import { Service, Inject } from "typedi"; import { Service, Inject } from 'typedi';
import { IItemsFilter, IItemsService, IItemDTO, IItem } from 'interfaces'; import { IItemsFilter, IItemsService, IItemDTO, IItem } from 'interfaces';
import DynamicListingService from 'services/DynamicListing/DynamicListService'; import DynamicListingService from 'services/DynamicListing/DynamicListService';
import TenancyService from 'services/Tenancy/TenancyService'; import TenancyService from 'services/Tenancy/TenancyService';
import { ServiceError } from "exceptions"; import { ServiceError } from 'exceptions';
const ERRORS = { const ERRORS = {
NOT_FOUND: 'NOT_FOUND', NOT_FOUND: 'NOT_FOUND',
@@ -18,7 +18,7 @@ const ERRORS = {
INVENTORY_ACCOUNT_NOT_INVENTORY: 'INVENTORY_ACCOUNT_NOT_INVENTORY', INVENTORY_ACCOUNT_NOT_INVENTORY: 'INVENTORY_ACCOUNT_NOT_INVENTORY',
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS', ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS' ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS',
}; };
@Service() @Service()
@@ -38,7 +38,10 @@ export default class ItemsService implements IItemsService {
* @param {number} itemId * @param {number} itemId
* @return {Promise<void>} * @return {Promise<void>}
*/ */
private async getItemOrThrowError(tenantId: number, itemId: number): Promise<void> { private async getItemOrThrowError(
tenantId: number,
itemId: number
): Promise<void> {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
this.logger.info('[items] validate item id existance.', { itemId }); this.logger.info('[items] validate item id existance.', { itemId });
@@ -58,10 +61,17 @@ export default class ItemsService implements IItemsService {
* @param {number} notItemId * @param {number} notItemId
* @return {Promise<void>} * @return {Promise<void>}
*/ */
private async validateItemNameUniquiness(tenantId: number, itemName: string, notItemId?: number): Promise<void> { private async validateItemNameUniquiness(
tenantId: number,
itemName: string,
notItemId?: number
): Promise<void> {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
this.logger.info('[items] validate item name uniquiness.', { itemName, tenantId }); this.logger.info('[items] validate item name uniquiness.', {
itemName,
tenantId,
});
const foundItems: [] = await Item.query().onBuild((builder: any) => { const foundItems: [] = await Item.query().onBuild((builder: any) => {
builder.where('name', itemName); builder.where('name', itemName);
if (notItemId) { if (notItemId) {
@@ -69,7 +79,10 @@ export default class ItemsService implements IItemsService {
} }
}); });
if (foundItems.length > 0) { if (foundItems.length > 0) {
this.logger.info('[items] item name already exists.', { itemName, tenantId }); this.logger.info('[items] item name already exists.', {
itemName,
tenantId,
});
throw new ServiceError(ERRORS.ITEM_NAME_EXISTS); throw new ServiceError(ERRORS.ITEM_NAME_EXISTS);
} }
} }
@@ -80,18 +93,33 @@ export default class ItemsService implements IItemsService {
* @param {number} costAccountId * @param {number} costAccountId
* @return {Promise<void>} * @return {Promise<void>}
*/ */
private async validateItemCostAccountExistance(tenantId: number, costAccountId: number): Promise<void> { private async validateItemCostAccountExistance(
const { accountRepository, accountTypeRepository } = this.tenancy.repositories(tenantId); tenantId: number,
costAccountId: number
): Promise<void> {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate cost account existance.', { tenantId, costAccountId }); this.logger.info('[items] validate cost account existance.', {
tenantId,
costAccountId,
});
const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold'); const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold');
const foundAccount = await accountRepository.findOneById(costAccountId) const foundAccount = await accountRepository.findOneById(costAccountId);
if (!foundAccount) { if (!foundAccount) {
this.logger.info('[items] cost account not found.', { tenantId, costAccountId }); this.logger.info('[items] cost account not found.', {
tenantId,
costAccountId,
});
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD); throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
} else if (foundAccount.accountTypeId !== COGSType.id) { } else if (foundAccount.accountTypeId !== COGSType.id) {
this.logger.info('[items] validate cost account not COGS type.', { tenantId, costAccountId }); this.logger.info('[items] validate cost account not COGS type.', {
tenantId,
costAccountId,
});
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_COGS); throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_COGS);
} }
} }
@@ -101,18 +129,33 @@ export default class ItemsService implements IItemsService {
* @param {number} tenantId - Tenant id. * @param {number} tenantId - Tenant id.
* @param {number} sellAccountId - Sell account id. * @param {number} sellAccountId - Sell account id.
*/ */
private async validateItemSellAccountExistance(tenantId: number, sellAccountId: number) { private async validateItemSellAccountExistance(
const { accountRepository, accountTypeRepository } = this.tenancy.repositories(tenantId); tenantId: number,
sellAccountId: number
) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate sell account existance.', { tenantId, sellAccountId }); this.logger.info('[items] validate sell account existance.', {
tenantId,
sellAccountId,
});
const incomeType = await accountTypeRepository.getByKey('income'); const incomeType = await accountTypeRepository.getByKey('income');
const foundAccount = await accountRepository.findOneById(sellAccountId); const foundAccount = await accountRepository.findOneById(sellAccountId);
if (!foundAccount) { if (!foundAccount) {
this.logger.info('[items] sell account not found.', { tenantId, sellAccountId }); this.logger.info('[items] sell account not found.', {
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND) tenantId,
sellAccountId,
});
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
} else if (foundAccount.accountTypeId !== incomeType.id) { } else if (foundAccount.accountTypeId !== incomeType.id) {
this.logger.info('[items] sell account not income type.', { tenantId, sellAccountId }); this.logger.info('[items] sell account not income type.', {
tenantId,
sellAccountId,
});
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_INCOME); throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_INCOME);
} }
} }
@@ -122,18 +165,35 @@ export default class ItemsService implements IItemsService {
* @param {number} tenantId * @param {number} tenantId
* @param {number} inventoryAccountId * @param {number} inventoryAccountId
*/ */
private async validateItemInventoryAccountExistance(tenantId: number, inventoryAccountId: number) { private async validateItemInventoryAccountExistance(
const { accountTypeRepository, accountRepository } = this.tenancy.repositories(tenantId); tenantId: number,
inventoryAccountId: number
) {
const {
accountTypeRepository,
accountRepository,
} = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate inventory account existance.', { tenantId, inventoryAccountId }); this.logger.info('[items] validate inventory account existance.', {
tenantId,
inventoryAccountId,
});
const otherAsset = await accountTypeRepository.getByKey('other_asset'); const otherAsset = await accountTypeRepository.getByKey('other_asset');
const foundAccount = await accountRepository.findOneById(inventoryAccountId); const foundAccount = await accountRepository.findOneById(
inventoryAccountId
);
if (!foundAccount) { if (!foundAccount) {
this.logger.info('[items] inventory account not found.', { tenantId, inventoryAccountId }); this.logger.info('[items] inventory account not found.', {
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND) tenantId,
inventoryAccountId,
});
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
} else if (otherAsset.id !== foundAccount.accountTypeId) { } else if (otherAsset.id !== foundAccount.accountTypeId) {
this.logger.info('[items] inventory account not inventory type.', { tenantId, inventoryAccountId }); this.logger.info('[items] inventory account not inventory type.', {
tenantId,
inventoryAccountId,
});
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_INVENTORY); throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_INVENTORY);
} }
} }
@@ -143,7 +203,10 @@ export default class ItemsService implements IItemsService {
* @param {number} tenantId * @param {number} tenantId
* @param {number} itemCategoryId * @param {number} itemCategoryId
*/ */
private async validateItemCategoryExistance(tenantId: number, itemCategoryId: number) { private async validateItemCategoryExistance(
tenantId: number,
itemCategoryId: number
) {
const { ItemCategory } = this.tenancy.models(tenantId); const { ItemCategory } = this.tenancy.models(tenantId);
const foundCategory = await ItemCategory.query().findById(itemCategoryId); const foundCategory = await ItemCategory.query().findById(itemCategoryId);
@@ -168,19 +231,31 @@ export default class ItemsService implements IItemsService {
await this.validateItemCategoryExistance(tenantId, itemDTO.categoryId); await this.validateItemCategoryExistance(tenantId, itemDTO.categoryId);
} }
if (itemDTO.sellAccountId) { if (itemDTO.sellAccountId) {
await this.validateItemSellAccountExistance(tenantId, itemDTO.sellAccountId); await this.validateItemSellAccountExistance(
tenantId,
itemDTO.sellAccountId
);
} }
if (itemDTO.costAccountId) { if (itemDTO.costAccountId) {
await this.validateItemCostAccountExistance(tenantId, itemDTO.costAccountId); await this.validateItemCostAccountExistance(
tenantId,
itemDTO.costAccountId
);
} }
if (itemDTO.inventoryAccountId) { if (itemDTO.inventoryAccountId) {
await this.validateItemInventoryAccountExistance(tenantId, itemDTO.inventoryAccountId); await this.validateItemInventoryAccountExistance(
tenantId,
itemDTO.inventoryAccountId
);
} }
const storedItem = await Item.query().insertAndFetch({ const storedItem = await Item.query().insertAndFetch({
...itemDTO, ...itemDTO,
active: defaultTo(itemDTO.active, 1), active: defaultTo(itemDTO.active, 1),
}); });
this.logger.info('[items] item inserted successfully.', { tenantId, itemDTO }); this.logger.info('[items] item inserted successfully.', {
tenantId,
itemDTO,
});
return storedItem; return storedItem;
} }
@@ -197,21 +272,40 @@ export default class ItemsService implements IItemsService {
// Validates the given item existance on the storage. // Validates the given item existance on the storage.
const oldItem = await this.getItemOrThrowError(tenantId, itemId); const oldItem = await this.getItemOrThrowError(tenantId, itemId);
// Validate the item category existance on the storage,
if (itemDTO.categoryId) { if (itemDTO.categoryId) {
await this.validateItemCategoryExistance(tenantId, itemDTO.categoryId); await this.validateItemCategoryExistance(tenantId, itemDTO.categoryId);
} }
// Validate the sell account existance on the storage.
if (itemDTO.sellAccountId) { if (itemDTO.sellAccountId) {
await this.validateItemSellAccountExistance(tenantId, itemDTO.sellAccountId); await this.validateItemSellAccountExistance(
tenantId,
itemDTO.sellAccountId
);
} }
// Validate the cost account existance on the storage.
if (itemDTO.costAccountId) { if (itemDTO.costAccountId) {
await this.validateItemCostAccountExistance(tenantId, itemDTO.costAccountId); await this.validateItemCostAccountExistance(
tenantId,
itemDTO.costAccountId
);
} }
// Validate the inventory account existance onthe storage.
if (itemDTO.inventoryAccountId) { if (itemDTO.inventoryAccountId) {
await this.validateItemInventoryAccountExistance(tenantId, itemDTO.inventoryAccountId); await this.validateItemInventoryAccountExistance(
tenantId,
itemDTO.inventoryAccountId
);
} }
const newItem = await Item.query().patchAndFetchById(itemId, { ...itemDTO }); const newItem = await Item.query().patchAndFetchById(itemId, {
this.logger.info('[items] item edited successfully.', { tenantId, itemId, itemDTO }); ...itemDTO,
});
this.logger.info('[items] item edited successfully.', {
tenantId,
itemId,
itemDTO,
});
return newItem; return newItem;
} }
@@ -242,7 +336,10 @@ export default class ItemsService implements IItemsService {
public async activateItem(tenantId: number, itemId: number): Promise<void> { public async activateItem(tenantId: number, itemId: number): Promise<void> {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
this.logger.info('[items] trying to activate the given item.', { tenantId, itemId }); this.logger.info('[items] trying to activate the given item.', {
tenantId,
itemId,
});
const item = await this.getItemOrThrowError(tenantId, itemId); const item = await this.getItemOrThrowError(tenantId, itemId);
await Item.query().findById(itemId).patch({ active: true }); await Item.query().findById(itemId).patch({ active: true });
@@ -256,10 +353,13 @@ export default class ItemsService implements IItemsService {
* @param {number} itemId * @param {number} itemId
* @return {Promise<void>} * @return {Promise<void>}
*/ */
public async inactivateItem(tenantId: number, itemId: number): Promise<void> { public async inactivateItem(tenantId: number, itemId: number): Promise<void> {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
this.logger.info('[items] trying to inactivate the given item.', { tenantId, itemId }); this.logger.info('[items] trying to inactivate the given item.', {
tenantId,
itemId,
});
const item = await this.getItemOrThrowError(tenantId, itemId); const item = await this.getItemOrThrowError(tenantId, itemId);
await Item.query().findById(itemId).patch({ active: false }); await Item.query().findById(itemId).patch({ active: false });
@@ -275,8 +375,19 @@ export default class ItemsService implements IItemsService {
public async getItem(tenantId: number, itemId: number): Promise<IItem> { public async getItem(tenantId: number, itemId: number): Promise<IItem> {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
const item = Item.query().findById(itemId) this.logger.info('[items] trying to get the specific item.', {
.withGraphFetched('costAccount', 'sellAccount', 'inventoryAccount', 'category'); tenantId,
itemId,
});
const item = await Item.query()
.findById(itemId)
.withGraphFetched(
'costAccount',
'sellAccount',
'inventoryAccount',
'category'
);
if (!item) { if (!item) {
throw new ServiceError(ERRORS.NOT_FOUND); throw new ServiceError(ERRORS.NOT_FOUND);
@@ -307,12 +418,18 @@ export default class ItemsService implements IItemsService {
public async bulkDeleteItems(tenantId: number, itemsIds: number[]) { public async bulkDeleteItems(tenantId: number, itemsIds: number[]) {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
this.logger.info('[items] trying to delete items in bulk.', { tenantId, itemsIds }); this.logger.info('[items] trying to delete items in bulk.', {
tenantId,
itemsIds,
});
await this.validateItemsIdsExists(tenantId, itemsIds); await this.validateItemsIdsExists(tenantId, itemsIds);
await this.validateHasNoInvoicesOrBills(tenantId, itemsIds); await this.validateHasNoInvoicesOrBills(tenantId, itemsIds);
await Item.query().whereIn('id', itemsIds).delete(); await Item.query().whereIn('id', itemsIds).delete();
this.logger.info('[items] deleted successfully in bulk.', { tenantId, itemsIds }); this.logger.info('[items] deleted successfully in bulk.', {
tenantId,
itemsIds,
});
} }
/** /**
@@ -322,20 +439,27 @@ export default class ItemsService implements IItemsService {
*/ */
public async itemsList(tenantId: number, itemsFilter: IItemsFilter) { public async itemsList(tenantId: number, itemsFilter: IItemsFilter) {
const { Item } = this.tenancy.models(tenantId); const { Item } = this.tenancy.models(tenantId);
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, Item, itemsFilter); const dynamicFilter = await this.dynamicListService.dynamicList(
tenantId,
const { results, pagination } = await Item.query().onBuild((builder) => { Item,
builder.withGraphFetched('inventoryAccount'); itemsFilter
builder.withGraphFetched('sellAccount');
builder.withGraphFetched('costAccount');
builder.withGraphFetched('category');
dynamicFilter.buildQuery()(builder);
}).pagination(
itemsFilter.page - 1,
itemsFilter.pageSize,
); );
return { items: results, pagination, filterMeta: dynamicFilter.getResponseMeta() };
const { results, pagination } = await Item.query()
.onBuild((builder) => {
builder.withGraphFetched('inventoryAccount');
builder.withGraphFetched('sellAccount');
builder.withGraphFetched('costAccount');
builder.withGraphFetched('category');
dynamicFilter.buildQuery()(builder);
})
.pagination(itemsFilter.page - 1, itemsFilter.pageSize);
return {
items: results,
pagination,
filterMeta: dynamicFilter.getResponseMeta(),
};
} }
/** /**
@@ -344,7 +468,10 @@ export default class ItemsService implements IItemsService {
* @param {number|number[]} itemId - Item id. * @param {number|number[]} itemId - Item id.
* @throws {ServiceError} * @throws {ServiceError}
*/ */
private async validateHasNoInvoicesOrBills(tenantId: number, itemId: number[]|number) { private async validateHasNoInvoicesOrBills(
tenantId: number,
itemId: number[] | number
) {
const { ItemEntry } = this.tenancy.models(tenantId); const { ItemEntry } = this.tenancy.models(tenantId);
const ids = Array.isArray(itemId) ? itemId : [itemId]; const ids = Array.isArray(itemId) ? itemId : [itemId];
@@ -353,9 +480,10 @@ export default class ItemsService implements IItemsService {
.whereIn('reference_type', ['SaleInvoice', 'Bill']); .whereIn('reference_type', ['SaleInvoice', 'Bill']);
if (foundItemEntries.length > 0) { if (foundItemEntries.length > 0) {
throw new ServiceError(ids.length > 1 ? throw new ServiceError(
ERRORS.ITEMS_HAVE_ASSOCIATED_TRANSACTIONS : ids.length > 1
ERRORS.ITEM_HAS_ASSOCIATED_TRANSACTINS ? ERRORS.ITEMS_HAVE_ASSOCIATED_TRANSACTIONS
: ERRORS.ITEM_HAS_ASSOCIATED_TRANSACTINS
); );
} }
} }