67 lines
2.3 KiB
JavaScript
67 lines
2.3 KiB
JavaScript
'use strict';
|
|
|
|
const { AppError } = require('../helpers/app_error'),
|
|
{ Errors, UserTypes } = require('../helpers/constants'),
|
|
{ Job, CostingItem } = require('../model'),
|
|
{ isNil } = require('lodash'),
|
|
{ getPuid: getPuidBase, checkUserClient } = require('../helpers/user_helper'),
|
|
utils = require('../helpers/utils');
|
|
|
|
function getPuid(req, isObject) {
|
|
const roles = [UserTypes.APP_ADM, UserTypes.CLIENT, UserTypes.OFFICER, UserTypes.PILOT];
|
|
return getPuidBase(req, isObject, roles);
|
|
}
|
|
|
|
async function getCostingItems_get(req, res) {
|
|
const costingItems = await CostingItem.find(getPuid(req));
|
|
res.json(costingItems);
|
|
}
|
|
|
|
async function createCostingItem_post(req, res) {
|
|
const itemObj = req.body;
|
|
itemObj.price = utils.toFixedNumber(itemObj.price);
|
|
|
|
const newSetting = new CostingItem({ ...itemObj, ...getPuid(req), createdBy: req.uid, updatedBy: req.uid });
|
|
const costingItem = await newSetting.save();
|
|
res.json(costingItem);
|
|
}
|
|
|
|
async function getCostingItemDetail_get(req, res) {
|
|
const costingItem = await CostingItem.findOne({ _id: req.params.costingItemId, ...getPuid(req) });
|
|
if (!costingItem) AppError.throw(Errors.COSTING_ITEM_NOT_FOUND);
|
|
|
|
res.json(costingItem);
|
|
}
|
|
|
|
async function updateCostingItem_put(req, res) {
|
|
const input = req.body;
|
|
|
|
if (input.userId) await checkUserClient(input.userId, req);
|
|
if (!isNil(input.price)) input.price = utils.toFixedNumber(input.price);
|
|
|
|
const costingItem = await CostingItem.findOne({ _id: req.params.costingItemId, ...getPuid(req) });
|
|
if (!costingItem) AppError.throw(Errors.COSTING_ITEM_NOT_FOUND);
|
|
|
|
for (const [key, value] of Object.entries(req.body)) {
|
|
if (!isNil(value)) costingItem[key] = value;
|
|
}
|
|
costingItem.updatedBy = req.uid;
|
|
await costingItem.save();
|
|
res.json(costingItem);
|
|
}
|
|
|
|
async function deleteCostingItem(req, res) {
|
|
const costingItem = await CostingItem.findOne({ _id: req.params.costingItemId, ...getPuid(req) });
|
|
if (costingItem) {
|
|
const jobUseTheItem = await Job.findOne({ 'costings.items': { $elemMatch: { item: costingItem._id } } });
|
|
if (!!jobUseTheItem) AppError.throw(Errors.COSTING_ITEM_IN_USE);
|
|
|
|
await CostingItem.deleteOne({ _id: req.params.costingItemId });
|
|
}
|
|
res.json({ ok: true });
|
|
}
|
|
|
|
module.exports = {
|
|
getCostingItems_get, createCostingItem_post, getCostingItemDetail_get, updateCostingItem_put, deleteCostingItem,
|
|
};
|