'use strict'; const { AppError } = require('../helpers/app_error'), { Errors } = 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) { return getPuidBase(req, isObject); } 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, };