all files / keystone/fields/types/location/ LocationType.js

48.56% Statements 101/208
35.03% Branches 55/157
31.25% Functions 10/32
48.54% Lines 100/206
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490                                                                                       18× 18×     18×                                                                                             30×                                                                                       12×           10×     10×                       33×           32× 16×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
var _ = require('lodash');
var FieldType = require('../Type');
var https = require('https');
var keystone = require('../../../');
var querystring = require('querystring');
var util = require('util');
var utils = require('keystone-utils');
 
var RADIUS_KM = 6371;
var RADIUS_MILES = 3959;
 
/**
 * Location FieldType Constructor
 */
function location (list, path, options) {
 
	this._underscoreMethods = ['format', 'googleLookup', 'kmFrom', 'milesFrom'];
	this._fixedSize = 'full';
	this._properties = ['enableMapsAPI'];
	this.enableMapsAPI = (options.geocodeGoogle === true || (options.geocodeGoogle !== false && keystone.get('google server api key'))) ? true : false;
 
	Eif (!options.defaults) {
		options.defaults = {};
	}
 
	if (options.required) {
		Eif (Array.isArray(options.required)) {
			// required can be specified as an array of paths
			this.requiredPaths = options.required;
		} else if (typeof options.required === 'string') {
			// or it can be specified as a comma-delimited list
			this.requiredPaths = options.required.replace(/,/g, ' ').split(/\s+/);
		}
		// options.required should always be simplified to a boolean
		options.required = true;
	}
 
	// default this.requiredPaths
	if (!this.requiredPaths) {
		this.requiredPaths = ['street1', 'suburb'];
	}
 
	location.super_.call(this, list, path, options);
}
util.inherits(location, FieldType);
 
/**
 * Registers the field on the List's Mongoose Schema.
 */
location.prototype.addToSchema = function () {
 
	var field = this;
	var schema = this.list.schema;
	var options = this.options;
 
	var paths = this.paths = {
		number: this._path.append('.number'),
		name: this._path.append('.name'),
		street1: this._path.append('.street1'),
		street2: this._path.append('.street2'),
		suburb: this._path.append('.suburb'),
		state: this._path.append('.state'),
		postcode: this._path.append('.postcode'),
		country: this._path.append('.country'),
		geo: this._path.append('.geo'),
		geo_lat: this._path.append('.geo_lat'),
		geo_lng: this._path.append('.geo_lng'),
		serialised: this._path.append('.serialised'),
		improve: this._path.append('_improve'),
		overwrite: this._path.append('_improve_overwrite'),
	};
 
	var getFieldDef = function (type, key) {
		var def = { type: type };
		Iif (options.defaults[key]) {
			def.default = options.defaults[key];
		}
		return def;
	};
 
	schema.nested[this.path] = true;
	schema.add({
		number: getFieldDef(String, 'number'),
		name: getFieldDef(String, 'name'),
		street1: getFieldDef(String, 'street1'),
		street2: getFieldDef(String, 'street2'),
		street3: getFieldDef(String, 'street3'),
		suburb: getFieldDef(String, 'suburb'),
		state: getFieldDef(String, 'state'),
		postcode: getFieldDef(String, 'postcode'),
		country: getFieldDef(String, 'country'),
		geo: { type: [Number], index: '2dsphere' },
	}, this.path + '.');
 
	schema.virtual(paths.serialised).get(function () {
		return _.compact([
			this.get(paths.number),
			this.get(paths.name),
			this.get(paths.street1),
			this.get(paths.street2),
			this.get(paths.suburb),
			this.get(paths.state),
			this.get(paths.postcode),
			this.get(paths.country),
		]).join(', ');
	});
 
	// pre-save hook to fix blank geo fields
	// see http://stackoverflow.com/questions/16388836/does-applying-a-2dsphere-index-on-a-mongoose-schema-force-the-location-field-to
	schema.pre('save', function (next) {
		var obj = field._path.get(this);
		if (Array.isArray(obj.geo) && (obj.geo.length !== 2 || (obj.geo[0] === null && obj.geo[1] === null))) {
			obj.geo = undefined;
		}
		next();
	});
 
	this.bindUnderscoreMethods();
};
 
/**
 * Add filters to a query
 */
var FILTER_PATH_MAP = {
	street: 'street1',
	city: 'suburb',
	state: 'state',
	code: 'postcode',
	country: 'country',
};
location.prototype.addFilterToQuery = function (filter, query) {
	query = query || {};
	var field = this;
	['street', 'city', 'state', 'code', 'country'].forEach(function (i) {
		if (!filter[i]) return;
		var value = utils.escapeRegExp(filter[i]);
		value = new RegExp(value, 'i');
		query[field.paths[FILTER_PATH_MAP[i]]] = filter.inverted ? { $not: value } : value;
	});
	return query;
};
 
/**
 * Formats a list of the values stored by the field. Only paths that
 * have values will be included.
 *
 * Optionally provide a space-separated list of values to include.
 *
 * Delimiter defaults to `', '`.
 */
location.prototype.format = function (item, values, delimiter) {
	if (!values) {
		return item.get(this.paths.serialised);
	}
	var paths = this.paths;
	values = values.split(' ').map(function (i) {
		return item.get(paths[i]);
	});
	return _.compact(values).join(delimiter || ', ');
};
 
/**
 * Detects whether the field has been modified
 */
location.prototype.isModified = function (item) {
	return item.isModified(this.paths.number)
	|| item.isModified(this.paths.name)
	|| item.isModified(this.paths.street1)
	|| item.isModified(this.paths.street2)
	|| item.isModified(this.paths.suburb)
	|| item.isModified(this.paths.state)
	|| item.isModified(this.paths.postcode)
	|| item.isModified(this.paths.country)
	|| item.isModified(this.paths.geo);
};
 
/**
 * Validates that a value for this field has been provided in a data object
 *
 * options.required specifies an array or space-delimited list of paths that
 * are required (defaults to street1, suburb)
 *
 * Deprecated
 */
location.prototype.inputIsValid = function (data, required, item) {
	Iif (!required) return true;
	var paths = this.paths;
	var nested = this._path.get(data);
	var values = nested || data;
	var valid = true;
	this.requiredPaths.forEach(function (path) {
		if (nested) {
			Iif (!(path in values) && item && item.get(paths[path])) {
				return;
			}
			Iif (!values[path]) {
				valid = false;
			}
		} else {
			Iif (!(paths[path] in values) && item && item.get(paths[path])) {
				return;
			}
			if (!values[paths[path]]) {
				valid = false;
			}
		}
	});
	return valid;
};
 
/**
 * Updates the value for this field in the item from a data object
 */
location.prototype.updateItem = function (item, data, callback) {
 
	var paths = this.paths;
	var fieldKeys = ['number', 'name', 'street1', 'street2', 'suburb', 'state', 'postcode', 'country'];
	var geoKeys = ['geo', 'geo_lat', 'geo_lng'];
	var valueKeys = fieldKeys.concat(geoKeys);
	var valuePaths = valueKeys;
	var values = this._path.get(data);
 
	if (!values) {
		// Handle flattened values
		valuePaths = valueKeys.map(function (i) {
			return paths[i];
		});
		values = _.pick(data, valuePaths);
	}
 
	// convert valuePaths to a map for easier usage
	valuePaths = _.zipObject(valueKeys, valuePaths);
 
	var setValue = function (key) {
		if (valuePaths[key] in values && values[valuePaths[key]] !== item.get(paths[key])) {
			item.set(paths[key], values[valuePaths[key]] || null);
		}
	};
 
	_.forEach(fieldKeys, setValue);
 
	if (valuePaths.geo in values) {
		var oldGeo = item.get(paths.geo) || [];
		Iif (oldGeo.length > 1) {
			oldGeo[0] = item.get(paths.geo)[1];
			oldGeo[1] = item.get(paths.geo)[0];
		}
		var newGeo = values[valuePaths.geo];
		Iif (!Array.isArray(newGeo) || newGeo.length !== 2) {
			newGeo = [];
		}
		Eif (newGeo[0] !== oldGeo[0] || newGeo[1] !== oldGeo[1]) {
			item.set(paths.geo, newGeo);
		}
	} else Eif (valuePaths.geo_lat in values && valuePaths.geo_lng in values) {
		var lat = utils.number(values[valuePaths.geo_lat]);
		var lng = utils.number(values[valuePaths.geo_lng]);
		item.set(paths.geo, (lat && lng) ? [lng, lat] : undefined);
	}
 
	process.nextTick(callback);
};
 
/**
 * Returns a callback that handles a standard form submission for the field
 *
 * Handles:
 * - `field.paths.improve` in `req.body` - improves data via `.googleLookup()`
 * - `field.paths.overwrite` in `req.body` - in conjunction with `improve`, overwrites existing data
 */
location.prototype.getRequestHandler = function (item, req, paths, callback) {
	var field = this;
	if (utils.isFunction(paths)) {
		callback = paths;
		paths = field.paths;
	} else if (!paths) {
		paths = field.paths;
	}
	callback = callback || function () {};
	return function () {
		var update = req.body[paths.overwrite] ? 'overwrite' : true;
		if (req.body && req.body[paths.improve]) {
			field.googleLookup(item, false, update, function () {
				callback();
			});
		} else {
			callback();
		}
	};
};
 
/**
 * Immediately handles a standard form submission for the field (see `getRequestHandler()`)
 */
location.prototype.handleRequest = function (item, req, paths, callback) {
	this.getRequestHandler(item, req, paths, callback)();
};
 
/**
 * Internal Google geocode request method
 */
function doGoogleGeocodeRequest (address, region, callback) {
 
	// https://developers.google.com/maps/documentation/geocoding/
	// Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day, except with an enterprise license.
	// Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited.
	// Please make sure your Keystone app complies with the Google Maps API License.
 
	var options = {
		sensor: false,
		language: 'en',
		address: address,
	};
 
	if (arguments.length === 2 && _.isFunction(region)) {
		callback = region;
		region = null;
	}
 
	if (region) {
		options.region = region;
	}
 
	if (keystone.get('google server api key')) {
		options.key = keystone.get('google server api key');
	}
 
	var endpoint = 'https://maps.googleapis.com/maps/api/geocode/json?' + querystring.stringify(options);
 
	https.get(endpoint, function (res) {
		var data = [];
		res.on('data', function (chunk) {
			data.push(chunk);
		})
		.on('end', function () {
			var dataBuff = data.join('').trim();
			var result;
			try {
				result = JSON.parse(dataBuff);
			}
			catch (exp) {
				result = {
					status_code: 500,
					status_text: 'JSON Parse Failed',
					status: 'UNKNOWN_ERROR',
				};
			}
			callback(null, result);
		});
	})
	.on('error', function (err) {
		callback(err);
	});
}
 
/**
 * Autodetect the full address and lat, lng from the stored value.
 *
 * Uses Google's Maps API and may only be used in conjunction with a Google map.
 * Geocoding results without displaying them on a map is prohibited.
 * Please make sure your Keystone app complies with the Google Maps API License.
 *
 * Internal status codes mimic the Google API status codes.
 */
location.prototype.googleLookup = function (item, region, update, callback) {
 
	if (_.isFunction(update)) {
		callback = update;
		update = false;
	}
 
	var field = this;
	var stored = item.get(this.path);
	var address = item.get(this.paths.serialised);
 
	if (address.length === 0) {
		return callback({
			status_code: 500,
			status_text: 'No address to geocode',
			status: 'NO_ADDRESS',
		});
	}
 
	doGoogleGeocodeRequest(address, region || keystone.get('default region'), function (err, geocode) {
 
		if (err || geocode.status !== 'OK') {
			return callback(err || new Error(geocode.status + ': ' + geocode.error_message));
		}
 
		// use the first result
		// if there were no results in the array, status would be ZERO_RESULTS
		var result = geocode.results[0];
 
		// parse the address components into a location object
 
		var location = {};
 
		_.forEach(result.address_components, function (val) {
			if (_.indexOf(val.types, 'street_number') >= 0) {
				location.street1 = location.street1 || [];
				location.street1.push(val.long_name);
			}
			if (_.indexOf(val.types, 'route') >= 0) {
				location.street1 = location.street1 || [];
				location.street1.push(val.short_name);
			}
			// in some cases, you get suburb, city as locality - so only use the first
			if (_.indexOf(val.types, 'locality') >= 0 && !location.suburb) {
				location.suburb = val.long_name;
			}
			if (_.indexOf(val.types, 'administrative_area_level_1') >= 0) {
				location.state = val.short_name;
			}
			if (_.indexOf(val.types, 'country') >= 0) {
				location.country = val.long_name;
			}
			if (_.indexOf(val.types, 'postal_code') >= 0) {
				location.postcode = val.short_name;
			}
		});
 
		if (Array.isArray(location.street1)) {
			location.street1 = location.street1.join(' ');
		}
 
		location.geo = [
			result.geometry.location.lng,
			result.geometry.location.lat,
		];
 
		// console.log('------ Google Geocode Results ------');
		// console.log(address);
		// console.log(result);
		// console.log(location);
 
		if (update === 'overwrite') {
			item.set(field.path, location);
		} else if (update) {
			_.forEach(location, function (value, key) {
				if (key === 'geo') {
					return;
				}
				if (!stored[key]) {
					item.set(field.paths[key], value);
				}
			});
			if (!Array.isArray(stored.geo) || !stored.geo[0] || !stored.geo[1]) {
				item.set(field.paths.geo, location.geo);
			}
		}
 
		callback(null, location, result);
 
	});
};
 
/**
 * Internal Distance calculation function
 *
 * See http://en.wikipedia.org/wiki/Haversine_formula
 */
function calculateDistance (point1, point2) {
	var dLng = (point2[0] - point1[0]) * Math.PI / 180;
	var dLat = (point2[1] - point1[1]) * Math.PI / 180;
	var lat1 = (point1[1]) * Math.PI / 180;
	var lat2 = (point2[1]) * Math.PI / 180;
	/* eslint-disable space-infix-ops */
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLng/2) * Math.sin(dLng/2) * Math.cos(lat1) * Math.cos(lat2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	/* eslint-enable space-infix-ops */
	return c;
}
 
/**
 * Returns the distance from a [lat, lng] point in kilometres
 */
location.prototype.kmFrom = function (item, point) {
	return calculateDistance(this.get(this.paths.geo), point) * RADIUS_KM;
};
 
/**
 * Returns the distance from a [lat, lng] point in miles
 */
location.prototype.milesFrom = function (item, point) {
	return calculateDistance(this.get(this.paths.geo), point) * RADIUS_MILES;
};
 
/* Export Field Type */
module.exports = location;