skyhub
Version:
412 lines • 18.1 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = require("axios");
const eventemitter3_1 = require("eventemitter3");
const sleep_1 = require("./sleep");
var SkyHub;
(function (SkyHub) {
const BASE_URL = 'https://api.skyhub.com.br';
class Address {
}
SkyHub.Address = Address;
class OrderPayment {
}
SkyHub.OrderPayment = OrderPayment;
class OrderItem {
}
SkyHub.OrderItem = OrderItem;
class Order {
}
SkyHub.Order = Order;
/** Interface para definição de atributos como: Tamanho, Cor, Crossdocking, etc
* Exemplo: { "key": "Tamanho", "value: "M" }
* */
class Specification {
}
SkyHub.Specification = Specification;
/** Interface para definição de categorias
* Exemplo: { "code": "01", "name": "Blusa" }
* Exemplo Sub-categoria: { "code": "02", "name": "Blusa > Manga Curta" }
* */
class Category {
}
SkyHub.Category = Category;
class SimpleProduct {
}
SkyHub.SimpleProduct = SimpleProduct;
class Variation {
}
SkyHub.Variation = Variation;
class ProductWithVariation {
}
SkyHub.ProductWithVariation = ProductWithVariation;
class OrderShipment {
}
SkyHub.OrderShipment = OrderShipment;
class OrderShipmentItem {
}
SkyHub.OrderShipmentItem = OrderShipmentItem;
class OrderShipmentTrack {
}
SkyHub.OrderShipmentTrack = OrderShipmentTrack;
/*
* Exemplo: { "code": "payment_received", "label": "Pagamento aprovado", "type": "APPROVED" }*/
class OrderStatus {
}
SkyHub.OrderStatus = OrderStatus;
class OrderInvoice {
}
SkyHub.OrderInvoice = OrderInvoice;
class Customer {
}
SkyHub.Customer = Customer;
class RestClient {
options(data, params = undefined) {
/*
{
adapter: AxiosAdapter, auth: { username: '', password: '' }, baseURL: '',
cancelToken: CancelToken, data: any,
headers: any,
httpAgent: any, httpsAgent:any,
maxContentLength: string,
maxRedirects: number,
method: string,
onDownloadProgress: (progressEvent) => void,
onUploadProgress: (progressEvent) => void,
params: any,
paramsSerializer: string,
proxy: AxiosProxyConfig,
responseType: string,
timeout: number,
transformRequest: AxiosTransformer | AxiosTransformer[],
transformResponse: AxiosTransformer | AxiosTransformer[],
url: string,
validateStatus: boolean,
withCredentials: boolean,
xsrfCookieName: string,
xsrfHeaderName: string
}
*/
return { headers: this.headers, data: data, params: params };
}
full(api) {
let ew = `${this.baseUrl}`.indexOf('/') === `${this.baseUrl}`.length - 1;
let sw = `${api}`.indexOf('/') === 0;
if (ew && sw)
return `${this.baseUrl}${api.substr(1)}`;
if ((!ew && sw) || (ew && !sw))
return `${this.baseUrl}${api}`;
return `${this.baseUrl}/${api}`;
}
get(api, params, data = null) {
return axios_1.default.get(this.full(api), this.options(params, data));
}
post(api, data, params = undefined) {
return axios_1.default.post(this.full(api), data, this.options(data, params));
}
put(api, data) {
return axios_1.default.put(this.full(api), data, this.options(data));
}
delete(api, data) {
return axios_1.default.delete(this.full(api), this.options(data));
}
head(api, data) {
return axios_1.default.head(this.full(api), this.options(data));
}
translateMethod(method) { return method; }
custom(method, api, data, params) {
let o = this.options(data, params);
o.url = api;
o.method = this.translateMethod(`${method}`.toLowerCase());
return axios_1.default.request(o);
}
constructor(baseUrl, headers) {
this.baseUrl = baseUrl;
this.headers = headers;
}
}
class Client extends eventemitter3_1.EventEmitter {
constructor(parameters) {
super();
this.headers = {
"Content-Type": "application/json",
Accept: "application/json;charset=UTF-8",
"X-Accountmanager-Key": null,
"X-Api-Key": null,
"X-User-Email": null
};
if (typeof parameters === 'undefined')
throw new Error(`Missing initialization 'parameters'`);
if (typeof parameters !== 'object' || Array.isArray(parameters))
throw new Error('Initialization parameters must be an object');
if (!parameters.userEmail)
throw new Error(`Missing 'userEmail' on initialization parameters`);
if (!parameters.apiKey)
throw new Error(`Missing 'apiKey' on initialization parameters`);
if (!parameters.accountManagerKey)
throw new Error(`Missing 'accountManagerKey' on initialization parameters`);
this.headers["X-User-Email"] = parameters.userEmail;
this.headers["X-Api-Key"] = parameters.apiKey;
this.headers["X-Accountmanager-Key"] = parameters.accountManagerKey;
this.client = new RestClient(BASE_URL, this.headers);
}
post(api, data) {
return __awaiter(this, void 0, void 0, function* () {
var res;
var start = Date.now();
try {
res = this.lastResponse = yield this.client.post(api, data);
if (res.status === 201)
return { success: true, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
}
catch (e) {
res = yield e.response;
if (res.status === 429) {
this.emit('status-429');
yield sleep_1.sleep(1000);
return yield this.post(api, data);
}
}
return { success: false, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
});
}
get(api, data = null) {
return __awaiter(this, void 0, void 0, function* () {
var res;
var start = Date.now();
try {
res = this.lastResponse = yield this.client.get(api, data);
if (res.status === 200)
return { success: true, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
}
catch (e) {
res = yield e.response;
if (res.status === 429) {
this.emit('status-429');
yield sleep_1.sleep(1000);
return yield this.get(api, data);
}
}
return { success: false, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
});
}
/**
*
* @param {string} api
* @param {any} data
* @returns {{ success: boolean, response: any, httpStatus: number, statusText: string, elapsed: number }}
*/
put(api, data) {
return __awaiter(this, void 0, void 0, function* () {
var res;
var start = Date.now();
try {
res = this.lastResponse = yield this.client.put(api, data);
if (res.status === 204)
return { success: true, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
}
catch (e) {
res = yield e.response;
if (res.status === 429) {
this.emit('status-429');
yield sleep_1.sleep(1000);
return yield this.put(api, data);
}
}
return { success: false, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
});
}
/**
*
* @param {string} api
* @param {any} data
* @returns {{ success: boolean, response: any, httpStatus: number, statusText: string, elapsed: number }}
*/
delete(api, data = {}) {
return __awaiter(this, void 0, void 0, function* () {
var res;
var start = Date.now();
try {
res = this.lastResponse = yield this.client.delete(api, data);
if (res.status === 204)
return { success: true, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
}
catch (e) {
res = yield e.response;
if (res.status === 429) {
this.emit('status-429');
yield sleep_1.sleep(1000);
return yield this.delete(api, data);
}
}
return { success: false, response: res.data, httpStatus: res.status, statusText: res.statusText, elapsed: Date.now() - start };
});
}
/**
* Max Products Returned Per Page: 100
* @param page (min: 1)
* @param per_page (max: 100)
*/
getProdutos(page = 1, per_page = 100) {
return __awaiter(this, void 0, void 0, function* () {
return this.get('/products', { page: page, per_page: per_page });
});
}
/**
* Lista os produtos cadastrados agrupados por página (conforme parametro 'per_page', suportado no máx 100)
* NOTA: Não será possível listar mais que 10.000 (dez mil) itens
*/
getProduto(codigo_sku) {
return __awaiter(this, void 0, void 0, function* () {
return this.get(`/products/${codigo_sku}`);
});
}
/**
* Cadastra um novo Produto
*/
postProduto(product) {
return __awaiter(this, void 0, void 0, function* () {
return this.post('/products', JSON.stringify({ product: product }));
});
}
/**
* Atualiza Cadastro do Produto
* Nota: Atualiza apenas campos informados no parametro produto
* @param {Produto} produto Campos informados serão atualizados, campos não informados serão mantidos os valores atuais
* @returns {SkyHub.IResult<SkyHub.PutProduto>}
*/
putProduto(sku, produto) {
return __awaiter(this, void 0, void 0, function* () {
return this.put(`/products/${encodeURIComponent(sku)}`, JSON.stringify({ product: produto }));
});
}
/**
* Remove um Produto
*/
deleteProduto(sku) {
return __awaiter(this, void 0, void 0, function* () {
return this.delete(`/products/${encodeURIComponent(sku)}`);
});
}
/** Retorna 1 Pedido da fila
* */
getPedidoNaFila() {
return __awaiter(this, void 0, void 0, function* () {
return this.get('/queues/orders');
});
}
/** Retorna lista de pedidos
*/
getPedidos() {
return __awaiter(this, void 0, void 0, function* () {
return this.get('/orders');
});
}
/**
* Retorna 1 único pedido
*/
getPedido(id_pedido) {
return __awaiter(this, void 0, void 0, function* () {
return this.get('/orders/' + encodeURIComponent(id_pedido));
});
}
/**
* Confirma o Processamento (gravação no ERP) do pedido, removendo-o da fila de pedidos do SkyHub
*/
confirmarProcessamentoPedido(id_pedido_skyhub) {
return __awaiter(this, void 0, void 0, function* () {
return this.delete(`/queues/orders/${encodeURIComponent(id_pedido_skyhub)}`);
});
}
/**
* Altera Status do Pedido para 'Aprovado' no SkyHub
* NOTA: ESTA CHAMADA NÃO ESTÁ DISPONÍVEL EM PRODUÇÃO!
* @param {string} id_pedido_skyhub
* @returns {Promise<SkyHub.IResult<SkyHub.ISetPedidoAprovado>>}
*/
setPedidoAprovado(id_pedido_skyhub) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/approval`, JSON.stringify({ status: 'payment_received', }));
});
}
/**
* Altera Status do Pedido para 'Faturado' no SkyHub, vinculando a chave de acesso
* @param {string} id_pedido_skyhub
* @param {string} chaveAcesso
* @returns {Promise<SkyHub.IResult<SkyHub.ISetPedidoFaturado>>}
*/
setPedidoFaturado(id_pedido_skyhub, chaveAcesso) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/invoice`, JSON.stringify({ status: 'payment_received', invoice: { key: chaveAcesso } }));
});
}
/**
* Altera Status do Pedido para 'Não Entregue' no SkyHub
*/
setPedidoNaoEntregue(id_pedido_skyhub, obs) {
return __awaiter(this, void 0, void 0, function* () {
let d = new Date();
let tz = d.toString().replace(/.+([+-]\d\d)\:?(\d\d).+/, '$1:$2');
/*let tzMinutes = Math.abs(d.getTimezoneOffset() % 60).toString().padStart(2, '0');
let tzHours = ((d.getTimezoneOffset() - Math.abs(d.getTimezoneOffset() % 60)) / 60);
tzHours = (tzHours < 0 ? `+` : `-`) + tzHours.toString().padStart(2, '0');*/
let dados = {
shipment_exception: {
occurrence_date: `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}T${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}${tz}`,
observation: obs
}
};
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/shipment_exception`, JSON.stringify(dados));
});
}
/**
* Altera Status do Pedido para 'Entregue a Transportadora' no SkyHub, vinculando dados da Transportadora
*/
setPedidoEntregueTransportadora(id_pedido_skyhub, shipment) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/shipments`, JSON.stringify({ status: 'order_shipped', shipment: shipment }));
});
}
/**
* Altera Status do Pedido para 'Entregue ao Cliente' no SkyHub
*/
setPedidoEntregueCliente(id_pedido_skyhub) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/delivery`, JSON.stringify({ status: 'complete' }));
});
}
/**
* Altera Status do Pedido para 'Cancelado' no SkyHub
* @param id_pedido_skyhub
*/
setPedidoCancelado(id_pedido_skyhub) {
return __awaiter(this, void 0, void 0, function* () {
return this.post(`/orders/${encodeURIComponent(id_pedido_skyhub)}/cancel`, JSON.stringify({ status: 'order_canceled' }));
});
}
/**
* Cria um novo pedido no SkyHub
* IMPORTANTE: Esta chamada só funciona em homologação
* @param {SkyHub.NewOrder} order
* @returns {Promise<SkyHub.IResult<SkyHub.INovoPedidoTeste>>}
*/
novoPedidoTeste(order) {
return __awaiter(this, void 0, void 0, function* () {
return this.post('/orders', JSON.stringify({ order: order }));
});
}
}
SkyHub.Client = Client;
})(SkyHub = exports.SkyHub || (exports.SkyHub = {}));
exports.default = SkyHub.Client;
function myfunction() {
}
//# sourceMappingURL=skyhub.js.map