<commit_before>var mongoose = require('mongoose');
var schema = require('./schema');
var url = require('url');
var _ = require('lodash');

var Patient = mongoose.model('Patient', schema.patientSchema);

function addReference(patient, success, failure) {
    //generate a 6 digit number and check that it hasn't been used in that hospital before.
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    var length = 6;
    var reference = patient.hospital.substr(0, 4).toUpperCase() + '-';
    for (var i = length; i > 0; --i) {
        reference += chars[Math.round(Math.random() * (chars.length - 1))];
    }
    var filter = {
        reference: new RegExp(reference, 'i'),
        hospital: patient.hospital
    };

    Patient.find(filter, function (err, patients) {
        if (err) {
            failure();
        }
        if (patients.length > 0) {
            addReference(patient, success, failure);
        } else {
            patient.reference = reference;
            success();
        }
    });
}

function updateOrInsertPatient(id, patient, response) {
    Patient.findByIdAndUpdate(id, patient, {upsert: true}, function (err, savedPatient) {
        if (err) {
            console.log(err);
        }
        response.json(savedPatient);
    });
}

module.exports = {
    search: function (request, response) {
        var query = request.query.query;
        var filter = {
            $or: [
                {reference: new RegExp(query, 'i')},
                {firstName: new RegExp(query, 'i')},
                {lastName: new RegExp(query, 'i')}
            ]
        };
        filter.hospital = request.hospital;
        Patient.find(filter)
        .sort('-referral.referralDate')
        .limit(20)
        .exec(function (err, patients) {
            if (err) {
                console.log(err);
            }
            response.json(patients);
        });
    },

    // add a parameter to say whether to return the whole set, the top n, or just the count.
    // maybe do the whole list by default, add a parameter now for count, and do n constraint later.
    list: function (request, response) {
        var query = url.parse(request.url, true).query;
        var filter = JSON.parse(unescape(query.filter));

        var hospitalFilter = {hospital: request.hospital};

        if (query.range && query.rangeField) {
            var rangeParam = JSON.parse(query.range);
            var range = {};
            range[query.rangeField] = {"$gte": new Date(rangeParam.startDate), "$lt": new Date(rangeParam.endDate)};
            if (filter.$and) {
                filter.$and.push(range);
                filter.$and.push(hospitalFilter);
            } else {
                filter = {"$and": [filter, range, hospitalFilter]};
            }
        }
        console.log(JSON.stringify(filter));

        Patient.find(filter, function (err, patients) {
            if (err) {
                console.log(err);
            }
            if (query.countOnly) {
                response.json(patients.length);
            } else {
                response.json(patients);
            }
        });
    },<commit_msg>Filter patients by hospital even if no query range is specified<commit_after>var mongoose = require('mongoose');
var schema = require('./schema');
var url = require('url');
var _ = require('lodash');

var Patient = mongoose.model('Patient', schema.patientSchema);

function addReference(patient, success, failure) {
    //generate a 6 digit number and check that it hasn't been used in that hospital before.
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    var length = 6;
    var reference = patient.hospital.substr(0, 4).toUpperCase() + '-';
    for (var i = length; i > 0; --i) {
        reference += chars[Math.round(Math.random() * (chars.length - 1))];
    }
    var filter = {
        reference: new RegExp(reference, 'i'),
        hospital: patient.hospital
    };

    Patient.find(filter, function (err, patients) {
        if (err) {
            failure();
        }
        if (patients.length > 0) {
            addReference(patient, success, failure);
        } else {
            patient.reference = reference;
            success();
        }
    });
}

function updateOrInsertPatient(id, patient, response) {
    Patient.findByIdAndUpdate(id, patient, {upsert: true}, function (err, savedPatient) {
        if (err) {
            console.log(err);
        }
        response.json(savedPatient);
    });
}

module.exports = {
    search: function (request, response) {
        var query = request.query.query;
        var filter = {
            $or: [
                {reference: new RegExp(query, 'i')},
                {firstName: new RegExp(query, 'i')},
                {lastName: new RegExp(query, 'i')}
            ]
        };
        filter.hospital = request.hospital;
        Patient.find(filter)
        .sort('-referral.referralDate')
        .limit(20)
        .exec(function (err, patients) {
            if (err) {
                console.log(err);
            }
            response.json(patients);
        });
    },

    // add a parameter to say whether to return the whole set, the top n, or just the count.
    // maybe do the whole list by default, add a parameter now for count, and do n constraint later.
    list: function (request, response) {
        var query = url.parse(request.url, true).query;
        var filter = JSON.parse(unescape(query.filter));

        var hospitalFilter = {hospital: request.hospital};

        if (query.range && query.rangeField) {
            var rangeParam = JSON.parse(query.range);
            var range = {};
            range[query.rangeField] = {"$gte": new Date(rangeParam.startDate), "$lt": new Date(rangeParam.endDate)};
            if (filter.$and) {
                filter.$and.push(range);
                filter.$and.push(hospitalFilter);
            } else {
                filter = {"$and": [filter, range, hospitalFilter]};
            }
        } else {
            filter = {"$and": [filter, hospitalFilter]};
        }
        console.log(JSON.stringify(filter));

        Patient.find(filter, function (err, patients) {
            if (err) {
                console.log(err);
            }
            if (query.countOnly) {
                response.json(patients.length);
            } else {
                response.json(patients);
            }
        });
    },
{'fraction_non_alphanumeric': 0.1308338518979465, 'fraction_numerical': 0.005911636589919104, 'mean_word_length': 1.9077340569877883, 'pattern_counts': {'":': 7, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '639021', 'n_tokens_mistral': 1869, 'n_tokens_neox': 1768, 'n_words': 455}