fix: retrieve bills and bills payments list.

This commit is contained in:
Ahmed Bouhuolia
2020-10-24 12:37:17 +02:00
parent ab4ec24619
commit 0a03fcdd92
7 changed files with 148 additions and 49 deletions

View File

@@ -7,6 +7,7 @@ import BillsService from 'services/Purchases/Bills';
import BaseController from 'api/controllers/BaseController'; import BaseController from 'api/controllers/BaseController';
import ItemsService from 'services/Items/ItemsService'; import ItemsService from 'services/Items/ItemsService';
import TenancyService from 'services/Tenancy/TenancyService'; import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions'; import { ServiceError } from 'exceptions';
@Service() @Service()
@@ -20,6 +21,9 @@ export default class BillsController extends BaseController {
@Inject() @Inject()
tenancy: TenancyService; tenancy: TenancyService;
@Inject()
dynamicListService: DynamicListingService;
/** /**
* Router constructor. * Router constructor.
*/ */
@@ -28,7 +32,7 @@ export default class BillsController extends BaseController {
router.post( router.post(
'/', [ '/', [
...this.billValidationSchema ...this.billValidationSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.newBill.bind(this)), asyncMiddleware(this.newBill.bind(this)),
@@ -44,29 +48,25 @@ export default class BillsController extends BaseController {
); );
router.get( router.get(
'/:id', [ '/:id', [
...this.specificBillValidationSchema ...this.specificBillValidationSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.getBill.bind(this)), asyncMiddleware(this.getBill.bind(this)),
this.handleServiceError,
);
router.get(
'/', [
...this.billsListingValidationSchema,
],
this.validationResult,
asyncMiddleware(this.billsList.bind(this)),
this.handleServiceError,
this.dynamicListService.handlerErrorsToResponse,
); );
// router.get(
// '/:id',
// [...this.specificBillValidationSchema],
// this.validationResult,
// asyncMiddleware(this.getBill.bind(this)),
// this.handleServiceError,
// );
// router.get(
// '/',
// [...this.billsListingValidationSchema],
// this.validationResult,
// asyncMiddleware(this.listingBills.bind(this)),
// this.handleServiceError,
// );
router.delete( router.delete(
'/:id', '/:id', [
[...this.specificBillValidationSchema], ...this.specificBillValidationSchema
],
this.validationResult, this.validationResult,
asyncMiddleware(this.deleteBill.bind(this)), asyncMiddleware(this.deleteBill.bind(this)),
this.handleServiceError, this.handleServiceError,
@@ -221,8 +221,30 @@ export default class BillsController extends BaseController {
* @param {Response} res - * @param {Response} res -
* @return {Response} * @return {Response}
*/ */
async billsList(req: Request, res: Response) { public async billsList(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const filter = {
page: 1,
pageSize: 12,
filterRoles: [],
sortOrder: 'asc',
columnSortBy: 'created_at',
...this.matchedQueryData(req),
};
if (filter.stringifiedFilterRoles) {
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
}
try {
const { bills, pagination, filterMeta } = await this.billsService.getBills(tenantId, filter);
return res.status(200).send({
bills,
pagination: this.transfromToResponse(pagination),
filter_meta: this.transfromToResponse(filterMeta),
});
} catch (error) {
next(error);
}
} }
/** /**

View File

@@ -6,6 +6,7 @@ import asyncMiddleware from 'api/middleware/asyncMiddleware';
import { ServiceError } from 'exceptions'; import { ServiceError } from 'exceptions';
import BaseController from 'api/controllers/BaseController'; import BaseController from 'api/controllers/BaseController';
import BillPaymentsService from 'services/Purchases/BillPayments'; import BillPaymentsService from 'services/Purchases/BillPayments';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import AccountsService from 'services/Accounts/AccountsService'; import AccountsService from 'services/Accounts/AccountsService';
/** /**
@@ -20,6 +21,9 @@ export default class BillsPayments extends BaseController {
@Inject() @Inject()
accountsService: AccountsService; accountsService: AccountsService;
@Inject()
dynamicListService: DynamicListingService;
/** /**
* Router constructor. * Router constructor.
*/ */
@@ -48,16 +52,19 @@ export default class BillsPayments extends BaseController {
asyncMiddleware(this.deleteBillPayment.bind(this)), asyncMiddleware(this.deleteBillPayment.bind(this)),
this.handleServiceError, this.handleServiceError,
); );
// router.get('/:id', router.get('/:id',
// this.specificBillPaymentValidateSchema, this.specificBillPaymentValidateSchema,
// this.validationResult, this.validationResult,
// asyncMiddleware(this.getBillPayment.bind(this)), asyncMiddleware(this.getBillPayment.bind(this)),
// ); this.handleServiceError,
// router.get('/', );
// this.listingValidationSchema, router.get('/',
// this.validationResult, this.listingValidationSchema,
// asyncMiddleware(this.getBillsPayments.bind(this)) this.validationResult,
// ); asyncMiddleware(this.getBillsPayments.bind(this)),
this.handleServiceError,
this.dynamicListService.handlerErrorsToResponse,
);
return router; return router;
} }
@@ -183,10 +190,9 @@ export default class BillsPayments extends BaseController {
const { tenantId } = req; const { tenantId } = req;
const { id: billPaymentId } = req.params; const { id: billPaymentId } = req.params;
const billPayment = await this.billPaymentService const billPayment = await this.billPaymentService.getBillPayment(tenantId, billPaymentId);
.getBillPaymentWithMetadata(tenantId, billPaymentId);
return res.status(200).send({ bill_payment: { ...billPayment } }); return res.status(200).send({ bill_payment: billPayment });
} }
/** /**
@@ -196,12 +202,18 @@ export default class BillsPayments extends BaseController {
* @return {Response} * @return {Response}
*/ */
async getBillsPayments(req: Request, res: Response, next: NextFunction) { async getBillsPayments(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req.params; const { tenantId } = req;
const billPaymentsFilter = this.matchedQueryData(req); const billPaymentsFilter = {
page: 1,
pageSize: 12,
filterRoles: [],
sortOrder: 'asc',
columnSortBy: 'created_at',
...this.matchedQueryData(req),
};
try { try {
const { billPayments, pagination, filterMeta } = await this.billPaymentService const { billPayments, pagination, filterMeta } = await this.billPaymentService.listBillPayments(tenantId, billPaymentsFilter);
.listBillPayments(tenantId, billPaymentsFilter);
return res.status(200).send({ return res.status(200).send({
bill_payments: billPayments, bill_payments: billPayments,
@@ -273,7 +285,6 @@ export default class BillsPayments extends BaseController {
}) })
} }
} }
console.log(error);
next(error); next(error);
} }
} }

View File

@@ -42,3 +42,7 @@ export interface IBill {
entries: IItemEntry[], entries: IItemEntry[],
}; };
export interface IBillsFilter {
page: number,
pageSize: number,
}

View File

@@ -17,6 +17,10 @@ export default class Bill extends TenantModel {
return 'bills'; return 'bills';
} }
static get resourceable() {
return true;
}
/** /**
* Timestamps columns. * Timestamps columns.
*/ */
@@ -48,7 +52,7 @@ export default class Bill extends TenantModel {
to: 'contacts.id', to: 'contacts.id',
}, },
filter(query) { filter(query) {
query.where('contact_type', 'Vendor'); query.where('contact_service', 'vendor');
} }
}, },
@@ -97,4 +101,14 @@ export default class Bill extends TenantModel {
.where('id', billId) .where('id', billId)
[changeMethod]('payment_amount', Math.abs(amount)); [changeMethod]('payment_amount', Math.abs(amount));
} }
static get fields() {
return {
created_at: {
label: 'Created at',
column: 'created_at',
columnType: 'date',
},
}
}
} }

View File

@@ -16,6 +16,10 @@ export default class BillPayment extends TenantModel {
return ['createdAt', 'updatedAt']; return ['createdAt', 'updatedAt'];
} }
static get resourceable() {
return true;
}
/** /**
* Relationship mapping. * Relationship mapping.
*/ */
@@ -43,7 +47,7 @@ export default class BillPayment extends TenantModel {
to: 'contacts.id', to: 'contacts.id',
}, },
filter(query) { filter(query) {
query.where('contact_type', 'Vendor'); query.where('contact_service', 'vendor');
} }
}, },
@@ -69,4 +73,15 @@ export default class BillPayment extends TenantModel {
} }
}; };
} }
static get fields() {
return {
created_at: {
label: 'Created at',
column: 'created_at',
columnType: 'date',
},
}
}
} }

View File

@@ -423,7 +423,7 @@ export default class BillPaymentsService {
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, BillPayment, billPaymentsFilter); const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, BillPayment, billPaymentsFilter);
this.logger.info('[bill_payment] try to get bill payments list.', { tenantId }); this.logger.info('[bill_payment] try to get bill payments list.', { tenantId });
const { results, pagination } = await BillPayment.query().onBuild(builder => { const { results, pagination } = await BillPayment.query().onBuild((builder) => {
builder.withGraphFetched('vendor'); builder.withGraphFetched('vendor');
builder.withGraphFetched('paymentAccount'); builder.withGraphFetched('paymentAccount');
dynamicFilter.buildQuery()(builder); dynamicFilter.buildQuery()(builder);
@@ -444,15 +444,17 @@ export default class BillPaymentsService {
* @param {number} billPaymentId - The bill payment id. * @param {number} billPaymentId - The bill payment id.
* @return {object} * @return {object}
*/ */
async getBillPaymentWithMetadata(tenantId: number, billPaymentId: number) { public async getBillPayment(tenantId: number, billPaymentId: number) {
const { BillPayment } = this.tenancy.models(tenantId); const { BillPayment } = this.tenancy.models(tenantId);
const billPayment = await BillPayment.query() const billPayment = await BillPayment.query()
.where('id', billPaymentId) .findById(billPaymentId)
.withGraphFetched('entries') .withGraphFetched('entries')
.withGraphFetched('vendor') .withGraphFetched('vendor')
.withGraphFetched('paymentAccount') .withGraphFetched('paymentAccount');
.first();
if (!billPayment) {
throw new ServiceError(ERRORS.PAYMENT_MADE_NOT_FOUND);
}
return billPayment; return billPayment;
} }
} }

View File

@@ -12,6 +12,7 @@ import AccountsService from 'services/Accounts/AccountsService';
import InventoryService from 'services/Inventory/Inventory'; import InventoryService from 'services/Inventory/Inventory';
import SalesInvoicesCost from 'services/Sales/SalesInvoicesCost'; import SalesInvoicesCost from 'services/Sales/SalesInvoicesCost';
import TenancyService from 'services/Tenancy/TenancyService'; import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { formatDateFields } from 'utils'; import { formatDateFields } from 'utils';
import { import {
IBillDTO, IBillDTO,
@@ -21,6 +22,9 @@ import {
IItemEntry, IItemEntry,
IItemEntryDTO, IItemEntryDTO,
IBillEditDTO, IBillEditDTO,
IPaginationMeta,
IFilterMeta,
IBillsFilter,
} from 'interfaces'; } from 'interfaces';
import { ServiceError } from 'exceptions'; import { ServiceError } from 'exceptions';
import ItemsService from 'services/Items/ItemsService'; import ItemsService from 'services/Items/ItemsService';
@@ -59,6 +63,9 @@ export default class BillsService extends SalesInvoicesCost {
@Inject('logger') @Inject('logger')
logger: any; logger: any;
@Inject()
dynamicListService: DynamicListingService;
/** /**
* Validates whether the vendor is exist. * Validates whether the vendor is exist.
* @async * @async
@@ -423,6 +430,30 @@ export default class BillsService extends SalesInvoicesCost {
]); ]);
} }
/**
* Retrieve bills data table list.
* @param {number} tenantId -
* @param {IBillsFilter} billsFilter -
*/
public async getBills(
tenantId: number,
billsFilter: IBillsFilter,
): Promise<{ bills: IBill, pagination: IPaginationMeta, filterMeta: IFilterMeta }> {
const { Bill } = this.tenancy.models(tenantId);
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, Bill, billsFilter);
this.logger.info('[bills] trying to get bills data table.', { tenantId, billsFilter });
const { results, pagination } = await Bill.query().onBuild((builder) => {
builder.withGraphFetched('vendor');
dynamicFilter.buildQuery()(builder);
}).pagination(billsFilter.page - 1, billsFilter.pageSize);
return {
bills: results,
pagination,
filterMeta: dynamicFilter.getResponseMeta(),
};
}
/** /**
* Retrieve the given bill details with associated items entries. * Retrieve the given bill details with associated items entries.