agmission/Development/server/controllers/client.js

78 lines
2.5 KiB
JavaScript

'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 } = 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.byUserId)) AppError.throw(Errors.INVALID_PARAM);
const clients = await Client.find({ parent: ObjectId(req.body.byUserId), markedDelete: { $ne: true } }, '-password', { lean: true });
res.json(clients);
}
async function searchWithSetting_post(req, res) {
if (!utils.isObjectId(req.body.byUserId)) AppError.throw(Errors.INVALID_PARAM);
const clients = await Client.aggregate([
{ $match: { parent: ObjectId(req.body.byUserId), markedDelete: { $ne: true } } },
{ $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,
};