sample number generation
This commit is contained in:
@ -36,9 +36,6 @@ router.put('/sample/' + IdValidate.parameter(), (req, res, next) => {
|
||||
// only maintain and admin are allowed to edit other user's data
|
||||
if (sampleData.user_id.toString() !== req.authDetails.id && !req.auth(res, ['maintain', 'admin'], 'basic')) return;
|
||||
|
||||
if (sample.hasOwnProperty('number') && sample.number !== sampleData.number) {
|
||||
if (!await numberCheck(sample, res, next)) return;
|
||||
}
|
||||
if (sample.hasOwnProperty('material_id')) {
|
||||
if (!await materialCheck(sample, res, next)) return;
|
||||
}
|
||||
@ -120,7 +117,6 @@ router.post('/sample/new', async (req, res, next) => {
|
||||
const {error, value: sample} = SampleValidate.input(req.body, 'new');
|
||||
if (error) return res400(error, res);
|
||||
|
||||
if (!await numberCheck(sample, res, next)) return;
|
||||
if (!await materialCheck(sample, res, next)) return;
|
||||
if (!await sampleRefCheck(sample, res, next)) return;
|
||||
|
||||
@ -129,6 +125,8 @@ router.post('/sample/new', async (req, res, next) => {
|
||||
}
|
||||
|
||||
sample.status = 0;
|
||||
sample.number = await numberGenerate(sample, req, res, next);
|
||||
if (!sample.number) return;
|
||||
new NoteModel(sample.notes).save((err, data) => {
|
||||
if (err) return next(err);
|
||||
delete sample.notes;
|
||||
@ -155,17 +153,18 @@ router.get('/sample/notes/fields', (req, res, next) => {
|
||||
module.exports = router;
|
||||
|
||||
|
||||
async function numberCheck (sample, res, next) { // validate number, returns false if invalid
|
||||
const sampleData = await SampleModel.findOne({number: sample.number}).lean().exec().catch(err => {next(err); return false;});
|
||||
if (sampleData) { // found entry with sample number
|
||||
res.status(400).json({status: 'Sample number already taken'});
|
||||
return false
|
||||
}
|
||||
return true;
|
||||
async function numberGenerate (sample, req, res, next) { // validate number, returns false if invalid
|
||||
const sampleData = await SampleModel
|
||||
.find({number: new RegExp('^' + req.authDetails.location + '[0-9]+$', 'm')})
|
||||
.lean()
|
||||
.exec()
|
||||
.catch(err => next(err));
|
||||
if (sampleData instanceof Error) return false;
|
||||
return req.authDetails.location + (sampleData.length > 0 ? Number(sampleData[0].number.replace(/[^0-9]+/g, '')) + 1 : 1);
|
||||
}
|
||||
|
||||
async function materialCheck (sample, res, next, id = sample.material_id) { // validate material_id and color, returns false if invalid
|
||||
const materialData = await MaterialModel.findById(id).lean().exec().catch(err => {next(err); return false;}) as any;
|
||||
const materialData = await MaterialModel.findById(id).lean().exec().catch(err => next(err)) as any;
|
||||
if (materialData instanceof Error) return false;
|
||||
if (!materialData) { // could not find material_id
|
||||
res.status(400).json({status: 'Material not available'});
|
||||
|
Reference in New Issue
Block a user