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, requestOptions = {}) { 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) this.requestTimeoutMs = requestOptions.timeoutMs || 15000; this.maxGetAttempts = requestOptions.maxGetAttempts || 3; this.retryBaseMs = requestOptions.retryBaseMs || 250; } 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); const method = String(metod || 'GET').toUpperCase(); let options = { method, headers: { "Authorization": "Basic " + Buffer.from(this.apiKey + ":").toString("base64"), 'content-type': 'application/xml', 'accept': 'application/json' } }; if (data) { if (method === 'GET') { const params = new URLSearchParams(data); url += (url.includes('?') ? '&' : '?') + params.toString(); } else { options.body = js2xmlparser.parse("prestashop", data, { format: { doubleQuotes: true, pretty: false } }); } } const maxAttempts = method === 'GET' ? this.maxGetAttempts : 1; for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { try { const response = await this.fetchWithTimeout(url, options); const body = response.text(); let parsed = {}; if (body) { try { parsed = JSON.parse(body); } catch (parseError) { const error = new Error(`PrestaShop returned invalid JSON (HTTP ${response.status})`); error.statusCode = response.status; throw error; } } if (response.status < 200 || response.status >= 300) { if (allowPartialSuccess && response.status === 500 && parsed && typeof parsed === 'object' && Object.keys(parsed).length > 0) { Log.warn('PrestaShop returned usable data with HTTP 500', { endpoint }); return parsed; } const error = new Error(`PrestaShop request failed with HTTP ${response.status}`); error.statusCode = response.status; error.responseBody = body.slice(0, 1000); throw error; } return parsed; } catch (error) { const retryableStatus = [408, 425, 429].includes(error.statusCode) || error.statusCode >= 500; const retryable = method === 'GET' && (retryableStatus || !error.statusCode); if (!retryable || attempt >= maxAttempts) throw error; await new Promise(resolve => setTimeout(resolve, this.retryBaseMs * (2 ** (attempt - 1)))); } } } async fetchWithTimeout(url, options) { let timer; try { return await Promise.race([ Core.fetch(url, options), new Promise((_, reject) => { timer = setTimeout(() => { const error = new Error(`PrestaShop request timed out after ${this.requestTimeoutMs} ms`); error.code = 'PRESTASHOP_TIMEOUT'; reject(error); }, this.requestTimeoutMs); timer.unref?.(); }), ]); } finally { clearTimeout(timer); } } 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"); } } // PrestaShop image type (not original). home_default ≈ 250×250 in classic theme. static PRODUCT_IMAGE_TYPE = 'home_default'; getProductImageUrl(productId, imageId) { const url = this.getUrl( 'images/products/' + productId + '/' + imageId + '/' + PrestashopApi.PRODUCT_IMAGE_TYPE ); 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 + '/' + PrestashopApi.PRODUCT_IMAGE_TYPE ), encoding: null, headers : { "Authorization" : "Basic " + Buffer.from(this.apiKey + ":").toString("base64") } }); return r; } };