'use strict'; const Client = require('../model/client'), ObjectId = require('mongodb').ObjectId, userCtl = require('../controllers/user'), cache = require('../helpers/mem_cache'), utils = require('../helpers/utils'), { Errors } = require('../helpers/constants'), { AppError, AppParamError } = require('../helpers/app_error'); async function createClient_post(req, res) { const _client = req.body; delete _client._id; await userCtl.ensureParentExists(_client); delete _client.kind; const newClient = new Client(_client); const client = await newClient.save(); res.json(client); } async function getClient_get(req, res) { const cId = req.params.client_id; if (!ObjectId.isValid(cId)) AppError.throw(Errors.INVALID_PARAM); const client = await Client.findOne({ _id: ObjectId(cId) }, null, { lean: true }); res.json(client); } async function updateClient_put(req, res) { if (!utils.isObjectId(req.body['_id'])) AppError.throw(Errors.INVALID_PARAM); const _client = req.body; if (utils.isBlank(_client.username) && !utils.isBlank(_client.password)) _client.password = undefined; if (!_client.hasOwnProperty('active')) _client.active = true; const client = await Client.findOneAndUpdate({ _id: ObjectId(_client._id) }, _client, { runValidators: true, new: true, lean: true }); res.json(client); } async function deleteClient(req, res) { const _id = req.params.client_id; if (!utils.isObjectId(_id)) AppError.throw(Errors.INVALID_PARAM); const client = await Client.findById(ObjectId(_id)); if (client) { await client.removeFull(); } cache.delete(_id); res.json(client); } async function search_post(req, res) { if (!utils.isObjectId(req.body.byPuid)) AppParamError.throw(Errors.INVALID_PUID); const clients = await Client.find({ parent: ObjectId(req.body.byPuid), markedDelete: { $ne: true } }, '-password', { lean: true }); res.json(clients); } async function searchWithSetting_post(req, res) { /* params { byPuid: , excludeIds:[] (Optional - excluded Client Ids) } */ const input = req.body; if (!utils.isObjectId(input.byPuid)) AppParamError.throw(Errors.INVALID_PUID); if (!utils.isEmptyArray(input.excludeIds) && input.excludeIds.some(id => !utils.isObjectId(id))) AppParamError.throw(); const clients = await Client.aggregate([ { $match: { markedDelete: { $ne: true }, parent: ObjectId(input.byPuid), ...(!utils.isEmptyArray(input.excludeIds) && { _id: { $nin: input.excludeIds.map(id => ObjectId(id)) } }) } }, { $lookup: { from: 'invoice_settings', localField: '_id', foreignField: 'userId', as: 'invoiceSettings' } }, { $unset: ['password'] }, { $unwind: { path: '$invoiceSettings', preserveNullAndEmptyArrays: true } } ]); res.json(clients); } module.exports = { createClient_post, getClient_get, updateClient_put, deleteClient, search_post, searchWithSetting_post, };