<commit_before>/* global Source, User, Group, SourceMetric, SourceTypes, Attribute, GroupAttribute, PrincipalInvestigator, MembershipGroup, GroupTypes*/
// Importer.js - in api/services

"use strict";

const xlsx = require('xlsx');
const _ = require('lodash');
const fs = require('fs');
const request = require('request-promise');
const moment = require('moment');

module.exports = {
    importSources,
    importPeople,
    importGroups,
    importSourceMetrics
};

async function importSources() {

    function readWorksheet(worksheet, mappingsTable, mapFn = _.identity, filterFn = _.stubTrue) {
        function readSourceRow(r) {
            const sourceData = {};
            _.forEach(mappingsTable, (col, field) => {
                const cell = col + r;
                if (!_.isUndefined(worksheet[cell]))
                    sourceData[field] = worksheet[cell]['v'];
            });
            return sourceData;
        }

        const sources = [];
        for (let r = 2; ; r++) {
            const sourceData = readSourceRow(r);
            if (_.isEmpty(sourceData))
                break;
            const mappedSourceData = mapFn(sourceData);
            if (filterFn(mappedSourceData))
                sources.push(mappedSourceData);
        }
        return sources;
    }

    const scopusSourcesFileName = 'config/init/scopus_sources.xlsx';
    let journalsAndBookSeries = [], newConferences = [], oldConferences = [];
    if (fs.existsSync(scopusSourcesFileName)) {
        const workbook = xlsx.readFile(scopusSourcesFileName);
        const sheetNameList = workbook.SheetNames;

        const journalWorksheet = workbook.Sheets[sheetNameList[0]];
        const journalMappingsTable = {
            "title": 'B',
            "scopusId": 'A',
            "issn": 'C',
            "eissn": 'D',
            "type": 'T',
            "publisher": 'Z'
        };

        const mapJournal = (s) => {
            const sourceMappingTable = {
                'Book Series': SourceTypes.BOOKSERIES,
                'Journal': SourceTypes.JOURNAL
            };
            s.type = sourceMappingTable[s.type];
            return s;
        };

        const filterJournals = (s) => s.type;

        journalsAndBookSeries = readWorksheet(journalWorksheet, journalMappingsTable, mapJournal, filterJournals);

        const newConferencesWorksheet = workbook.Sheets[sheetNameList[1]];
        const newConferencesMappingsTable = {
            "title": 'B',
            "scopusId": 'A',
            "issn": 'D'
        };
        const mapConference = s => {
            s.type = SourceTypes.CONFERENCE;
            return s;
        };
        newConferences = readWorksheet(newConferencesWorksheet, newConferencesMappingsTable, mapConference);

        const oldConferencesWorksheet = workbook.Sheets[sheetNameList[2]];
        const oldConferencesMappingsTable = newConferencesMappingsTable;
        oldConferences = readWorksheet(oldConferencesWorksheet, oldConferencesMappingsTable, mapConference);
    }

    let books = [];
    const scopusSourcesFileName2 = 'config/init/scopus_book_sources.xlsx';
    if (fs.existsSync(scopusSourcesFileName2)) {
        const workbook2 = xlsx.readFile(scopusSourcesFileName2);
        const sheetNameList2 = workbook2.SheetNames;

        const bookWorksheet = workbook2.Sheets[sheetNameList2[0]];
        const bookMappingsTable = {
            "title": 'A',
            "isbn": 'C',
            "publisher": 'D',
            "year": 'E'
        };

        const mapBook = (s) => {
            s.type = 'book';
            return s;
        };

        books = readWorksheet(bookWorksheet, bookMappingsTable, mapBook);
    }

    const sources = _.union(journalsAndBookSeries, newConferences, oldConferences, books);

    sails.log.info('Inserting ' + sources.length + ' new sources');
    await Source.create(sources);
}

async function importPeople() {
    function userShouldBeUpdated(user, values) {
        const userFieldsToUpdate = [
            'jobTitle',
            'name',
            'surname'
        ];
        const toUpdate = userFieldsToUpdate.some(f => values[f] !== user[f]);
        return toUpdate;
    }

    const usersCreationCondition = sails.config.scientilla.mainInstituteImport.usersCreationCondition;
    const groupInsertionEnabled = false;
    sails.log.info('Import started');
    const url = sails.config.scientilla.mainInstituteImport.userImportUrl;
    const reqOptions = {
        uri: url,
        json: true
    };

    let people;
    try {
        people = await request(reqOptions);
    } catch (e) {
        sails.log.debug('importPeople');
        sails.log.debug(e);
    }
    sails.log.info(people.length + ' entries found');
    const importTime = moment.utc().format();
    let numUsersInserted = 0, numUsersUpdated = 0, numGroupsInserted = 0;
    for (let [i, p] of people.entries()) {
        //groups are loaded in memory because waterline doesn't allow case-insensitive queries with postegres
        p.username = _.toLower(p.username);
        const allGroups = await Group.find();
        const groupsToBeInserted = p.groups.filter(g => !allGroups.some(g2 => _.toLower(g2.name) == _.toLower(g)));
        const groupsToSearch = allGroups.filter(g => p.groups.some(g2 => _.toLower(g2) == _.toLower(g.name))).map(g => g.name);
        if (groupInsertionEnabled && groupsToBeInserted.length) {
            const groupObjs = groupsToBeInserted.map(g => ({name: g}));
            sails.log.info('inserting groups: ' + groupsToBeInserted.join(', '));
            const newGroups = await Group.create(groupObjs);
            numGroupsInserted++;
            const newGroupsName = newGroups.map(g => g.name);
            groupsToSearch.push(...newGroupsName);
        }
        const groupSearchCriteria = {or: groupsToSearch.map(g => ({name: g}))};
        const groups = await Group.find(groupSearchCriteria).populate('members').populate('administrators');
        const criteria = {username: p.username};
        let user = await User.findOne(criteria);
        p.lastsynch = moment().utc().format();
        p.synchronized = true;
        const activeMembership = p.active;
        p.active = true;
        if (user) {
            const u = await User.update(criteria, p);
            if (userShouldBeUpdated(user, p)) {
                sails.log.info(`Updating user ${p.username}`);
                numUsersUpdated++;
            }
        }
        else {
            if (p[usersCreationCondition.attribute] === usersCreationCondition.value) {
                sails.log.info(`Inserting user ${p.username}`);
                user = await User.createCompleteUser(p);
                numUsersInserted++;
            }
        }
        if (!user)
            continue;

        for (let g of groups) {
            g.members.add(user.id);
            await g.savePromise();
            const membershipCriteria = {user: user.id, group: g.id};
            const membership = await Membership.findOne(membershipCriteria);
            if (membership) {
                membership.lastsynch = moment.utc().format();
                membership.synchronized = true;
                membership.active = activeMembership;
                const m = await Membership.update(membershipCriteria, membership);
            }
            if (p.pi) {
                g.administrators.add(user.id);
                await g.savePromise();
            }
        }
    }
    const membershipUpdateCriteria = {lastsynch: {'<': importTime}, synchronized: true, active: true};
    const membershipDisabled = await Membership.update(membershipUpdateCriteria, {active: false});
    const numMembershipDisabled = membershipDisabled.length;
    const userUpdateCriteria = {lastsynch: {'<': importTime}, synchronized: true, active: true};
    const usersDisabled = await User.update(userUpdateCriteria, {active: false});
    const numUsersDisabled = usersDisabled.length;
    sails.log.info('Import finished');
    sails.log.info(`${numUsersInserted} users inserted`);
    sails.log.info(`${numUsersUpdated} users updated`);
    sails.log.info(`${numUsersDisabled} users disabled`);
    sails.log.info(`${numGroupsInserted} groups inserted`);
    sails.log.info(`${numMembershipDisabled} membership disabled`);
}

async function importGroups() {
    sails.log.info('Group import started');

    const researchDomains = [];
    const url = sails.config.scientilla.mainInstituteImport.officialGroupsImportUrl;
    const reqOptions = {
        uri: url,
        json: true
    };

    let res;
    try {
        res = await request(reqOptions);
    } catch (e) {
        sails.log.debug('importGroups');
        sails.log.debug(e);
    }
    const {
        research_domains: researchDomainsData,
        research_structures: researchStructuresData
    } = res;

    await Attribute.destroy({
        key: {'!': researchDomainsData.map(rd => rd.code)},
        category: 'research_domain'
    });
    for (const rdData of researchDomainsData) {
        let researchDomain = await Attribute.findOrCreate({
            key: rdData.code,
            category: 'research_domain'
        });
        researchDomain = await Attribute.update({id: researchDomain.id}, {value: rdData});
        researchDomains.push(researchDomain[0]);
    }

    for (const rsData of researchStructuresData) {
        const group = await Group.findOrCreate({code: rsData.cdr});
        await Group.update({id: group.id}, {
            name: rsData.description,
            type: rsData.type,
            starting_date: rsData.start_date
        });

        //PI
        if (Array.isArray(rsData.pis) && rsData.pis.length > 0) {
            const pis = await User.find({username: rsData.pis.map(p => p.email)});

            if (pis && pis.length) {
                await PrincipalInvestigator.destroy({
                    group: group.id,
                    pi: {'!': pis.map(p => p.id)}
                });

                for (const pi of pis)
                    await PrincipalInvestigator.findOrCreate({
                        pi: pi.id,
                        group: group.id
                    });
            }
            else
                await PrincipalInvestigator.destroy({group: group.id});
        }
        else
            await PrincipalInvestigator.destroy({group: group.id});

        //center
        const membershipGroups = await MembershipGroup.find({child_group: group.id}).populate('parent_group');
        const oldCentersMG = membershipGroups.filter(mg => mg.parent_group.type === GroupTypes.CENTER);

        if (rsData.center && rsData.center.code) {
            const center = await Group.findOrCreate({code: rsData.center.code});
            await Group.update({id: center.id}, {
                name: rsData.center.name,
                type: GroupTypes.CENTER
            });

            const toDeleteIds = oldCentersMG.filter(mg => mg.parent_group.id !== center.id).map(mg => mg.id);
            if (toDeleteIds.length > 0)
                await MembershipGroup.destroy({id: toDeleteIds});

            if (!oldCentersMG.find(mg => mg.parent_group.id === center.id))
                await MembershipGroup.create({
                    parent_group: center.id,
                    child_group: group.id
                });
        }
        else
            await MembershipGroup.destroy({child_group: oldCentersMG.map(mg => mg.id)});

        //research domains and interactions
        if (rsData.main_research_domain) {
            await clearResearchDomains([rsData.main_research_domain.code], group, 'main');
            await addResearchDomain(rsData.main_research_domain.code, group, 'main');
        }
        else
            await clearResearchDomains([], group, 'main');

        await clearResearchDomains(rsData.interactions.map(i => i.code), group, 'interaction');
        for (const ird of rsData.interactions)
            await addResearchDomain(ird.code, group, 'interaction');
    }

    async function clearResearchDomains(correctRdCodes, group, type) {
        let res;
        if (!correctRdCodes.length)
            res = await GroupAttribute.find({
                researchEntity: group.id
            });
        else
            res = await GroupAttribute.find({
                attribute: {
                    '!': researchDomains.filter(rd => correctRdCodes.includes(rd.key)).map(rd => rd.id),
                },
                researchEntity: group.id
            });

        //query language does not support JSON
        const toDeleteIds = res.filter(ga => ga.extra.type === type).map(ga => ga.id);
        if (toDeleteIds.length)
            await GroupAttribute.destroy({id: toDeleteIds});
    }

    async function addResearchDomain(rdCode, group, type) {
        const rd = researchDomains.find(rd => rd.key === rdCode);
        if (rd) {
            const res = await GroupAttribute.find({attribute: rd.id, researchEntity: group.id});
            if (!res.filter(ga => ga.extra.type === type).length)
                await GroupAttribute.create({attribute: rd.id, researchEntity: group.id, extra: {type}});
        }
    }

    sails.log.info('Group import finished');
}

async function importSourceMetrics(filename) {
    sails.log.info('Source metrics import started');

    const sourceIdentifiers = SourceMetric.sourceIdentifiers;

    const originCellCoord = 'B1';
    const yearCellCoord = 'D1';

    let recordsCount = 0;

    const cols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    const filePath = 'config/init/' + filename;
    if (fs.existsSync(filePath)) {
        const workbook = xlsx.readFile(filePath);
        const sheetNameList = workbook.SheetNames;

        const workSheet = workbook.Sheets[sheetNameList[0]];

        if (!workSheet[originCellCoord] || !workSheet[yearCellCoord])
            throw 'Invalid file format';

        const origin = workSheet[originCellCoord].v;
        const year = workSheet[yearCellCoord].v;

        const columnsMapping = {};

        for (const c of cols) {
            const colNameCell = workSheet[c + '2'];
            if (!colNameCell)
                break;

            columnsMapping[colNameCell.v] = c;
        }

        const keyColumns = Object.keys(columnsMapping).filter(c => sourceIdentifiers.includes(c));
        const valueColumns = Object.keys(columnsMapping).filter(c => !sourceIdentifiers.includes(c));

        let i = 3;
        while (true) {
            const workSheetRow = {};

            for (const colName in columnsMapping) {
                const col = columnsMapping[colName];
                const cellCoord = col + i;
                if (workSheet[cellCoord])
                    workSheetRow[colName] = workSheet[cellCoord].v;
            }

            if (workSheetRow.issn) {
                workSheetRow.issn = workSheetRow.issn + '';
                workSheetRow.issn = workSheetRow.issn.replace(/-/g, '');
            }
            if (workSheetRow.eissn) {
                workSheetRow.eissn = workSheetRow.eissn + '';
                workSheetRow.eissn = workSheetRow.eissn.replace(/-/g, '');
            }

            if (_.isEmpty(workSheetRow))
                break;

            i++;

            const baseRecord = {};

            for (const kc of keyColumns)
                if (workSheetRow[kc])
                    baseRecord[kc] = workSheetRow[kc];

            if (_.isEmpty(baseRecord))
                continue;

            baseRecord.year = year;
            baseRecord.origin = origin;

            for (const vc of valueColumns) {
                if (!workSheetRow[vc])
                    continue;

                const criteria = _.clone(baseRecord);
                criteria.name = vc;
                const record = _.clone(baseRecord);
                record.name = vc;
                record.value = workSheetRow[vc];
                await SourceMetric.createOrUpdate(criteria, record);
                recordsCount++;
            }
        }
    }

    sails.log.info('imported ' + recordsCount + ' records');
    sails.log.info('Source metrics import finished');
}<commit_msg>Added possibility of not having a condition to check on user import.<commit_after>/* global Source, User, Group, SourceMetric, SourceTypes, Attribute, GroupAttribute, PrincipalInvestigator, MembershipGroup, GroupTypes*/
// Importer.js - in api/services

"use strict";

const xlsx = require('xlsx');
const _ = require('lodash');
const fs = require('fs');
const request = require('request-promise');
const moment = require('moment');

module.exports = {
    importSources,
    importPeople,
    importGroups,
    importSourceMetrics
};

async function importSources() {

    function readWorksheet(worksheet, mappingsTable, mapFn = _.identity, filterFn = _.stubTrue) {
        function readSourceRow(r) {
            const sourceData = {};
            _.forEach(mappingsTable, (col, field) => {
                const cell = col + r;
                if (!_.isUndefined(worksheet[cell]))
                    sourceData[field] = worksheet[cell]['v'];
            });
            return sourceData;
        }

        const sources = [];
        for (let r = 2; ; r++) {
            const sourceData = readSourceRow(r);
            if (_.isEmpty(sourceData))
                break;
            const mappedSourceData = mapFn(sourceData);
            if (filterFn(mappedSourceData))
                sources.push(mappedSourceData);
        }
        return sources;
    }

    const scopusSourcesFileName = 'config/init/scopus_sources.xlsx';
    let journalsAndBookSeries = [], newConferences = [], oldConferences = [];
    if (fs.existsSync(scopusSourcesFileName)) {
        const workbook = xlsx.readFile(scopusSourcesFileName);
        const sheetNameList = workbook.SheetNames;

        const journalWorksheet = workbook.Sheets[sheetNameList[0]];
        const journalMappingsTable = {
            "title": 'B',
            "scopusId": 'A',
            "issn": 'C',
            "eissn": 'D',
            "type": 'T',
            "publisher": 'Z'
        };

        const mapJournal = (s) => {
            const sourceMappingTable = {
                'Book Series': SourceTypes.BOOKSERIES,
                'Journal': SourceTypes.JOURNAL
            };
            s.type = sourceMappingTable[s.type];
            return s;
        };

        const filterJournals = (s) => s.type;

        journalsAndBookSeries = readWorksheet(journalWorksheet, journalMappingsTable, mapJournal, filterJournals);

        const newConferencesWorksheet = workbook.Sheets[sheetNameList[1]];
        const newConferencesMappingsTable = {
            "title": 'B',
            "scopusId": 'A',
            "issn": 'D'
        };
        const mapConference = s => {
            s.type = SourceTypes.CONFERENCE;
            return s;
        };
        newConferences = readWorksheet(newConferencesWorksheet, newConferencesMappingsTable, mapConference);

        const oldConferencesWorksheet = workbook.Sheets[sheetNameList[2]];
        const oldConferencesMappingsTable = newConferencesMappingsTable;
        oldConferences = readWorksheet(oldConferencesWorksheet, oldConferencesMappingsTable, mapConference);
    }

    let books = [];
    const scopusSourcesFileName2 = 'config/init/scopus_book_sources.xlsx';
    if (fs.existsSync(scopusSourcesFileName2)) {
        const workbook2 = xlsx.readFile(scopusSourcesFileName2);
        const sheetNameList2 = workbook2.SheetNames;

        const bookWorksheet = workbook2.Sheets[sheetNameList2[0]];
        const bookMappingsTable = {
            "title": 'A',
            "isbn": 'C',
            "publisher": 'D',
            "year": 'E'
        };

        const mapBook = (s) => {
            s.type = 'book';
            return s;
        };

        books = readWorksheet(bookWorksheet, bookMappingsTable, mapBook);
    }

    const sources = _.union(journalsAndBookSeries, newConferences, oldConferences, books);

    sails.log.info('Inserting ' + sources.length + ' new sources');
    await Source.create(sources);
}

async function importPeople() {
    function userShouldBeUpdated(user, values) {
        const userFieldsToUpdate = [
            'jobTitle',
            'name',
            'surname'
        ];
        const toUpdate = userFieldsToUpdate.some(f => values[f] !== user[f]);
        return toUpdate;
    }

    const usersCreationCondition = sails.config.scientilla.mainInstituteImport.usersCreationCondition;
    const groupInsertionEnabled = false;
    sails.log.info('Import started');
    const url = sails.config.scientilla.mainInstituteImport.userImportUrl;
    const reqOptions = {
        uri: url,
        json: true
    };

    let people;
    try {
        people = await request(reqOptions);
    } catch (e) {
        sails.log.debug('importPeople');
        sails.log.debug(e);
    }
    sails.log.info(people.length + ' entries found');
    const importTime = moment.utc().format();
    let numUsersInserted = 0, numUsersUpdated = 0, numGroupsInserted = 0;
    for (let [i, p] of people.entries()) {
        //groups are loaded in memory because waterline doesn't allow case-insensitive queries with postegres
        p.username = _.toLower(p.username);
        const allGroups = await Group.find();
        const groupsToBeInserted = p.groups.filter(g => !allGroups.some(g2 => _.toLower(g2.name) == _.toLower(g)));
        const groupsToSearch = allGroups.filter(g => p.groups.some(g2 => _.toLower(g2) == _.toLower(g.name))).map(g => g.name);
        if (groupInsertionEnabled && groupsToBeInserted.length) {
            const groupObjs = groupsToBeInserted.map(g => ({name: g}));
            sails.log.info('inserting groups: ' + groupsToBeInserted.join(', '));
            const newGroups = await Group.create(groupObjs);
            numGroupsInserted++;
            const newGroupsName = newGroups.map(g => g.name);
            groupsToSearch.push(...newGroupsName);
        }
        const groupSearchCriteria = {or: groupsToSearch.map(g => ({name: g}))};
        const groups = await Group.find(groupSearchCriteria).populate('members').populate('administrators');
        const criteria = {username: p.username};
        let user = await User.findOne(criteria);
        p.lastsynch = moment().utc().format();
        p.synchronized = true;
        const activeMembership = p.active;
        p.active = true;
        if (user) {
            const u = await User.update(criteria, p);
            if (userShouldBeUpdated(user, p)) {
                sails.log.info(`Updating user ${p.username}`);
                numUsersUpdated++;
            }
        }
        else {
            if (!usersCreationCondition || p[usersCreationCondition.attribute] === usersCreationCondition.value) {
                sails.log.info(`Inserting user ${p.username}`);
                user = await User.createCompleteUser(p);
                numUsersInserted++;
            }
        }
        if (!user)
            continue;

        for (let g of groups) {
            g.members.add(user.id);
            await g.savePromise();
            const membershipCriteria = {user: user.id, group: g.id};
            const membership = await Membership.findOne(membershipCriteria);
            if (membership) {
                membership.lastsynch = moment.utc().format();
                membership.synchronized = true;
                membership.active = activeMembership;
                const m = await Membership.update(membershipCriteria, membership);
            }
            if (p.pi) {
                g.administrators.add(user.id);
                await g.savePromise();
            }
        }
    }
    const membershipUpdateCriteria = {lastsynch: {'<': importTime}, synchronized: true, active: true};
    const membershipDisabled = await Membership.update(membershipUpdateCriteria, {active: false});
    const numMembershipDisabled = membershipDisabled.length;
    const userUpdateCriteria = {lastsynch: {'<': importTime}, synchronized: true, active: true};
    const usersDisabled = await User.update(userUpdateCriteria, {active: false});
    const numUsersDisabled = usersDisabled.length;
    sails.log.info('Import finished');
    sails.log.info(`${numUsersInserted} users inserted`);
    sails.log.info(`${numUsersUpdated} users updated`);
    sails.log.info(`${numUsersDisabled} users disabled`);
    sails.log.info(`${numGroupsInserted} groups inserted`);
    sails.log.info(`${numMembershipDisabled} membership disabled`);
}

async function importGroups() {
    sails.log.info('Group import started');

    const researchDomains = [];
    const url = sails.config.scientilla.mainInstituteImport.officialGroupsImportUrl;
    const reqOptions = {
        uri: url,
        json: true
    };

    let res;
    try {
        res = await request(reqOptions);
    } catch (e) {
        sails.log.debug('importGroups');
        sails.log.debug(e);
    }
    const {
        research_domains: researchDomainsData,
        research_structures: researchStructuresData
    } = res;

    await Attribute.destroy({
        key: {'!': researchDomainsData.map(rd => rd.code)},
        category: 'research_domain'
    });
    for (const rdData of researchDomainsData) {
        let researchDomain = await Attribute.findOrCreate({
            key: rdData.code,
            category: 'research_domain'
        });
        researchDomain = await Attribute.update({id: researchDomain.id}, {value: rdData});
        researchDomains.push(researchDomain[0]);
    }

    for (const rsData of researchStructuresData) {
        const group = await Group.findOrCreate({code: rsData.cdr});
        await Group.update({id: group.id}, {
            name: rsData.description,
            type: rsData.type,
            starting_date: rsData.start_date
        });

        //PI
        if (Array.isArray(rsData.pis) && rsData.pis.length > 0) {
            const pis = await User.find({username: rsData.pis.map(p => p.email)});

            if (pis && pis.length) {
                await PrincipalInvestigator.destroy({
                    group: group.id,
                    pi: {'!': pis.map(p => p.id)}
                });

                for (const pi of pis)
                    await PrincipalInvestigator.findOrCreate({
                        pi: pi.id,
                        group: group.id
                    });
            }
            else
                await PrincipalInvestigator.destroy({group: group.id});
        }
        else
            await PrincipalInvestigator.destroy({group: group.id});

        //center
        const membershipGroups = await MembershipGroup.find({child_group: group.id}).populate('parent_group');
        const oldCentersMG = membershipGroups.filter(mg => mg.parent_group.type === GroupTypes.CENTER);

        if (rsData.center && rsData.center.code) {
            const center = await Group.findOrCreate({code: rsData.center.code});
            await Group.update({id: center.id}, {
                name: rsData.center.name,
                type: GroupTypes.CENTER
            });

            const toDeleteIds = oldCentersMG.filter(mg => mg.parent_group.id !== center.id).map(mg => mg.id);
            if (toDeleteIds.length > 0)
                await MembershipGroup.destroy({id: toDeleteIds});

            if (!oldCentersMG.find(mg => mg.parent_group.id === center.id))
                await MembershipGroup.create({
                    parent_group: center.id,
                    child_group: group.id
                });
        }
        else
            await MembershipGroup.destroy({child_group: oldCentersMG.map(mg => mg.id)});

        //research domains and interactions
        if (rsData.main_research_domain) {
            await clearResearchDomains([rsData.main_research_domain.code], group, 'main');
            await addResearchDomain(rsData.main_research_domain.code, group, 'main');
        }
        else
            await clearResearchDomains([], group, 'main');

        await clearResearchDomains(rsData.interactions.map(i => i.code), group, 'interaction');
        for (const ird of rsData.interactions)
            await addResearchDomain(ird.code, group, 'interaction');
    }

    async function clearResearchDomains(correctRdCodes, group, type) {
        let res;
        if (!correctRdCodes.length)
            res = await GroupAttribute.find({
                researchEntity: group.id
            });
        else
            res = await GroupAttribute.find({
                attribute: {
                    '!': researchDomains.filter(rd => correctRdCodes.includes(rd.key)).map(rd => rd.id),
                },
                researchEntity: group.id
            });

        //query language does not support JSON
        const toDeleteIds = res.filter(ga => ga.extra.type === type).map(ga => ga.id);
        if (toDeleteIds.length)
            await GroupAttribute.destroy({id: toDeleteIds});
    }

    async function addResearchDomain(rdCode, group, type) {
        const rd = researchDomains.find(rd => rd.key === rdCode);
        if (rd) {
            const res = await GroupAttribute.find({attribute: rd.id, researchEntity: group.id});
            if (!res.filter(ga => ga.extra.type === type).length)
                await GroupAttribute.create({attribute: rd.id, researchEntity: group.id, extra: {type}});
        }
    }

    sails.log.info('Group import finished');
}

async function importSourceMetrics(filename) {
    sails.log.info('Source metrics import started');

    const sourceIdentifiers = SourceMetric.sourceIdentifiers;

    const originCellCoord = 'B1';
    const yearCellCoord = 'D1';

    let recordsCount = 0;

    const cols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    const filePath = 'config/init/' + filename;
    if (fs.existsSync(filePath)) {
        const workbook = xlsx.readFile(filePath);
        const sheetNameList = workbook.SheetNames;

        const workSheet = workbook.Sheets[sheetNameList[0]];

        if (!workSheet[originCellCoord] || !workSheet[yearCellCoord])
            throw 'Invalid file format';

        const origin = workSheet[originCellCoord].v;
        const year = workSheet[yearCellCoord].v;

        const columnsMapping = {};

        for (const c of cols) {
            const colNameCell = workSheet[c + '2'];
            if (!colNameCell)
                break;

            columnsMapping[colNameCell.v] = c;
        }

        const keyColumns = Object.keys(columnsMapping).filter(c => sourceIdentifiers.includes(c));
        const valueColumns = Object.keys(columnsMapping).filter(c => !sourceIdentifiers.includes(c));

        let i = 3;
        while (true) {
            const workSheetRow = {};

            for (const colName in columnsMapping) {
                const col = columnsMapping[colName];
                const cellCoord = col + i;
                if (workSheet[cellCoord])
                    workSheetRow[colName] = workSheet[cellCoord].v;
            }

            if (workSheetRow.issn) {
                workSheetRow.issn = workSheetRow.issn + '';
                workSheetRow.issn = workSheetRow.issn.replace(/-/g, '');
            }
            if (workSheetRow.eissn) {
                workSheetRow.eissn = workSheetRow.eissn + '';
                workSheetRow.eissn = workSheetRow.eissn.replace(/-/g, '');
            }

            if (_.isEmpty(workSheetRow))
                break;

            i++;

            const baseRecord = {};

            for (const kc of keyColumns)
                if (workSheetRow[kc])
                    baseRecord[kc] = workSheetRow[kc];

            if (_.isEmpty(baseRecord))
                continue;

            baseRecord.year = year;
            baseRecord.origin = origin;

            for (const vc of valueColumns) {
                if (!workSheetRow[vc])
                    continue;

                const criteria = _.clone(baseRecord);
                criteria.name = vc;
                const record = _.clone(baseRecord);
                record.name = vc;
                record.value = workSheetRow[vc];
                await SourceMetric.createOrUpdate(criteria, record);
                recordsCount++;
            }
        }
    }

    sails.log.info('imported ' + recordsCount + ' records');
    sails.log.info('Source metrics import finished');
}<|endoftext|>


<commit_before>(function () {
  "use strict";

  angular
    .module('mnAlertsService', ['ui.bootstrap', 'mnFilters'])
    .service('mnAlertsService', mnAlertsServiceFactory);

  function mnAlertsServiceFactory($uibModal, $rootScope, $window, $timeout) {
    var alerts = [];
    var alertsHistory = [];
    var mnAlertsService = {
      setAlert: setAlert,
      formatAndSetAlerts: formatAndSetAlerts,
      showAlertInPopup: showAlertInPopup,
      alerts: alerts,
      removeItem: removeItem,
      isNewAlert: isNewAlert
    };

    return mnAlertsService;

    function showAlertInPopup(message, title) {
      var scope = $rootScope.$new();
      scope.alertsCtl = {
        message: message
      };
      scope.title = title;
      return $uibModal.open({
        scope: scope,
        templateUrl: "app/components/mn_alerts_popup_message.html"
      }).result;
    }

    function isNewAlert(item) {
      var findedItem = _.find(alertsHistory, item);
      return _.indexOf(alertsHistory, findedItem) === -1;
    }

    function startTimer(item, timeout) {
      return $timeout(function () {
        removeItem(item);
      }, parseInt(timeout, 10));
    }

    function removeItem(item) {
      var index = _.indexOf(alerts, item);
      item.timeout && $timeout.cancel(item.timeout);
      alerts.splice(index, 1);
    }

    function setAlert(type, message, timeout, id) {
      var item = {
        type: type,
        msg: message,
        id: id
      };
      var findedItem = _.find(alerts, item);
      if (findedItem) {
        removeItem(findedItem);
      }

      alerts.push(item);
      alertsHistory.push(item);

      if (timeout) {
        item.timeout = startTimer(item, timeout);
      }
      $window.scrollTo(0, 0);
    }
    function formatAndSetAlerts(incomingAlerts, type, timeout) {
      timeout = timeout || 60000;
      if ((angular.isArray(incomingAlerts) && angular.isString(incomingAlerts[0])) ||
          angular.isObject(incomingAlerts)) {
        angular.forEach(incomingAlerts, function (msg) {
          setAlert(type, msg, timeout);
        });
      }

      if (angular.isString(incomingAlerts)) {
        setAlert(type, incomingAlerts, timeout);
      }
    }
  }
})();
<commit_msg>MB-22843: do not duplicate alert messages<commit_after>(function () {
  "use strict";

  angular
    .module('mnAlertsService', ['ui.bootstrap', 'mnFilters'])
    .service('mnAlertsService', mnAlertsServiceFactory);

  function mnAlertsServiceFactory($uibModal, $rootScope, $window, $timeout) {
    var alerts = [];
    var alertsHistory = [];
    var mnAlertsService = {
      setAlert: setAlert,
      formatAndSetAlerts: formatAndSetAlerts,
      showAlertInPopup: showAlertInPopup,
      alerts: alerts,
      removeItem: removeItem,
      isNewAlert: isNewAlert
    };

    return mnAlertsService;

    function showAlertInPopup(message, title) {
      var scope = $rootScope.$new();
      scope.alertsCtl = {
        message: message
      };
      scope.title = title;
      return $uibModal.open({
        scope: scope,
        templateUrl: "app/components/mn_alerts_popup_message.html"
      }).result;
    }

    function isNewAlert(item) {
      var findedItem = _.find(alertsHistory, item);
      return _.indexOf(alertsHistory, findedItem) === -1;
    }

    function startTimer(item, timeout) {
      return $timeout(function () {
        removeItem(item);
      }, parseInt(timeout, 10));
    }

    function removeItem(item) {
      var index = _.indexOf(alerts, item);
      item.timeout && $timeout.cancel(item.timeout);
      alerts.splice(index, 1);
    }

    function setAlert(type, message, timeout, id) {
      var item = {
        type: type,
        msg: message,
        id: id
      };

      //in case we get alert with the same message
      //but different id find and remove it
      var findedItem = _.find(alerts, {
        type: type,
        msg: message
      });

      if (findedItem) {
        removeItem(findedItem);
      }

      alerts.push(item);
      alertsHistory.push(item);

      if (timeout) {
        item.timeout = startTimer(item, timeout);
      }
      $window.scrollTo(0, 0);
    }
    function formatAndSetAlerts(incomingAlerts, type, timeout) {
      timeout = timeout || 60000;
      if ((angular.isArray(incomingAlerts) && angular.isString(incomingAlerts[0])) ||
          angular.isObject(incomingAlerts)) {
        angular.forEach(incomingAlerts, function (msg) {
          setAlert(type, msg, timeout);
        });
      }

      if (angular.isString(incomingAlerts)) {
        setAlert(type, incomingAlerts, timeout);
      }
    }
  }
})();
<|endoftext|>


<commit_before>var Patient_zero = require("lib/patient_zero");

Patient_zero.crawl(process.argv.splice(2));
<commit_msg>Patient Zero was in a different location!<commit_after>var Patient_zero = require("./lib/patient_zero");

Patient_zero.crawl(process.argv.splice(2));
<|endoftext|>


<commit_before>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';

export default Route.extend({
  access: service(),

  // TODO 2.0
  model: function() {
    var route = (this.get('access.provider')||'').toLowerCase().replace(/config$/i,'');

    if ( route === 'ldap' ) {
      route = 'activedirectory';
    }

    if ( this.get('access.enabled') && route !== 'local') {
      this.replaceWith('security.authentication.' + route);
    } else {
      this.replaceWith('security.authentication.localauth');
    }
  },
});
<commit_msg>select active auth<commit_after>import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import { get } from '@ember/object';

export default Route.extend({
  access: service(),
  globalStore: service(),

  // TODO 2.0
  model: function() {
    var route = (this.get('access.provider')||'').toLowerCase().replace(/config$/i,'');

    if ( route === 'ldap' ) {
      route = 'activedirectory';
    }

    return get(this, 'globalStore').find('authconfig', null, {filter: {enabled: true}}).then((configs) => {
      if (get(configs, 'length') === 2) {
        let neuRt = configs.find((config) =>  get(config, 'id') !== 'local');
        this.replaceWith('security.authentication.' + get(neuRt, 'id'));
      } else if (get(configs, 'length') > 2) {
        // ???
      } else {
        this.replaceWith('security.authentication.localauth');
      }
    })
  },
});
<|endoftext|>


<commit_before>var Ascend = (function() {

	return func = function() {
		console.log(arguments[0]);

		if (!this.controller) {
			this.controller = new Leap.Controller({ enableGestures: true });
			this.controller.on('animationFrame', function(frame){
				if (frame.id%10 === 0) {
					if (frame.pointables.length) {
						// $(options.element).trigger('pointables', frame);
					} else {
						// $(options.element).trigger('pointablesout', frame);
					}
					if (frame.hands.length) {
						// $(options.element).trigger('hands', frame);
					} else {
						// $(options.element).trigger('handsout', frame);
					}
					if (frame.fingers.length) {
						// $(options.element).trigger('fingers', frame);
					} else {
						// $(options.element).trigger('fingersout', frame);
					}
					if (frame.tools.length) {
						console.log('Tool '+frame.tools[0].id+' Detected');
						// $(options.element).trigger('tools', frame);
					} else {
						// $(options.element).trigger('toolsout', frame);
					}
					if (frame.gestures.length > 0) {
						// $(options.element).trigger('gesture', frame);
						frame.gestures.forEach(function(gesture) {
							// $(options.element).trigger(gesture.type, gesture);
							// $(options.element).trigger(
							// 	gesture.type + gesture.state,
							// 	gesture
							// );
						});
					}
				}
			});

			//Lets monitor the default things for LeapJS
			this.controller.on('connect', function(){
				trigger('connect');
			})

			this.controller.connect();
		}

		function bind(eventType, listener) {
			if(!this._listeners) {
				 this._listeners = {};
			}
			if(!(eventType in this._listeners)) {
				this._listeners[eventType] = [];
			}
			var arr = this._listeners[eventType];
			if(arrIndexOf(arr, listener) === -1) {
				arr.push(listener);
			}
			return;
		};

		function unbind(eventType, listener) {
			if(!(this._listeners && (eventType in this._listeners))) {
				return;
			}
			var arr = this._listeners[eventType];
			var idx = arrIndexOf(arr, listener);
			if (idx !== -1) {
				if(arr.length > 1) {
					this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) );
				} else {
					delete this._listeners[eventType];
				}
				return;
			}
			return;
		};

		function trigger(event) {
			var t = event.type;
			var args = Array.prototype.slice.call(arguments, 0);
			if (this['on'+t]) {
				this['on'+t].apply(this, args);
			}
			if (this._listeners && t in this._listeners) {
				for(var i=0; i < this._listeners[t].length; i++) {
					this._listeners[t][i].apply(this, args);
				}
			}
		};

		function arrIndexOf(arr, obj) {
			for(var i=0; i < arr.length; i++){
				if(arr[i] === obj){
					return i;
				}
			}
			return -1;
		}

		return {
			controller: this.controller,
			bind: bind,
			unbind: unbind,
			trigger: trigger,
			swipe: function(callback) {

			},
			punch: function() {

			}
		};
	}

})();<commit_msg>Added in Connect/disconnect events<commit_after>var Ascend = (function() {

	return func = function() {
		console.log(arguments[0]);

		if (!this.controller) {
			this.controller = new Leap.Controller({ enableGestures: true });
			this.controller.on('animationFrame', function(frame){
				if (frame.id%10 === 0) {
					if (frame.pointables.length) {
						// $(options.element).trigger('pointables', frame);
					} else {
						// $(options.element).trigger('pointablesout', frame);
					}
					if (frame.hands.length) {
						// $(options.element).trigger('hands', frame);
					} else {
						// $(options.element).trigger('handsout', frame);
					}
					if (frame.fingers.length) {
						// $(options.element).trigger('fingers', frame);
					} else {
						// $(options.element).trigger('fingersout', frame);
					}
					if (frame.tools.length) {
						console.log('Tool '+frame.tools[0].id+' Detected');
						// $(options.element).trigger('tools', frame);
					} else {
						// $(options.element).trigger('toolsout', frame);
					}
					if (frame.gestures.length > 0) {
						// $(options.element).trigger('gesture', frame);
						frame.gestures.forEach(function(gesture) {
							// $(options.element).trigger(gesture.type, gesture);
							// $(options.element).trigger(
							// 	gesture.type + gesture.state,
							// 	gesture
							// );
						});
					}
				}
			});

			//Lets bind some default functions
			bind('connect', function() {
				console.log('Device Connected');
			})

			bind('deviceConnected', function() {
				console.log('Device Connected');
			})

			bind('deviceDisconnected', function() {
				console.log('Device Disconnected');
			})

			//Lets monitor the default things for LeapJS
			this.controller.on('connect', function(){
				trigger('connect');
			})

			this.controller.on('deviceConnected', function(){
				trigger('deviceConnected');
			});

			this.controller.on('deviceDisconnected', function(){
				trigger('deviceDisconnected');
			});

			//Finally Connect
			this.controller.connect();
		}

		function bind(eventType, listener) {
			if(!this._listeners) {
				 this._listeners = {};
			}
			if(!(eventType in this._listeners)) {
				this._listeners[eventType] = [];
			}
			var arr = this._listeners[eventType];
			if(arrIndexOf(arr, listener) === -1) {
				arr.push(listener);
			}
			return;
		};

		function unbind(eventType, listener) {
			if(!(this._listeners && (eventType in this._listeners))) {
				return;
			}
			var arr = this._listeners[eventType];
			var idx = arrIndexOf(arr, listener);
			if (idx !== -1) {
				if(arr.length > 1) {
					this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) );
				} else {
					delete this._listeners[eventType];
				}
				return;
			}
			return;
		};

		function trigger(eventType) {
			var args = Array.prototype.slice.call(arguments, 0);
			if (this._listeners && eventType in this._listeners) {
				for(var i=0; i < this._listeners[eventType].length; i++) {
					this._listeners[eventType][i].apply(this, args);
				}
			}
		};

		function arrIndexOf(arr, obj) {
			for(var i=0; i < arr.length; i++){
				if(arr[i] === obj){
					return i;
				}
			}
			return -1;
		}

		return {
			controller: this.controller,
			bind: bind,
			unbind: unbind,
			trigger: trigger,
			swipe: function(callback) {

			},
			punch: function() {

			}
		};
	}

})();<|endoftext|>


<commit_before>#!/usr/bin/env node

var app = require('commander')
var chalk = require('chalk')
var api = require('./lib/api')
var auth = require('./lib/auth')

app
  .description('Display effective user')
  .parse(process.argv)

function main () {
  api('/user', function (err, res, body) {
    if (err || body.error) {
      console.error(JSON.stringify(err || body.error, null, 2))
      process.exit(1)
    }
    console.log(body.name + ' <' + chalk.underline(body.email) + '>')
    process.exit()
  })
}

auth(main)
<commit_msg>shows authentication timestamp<commit_after>#!/usr/bin/env node

var app = require('commander')
var api = require('./lib/api')
var auth = require('./lib/auth')
var Configstore = require('configstore');
var conf = new Configstore('wunderline');
var chalk = require('chalk')

app
  .description('Display effective user')
  .parse(process.argv)

function main () {
  api('/user', function (err, res, body) {
    if (err || body.error) {
      console.error(JSON.stringify(err || body.error, null, 2))
      process.exit(1)
    }
    console.log(body.name + ' <' + body.email + '>')
    console.log(chalk.dim('Authenticated at ' + conf.get('authenticated_at')))
    process.exit()
  })
}

auth(main)
<|endoftext|>


<commit_before>var gulp = require('gulp')
  , util = require('gulp-util')
  , rename = require('gulp-rename')
  , less = require('gulp-less')
  , autoprefixer = require('gulp-autoprefixer')
  , sourcemaps = require('gulp-sourcemaps')
  , watchify = require('watchify')
  , browserify = require('browserify')
  , source = require('vinyl-source-stream')
  , clean = require('./clean')
  , lint = require('./lint')
  , async = require('async')
  , _ = require('underscore');

var js = module.exports.js = function js(options, cb) {
  options = options || {};
  if (!options.app || !options.dest || !options.name) return cb(new Error('(BuildJS) app, dest and name are required.'));

  var browserifyArgs = {
    entries: [options.app]
  , extensions: ['.js']
  , debug: true // source maps
  };
  var compiler = watchify(browserify(_.extend(watchify.args, browserifyArgs)));

  compiler.on('update', compile);
  compiler.on('error', util.log);
  compile();

  function compile(wargs) {
    async.series([
      clean.bind(null, {src: options.dest + '/' + (options.name || '**/*') + '.js'})
    , lint.js.bind(null, options)
    ], function(err) {
      if (err) return cb ? cb(err) : util.log(err);
      util.log('Browserifying ' + util.colors.blue(options.app) + ' into ' + util.colors.blue(options.dest + '/' + options.name + '.js'));

      return compiler.bundle()
        .pipe(source(options.name + '.js'))
        .pipe(gulp.dest(options.dest))
        .on('end', wargs ? function() {} : cb || function() {})
        .on('error', cb || util.log);
    });
  }
};

var css = module.exports.css = function css(options, cb) {
  options = options || {};
  if (!options.app || !options.dest || !options.name) return cb(new Error('(BuildCSS) app, dest and name are required.'));

  async.series([
    clean.bind(null, {src: options.dest + '/' + (options.name || '**/*') + '.css'})
  , lint.css.bind(null, options)
  ], function(err) {
    if (err) return cb ? cb(err) : util.log(err);
    util.log('Compiling ' + util.colors.blue(options.app) + ' into ' + util.colors.blue(options.dest + '/' + options.name + '.css'));

    gulp.src(options.app)
      .pipe(sourcemaps.init())
      .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8"))
      .pipe(less())
      .pipe(rename(options.name + '.css'))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(options.dest))
      .on('end', cb || function() {})
      .on('error', cb || util.log);
  });
};

var html = module.exports.html = function html(options, cb) {
  options = options || {};
  if (!options.src || !options.dest) return cb(new Error('(BuildHTML) src and dest are required.'));

  clean({src: options.dest + '/**/*.html'}, function(err) {
    if (err) return cb ? cb(err) : util.log(err);
    util.log('Moving ' + util.colors.blue(options.src) + ' to ' + util.colors.blue(options.dest));

    gulp.src(options.src)
      .pipe(gulp.dest(options.dest))
      .on('end', cb || function() {})
      .on('error', cb || util.log);
  });
};

module.exports.all = function all(options, cb) {
  async.parallel([
    js.bind(null, _.extend(options.js, {dest: options.build.dest, name: options.name}))
  , css.bind(null, _.extend(options.css, {dest: options.build.dest, name: options.name}))
  , html.bind(null, {src: options.html.src, dest: options.build.dest})
  ], cb);
};
<commit_msg>update build with watch & dest options<commit_after>var gulp = require('gulp')
  , util = require('gulp-util')
  , rename = require('gulp-rename')
  , less = require('gulp-less')
  , autoprefixer = require('gulp-autoprefixer')
  , sourcemaps = require('gulp-sourcemaps')
  , watchify = require('watchify')
  , browserify = require('browserify')
  , source = require('vinyl-source-stream')
  , clean = require('./clean')
  , lint = require('./lint')
  , async = require('async')
  , _ = require('underscore');

module.exports.all = function all(buildOptions, options, cb) {
  async.parallel([
    js.bind(this, _.extend(options.js, buildOptions))
  , css.bind(this, _.extend(options.css, buildOptions))
  , html.bind(this, {src: options.html.src, dest: buildOptions.dest})
  ], cb);
};

var js = module.exports.js = function js(options, cb) {
  options = options || {};
  if (!options.app || !options.dest || !options.name) return cb(new Error('(BuildJS) app, dest and name are required.'));

  var compiler = browserify(_.extend(watchify.args, {entries: [options.app], extensions: ['.js'], debug: true}));
  // debug is for source maps

  if (options.watch) {
    compiler = watchify(compiler);
    compiler.on('update', compile);
    compiler.on('error', util.log);
  }

  compile();

  function compile(wargs) {
    async.series([
      clean.bind(null, {src: options.dest + '/' + (options.name || '**/*') + '.js'})
    , lint.js.bind(null, options)
    ], function(err) {
      if (err) return cb ? cb(err) : util.log(err);
      util.log('Browserifying ' + util.colors.blue(options.app) + ' into ' + util.colors.blue(options.dest + '/' + options.name + '.js'));

      return compiler.bundle()
        .pipe(source(options.name + '.js'))
        .pipe(gulp.dest(options.dest))
        .on('end', wargs ? function() {} : cb || function() {})
        .on('error', cb || util.log);
    });
  }
};

var css = module.exports.css = function css(options, cb) {
  options = options || {};
  if (!options.app || !options.dest || !options.name) return cb(new Error('(BuildCSS) app, dest and name are required.'));

  async.series([
    clean.bind(null, {src: options.dest + '/' + (options.name || '**/*') + '.css'})
  , lint.css.bind(null, options)
  ], function(err) {
    if (err) return cb ? cb(err) : util.log(err);
    util.log('Compiling ' + util.colors.blue(options.app) + ' into ' + util.colors.blue(options.dest + '/' + options.name + '.css'));

    gulp.src(options.app)
      .pipe(sourcemaps.init())
      .pipe(autoprefixer("last 2 versions", "> 1%", "ie 8"))
      .pipe(less())
      .pipe(rename(options.name + '.css'))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest(options.dest))
      .on('end', cb || function() {})
      .on('error', cb || util.log);
  });
};

var html = module.exports.html = function html(options, cb) {
  options = options || {};
  if (!options.src || !options.dest) return cb(new Error('(BuildHTML) src and dest are required.'));

  clean({src: options.dest + '/**/*.html'}, function(err) {
    if (err) return cb ? cb(err) : util.log(err);
    util.log('Moving ' + util.colors.blue(options.src) + ' to ' + util.colors.blue(options.dest));

    gulp.src(options.src)
      .pipe(gulp.dest(options.dest))
      .on('end', cb || function() {})
      .on('error', cb || util.log);
  });
};
<|endoftext|>


<commit_before>UseradminApp.service('Applications', function($http,Messages){

    var defaultlist = [
        {
            "id": "1",
            "name": "UserAdmin",
            "defaultRole": "UserAdmin",
            "defaultOrgid": "Whydah",
            "availableOrgIds": null
        },
        {
            "id": "2",
            "name": "Mobilefirst",
            "defaultRole": "client",
            "defaultOrgid": "Altran",
            "availableOrgIds": null
        },
        {
            "id": "3",
            "name": "Whydah",
            "defaultRole": "developer",
            "defaultOrgid": "Whydah",
            "availableOrgIds": null
        }
    ];

    var wishlist = {
        applicationId: 1,
        applicationName: 'name',
        defaultRole: 'role',
        defaultRoleValue: 'value',
        defaultOrg: 'org1',
        organisations: [
            'org1',
            'org2',
            'org3'
        ]
    }

    this.list = [];
    this.selected = false;

//    this.search = function() {
//        console.log('Searching for applications...');
//        var that = this;
//        $http({
//            method: 'GET',
//            url: baseUrl + 'applications'
//        }).success(function (data) {
//            that.list = data;
//        });
//        return this;
//    };

     this.search = function(searchQuery) {
        console.log('Searching for applications...');
        this.searchQuery = searchQuery || '*';
         var that = this;
         $http({
            method: 'GET',
            url: baseUrl+'applications/find/'+this.searchQuery
            //url: 'json/users.json',
         }).success(function (data) {
            that.list = data.result;
            that.rows = data.rows;
         }).error(function(data,status){
         // This is most likely due to usertoken timeout - TODO: Redirect to login webapp
         console.log('Unable to search', data);
         switch (status) {
            case 403: // Forbidden
               Messages.add('danger', 'Unable to seach! Forbidden...');
               break;
            case 404:  // 404 No access
               Messages.add('danger', 'Unable to search! No access...');
               break;
            case 409:  // 409 Conflict - will prbably not occur here
               Messages.add('danger', 'Search already exists...');
               break;
            default:
               Messages.add('danger', 'Search failed with error code: ' + status);
          }

          });
        return this;
     };

    function buildRoleNames(application) {
        var roleNames = [];
        if (application.hasOwnProperty("roles")) {
            if (application.roles && application.roles.length) {
                for (var i = 0; i < application.roles.length; i++) {
                    var role = application.roles[i];
                    roleNames.push(role.name);
                }
            }
        }
        return roleNames;
    }
    function buildOrgNames(application) {
        var orgNames = [];
        if (application.hasOwnProperty("organizationNames")) {
            if (application.organizationNames && application.organizationNames.length) {
                for (var i = 0; i < application.organizationNames.length; i++) {
                    var org = application.organizationNames[i];
                    orgNames.push(org.name);
                }
            }
        }
        return orgNames;
    }

    this.get = function(id, callback) {
        console.log('Getting Application with id=', id);
        var that = this;
        $http({
            method: 'GET',
            url: baseUrl+'application/'+id+'/'
        }).success(function (data) {
            console.log('Got applicaton', data);
            that.application = data;
            that.application.secret = data.security.secret;
            that.application.applicationJson = JSON.stringify(data);
            that.application.roleNames = buildRoleNames(that.application);
            that.application.orgNames = buildOrgNames(that.application);
            if(callback) {
                callback(that.application);
            }
        });
        return this;
    };

    this.add = function(application, successCallback) {
        console.log('Adding application', application);
        var that = this;

        //application.security = {};
        //application.security.secret = application.secret;
        //delete application.secret;
        var postData = buildApplicationUpdate(application);
        if (postData.hasOwnProperty('name')) {
            $http({
                method: 'POST',
                url: baseUrl + 'application/',
                data: postData
            }).success(function (data) {
                Messages.add('success', 'application "' + application.name + '" was added successfully.');
                application.id = data.id;
                that.search(that.searchQuery);
                if (successCallback) {
                    successCallback();
                }
            }).error(function (data, status) {
                console.log('application was not added', data);
                switch (status) {
                    case 403:
                        Messages.add('danger', 'application was not added! No access...');
                        break;
                    case 404:  /* 404 No access */
                        Messages.add('danger', 'application was not added! No access...');
                        break;
                    case 409:  /* 409 Conflict - user exists or was double posted */
                        Messages.add('danger', 'application was not added! Already exists...');
                        break;
                    default:
                        Messages.add('danger', 'application was not added and! Try again later...');
                }
                $scope.activateTimeoutModal();
            });
        }
        return this;
    };

    this.save = function(application, successCallback) {
        console.log('Updating application', JSON.stringify(application));
        var that = this;
        var postData = buildApplicationUpdate(application);
        if (postData.hasOwnProperty('name')) {
            console.log("Save this json: " + JSON.stringify(postData));
            $http({
                method: 'PUT',
                url: baseUrl + 'application/' + application.id + '/',
                data: postData
            }).success(function (data) {
                Messages.add('success', 'application "' + application.name + '" was updated successfully.');
                application.id = data.id;
                that.search(that.searchQuery);
                if (successCallback) {
                    successCallback();
                }
            }).error(function (data, status) {
                console.log('application was not updated', data);
                switch (status) {
                    case 400:
                        Messages.add('danger','application was not updated! Please validate your form and applicationjson input.');
                        break;
                    case 403:
                        Messages.add('danger', 'application was not updated! No access...');
                        break;
                    case 404:  /* 404 No access */
                        Messages.add('danger', 'application was not updated! No access...');
                        break;
                    case 409:  /* 409 Conflict - user exists or was double posted */
                        Messages.add('danger', 'application was not updated! Already exists...');
                        break;
                    default:
                        Messages.add('danger', 'application was not updated and! Try again later...');
                }
                $scope.activateTimeoutModal();
            });
        }
        return this;
    };

    function buildApplicationUpdate(application) {
        var postData = {};
        if (application.hasOwnProperty('secret')) {
            if (application.hasOwnProperty('security')) {
                application.security.secret = application.secret;
            } else {
                application.security = {};
                application.security.secret = application.secret;
            }
            delete application.secret;
        }
        if (application.hasOwnProperty('roleNames')) {
            if (typeof application.roleNames === 'string') {
                application.roles = [];
                var roleSplit = application.roleNames.split(",");
                for (i = 0; i < roleSplit.length; i++) {
                     var role = {};
                     var item = roleSplit[i];
                     role.id = item.trim();
                     role.name = item.trim();
                     application.roles.push(role);
                }
            }
        }
        if (application.hasOwnProperty('orgNames')) {
            if (typeof application.orgNames === 'string') {
                application.organizationNames = [];
                var nameSplit = application.orgNames.split(",");
                for (i = 0; i < nameSplit.length; i++) {
                    var name = {};
                    var item = nameSplit[i];
                    name.id = item.trim();
                    name.name = item.trim();
                    application.organizationNames.push(name);
                }
            }
        }
        return application;
    }

    this.saveFromJson = function(application, successCallback) {
        console.log('Updating application from json', JSON.stringify(application.applicationJson));
        var that = this;
        var postData = {};
        if (application.applicationJson) {
            try {
                postData = JSON.parse(application.applicationJson);

                console.log("Save this json: " + JSON.stringify(postData));
                $http({
                    method: 'PUT',
                    url: baseUrl + 'application/' + application.id + '/',
                    data: postData
                }).success(function (data) {
                    Messages.add('success', 'application "' + application.name + '" was updated successfully.');
                    application.id = data.id;
                    that.search(that.searchQuery);
                    if (successCallback) {
                        successCallback();
                    }
                }).error(function (data, status) {
                    console.log('application was not updated', data);
                    switch (status) {
                        case 400:
                            Messages.add('danger','application was not updated! Please validate your form and applicationjson input.');
                            break;
                        case 403:
                            Messages.add('danger', 'application was not updated! No access...');
                            break;
                        case 404:  /* 404 No access */
                            Messages.add('danger', 'application was not updated! No access...');
                            break;
                        case 409:  /* 409 Conflict - user exists or was double posted */
                            Messages.add('danger', 'application was not updated! Already exists...');
                            break;
                        default:
                            Messages.add('danger', 'application was not updated and! Try again later...');
                    }
                    $scope.activateTimeoutModal();
                });
            } catch (e) {
                Messages.add('danger', 'Could not parse applicationJson to JSON object.');
            }
        } else {
            Messages.add('danger', 'Could not update application. ApplcationJson is missing.');
        }

        return this;
    };

    this.delete = function(application, successCallback) {
        console.log('Deleting application', JSON.stringify(application));
        var that = this;
        if (application.hasOwnProperty(secret)) {
            application.security = {};
            application.security.secret = application.secret;
            delete application.secret;
        }
        $http({
            method: 'DELETE',
            url: baseUrl+'application/'+application.id +'/'
            //data: application
        }).success(function (data) {
            Messages.add('success', 'application "'+application.name+'" was deleted.');
            application.id = data.id;
            that.search(that.searchQuery);
            if(successCallback){
                successCallback();
            }
        }).error(function(data,status){
            console.log('application was not deleted.', data, status);
            switch (status) {
                case 403:
                    Messages.add('danger', 'application was not deleted! No access...');
                    break;
                case 404:  /* 404 No access */
                    Messages.add('danger', 'application was not deleted! No access...');
                    break;
                case 409:  /* 409 Conflict - user exists or was double posted */
                    Messages.add('danger', 'application was not deleted! Already exists...');
                    break;
                default:
                    Messages.add('danger', 'application was not deleted and! Try again later...');
            }
            $scope.activateTimeoutModal();
        });
        return this;
    };

});<commit_msg>trial and error<commit_after>UseradminApp.service('Applications', function($http,Messages){

    var defaultlist = [
        {
            "id": "1",
            "name": "UserAdmin",
            "defaultRole": "UserAdmin",
            "defaultOrgid": "Whydah",
            "availableOrgIds": null
        },
        {
            "id": "2",
            "name": "Mobilefirst",
            "defaultRole": "client",
            "defaultOrgid": "Altran",
            "availableOrgIds": null
        },
        {
            "id": "3",
            "name": "Whydah",
            "defaultRole": "developer",
            "defaultOrgid": "Whydah",
            "availableOrgIds": null
        }
    ];

    var wishlist = {
        applicationId: 1,
        applicationName: 'name',
        defaultRole: 'role',
        defaultRoleValue: 'value',
        defaultOrg: 'org1',
        organisations: [
            'org1',
            'org2',
            'org3'
        ]
    }

    this.list = [];
    this.selected = false;

    this.search = function() {
        console.log('Searching for applications...');
        var that = this;
        $http({
            method: 'GET',
            url: baseUrl + 'applications'
        }).success(function (data) {
            that.list = data;
        });
        return this;
    };

     this.search2 = function(searchQuery) {
        console.log('Searching for applications...');
        this.searchQuery = searchQuery || '*';
         var that = this;
         $http({
            method: 'GET',
            url: baseUrl+'applications/find/'+this.searchQuery
            //url: 'json/users.json',
         }).success(function (data) {
            that.list = data;
         }).error(function(data,status){
         // This is most likely due to usertoken timeout - TODO: Redirect to login webapp
         console.log('Unable to search', data);
         switch (status) {
            case 403: // Forbidden
               Messages.add('danger', 'Unable to seach! Forbidden...');
               break;
            case 404:  // 404 No access
               Messages.add('danger', 'Unable to search! No access...');
               break;
            case 409:  // 409 Conflict - will prbably not occur here
               Messages.add('danger', 'Search already exists...');
               break;
            default:
               Messages.add('danger', 'Search failed with error code: ' + status);
          }

          });
        return this;
     };

    function buildRoleNames(application) {
        var roleNames = [];
        if (application.hasOwnProperty("roles")) {
            if (application.roles && application.roles.length) {
                for (var i = 0; i < application.roles.length; i++) {
                    var role = application.roles[i];
                    roleNames.push(role.name);
                }
            }
        }
        return roleNames;
    }
    function buildOrgNames(application) {
        var orgNames = [];
        if (application.hasOwnProperty("organizationNames")) {
            if (application.organizationNames && application.organizationNames.length) {
                for (var i = 0; i < application.organizationNames.length; i++) {
                    var org = application.organizationNames[i];
                    orgNames.push(org.name);
                }
            }
        }
        return orgNames;
    }

    this.get = function(id, callback) {
        console.log('Getting Application with id=', id);
        var that = this;
        $http({
            method: 'GET',
            url: baseUrl+'application/'+id+'/'
        }).success(function (data) {
            console.log('Got applicaton', data);
            that.application = data;
            that.application.secret = data.security.secret;
            that.application.applicationJson = JSON.stringify(data);
            that.application.roleNames = buildRoleNames(that.application);
            that.application.orgNames = buildOrgNames(that.application);
            if(callback) {
                callback(that.application);
            }
        });
        return this;
    };

    this.add = function(application, successCallback) {
        console.log('Adding application', application);
        var that = this;

        //application.security = {};
        //application.security.secret = application.secret;
        //delete application.secret;
        var postData = buildApplicationUpdate(application);
        if (postData.hasOwnProperty('name')) {
            $http({
                method: 'POST',
                url: baseUrl + 'application/',
                data: postData
            }).success(function (data) {
                Messages.add('success', 'application "' + application.name + '" was added successfully.');
                application.id = data.id;
                that.search(that.searchQuery);
                if (successCallback) {
                    successCallback();
                }
            }).error(function (data, status) {
                console.log('application was not added', data);
                switch (status) {
                    case 403:
                        Messages.add('danger', 'application was not added! No access...');
                        break;
                    case 404:  /* 404 No access */
                        Messages.add('danger', 'application was not added! No access...');
                        break;
                    case 409:  /* 409 Conflict - user exists or was double posted */
                        Messages.add('danger', 'application was not added! Already exists...');
                        break;
                    default:
                        Messages.add('danger', 'application was not added and! Try again later...');
                }
                $scope.activateTimeoutModal();
            });
        }
        return this;
    };

    this.save = function(application, successCallback) {
        console.log('Updating application', JSON.stringify(application));
        var that = this;
        var postData = buildApplicationUpdate(application);
        if (postData.hasOwnProperty('name')) {
            console.log("Save this json: " + JSON.stringify(postData));
            $http({
                method: 'PUT',
                url: baseUrl + 'application/' + application.id + '/',
                data: postData
            }).success(function (data) {
                Messages.add('success', 'application "' + application.name + '" was updated successfully.');
                application.id = data.id;
                that.search(that.searchQuery);
                if (successCallback) {
                    successCallback();
                }
            }).error(function (data, status) {
                console.log('application was not updated', data);
                switch (status) {
                    case 400:
                        Messages.add('danger','application was not updated! Please validate your form and applicationjson input.');
                        break;
                    case 403:
                        Messages.add('danger', 'application was not updated! No access...');
                        break;
                    case 404:  /* 404 No access */
                        Messages.add('danger', 'application was not updated! No access...');
                        break;
                    case 409:  /* 409 Conflict - user exists or was double posted */
                        Messages.add('danger', 'application was not updated! Already exists...');
                        break;
                    default:
                        Messages.add('danger', 'application was not updated and! Try again later...');
                }
                $scope.activateTimeoutModal();
            });
        }
        return this;
    };

    function buildApplicationUpdate(application) {
        var postData = {};
        if (application.hasOwnProperty('secret')) {
            if (application.hasOwnProperty('security')) {
                application.security.secret = application.secret;
            } else {
                application.security = {};
                application.security.secret = application.secret;
            }
            delete application.secret;
        }
        if (application.hasOwnProperty('roleNames')) {
            if (typeof application.roleNames === 'string') {
                application.roles = [];
                var roleSplit = application.roleNames.split(",");
                for (i = 0; i < roleSplit.length; i++) {
                     var role = {};
                     var item = roleSplit[i];
                     role.id = item.trim();
                     role.name = item.trim();
                     application.roles.push(role);
                }
            }
        }
        if (application.hasOwnProperty('orgNames')) {
            if (typeof application.orgNames === 'string') {
                application.organizationNames = [];
                var nameSplit = application.orgNames.split(",");
                for (i = 0; i < nameSplit.length; i++) {
                    var name = {};
                    var item = nameSplit[i];
                    name.id = item.trim();
                    name.name = item.trim();
                    application.organizationNames.push(name);
                }
            }
        }
        return application;
    }

    this.saveFromJson = function(application, successCallback) {
        console.log('Updating application from json', JSON.stringify(application.applicationJson));
        var that = this;
        var postData = {};
        if (application.applicationJson) {
            try {
                postData = JSON.parse(application.applicationJson);

                console.log("Save this json: " + JSON.stringify(postData));
                $http({
                    method: 'PUT',
                    url: baseUrl + 'application/' + application.id + '/',
                    data: postData
                }).success(function (data) {
                    Messages.add('success', 'application "' + application.name + '" was updated successfully.');
                    application.id = data.id;
                    that.search(that.searchQuery);
                    if (successCallback) {
                        successCallback();
                    }
                }).error(function (data, status) {
                    console.log('application was not updated', data);
                    switch (status) {
                        case 400:
                            Messages.add('danger','application was not updated! Please validate your form and applicationjson input.');
                            break;
                        case 403:
                            Messages.add('danger', 'application was not updated! No access...');
                            break;
                        case 404:  /* 404 No access */
                            Messages.add('danger', 'application was not updated! No access...');
                            break;
                        case 409:  /* 409 Conflict - user exists or was double posted */
                            Messages.add('danger', 'application was not updated! Already exists...');
                            break;
                        default:
                            Messages.add('danger', 'application was not updated and! Try again later...');
                    }
                    $scope.activateTimeoutModal();
                });
            } catch (e) {
                Messages.add('danger', 'Could not parse applicationJson to JSON object.');
            }
        } else {
            Messages.add('danger', 'Could not update application. ApplcationJson is missing.');
        }

        return this;
    };

    this.delete = function(application, successCallback) {
        console.log('Deleting application', JSON.stringify(application));
        var that = this;
        if (application.hasOwnProperty(secret)) {
            application.security = {};
            application.security.secret = application.secret;
            delete application.secret;
        }
        $http({
            method: 'DELETE',
            url: baseUrl+'application/'+application.id +'/'
            //data: application
        }).success(function (data) {
            Messages.add('success', 'application "'+application.name+'" was deleted.');
            application.id = data.id;
            that.search(that.searchQuery);
            if(successCallback){
                successCallback();
            }
        }).error(function(data,status){
            console.log('application was not deleted.', data, status);
            switch (status) {
                case 403:
                    Messages.add('danger', 'application was not deleted! No access...');
                    break;
                case 404:  /* 404 No access */
                    Messages.add('danger', 'application was not deleted! No access...');
                    break;
                case 409:  /* 409 Conflict - user exists or was double posted */
                    Messages.add('danger', 'application was not deleted! Already exists...');
                    break;
                default:
                    Messages.add('danger', 'application was not deleted and! Try again later...');
            }
            $scope.activateTimeoutModal();
        });
        return this;
    };

});<|endoftext|>