<commit_before>/*
 * Copyright 2017 Next Century Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* exported entityTransforms */
/* jshint camelcase:false */

var entityTransforms = (function(_, commonTransforms, esConfig) {
  function getSingleStringFromResult(result, path, property) {
    var data = _.get(result, path, []);

    if(data && _.isArray(data)) {
      return data.length ? data.map(function(item) {
        return item[property];
      }).join('\n') : undefined;
    }

    return data ? data[property] : undefined;
  }

  function getExtraction(item, config, index, confidence) {
    /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
    var count = item.doc_count;
    /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
    var extraction = {
      confidence: confidence,
      count: count,
      id: commonTransforms.getExtractionDataId(item.key, item.value, config.type),
      icon: config.icon,
      link: commonTransforms.getLink(item.key, config.link, config.key),
      styleClass: commonTransforms.getStyleClass(config.color),
      text: commonTransforms.getExtractionDataText(item.key, item.value, config.type, (index || 0)),
      type: config.key
    };
    if(config.type !== 'url') {
      extraction.classifications = {
        database: '',
        type: config.key,
        user: ''
      };
    }
    if(config.type === 'location') {
      var locationData = commonTransforms.getLocationDataFromKey(item.key);
      extraction.latitude = locationData.latitude;
      extraction.longitude = locationData.longitude;
      extraction.text = locationData.text;
      extraction.textAndCountry = locationData.text + (locationData.country ? (', ' + locationData.country) : '');
    }
    if(config.type === 'image') {
      extraction.source = item.key;
    }
    extraction.textAndCount = extraction.text + (extraction.count ? (' (' + extraction.count + ')') : '');
    return extraction;
  }

  function getExtractionsFromList(extractionList, config) {
    var extractionData = extractionList.map(function(item, index) {
      var confidence = _.isUndefined(item.confidence) ? undefined : (Math.round(Math.min(item.confidence, 1) * 10000.0) / 100.0);
      return getExtraction(item, config, index, confidence);
    });
    return extractionData.filter(commonTransforms.getExtractionFilterFunction(config.type));
  }

  function getExtractionsFromResult(result, path, config) {
    var data = _.get(result, path, []);
    return getExtractionsFromList(data, config);
  }

  function getHighlightedText(result, paths) {
    var path = _.find(paths, function(path) {
      return result.highlight && result.highlight[path] && result.highlight[path].length && result.highlight[path][0];
    });
    return path ? result.highlight[path][0] : undefined;
  }

  function getHighlightPathList(item, result, highlightMapping) {
    /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
    var pathList = result.matched_queries;
    /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

    if(pathList && pathList.length && highlightMapping && highlightMapping[item.id]) {
      return pathList.filter(function(path) {
        return _.startsWith(path, highlightMapping[item.id]);
      }).map(function(path) {
        return path.split(':')[1];
      });
    }

    return [];
  }

  function cleanHighlight(text, type) {
    // Ignore partial matches for emails.
    if(type === 'email' && (!_.startsWith(text, '') || !_.endsWith(text, ''))) {
      return text.toLowerCase();
    }

    var output = text;

    // Usernames are formatted "<website> <username>".  Ignore matches on the <website>.
    if(type === 'username') {
      output = output.indexOf(' ') ? output.substring(output.indexOf(' ') + 1) : output;
    }

    return output.indexOf('') >= 0 ? output.replace(/<\/?em\>/g, '').toLowerCase() : '';
  }

  function addHighlight(item, result, type, highlightMapping) {
    var pathList = getHighlightPathList(item, result, highlightMapping);
    if(result.highlight && pathList.length) {
      item.highlight = pathList.some(function(path) {
        return (result.highlight[path] || []).some(function(text) {
          var cleanedHighlight = cleanHighlight(text, type);
          return cleanedHighlight && (('' + item.id).toLowerCase().indexOf(cleanedHighlight) >= 0);
        });
      });
    }
    return item;
  }

  function addAllHighlights(data, result, type, highlightMapping) {
    return data.map(function(item) {
      return addHighlight(item, result, type, highlightMapping);
    });
  }

  function getHighlightedExtractionObjectFromResult(result, config, highlightMapping) {
    var data = getExtractionsFromResult(result, '_source.knowledge_graph.' + config.key, config);
    if(highlightMapping) {
      data = addAllHighlights(data, result, config.type, highlightMapping[config.key]);
    }
    return {
      data: data,
      key: config.key,
      name: config.titlePlural
    };
  }

  function getDocumentObject(result, searchFields, documentPage, highlightMapping) {
    var id = _.get(result, '_source.doc_id');
    var url = _.get(result, '_source.url');

    if(!id || !url) {
      return {};
    }

    var rank = _.get(result, '_score');
    var domain = _.get(result, '_source.tld');
    var esDataEndpoint = (esConfig && esConfig.esDataEndpoint ? (esConfig.esDataEndpoint + id) : undefined);

    var documentObject = {
      id: id,
      url: url,
      rank: rank ? rank.toFixed(2) : rank,
      domain: domain || 'No Domain',
      type: 'document',
      icon: 'icons:assignment',
      link: commonTransforms.getLink(id, 'entity', 'document'),
      styleClass: '',
      cached: commonTransforms.getLink(id, 'cached'),
      esData: esDataEndpoint,
      // TODO
      title: getSingleStringFromResult(result, '_source.content_extraction.title', 'text') || 'No Title',
      description: getSingleStringFromResult(result, '_source.content_extraction.content_strict', 'text') || 'No Description',
      highlightedText: getHighlightedText(result, ['content_extraction.title.text']),
      headerExtractions: [],
      detailExtractions: [],
      details: []
    };

    // TODO Don't truncate the extractions once the data can support it.
    var truncateFunction = function(extractionObject) {
      if(!documentPage) {
        extractionObject.data = extractionObject.data.slice(0, 10);
      }
      return extractionObject;
    };

    documentObject.headerExtractions = searchFields.filter(function(object) {
      return object.result === 'header';
    }).map(function(object) {
      return truncateFunction(getHighlightedExtractionObjectFromResult(result, object, highlightMapping));
    });

    var domainExtraction = getExtraction({
      key: domain,
    }, {
      color: 'light green',
      key: '_domain',
      icon: 'av:web',
      type: 'url'
    });

    documentObject.headerExtractions.splice(0, 0, {
      data: [domainExtraction],
      key: '_domain',
      name: 'Website'
    });

    documentObject.detailExtractions = searchFields.filter(function(object) {
      return object.result === 'detail';
    }).map(function(object) {
      return truncateFunction(getHighlightedExtractionObjectFromResult(result, object, highlightMapping));
    });

    if(esDataEndpoint) {
      documentObject.details.push({
        name: 'Raw ES Document',
        link: esDataEndpoint,
        text: 'Open'
      });
    }

    documentObject.details.push({
      name: 'Url',
      link: url,
      text: url
    });

    documentObject.details.push({
      name: 'Description',
      highlightedText: getHighlightedText(result, ['content_extraction.content_strict.text']),
      text: documentObject.description
    });

    if(documentObject.cached) {
      documentObject.details.push({
        name: 'Cached Ad Webpage',
        link: documentObject.cached,
        text: 'Open'
      });
    }

    // TODO Images

    return documentObject;
  }

  function createDateObjectFromBucket(dateBucket, config) {
    return {
      date: commonTransforms.getFormattedDate(dateBucket.key),
      icon: config.date.icon,
      styleClass: config.date.styleClass,
      data: dateBucket[config.entity.key].buckets.map(function(entityBucket, index) {
        return getExtraction(entityBucket, config.entity, index);
      }).filter(commonTransforms.getExtractionFilterFunction(config.entity.type))
    };
  }

  function createUnidentifiedEntityObject(config, count) {
    var text = 'Unidentified ' + config.titlePlural;
    return {
      count: count,
      icon: config.icon,
      styleClass: commonTransforms.getStyleClass(config.color),
      text: text,
      textAndCount: text + ' (' + (count) + ')',
      type: config.key
    };
  }

  function createSubtitle(data) {
    var subtitle = data.map(function(entityObject) {
      return entityObject.textAndCount;
    });
    return subtitle.length ? subtitle[0].text + (subtitle.length > 1 ? (' and ' + (subtitle.length - 1) + ' more') : '') : '';
  }

  function createDateHistogram(buckets, config) {
    return buckets.reduce(function(histogram, dateBucket) {
      /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
      var count = dateBucket.doc_count;
      /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

      if(count) {
        var dateObject = createDateObjectFromBucket(dateBucket, config);

        var sum = dateObject.data.reduce(function(sum, entityObject) {
          return sum + entityObject.count;
        }, 0);

        if(sum < count) {
          dateObject.data.push(createUnidentifiedEntityObject(count - sum));
        }

        if(config.entity.key === config.page.key) {
          // Filter out the items that do not match the ID for the entity page (only once the unknown item is created).
          dateObject.data = dateObject.data.filter(function(entityObject) {
            return entityObject.id === config.id;
          });
        }

        // The data list may be empty if none match the ID for the entity page.
        if(!dateObject.data.length) {
          return;
        }

        dateObject.subtitle = createSubtitle(dateObject.data);
        histogram.push(dateObject);
      }

      return histogram;
    }, []).sort(function(a, b) {
      // Sort oldest first.
      return new Date(a.date).getTime() - new Date(b.date).getTime();
    });
  }

  return {
    document: function(data, searchFields) {
      if(data && data.hits && data.hits.hits && data.hits.hits.length) {
        return getDocumentObject(data.hits.hits[0], searchFields, true);
      }
      return {};
    },

    documents: function(data, searchFields) {
      if(data && data.hits && data.hits.hits && data.hits.hits.length) {
        return data.hits.hits.map(function(result) {
          // Data returned by the searchResults function from the searchTransforms will have a "fields" property.
          return getDocumentObject(result, searchFields, false, data.fields);
        });
      }
      return [];
    },

    externalImageLink: function(id) {
      return commonTransforms.getLink(id, 'image');
    },

    extractions: function(data, config) {
      var extractions = [];
      var sayOther = false;

      if(data && data.aggregations && data.aggregations[config.entity.key] && data.aggregations[config.entity.key][config.entity.key]) {
        extractions = getExtractionsFromList(data.aggregations[config.entity.key][config.entity.key].buckets || [], config.entity).filter(function(extraction) {
          var result = config.id && config.page && config.page.type === config.entity.type ? extraction.id !== config.id : true;
          sayOther = sayOther || !result;
          return result;
        });
      }

      return extractions;
    },

    histogram: function(data, config) {
      if(data && data.aggregations && data.aggregations[config.date.key] && data.aggregations[config.date.key][config.date.key]) {
        return createDateHistogram(data.aggregations[config.date.key][config.date.key].buckets, config);
      }
      return {};
    }
  };
});
<commit_msg>Use the fields from the fields config for the title and description rather than the content_extraction fields if available.<commit_after>/*
 * Copyright 2017 Next Century Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* exported entityTransforms */
/* jshint camelcase:false */

var entityTransforms = (function(_, commonTransforms, esConfig) {
  function getSingleStringFromResult(result, path) {
    var parentPath = path.substring(0, path.lastIndexOf('.'));
    var property = path.substring(path.lastIndexOf('.') + 1, path.length);
    var data = _.get(result, parentPath, []);

    if(data && _.isArray(data)) {
      return data.length ? data.map(function(item) {
        return item[property];
      }).join('\n') : undefined;
    }

    return data ? data[property] : undefined;
  }

  function getExtraction(item, config, index, confidence) {
    /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
    var count = item.doc_count;
    /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
    var extraction = {
      confidence: confidence,
      count: count,
      id: commonTransforms.getExtractionDataId(item.key, item.value, config.type),
      icon: config.icon,
      link: commonTransforms.getLink(item.key, config.link, config.key),
      styleClass: commonTransforms.getStyleClass(config.color),
      text: commonTransforms.getExtractionDataText(item.key, item.value, config.type, (index || 0)),
      type: config.key
    };
    if(config.type !== 'url') {
      extraction.classifications = {
        database: '',
        type: config.key,
        user: ''
      };
    }
    if(config.type === 'location') {
      var locationData = commonTransforms.getLocationDataFromKey(item.key);
      extraction.latitude = locationData.latitude;
      extraction.longitude = locationData.longitude;
      extraction.text = locationData.text;
      extraction.textAndCountry = locationData.text + (locationData.country ? (', ' + locationData.country) : '');
    }
    if(config.type === 'image') {
      extraction.source = item.key;
    }
    extraction.textAndCount = extraction.text + (extraction.count ? (' (' + extraction.count + ')') : '');
    return extraction;
  }

  function getExtractionsFromList(extractionList, config) {
    var extractionData = extractionList.map(function(item, index) {
      var confidence = _.isUndefined(item.confidence) ? undefined : (Math.round(Math.min(item.confidence, 1) * 10000.0) / 100.0);
      return getExtraction(item, config, index, confidence);
    });
    return extractionData.filter(commonTransforms.getExtractionFilterFunction(config.type));
  }

  function getExtractionsFromResult(result, path, config) {
    var data = _.get(result, path, []);
    return getExtractionsFromList(data, config);
  }

  function getHighlightedText(result, paths) {
    var path = _.find(paths, function(path) {
      return result.highlight && result.highlight[path] && result.highlight[path].length && result.highlight[path][0];
    });
    return path ? result.highlight[path][0] : undefined;
  }

  function getHighlightPathList(item, result, highlightMapping) {
    /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
    var pathList = result.matched_queries;
    /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

    if(pathList && pathList.length && highlightMapping && highlightMapping[item.id]) {
      return pathList.filter(function(path) {
        return _.startsWith(path, highlightMapping[item.id]);
      }).map(function(path) {
        return path.split(':')[1];
      });
    }

    return [];
  }

  function cleanHighlight(text, type) {
    // Ignore partial matches for emails.
    if(type === 'email' && (!_.startsWith(text, '') || !_.endsWith(text, ''))) {
      return text.toLowerCase();
    }

    var output = text;

    // Usernames are formatted "<website> <username>".  Ignore matches on the <website>.
    if(type === 'username') {
      output = output.indexOf(' ') ? output.substring(output.indexOf(' ') + 1) : output;
    }

    return output.indexOf('') >= 0 ? output.replace(/<\/?em\>/g, '').toLowerCase() : '';
  }

  function addHighlight(item, result, type, highlightMapping) {
    var pathList = getHighlightPathList(item, result, highlightMapping);
    if(result.highlight && pathList.length) {
      item.highlight = pathList.some(function(path) {
        return (result.highlight[path] || []).some(function(text) {
          var cleanedHighlight = cleanHighlight(text, type);
          return cleanedHighlight && (('' + item.id).toLowerCase().indexOf(cleanedHighlight) >= 0);
        });
      });
    }
    return item;
  }

  function addAllHighlights(data, result, type, highlightMapping) {
    return data.map(function(item) {
      return addHighlight(item, result, type, highlightMapping);
    });
  }

  function getHighlightedExtractionObjectFromResult(result, config, highlightMapping) {
    var data = getExtractionsFromResult(result, '_source.knowledge_graph.' + config.key, config);
    if(highlightMapping) {
      data = addAllHighlights(data, result, config.type, highlightMapping[config.key]);
    }
    return {
      data: data,
      key: config.key,
      name: config.titlePlural
    };
  }

  function getDocumentObject(result, searchFields, documentPage, highlightMapping) {
    var id = _.get(result, '_source.doc_id');
    var url = _.get(result, '_source.url');

    if(!id || !url) {
      return {};
    }

    var rank = _.get(result, '_score');
    var domain = _.get(result, '_source.tld');
    var esDataEndpoint = (esConfig && esConfig.esDataEndpoint ? (esConfig.esDataEndpoint + id) : undefined);

    var titleFieldObject = _.find(searchFields, function(object) {
      return object.result === 'title';
    });
    var titleField = titleFieldObject ? titleFieldObject.field : '_source.content_extraction.title.text';

    var descriptionFieldObject = _.find(searchFields, function(object) {
      return object.result === 'description';
    });
    var descriptionField = descriptionFieldObject ? descriptionFieldObject.field : '_source.content_extraction.content_strict.text';

    var documentObject = {
      id: id,
      url: url,
      rank: rank ? rank.toFixed(2) : rank,
      domain: domain || 'No Domain',
      type: 'document',
      icon: 'icons:assignment',
      link: commonTransforms.getLink(id, 'entity', 'document'),
      styleClass: '',
      cached: commonTransforms.getLink(id, 'cached'),
      esData: esDataEndpoint,
      // TODO
      title: getSingleStringFromResult(result, titleField) || 'No Title',
      description: getSingleStringFromResult(result, descriptionField) || 'No Description',
      highlightedText: getHighlightedText(result, [titleField]),
      headerExtractions: [],
      detailExtractions: [],
      details: []
    };

    // TODO Don't truncate the extractions once the data can support it.
    var truncateFunction = function(extractionObject) {
      if(!documentPage) {
        extractionObject.data = extractionObject.data.slice(0, 10);
      }
      return extractionObject;
    };

    documentObject.headerExtractions = searchFields.filter(function(object) {
      return object.result === 'header';
    }).map(function(object) {
      return truncateFunction(getHighlightedExtractionObjectFromResult(result, object, highlightMapping));
    });

    var domainExtraction = getExtraction({
      key: domain,
    }, {
      color: 'light green',
      key: '_domain',
      icon: 'av:web',
      type: 'url'
    });

    documentObject.headerExtractions.splice(0, 0, {
      data: [domainExtraction],
      key: '_domain',
      name: 'Website'
    });

    documentObject.detailExtractions = searchFields.filter(function(object) {
      return object.result === 'detail';
    }).map(function(object) {
      return truncateFunction(getHighlightedExtractionObjectFromResult(result, object, highlightMapping));
    });

    if(esDataEndpoint) {
      documentObject.details.push({
        name: 'Raw ES Document',
        link: esDataEndpoint,
        text: 'Open'
      });
    }

    documentObject.details.push({
      name: 'Url',
      link: url,
      text: url
    });

    documentObject.details.push({
      name: 'Description',
      highlightedText: getHighlightedText(result, [descriptionField]),
      text: documentObject.description
    });

    if(documentObject.cached) {
      documentObject.details.push({
        name: 'Cached Ad Webpage',
        link: documentObject.cached,
        text: 'Open'
      });
    }

    // TODO Images

    return documentObject;
  }

  function createDateObjectFromBucket(dateBucket, config) {
    return {
      date: commonTransforms.getFormattedDate(dateBucket.key),
      icon: config.date.icon,
      styleClass: config.date.styleClass,
      data: dateBucket[config.entity.key].buckets.map(function(entityBucket, index) {
        return getExtraction(entityBucket, config.entity, index);
      }).filter(commonTransforms.getExtractionFilterFunction(config.entity.type))
    };
  }

  function createUnidentifiedEntityObject(config, count) {
    var text = 'Unidentified ' + config.titlePlural;
    return {
      count: count,
      icon: config.icon,
      styleClass: commonTransforms.getStyleClass(config.color),
      text: text,
      textAndCount: text + ' (' + (count) + ')',
      type: config.key
    };
  }

  function createSubtitle(data) {
    var subtitle = data.map(function(entityObject) {
      return entityObject.textAndCount;
    });
    return subtitle.length ? subtitle[0].text + (subtitle.length > 1 ? (' and ' + (subtitle.length - 1) + ' more') : '') : '';
  }

  function createDateHistogram(buckets, config) {
    return buckets.reduce(function(histogram, dateBucket) {
      /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
      var count = dateBucket.doc_count;
      /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */

      if(count) {
        var dateObject = createDateObjectFromBucket(dateBucket, config);

        var sum = dateObject.data.reduce(function(sum, entityObject) {
          return sum + entityObject.count;
        }, 0);

        if(sum < count) {
          dateObject.data.push(createUnidentifiedEntityObject(count - sum));
        }

        if(config.entity.key === config.page.key) {
          // Filter out the items that do not match the ID for the entity page (only once the unknown item is created).
          dateObject.data = dateObject.data.filter(function(entityObject) {
            return entityObject.id === config.id;
          });
        }

        // The data list may be empty if none match the ID for the entity page.
        if(!dateObject.data.length) {
          return;
        }

        dateObject.subtitle = createSubtitle(dateObject.data);
        histogram.push(dateObject);
      }

      return histogram;
    }, []).sort(function(a, b) {
      // Sort oldest first.
      return new Date(a.date).getTime() - new Date(b.date).getTime();
    });
  }

  return {
    document: function(data, searchFields) {
      if(data && data.hits && data.hits.hits && data.hits.hits.length) {
        return getDocumentObject(data.hits.hits[0], searchFields, true);
      }
      return {};
    },

    documents: function(data, searchFields) {
      if(data && data.hits && data.hits.hits && data.hits.hits.length) {
        return data.hits.hits.map(function(result) {
          // Data returned by the searchResults function from the searchTransforms will have a "fields" property.
          return getDocumentObject(result, searchFields, false, data.fields);
        });
      }
      return [];
    },

    externalImageLink: function(id) {
      return commonTransforms.getLink(id, 'image');
    },

    extractions: function(data, config) {
      var extractions = [];
      var sayOther = false;

      if(data && data.aggregations && data.aggregations[config.entity.key] && data.aggregations[config.entity.key][config.entity.key]) {
        extractions = getExtractionsFromList(data.aggregations[config.entity.key][config.entity.key].buckets || [], config.entity).filter(function(extraction) {
          var result = config.id && config.page && config.page.type === config.entity.type ? extraction.id !== config.id : true;
          sayOther = sayOther || !result;
          return result;
        });
      }

      return extractions;
    },

    histogram: function(data, config) {
      if(data && data.aggregations && data.aggregations[config.date.key] && data.aggregations[config.date.key][config.date.key]) {
        return createDateHistogram(data.aggregations[config.date.key][config.date.key].buckets, config);
      }
      return {};
    }
  };
});
<|endoftext|>


<commit_before>var router = getRouter();
var socket = rootRequire('app/helpers/socket');
var io = socket('/users/application', ['admin', 'staff']);
var User = require('../model');
var Application = require('./model');
var Email = rootRequire('app/emails/model');
var extend = require('extend');
var multiparty = require('multiparty');
var fs = require('fs');
var path = require('path');
var uuid = require('uuid');

/**
* Create an application
* POST /users/application
* Auth
*/
router.post('/users/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      if (user.application) return res.singleError('You have already submitted an application');
      var errors = Application.validate(req.body);
      if (errors.length) return res.multiError(errors);
      extend(req.body, {
        status: Application.Status.PENDING,
        going: false,
        checked: false,
        door: false
      });
      if (req.body.dietary) req.body.dietary = req.body.dietary.split('|');
      var application = new Application(req.body);
      application.save(function (err, application) {
        if (err) return res.internalError();
        user.application = application._id;
        user.save(function (err, user) {
          if (err) res.internalError();

          if (process.env.NODE_ENV == 'production') {
            var email = new Email({
              subject: 'Your Kent Hack Enough Application',
              body: '# Thanks for applying to Kent Hack Enough!\nWe appreciate your interest.',
              recipients: {
                emails: [user.email]
              }
            });
            email.send(false);
          }

          var response = {
            _id: user._id,
            email: user.email,
            role: user.role,
            created: user.created,
            application: application
          };
          io.emit('create', response);
          return res.json(response);
        });
      });
    });
});

/**
* Get the logged in user with their application
* GET /users/me/application
* Auth
*/
router.get('/users/me/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('email application role created')
    .populate('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      return res.json(user);
    });
});

/**
* Get a list of users with their applications
* GET /users/application
* Auth -> admin, staff
*/
router.get('/users/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .find()
    .select('email application role created')
    .populate('application')
    .exec(function (err, users) {
      if (err) return res.internalError();
      return res.json({users: users});
    });
});

/**
* Get a user by ID with their application
* GET /users/:id/application
* Auth -> admin, staff
*/
router.get('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .findById(req.params.id)
    .select('email application role created')
    .populate('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      return res.json(user);
    });
});

/**
* Partially update the logged in user's application
* PATCH /users/me/application
* Auth
*/
router.patch('/users/me/application', User.auth(), function (req, res) {
  var errors = Application.validate(req.body);
  if (errors.length) return res.multiError(errors);
  if (req.body.dietary) {
    req.body.dietary = req.body.dietary.split('|');
  } else {
    req.body.dietary = [];
  }
  User
    .findByIdAndUpdate(req.user._id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndUpdate(user.application, req.body)
        .exec(function (err, application) {
          var response = {
            _id: user._id,
            email: user.email,
            role: user.role,
            created: user.created,
            application: application
          };
          io.emit('update', response);
          return res.json(response);
        });
    });
});

/**
* Partially update a user's application by ID
* PATCH /users/:id/application
* Auth -> admin, staff
*/
router.patch('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  if (req.body.dietary) req.body.dietary = req.body.dietary.split('|');
  User
    .findById(req.params.id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      if (user.application) {
        Application
          .findByIdAndUpdate(user.application, req.body)
          .exec(function (err, application) {
            if (err) return res.internalError();
            if (req.body.status == Application.Status.APPROVED) {
              // Send acceptance email
              new Email({
                subject: 'You\'ve been accepted to KHE!',
                body: '## You\'re invited!\n\n\nCongratulations, you have been accepted to Kent Hack Enough. Please RSVP here: [khe.io/rsvp](https://khe.io/rsvp).\n\n\nUntil then, a few things to note:\n\n\n**What you should bring:**\n- Deodorant\n- Laptop and charger\n- Valid school ID\n- Phone/charger\n- Change of clothes\n- Deodorant\n- Basic toiletries\n- Pillow and blanket\n- Deodorant\n\n\n**Hackers looking for travel reimbursements:** Please submit a request on the contact form of [our website](https://khe.io) and we\'ll get back to you. Hackers may receive up to $150 towards travel on a first come first serve basis.\n\n\n**Hackers under the age of 18:** Please have a parent/guardian sign our minor waiver [go.khe.io/waiver](https://go.khe.io/waiver) and return that to us at [staff@khe.io](mailto:staff@khe.io) before the event.\n\n\n**Make sure your resume is attached to your application if you\'re looking for full time jobs or internships.** You can edit your application by logging in at [khe.io](https://khe.io)\n\n\nWe\'re looking forward to seeing you on October 9th!\n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            } else if (req.body.status == Application.Status.WAITLISTED) {
              // Send waitlist email
              new Email({
                subject: 'You have been waitlisted',
                body: 'Hello,\n\nYou have been added to the Kent Hack Enough waitlist. Please standby for further emails, as we will try to accomodate as many hackers from the waitlist as we can. \n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            } else if (req.body.status == Application.Status.DENIED) {
              // Send denial email
              new Email({
                subject: 'KHE Status: Denied',
                body: 'Hello,\n\nWe\'re sorry to say that you have been denied from Kent Hack Enough. We are trying to accomodate as many hackers as we can, but we just can\'t fit everyone in our venue. Thank you so much for your interest, and please come again next year! \n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            }
            var response = {
              _id: user._id,
              email: user.email,
              role: user.role,
              created: user.created,
              application: application
            };
            io.emit('update', response);
            return res.json(response);
          });
      } else {
        var application = new Application(req.body);
        application.save(function (err, application) {
          user.application = application;
          user.save(function (err, user) {
            if (err) return res.internalError();
            var response = {
              _id: user._id,
              email: user.email,
              role: user.role,
              created: user.created,
              application: application
            };
            io.emit('update', response);
            return res.json(response);
          });
        });
      }
    });
});

/**
* Delete the logged in user's application
* DELETE /users/me/application
* Auth
*/
router.delete('/users/me/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndRemove(user.application)
        .exec(function (err) {
          if (err) return res.internalError();
          var response = {_id: req.user._id};
          io.emit('delete', response);
          return res.json(response);
        });
    });
});

/**
* Delete a user's application by ID
* DELETE /users/:id/application
* Auth -> admin, staff
*/
router.delete('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .findById(req.params.id)
    .select('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndRemove(user.application)
        .exec(function (err) {
          if (err) return res.internalError();
          var response = {_id: req.params.id};
          io.emit('delete', response);
          return res.json(response);
        });
    });
});

/**
* Upload a resume
* POST /users/application/resume
*/
router.post('/users/application/resume', function (req, res) {
  var form = new multiparty.Form();
  form.parse(req, function (err, fields, files) {
    if (err || !files.resume) return res.internalError();
    fs.readFile(files.resume[0].path, function (err, data) {
      if (err) return res.internalError();
      var ext = path.extname(files.resume[0].path);
      var name = uuid.v4();
      var dest = path.join(__dirname, '../../../uploads/' + name + ext);
      fs.writeFile(dest, data, function (err) {
        if (err) return res.internalError();
        return res.json({
          filename: name + ext
        });
      });
    });
  });
});

/**
* Retreive a resume
* GET /users/application/resume/:filename
*/
router.get('/users/application/resume/:filename', function (req, res) {
  var file = path.join(__dirname, '../../../uploads', req.params.filename);
  res.download(file);
});

/**
* Search for applications
* GET /users/application/search?q=String
*/
router.get('/users/application/search', User.auth('admin', 'staff'), function (req, res) {
  if (!req.query.q) return res.singleError('You must provide a search query');

  // Search for applications
  Application
    .search(
      req.query.q,
      {limit: 10},
    function (err, data) {
      if (err) return res.internalError();

      // Get the ids of the results
      var ids = data.results.map(function (r) { return r._id; });

      // Find the owners of the applications
      User
        .find({'application': {$in: ids}})
        .select('email role application created')
        .populate('application')
        .exec(function (err, users) {
          if (err) return res.internalError();
          return res.json({results: users});
        });
    });

});<commit_msg>Fix waiver link<commit_after>var router = getRouter();
var socket = rootRequire('app/helpers/socket');
var io = socket('/users/application', ['admin', 'staff']);
var User = require('../model');
var Application = require('./model');
var Email = rootRequire('app/emails/model');
var extend = require('extend');
var multiparty = require('multiparty');
var fs = require('fs');
var path = require('path');
var uuid = require('uuid');

/**
* Create an application
* POST /users/application
* Auth
*/
router.post('/users/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      if (user.application) return res.singleError('You have already submitted an application');
      var errors = Application.validate(req.body);
      if (errors.length) return res.multiError(errors);
      extend(req.body, {
        status: Application.Status.PENDING,
        going: false,
        checked: false,
        door: false
      });
      if (req.body.dietary) req.body.dietary = req.body.dietary.split('|');
      var application = new Application(req.body);
      application.save(function (err, application) {
        if (err) return res.internalError();
        user.application = application._id;
        user.save(function (err, user) {
          if (err) res.internalError();

          if (process.env.NODE_ENV == 'production') {
            var email = new Email({
              subject: 'Your Kent Hack Enough Application',
              body: '# Thanks for applying to Kent Hack Enough!\nWe appreciate your interest.',
              recipients: {
                emails: [user.email]
              }
            });
            email.send(false);
          }

          var response = {
            _id: user._id,
            email: user.email,
            role: user.role,
            created: user.created,
            application: application
          };
          io.emit('create', response);
          return res.json(response);
        });
      });
    });
});

/**
* Get the logged in user with their application
* GET /users/me/application
* Auth
*/
router.get('/users/me/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('email application role created')
    .populate('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      return res.json(user);
    });
});

/**
* Get a list of users with their applications
* GET /users/application
* Auth -> admin, staff
*/
router.get('/users/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .find()
    .select('email application role created')
    .populate('application')
    .exec(function (err, users) {
      if (err) return res.internalError();
      return res.json({users: users});
    });
});

/**
* Get a user by ID with their application
* GET /users/:id/application
* Auth -> admin, staff
*/
router.get('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .findById(req.params.id)
    .select('email application role created')
    .populate('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      return res.json(user);
    });
});

/**
* Partially update the logged in user's application
* PATCH /users/me/application
* Auth
*/
router.patch('/users/me/application', User.auth(), function (req, res) {
  var errors = Application.validate(req.body);
  if (errors.length) return res.multiError(errors);
  if (req.body.dietary) {
    req.body.dietary = req.body.dietary.split('|');
  } else {
    req.body.dietary = [];
  }
  User
    .findByIdAndUpdate(req.user._id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndUpdate(user.application, req.body)
        .exec(function (err, application) {
          var response = {
            _id: user._id,
            email: user.email,
            role: user.role,
            created: user.created,
            application: application
          };
          io.emit('update', response);
          return res.json(response);
        });
    });
});

/**
* Partially update a user's application by ID
* PATCH /users/:id/application
* Auth -> admin, staff
*/
router.patch('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  if (req.body.dietary) req.body.dietary = req.body.dietary.split('|');
  User
    .findById(req.params.id)
    .select('email application role created')
    .exec(function (err, user) {
      if (err) return res.internalError();
      if (user.application) {
        Application
          .findByIdAndUpdate(user.application, req.body)
          .exec(function (err, application) {
            if (err) return res.internalError();
            if (req.body.status == Application.Status.APPROVED) {
              // Send acceptance email
              new Email({
                subject: 'You\'ve been accepted to KHE!',
                body: '## You\'re invited!\n\n\nCongratulations, you have been accepted to Kent Hack Enough. Please RSVP here: [khe.io/rsvp](https://khe.io/rsvp).\n\n\nUntil then, a few things to note:\n\n\n**What you should bring:**\n- Deodorant\n- Laptop and charger\n- Valid school ID\n- Phone/charger\n- Change of clothes\n- Deodorant\n- Basic toiletries\n- Pillow and blanket\n- Deodorant\n\n\n**Hackers looking for travel reimbursements:** Please submit a request on the contact form of [our website](https://khe.io) and we\'ll get back to you. Hackers may receive up to $150 towards travel on a first come first serve basis.\n\n\n**Hackers under the age of 18:** Please have a parent/guardian sign our minor waiver [go.khe.io/waiver](http://go.khe.io/waiver) and return that to us at [staff@khe.io](mailto:staff@khe.io) before the event.\n\n\n**Make sure your resume is attached to your application if you\'re looking for full time jobs or internships.** You can edit your application by logging in at [khe.io](https://khe.io)\n\n\nWe\'re looking forward to seeing you on October 9th!\n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            } else if (req.body.status == Application.Status.WAITLISTED) {
              // Send waitlist email
              new Email({
                subject: 'You have been waitlisted',
                body: 'Hello,\n\nYou have been added to the Kent Hack Enough waitlist. Please standby for further emails, as we will try to accomodate as many hackers from the waitlist as we can. \n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            } else if (req.body.status == Application.Status.DENIED) {
              // Send denial email
              new Email({
                subject: 'KHE Status: Denied',
                body: 'Hello,\n\nWe\'re sorry to say that you have been denied from Kent Hack Enough. We are trying to accomodate as many hackers as we can, but we just can\'t fit everyone in our venue. Thank you so much for your interest, and please come again next year! \n\n\n\nRegards,\n\nKent Hack Enough Team',
                recipients: {
                  emails: [user.email]
                }
              }).send();
            }
            var response = {
              _id: user._id,
              email: user.email,
              role: user.role,
              created: user.created,
              application: application
            };
            io.emit('update', response);
            return res.json(response);
          });
      } else {
        var application = new Application(req.body);
        application.save(function (err, application) {
          user.application = application;
          user.save(function (err, user) {
            if (err) return res.internalError();
            var response = {
              _id: user._id,
              email: user.email,
              role: user.role,
              created: user.created,
              application: application
            };
            io.emit('update', response);
            return res.json(response);
          });
        });
      }
    });
});

/**
* Delete the logged in user's application
* DELETE /users/me/application
* Auth
*/
router.delete('/users/me/application', User.auth(), function (req, res) {
  User
    .findById(req.user._id)
    .select('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndRemove(user.application)
        .exec(function (err) {
          if (err) return res.internalError();
          var response = {_id: req.user._id};
          io.emit('delete', response);
          return res.json(response);
        });
    });
});

/**
* Delete a user's application by ID
* DELETE /users/:id/application
* Auth -> admin, staff
*/
router.delete('/users/:id/application', User.auth('admin', 'staff'), function (req, res) {
  User
    .findById(req.params.id)
    .select('application')
    .exec(function (err, user) {
      if (err) return res.internalError();
      Application
        .findByIdAndRemove(user.application)
        .exec(function (err) {
          if (err) return res.internalError();
          var response = {_id: req.params.id};
          io.emit('delete', response);
          return res.json(response);
        });
    });
});

/**
* Upload a resume
* POST /users/application/resume
*/
router.post('/users/application/resume', function (req, res) {
  var form = new multiparty.Form();
  form.parse(req, function (err, fields, files) {
    if (err || !files.resume) return res.internalError();
    fs.readFile(files.resume[0].path, function (err, data) {
      if (err) return res.internalError();
      var ext = path.extname(files.resume[0].path);
      var name = uuid.v4();
      var dest = path.join(__dirname, '../../../uploads/' + name + ext);
      fs.writeFile(dest, data, function (err) {
        if (err) return res.internalError();
        return res.json({
          filename: name + ext
        });
      });
    });
  });
});

/**
* Retreive a resume
* GET /users/application/resume/:filename
*/
router.get('/users/application/resume/:filename', function (req, res) {
  var file = path.join(__dirname, '../../../uploads', req.params.filename);
  res.download(file);
});

/**
* Search for applications
* GET /users/application/search?q=String
*/
router.get('/users/application/search', User.auth('admin', 'staff'), function (req, res) {
  if (!req.query.q) return res.singleError('You must provide a search query');

  // Search for applications
  Application
    .search(
      req.query.q,
      {limit: 10},
    function (err, data) {
      if (err) return res.internalError();

      // Get the ids of the results
      var ids = data.results.map(function (r) { return r._id; });

      // Find the owners of the applications
      User
        .find({'application': {$in: ids}})
        .select('email role application created')
        .populate('application')
        .exec(function (err, users) {
          if (err) return res.internalError();
          return res.json({results: users});
        });
    });

});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'common/ui/js/models/ContrailModel'
], function (_, ContrailModel) {
    var ServerModel = ContrailModel.extend({

        defaultConfig: smwmc.getServerModel(),

        configure: function (checkedRows, callbackObj) {
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var ajaxConfig = {};
                var putData = {}, serverAttrsEdited = [], serversEdited = [],
                    serverAttrs = this.model().attributes,
                    originalAttrs = this.model()._originalAttributes,
                    locks = this.model().attributes.locks.attributes,
                    that = this;

                serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);
                for (var i = 0; i < checkedRows.length; i++) {
                    serversEdited.push(serverAttrsEdited);
                }

                putData[smwc.SERVER_PREFIX_ID] = serversEdited;
                if(originalAttrs['cluster_id'] != serverAttrsEdited['cluster_id']) {
                    smwu.removeRolesFromServers(putData);
                }

                ajaxConfig.type = "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        configureServers: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            var putData = {}, serverAttrsEdited = {}, serversEdited = [],
                serverAttrs = this.model().attributes,
                locks = this.model().attributes.locks.attributes,
                that = this;

            serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);
            $.each(checkedRows, function (checkedRowsKey, checkedRowsValue) {
                serversEdited.push($.extend(true, {}, serverAttrsEdited, {id: checkedRowsValue.id}));
            });

            putData[smwc.SERVER_PREFIX_ID] = serversEdited;
            smwu.removeRolesFromServers(putData);

            ajaxConfig.type = "PUT";
            ajaxConfig.data = JSON.stringify(putData);
            ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
            console.log(ajaxConfig);
            contrail.ajaxHandler(ajaxConfig, function () {
                if (contrail.checkIfFunction(callbackObj.init)) {
                    callbackObj.init();
                }
            }, function (response) {
                console.log(response);
                if (contrail.checkIfFunction(callbackObj.success)) {
                    callbackObj.success();
                }
            }, function (error) {
                console.log(error);
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(error);
                }
            });
        },
        createServers: function (callbackObj, ajaxMethod) {
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var ajaxConfig = {};
                var putData = {}, serversCreated = [], that = this,
                    serverAttrs = this.model().attributes;
                serversCreated.push(serverAttrs),
                    that = this;

                putData[smwc.SERVER_PREFIX_ID] = serversCreated;

                ajaxConfig.type = contrail.checkIfExist(ajaxMethod) ? ajaxMethod : "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);

                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        editRoles: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    roles = serverAttrs['roles'].split(','),
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'roles': roles});
                }
                putData[smwc.SERVER_PREFIX_ID] = servers;

                ajaxConfig.type = "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        editTags: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_EDIT_TAGS_VALIDATION)) {
                var putData = {}, serverAttrsEdited = {}, serversEdited = [],
                    serverAttrs = this.model().attributes,
                    locks = this.model().attributes.locks.attributes,
                    that = this;

                contrail.ajaxHandler({
                    type: 'GET',
                    url: smwc.URL_TAG_NAMES
                }, function () {
                }, function (response) {
                    $.each(response, function (tagKey, tagValue) {
                        if (!contrail.checkIfExist(serverAttrs.tag[tagValue])) {
                            serverAttrs.tag[tagValue] = null;
                        }
                    });

                    serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);

                    $.each(checkedRows, function (checkedRowsKey, checkedRowsValue) {
                        serversEdited.push({'id': checkedRowsValue.id, 'tag': serverAttrsEdited['tag']});
                    });
                    putData[smwc.SERVER_PREFIX_ID] = serversEdited;

                    ajaxConfig.type = "PUT";
                    ajaxConfig.data = JSON.stringify(putData);
                    ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                    console.log(ajaxConfig);
                    contrail.ajaxHandler(ajaxConfig, function () {
                        if (contrail.checkIfFunction(callbackObj.init)) {
                            callbackObj.init();
                        }
                    }, function (response) {
                        console.log(response);
                        if (contrail.checkIfFunction(callbackObj.success)) {
                            callbackObj.success();
                        }
                    }, function (error) {
                        console.log(error);
                        if (contrail.checkIfFunction(callbackObj.error)) {
                            callbackObj.error(error);
                        }
                    });
                }, function (error) {
                    console.log(error);
                    that.showErrorAttr(smwc.SERVER_PREFIX_ID + '_form', error.responseText);
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        reimage: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_REIMAGE_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'base_image_id': serverAttrs['base_image_id']});
                }
                putData = servers;
                ajaxConfig.type = "POST";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.timeout = smwc.TIMEOUT;
                ajaxConfig.url = smwc.URL_SERVER_REIMAGE;
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            }  else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        provision: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_PROVISION_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'package_image_id': serverAttrs['package_image_id']});
                }
                putData = servers;

                ajaxConfig.type = "POST";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.timeout = smwc.TIMEOUT;
                ajaxConfig.url = smwc.URL_SERVER_PROVISION;
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        deleteServer: function (checkedRow, callbackObj) {
            var ajaxConfig = {}, that = this,
                serverId = checkedRow['id'];
            ajaxConfig.type = "DELETE";
            ajaxConfig.url = smwc.URL_OBJ_SERVER_ID + serverId;
            contrail.ajaxHandler(ajaxConfig, function () {
                if (contrail.checkIfFunction(callbackObj.init)) {
                    callbackObj.init();
                }
            }, function (response) {
                console.log(response);
                if (contrail.checkIfFunction(callbackObj.success)) {
                    callbackObj.success();
                }
            }, function (error) {
                console.log(error);
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(error);
                }
            });
        },
        validations: {
            reimageValidation: {
                'base_image_id': {
                    required: true,
                    msg: smwm.getRequiredMessage('base_image_id')
                }
            },
            provisionValidation: {
                'package_image_id': {
                    required: true,
                    msg: smwm.getRequiredMessage('package_image_id')
                }
            },
            configureValidation: {
                'id': {
                    required: true,
                    msg: smwm.getRequiredMessage('id')
                },
                'ip_address': {
                    required: true,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('ip_address')
                },
                'ipmi_address': {
                    required: false,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('ipmi_address')
                },
                'mac_address': {
                    required: true,
                    pattern: smwc.PATTERN_MAC_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('mac_address')
                },
                'email': {
                    required: false,
                    pattern: 'email',
                    msg: smwm.getInvalidErrorMessage('email')
                },
                'gateway': {
                    required: false,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('gateway')
                },
                'parameters.interface_name': {
                    required: true,
                    msg: smwm.getRequiredMessage('interface_name')
                },
                'subnet_mask': {
                    required: false,
                    pattern: smwc.PATTERN_SUBNET_MASK,
                    msg: smwm.getInvalidErrorMessage('subnet_mask')
                }
            },
            editTagsValidation: {}
        }
    });

    return ServerModel;
});
<commit_msg>Bug Fix: 1398268 - Removed locks and errors fields from request payload.<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'common/ui/js/models/ContrailModel'
], function (_, ContrailModel) {
    var ServerModel = ContrailModel.extend({

        defaultConfig: smwmc.getServerModel(),

        configure: function (checkedRows, callbackObj) {
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var ajaxConfig = {};
                var putData = {}, serverAttrsEdited = [], serversEdited = [],
                    serverAttrs = this.model().attributes,
                    originalAttrs = this.model()._originalAttributes,
                    locks = this.model().attributes.locks.attributes,
                    that = this;

                serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);
                for (var i = 0; i < checkedRows.length; i++) {
                    serversEdited.push(serverAttrsEdited);
                }

                putData[smwc.SERVER_PREFIX_ID] = serversEdited;
                if(originalAttrs['cluster_id'] != serverAttrsEdited['cluster_id']) {
                    smwu.removeRolesFromServers(putData);
                }

                ajaxConfig.type = "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        configureServers: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            var putData = {}, serverAttrsEdited = {}, serversEdited = [],
                serverAttrs = this.model().attributes,
                locks = this.model().attributes.locks.attributes,
                that = this;

            serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);
            $.each(checkedRows, function (checkedRowsKey, checkedRowsValue) {
                serversEdited.push($.extend(true, {}, serverAttrsEdited, {id: checkedRowsValue.id}));
            });

            putData[smwc.SERVER_PREFIX_ID] = serversEdited;
            smwu.removeRolesFromServers(putData);

            ajaxConfig.type = "PUT";
            ajaxConfig.data = JSON.stringify(putData);
            ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
            console.log(ajaxConfig);
            contrail.ajaxHandler(ajaxConfig, function () {
                if (contrail.checkIfFunction(callbackObj.init)) {
                    callbackObj.init();
                }
            }, function (response) {
                console.log(response);
                if (contrail.checkIfFunction(callbackObj.success)) {
                    callbackObj.success();
                }
            }, function (error) {
                console.log(error);
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(error);
                }
            });
        },
        createServers: function (callbackObj, ajaxMethod) {
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var ajaxConfig = {};
                var putData = {}, serverAttrsEdited = [], serversCreated = [],
                    serverAttrs = this.model().attributes,
                    locks = this.model().attributes.locks.attributes,
                    that = this;

                serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);
                serversCreated.push(serverAttrsEdited);

                putData[smwc.SERVER_PREFIX_ID] = serversCreated;

                ajaxConfig.type = contrail.checkIfExist(ajaxMethod) ? ajaxMethod : "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);

                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        editRoles: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_CONFIGURE_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    roles = serverAttrs['roles'].split(','),
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'roles': roles});
                }
                putData[smwc.SERVER_PREFIX_ID] = servers;

                ajaxConfig.type = "PUT";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        editTags: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_EDIT_TAGS_VALIDATION)) {
                var putData = {}, serverAttrsEdited = {}, serversEdited = [],
                    serverAttrs = this.model().attributes,
                    locks = this.model().attributes.locks.attributes,
                    that = this;

                contrail.ajaxHandler({
                    type: 'GET',
                    url: smwc.URL_TAG_NAMES
                }, function () {
                }, function (response) {
                    $.each(response, function (tagKey, tagValue) {
                        if (!contrail.checkIfExist(serverAttrs.tag[tagValue])) {
                            serverAttrs.tag[tagValue] = null;
                        }
                    });

                    serverAttrsEdited = smwu.getEditConfigObj(serverAttrs, locks);

                    $.each(checkedRows, function (checkedRowsKey, checkedRowsValue) {
                        serversEdited.push({'id': checkedRowsValue.id, 'tag': serverAttrsEdited['tag']});
                    });
                    putData[smwc.SERVER_PREFIX_ID] = serversEdited;

                    ajaxConfig.type = "PUT";
                    ajaxConfig.data = JSON.stringify(putData);
                    ajaxConfig.url = smwu.getObjectUrl(smwc.SERVER_PREFIX_ID);
                    console.log(ajaxConfig);
                    contrail.ajaxHandler(ajaxConfig, function () {
                        if (contrail.checkIfFunction(callbackObj.init)) {
                            callbackObj.init();
                        }
                    }, function (response) {
                        console.log(response);
                        if (contrail.checkIfFunction(callbackObj.success)) {
                            callbackObj.success();
                        }
                    }, function (error) {
                        console.log(error);
                        if (contrail.checkIfFunction(callbackObj.error)) {
                            callbackObj.error(error);
                        }
                    });
                }, function (error) {
                    console.log(error);
                    that.showErrorAttr(smwc.SERVER_PREFIX_ID + '_form', error.responseText);
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        reimage: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_REIMAGE_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'base_image_id': serverAttrs['base_image_id']});
                }
                putData = servers;
                ajaxConfig.type = "POST";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.timeout = smwc.TIMEOUT;
                ajaxConfig.url = smwc.URL_SERVER_REIMAGE;
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            }  else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        provision: function (checkedRows, callbackObj) {
            var ajaxConfig = {};
            if (this.model().isValid(true, smwc.KEY_PROVISION_VALIDATION)) {
                var serverAttrs = this.model().attributes,
                    putData = {}, servers = [],
                    that = this;

                for (var i = 0; i < checkedRows.length; i++) {
                    servers.push({'id': checkedRows[i]['id'], 'package_image_id': serverAttrs['package_image_id']});
                }
                putData = servers;

                ajaxConfig.type = "POST";
                ajaxConfig.data = JSON.stringify(putData);
                ajaxConfig.timeout = smwc.TIMEOUT;
                ajaxConfig.url = smwc.URL_SERVER_PROVISION;
                console.log(ajaxConfig);
                contrail.ajaxHandler(ajaxConfig, function () {
                    if (contrail.checkIfFunction(callbackObj.init)) {
                        callbackObj.init();
                    }
                }, function (response) {
                    console.log(response);
                    if (contrail.checkIfFunction(callbackObj.success)) {
                        callbackObj.success();
                    }
                }, function (error) {
                    console.log(error);
                    if (contrail.checkIfFunction(callbackObj.error)) {
                        callbackObj.error(error);
                    }
                });
            } else {
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(this.getFormErrorText(smwc.SERVER_PREFIX_ID));
                }
            }
        },
        deleteServer: function (checkedRow, callbackObj) {
            var ajaxConfig = {}, that = this,
                serverId = checkedRow['id'];
            ajaxConfig.type = "DELETE";
            ajaxConfig.url = smwc.URL_OBJ_SERVER_ID + serverId;
            contrail.ajaxHandler(ajaxConfig, function () {
                if (contrail.checkIfFunction(callbackObj.init)) {
                    callbackObj.init();
                }
            }, function (response) {
                console.log(response);
                if (contrail.checkIfFunction(callbackObj.success)) {
                    callbackObj.success();
                }
            }, function (error) {
                console.log(error);
                if (contrail.checkIfFunction(callbackObj.error)) {
                    callbackObj.error(error);
                }
            });
        },
        validations: {
            reimageValidation: {
                'base_image_id': {
                    required: true,
                    msg: smwm.getRequiredMessage('base_image_id')
                }
            },
            provisionValidation: {
                'package_image_id': {
                    required: true,
                    msg: smwm.getRequiredMessage('package_image_id')
                }
            },
            configureValidation: {
                'id': {
                    required: true,
                    msg: smwm.getRequiredMessage('id')
                },
                'ip_address': {
                    required: true,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('ip_address')
                },
                'ipmi_address': {
                    required: false,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('ipmi_address')
                },
                'mac_address': {
                    required: true,
                    pattern: smwc.PATTERN_MAC_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('mac_address')
                },
                'email': {
                    required: false,
                    pattern: 'email',
                    msg: smwm.getInvalidErrorMessage('email')
                },
                'gateway': {
                    required: false,
                    pattern: smwc.PATTERN_IP_ADDRESS,
                    msg: smwm.getInvalidErrorMessage('gateway')
                },
                'parameters.interface_name': {
                    required: true,
                    msg: smwm.getRequiredMessage('interface_name')
                },
                'subnet_mask': {
                    required: false,
                    pattern: smwc.PATTERN_SUBNET_MASK,
                    msg: smwm.getInvalidErrorMessage('subnet_mask')
                }
            },
            editTagsValidation: {}
        }
    });

    return ServerModel;
});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const replace = require('gulp-replace');

<% if (framework === 'angular1') { -%>
const Builder = require('systemjs-builder');
<% } else { -%>
const Builder = require('jspm').Builder;
<% } -%>
const conf = require('../conf/gulp.conf');

gulp.task('systemjs', systemjs);
<% if (framework === 'angular2') { -%>
gulp.task('systemjs:html', gulp.parallel(updateIndexHtml, copyVendor));
<% } else { -%>
gulp.task('systemjs:html', updateIndexHtml));
<% } -%>

function systemjs(done) {
  const builder = new Builder('./', 'jspm.config.js');
  builder.config({
    paths: {
      "github:*": "jspm_packages/github/*",
      "npm:*": "jspm_packages/npm/*"
    },
    packageConfigPaths: [
      'npm:@*/*.json',
      'npm:*.json',
      'github:*/*.json'
    ]
  });
  builder.buildStatic(
    <%- entry %>,
    conf.path.tmp('index.js'),
    {
      production: true,
      browser: true
    }
  ).then(() => done(), done);
}
<% if (framework === 'angular2') { -%>

function copyVendor() {
  return gulp.src([
    'node_modules/reflect-metadata/Reflect.js'
  ])
  .pipe(gulp.dest(conf.path.dist('vendor')));
}
<% } -%>

function updateIndexHtml() {
  return gulp.src(conf.path.src('index.html'))
    .pipe(replace(
      /<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/,
      `<script src="index.js"></script>`
    ))
<% if (framework === 'angular2') { -%>
    .pipe(replace(
      /<!-- <script src="(node_modules)(\/([\s\S]*?))*"><\/script> -->/g,
      `<script src="vendor$2"></script>`
    ))
<% } -%>
    .pipe(gulp.dest(conf.path.tmp()));
}
<commit_msg>Fix typo in template<commit_after>const gulp = require('gulp');
const replace = require('gulp-replace');

<% if (framework === 'angular1') { -%>
const Builder = require('systemjs-builder');
<% } else { -%>
const Builder = require('jspm').Builder;
<% } -%>
const conf = require('../conf/gulp.conf');

gulp.task('systemjs', systemjs);
<% if (framework === 'angular2') { -%>
gulp.task('systemjs:html', gulp.parallel(updateIndexHtml, copyVendor));
<% } else { -%>
gulp.task('systemjs:html', updateIndexHtml);
<% } -%>

function systemjs(done) {
  const builder = new Builder('./', 'jspm.config.js');
  builder.config({
    paths: {
      "github:*": "jspm_packages/github/*",
      "npm:*": "jspm_packages/npm/*"
    },
    packageConfigPaths: [
      'npm:@*/*.json',
      'npm:*.json',
      'github:*/*.json'
    ]
  });
  builder.buildStatic(
    <%- entry %>,
    conf.path.tmp('index.js'),
    {
      production: true,
      browser: true
    }
  ).then(() => done(), done);
}
<% if (framework === 'angular2') { -%>

function copyVendor() {
  return gulp.src([
    'node_modules/reflect-metadata/Reflect.js'
  ])
  .pipe(gulp.dest(conf.path.dist('vendor')));
}
<% } -%>

function updateIndexHtml() {
  return gulp.src(conf.path.src('index.html'))
    .pipe(replace(
      /<script src="jspm_packages\/system.js">[\s\S]*System.import.*\n\s*<\/script>/,
      `<script src="index.js"></script>`
    ))
<% if (framework === 'angular2') { -%>
    .pipe(replace(
      /<!-- <script src="(node_modules)(\/([\s\S]*?))*"><\/script> -->/g,
      `<script src="vendor$2"></script>`
    ))
<% } -%>
    .pipe(gulp.dest(conf.path.tmp()));
}
<|endoftext|>


<commit_before>import React from 'react';
import { TouchableHighlight, View, Text } from 'react-native';
import { render, normalizeStyle, nthChild } from './helpers';

jest.dontMock('../src/MenuTrigger');
jest.dontMock('../src/helpers');
const MenuTrigger = require('../src/MenuTrigger').default;
const { createSpy, objectContaining } = jasmine;

describe('MenuTrigger', () => {

  it('should render component', () => {
    const { output } = render(
      <MenuTrigger>
        <Text>Trigger Button</Text>
      </MenuTrigger>
    );
    expect(output.type).toEqual(View);
    expect(nthChild(output, 1).type).toEqual(TouchableHighlight);
    expect(nthChild(output, 2).type).toEqual(View);
    expect(nthChild(output, 3)).toEqual(
      <Text>Trigger Button</Text>
    );
  });

  it('should render component using text property', () => {
    const { output } = render(
      <MenuTrigger text='Trigger text' />
    );
    expect(nthChild(output, 1).type).toEqual(TouchableHighlight);
    expect(nthChild(output, 2).type).toEqual(View);
    expect(nthChild(output, 3)).toEqual(
      <Text>Trigger text</Text>
    );
  });

  it('should be enabled by default', () => {
    const { instance } = render(
      <MenuTrigger />
    );
    expect(instance.props.disabled).toBe(false);
  });

  it('should trigger on ref event', () => {
    const onRefSpy = createSpy();
    const { output } = render(
      <MenuTrigger onRef={onRefSpy} />
    );
    expect(typeof output.ref).toEqual('function');
    output.ref();
    expect(onRefSpy).toHaveBeenCalled();
    expect(onRefSpy.calls.count()).toEqual(1);
  });

  it('should open menu', () => {
    const { output, instance } = render(
      <MenuTrigger menuName='menu1' />
    );
    const menuActions = { openMenu: createSpy() };
    instance.context = { menuActions };
    nthChild(output, 1).props.onPress();
    expect(menuActions.openMenu).toHaveBeenCalledWith('menu1');
    expect(menuActions.openMenu.calls.count()).toEqual(1);
  });

  it('should not open menu when disabled', () => {
    const { output, instance } = render(
      <MenuTrigger menuName='menu1' disabled={true} />
    );
    const menuActions = { openMenu: createSpy() };
    instance.context = { menuActions };
    nthChild(output, 1).props.onPress();
    expect(menuActions.openMenu).not.toHaveBeenCalled();
  });

  it('should render trigger with custom styles', () => {
    const customStyles = {
      triggerWrapper: { backgroundColor: 'red' },
      triggerText: { color: 'blue' },
      triggerTouchable: { underlayColor: 'green' },
    };
    const { output } = render(
      <MenuTrigger menuName='menu1' text='some text' customStyles={customStyles} />
    );
    const touchable = nthChild(output, 1);
    const view = nthChild(output, 2);
    const text = nthChild(output, 3);
    expect(normalizeStyle(touchable.props))
      .toEqual(objectContaining({ underlayColor: 'green' }));
    expect(normalizeStyle(view.props.style))
      .toEqual(objectContaining(customStyles.triggerWrapper));
    expect(normalizeStyle(text.props.style))
      .toEqual(objectContaining(customStyles.triggerText));
  });

});
<commit_msg>reduced views in trigger - tests<commit_after>import React from 'react';
import { TouchableHighlight, View, Text } from 'react-native';
import { render, normalizeStyle, nthChild } from './helpers';

jest.dontMock('../src/MenuTrigger');
jest.dontMock('../src/helpers');
const MenuTrigger = require('../src/MenuTrigger').default;
const { createSpy, objectContaining } = jasmine;

describe('MenuTrigger', () => {

  it('should render component', () => {
    const { output } = render(
      <MenuTrigger>
        <Text>Trigger Button</Text>
      </MenuTrigger>
    );
    expect(nthChild(output, 0).type).toEqual(TouchableHighlight);
    expect(nthChild(output, 1).type).toEqual(View);
    expect(nthChild(output, 2)).toEqual(
      <Text>Trigger Button</Text>
    );
  });

  it('should render component using text property', () => {
    const { output } = render(
      <MenuTrigger text='Trigger text' />
    );
    expect(nthChild(output, 0).type).toEqual(TouchableHighlight);
    expect(nthChild(output, 1).type).toEqual(View);
    expect(nthChild(output, 2)).toEqual(
      <Text>Trigger text</Text>
    );
  });

  it('should be enabled by default', () => {
    const { instance } = render(
      <MenuTrigger />
    );
    expect(instance.props.disabled).toBe(false);
  });

  it('should trigger on ref event', () => {
    const onRefSpy = createSpy();
    const { output } = render(
      <MenuTrigger onRef={onRefSpy} />
    );
    const triggerView = nthChild(output, 1);
    expect(typeof triggerView.ref).toEqual('function');
    triggerView.ref();
    expect(onRefSpy).toHaveBeenCalled();
    expect(onRefSpy.calls.count()).toEqual(1);
  });

  it('should open menu', () => {
    const { output, instance } = render(
      <MenuTrigger menuName='menu1' />
    );
    const menuActions = { openMenu: createSpy() };
    instance.context = { menuActions };
    nthChild(output, 0).props.onPress();
    expect(menuActions.openMenu).toHaveBeenCalledWith('menu1');
    expect(menuActions.openMenu.calls.count()).toEqual(1);
  });

  it('should not open menu when disabled', () => {
    const { output, instance } = render(
      <MenuTrigger menuName='menu1' disabled={true} />
    );
    const menuActions = { openMenu: createSpy() };
    instance.context = { menuActions };
    nthChild(output, 0).props.onPress();
    expect(menuActions.openMenu).not.toHaveBeenCalled();
  });

  it('should render trigger with custom styles', () => {
    const customStyles = {
      triggerWrapper: { backgroundColor: 'red' },
      triggerText: { color: 'blue' },
      triggerTouchable: { underlayColor: 'green' },
    };
    const { output } = render(
      <MenuTrigger menuName='menu1' text='some text' customStyles={customStyles} />
    );
    const touchable = nthChild(output, 0);
    const view = nthChild(output, 1);
    const text = nthChild(output, 2);
    expect(normalizeStyle(touchable.props))
      .toEqual(objectContaining({ underlayColor: 'green' }));
    expect(normalizeStyle(view.props.style))
      .toEqual(objectContaining(customStyles.triggerWrapper));
    expect(normalizeStyle(text.props.style))
      .toEqual(objectContaining(customStyles.triggerText));
  });

});
<|endoftext|>


<commit_before>var path = require( 'path' );
var fs = require( 'fs' );

// Creates a rollup config object for the given file to
// be converted to umd
function createOutput( file ) {

	var inputPath = path.resolve( file );
	var outputPath = inputPath.replace( /[\\\/]examples[\\\/]jsm[\\\/]/, '/examples/js/' );

	// Every import is marked as external so the output is 1-to-1. We
	// assume that that global object should be the THREE object so we
	// replicate the existing behavior.
	return {

		input: inputPath,
		treeshake: false,
		external: p => p !== inputPath,

		output: {

			format: 'umd',
			name: 'THREE',
			file: outputPath,

			globals: () => 'THREE',
			extend: true,

			banner:
				'/**\n' +
				` * Generated from '${ path.relative( '.', inputPath.replace( /\\/, '/' ) ) }'\n` +
				' **/\n'

		}

	};

}

// Walk the file structure starting at the given directory and fire
// the callback for every file.
function walk( dir, cb ) {

	var files = fs.readdirSync( dir );
	files.forEach( f => {

		var p = path.join( dir, f );
		var stats = fs.statSync( p );
		if ( stats.isDirectory() ) {

			walk( p, cb );

		} else {

			cb( p );

		}

	} );

}

// Gather up all the files
var files = [];
walk( 'examples/jsm/', p => files.push( p ) );

// Create a rollup config for each module.js file
export default files.map( p => createOutput( p ) );
<commit_msg>Update banner, convert three.module path to 'three'<commit_after>var path = require( 'path' );
var fs = require( 'fs' );

// Creates a rollup config object for the given file to
// be converted to umd
function createOutput( file ) {

	var inputPath = path.resolve( file );
	var outputPath = inputPath.replace( /[\\\/]examples[\\\/]jsm[\\\/]/, '/examples/js/' );

	// Every import is marked as external so the output is 1-to-1. We
	// assume that that global object should be the THREE object so we
	// replicate the existing behavior.
	return {

		input: inputPath,
		treeshake: false,
		external: p => p !== inputPath,

		output: {

			format: 'umd',
			name: 'THREE',
			file: outputPath,

            globals: () => 'THREE',
            paths: p => /three\.module\.js$/.test( p ) ? 'three' : p,
			extend: true,

			banner:
				'/**\n' +
				` * Generated from '${ path.relative( '.', inputPath.replace( /\\/, '/' ) ) }'\n` +
				' */\n'

		}

	};

}

// Walk the file structure starting at the given directory and fire
// the callback for every file.
function walk( dir, cb ) {

	var files = fs.readdirSync( dir );
	files.forEach( f => {

		var p = path.join( dir, f );
		var stats = fs.statSync( p );
		if ( stats.isDirectory() ) {

			walk( p, cb );

		} else {

			cb( p );

		}

	} );

}

// Gather up all the files
var files = [];
walk( 'examples/jsm/', p => files.push( p ) );

// Create a rollup config for each module.js file
export default files.map( p => createOutput( p ) );
<|endoftext|>