Initial commit: core-prestashop module v1.1.1
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,271 @@
|
||||
const { Core, Log } = require('@orbito/api-lib');
|
||||
|
||||
const js2xmlparser = require("js2xmlparser");
|
||||
const NodeCache = require("node-cache");
|
||||
|
||||
module.exports = class PrestashopApi {
|
||||
constructor(shopUrl, apiKey, legacy = true) {
|
||||
this.shopUrl = new URL(shopUrl);
|
||||
this.apiKey = apiKey;
|
||||
this.cache = new NodeCache({ stdTTL: 600, checkperiod: 100 });
|
||||
this.legacy = legacy; // czy używać legacy API (dla PrestaShop < 8)
|
||||
}
|
||||
|
||||
getUrl(endpoint = "") {
|
||||
if (endpoint.startsWith('/')) {
|
||||
endpoint = endpoint.slice(1);
|
||||
}
|
||||
|
||||
if (this.shopUrl.pathname == '/') {
|
||||
return this.shopUrl.origin + '/api/' + endpoint;
|
||||
}
|
||||
|
||||
if (this.shopUrl.pathname.endsWith('api') || this.shopUrl.pathname.endsWith('api/')) {
|
||||
return this.shopUrl.href.endsWith('/') ? this.shopUrl.href + endpoint : this.shopUrl.href + '/' + endpoint;
|
||||
}
|
||||
|
||||
// pozostałe przypadki kiedy sklep znajduje sie w folderze np https://nanocor.eu/b2b
|
||||
let href = this.shopUrl.href;
|
||||
if (href.endsWith('/')) {
|
||||
return href + 'api/' + endpoint;
|
||||
} else {
|
||||
return href + '/api/' + endpoint;
|
||||
}
|
||||
}
|
||||
|
||||
async makeRequest(endpoint, metod, data, allowPartialSuccess = false) {
|
||||
// @todo przemyśleć czy nie dodac tutaj na sztywno do kazdego zapytania output_format=JSON
|
||||
let url = this.getUrl(endpoint);
|
||||
|
||||
let options = {
|
||||
method: metod,
|
||||
headers: {
|
||||
"Authorization": "Basic " + Buffer.from(this.apiKey + ":").toString("base64"),
|
||||
'content-type': 'application/xml',
|
||||
'accept': 'application/json'
|
||||
}
|
||||
};
|
||||
|
||||
if (data) {
|
||||
if (metod.toLowerCase() === 'get') {
|
||||
const params = new URLSearchParams(data);
|
||||
url += (url.includes('?') ? '&' : '?') + params.toString();
|
||||
} else {
|
||||
options.body = js2xmlparser.parse("prestashop", data, {
|
||||
format: {
|
||||
doubleQuotes: true,
|
||||
pretty: false
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
let r = await Core.fetch(url, options);
|
||||
return r.json();
|
||||
} catch (error) {
|
||||
// Jeśli allowPartialSuccess jest true i mamy błąd 500, sprawdź czy odpowiedź zawiera użyteczne dane
|
||||
if (allowPartialSuccess && error.statusCode === 500 && error.response && error.response.body) {
|
||||
try {
|
||||
let parsedResponse = JSON.parse(error.response.body);
|
||||
// Jeśli odpowiedź zawiera dane mimo błędu, zwróć je
|
||||
if (parsedResponse && typeof parsedResponse === 'object') {
|
||||
return parsedResponse;
|
||||
}
|
||||
} catch (parseError) {
|
||||
// Jeśli nie można sparsować odpowiedzi, rzuć oryginalny błąd
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async isBLSupported() {
|
||||
let cacheKey = "bl_supported";
|
||||
let blSupported = this.cache.get(cacheKey);
|
||||
if (typeof blSupported == 'undefined') {
|
||||
try {
|
||||
let res = await this.makeRequest('bl_order', 'GET', { limit: 1, output_format: "JSON" });
|
||||
blSupported = res.orders && res.orders.length > 0;
|
||||
} catch (e) {
|
||||
blSupported = false;
|
||||
}
|
||||
this.cache.set(cacheKey, blSupported);
|
||||
}
|
||||
|
||||
return blSupported;
|
||||
}
|
||||
|
||||
async getCountry(countryId) {
|
||||
let cacheKey = "country_" + countryId;
|
||||
let country = this.cache.get(cacheKey);
|
||||
if (!country) {
|
||||
let res = await this.makeRequest('countries/' + countryId, 'GET', { output_format: "JSON" });
|
||||
country = res.country;
|
||||
this.cache.set(cacheKey, country);
|
||||
}
|
||||
|
||||
return country;
|
||||
}
|
||||
|
||||
async getCarrier(orderId) {
|
||||
let cacheKey = "carrier_" + orderId;
|
||||
let carrier = this.cache.get(cacheKey);
|
||||
if (!carrier) {
|
||||
let res = await this.makeRequest('carriers/' + orderId, 'GET', { output_format: "JSON" });
|
||||
carrier = res.carrier;
|
||||
this.cache.set(cacheKey, carrier);
|
||||
}
|
||||
|
||||
return carrier;
|
||||
}
|
||||
|
||||
async getCurrency(currencyId) {
|
||||
let cacheKey = "currency_" + currencyId;
|
||||
let currency = this.cache.get(cacheKey);
|
||||
if (!currency) {
|
||||
let res = await this.makeRequest('currencies/' + currencyId, 'GET', { output_format: "JSON" });
|
||||
currency = res.currency;
|
||||
this.cache.set(cacheKey, currency);
|
||||
}
|
||||
|
||||
return currency;
|
||||
}
|
||||
|
||||
async getProduct(productId) {
|
||||
let cacheKey = "product_" + productId;
|
||||
let product = this.cache.get(cacheKey);
|
||||
if (!product) {
|
||||
let res = await this.makeRequest('products/' + productId, 'GET', { output_format: "JSON" }, true);
|
||||
if (res.product) {
|
||||
product = res.product;
|
||||
this.cache.set(cacheKey, product);
|
||||
} else {
|
||||
throw new Error("Product data not found in response");
|
||||
}
|
||||
}
|
||||
|
||||
return product;
|
||||
}
|
||||
|
||||
async getProductCombination(combinationId) {
|
||||
let cacheKey = "product_combination_" + combinationId;
|
||||
let combination = this.cache.get(cacheKey);
|
||||
if (!combination) {
|
||||
let res = await this.makeRequest('combinations/' + combinationId, 'GET', { output_format: "JSON" });
|
||||
combination = res.combination;
|
||||
this.cache.set(cacheKey, combination);
|
||||
}
|
||||
|
||||
return combination;
|
||||
}
|
||||
|
||||
async getStatuses() {
|
||||
let cacheKey = "statuses";
|
||||
let statuses = this.cache.get(cacheKey);
|
||||
if (!statuses) {
|
||||
let res = await this.makeRequest('order_states', 'GET', { output_format: "JSON", display: '[id,name,color,deleted]' });
|
||||
statuses = res.order_states;
|
||||
this.cache.set(cacheKey, statuses);
|
||||
}
|
||||
|
||||
return statuses;
|
||||
}
|
||||
|
||||
async getOrder(orderId) {
|
||||
const blSupported = await this.isBLSupported();
|
||||
const endpoint = blSupported ? 'bl_order' : 'orders';
|
||||
const res = await this.makeRequest(endpoint + '/' + orderId, 'GET', { output_format: 'JSON' });
|
||||
return res?.order || null;
|
||||
}
|
||||
|
||||
async getOrderPayments(orderReference) {
|
||||
const res = await this.makeRequest('order_payments', 'GET', {
|
||||
output_format: 'JSON',
|
||||
display: 'full',
|
||||
'filter[order_reference]': orderReference,
|
||||
});
|
||||
return res?.order_payments || [];
|
||||
}
|
||||
|
||||
async setOrderState(orderId, stateId) {
|
||||
if (this.legacy) {
|
||||
return await this.updateOrderLegacy(orderId, {
|
||||
current_state: stateId
|
||||
});
|
||||
}
|
||||
|
||||
return await this.updateOrder(orderId, {
|
||||
current_state: stateId
|
||||
});
|
||||
}
|
||||
|
||||
async updateOrder(orderId, data) {
|
||||
let res = await this.makeRequest('orders?output_format=JSON', 'PATCH', {
|
||||
order: {
|
||||
id: orderId,
|
||||
...data
|
||||
}
|
||||
});
|
||||
|
||||
if (res && res.order && res.order.id) {
|
||||
return res.order;
|
||||
} else {
|
||||
throw new Error("Failed to set order state");
|
||||
}
|
||||
}
|
||||
|
||||
async updateOrderLegacy(orderId, data) {
|
||||
// in legacy API, we need to use PUT instead of PATCH
|
||||
// and we need to sent the whole order data, not just the fields we want to update
|
||||
// so we need to fetch the current order data first
|
||||
let currentOrder = await this.makeRequest('orders/' + orderId + '?output_format=JSON', 'GET');
|
||||
if (!currentOrder || !currentOrder.order || !currentOrder.order.id) {
|
||||
throw new Error("Order not found");
|
||||
}
|
||||
|
||||
// merge current order data with the new data
|
||||
data = {
|
||||
...currentOrder.order,
|
||||
...data
|
||||
};
|
||||
|
||||
let res = await this.makeRequest('orders/' + orderId + '?output_format=JSON', 'PUT', {
|
||||
order: data
|
||||
});
|
||||
|
||||
if (res && res.order && res.order.id) {
|
||||
return res.order;
|
||||
} else {
|
||||
throw new Error("Failed to set order state");
|
||||
}
|
||||
}
|
||||
|
||||
getProductImageUrl(productId, imageId) {
|
||||
const url = this.getUrl('images/products/' + productId + '/' + imageId);
|
||||
const sep = url.includes('?') ? '&' : '?';
|
||||
return url + sep + 'ws_key=' + encodeURIComponent(this.apiKey);
|
||||
}
|
||||
|
||||
async getProductCoverImageUrl(productId) {
|
||||
const product = await this.getProduct(productId);
|
||||
const defaultImageId = product.id_default_image;
|
||||
if (defaultImageId && defaultImageId !== '0' && defaultImageId !== '') {
|
||||
return this.getProductImageUrl(productId, defaultImageId);
|
||||
}
|
||||
if (product.associations?.images?.length > 0) {
|
||||
return this.getProductImageUrl(productId, product.associations.images[0].id);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async getProductImageBuffer(productId, imageId) {
|
||||
let r = await Request({
|
||||
url: this.getUrl('images/products/' + productId + '/' + imageId),
|
||||
encoding: null,
|
||||
headers : { "Authorization" : "Basic " + Buffer.from(this.apiKey + ":").toString("base64") }
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user