pd-api
Version:
889 lines (876 loc) • 24.7 kB
JavaScript
import { Inject, Injectable, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CrossStorageClient } from 'cross-storage';
import { Observable } from 'rxjs';
import moment from 'moment';
import { Observable as Observable$1 } from 'rxjs/Observable';
import 'rxjs/Rx';
/**
* Api helper
* For static and pure functions
*/
var ApiHelper = (function () {
function ApiHelper() {
}
/**
* @param {?} host
* @param {?} method
* @param {?=} query
* @return {?}
*/
ApiHelper.GenerateURL = function (host, method, query) {
var /** @type {?} */ keys = [];
for (var /** @type {?} */ key in query) {
if (query.hasOwnProperty(key) && key) {
keys.push(key);
}
}
if (!query || keys.length === 0) {
return host + method;
}
var /** @type {?} */ params = keys.reduce(function (url, key) {
if (url !== '?') {
url += '&';
}
if (typeof query[key] !== 'undefined') {
return url + key + '=' + query[key];
}
else {
return url;
}
}, '?');
return host + method + params;
};
return ApiHelper;
}());
// Core
// Global
// todo path must be relative
// import { environment } from "../../environments/environment";
// Ghetto
var ANAL_HOSTS = {
dev: 'https://anl.anldev.pingdelivery.com/v1/',
prod: 'https://anl.pingdelivery.com/v1/'
};
var PLATFORM_HOSTS = {
dev: 'https://ulc.apidev.pingdelivery.com/v1/',
prod: 'https://api.pingdelivery.com/v1/'
};
/**
* Hosts
*/
var HOSTS = {
// analytics: environment.production ? ANAL_HOSTS.prod : ANAL_HOSTS.dev,
analytics: ANAL_HOSTS.prod,
// platform: environment.production ? PLATFORM_HOSTS.prod : PLATFORM_HOSTS.dev,
platform: PLATFORM_HOSTS.prod,
hub: null
};
var ApiService = (function () {
/**
* Constructor method
* @param {?} http
* @param {?} auth
* @param {?} env Inject 'api.env' environment
*/
function ApiService(http, auth, env) {
this.http = http;
this.auth = auth;
this.env = env;
HOSTS.platform = env.production ? PLATFORM_HOSTS.prod : PLATFORM_HOSTS.dev;
console.info(env);
console.info(HOSTS);
}
/**
* Make GET Request
* @param {?} host
* @param {?} method
* @param {?} query
* @return {?}
*/
ApiService.prototype.get = function (host, method, query) {
var _this = this;
var /** @type {?} */ url = ApiHelper.GenerateURL(host, method, query);
return this.http.get(url, this.generateOptions(host))
.map(function (res) {
return res.json();
})
.catch(function (error) {
console.error(error);
_this.handleResponseError(error);
var /** @type {?} */ _error = error = error.json().error;
throw _error;
});
};
/**
* Make POST Request
* @param {?} host
* @param {?} method
* @param {?} body
* @return {?}
*/
ApiService.prototype.post = function (host, method, body) {
var _this = this;
var /** @type {?} */ url = ApiHelper.GenerateURL(host, method);
return this.http.post(url, body, this.generateOptions(host))
.map(function (res) {
var /** @type {?} */ obj = res.json();
return obj;
})
.catch(function (error) {
_this.handleResponseError(error);
// Convert object to ApiError
var /** @type {?} */ _error = error = error.json().error;
throw _error;
});
};
/**
* Generate request options => headers, token, etc
* @param {?} host
* @return {?}
*/
ApiService.prototype.generateOptions = function (host) {
if (host.includes('anl')) {
return ({});
}
var /** @type {?} */ headers = {
'authorization': this.auth.getToken().key,
};
var /** @type {?} */ options = ({
headers: /** @type {?} */ (headers),
withCredentials: true
});
return options;
};
/**
* Response errors handler
* @param {?} error
* @return {?}
*/
ApiService.prototype.handleResponseError = function (error) {
if (error.status === 401) {
this.auth.reLogin();
}
};
return ApiService;
}());
ApiService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
ApiService.ctorParameters = function () { return [
{ type: Http, },
{ type: AuthService, },
{ type: undefined, decorators: [{ type: Inject, args: ['environment',] },] },
]; };
var __assign = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var HUB_HOSTS = {
dev: 'https://cross-storage.fntdev.pingdelivery.com/index.html',
prod: 'https://cross-storage.pingdelivery.com/index.html'
};
var AuthService = (function () {
/**
* @param {?} env
*/
function AuthService(env) {
var _this = this;
this.env = env;
this.HUB_HOST = HOSTS.hub;
HOSTS.hub = env.production ? HUB_HOSTS.prod : HUB_HOSTS.dev;
this.HUB_HOST = HOSTS.hub;
console.info('Cross-Domain storage: ', this.HUB_HOST);
this.onLogin = new Observable(function (observer) { return _this._login = observer; });
this.onLogout = new Observable(function (observer) { return _this._logout = observer; });
this.token = JSON.parse(localStorage.getItem('user.token'));
this.hub = new CrossStorageClient(this.HUB_HOST, {
frameId: 'storageFrame'
});
}
/**
* Get copy of token
* @return {?}
*/
AuthService.prototype.getToken = function () {
return __assign({}, this.token);
};
/**
* Save token to local storage and to iFrame for cross-domain auth
* @param {?} token
* @return {?}
*/
AuthService.prototype.saveToken = function (token) {
var _this = this;
localStorage.setItem('user.token', JSON.stringify(token));
this.token = token;
this.saveTokenToHub(this.token)
.then(function () {
console.info('Token saved to cross-storage HUB: ', _this.HUB_HOST);
});
};
/**
* Save token to cross-domain hub
* @param {?} token
* @return {?}
*/
AuthService.prototype.saveTokenToHub = function (token) {
var _this = this;
return this.hub.onConnect()
.then(function () {
// console.log('hub ready!');
return _this.hub.set('user.token', JSON.stringify(token));
})
.then(function () {
// console.log('token saved to hub');
});
};
/**
* Open modal window for reLogin
* @return {?}
*/
AuthService.prototype.reLogin = function () {
// this.router.navigate(['/login']);
if (this._login) {
this._login.next();
}
};
/**
* Redirect to login form
* @return {?}
*/
AuthService.prototype.logout = function () {
if (this._logout) {
this._logout.next();
}
// this.router.navigate(['/login']);
};
/**
* Remove token from local storage and iFrame
* @return {?}
*/
AuthService.prototype.removeToken = function () {
this.hub.del('user.token');
localStorage.removeItem('user.token');
this.token = null;
// todo remove from iFrame
};
/**
* Check token in local storage
* todo must Check token exp date
* @return {?}
*/
AuthService.prototype.isLoggedIn = function () {
// localStorage.getItem('user.token');
var _this = this;
return this.hub.onConnect()
.then(function () {
// console.log('hub ready!');
return _this.hub.get('user.token');
})
.then(function (tokenJson) {
// console.log('hub data received');
if (tokenJson) {
// console.log('hub data sate to local storage');
_this.token = JSON.parse(tokenJson);
_this.saveToken(_this.token);
return true;
}
else {
// console.log('error hub data');
return false;
}
});
};
return AuthService;
}());
AuthService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
AuthService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: ['environment',] },] },
]; };
// Core
// Ghetto
var AnalyticsService = (function () {
/**
* @param {?} api
*/
function AnalyticsService(api) {
this.api = api;
this.host = HOSTS.analytics;
}
/**
* @param {?} country
* @param {?} from
* @param {?} to
* @param {?=} timezone
* @return {?}
*/
AnalyticsService.prototype.getTopRejectReasons = function (country, from, to, timezone) {
// http://anl.anldev.pingdelivery.com/v1/
// report/reject-reason-top
// ?from=2016-11-02
// &to=2016-11-12
// &tz=America/Mexico_City
// &by=day
var /** @type {?} */ method = 'report/reject-reason-top';
var /** @type {?} */ params = {
by: 'day',
country: country.id,
from: from.format('YYYY-MM-DD'),
to: to.format('YYYY-MM-DD'),
tz: 'UTC'
};
return this.api.get(this.host, method, params)
.map(function (res) {
if (res.success) {
var /** @type {?} */ reasons = [];
for (var /** @type {?} */ key in res.data.total) {
if (!res.data.total.hasOwnProperty(key)) {
continue;
}
reasons.push({
name: key,
count: res.data.total[key].count,
diff: res.data.total[key].diff,
});
}
res.data = reasons;
return res.data;
}
throw res.error;
});
};
/**
* @param {?} country
* @param {?} from
* @param {?} to
* @param {?=} timezone
* @return {?}
*/
AnalyticsService.prototype.getBuyout = function (country, from, to, timezone) {
var /** @type {?} */ method = 'report/calculate-buyout';
var /** @type {?} */ countryParam = Array.isArray(country) ? country.map(function (c) { return c.id; }).join() : country.id;
var /** @type {?} */ params = {
by_date: 'delivery_desired',
country: countryParam,
from: from.format('YYYY-MM-DD'),
to: to.format('YYYY-MM-DD'),
metric: 'buyout',
pending: 1,
template: 'manager_table',
type: 'xlsx',
tz: timezone || 'UTC'
};
return this.api.get(this.host, method, params)
.map(function (res) {
if (res.success) {
return res.data;
}
throw res.error;
});
};
/**
* @param {?} country
* @param {?} from
* @param {?} to
* @param {?=} timezone
* @return {?}
*/
AnalyticsService.prototype.getNewOrders = function (country, from, to, timezone) {
// http://anl.pingdelivery.com/v1/
// report/calculate-buyout
// ?by_date=created
// &country=PE
// &from=2017-01-01
// &to=2017-01-31
// &metric=buyout
// &pending=1
// &template=new_orders
// &type=xlsx
// &tz=UTC
var /** @type {?} */ method = 'report/calculate-buyout';
var /** @type {?} */ params = {
by_date: 'created',
country: country.id,
from: from.format('YYYY-MM-DD'),
to: to.format('YYYY-MM-DD'),
metric: 'buyout',
pending: 1,
template: 'new_orders',
type: 'xlsx',
tz: country.timezone
};
return this.api.get(this.host, method, params)
.map(function (res) {
if (res.success) {
return res.data;
}
throw res.error;
});
};
/**
* @param {?} country
* @param {?} from
* @param {?} to
* @param {?=} template
* @param {?=} timezone
* @return {?}
*/
AnalyticsService.prototype.getPlanFact = function (country, from, to, template, timezone) {
// http://anl.anldev.pingdelivery.com/v1/report/plan-fact-last-mile
// ?tz=UTC
// &from=2016-10-29
// &to=2016-10-30
// &template=total_total
// &partner_lm=FedEx
if (template === void 0) { template = 'total'; }
var /** @type {?} */ method = 'report/plan-fact-last-mile';
var /** @type {?} */ countryParam = Array.isArray(country) ? country.map(function (c) { return c.id; }).join() : country.id;
var /** @type {?} */ params = {
by_date: 'delivery_desired',
country: countryParam,
from: from.format('YYYY-MM-DD'),
to: to.format('YYYY-MM-DD'),
template: template,
tz: timezone || Array.isArray(country) ? 'UTC' : country.timezone
};
return this.api.get(this.host, method, params)
.map(function (res) {
// todo handle analytics backend error
return res.data;
});
};
/**
* @param {?} country
* @param {?} from
* @param {?} to
* @return {?}
*/
AnalyticsService.prototype.getBestBuyout = function (country, from, to) {
// http://anl.anldev.pingdelivery.com/v1/
// report/calculate-buyout
// ?by_date=delivery_desired
// &country=MY
// &from=2017-02-01
// &to=2017-02-08
// &metric=buyout
// &pending=1
// &template=best_buyout
// &type=xlsx
// &tz=UTC
var /** @type {?} */ method = 'report/calculate-buyout';
var /** @type {?} */ params = {
by_date: 'delivery_desired',
country: country.id,
from: from.format('YYYY-MM-DD'),
to: to.format('YYYY-MM-DD'),
metric: 'buyout',
pending: 1,
template: 'best_buyout',
type: 'xlsx',
tz: 'UTC'
};
return this.api.get(this.host, method, params)
.map(function (res) {
// todo handle analytics backend error
return res.data;
});
};
return AnalyticsService;
}());
AnalyticsService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
AnalyticsService.ctorParameters = function () { return [
{ type: ApiService, },
]; };
/**
* Global Country Names
*/
var countryNames = {
'BO': {
'name': 'Bolivia',
'timezone': 'America/La_Paz',
},
'CO': {
'name': 'Colombia',
'timezone': 'America/Bogota',
},
'CL': {
'name': 'Chile',
'timezone': 'America/Santiago',
},
'AR': {
'name': 'Argentina',
'timezone': 'America/Argentina/Buenos_Aires',
},
'MX': {
'name': 'Mexico',
'timezone': 'America/Mexico_City',
},
'PE': {
'name': 'Peru',
'timezone': 'America/Lima',
},
'ID': {
'name': 'Indonesia',
'timezone': 'Asia/Jakarta',
},
'IN': {
'name': 'India',
'timezone': 'Asia/Kolkata',
},
'MY': {
'name': 'Malaysia',
'timezone': 'Asia/Kuala_Lumpur',
},
'NG': {
'name': 'Nigeria',
'timezone': 'Africa/Luanda',
},
'PH': {
'name': 'Phillipines',
'timezone': 'Asia/Manila',
},
'KH': {
'name': 'Cambodia',
'timezone': 'Asia/Phnom_Penh',
},
'UZ': {
'name': 'Uzbekistan',
'timezone': 'Asia/Karachi',
},
'TJ': {
'name': 'Tadjikistan',
'timezone': 'Asia/Karachi',
},
'LK': {
'name': 'Sri Lanka',
'timezone': 'Asia/Colombo',
},
'LA': {
'name': 'Laos',
'timezone': 'Asia/Vientiane',
},
'TT': {
'name': 'Testaria',
'timezone': 'Asia/Tbilisi',
},
'GE': {
'name': 'Georgia',
'timezone': 'Asia/Tbilisi',
},
'GH': {
'name': 'Ghana',
'timezone': 'UTC',
}
};
// Core
// Ghetto
var CountryService = (function () {
function CountryService() {
this.countryNames = countryNames;
}
/**
* @param {?} country_1
* @param {?} country_2
* @return {?}
*/
CountryService.isEqual = function (country_1, country_2) {
return country_1.id === country_2.id;
};
/**
* @param {?} user
* @return {?}
*/
CountryService.prototype.getCountriesForUser = function (user) {
return new Observable$1(function (subscriber) {
subscriber.next(user.countries);
});
};
/**
* Get Country By id
* @param {?} id
* @return {?}
*/
CountryService.prototype.countryById = function (id) {
if (!this.countryNames.hasOwnProperty(id)) {
return {
id: id,
name: id,
timezone: 'UTC'
};
}
return {
id: id,
name: this.countryNames[id].name,
timezone: this.countryNames[id].timezone
};
};
return CountryService;
}());
CountryService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
CountryService.ctorParameters = function () { return []; };
// import * as moment from 'moment';
var UserApiService = (function () {
/**
* @param {?} api
* @param {?} country
*/
function UserApiService(api, country) {
this.api = api;
this.country = country;
this.host = HOSTS.platform;
}
/**
* Get user token by login and password
* @param {?} login
* @param {?} password
* @return {?}
*/
UserApiService.prototype.getUserToken = function (login, password) {
// POST
var /** @type {?} */ method = 'users/token';
var /** @type {?} */ params = {
login: login,
password: password
};
return this.api.post(this.host, method, params)
.map(function (res) {
// todo handle egor backend error
return res;
})
.catch(function (error) {
throw error;
});
};
/**
* Get User info
* @return {?}
*/
UserApiService.prototype.getUserInfo = function () {
var _this = this;
var /** @type {?} */ method = 'users/info';
return this.api.get(this.host, method, {})
.map(function (res) {
// todo handle egor backend error
if (res.error) {
console.error(res.error);
throw res.error;
}
// Serialize countries
res.countries = res.countries
.map(function (id) {
return _this.country.countryById(id);
});
// Serialize country
res.country = _this.country.countryById(res.country);
// Serialize Dates
res.created = moment(res.created);
res.updated = moment(res.updated);
res.lastLogin = moment(res.lastLogin);
return res;
});
};
return UserApiService;
}());
UserApiService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
UserApiService.ctorParameters = function () { return [
{ type: ApiService, },
{ type: CountryService, },
]; };
var WarningsApiService = (function () {
/**
* @param {?} api
*/
function WarningsApiService(api) {
this.api = api;
this.host = HOSTS.platform;
}
/**
* @param {?} country
* @return {?}
*/
WarningsApiService.prototype.getWarningStats = function (country) {
// v1/operationApi/warningStat?country=country
var /** @type {?} */ method = 'operationApi/warningStat';
var /** @type {?} */ params = {
country: country.id,
};
return this.api.get(this.host, method, params)
.map(function (res) {
// todo handle analytics backend error
return res.data;
});
};
return WarningsApiService;
}());
WarningsApiService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
WarningsApiService.ctorParameters = function () { return [
{ type: ApiService, },
]; };
// Core
// Ghetto
var OrdersApiService = (function () {
/**
* @param {?} api
*/
function OrdersApiService(api) {
this.api = api;
this.host = HOSTS.platform;
}
/**
* @param {?} country
* @param {?} dateFrom
* @param {?} dateTo
* @return {?}
*/
OrdersApiService.prototype.getOrdersPerDay = function (country, dateFrom, dateTo) {
var /** @type {?} */ method = 'orders/month-average';
var /** @type {?} */ params = {
country: country.id,
};
return this.api.get(this.host, method, params)
.map(function (res) {
// todo handle analytics backend error
return res.data;
})
.catch(function (error) {
throw error;
});
};
return OrdersApiService;
}());
OrdersApiService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
OrdersApiService.ctorParameters = function () { return [
{ type: ApiService, },
]; };
var PrintersService = (function () {
/**
* @param {?} api
*/
function PrintersService(api) {
this.api = api;
}
/**
* @param {?} method
* @param {?=} body
* @return {?}
*/
PrintersService.prototype.requestToApi = function (method, body) {
var /** @type {?} */ host = 'http://ulc.apidev.pingdelivery.com/v1/';
return this.api.get(host, method, body);
};
/**
* @return {?}
*/
PrintersService.prototype.getPrinters = function () {
var /** @type {?} */ method = 'wms/get-printer-list';
return this.requestToApi(method).map(function (res) {
console.log(res);
return res.data;
});
};
return PrintersService;
}());
// const options: RequestOptionsArgs = {
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': '08e6c2b6932ad2c62743e9e16d98ca4a',
// },
// withCredentials: true
// };
//
// return this.http.get(url, options)
// .map((res: Response) => {
// console.log(res);
// return null;
// const data = res.json();
// if (data.success) {
// }
// })
// getPrinterApp(): Observable<any> {
//
// }
PrintersService.decorators = [
{ type: Injectable },
];
/**
* @nocollapse
*/
PrintersService.ctorParameters = function () { return [
{ type: ApiService, },
]; };
// API Services
var ApiModule = (function () {
function ApiModule() {
}
return ApiModule;
}());
// static forRoot(): ModuleWithProviders {
// return {
// ngModule: SampleModule,
// providers: [SampleService]
// };
// }
ApiModule.decorators = [
{ type: NgModule, args: [{
imports: [
CommonModule
],
declarations: [],
providers: [
ApiService,
AuthService,
CountryService,
AnalyticsService,
WarningsApiService,
OrdersApiService,
UserApiService,
PrintersService
]
},] },
];
/**
* @nocollapse
*/
ApiModule.ctorParameters = function () { return []; };
export { ApiModule, HOSTS, ApiService, AuthService, AnalyticsService, UserApiService, WarningsApiService, OrdersApiService, PrintersService, CountryService, countryNames };