/var/www/greso.tech/server/nsm/controllers/company/client
Edit: /var/www/greso.tech/server/nsm/controllers/company/client/create.js (1482B)
module.exports = function ({ db, logger }) {
const { NotFound, BadRequest } = require('../../../responseModels/errors')
const { isSet, isEmail, isPhone, isEmpty, minLength, isNumber } = require('../../../utils/validator.util')
return async (req, res, next) => {
logger.child({ path: req.path, request: req.query }).info()
let t1 = performance.now()
try {
// checkPermission(req, 'company_edit')
const { companyId, userId, discount } = req.body
if (!isSet(companyId) || !isSet(userId) || isEmpty(companyId) || isEmpty(userId)) {
throw new BadRequest({ lang: req.user?.languageCode })
}
const company = await db.company.findOne({ where: { id: companyId } })
const user = await db.user.findOne({ where: { id: userId } })
if (!user || !company) {
throw new NotFound({ lang: req.user?.languageCode })
}
//company.addClient(user)
const companyClient = await db.companyClients.findOne({
where: { companyId: company.id, userId: user.id }
})
if (companyClient) {
if (discount) {
companyClient.discount = parseInt(discount)
await companyClient.save()
}
} else {
await db.companyClients.create({
userId: user.id,
companyId: company.id,
discount: parseInt(discount) || 0
})
// company counters
company.countClients++
company.save()
}
const time = performance.now() - t1
return res.status(200).json({ status: 'success', time })
} catch (err) {
next(err)
}
}
}