<commit_before>'use strict';
var _ = require('lodash');
var config = require('config');
var should = require('should');
var glob = require('glob');
var homedir = require('homedir');
var fs = require('fs');

var client = require('./lib/client.js').client;
var nav = require('./lib/nav/navigation.js')(client, config);
var dataEntry = require('./lib/dataEntry.js')(client, config);
var manage = require('./lib/manage.js')(client, config);

var micis = require('./lib/auth/micis.js')(client);

describe('navigate to asmt and fill out asmts', function() {
    this.timeout(config.defaultTimeout);

    before('initialize', function(done) {
        client.clientReady.then(function boot() {
            if (!micis.loggedOn) {
                micis.logon();
            }
            client.call(done);
        });
    });

    describe('asmt double entry without error', function() {

        // define inputs
        var asmtDetails = {
            ursi: 'M06100119',
            studyId: 2319, // NI TEST
            instrumentId: 26363, // Calculation Test
            segmentInterval: 'v3', // can vary this: visit1, v1, v2, v3, v4
            sourceType: '5',  // can vary this: 3, 4, 5, 6, 7, 8, 9
            assessmentDate: '12/24/1900', // don't change this Date, or need to make sure it's unique in resume queue
            assessmentStartTime: '10:22',
            rater1: 1341, // Abeer Ayaz
            rater2: 1162, // Abigail Quish
            siteId: '7', // MRN (default)
            dataEntryTypeId: 1, // Clinical Study (default)
            incompleteAssessment: 'successfully_completedY', // (default)
            notes: 'double entry without error'
        };

        var asmtFirstEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '3',
            asmtTestcal51: 0
        };

        var asmtSecondEntry = asmtFirstEntry;

        it ('should go to asmt and select NITEST (study_id 2319)', function(done) {
            nav.gotoAsmt();
            nav.selectAsmtStudy(asmtDetails.studyId, done);
        });

        it ('should navigate to DATA ENTRY > New Assessment', function(done) {
            nav.asmtMenu
                .clickNested('New Assessment', done);
        });

        it ('should not see AASE instrument in the instrument list', function(done) {
            // 1995, 31563 are instrument ids for AASE instruments
            client.isExisting('select#instrument_id option[value="1995"]').should.be.fulfilledWith(false);
            client.isExisting('select#instrument_id option[value="31563"]').should.be.fulfilledWith(false);
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363)', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should not see specialvisit option in visit dropdown list', function(done) {
            client.isExisting('select#segment_interval option[value="specialvisit"]').should.be.fulfilledWith(false);
            client.call(done);
        });

        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should partially fill in assessment, then save and escape', function(done) {
            // partially fill in asmt, save, escape
            dataEntry.partiallyFillCalTestAsmt(asmtFirstEntry, done);
        });

        it ('should navigate to DATA ENTRY > Resume Entry', function(done) {
            nav.asmtMenu
                .clickNested('Resume Entry', done);
        });

        it ('should resume the assessment which was just escaped', function(done) {
            // go to resume queue, click the escaped asmt
            const asmtDate = asmtDetails.assessmentDate.replace(/\//g, '-');
            dataEntry.resumeEntry(asmtDate, done);
        });

        it ('should enter the resumed assessment', function(done) {
            // click the button to enter resumed assessment
            dataEntry.enterResumedEntry(done);
        });

        it ('should fill in assessment first entry', function(done) {
            // fill assessment 1 First Entry
            dataEntry.fillCalculationTestAsmt(asmtFirstEntry, done);
        });

        it ('should begin a new assessment', function(done) {
            dataEntry.beginNewAssessment();
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363) for the second time', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        // After escape-resume, the coversheet info lost. Need to re-fill in.
        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should fill in assessment second entry', function(done) {
            // fill assessment 1 Seond Entry
            dataEntry.fillCalculationTestAsmt(asmtSecondEntry, done);
        });

        it ('should navigate to MANAGE > Search Assessments', function(done) {
            nav.asmtMenu
                .clickNested('Search Assessments', done);
        });

        it ('should fill assessment search criteria and click search button', function(done) {
            manage.fillAsmtSearchCriteria(asmtDetails, done);
        });

        /**
         * We did not create a profile for the browser to NOT ASK BEFORE DOWNLOADING.
         * So, in order for this test to be successful, you need to make sure the popup window
         * not shown up. To do this, try manually downloading the file in the testing browser,
         * when the window pops up for you to confirm the download, check the checkbox saying
         * "Do this automatically for files like this from now on" and click "OK" to download
         * the data. Once this is done, this test should be able to pass. This only needs to
         * be done once in the testing browser.
         */
        it ('should select all assessments and download them', function(done) {
            manage.downloadAsmt(done);
        });

        it ('should check if the downloaded file exists', function(done) {
            // check download folder to see if the file exists
            let exists = false;
            glob.sync(homedir() + '/Downloads/assessmentsResults*.csv').forEach(function(file) {
                // check if any file download within 30 seconds
                if ((new Date).getTime() - fs.statSync(file).ctime.getTime() < 30*1000) {
                    exists = true;
                }
            });
            if (!exists) {
                throw new Error('Assessment download failed.');
            }
            client.call(done);
        });

        it ('should select "responses" button in order to view assessment responses', function(done) {
            manage.clickAsmtResponsesButton(done);
        });

        it ('should find auto calc that matches: 10.760204081633', function (done) {
            manage.verifyAutoCalcResponseExists(done);
        });

    });

    // This is very very similar to the above test with only a few slight changes
    describe('asmt double entry with entry error and entry error correction', function() {

        // define inputs
        var asmtDetails = {
            ursi: 'M06100119',
            studyId: 2319, // NI TEST
            instrumentId: 26363, // Calculation Test
            segmentInterval: 'v2', // can vary this: visit1, v1, v2, v3, v4
            sourceType: '8',  // can vary this: 3, 4, 5, 6, 7, 8, 9
            assessmentDate: '10/22/1953',
            assessmentStartTime: '11:22',
            rater1: 1341, // Abeer Ayaz
            rater2: 1162, // Abigail Quish
            siteId: '7', // MRN (default)
            dataEntryTypeId: 1, // Clinical Study (default)
            incompleteAssessment: 'successfully_completedY', // (default)
            notes: 'double entry with error...'
        };

        var asmtFirstEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '3',
            asmtTestcal51: 0
        };

        var asmtSecondEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '2', // this is the error we are introducing
            asmtTestcal51: 0
        };

        it ('should navigate to DATA ENTRY > New Assessment', function(done) {
            nav.asmtMenu
                .clickNested('New Assessment', done);
        });

        it ('should select Calculation Test (instrument_id 26363)', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should fill in assessment first entry', function(done) {
            // fill assessment 1 First Entry
            dataEntry.fillCalculationTestAsmt(asmtFirstEntry, done);
        });

        it ('should begin a new assessment', function(done) {
            dataEntry.beginNewAssessment();
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363) for the second time', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should click the next button for the first section of the Data Entry: Cover Sheet form', function(done) {
            // click the next button and wait for pagination to complete
            dataEntry.clickCoverSheetNextButton(done);
        });

        it ('should click the next button for the second section of the Data Entry: Cover Sheet form', function(done) {
            // click the next button a second time and wait for pagination to complete
            dataEntry.clickCoverSheetNextButton(done);
        });

        it ('should fill in assessment second entry', function(done) {
            // fill assessment 1 Seond Entry
            dataEntry.fillCalculationTestAsmt(asmtSecondEntry, done);
        });

        it ('should navigate to MANAGE > View Conflicts', function(done) {
            nav.asmtMenu
                .clickNested('View Conflicts', done);
        });

        it ('should search for and find the asmt conflict', function(done) {
            manage.findAsmtConflict(asmtDetails, done);
        });

        it ('should fix the error, then resolve the conflict', function(done) {
            manage.fixAndResolveConflict(done);
        });

        it ('should navigate to MANAGE > Search Assessments', function(done) {
            nav.asmtMenu
                .clickNested('Search Assessments', done);
        });

        it ('should fill assessment search criteria and click search button', function(done) {
            manage.fillAsmtSearchCriteria(asmtDetails, done);
        });

        it ('should select "responses" button in order to view assessment responses', function(done) {
            manage.clickAsmtResponsesButton(done);
        });

        it ('should find auto calc that matches: 10.760204081633', function (done) {
            manage.verifyAutoCalcResponseExists(done);
        });

    });

});

<commit_msg>make tests idempotent by generating a random date and random time that way you can run it multiple times in a row<commit_after>'use strict';
var _ = require('lodash');
var config = require('config');
var should = require('should');
var glob = require('glob');
var homedir = require('homedir');
var fs = require('fs');

var client = require('./lib/client.js').client;
var nav = require('./lib/nav/navigation.js')(client, config);
var dataEntry = require('./lib/dataEntry.js')(client, config);
var manage = require('./lib/manage.js')(client, config);

var micis = require('./lib/auth/micis.js')(client);

/**
 * Random Time Generator
 *
 * Returns a time between 00:00 and 23:59
 * @return {String} 24-format HH:MM
 */
const getRandomTime = () => {
  // Minute: 00-59
  let min = Math.floor(Math.random() * 59).toString();
  min = min.length === 1 ? `0${min}` : min;

  // Hour: 00-23
  let hour = Math.floor(Math.random() * 23).toString();
  hour = hour.length === 1 ? `0${hour}` : hour;

  return `${hour}:${min}`;
}

/**
 * Random Date Generator
 *
 * Returns a date between 01/01/1900 and 12/28/1980
 * @return {String} MM/DD/YYYY
 */
const getRandomDate = () => {
  // Day: 01 - 28
  let day = Math.floor(Math.random() * 27 + 1).toString();
  day = day.length === 1 ? `0${day}` : day;

  // Month: 01 - 12
  let month = Math.floor(Math.random() * 11 + 1).toString();
  month = month.length === 1 ? `0${month}` : month;

  // Year: 00 - 80
  let year = Math.floor(Math.random() * 80).toString();
  year = year.length === 1 ? `0${year}` : year;

  return `${month}/${day}/19${year}`;
}

describe('navigate to asmt and fill out asmts', function() {
    this.timeout(config.defaultTimeout);

    before('initialize', function(done) {
        client.clientReady.then(function boot() {
            if (!micis.loggedOn) {
                micis.logon();
            }
            client.call(done);
        });
    });

    describe('asmt double entry without error', function() {

        // define inputs
        var asmtDetails = {
            ursi: 'M06100119',
            studyId: 2319, // NI TEST
            instrumentId: 26363, // Calculation Test
            segmentInterval: 'v3', // can vary this: visit1, v1, v2, v3, v4
            sourceType: '5',  // can vary this: 3, 4, 5, 6, 7, 8, 9
            assessmentDate: getRandomDate(),
            assessmentStartTime: getRandomTime(),
            rater1: 1341, // Abeer Ayaz
            rater2: 1162, // Abigail Quish
            siteId: '7', // MRN (default)
            dataEntryTypeId: 1, // Clinical Study (default)
            incompleteAssessment: 'successfully_completedY', // (default)
            notes: 'double entry without error'
        };

        var asmtFirstEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '3',
            asmtTestcal51: 0
        };

        var asmtSecondEntry = asmtFirstEntry;

        it ('should go to asmt and select NITEST (study_id 2319)', function(done) {
            nav.gotoAsmt();
            nav.selectAsmtStudy(asmtDetails.studyId, done);
        });

        it ('should navigate to DATA ENTRY > New Assessment', function(done) {
            nav.asmtMenu
                .clickNested('New Assessment', done);
        });

        it ('should not see AASE instrument in the instrument list', function(done) {
            // 1995, 31563 are instrument ids for AASE instruments
            client.isExisting('select#instrument_id option[value="1995"]').should.be.fulfilledWith(false);
            client.isExisting('select#instrument_id option[value="31563"]').should.be.fulfilledWith(false);
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363)', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should not see specialvisit option in visit dropdown list', function(done) {
            client.isExisting('select#segment_interval option[value="specialvisit"]').should.be.fulfilledWith(false);
            client.call(done);
        });

        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should partially fill in assessment, then save and escape', function(done) {
            // partially fill in asmt, save, escape
            dataEntry.partiallyFillCalTestAsmt(asmtFirstEntry, done);
        });

        it ('should navigate to DATA ENTRY > Resume Entry', function(done) {
            nav.asmtMenu
                .clickNested('Resume Entry', done);
        });

        it ('should resume the assessment which was just escaped', function(done) {
            // go to resume queue, click the escaped asmt
            const asmtDate = asmtDetails.assessmentDate.replace(/\//g, '-');
            dataEntry.resumeEntry(asmtDate, done);
        });

        it ('should enter the resumed assessment', function(done) {
            // click the button to enter resumed assessment
            dataEntry.enterResumedEntry(done);
        });

        it ('should fill in assessment first entry', function(done) {
            // fill assessment 1 First Entry
            dataEntry.fillCalculationTestAsmt(asmtFirstEntry, done);
        });

        it ('should begin a new assessment', function(done) {
            dataEntry.beginNewAssessment();
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363) for the second time', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        // After escape-resume, the coversheet info lost. Need to re-fill in.
        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should fill in assessment second entry', function(done) {
            // fill assessment 1 Seond Entry
            dataEntry.fillCalculationTestAsmt(asmtSecondEntry, done);
        });

        it ('should navigate to MANAGE > Search Assessments', function(done) {
            nav.asmtMenu
                .clickNested('Search Assessments', done);
        });

        it ('should fill assessment search criteria and click search button', function(done) {
            manage.fillAsmtSearchCriteria(asmtDetails, done);
        });

        /**
         * We did not create a profile for the browser to NOT ASK BEFORE DOWNLOADING.
         * So, in order for this test to be successful, you need to make sure the popup window
         * not shown up. To do this, try manually downloading the file in the testing browser,
         * when the window pops up for you to confirm the download, check the checkbox saying
         * "Do this automatically for files like this from now on" and click "OK" to download
         * the data. Once this is done, this test should be able to pass. This only needs to
         * be done once in the testing browser.
         */
        it ('should select all assessments and download them', function(done) {
            manage.downloadAsmt(done);
        });

        it ('should check if the downloaded file exists', function(done) {
            // check download folder to see if the file exists
            let exists = false;
            glob.sync(homedir() + '/Downloads/assessmentsResults*.csv').forEach(function(file) {
                // check if any file download within 30 seconds
                if ((new Date).getTime() - fs.statSync(file).ctime.getTime() < 30*1000) {
                    exists = true;
                }
            });
            if (!exists) {
                throw new Error('Assessment download failed.');
            }
            client.call(done);
        });

        it ('should select "responses" button in order to view assessment responses', function(done) {
            manage.clickAsmtResponsesButton(done);
        });

        it ('should find auto calc that matches: 10.760204081633', function (done) {
            manage.verifyAutoCalcResponseExists(done);
        });

    });

    // This is very very similar to the above test with only a few slight changes
    describe('asmt double entry with entry error and entry error correction', function() {

        // define inputs
        var asmtDetails = {
            ursi: 'M06100119',
            studyId: 2319, // NI TEST
            instrumentId: 26363, // Calculation Test
            segmentInterval: 'v2', // can vary this: visit1, v1, v2, v3, v4
            sourceType: '8',  // can vary this: 3, 4, 5, 6, 7, 8, 9
            assessmentDate: getRandomDate(),
            assessmentStartTime: getRandomTime(),
            rater1: 1341, // Abeer Ayaz
            rater2: 1162, // Abigail Quish
            siteId: '7', // MRN (default)
            dataEntryTypeId: 1, // Clinical Study (default)
            incompleteAssessment: 'successfully_completedY', // (default)
            notes: 'double entry with error...'
        };

        var asmtFirstEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '3',
            asmtTestcal51: 0
        };

        var asmtSecondEntry = {
            asmtTestcal11: '1',
            asmtTestcal21: '2',
            asmtTestcal31: '2', // this is the error we are introducing
            asmtTestcal51: 0
        };

        it ('should navigate to DATA ENTRY > New Assessment', function(done) {
            nav.asmtMenu
                .clickNested('New Assessment', done);
        });

        it ('should select Calculation Test (instrument_id 26363)', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should fill out the first 4 values of the Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 1
            dataEntry.fillCoverSheetPart1(asmtDetails, done);
        });

        it ('should fill out the remaining required inputs for Data Entry: Cover Sheet form', function(done) {
            // fill cover sheet part 2
            dataEntry.fillCoverSheetPart2(asmtDetails, done);
        });

        it ('should fill in assessment first entry', function(done) {
            // fill assessment 1 First Entry
            dataEntry.fillCalculationTestAsmt(asmtFirstEntry, done);
        });

        it ('should begin a new assessment', function(done) {
            dataEntry.beginNewAssessment();
            client.call(done);
        });

        it ('should select Calculation Test (instrument_id 26363) for the second time', function(done) {
            // select calculation test
            dataEntry.selectInstrument(asmtDetails.instrumentId, done);
        });

        it ('should click the next button for the first section of the Data Entry: Cover Sheet form', function(done) {
            // click the next button and wait for pagination to complete
            dataEntry.clickCoverSheetNextButton(done);
        });

        it ('should click the next button for the second section of the Data Entry: Cover Sheet form', function(done) {
            // click the next button a second time and wait for pagination to complete
            dataEntry.clickCoverSheetNextButton(done);
        });

        it ('should fill in assessment second entry', function(done) {
            // fill assessment 1 Seond Entry
            dataEntry.fillCalculationTestAsmt(asmtSecondEntry, done);
        });

        it ('should navigate to MANAGE > View Conflicts', function(done) {
            nav.asmtMenu
                .clickNested('View Conflicts', done);
        });

        it ('should search for and find the asmt conflict', function(done) {
            manage.findAsmtConflict(asmtDetails, done);
        });

        it ('should fix the error, then resolve the conflict', function(done) {
            manage.fixAndResolveConflict(done);
        });

        it ('should navigate to MANAGE > Search Assessments', function(done) {
            nav.asmtMenu
                .clickNested('Search Assessments', done);
        });

        it ('should fill assessment search criteria and click search button', function(done) {
            manage.fillAsmtSearchCriteria(asmtDetails, done);
        });

        it ('should select "responses" button in order to view assessment responses', function(done) {
            manage.clickAsmtResponsesButton(done);
        });

        it ('should find auto calc that matches: 10.760204081633', function (done) {
            manage.verifyAutoCalcResponseExists(done);
        });

    });

});
<|endoftext|>


<commit_before>/* eslint-disable camelcase */
const { get } = require('lodash')

const { getFormattedAddress } = require('../../../lib/address')

module.exports = function transformCompanyToListItem ({
  id,
  name,
  sector,
  uk_based,
  uk_region,
  trading_name,
  trading_address_country,
  trading_address_county,
  trading_address_town,
  trading_address_postcode,
  trading_address_1,
  trading_address_2,
  registered_address_country,
  registered_address_county,
  registered_address_town,
  registered_address_postcode,
  registered_address_1,
  registered_address_2,
  companies_house_data,
} = {}) {
  if (!id) { return }

  const meta = []

  if (trading_name) {
    meta.push({
      label: 'Trading name',
      value: trading_name,
    })
  }

  const isTradingAddress = trading_address_town && trading_address_postcode && trading_address_1
  let address

  if (isTradingAddress) {
    address = getFormattedAddress({
      address_1: trading_address_1,
      address_2: trading_address_2,
      address_town: trading_address_town,
      address_county: trading_address_county,
      address_postcode: trading_address_postcode,
      address_country: trading_address_country,
    })
  } else {
    address = getFormattedAddress({
      address_1: registered_address_1,
      address_2: registered_address_2,
      address_town: registered_address_town,
      address_county: registered_address_county,
      address_postcode: registered_address_postcode,
      address_country: registered_address_country,
    })
  }

  if (sector) {
    meta.push({
      label: 'Sector',
      value: get(sector, 'name'),
    })
  }

  if (trading_address_country || registered_address_country) {
    meta.push({
      label: 'Country',
      type: 'badge',
      value: get(trading_address_country, 'name') || get(registered_address_country, 'name'),
    })
  }

  if (uk_based) {
    meta.push({
      label: 'UK region',
      type: 'badge',
      value: get(uk_region, 'name'),
    })
  }

  if (address) {
    meta.push({
      label: isTradingAddress ? 'Trading address' : 'Registered address',
      value: address,
    })
  }

  const url = id ? `/companies/${id}` : `/companies/view/ch/${companies_house_data.company_number}`

  return {
    id,
    name,
    url,
    meta,
    type: 'company',
  }
}
<commit_msg>Update company list to use getCompanyAddress<commit_after>/* eslint-disable camelcase */
const { get } = require('lodash')

const { getCompanyAddress } = require('./shared')

module.exports = function transformCompanyToListItem ({
  id,
  name,
  sector,
  uk_based,
  uk_region,
  trading_name,
  trading_address_country,
  trading_address_county,
  trading_address_town,
  trading_address_postcode,
  trading_address_1,
  trading_address_2,
  registered_address_country,
  registered_address_county,
  registered_address_town,
  registered_address_postcode,
  registered_address_1,
  registered_address_2,
  companies_house_data,
} = {}) {
  if (!id) { return }

  const meta = []

  if (trading_name) {
    meta.push({
      label: 'Trading name',
      value: trading_name,
    })
  }

  const address = getCompanyAddress({
    trading_address_country,
    trading_address_county,
    trading_address_town,
    trading_address_postcode,
    trading_address_1,
    trading_address_2,
    registered_address_country,
    registered_address_county,
    registered_address_town,
    registered_address_postcode,
    registered_address_1,
    registered_address_2,
  })

  if (sector) {
    meta.push({
      label: 'Sector',
      value: get(sector, 'name'),
    })
  }

  if (trading_address_country || registered_address_country) {
    meta.push({
      label: 'Country',
      type: 'badge',
      value: get(trading_address_country, 'name') || get(registered_address_country, 'name'),
    })
  }

  if (uk_based) {
    meta.push({
      label: 'UK region',
      type: 'badge',
      value: get(uk_region, 'name'),
    })
  }

  meta.push(address)

  const url = id ? `/companies/${id}` : `/companies/view/ch/${companies_house_data.company_number}`

  return {
    id,
    name,
    url,
    meta,
    type: 'company',
  }
}
<|endoftext|>


<commit_before>"use strict";

/*
 * container
 */
var container = {};

$.extend(container, {
    table: null,

    list: function(options) {
        options = options || {};

        $.ajax({
            type: 'POST',
            url: '/containers/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // console.log(data);
            _.each(data.containers, function(container_) {
                container._add(container_);
            });
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },

    _add: function(container_) {
        var tbody = container.table.find('tbody');
        var tr_template = _.template($('#table-row-container').html());

        var tr = $(tr_template(container_))
            .appendTo(tbody);

        // activate
        tr.find('a#activate').click(function(e) {
            // update container
            var _container = {
                id: container_.id,
                active: true,
            };

            $.ajax({
                type: 'POST',
                url: '/container/update',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                // required to fix variable "container" from closure
                _.each(_container, function(value, key) { container_[key] = value; });

                // update UI
                container._update(data.container);
                $.bootstrapGrowl('Volume activated.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        // deactivate
        tr.find('a#deactivate').click(function(e) {
            // update container
            var _container = {
                id: container_.id,
                active: false,
            };

            $.ajax({
                type: 'POST',
                url: '/container/update',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                // required to fix variable "container" from closure
                _.each(_container, function(value, key) { container_[key] = value; });

                // update UI
                container._update(data.container);
                $.bootstrapGrowl('Volume deactivated.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        // remove
        tr.find('a#remove').click(function(e) {
            $.ajax({
                type: 'POST',
                url: '/container/remove',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    id: container_.id,
                }),
            })
            .done(function(data) {
                tr.remove();
                $.bootstrapGrowl('User successfully removed.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });
    },

    add: function(options) {
        options = options || {};
        var new_template = _.template($('#modal-new-container').html());
        var modal_div = $(new_template());
        var host_id_select = modal_div.find('#host_id');
        var image_id_select = modal_div.find('#image_id');

        // populate hosts
        container._populate_hosts(host_id_select);

        // populate images
        container._populate_images(image_id_select);

        // close
        modal_div.find('button#close').click(function(e) {
            // close modal
            modal_div.modal('hide');
            setTimeout(function() { modal_div.remove();}, 500);
            $('.modal-backdrop').remove();
        });

        // update
        modal_div.find('button#create').click(function(e) {
            // close modal
            modal_div.modal('hide');
            setTimeout(function() { modal_div.remove();}, 500);
            $('.modal-backdrop').remove();

            // create container
            var _container = {
                name: modal_div.find('#name').val(),
                host_id: modal_div.find('#host_id').val(),
                image_id: modal_div.find('#image_id').val(),
                command: modal_div.find('#command').val(),
                volumes: modal_div.find('#volumes').val(),
                volumes_from: modal_div.find('#volumes_from').val(),
                env_vars: modal_div.find('#env_vars').val(),
                expose_ports: modal_div.find('#expose_ports').val(),
                publish_ports: modal_div.find('#publish_ports').val(),
                link_containers: modal_div.find('#link_containers').val(),
                ram_limit: modal_div.find('#ram_limit').val(),
                n_cpu_cores: modal_div.find('#n_cpu_cores').val(),
                cpu_share: modal_div.find('#cpu_share').val(),
                status: modal_div.find('#status').val(),
            };

            $.ajax({
                type: 'POST',
                url: '/container/create',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                container._add(data.container);
                $.bootstrapGrowl('Volume successfully created.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        modal_div.modal({
            backdrop: 'static',
        });
    },

    _update: function(container_) {
        var tr = $('tr[data-id="' + container_.id + '"]');

        _.each(container_, function(value, key) {
            if (key === 'id') return;
            var td = tr.find('td#' + key);
            td.text(value);
        });
    },

    _populate_hosts: function(host_id_select, host_id) {
        host_id_select.empty();

        // populate hosts
        $.ajax({
            type: 'POST',
            url: '/hosts/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // handled error
            if (data.error) {
                $.bootstrapGrowl(data.error, {type: 'info', align: 'center'});
                return;
            }

            // console.log(data);
            var option = $('<option>')
                .attr('value', '')
                .text('')
                .appendTo(host_id_select);

            _.each(data.hosts, function(host_) {
                var option = $('<option>')
                    .attr('value', host_.id)
                    .text(host_.name)
                    .appendTo(host_id_select);
            });

            // select host
            if (!!host_id) {
                host_id_select.val(host_id);
            }
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },

    _populate_images: function(image_id_select, image_id) {
        $.ajax({
            type: 'POST',
            url: '/images/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // console.log(data);
            _.each(data.images, function(image_) {
                var option = $('<option>')
                    .attr('value', image_.id)
                    .text(image_.name)
                    .appendTo(image_id_select);
            });

            if (!!image_id) {
                image_id_select.val(image_id);
            }
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },
});

<commit_msg>container volume<commit_after>"use strict";

/*
 * container
 */
var container = {};

$.extend(container, {
    table: null,

    list: function(options) {
        options = options || {};

        $.ajax({
            type: 'POST',
            url: '/containers/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // console.log(data);
            _.each(data.containers, function(container_) {
                container._add(container_);
            });
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },

    add: function(options) {
        options = options || {};
        var new_template = _.template($('#modal-new-container').html());
        var modal_div = $(new_template());
        var host_id_select = modal_div.find('#host_id');
        var image_id_select = modal_div.find('#image_id');
        var volumes_select = modal_div.find('#volumes');

        // populate hosts
        container._populate_hosts(host_id_select);

        // populate images
        container._populate_images(image_id_select);

        // populate volumes
        container._populate_volumes(volumes_select);

        // close
        modal_div.find('button#close').click(function(e) {
            // close modal
            modal_div.modal('hide');
            setTimeout(function() { modal_div.remove();}, 500);
            $('.modal-backdrop').remove();
        });

        // update
        modal_div.find('button#create').click(function(e) {
            // close modal
            modal_div.modal('hide');
            setTimeout(function() { modal_div.remove();}, 500);
            $('.modal-backdrop').remove();

            // create container
            var _container = {
                name: modal_div.find('#name').val(),
                host_id: modal_div.find('#host_id').val(),
                image_id: modal_div.find('#image_id').val(),
                command: modal_div.find('#command').val(),
                volumes: modal_div.find('#volumes').val(),
                // volumes: modal_div.find('#volumes').val(),
                // volumes_from: modal_div.find('#volumes_from').val(),
                env_vars: modal_div.find('#env_vars').val(),
                expose_ports: modal_div.find('#expose_ports').val(),
                publish_ports: modal_div.find('#publish_ports').val(),
                // link_containers: modal_div.find('#link_containers').val(),
                ram_limit: modal_div.find('#ram_limit').val(),
                n_cpu_cores: modal_div.find('#n_cpu_cores').val(),
                // cpu_share: modal_div.find('#cpu_share').val(),
                status: modal_div.find('#status').val(),
            };

            $.ajax({
                type: 'POST',
                url: '/container/create',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                container._add(data.container);
                $.bootstrapGrowl('Volume successfully created.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        modal_div.modal({
            backdrop: 'static',
        });
    },

    _add: function(container_) {
        var tbody = container.table.find('tbody');
        var tr_template = _.template($('#table-row-container').html());

        var tr = $(tr_template(container_))
            .appendTo(tbody);

        // activate
        tr.find('a#activate').click(function(e) {
            // update container
            var _container = {
                id: container_.id,
                active: true,
            };

            $.ajax({
                type: 'POST',
                url: '/container/update',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                // required to fix variable "container" from closure
                _.each(_container, function(value, key) { container_[key] = value; });

                // update UI
                container._update(data.container);
                $.bootstrapGrowl('Volume activated.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        // deactivate
        tr.find('a#deactivate').click(function(e) {
            // update container
            var _container = {
                id: container_.id,
                active: false,
            };

            $.ajax({
                type: 'POST',
                url: '/container/update',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    container: _container,
                }),
            })
            .done(function(data) {
                // required to fix variable "container" from closure
                _.each(_container, function(value, key) { container_[key] = value; });

                // update UI
                container._update(data.container);
                $.bootstrapGrowl('Volume deactivated.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });

        // remove
        tr.find('a#remove').click(function(e) {
            $.ajax({
                type: 'POST',
                url: '/container/remove',
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                data: JSON.stringify({
                    id: container_.id,
                }),
            })
            .done(function(data) {
                tr.remove();
                $.bootstrapGrowl('User successfully removed.', {type: 'success', align: 'center'});
            })
            .error(function (xhr, ajaxOptions, thrownError) {
                $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
            });
        });
    },

    _update: function(container_) {
        var tr = $('tr[data-id="' + container_.id + '"]');

        _.each(container_, function(value, key) {
            if (key === 'id') return;
            var td = tr.find('td#' + key);
            td.text(value);
        });
    },

    _populate_hosts: function(host_id_select, host_id) {
        host_id_select.empty();

        // populate hosts
        $.ajax({
            type: 'POST',
            url: '/hosts/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // handled error
            if (data.error) {
                $.bootstrapGrowl(data.error, {type: 'info', align: 'center'});
                return;
            }

            var option = $('<option>')
                .attr('value', '')
                .text('')
                .appendTo(host_id_select);

            _.each(data.hosts, function(host_) {
                var option = $('<option>')
                    .attr('value', host_.id)
                    .text(host_.name)
                    .appendTo(host_id_select);
            });

            // select host
            if (!!host_id) {
                host_id_select.val(host_id);
            }
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },

    _populate_images: function(image_id_select, image_id) {
        $.ajax({
            type: 'POST',
            url: '/images/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            // console.log(data);
            _.each(data.images, function(image_) {
                var option = $('<option>')
                    .attr('value', image_.id)
                    .text(image_.name)
                    .appendTo(image_id_select);
            });

            if (!!image_id) {
                image_id_select.val(image_id);
            }
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },

    _populate_volumes: function(volumes_select, volume_id) {
        $.ajax({
            type: 'POST',
            url: '/volumes/all',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            data: JSON.stringify({}),
        })
        .done(function(data) {
            var option = $('<option>')
                .attr('value', '')
                .text('')
                .appendTo(volumes_select);

            _.each(data.volumes, function(volume_) {
                var option = $('<option>')
                    .attr('value', volume_.id)
                    .text(volume_.name)
                    .appendTo(volumes_select);
            });

            if (!!volume_id) {
                volumes_select.val(volume_id);
            }
        })
        .error(function (xhr, ajaxOptions, thrownError) {
            $.bootstrapGrowl('Oops, something went wrong!', {type: 'info', align: 'center'});
        });
    },
});

<|endoftext|>


<commit_before>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var PropTypes = window.shared.PropTypes;
  var ReactSelect = window.Select;
  var Datepicker = window.shared.Datepicker;
  var serviceColor = window.shared.serviceColor;

  var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown;

  var styles = {
    dialog: {
      border: '1px solid #ccc',
      borderRadius: 2,
      padding: 20,
      marginBottom: 20,
      marginTop: 10
    },
    cancelRecordServiceButton: { // overidding CSS
      color: 'black',
      background: '#eee',
      marginLeft: 10,
      marginRight: 10
    },
    datepickerInput: {
      fontSize: 14,
      padding: 5,
      width: '50%'
    },
    serviceButton: {
      background: '#eee', // override CSS
      color: 'black'
    },
    buttonWidth: {
      width: '12em',
      fontSize: 12,
      padding: 8
    }
  };

  /*
  Pure UI form for recording that a student is receiving a service.
  Tracks its own local state and submits values to prop callbacks.
  */
  var RecordService = window.shared.RecordService = React.createClass({
    displayName: 'RecordService',

    propTypes: {
      studentFirstName: React.PropTypes.string.isRequired,
      onSave: React.PropTypes.func.isRequired,
      onCancel: React.PropTypes.func.isRequired,
      requestState: PropTypes.nullable(React.PropTypes.string.isRequired),

      // context
      nowMoment: React.PropTypes.object.isRequired,
      serviceTypesIndex: React.PropTypes.object.isRequired,
      educatorsIndex: React.PropTypes.object.isRequired,
      educatorsForServicesDropdown: React.PropTypes.array.isRequired,
      currentEducator: React.PropTypes.object.isRequired
    },

    getInitialState: function() {
      return {
        serviceTypeId: null,
        providedByEducatorName: null,
        momentStarted: moment.utc() // TODO should thread through
      }
    },

    onDateChanged: function(dateText) {
      var textMoment = moment.utc(dateText, 'MM/DD/YYYY');
      var updatedMoment = (textMoment.isValid()) ? textMoment : null;
      this.setState({ momentStarted: updatedMoment });
    },

    onProvidedByEducatorChanged: function(event) {
      this.setState({ providedByEducatorName: event.target.value });
    },

    onServiceClicked: function(serviceTypeId, event) {
      this.setState({ serviceTypeId: serviceTypeId });
    },

    onClickCancel: function(event) {
      this.props.onCancel();
    },

    onClickSave: function(event) {
      // Get the value of the autocomplete input
      this.props.onSave({
        serviceTypeId: this.state.serviceTypeId,
        providedByEducatorName: this.state.providedByEducatorName,
        dateStartedText: this.state.momentStarted.format('YYYY-MM-DD'),
        recordedByEducatorId: this.props.currentEducator.id
      });
    },

    render: function() {
      return dom.div({ className: 'RecordService', style: styles.dialog },
        this.renderWhichService(),
        this.renderWhoAndWhen(),
        this.renderButtons()
      );
    },

    renderWhichService: function() {
      return dom.div({},
        dom.div({ style: { marginBottom: 5 } }, 'Which service?'),
        dom.div({ style: { display: 'flex', justifyContent: 'flex-start' } },
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(505),
            this.renderServiceButton(506)
          ),
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(507),
            this.renderServiceButton(508)
          ),
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(502),
            this.renderServiceButton(503),
            this.renderServiceButton(504)
          )
        )
      );
    },

    renderServiceButton: function(serviceTypeId, options) {
      var serviceText = this.props.serviceTypesIndex[serviceTypeId].name;
      var color = serviceColor(serviceTypeId);

      return dom.button({
        className: 'btn service-type',
        onClick: this.onServiceClicked.bind(this, serviceTypeId),
        tabIndex: -1,
        style: merge(styles.serviceButton, styles.buttonWidth, {
          background: color,
          opacity: (this.state.serviceTypeId === null || this.state.serviceTypeId === serviceTypeId) ? 1 : 0.25,
          border: (this.state.serviceTypeId === serviceTypeId)
            ? '4px solid rgba(49, 119, 201, 0.75)'
            : '4px solid white'
        })
      }, serviceText);
    },

    renderEducatorSelect: function() {
      return createEl(ProvidedByEducatorDropdown, {
        educatorsForServicesDropdown: this.props.educatorsForServicesDropdown,
        onChange: this.onProvidedByEducatorChanged
      });
    },

    renderWhoAndWhen: function() {
      return dom.div({},
        dom.div({ style: { marginTop: 20 } },
          dom.div({}, 'Who is working with ' + this.props.studentFirstName + '?'),
          dom.div({ style: { width: '50%' } }, this.renderEducatorSelect())
        ),
        dom.div({ style: { marginTop: 20 } }, 'When did they start?'),
        createEl(Datepicker, {
          styles: { input: styles.datepickerInput },
          defaultValue: (this.state.momentStarted && this.state.momentStarted.format('MM/DD/YYYY')),
          onChange: this.onDateChanged,
          datepickerOptions: {
            showOn: 'both',
            dateFormat: 'mm/dd/yy',
            minDate: undefined
          }
        })
      );
    },

    renderButtons: function() {
      var isFormComplete = (this.state.serviceTypeId && this.state.momentStarted);
      return dom.div({ style: { marginTop: 15 } },
        dom.button({
          style: {
            marginTop: 20,
            background: (isFormComplete) ? undefined : '#ccc'
          },
          disabled: !isFormComplete,
          className: 'btn save',
          onClick: this.onClickSave
        }, 'Record service'),
        dom.button({
          className: 'btn cancel',
          style: styles.cancelRecordServiceButton,
          onClick: this.onClickCancel
        }, 'Cancel'),
        (this.props.requestState === 'pending') ? dom.span({}, 'Saving...') : null,
        (this.props.requestState === 'error') ? dom.span({}, 'Try again!') : null
      );
    }
  });
})();
<commit_msg>Widen input box<commit_after>(function() {
  window.shared || (window.shared = {});
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var PropTypes = window.shared.PropTypes;
  var ReactSelect = window.Select;
  var Datepicker = window.shared.Datepicker;
  var serviceColor = window.shared.serviceColor;

  var ProvidedByEducatorDropdown = window.shared.ProvidedByEducatorDropdown;

  var styles = {
    dialog: {
      border: '1px solid #ccc',
      borderRadius: 2,
      padding: 20,
      marginBottom: 20,
      marginTop: 10
    },
    cancelRecordServiceButton: { // overidding CSS
      color: 'black',
      background: '#eee',
      marginLeft: 10,
      marginRight: 10
    },
    datepickerInput: {
      fontSize: 14,
      padding: 5,
      width: '50%'
    },
    serviceButton: {
      background: '#eee', // override CSS
      color: 'black'
    },
    buttonWidth: {
      width: '12em',
      fontSize: 12,
      padding: 8
    }
  };

  /*
  Pure UI form for recording that a student is receiving a service.
  Tracks its own local state and submits values to prop callbacks.
  */
  var RecordService = window.shared.RecordService = React.createClass({
    displayName: 'RecordService',

    propTypes: {
      studentFirstName: React.PropTypes.string.isRequired,
      onSave: React.PropTypes.func.isRequired,
      onCancel: React.PropTypes.func.isRequired,
      requestState: PropTypes.nullable(React.PropTypes.string.isRequired),

      // context
      nowMoment: React.PropTypes.object.isRequired,
      serviceTypesIndex: React.PropTypes.object.isRequired,
      educatorsIndex: React.PropTypes.object.isRequired,
      educatorsForServicesDropdown: React.PropTypes.array.isRequired,
      currentEducator: React.PropTypes.object.isRequired
    },

    getInitialState: function() {
      return {
        serviceTypeId: null,
        providedByEducatorName: null,
        momentStarted: moment.utc() // TODO should thread through
      }
    },

    onDateChanged: function(dateText) {
      var textMoment = moment.utc(dateText, 'MM/DD/YYYY');
      var updatedMoment = (textMoment.isValid()) ? textMoment : null;
      this.setState({ momentStarted: updatedMoment });
    },

    onProvidedByEducatorChanged: function(event) {
      this.setState({ providedByEducatorName: event.target.value });
    },

    onServiceClicked: function(serviceTypeId, event) {
      this.setState({ serviceTypeId: serviceTypeId });
    },

    onClickCancel: function(event) {
      this.props.onCancel();
    },

    onClickSave: function(event) {
      // Get the value of the autocomplete input
      this.props.onSave({
        serviceTypeId: this.state.serviceTypeId,
        providedByEducatorName: this.state.providedByEducatorName,
        dateStartedText: this.state.momentStarted.format('YYYY-MM-DD'),
        recordedByEducatorId: this.props.currentEducator.id
      });
    },

    render: function() {
      return dom.div({ className: 'RecordService', style: styles.dialog },
        this.renderWhichService(),
        this.renderWhoAndWhen(),
        this.renderButtons()
      );
    },

    renderWhichService: function() {
      return dom.div({},
        dom.div({ style: { marginBottom: 5 } }, 'Which service?'),
        dom.div({ style: { display: 'flex', justifyContent: 'flex-start' } },
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(505),
            this.renderServiceButton(506)
          ),
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(507),
            this.renderServiceButton(508)
          ),
          dom.div({ style: styles.buttonWidth },
            this.renderServiceButton(502),
            this.renderServiceButton(503),
            this.renderServiceButton(504)
          )
        )
      );
    },

    renderServiceButton: function(serviceTypeId, options) {
      var serviceText = this.props.serviceTypesIndex[serviceTypeId].name;
      var color = serviceColor(serviceTypeId);

      return dom.button({
        className: 'btn service-type',
        onClick: this.onServiceClicked.bind(this, serviceTypeId),
        tabIndex: -1,
        style: merge(styles.serviceButton, styles.buttonWidth, {
          background: color,
          opacity: (this.state.serviceTypeId === null || this.state.serviceTypeId === serviceTypeId) ? 1 : 0.25,
          border: (this.state.serviceTypeId === serviceTypeId)
            ? '4px solid rgba(49, 119, 201, 0.75)'
            : '4px solid white'
        })
      }, serviceText);
    },

    renderEducatorSelect: function() {
      return createEl(ProvidedByEducatorDropdown, {
        educatorsForServicesDropdown: this.props.educatorsForServicesDropdown,
        onChange: this.onProvidedByEducatorChanged
      });
    },

    renderWhoAndWhen: function() {
      return dom.div({},
        dom.div({ style: { marginTop: 20 } },
          dom.div({}, 'Who is working with ' + this.props.studentFirstName + '?'),
          dom.div({}, this.renderEducatorSelect())
        ),
        dom.div({ style: { marginTop: 20 } }, 'When did they start?'),
        createEl(Datepicker, {
          styles: { input: styles.datepickerInput },
          defaultValue: (this.state.momentStarted && this.state.momentStarted.format('MM/DD/YYYY')),
          onChange: this.onDateChanged,
          datepickerOptions: {
            showOn: 'both',
            dateFormat: 'mm/dd/yy',
            minDate: undefined
          }
        })
      );
    },

    renderButtons: function() {
      var isFormComplete = (this.state.serviceTypeId && this.state.momentStarted);
      return dom.div({ style: { marginTop: 15 } },
        dom.button({
          style: {
            marginTop: 20,
            background: (isFormComplete) ? undefined : '#ccc'
          },
          disabled: !isFormComplete,
          className: 'btn save',
          onClick: this.onClickSave
        }, 'Record service'),
        dom.button({
          className: 'btn cancel',
          style: styles.cancelRecordServiceButton,
          onClick: this.onClickCancel
        }, 'Cancel'),
        (this.props.requestState === 'pending') ? dom.span({}, 'Saving...') : null,
        (this.props.requestState === 'error') ? dom.span({}, 'Try again!') : null
      );
    }
  });
})();
<|endoftext|>


<commit_before>var MapMoveEvents = function(leafletMap) {

    var _eventType = [
        "move",
        "movestart",
        "moveend",
        "drag",
        "dragstart",
        "dragend",
        "pan",
        "panstart",
        "panend",
        "rotate",
        "rotatestart",
        "rotateend",
        "tilt",
        "tiltstart",
        "tiltend",
        "zoomstart",
        "zoomend",
    ];

    var _onEvent = function(eventKey) {
        leafletMap.fire(_eventType[eventKey]);
    }

    this.setEventCallbacks = function(cameraApi) {
        cameraApi.setEventCallback(_onEvent);
    };
};
module.exports = MapMoveEvents;<commit_msg>Fixed two errors from js lint<commit_after>var MapMoveEvents = function(leafletMap) {

    var _eventType = [
        "move",
        "movestart",
        "moveend",
        "drag",
        "dragstart",
        "dragend",
        "pan",
        "panstart",
        "panend",
        "rotate",
        "rotatestart",
        "rotateend",
        "tilt",
        "tiltstart",
        "tiltend",
        "zoomstart",
        "zoomend"
    ];

    var _onEvent = function(eventKey) {
        leafletMap.fire(_eventType[eventKey]);
    };

    this.setEventCallbacks = function(cameraApi) {
        cameraApi.setEventCallback(_onEvent);
    };
};
module.exports = MapMoveEvents;<|endoftext|>


<commit_before>/* eslint-disable no-empty-function */
'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var pkg = require( './../package.json' ).name;
var isJSON = require( './../lib' );

// MAIN //

bench( pkg+'::invalid-arguments', function benchmark( b ) {
	var values;
	var bool;
	var i;

	values = [
		5,
		NaN,
		true,
		false,
		null,
		void 0,
		[],
		{},
		function noop() {}
	];

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( values[ i%values.length ] );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( isBoolean( bool ) ) {
		b.pass( 'benchmark finished' );
	} else {
		b.fail( 'should return a boolean' );
	}
	b.end();
});

bench( pkg+'::invalid-json', function benchmark( b ) {
	var bool;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( '{a":"'+String.fromCharCode( 97 + (i%26) )+'"}' );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( isBoolean( bool ) ) {
		b.pass( 'benchmark finished' );
	} else {
		b.fail( 'should return a boolean' );
	}
	b.end();
});

bench( pkg+'::valid-json', function benchmark( b ) {
	var bool;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( '{"a":"'+String.fromCharCode( 97 + (i%26) )+'"}' );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( isBoolean( bool ) ) {
		b.pass( 'benchmark finished' );
	} else {
		b.fail( 'should return a boolean' );
	}
	b.end();
});

bench( 'JSON.parse', function benchmark( b ) {
	var out;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		out = JSON.parse( '{"a":"'+String.fromCharCode( 97 + (i%26) )+'"}' );
		if ( typeof out !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( typeof out === 'object' ) {
		b.pass( 'benchmark finished' );
	} else {
		b.fail( 'should return an object' );
	}
	b.end();
});
<commit_msg>Use string utility<commit_after>/* eslint-disable no-empty-function */
'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive;
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var pkg = require( './../package.json' ).name;
var isJSON = require( './../lib' );

// MAIN //

bench( pkg+'::invalid-arguments', function benchmark( b ) {
	var values;
	var bool;
	var i;

	values = [
		5,
		NaN,
		true,
		false,
		null,
		void 0,
		[],
		{},
		function noop() {}
	];

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( values[ i%values.length ] );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( !isBoolean( bool ) ) {
		b.fail( 'should return a boolean' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::invalid-json', function benchmark( b ) {
	var bool;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( '{a":"'+fromCodePoint( 97 + (i%26) )+'"}' );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( !isBoolean( bool ) ) {
		b.fail( 'should return a boolean' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::valid-json', function benchmark( b ) {
	var bool;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		bool = isJSON( '{"a":"'+fromCodePoint( 97 + (i%26) )+'"}' );
		if ( !isBoolean( bool ) ) {
			b.fail( 'should return a boolean' );
		}
	}
	b.toc();
	if ( !isBoolean( bool ) ) {
		b.fail( 'should return a boolean' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( 'JSON.parse', function benchmark( b ) {
	var out;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		out = JSON.parse( '{"a":"'+fromCodePoint( 97 + (i%26) )+'"}' );
		if ( typeof out !== 'object' ) {
			b.fail( 'should return an object' );
		}
	}
	b.toc();
	if ( typeof out !== 'object' ) {
		b.fail( 'should return an object' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2015
 * We believe in an open Internet of Things
 */

var nedb = require('nedb');

var ASSOCIATION_DB = "urls.db";
var TEST_ASSOCIATION = { "_id": "001bc50940100000",
                         "url": "http://reelyactive.com/metadata/test.json" };

/**
 * AssociationManager Class
 * Manages the association of identifiers with URLs
 * @constructor
 */
function AssociationManager() {
  var self = this;
  this.db = new nedb({filename: ASSOCIATION_DB, autoload: true });
  this.db.insert(TEST_ASSOCIATION);
};

/**
 * Find and append any URL associated with each device identifier
 * @param {Object} identifiers List of identifiers.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.addUrls = function(identifiers, callback) {
  var self = this;
  var ids = Object.keys(identifiers);

  this.db.find({ _id: { $in: ids } }, function(err, urls) {
    var lookup = {};
    for(cUrl = 0; cUrl < urls.length; cUrl++) {
      lookup[urls[cUrl]._id] = urls[cUrl].url;
    }
    for(id in lookup) {
      identifiers[id].url = lookup[id];
    }
    for(id in identifiers) {
      if(!identifiers[id].url) {
        makeExternalAssociation(identifiers[id]);
      }
    }
    callback(identifiers);
  });
}

/**
 * Attempts to associate a device with an external API
 * https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
 * @param {Object} device The given device.
 */
function makeExternalAssociation(device) {
  if(device.identifier.type === "EUI-64") { // RA-T411
    device.url = "http://reelyactive.com/metadata/ra-t411.json";
    return
  }
  var advData = device.identifier.advData;
  var advHeader = device.identifier.advHeader;
  if(advData) {
    var complete128BitUUIDs = advData.complete128BitUUIDs;
    var nonComplete128BitUUIDs = advData.nonComplete128BitUUIDs;
    var complete16BitUUIDs = advData.complete16BitUUIDs;
    var nonComplete16BitUUIDs = advData.nonComplete16BitUUIDs;
    var uuid = complete128BitUUIDs || nonComplete128BitUUIDs ||
               complete16BitUUIDs || nonComplete16BitUUIDs;
    switch(uuid) {
      case "7265656c794163746976652055554944":  // RA-R436
        device.url = "http://reelyactive.com/metadata/ra-r436.json";
        return;
      case "2f521f8c4d6f12269c600050e4c00067":  // WNDR
        device.url = "http://reelyactive.com/metadata/wndr.json";
                     // "http://getwndr.com/reelyactive/user/" +
                     // advData.completeLocalName;
        return;
      case "d5060001a904deb947482c7f4a124842":  // MYO
        device.url = "http://reelyactive.com/metadata/myo.json";
        return;
      case "febf":  // Nod (OpenSpatial)
        device.url = "http://reelyactive.com/metadata/nod.json";
        return;
    }
    var manufacturerSpecificData = advData.manufacturerSpecificData;
    if(manufacturerSpecificData) {
      var iBeacon = manufacturerSpecificData.iBeacon;
      if(iBeacon) {
        var beaconId = iBeacon.uuid;
        switch(beaconId) {
          case "b9407f30f5f8466eaff925556b57fe6d": // Estimote
            device.url = "http://reelyactive.com/metadata/estimote.json";
            return;
          case "8deefbb9f7384297804096668bb44281": // Roximity
            device.url = "http://reelyactive.com/metadata/roximity.json";
            return;
          default:
            device.url = "http://reelyactive.com/metadata/ibeacon.json";
            return;
        }
      }
      var companyIdentifierCode = manufacturerSpecificData.companyIdentifierCode;
      switch(companyIdentifierCode) {
        case "004c": // Apple inc.
          device.url = "http://reelyactive.com/metadata/apple.json";
          return;
      }
    }
  }
  if(advHeader) {
    var type = advHeader.type;
    if(type === "SCAN_REQ") { // Curious device
      device.url = "http://reelyactive.com/metadata/curious.json";
      return;
    }
    else { // Unknown Bluetooth Smart device
      device.url = "http://reelyactive.com/metadata/bluetoothsmart.json";
    }
  }
}

/**
 * Add an association to the database
 * @param {String} id Identifier to associate.
 * @param {String} url URL to associate.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.add = function(id, url, callback) {
  var self = this;
  this.db.update({ _id: id }, { $set: { url: url } }, { upsert: true },
                 function(err, numReplaced) {
    callback();
  });
}

/**
 * Remove an association from the database
 * @param {String} id Identifier to remove.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.remove = function(id, callback) {
  var self = this;
  this.db.remove({ _id: id }, function(err, numReplaced) {
    callback();
  });
}

module.exports = AssociationManager;
<commit_msg>Added replace() and accept various identifiers<commit_after>/**
 * Copyright reelyActive 2015
 * We believe in an open Internet of Things
 */

var nedb = require('nedb');

var ASSOCIATION_DB = "urls.db";
var TEST_ASSOCIATION = { "_id": "001bc50940100000",
                         "url": "http://reelyactive.com/metadata/test.json" };

/**
 * AssociationManager Class
 * Manages the association of identifiers with URLs
 * @constructor
 */
function AssociationManager() {
  var self = this;
  this.db = new nedb({filename: ASSOCIATION_DB, autoload: true });
  this.db.insert(TEST_ASSOCIATION);
};

/**
 * Find and append any URL associated with each device identifier
 * @param {Object} identifiers List of identifiers.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.addUrls = function(identifiers, callback) {
  var self = this;
  var ids = Object.keys(identifiers);

  this.db.find({ _id: { $in: ids } }, function(err, urls) {
    var lookup = {};
    for(cUrl = 0; cUrl < urls.length; cUrl++) {
      lookup[urls[cUrl]._id] = urls[cUrl].url;
    }
    for(id in lookup) {
      identifiers[id].url = lookup[id];
    }
    for(id in identifiers) {
      if(!identifiers[id].url) {
        makeExternalAssociation(identifiers[id]);
      }
    }
    callback(identifiers);
  });
}

/**
 * Attempts to associate a device with an external API
 * https://www.bluetooth.org/en-us/specification/assigned-numbers/company-identifiers
 * @param {Object} device The given device.
 */
function makeExternalAssociation(device) {
  if(device.identifier.type === "EUI-64") { // RA-T411
    device.url = "http://reelyactive.com/metadata/ra-t411.json";
    return
  }
  var advData = device.identifier.advData;
  var advHeader = device.identifier.advHeader;
  if(advData) {
    var complete128BitUUIDs = advData.complete128BitUUIDs;
    var nonComplete128BitUUIDs = advData.nonComplete128BitUUIDs;
    var complete16BitUUIDs = advData.complete16BitUUIDs;
    var nonComplete16BitUUIDs = advData.nonComplete16BitUUIDs;
    var uuid = complete128BitUUIDs || nonComplete128BitUUIDs ||
               complete16BitUUIDs || nonComplete16BitUUIDs;
    switch(uuid) {
      case "7265656c794163746976652055554944":  // RA-R436
        device.url = "http://reelyactive.com/metadata/ra-r436.json";
        return;
      case "2f521f8c4d6f12269c600050e4c00067":  // WNDR
        device.url = "http://reelyactive.com/metadata/wndr.json";
                     // "http://getwndr.com/reelyactive/user/" +
                     // advData.completeLocalName;
        return;
      case "d5060001a904deb947482c7f4a124842":  // MYO
        device.url = "http://reelyactive.com/metadata/myo.json";
        return;
      case "febf":  // Nod (OpenSpatial)
        device.url = "http://reelyactive.com/metadata/nod.json";
        return;
    }
    var manufacturerSpecificData = advData.manufacturerSpecificData;
    if(manufacturerSpecificData) {
      var iBeacon = manufacturerSpecificData.iBeacon;
      if(iBeacon) {
        var beaconId = iBeacon.uuid;
        switch(beaconId) {
          case "b9407f30f5f8466eaff925556b57fe6d": // Estimote
            device.url = "http://reelyactive.com/metadata/estimote.json";
            return;
          case "8deefbb9f7384297804096668bb44281": // Roximity
            device.url = "http://reelyactive.com/metadata/roximity.json";
            return;
          default:
            device.url = "http://reelyactive.com/metadata/ibeacon.json";
            return;
        }
      }
      var companyIdentifierCode = manufacturerSpecificData.companyIdentifierCode;
      switch(companyIdentifierCode) {
        case "004c": // Apple inc.
          device.url = "http://reelyactive.com/metadata/apple.json";
          return;
      }
    }
  }
  if(advHeader) {
    var type = advHeader.type;
    if(type === "SCAN_REQ") { // Curious device
      device.url = "http://reelyactive.com/metadata/curious.json";
      return;
    }
    else { // Unknown Bluetooth Smart device
      device.url = "http://reelyactive.com/metadata/bluetoothsmart.json";
    }
  }
}

/**
 * Create an association in the database if it doesn't already exist
 * @param {Object} identifier Identifier(s) to associate.
 * @param {String} url URL to associate.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.create = function(identifier, url, callback) {
  var self = this;
  var association = { identifier: identifier, url: url };

  // TODO: move all this identifier handling to a utils package
  if(!identifier) {
    callback("Identifier is missing");
  }
  else if(typeof identifier === 'string') {
    association._id = identifier;
  }
  else if(identifier instanceof Array) {
    for(distinctIdentifier in identifier) {
      if((distinctIdentifier.type === "EUI-64") ||
         ((distinctIdentifier.type === "ADVA-48") &&
          (distinctIdentifier.advHeader.txAdd === "public"))) {
        association._id = distinctIdentifier.value;
      }
    }
  }
  else if((identifier.type === "EUI-64") ||
          ((identifier.type === "ADVA-48") &&
           (identifier.advHeader.txAdd === "public"))) {
    association._id = identifier.value;
  }

  this.db.insert(association, function(err, newDoc) {
    var id = null;
    if(err && (err.errorType == 'uniqueViolated')) {
      err = "Association id already exists";
    }
    if(newDoc) { id = newDoc._id; }
    callback(err, id);
  });
}

/**
 * Replace an association in the database, create if it doesn't exist
 * @param {String} id The id of the association.
 * @param {Object} identifier Identifier to associate.
 * @param {String} url URL to associate.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.replace = function(id, identifier, url, callback) {
  var self = this;
  var association = { identifier: identifier, url: url };

  if(!identifier) {
    callback("Identifier is missing");
  }
  else {
    this.db.update({ _id: id }, { $set: association }, { upsert: true },
                   function(err, numReplaced, newDoc) {
      if(err) { err = err.message; }
      if(newDoc) { id = newDoc._id; }
      callback(err, id);
    });
  }
}

/**
 * Remove an association from the database
 * @param {String} id Identifier to remove.
 * @param {function} callback Function to call on completion.
 */
AssociationManager.prototype.remove = function(id, callback) {
  var self = this;
  this.db.remove({ _id: id }, function(err, numReplaced) {
    callback();
  });
}

module.exports = AssociationManager;
<|endoftext|>


<commit_before>import test from 'ava';
import { readFileSync, writeFileSync } from 'fs';
import { rollup } from 'rollup';
import sass from '..';

const sassOptions = {
    outputStyle: 'compressed'
};

test('should import *.scss and *.sass files', t => {
    return rollup({
        entry: 'fixtures/basic/index.js',
        plugins: [
            sass({
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code.trim();
        const style1 = readFileSync('fixtures/basic/style1.scss').toString();
        const style2 = readFileSync('fixtures/basic/style2.sass').toString();

        t.true(code.indexOf(style1.trim()) > -1);
        t.true(code.indexOf(style2.trim()) > -1);
    });
});

test('should process code with processor', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/processor/index.js',
        plugins: [
            sass({
                processor(code) {
                    return outputCode = code;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/processor/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style.trim()}`);
    })
});

test('should processor support promise', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/processor-promise/index.js',
        plugins: [
            sass({
                processor(code) {
                    return new Promise((resolve) => {
                        setTimeout(() => {
                            resolve(outputCode = code)
                        }, 100);
                    });
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/processor-promise/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style.trim()}`);
    });
});

test('should support output as path', t => {
    writeFileSync('fixtures/output-path/output.css', '');

    return rollup({
        entry: 'fixtures/output-path/index.js',
        plugins: [
            sass({
                output: 'fixtures/output-path/output.css',
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-path/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-path/style2.scss').toString();
        const output = readFileSync('fixtures/output-path/output.css').toString();

        t.is(code.trim(), '');
        t.is(output.trim(), `${style1}${style2}`.trim());
    });
});

test('should support output as function', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-function/index.js',
        plugins: [
            sass({
                output(style) {
                    outputCode = style;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-function/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-function/style2.scss').toString();

        t.is(code.trim(), '');
        t.is(outputCode.trim(), `${style1}${style2}`.trim());
    });
});

test('should support output as true', t => {
    writeFileSync('fixtures/output-true/output.css', '');

    return rollup({
        entry: 'fixtures/output-true/index.js',
        dest: 'fixtures/output-true/output.js',
        plugins: [
            sass({
                output: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-true/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-true/style2.scss').toString();
        const output = readFileSync('fixtures/output-true/output.css').toString();

        t.is(code.trim(), '');
        t.is(output.trim(), `${style1}${style2}`.trim());
    });
});

test('should insert CSS into head tag', t => {
    return rollup({
        entry: 'fixtures/insert/index.js',
        plugins: [
            sass({
                insert: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/insert/style1.scss').toString();
        const style2 = readFileSync('fixtures/insert/style2.scss').toString();

        global.window = {};
        global.document = {
            innerHTML: '',
            head: {
                appendChild(mockNode) {
                    t.true(mockNode.hasOwnProperty('setAttribute'));
                    t.is(mockNode.innerHTML.trim(), `${style1}${style2}`);
                }
            },
            createElement() {
                return {
                    setAttribute(key, value) {
                        if (key === 'type') {
                            t.is(value, 'text/css');
                        }
                    }
                };
            }
        };

        new Function(code)();
    });
});
<commit_msg>Change test for inserting multiple styles<commit_after>import test from 'ava';
import { readFileSync, writeFileSync } from 'fs';
import { rollup } from 'rollup';
import sass from '..';

const sassOptions = {
    outputStyle: 'compressed'
};

test('should import *.scss and *.sass files', t => {
    return rollup({
        entry: 'fixtures/basic/index.js',
        plugins: [
            sass({
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code.trim();
        const style1 = readFileSync('fixtures/basic/style1.scss').toString();
        const style2 = readFileSync('fixtures/basic/style2.sass').toString();

        t.true(code.indexOf(style1.trim()) > -1);
        t.true(code.indexOf(style2.trim()) > -1);
    });
});

test('should process code with processor', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/processor/index.js',
        plugins: [
            sass({
                processor(code) {
                    return outputCode = code;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/processor/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style.trim()}`);
    })
});

test('should processor support promise', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/processor-promise/index.js',
        plugins: [
            sass({
                processor(code) {
                    return new Promise((resolve) => {
                        setTimeout(() => {
                            resolve(outputCode = code)
                        }, 100);
                    });
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style = readFileSync('fixtures/processor-promise/style.scss').toString();

        t.truthy(outputCode);
        t.is(outputCode.trim(), `${style.trim()}`);
    });
});

test('should support output as path', t => {
    writeFileSync('fixtures/output-path/output.css', '');

    return rollup({
        entry: 'fixtures/output-path/index.js',
        plugins: [
            sass({
                output: 'fixtures/output-path/output.css',
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-path/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-path/style2.scss').toString();
        const output = readFileSync('fixtures/output-path/output.css').toString();

        t.is(code.trim(), '');
        t.is(output.trim(), `${style1}${style2}`.trim());
    });
});

test('should support output as function', t => {
    let outputCode = '';

    return rollup({
        entry: 'fixtures/output-function/index.js',
        plugins: [
            sass({
                output(style) {
                    outputCode = style;
                },
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-function/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-function/style2.scss').toString();

        t.is(code.trim(), '');
        t.is(outputCode.trim(), `${style1}${style2}`.trim());
    });
});

test('should support output as true', t => {
    writeFileSync('fixtures/output-true/output.css', '');

    return rollup({
        entry: 'fixtures/output-true/index.js',
        dest: 'fixtures/output-true/output.js',
        plugins: [
            sass({
                output: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/output-true/style1.scss').toString();
        const style2 = readFileSync('fixtures/output-true/style2.scss').toString();
        const output = readFileSync('fixtures/output-true/output.css').toString();

        t.is(code.trim(), '');
        t.is(output.trim(), `${style1}${style2}`.trim());
    });
});

test('should insert CSS into head tag', t => {
    return rollup({
        entry: 'fixtures/insert/index.js',
        plugins: [
            sass({
                insert: true,
                options: sassOptions
            })
        ]
    }).then(bundle => {
        const code = bundle.generate().code;
        const style1 = readFileSync('fixtures/insert/style1.scss').toString();
        const style2 = readFileSync('fixtures/insert/style2.scss').toString();
        let count = 0;

        global.window = {};
        global.document = {
            innerHTML: '',
            head: {
                appendChild(mockNode) {
                    t.true(mockNode.hasOwnProperty('setAttribute'));

                    if (count === 0) {
                        t.is(mockNode.innerHTML.trim(), `${style1}`.trim());
                    } else if (count === 1) {
                        t.is(mockNode.innerHTML.trim(), `${style2}`.trim());
                    }

                    count++;
                }
            },
            createElement() {
                return {
                    setAttribute(key, value) {
                        if (key === 'type') {
                            t.is(value, 'text/css');
                        }
                    }
                };
            }
        };

        new Function(code)();
    });
});
<|endoftext|>


<commit_before>;(function($){
/**
 * jqGrid Icelandic Translation
 * jtm@hi.is Univercity of Iceland
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = {
	defaults : {
		recordtext: "View {0} - {1} of {2}",
	    emptyrecords: "No records to view",
		loadtext: "Hleður...",
		pgtext : "Page {0} of {1}"
	},
	search : {
	    caption: "Leita...",
	    Find: "Leita",
	    Reset: "Endursetja",
	    odata : ['equal', 'not equal', 'less', 'less or equal','greater','greater or equal', 'begins with','does not begin with','is in','is not in','ends with','does not end with','contains','does not contain'],
	    groupOps: [	{ op: "AND", text: "all" },	{ op: "OR",  text: "any" }	],
		matchText: " match",
		rulesText: " rules"
	},
	edit : {
	    addCaption: "Add Record",
	    editCaption: "Edit Record",
	    bSubmit: "Vista",
	    bCancel: "Hætta við",
		bClose: "Loka",
		saveData: "Data has been changed! Save changes?",
		bYes : "Yes",
		bNo : "No",
		bExit : "Cancel",
	    msg: {
	        required:"Reitur er nauðsynlegur",
	        number:"Vinsamlega settu inn tölu",
	        minValue:"gildi verður að vera meira en eða jafnt og ",
	        maxValue:"gildi verður að vera minna en eða jafnt og ",
	        email: "er ekki löglegt email",
	        integer: "Vinsamlega settu inn tölu",
			date: "Please, enter valid date value",
			url: "is not a valid URL. Prefix required ('http://' or 'https://')",
			nodefined : " is not defined!",
			novalue : " return value is required!",
			customarray : "Custom function should return array!",
			customfcheck : "Custom function should be present in case of custom checking!"
		}
	},
	view : {
	    caption: "View Record",
	    bClose: "Close"
	},
	del : {
	    caption: "Eyða",
	    msg: "Eyða völdum færslum ?",
	    bSubmit: "Eyða",
	    bCancel: "Hætta við"
	},
	nav : {
		edittext: " ",
	    edittitle: "Breyta færslu",
		addtext:" ",
	    addtitle: "Ný færsla",
	    deltext: " ",
	    deltitle: "Eyða færslu",
	    searchtext: " ",
	    searchtitle: "Leita",
	    refreshtext: "",
	    refreshtitle: "Endurhlaða",
	    alertcap: "Viðvörun",
	    alerttext: "Vinsamlega veldu færslu",
		viewtext: "",
		viewtitle: "View selected row"
	},
	col : {
	    caption: "Sýna / fela dálka",
	    bSubmit: "Vista",
	    bCancel: "Hætta við"
	},
	errors : {
		errcap : "Villa",
		nourl : "Vantar slóð",
		norecords: "Engar færslur valdar",
	    model : "Length of colNames <> colModel!"
	},
	formatter : {
		integer : {thousandsSeparator: " ", defaultValue: '0'},
		number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
		currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
		date : {
			dayNames:   [
				"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
				"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
			],
			monthNames: [
				"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
				"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
			],
			AmPm : ["am","pm","AM","PM"],
			S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'},
			srcformat: 'Y-m-d',
			newformat: 'd/m/Y',
			masks : {
	            ISO8601Long:"Y-m-d H:i:s",
	            ISO8601Short:"Y-m-d",
	            ShortDate: "n/j/Y",
	            LongDate: "l, F d, Y",
	            FullDateTime: "l, F d, Y g:i:s A",
	            MonthDay: "F d",
	            ShortTime: "g:i A",
	            LongTime: "g:i:s A",
	            SortableDateTime: "Y-m-d\\TH:i:s",
	            UniversalSortableDateTime: "Y-m-d H:i:sO",
	            YearMonth: "F, Y"
	        },
	        reformatAfterEdit : false
		},
		baseLinkUrl: '',
		showAction: '',
	    target: '',
	    checkbox : {disabled:true},
		idName : 'id'
	}
};
})(jQuery);
<commit_msg>Icelandic translations<commit_after>;(function($){
/**
 * jqGrid Icelandic Translation
 * jtm@hi.is Univercity of Iceland
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = {
	defaults : {
		recordtext: "Skoða {0} - {1} af {2}",
	    emptyrecords: "No records to view",
		loadtext: "Hleður...",
		pgtext : "Síða {0} af {1}"
	},
	search : {
	    caption: "Leita...",
	    Find: "Leita",
	    Reset: "Endursetja",
	    odata : ['sama og', 'ekki sama og', 'minna en', 'minna eða jafnt og','stærra en','stærra eða jafnt og', 'byrjar á','byrjar ekki á','er í','er ekki í','endar á','endar ekki á','inniheldur','inniheldur ekki'],
	    groupOps: [	{ op: "AND", text: "allt" },	{ op: "OR",  text: "eða" }	],
		matchText: " passar",
		rulesText: " reglur"
	},
	edit : {
	    addCaption: "Bæta við færslu",
	    editCaption: "Breyta færslu",
	    bSubmit: "Vista",
	    bCancel: "Hætta við",
		bClose: "Loka",
		saveData: "Gögn hafa breyst! Vista breytingar?",
		bYes : "Já",
		bNo : "Nei",
		bExit : "Hætta við",
	    msg: {
	        required:"Reitur er nauðsynlegur",
	        number:"Vinsamlega settu inn tölu",
	        minValue:"gildi verður að vera meira en eða jafnt og ",
	        maxValue:"gildi verður að vera minna en eða jafnt og ",
	        email: "er ekki löglegt email",
	        integer: "Vinsamlega settu inn tölu",
			date: "Vinsamlega setti inn dagsetningu",
			url: "er ekki löglegt URL. Vantar ('http://' eða 'https://')",
			nodefined : " er ekki skilgreint!",
			novalue : " skilagildi nauðsynlegt!",
			customarray : "Fall skal skila fylki!",
			customfcheck : "Fall skal vera skilgreint!"
		}
	},
	view : {
	    caption: "Skoða færslu",
	    bClose: "Loka"
	},
	del : {
	    caption: "Eyða",
	    msg: "Eyða völdum færslum ?",
	    bSubmit: "Eyða",
	    bCancel: "Hætta við"
	},
	nav : {
		edittext: " ",
	    edittitle: "Breyta færslu",
		addtext:" ",
	    addtitle: "Ný færsla",
	    deltext: " ",
	    deltitle: "Eyða færslu",
	    searchtext: " ",
	    searchtitle: "Leita",
	    refreshtext: "",
	    refreshtitle: "Endurhlaða",
	    alertcap: "Viðvörun",
	    alerttext: "Vinsamlega veldu færslu",
		viewtext: "",
		viewtitle: "Skoða valda færslu"
	},
	col : {
	    caption: "Sýna / fela dálka",
	    bSubmit: "Vista",
	    bCancel: "Hætta við"
	},
	errors : {
		errcap : "Villa",
		nourl : "Vantar slóð",
		norecords: "Engar færslur valdar",
	    model : "Length of colNames <> colModel!"
	},
	formatter : {
		integer : {thousandsSeparator: " ", defaultValue: '0'},
		number : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0.00'},
		currency : {decimalSeparator:".", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'},
		date : {
			dayNames:   [
				"Sun", "Mán", "Þri", "Mið", "Fim", "Fös", "Lau",
				"Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"
			],
			monthNames: [
				"Jan", "Feb", "Mar", "Apr", "Maí", "Jún", "Júl", "Ágú", "Sep", "Oct", "Nóv", "Des",
				"Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júný", "Júlý", "Ágúst", "September", "Október", "Nóvember", "Desember"
			],
			AmPm : ["am","pm","AM","PM"],
			S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'},
			srcformat: 'Y-m-d',
			newformat: 'd/m/Y',
			masks : {
	            ISO8601Long:"Y-m-d H:i:s",
	            ISO8601Short:"Y-m-d",
	            ShortDate: "n/j/Y",
	            LongDate: "l, F d, Y",
	            FullDateTime: "l, F d, Y g:i:s A",
	            MonthDay: "F d",
	            ShortTime: "g:i A",
	            LongTime: "g:i:s A",
	            SortableDateTime: "Y-m-d\\TH:i:s",
	            UniversalSortableDateTime: "Y-m-d H:i:sO",
	            YearMonth: "F, Y"
	        },
	        reformatAfterEdit : false
		},
		baseLinkUrl: '',
		showAction: '',
	    target: '',
	    checkbox : {disabled:true},
		idName : 'id'
	}
};
})(jQuery);
<|endoftext|>