<commit_before>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

var tags = require('_pr/model/tags/tags.js');
var unassignedInstances = require('_pr/model/unassigned-instances/');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider');
var logger = require('_pr/logger')(module);

const errorType = 'provider';

var providerService = module.exports = {};

providerService.checkIfProviderExists = function checkIfProviderExists(providerId, callback) {
    AWSProvider.getAWSProviderById(providerId, function(err, provider) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!provider) {
            var err = new Error('Provider not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, provider);
        }
    });
};

providerService.getTagsByProvider = function getTagsByProvider(provider, callback) {
    tags.getTagsByProviderId(provider._id, function(err, tags) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            callback(err);
        } else {
            return callback(null, tags);
        }
    });
};

providerService.getTagByNameAndProvider = function getTagByNameAndProvider(providerId, tagName, callback) {
    var params = {
        'providerId': providerId,
        'name': tagName
    };
    tags.getTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            return callback(null, tag);
        }
    });
};

providerService.getTagByCatalystEntityTypeAndProvider
    = function getTagByCatalystEntityTypeAndProvider(providerId, catalystEntityType, callback) {
    // @TODO entity types to be moved to config
    if((catalystEntityType != 'project') && (catalystEntityType != 'environment')) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var params = {
        'providerId': providerId,
        'catalystEntityType': catalystEntityType
    };
    tags.getTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            return callback(null, tag);
        }
    });
};

providerService.getUnassignedInstancesByProvider
    = function getUnassignedInstancesByProvider(provider, callback) {
    unassignedInstances.getByProviderId(provider._id, function(err, assignedInstances) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!assignedInstances) {
            return callback(null, []);
        }else {
            return callback(null, assignedInstances);
        }
    });
};

providerService.updateTag = function updateTag(provider, tagDetails, callback) {
    if(!('name' in tagDetails) || !('description' in tagDetails)) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var params = {
        'providerId': provider._id,
        'name': tagDetails.name
    };
    var fields = {
        'description': tagDetails.description
    };

    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            var tag = {
                'name': tagDetails.name,
                'description': tagDetails.description
            }
            return callback(null, tag);
        }
    });
};

// @TODO CatalystEntityMapping and values update to be implemented
// @TODO Handle asynchronous updates to guarantee correctness
// @TODO Update conflict based on tag names should be handled
providerService.addMultipleTagMappings = function addMultipleTagMappings(providerId, tagMappings, callback) {
    if(tagMappings.length < 1) {
        return callback(null, []);
    }
    logger.debug(tagMappings.length);
    var tagNames = [];
    for(var i = 0; i < tagMappings.length; i++) {
        if(!('tagName' in tagMappings[i]) || !('catalystEntityType' in tagMappings[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        // @TODO entity types to be moved to config
        if((tagMappings[i].catalystEntityType != 'project')
            && (tagMappings[i].catalystEntityType != 'environment')) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        tagNames.push(tagMappings[i].tagName);
        var params = {
            'providerId': providerId,
            'name': tagMappings[i].tagName
        };
        var fields = {
            'catalystEntityType': tagMappings[i].catalystEntityType
        };
        tags.updateTag(params, fields, function(err, tag) {
            if(err) {
                var err = new Error('Internal server error');
                err.status = 500;
                return callback(err);
            } else if(!tag) {
                var err = new Error('Tag not found');
                err.status = 404;
                return callback(err);
            }
        });
    }

    if(tagNames.length > 0) {
        return tags.getTagsByNames(tagNames, callback);
    } else {
        return callback(null, []);
    }
};

providerService.updateTagMapping = function updateTagMapping(tagDetails, tagMapping, callback) {
    if(!('tagName' in tagMapping) && !('catalystEntityMapping' in tagMapping)) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }
    if(!('values' in tagDetails)) {
        var err = new Error('Invalid Request');
        err.status = 400;
        return callback(err);
    }

    var catalystEntityMappingList = [];
    for(var i = 0; i < tagMapping.catalystEntityMapping.length; i++) {
        if(!('tagValue' in tagMapping.catalystEntityMapping[i])
            || !('catalystEntityId' in tagMapping.catalystEntityMapping[i])
            || !('catalystEntityName' in tagMapping.catalystEntityMapping[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        if(tagDetails.values.indexOf(tagMapping.catalystEntityMapping[i].tagValue) < 0) {
            var err = new Error('Tag value not found');
            err.status = 404;
            return callback(err);
        }

        catalystEntityMappingList.push({
            'tagValue': tagMapping.catalystEntityMapping[i].tagValue,
            'catalystEntityId': tagMapping.catalystEntityMapping[i].catalystEntityId,
            'catalystEntityName': tagMapping.catalystEntityMapping[i].catalystEntityName
        });
    }

    var params = {
        'providerId': tagDetails.providerId,
        'name': tagDetails.name
    };
    var fields = {
        'catalystEntityMapping': catalystEntityMappingList
    };
    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            tagDetails.catalystEntityMapping = catalystEntityMappingList;
            return callback(null, tagDetails);
        }
    });
};

providerService.updateCatalystEntityMapping
    = function updateCatalystEntityMapping(tagDetails, catalystEntityMapping, callback) {
    if(catalystEntityMapping.length == 0) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var catalystEntityMappingList = [];
    for(var i = 0; i < catalystEntityMapping.length; i++) {
        if(!('tagValue' in catalystEntityMapping[i]) || !('catalystEntityId' in catalystEntityMapping[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        if(tagDetails.values.indexOf(catalystEntityMapping[i].tagValue) < 0) {
            var err = new Error('Tag value not found');
            err.status = 404;
            return callback(err);
        }

        catalystEntityMappingList.push({
            'tagValue': catalystEntityMapping[i].tagValue,
            'catalystEntityId': catalystEntityMapping[i].catalystEntityId
        });
    }

    var params = {
        'providerId': tagDetails.providerId,
        'name': tagDetails.name
    };
    var fields = {
        'catalystEntityMapping': catalystEntityMappingList
    };
    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            tagDetails.catalystEntityMapping = catalystEntityMappingList;
            return callback(null, tagDetails);
        }
    });
};

providerService.deleteTag = function deleteTag(provider, tagName, callback) {
    var params = {
        'providerId': provider._id,
        'name': tagName
    };

    tags.deleteTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

providerService.deleteTagMapping = function deleteTagMapping(providerId, catalystEntityType, callback) {
    var params = {
        'providerId': providerId,
        'catalystEntityType': catalystEntityType
    };
    var fields = {
        'catalystEntityMapping': [],
        'catalystEntityType': null
    }

    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

providerService.createTagsList = function createTagsList(tags, callback) {
    var tagsListObject = {};
    var tagsList = [];
    tags.forEach(function(tag) {
        tagsList.push({
            'name': tag.name,
            'description': tag.description?tag.description:null
        });
    });
    tagsListObject.tags = tagsList;

    return callback(null, tagsList);
};

providerService.createTagObject = function createTagObject(tag, callback) {
    var tagObject = {
        'name': tag.name,
        'description': tag.description?tag.description:null
    };
    return callback(null, tagObject);
};

providerService.createTagMappingList = function createTagMappingList(tags, callback) {
    var tagMappingsListObject = {};
    var tagMappingsList = [];
    tags.forEach(function(tag) {
        if(tag.catalystEntityType) {
            var tagMapping = {
                'tagName': tag.name,
                'tagValues': tag.values ? tag.values : [],
                'catalystEntityType': tag.catalystEntityType ? tag.catalystEntityType : null,
                'catalystEntityMapping': tag.catalystEntityMapping ? tag.catalystEntityMapping : []
            };
            for (var i = 0; i < tagMapping.catalystEntityMapping.length; i++) {
                delete tagMapping.catalystEntityMapping[i]._id;
            }
            tagMappingsList.push(tagMapping);
        }
    });

    tagMappingsListObject.tagMappings = tagMappingsList;

    return callback(null, tagMappingsList);
};

providerService.createTagMappingObject = function createTagMappingObject(tag, callback) {
    var tagMappingObject = {
            'tagName': tag.name,
            'tagValues': tag.values?tag.values:[],
            'catalystEntityType': tag.catalystEntityType?tag.catalystEntityType:null,
            'catalystEntityMapping': tag.catalystEntityMapping?tag.catalystEntityMapping:[]
    };
    for (var i = 0; i < tagMappingObject.catalystEntityMapping.length; i++) {
        delete tagMappingObject.catalystEntityMapping[i]._id;
    }

    return callback(null, tagMappingObject);
};

providerService.createUnassignedInstancesList = function createUnassignedInstancesList(instances, callback) {
    var instancesListObject = {};
    var instancesList = [];

    instances.forEach(function(instance) {
        var tempInstance = {};
        var provider = {
            'id': instance.providerId,
            'type': instance.providerType,
            'data': instance.providerData?instance.providerData:null,
        };
        tempInstance.id = instance._id;
        tempInstance.orgId = instance.orgId;
        tempInstance.provider = provider;
        tempInstance.platformId = instance.platformId;
        tempInstance.ip = instance.ip;
        tempInstance.os = instance.os;
        tempInstance.state = instance.state;
        tempInstance.tags = instance.tags;

        instancesList.push(tempInstance);
    });

    instancesListObject.instances = instancesList;

    return callback(null, instancesListObject);
}
<commit_msg>changes to return tag values in alphabetical order<commit_after>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

var tags = require('_pr/model/tags/tags.js');
var unassignedInstances = require('_pr/model/unassigned-instances/');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider');
var logger = require('_pr/logger')(module);

const errorType = 'provider';

var providerService = module.exports = {};

providerService.checkIfProviderExists = function checkIfProviderExists(providerId, callback) {
    AWSProvider.getAWSProviderById(providerId, function(err, provider) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!provider) {
            var err = new Error('Provider not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, provider);
        }
    });
};

providerService.getTagsByProvider = function getTagsByProvider(provider, callback) {
    tags.getTagsByProviderId(provider._id, function(err, tags) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            callback(err);
        } else {
            return callback(null, tags);
        }
    });
};

providerService.getTagByNameAndProvider = function getTagByNameAndProvider(providerId, tagName, callback) {
    var params = {
        'providerId': providerId,
        'name': tagName
    };
    tags.getTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            return callback(null, tag);
        }
    });
};

providerService.getTagByCatalystEntityTypeAndProvider
    = function getTagByCatalystEntityTypeAndProvider(providerId, catalystEntityType, callback) {
    // @TODO entity types to be moved to config
    if((catalystEntityType != 'project') && (catalystEntityType != 'environment')) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var params = {
        'providerId': providerId,
        'catalystEntityType': catalystEntityType
    };
    tags.getTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            return callback(null, tag);
        }
    });
};

providerService.getUnassignedInstancesByProvider
    = function getUnassignedInstancesByProvider(provider, callback) {
    unassignedInstances.getByProviderId(provider._id, function(err, assignedInstances) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!assignedInstances) {
            return callback(null, []);
        }else {
            return callback(null, assignedInstances);
        }
    });
};

providerService.updateTag = function updateTag(provider, tagDetails, callback) {
    if(!('name' in tagDetails) || !('description' in tagDetails)) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var params = {
        'providerId': provider._id,
        'name': tagDetails.name
    };
    var fields = {
        'description': tagDetails.description
    };

    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            var tag = {
                'name': tagDetails.name,
                'description': tagDetails.description
            }
            return callback(null, tag);
        }
    });
};

// @TODO CatalystEntityMapping and values update to be implemented
// @TODO Handle asynchronous updates to guarantee correctness
// @TODO Update conflict based on tag names should be handled
providerService.addMultipleTagMappings = function addMultipleTagMappings(providerId, tagMappings, callback) {
    if(tagMappings.length < 1) {
        return callback(null, []);
    }
    logger.debug(tagMappings.length);
    var tagNames = [];
    for(var i = 0; i < tagMappings.length; i++) {
        if(!('tagName' in tagMappings[i]) || !('catalystEntityType' in tagMappings[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        // @TODO entity types to be moved to config
        if((tagMappings[i].catalystEntityType != 'project')
            && (tagMappings[i].catalystEntityType != 'environment')) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        tagNames.push(tagMappings[i].tagName);
        var params = {
            'providerId': providerId,
            'name': tagMappings[i].tagName
        };
        var fields = {
            'catalystEntityType': tagMappings[i].catalystEntityType
        };
        tags.updateTag(params, fields, function(err, tag) {
            if(err) {
                var err = new Error('Internal server error');
                err.status = 500;
                return callback(err);
            } else if(!tag) {
                var err = new Error('Tag not found');
                err.status = 404;
                return callback(err);
            }
        });
    }

    if(tagNames.length > 0) {
        return tags.getTagsByProviderIdAndNames(providerId, tagNames, callback);
    } else {
        return callback(null, []);
    }
};

providerService.updateTagMapping = function updateTagMapping(tagDetails, tagMapping, callback) {
    if(!('tagName' in tagMapping) && !('catalystEntityMapping' in tagMapping)) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }
    if(!('values' in tagDetails)) {
        var err = new Error('Invalid Request');
        err.status = 400;
        return callback(err);
    }

    var catalystEntityMappingList = [];
    for(var i = 0; i < tagMapping.catalystEntityMapping.length; i++) {
        if(!('tagValue' in tagMapping.catalystEntityMapping[i])
            || !('catalystEntityId' in tagMapping.catalystEntityMapping[i])
            || !('catalystEntityName' in tagMapping.catalystEntityMapping[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        if(tagDetails.values.indexOf(tagMapping.catalystEntityMapping[i].tagValue) < 0) {
            var err = new Error('Tag value not found');
            err.status = 404;
            return callback(err);
        }

        catalystEntityMappingList.push({
            'tagValue': tagMapping.catalystEntityMapping[i].tagValue,
            'catalystEntityId': tagMapping.catalystEntityMapping[i].catalystEntityId,
            'catalystEntityName': tagMapping.catalystEntityMapping[i].catalystEntityName
        });
    }

    var params = {
        'providerId': tagDetails.providerId,
        'name': tagDetails.name
    };
    var fields = {
        'catalystEntityMapping': catalystEntityMappingList
    };
    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            tagDetails.catalystEntityMapping = catalystEntityMappingList;
            return callback(null, tagDetails);
        }
    });
};

providerService.updateCatalystEntityMapping
    = function updateCatalystEntityMapping(tagDetails, catalystEntityMapping, callback) {
    if(catalystEntityMapping.length == 0) {
        var err = new Error('Malformed Request');
        err.status = 400;
        return callback(err);
    }

    var catalystEntityMappingList = [];
    for(var i = 0; i < catalystEntityMapping.length; i++) {
        if(!('tagValue' in catalystEntityMapping[i]) || !('catalystEntityId' in catalystEntityMapping[i])) {
            var err = new Error('Malformed Request');
            err.status = 400;
            return callback(err);
        }

        if(tagDetails.values.indexOf(catalystEntityMapping[i].tagValue) < 0) {
            var err = new Error('Tag value not found');
            err.status = 404;
            return callback(err);
        }

        catalystEntityMappingList.push({
            'tagValue': catalystEntityMapping[i].tagValue,
            'catalystEntityId': catalystEntityMapping[i].catalystEntityId
        });
    }

    var params = {
        'providerId': tagDetails.providerId,
        'name': tagDetails.name
    };
    var fields = {
        'catalystEntityMapping': catalystEntityMappingList
    };
    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        }else {
            tagDetails.catalystEntityMapping = catalystEntityMappingList;
            return callback(null, tagDetails);
        }
    });
};

providerService.deleteTag = function deleteTag(provider, tagName, callback) {
    var params = {
        'providerId': provider._id,
        'name': tagName
    };

    tags.deleteTag(params, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

providerService.deleteTagMapping = function deleteTagMapping(providerId, catalystEntityType, callback) {
    var params = {
        'providerId': providerId,
        'catalystEntityType': catalystEntityType
    };
    var fields = {
        'catalystEntityMapping': [],
        'catalystEntityType': null
    }

    tags.updateTag(params, fields, function(err, tag) {
        if(err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if(!tag) {
            var err = new Error('Tag not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

providerService.createTagsList = function createTagsList(tags, callback) {
    var tagsListObject = {};
    var tagsList = [];
    tags.forEach(function(tag) {
        tagsList.push({
            'name': tag.name,
            'description': tag.description?tag.description:null
        });
    });
    tagsListObject.tags = tagsList;

    return callback(null, tagsList);
};

providerService.createTagObject = function createTagObject(tag, callback) {
    var tagObject = {
        'name': tag.name,
        'description': tag.description?tag.description:null
    };
    return callback(null, tagObject);
};

providerService.createTagMappingList = function createTagMappingList(tags, callback) {
    var tagMappingsListObject = {};
    var tagMappingsList = [];
    tags.forEach(function(tag) {
        if(tag.catalystEntityType) {
            var tagMapping = {
                'tagName': tag.name,
                'tagValues': tag.values ? tag.values.sort(function (a, b) {
                                return a.toLowerCase().localeCompare(b.toLowerCase());
                            }) : [],
                'catalystEntityType': tag.catalystEntityType ? tag.catalystEntityType : null,
                'catalystEntityMapping': tag.catalystEntityMapping ? tag.catalystEntityMapping : []
            };
            for (var i = 0; i < tagMapping.catalystEntityMapping.length; i++) {
                delete tagMapping.catalystEntityMapping[i]._id;
            }
            tagMappingsList.push(tagMapping);
        }
    });

    tagMappingsListObject.tagMappings = tagMappingsList;

    return callback(null, tagMappingsList);
};

providerService.createTagMappingObject = function createTagMappingObject(tag, callback) {
    var tagMappingObject = {
            'tagName': tag.name,
            'tagValues': tag.values ? tag.values.sort(function (a, b) {
                            return a.toLowerCase().localeCompare(b.toLowerCase());
                        }) : [],
            'catalystEntityType': tag.catalystEntityType?tag.catalystEntityType : null,
            'catalystEntityMapping': tag.catalystEntityMapping?tag.catalystEntityMapping : []
    };
    for (var i = 0; i < tagMappingObject.catalystEntityMapping.length; i++) {
        delete tagMappingObject.catalystEntityMapping[i]._id;
    }

    return callback(null, tagMappingObject);
};

providerService.createUnassignedInstancesList = function createUnassignedInstancesList(instances, callback) {
    var instancesListObject = {};
    var instancesList = [];

    instances.forEach(function(instance) {
        var tempInstance = {};
        var provider = {
            'id': instance.providerId,
            'type': instance.providerType,
            'data': instance.providerData?instance.providerData:null,
        };
        tempInstance.id = instance._id;
        tempInstance.orgId = instance.orgId;
        tempInstance.provider = provider;
        tempInstance.platformId = instance.platformId;
        tempInstance.ip = instance.ip;
        tempInstance.os = instance.os;
        tempInstance.state = instance.state;
        tempInstance.tags = instance.tags;

        instancesList.push(tempInstance);
    });

    instancesListObject.instances = instancesList;

    return callback(null, instancesListObject);
}
<|endoftext|>


<commit_before>// this file is a subview of a user's offers that they received & inputted
// its parent is UserProfile.js

// import dependencies
import React, { PropTypes, Component }  from 'react';
import _                                from 'lodash';
import { Table, TableHeader, TableRow, TableRowColumn, TableHeaderColumn,TableBody, TableFooter, FontIcon, FlatButton, ClearFix } from 'material-ui';

import OfferVis from './OfferVis';

export default class MyOffers extends Component {
  constructor () {
    super();

    // sets the state for our table settings (material-ui)
    this.state = {
      fixedHeader: true,
      stripedRows: true,
      showRowHover: true,
      showOfferExplore: false,
      selectedOffer: []
    };

    this.selectedRow = [];
  }

  clickRemoveOffer(e) {
    e.preventDefault();
    this.props.removeApiData('/api/offer/', id)
  }

  doSelection(selection) {
    this.selectedRow = selection;
  }

  exploreOffer() {
    var offer = this.props.apiData.offers[this.selectedRow[0]];
    console.log(offer);
    this.setState({selectedOffer: offer});
    this.setState({showOfferExplore: true});
  }

  render () {
    return (

                <TableHeader>
                  <TableRow>
                    <TableHeaderColumn
                        colSpan="8"
                        style={{textAlign: 'center'}}
                    >

{'My Offers'}

                    </TableHeaderColumn>
                  </TableRow>

                  <TableRow>
                    <TableHeaderColumn>{'Offer #'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Startup Name'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Position'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Salary'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Equity'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Total Funding'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Employees'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Remove?'}</TableHeaderColumn>
                  </TableRow>
                </TableHeader>

                <TableBody
                  showRowHover={this.state.showRowHover}
                  stripedRows={this.state.stripedRows}
                >
                  {_.map(this.props.apiData.offers, function (offer) {
                    return (
                      <TableRow>
                        <TableRowColumn>{offer.id ? offer.id : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.Company.name ? offer.Company.name : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.position ? offer.position : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.salary ? offer.salary : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.equity ? offer.equity : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.total_funding ? offer.total_funding : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.employees ? offer.employees : ' - '}</TableRowColumn>

                      { /* this is not working; trying to remove list item upon clicking X */ }
                        <TableRowColumn onClick={this.clickRemoveOffer.bind(this)}>{'X'}</TableRowColumn>
                      </TableRow>
                    )
                  }.bind(this))
                  }
                </TableBody>

              <FlatButton
                  label="Explore"
                  onClick={this.exploreOffer.bind(this)}
                  primary={true}
              />

                {this.state.showOfferExplore ? <OfferVis data={this.state.selectedOffer} /> : ''}

)
  }
}

MyOffers.propTypes = {
  apiData: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object
  ]),
  removeApiData: PropTypes.func.isRequired
}
<commit_msg>minor tweaks<commit_after>// this file is a subview of a user's offers that they received & inputted
// its parent is UserProfile.js

// import dependencies
import React, { PropTypes, Component }  from 'react';
import _                                from 'lodash';
import { Table, TableHeader, TableRow, TableRowColumn, TableHeaderColumn,TableBody, TableFooter, FontIcon, FlatButton, ClearFix } from 'material-ui';

import OfferVis from './OfferVis';

export default class MyOffers extends Component {
  constructor () {
    super();

    // sets the state for our table settings (material-ui)
    this.state = {
      fixedHeader: true,
      stripedRows: true,
      showRowHover: true,
      showOfferExplore: false,
      selectedOffer: []
    };

    this.selectedRow = [];
  }

  componentWillMount(e) {
    e.preventDefault();
    this.props.removeApiData('/api/offer/', id)
  }

  doSelection(selection) {
    this.selectedRow = selection;
  }

  exploreOffer() {
    var offer = this.props.apiData.offers[this.selectedRow[0]];
    console.log(offer);
    this.setState({selectedOffer: offer});
    this.setState({showOfferExplore: true});
  }

  render () {
    return (

                <TableHeader>
                  <TableRow>
                    <TableHeaderColumn
                        colSpan="8"
                        style={{textAlign: 'center'}}
                    >

{'My Offers'}

                    </TableHeaderColumn>
                  </TableRow>

                  <TableRow>
                    <TableHeaderColumn>{'Offer #'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Startup Name'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Position'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Salary'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Equity'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Total Funding'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Employees'}</TableHeaderColumn>
                    <TableHeaderColumn>{'Remove?'}</TableHeaderColumn>
                  </TableRow>
                </TableHeader>

                <TableBody
                  showRowHover={this.state.showRowHover}
                  stripedRows={this.state.stripedRows}
                >
                  {_.map(this.props.apiData.offers, function (offer) {
                    return (
                      <TableRow>
                        <TableRowColumn>{offer.id ? offer.id : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.Company.name ? offer.Company.name : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.position ? offer.position : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.salary ? offer.salary : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.equity ? offer.equity : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.total_funding ? offer.total_funding : ' - '}</TableRowColumn>
                        <TableRowColumn>{offer.employees ? offer.employees : ' - '}</TableRowColumn>

                      { /* this is not working; trying to remove list item upon clicking X */ }
                        <TableRowColumn onClick={this.clickRemoveOffer.bind(this)}>{'X'}</TableRowColumn>
                      </TableRow>
                    )
                  }.bind(this))
                  }
                </TableBody>

              <FlatButton
                  label="Explore"
                  onClick={this.exploreOffer.bind(this)}
                  primary={true}
              />

                {this.state.showOfferExplore ? <OfferVis data={this.state.selectedOffer} /> : ''}

)
  }
}

MyOffers.propTypes = {
  apiData: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object
  ]),
  removeApiData: PropTypes.func.isRequired
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
    ObjectId = mongoose.Schema.Types.ObjectId,
    Product = require('./product');

var menuSectionSchema = new mongoose.Schema({
    title: String,
    content: [Product.schema]
})

menuSectionSchema.methods = {}
menuSectionSchema.statics = {
    getByName: function(name, isLean, next) {
        this.findOne({
            name: name
        })
            .lean(isLean)
            .exec(next)
    }
}

module.exports = mongoose.model('MenuSection', menuSectionSchema)
<commit_msg>Attach menu sections to place<commit_after>var mongoose = require('mongoose'),
    ObjectId = mongoose.Schema.Types.ObjectId,
    Place = require('./place'),
    Product = require('./product');

var menuSectionSchema = new mongoose.Schema({
    title: String,
    content: [Product.schema]
})

menuSectionSchema.methods = {
    attachToPlace: function(placeId, next) {
        var self = this

        Place.findByIdAndUpdate(placeId, {
            $push: {
                menu: self.id
            }
        }, function(err, place) {
            if (err)
                return next(err)
            return next(null, place, self)
        })
    }
}
menuSectionSchema.statics = {
    getByName: function(name, isLean, next) {
        this.findOne({
            name: name
        })
            .lean(isLean)
            .exec(next)
    }
}

module.exports = mongoose.model('MenuSection', menuSectionSchema)
<|endoftext|>


<commit_before>var connection = require('./connection.js');

// object relational mapper (ORM)

//
function connectToDB(){
    connection.connect(function(err){
        if (err) {
            console.error('error connection:', err.stack);
            return
        }
        console.log('connected to MySQL DB')
    });
}
module.exports.connectToDB = connectToDB;

var orm = {
    //form data entry queries
    Users: function(userName, emailAddress, password, userType, callback) {
        var queryString = 'INSERT INTO users (userName, emailAddress, password, userType) VALUES (?, ?, ?, ?)';
        var vals = [userName, emailAddress, password, userType];
        connection.query(queryString, vals, function(err, result) {
            if (err) return callback(false, err);
                console.log(err);
                console.log(result.insertId);
                callback(true, result.insertId);
                console.log(result);
            });
          },

    findUser: function (userName, callback){
        console.log('find user function, username is: ' + userName)
    connection.query('SELECT * FROM Users WHERE ?', {emailAddress: userName}, function(err, user){
        callback(err, user)
        })
     },

    members: function(userId, contactNum, bloodType) {
        var queryString = 'INSERT INTO members (userId, contactNum, bloodType) VALUES(?, ?, ?)';
        var vals = [userId, contactNum, bloodType];
        connection.query(queryString, vals, function(err, result){
            if(err) throw err;
            console.log(err);
            console.log(result);
        });
    },

    corporateMembers: function(userId, companyName, contactNum, donationDesc){
    var queryString = 'INSERT INTO corporateMembers (userId, companyName, contactNum, donationDesc) VALUES (?, ?, ?, ?)';
    var vals = [userId, companyName, contactNum, donationDesc];

         connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(result);
            });
        },

    //admin panel task

    AvailableTasks: function(taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip){
    var queryString = 'INSERT INTO AvailableTasks (taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
    var vals = [taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip];

            connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(err);
                console.log(result);
            });
        },

    ActiveCrisis: function(crisisName, crisisDesc){
        var queryString = 'INSERT INTO activeCrisis (crisisName, crisisDesc) VALUES (?, ?)';
        var vals = [crisisName, crisisDesc];

            connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(err);
                console.log(result);
            });
        },

    // volunteer for task
    volunteerForTask: function(taskId, volId) {

        var queryString = 'UPDATE availableTasks ';
        queryString += 'SET volsRemaining = volsRemaining - 1 ';
        queryString += 'WHERE taskID = ' + taskId + ';';

        connection.query(queryString, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

        var queryString2 = 'UPDATE members ';
        queryString2 += 'SET activeTasks = ? ';
        queryString2 += 'WHERE userID = ?;';

        taskId = taskId.toString();

        var vals = [taskId, volId];

        connection.query(queryString2, vals, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

    },

    // volunteer for task
    membTaskUpate: function(taskId, volId) {

        var queryString2 = 'UPDATE members ';
        queryString2 += 'SET activeTasks = ? ';
        queryString2 += 'WHERE userID = ?;';

        var vals = [taskId, volId];

        connection.query(queryString2, vals, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

    },

        //Profile update forms

    updateUsers: function(userName, emailAddress, password, userId) {
        connection.query('UPDATE users SET userName = ?, emailAddress = ?, password = ? WHERE userID = ?',[userName, emailAddress, password, userId], function(err, result) {
           if(err) throw err;
            console.log(result);
        });
    },

    updateMembers: function(userId, contactNum, bloodType) {
        connection.query('UPDATE members SET contactNum = ?, bloodType = ? WHERE userID = ?',[contactNum, bloodType, userId], function(err, result) {
            if(err) throw err;
            console.log(result);
        });
    },

    updateCorporate: function(companyName, contactNum, donationDesc, userId){
        connection.query('UPDATE corporateMembers SET companyName = ?, contactNum = ?, donationDesc = ? WHERE userID = ?,' [companyName, contactNum, donationDesc, userId], function(err, result) {
            if (err) throw err;
            console.log(result);
        });
    },

/*********************************************************************************************
**********************************************************************************************
****************************************  GET Requests ***************************************
**********************************************************************************************
*********************************************************************************************/

    allCorpUsers: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT corporateMembers.companyName, users.userName, users.emailAddress, corporateMembers.contactNum, corporateMembers.donationDesc ';
        queryString += 'FROM corporateMembers ';
        queryString += 'LEFT JOIN users ';
        queryString += 'ON users.userID=corporateMembers.userID ';
        queryString += 'ORDER By corporateMembers.companyName;';

        this.connectionQuery(queryString, callback);

    },

    numVolsNeeded: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsRemaining) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    numVolsWhoHaveVolunteered: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded - volsRemaining) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalNumMembers: function(callback) {

         // build the mysql query string
        var queryString = 'SELECT COUNT(*) ';
        queryString += 'FROM members;';

        this.connectionQuery(queryString, callback);

    },

    totalVolPositions: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalCompletedTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded = 0) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT COUNT(*) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    dashboardTasksList: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining ';
        queryString += 'FROM availableTasks ';
        queryString += 'ORDER BY volsRemaining DESC ';
        queryString += 'LIMIT 3;';

        this.connectionQuery(queryString, callback);

    },

    allTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT taskTitle, taskDescript, volsRemaining, taskId ';
        queryString += 'FROM availableTasks ';
        queryString += 'ORDER BY volsRemaining DESC;';

        this.connectionQuery(queryString, callback);

    },

    specificTask: function(task_id, callback) {

        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip ';
        queryString += 'FROM availableTasks ';
        queryString += 'WHERE taskId = ' + task_id + ';';

        this.connectionQuery(queryString, callback);

    },

    memberTask: function(user_id, callback) {

        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining, contactName, availabletasks.contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip ';
            queryString += 'FROM availabletasks ';
            queryString += 'LEFT JOIN members ';
            queryString += 'ON members.userID = ' + user_id + ' ';
            queryString += 'WHERE availableTasks.taskID = members.activeTasks; ';

        this.connectionQuery(queryString, callback);

    },

    memberProfile: function(user_id, callback) {

        var queryString = 'SELECT users.userType, users.userName, users.emailAddress, members.contactNum, members.bloodType ';
        queryString += 'FROM users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON users.userID = members.userID WHERE users.userId = ' + user_id + ' AND users.userType = 2 '
        queryString += 'ORDER By users.username;';

        this.connectionQuery(queryString, callback);

    },

    corpProfile: function(user_id, callback) {

        var queryString = 'SELECT users.userType, corporateMembers.companyName, users.userName, users.emailAddress, users.password, corporateMembers.contactNum, corporateMembers.donationDesc ';
        queryString += 'FROM corporateMembers ';
        queryString += 'LEFT JOIN users ';
        queryString += 'ON users.userID = corporateMembers.userID WHERE users.userID = ' + user_id + ' AND users.userType = 3 '
        queryString += 'ORDER By users.username;';

        this.connectionQuery(queryString, callback);

    },

    getNumbersBlood: function(bloodType, callback) {
        console.log(bloodType);
        // build the mysql query string
        var queryString = 'SELECT users.userID, members.contactNum ';
        queryString += 'FROM users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON users.userID = members.userID WHERE members.bloodType = ' + "'" + bloodType + "'" + ' AND users.userType = 4 '
        queryString += 'ORDER By users.userID;';
        console.log(queryString);
        this.connectionQuery(queryString, function(result){
            callback(result);
        });
        },

    getNumbers: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT users.userID, members.contactNum ';
        queryString += 'FROM users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON users.userID = members.userID WHERE users.userType = 4 '
        queryString += 'ORDER By users.userID;';

        this.connectionQuery(queryString, function(result){
            callback(result);
        });
        },

    getCrisisDetails: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT * ';
        queryString += 'FROM activeCrisis;';

        this.connectionQuery(queryString, callback);

    },

    connectionQuery: function(queryString, callback) {

        // call connection.query, pass the query string and get the callback to send to html-routes.js
        connection.query(queryString, function(err, result) {
            if (err) throw err;
            callback(result);
        }); // end connection.query()

    }

};

module.exports = orm;<commit_msg>update user<commit_after>var connection = require('./connection.js');

// object relational mapper (ORM)

//
function connectToDB(){
    connection.connect(function(err){
        if (err) {
            console.error('error connection:', err.stack);
            return
        }
        console.log('connected to MySQL DB')
    });
}
module.exports.connectToDB = connectToDB;

var orm = {
    //form data entry queries
    Users: function(userName, emailAddress, password, userType, callback) {
        var queryString = 'INSERT INTO Users (userName, emailAddress, password, userType) VALUES (?, ?, ?, ?)';
        var vals = [userName, emailAddress, password, userType];
        connection.query(queryString, vals, function(err, result) {
            if (err) return callback(false, err);
                console.log(err);
                console.log(result.insertId);
                callback(true, result.insertId);
                console.log(result);
            });
          },

    findUser: function (userName, callback){
        console.log('find user function, username is: ' + userName)
    connection.query('SELECT * FROM Users WHERE ?', {emailAddress: userName}, function(err, user){
        callback(err, user)
        })
     },

    members: function(userId, contactNum, bloodType) {
        var queryString = 'INSERT INTO members (userId, contactNum, bloodType) VALUES(?, ?, ?)';
        var vals = [userId, contactNum, bloodType];
        connection.query(queryString, vals, function(err, result){
            if(err) throw err;
            console.log(err);
            console.log(result);
        });
    },

    corporateMembers: function(userId, companyName, contactNum, donationDesc){
    var queryString = 'INSERT INTO corporateMembers (userId, companyName, contactNum, donationDesc) VALUES (?, ?, ?, ?)';
    var vals = [userId, companyName, contactNum, donationDesc];

         connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(result);
            });
        },

    //admin panel task

    AvailableTasks: function(taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip){
    var queryString = 'INSERT INTO AvailableTasks (taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
    var vals = [taskTitle, taskDescript, volsNeeded, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip];

            connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(err);
                console.log(result);
            });
        },

    ActiveCrisis: function(crisisName, crisisDesc){
        var queryString = 'INSERT INTO activeCrisis (crisisName, crisisDesc) VALUES (?, ?)';
        var vals = [crisisName, crisisDesc];

            connection.query(queryString, vals, function(err, result) {
                if (err) throw err;
                console.log(err);
                console.log(result);
            });
        },

    // volunteer for task
    volunteerForTask: function(taskId, volId) {

        var queryString = 'UPDATE availableTasks ';
        queryString += 'SET volsRemaining = volsRemaining - 1 ';
        queryString += 'WHERE taskID = ' + taskId + ';';

        connection.query(queryString, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

        var queryString2 = 'UPDATE members ';
        queryString2 += 'SET activeTasks = ? ';
        queryString2 += 'WHERE userID = ?;';

        taskId = taskId.toString();

        var vals = [taskId, volId];

        connection.query(queryString2, vals, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

    },

    // volunteer for task
    membTaskUpate: function(taskId, volId) {

        var queryString2 = 'UPDATE members ';
        queryString2 += 'SET activeTasks = ? ';
        queryString2 += 'WHERE userID = ?;';

        var vals = [taskId, volId];

        connection.query(queryString2, vals, function(err, result) {
            if (err) throw err;
            console.log(result);
        });

    },

        //Profile update forms

    updateUsers: function(userName, emailAddress, password, userId) {
        connection.query('UPDATE Users SET userName = ?, emailAddress = ?, password = ? WHERE userID = ?',[userName, emailAddress, password, userId], function(err, result) {
           if(err) throw err;
            console.log(result);
        });
    },

    updateMembers: function(userId, contactNum, bloodType) {
        connection.query('UPDATE members SET contactNum = ?, bloodType = ? WHERE userID = ?',[contactNum, bloodType, userId], function(err, result) {
            if(err) throw err;
            console.log(result);
        });
    },

    updateCorporate: function(companyName, contactNum, donationDesc, userId){
        connection.query('UPDATE corporateMembers SET companyName = ?, contactNum = ?, donationDesc = ? WHERE userID = ?,' [companyName, contactNum, donationDesc, userId], function(err, result) {
            if (err) throw err;
            console.log(result);
        });
    },

/*********************************************************************************************
**********************************************************************************************
****************************************  GET Requests ***************************************
**********************************************************************************************
*********************************************************************************************/

    allCorpUsers: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT corporateMembers.companyName, Users.userName, Users.emailAddress, corporateMembers.contactNum, corporateMembers.donationDesc ';
        queryString += 'FROM corporateMembers ';
        queryString += 'LEFT JOIN Users ';
        queryString += 'ON Users.userID=corporateMembers.userID ';
        queryString += 'ORDER By corporateMembers.companyName;';

        this.connectionQuery(queryString, callback);

    },

    numVolsNeeded: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsRemaining) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    numVolsWhoHaveVolunteered: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded - volsRemaining) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalNumMembers: function(callback) {

         // build the mysql query string
        var queryString = 'SELECT COUNT(*) ';
        queryString += 'FROM members;';

        this.connectionQuery(queryString, callback);

    },

    totalVolPositions: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalCompletedTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT SUM(volsNeeded = 0) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    totalTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT COUNT(*) ';
        queryString += 'FROM availableTasks;';

        this.connectionQuery(queryString, callback);

    },

    dashboardTasksList: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining ';
        queryString += 'FROM availableTasks ';
        queryString += 'ORDER BY volsRemaining DESC ';
        queryString += 'LIMIT 3;';

        this.connectionQuery(queryString, callback);

    },

    allTasks: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT taskTitle, taskDescript, volsRemaining, taskId ';
        queryString += 'FROM availableTasks ';
        queryString += 'ORDER BY volsRemaining DESC;';

        this.connectionQuery(queryString, callback);

    },

    specificTask: function(task_id, callback) {

        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining, contactName, contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip ';
        queryString += 'FROM availableTasks ';
        queryString += 'WHERE taskId = ' + task_id + ';';

        this.connectionQuery(queryString, callback);

    },

    memberTask: function(user_id, callback) {

        var queryString = 'SELECT taskId, taskTitle, taskDescript, volsRemaining, contactName, availabletasks.contactNum, taskAddress, taskAddress2, taskCity, taskState, taskZip ';
            queryString += 'FROM availabletasks ';
            queryString += 'LEFT JOIN members ';
            queryString += 'ON members.userID = ' + user_id + ' ';
            queryString += 'WHERE availableTasks.taskID = members.activeTasks; ';

        this.connectionQuery(queryString, callback);

    },

    memberProfile: function(user_id, callback) {

        var queryString = 'SELECT Users.userType, Users.userName, Users.emailAddress, members.contactNum, members.bloodType ';
        queryString += 'FROM Users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON Users.userID = members.userID WHERE Users.userId = ' + user_id + ' AND Users.userType = 2 '
        queryString += 'ORDER By Users.username;';

        this.connectionQuery(queryString, callback);

    },

    corpProfile: function(user_id, callback) {

        var queryString = 'SELECT Users.userType, corporateMembers.companyName, Users.userName, Users.emailAddress, Users.password, corporateMembers.contactNum, corporateMembers.donationDesc ';
        queryString += 'FROM corporateMembers ';
        queryString += 'LEFT JOIN Users ';
        queryString += 'ON Users.userID = corporateMembers.userID WHERE Users.userID = ' + user_id + ' AND Users.userType = 3 '
        queryString += 'ORDER By Users.username;';

        this.connectionQuery(queryString, callback);

    },

    getNumbersBlood: function(bloodType, callback) {
        console.log(bloodType);
        // build the mysql query string
        var queryString = 'SELECT Users.userID, members.contactNum ';
        queryString += 'FROM Users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON Users.userID = members.userID WHERE members.bloodType = ' + "'" + bloodType + "'" + ' AND Users.userType = 4 '
        queryString += 'ORDER By Users.userID;';
        console.log(queryString);
        this.connectionQuery(queryString, function(result){
            callback(result);
        });
        },

    getNumbers: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT Users.userID, members.contactNum ';
        queryString += 'FROM Users ';
        queryString += 'LEFT JOIN members ';
        queryString += 'ON Users.userID = members.userID WHERE Users.userType = 4 '
        queryString += 'ORDER By Users.userID;';

        this.connectionQuery(queryString, function(result){
            callback(result);
        });
        },

    getCrisisDetails: function(callback) {

        // build the mysql query string
        var queryString = 'SELECT * ';
        queryString += 'FROM activeCrisis;';

        this.connectionQuery(queryString, callback);

    },

    connectionQuery: function(queryString, callback) {

        // call connection.query, pass the query string and get the callback to send to html-routes.js
        connection.query(queryString, function(err, result) {
            if (err) throw err;
            callback(result);
        }); // end connection.query()

    }

};

module.exports = orm;<|endoftext|>


<commit_before>'use strict';

(function() {
    var wfmPagination = angular.module('wfm.pagination', []);
    wfmPagination.run([
		'$templateCache', function($templateCache) {
    $templateCache.put('wfm-pagination-default.tpl.html',
    '
 0">' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '
'
    );
		}]);
})();

(function () {
    var WfmPaginationCtrl = function ($scope) {
        var vm = this;
        vm.gotoPage = function (pageIndex) {
            vm.paginationOptions.pageNumber = pageIndex;
            if (vm.getDataForPageCallback !== undefined) {
                vm.getDataForPageCallback(pageIndex);
            }
        };

        vm.getVisiblePageNumbers = function (start, end) {
            var displayPageCount = 5;
            var ret = [];

            if (!start) {
                start = vm.paginationOptions.totalPages;
            }

            if (!end) {
                end = start;
                start = 1;
            }

            var leftBoundary = start;
            var rightBoundary = end;
            if (end - start >= displayPageCount) {
                var index = vm.paginationOptions.pageNumber;

                if (index < displayPageCount - 1) {
                    leftBoundary = 1;
                    rightBoundary = displayPageCount;
                } else if (end - index < 3) {
                    leftBoundary = end - displayPageCount + 1;
                    rightBoundary = end;
                } else {
                    leftBoundary = getLeftBoundary(index, displayPageCount);
                    rightBoundary = getRightBoundary(index, displayPageCount, end);
                }
            }

            for (var i = leftBoundary; i <= rightBoundary ; i++) {
                ret.push(i);
            }

            return ret;
        };

        function getLeftBoundary(index, displayPageCount) {
            return index - Math.floor(displayPageCount / 2) > 1 ? index - Math.floor(displayPageCount / 2) : 1;
        }

        function getRightBoundary(index, displayPageCount, end) {
            return index + Math.floor(displayPageCount / 2) > end ? end : index + Math.floor(displayPageCount / 2);
        }
    };
    var directive = function () {
        return {
            controller: 'WfmPaginationCtrl',
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: 'wfm-pagination-default.tpl.html',
            scope: {
                paginationOptions: '=?',
                getDataForPageCallback: '=?'
            },
            link: linkFunction
        };
    };
    angular.module('wfm.pagination')
    .directive('wfmPagination', directive)
    .controller('WfmPaginationCtrl', ['$scope', WfmPaginationCtrl]);

    function linkFunction(scope, elem, attrs, vm) {

    }
}());
<commit_msg>Add pageIndex range validation<commit_after>'use strict';

(function() {
    var wfmPagination = angular.module('wfm.pagination', []);
    wfmPagination.run([
		'$templateCache', function($templateCache) {
    $templateCache.put('wfm-pagination-default.tpl.html',
    '
 0">' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '			' +
    '				' +
    '			' +
    '
' +
    '
' +
    '
'
    );
		}]);
})();

(function () {
    var WfmPaginationCtrl = function ($scope) {
        var vm = this;
        vm.gotoPage = function (pageIndex) {
            if (pageIndex < 1 || pageIndex > vm.paginationOptions.totalPages) {
                return;
            }
            if (pageIndex === 1 && vm.paginationOptions.pageNumber === 1) {
                return;
            }
            if (pageIndex === vm.paginationOptions.totalPages && vm.paginationOptions.pageNumber === vm.paginationOptions.totalPages) {
                return;
            }
            vm.paginationOptions.pageNumber = pageIndex;
            if (vm.getDataForPageCallback !== undefined) {
                vm.getDataForPageCallback(pageIndex);
            }
        };

        vm.getVisiblePageNumbers = function (start, end) {
            var displayPageCount = 5;
            var ret = [];

            if (!start) {
                start = vm.paginationOptions.totalPages;
            }

            if (!end) {
                end = start;
                start = 1;
            }

            var leftBoundary = start;
            var rightBoundary = end;
            if (end - start >= displayPageCount) {
                var index = vm.paginationOptions.pageNumber;

                if (index < displayPageCount - 1) {
                    leftBoundary = 1;
                    rightBoundary = displayPageCount;
                } else if (end - index < 3) {
                    leftBoundary = end - displayPageCount + 1;
                    rightBoundary = end;
                } else {
                    leftBoundary = getLeftBoundary(index, displayPageCount);
                    rightBoundary = getRightBoundary(index, displayPageCount, end);
                }
            }

            for (var i = leftBoundary; i <= rightBoundary ; i++) {
                ret.push(i);
            }

            return ret;
        };

        function getLeftBoundary(index, displayPageCount) {
            return index - Math.floor(displayPageCount / 2) > 1 ? index - Math.floor(displayPageCount / 2) : 1;
        }

        function getRightBoundary(index, displayPageCount, end) {
            return index + Math.floor(displayPageCount / 2) > end ? end : index + Math.floor(displayPageCount / 2);
        }
    };
    var directive = function () {
        return {
            controller: 'WfmPaginationCtrl',
            controllerAs: 'vm',
            bindToController: true,
            templateUrl: 'wfm-pagination-default.tpl.html',
            scope: {
                paginationOptions: '=?',
                getDataForPageCallback: '=?'
            },
            link: linkFunction
        };
    };
    angular.module('wfm.pagination')
    .directive('wfmPagination', directive)
    .controller('WfmPaginationCtrl', ['$scope', WfmPaginationCtrl]);

    function linkFunction(scope, elem, attrs, vm) {

    }
}());
<|endoftext|>


<commit_before>/*jshint node: true */
'use strict';

var WebDriver = require('selenium-webdriver'),
	SeleniumServer = require('selenium-webdriver/remote').SeleniumServer,
	path = require('path'),
	ksInject = require('../inject'),
	ks = path.resolve(__dirname, '../../../../../kensington.min.js'),
	jar = path.resolve(__dirname, '../../build/selenium-server-standalone-2.41.0.jar');

module.exports = function (grunt) {
	var ksSource = grunt.file.read(ks);
	grunt.registerMultiTask('ks-selenium', function () {

		var done = this.async(),
			count = this.data.length;

		// start the selenium server
		var server = new SeleniumServer(jar, {
			port: 4444,
			args: ['-Xmx512m']
		});

		server.start();

		var driver = new WebDriver.Builder()
			.usingServer(server.address())
			.withCapabilities(WebDriver.Capabilities.firefox())
			.build();

		driver.manage().timeouts().setScriptTimeout(10000);

		this.data.forEach(function (testUrl) {
			driver.get(testUrl)
				.then(function () {
					ksInject(ksSource, driver, function () {
						driver.executeAsyncScript(function () {
							/*global document, dqre, window */
							var callback = arguments[arguments.length - 1];
							dqre.a11yCheck(document, null, function (results) {
								callback({results: results, url: window.location.href});
							});
						})
						.then(function (result) {
							grunt.file.write(result.url.replace(/[^a-z0-9]/gi, '-')
								.replace(/-{2,}/g, '-').replace(/^-|-$/g, '').toLowerCase() + '.json',
								JSON.stringify(result.results, null, '  '));

							if (!--count) {
								driver.quit();
								done(result.results.violations === 0);
							}
						});

					});
				});
		});

	});
};<commit_msg>Make it actually work<commit_after>/*jshint node: true */
'use strict';

var WebDriver = require('selenium-webdriver'),
	SeleniumServer = require('selenium-webdriver/remote').SeleniumServer,
	path = require('path'),
	ksInject = require('../inject'),
	ks = path.resolve(__dirname, '../../../../../kensington.min.js'),
	jar = path.resolve(__dirname, '../../build/selenium-server-standalone-2.41.0.jar');

module.exports = function (grunt) {
	var ksSource = grunt.file.read(ks);
	grunt.registerMultiTask('ks-selenium', function () {

		var done = this.async(),
			count = this.data.length;

		// start the selenium server
		var server = new SeleniumServer(jar, {
			port: 4444,
			args: ['-Xmx512m']
		});

		server.start();

		var driver = new WebDriver.Builder()
			.usingServer(server.address())
			.withCapabilities(WebDriver.Capabilities.firefox())
			.build();

		driver.manage().timeouts().setScriptTimeout(10000);

		this.data.forEach(function (testUrl) {
			driver.get(testUrl)
				.then(function () {
					ksInject(ksSource, driver, function () {
						driver.executeAsyncScript(function () {
							/*global document, dqre, window */
							var callback = arguments[arguments.length - 1];
							dqre.a11yCheck(document, null, function (results) {
								callback({results: results, url: window.location.href});
							});
						})
						.then(function (result) {
							grunt.file.write(result.url.replace(/[^a-z0-9]/gi, '-')
								.replace(/-{2,}/g, '-').replace(/^-|-$/g, '').toLowerCase() + '.json',
								JSON.stringify(result.results, null, '  '));

							if (!--count) {
								driver.quit();
								server.stop();
								done(result.results.violations.length === 0);
							}
						});

					});
				});
		});

	});
};<|endoftext|>


<commit_before>describe('MatrixService', function() {
    var scope, httpBackend;
    var BASE = "http://example.com";
    var PREFIX = "/_matrix/client/api/v1";
    var URL = BASE + PREFIX;
    var roomId = "!wejigf387t34:matrix.org";

    beforeEach(module('matrixService'));

    beforeEach(inject(function($rootScope, $httpBackend) {
        httpBackend = $httpBackend;
        scope = $rootScope;
    }));

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('should be able to POST /createRoom with an alias', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var alias = "flibble";
        matrixService.create(alias).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(URL + "/createRoom?access_token=foobar",
            {
                room_alias_name: alias
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to GET /initialSync', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var limit = 15;
        matrixService.initialSync(limit).then(function(response) {
            expect(response.data).toEqual([]);
        });

        httpBackend.expectGET(
            URL + "/initialSync?access_token=foobar&limit=15")
            .respond([]);
        httpBackend.flush();
    }));

    it('should be able to GET /rooms/$roomid/state', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.roomState(roomId).then(function(response) {
            expect(response.data).toEqual([]);
        });

        httpBackend.expectGET(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state?access_token=foobar")
            .respond([]);
        httpBackend.flush();
    }));

    it('should be able to POST /join', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.joinAlias(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/join/" + encodeURIComponent(roomId) +
            "?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/join', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.join(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/join?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/invite', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var inviteUserId = "@user:example.com";
        matrixService.invite(roomId, inviteUserId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/invite?access_token=foobar",
            {
                user_id: inviteUserId
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/leave', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.leave(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/leave?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/ban', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var userId = "@example:example.com";
        var reason = "Because.";
        matrixService.ban(roomId, userId, reason).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/ban?access_token=foobar",
            {
                user_id: userId,
                reason: reason
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to GET /directory/room/$alias', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var alias = "#test:example.com";
        var roomId = "!wefuhewfuiw:example.com";
        matrixService.resolveRoomAlias(alias).then(function(response) {
            expect(response.data).toEqual({
                room_id: roomId
            });
        });

        httpBackend.expectGET(
            URL + "/directory/room/" + encodeURIComponent(alias) +
                    "?access_token=foobar")
            .respond({
                room_id: roomId
            });
        httpBackend.flush();
    }));

    it('should be able to send m.room.name', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var name = "Room Name";
        matrixService.setName(roomId, name).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state/m.room.name?access_token=foobar",
            {
                name: name
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to send m.room.topic', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var topic = "A room topic can go here.";
        matrixService.setTopic(roomId, topic).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state/m.room.topic?access_token=foobar",
            {
                topic: topic
            })
            .respond({});
        httpBackend.flush();
    }));

    xit('should be able to send generic state events without a state key', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var eventType = "com.example.events.test:special@characters";
        var content = {
            testing: "1 2 3"
        };
        matrixService.sendStateEvent(roomId, eventType, content).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) + "/state/" +
            encodeURIComponent(eventType) + "?access_token=foobar",
            content)
            .respond({});
        httpBackend.flush();
    }));

    xit('should be able to send generic state events with a state key', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var eventType = "com.example.events.test:special@characters";
        var content = {
            testing: "1 2 3"
        };
        var stateKey = "version:1";
        matrixService.sendStateEvent(roomId, eventType, content, stateKey).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) + "/state/" +
            encodeURIComponent(eventType) + "/" + encodeURIComponent(stateKey)+
            "?access_token=foobar",
            content)
            .respond({});
        httpBackend.flush();
    }));
});
<commit_msg>Add more tests and a TODO.<commit_after>describe('MatrixService', function() {
    var scope, httpBackend;
    var BASE = "http://example.com";
    var PREFIX = "/_matrix/client/api/v1";
    var URL = BASE + PREFIX;
    var roomId = "!wejigf387t34:matrix.org";

    beforeEach(module('matrixService'));

    beforeEach(inject(function($rootScope, $httpBackend) {
        httpBackend = $httpBackend;
        scope = $rootScope;
    }));

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    it('should be able to POST /createRoom with an alias', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var alias = "flibble";
        matrixService.create(alias).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(URL + "/createRoom?access_token=foobar",
            {
                room_alias_name: alias
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to GET /initialSync', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var limit = 15;
        matrixService.initialSync(limit).then(function(response) {
            expect(response.data).toEqual([]);
        });

        httpBackend.expectGET(
            URL + "/initialSync?access_token=foobar&limit=15")
            .respond([]);
        httpBackend.flush();
    }));

    it('should be able to GET /rooms/$roomid/state', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.roomState(roomId).then(function(response) {
            expect(response.data).toEqual([]);
        });

        httpBackend.expectGET(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state?access_token=foobar")
            .respond([]);
        httpBackend.flush();
    }));

    it('should be able to POST /join', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.joinAlias(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/join/" + encodeURIComponent(roomId) +
            "?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/join', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.join(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/join?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/invite', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var inviteUserId = "@user:example.com";
        matrixService.invite(roomId, inviteUserId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/invite?access_token=foobar",
            {
                user_id: inviteUserId
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/leave', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        matrixService.leave(roomId).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/leave?access_token=foobar",
            {})
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to POST /rooms/$roomid/ban', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var userId = "@example:example.com";
        var reason = "Because.";
        matrixService.ban(roomId, userId, reason).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPOST(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/ban?access_token=foobar",
            {
                user_id: userId,
                reason: reason
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to GET /directory/room/$alias', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var alias = "#test:example.com";
        var roomId = "!wefuhewfuiw:example.com";
        matrixService.resolveRoomAlias(alias).then(function(response) {
            expect(response.data).toEqual({
                room_id: roomId
            });
        });

        httpBackend.expectGET(
            URL + "/directory/room/" + encodeURIComponent(alias) +
                    "?access_token=foobar")
            .respond({
                room_id: roomId
            });
        httpBackend.flush();
    }));

    it('should be able to send m.room.name', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var name = "Room Name";
        matrixService.setName(roomId, name).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state/m.room.name?access_token=foobar",
            {
                name: name
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to send m.room.topic', inject(function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var topic = "A room topic can go here.";
        matrixService.setTopic(roomId, topic).then(function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) +
            "/state/m.room.topic?access_token=foobar",
            {
                topic: topic
            })
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to send generic state events without a state key', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var eventType = "com.example.events.test";
        var content = {
            testing: "1 2 3"
        };
        matrixService.sendStateEvent(roomId, eventType, content).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) + "/state/" +
            encodeURIComponent(eventType) + "?access_token=foobar",
            content)
            .respond({});
        httpBackend.flush();
    }));

    // TODO: Skipped since the webclient is purposefully broken so as not to
    // 500 matrix.org
    xit('should be able to send generic state events with a state key', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var eventType = "com.example.events.test:special@characters";
        var content = {
            testing: "1 2 3"
        };
        var stateKey = "version:1";
        matrixService.sendStateEvent(roomId, eventType, content, stateKey).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) + "/state/" +
            encodeURIComponent(eventType) + "/" + encodeURIComponent(stateKey)+
            "?access_token=foobar",
            content)
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to PUT generic events ', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var eventType = "com.example.events.test";
        var txnId = "42";
        var content = {
            testing: "1 2 3"
        };
        matrixService.sendEvent(roomId, eventType, txnId, content).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            URL + "/rooms/" + encodeURIComponent(roomId) + "/send/" +
            encodeURIComponent(eventType) + "/" + encodeURIComponent(txnId)+
            "?access_token=foobar",
            content)
            .respond({});
        httpBackend.flush();
    }));

    it('should be able to PUT text messages ', inject(
    function(matrixService) {
        matrixService.setConfig({
            access_token: "foobar",
            homeserver: "http://example.com"
        });
        var roomId = "!fh38hfwfwef:example.com";
        var body = "ABC 123";
        matrixService.sendTextMessage(roomId, body).then(
        function(response) {
            expect(response.data).toEqual({});
        });

        httpBackend.expectPUT(
            new RegExp(URL + "/rooms/" + encodeURIComponent(roomId) +
            "/send/m.room.message/(.*)" +
            "?access_token=foobar"),
            {
                body: body,
                msgtype: "m.text"
            })
            .respond({});
        httpBackend.flush();
    }));
});
<|endoftext|>