Initial commit: core-prestashop module v1.1.1

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
fatequod
2026-07-07 14:30:30 +02:00
co-authored by Cursor
commit f163100ad4
33 changed files with 2605 additions and 0 deletions
+323
View File
@@ -0,0 +1,323 @@
const { Log, Core, DB } = require("@orbito/api-lib");
const PsOrder = require('./models/PsOrder');
const { resolveStatusId, normalizeStatusId } = require('./status-mapper');
function getPSMultiLangField(param, langId) {
if (Array.isArray(param)) {
if (param.length === 0) return '';
if (langId) {
let lang = param.find(l => l.id == langId);
if (lang) {
return lang.value;
}
}
return param[0].value;
}
return param;
}
async function resolveImportStatusId(companyId, config) {
const statusResult = await Core.callModule(companyId, 'core/orders', 'status.search', {});
const statuses = statusResult?.results ?? [];
const byId = new Map();
for (const status of statuses) {
const id = normalizeStatusId(status._id);
if (id) byId.set(id, status);
}
const configured = normalizeStatusId(config.orderStatus);
if (configured && byId.has(configured)) {
return configured;
}
const sorted = [...statuses].sort(
(a, b) => (a.positionInGroup ?? 0) - (b.positionInGroup ?? 0)
);
return normalizeStatusId(sorted[0]?._id);
}
async function importFromPSOrder(companyId, orderId, api, config) {
Log.debug(companyId, "Checking if BL is supported", { orderId });
let blSupported = await api.isBLSupported();
let endpoint = blSupported ? 'bl_order' : 'orders';
Log.debug(companyId, "Fetching order details", { endpoint: endpoint + '/' + orderId });
let { order } = await api.makeRequest(endpoint + '/' + orderId, 'GET', { output_format: "JSON" });
if (!order) {
Log.error(companyId, "Order not found", orderId);
return;
}
Log.info(companyId, "Importing order: " + order.reference);
let products = [];
for (let product of order.associations.order_rows) {
let unitPriceNet = parseFloat(product.unit_price_tax_excl); // jednak cen nie możemy zaokrąglać, bo presta pracuje w cenach brutto
let unitPriceGross = parseFloat(product.unit_price_tax_incl);
let taxRate = unitPriceNet ? (unitPriceGross - unitPriceNet) / unitPriceNet : 0;
const p = {
name: product.product_name,
sourceId: product.product_id,
sku: product.product_reference,
ean: product.product_ean13,
unitPrice: unitPriceNet,
tax: taxRate ? Math.round(taxRate * 100) / 100 : 0,
qty: parseFloat(product.product_quantity)
};
const psProduct = await api.getProduct(product.product_id);
Log.debug(companyId, "Fetched product details: " + getPSMultiLangField(psProduct.name));
p.weight = parseFloat(psProduct.weight);
try {
const imgUrl = await api.getProductCoverImageUrl(product.product_id);
if (imgUrl) p.coverImageUrl = imgUrl;
} catch (_) { /* no image available */ }
if (parseInt(product.product_attribute_id) > 0) {
const combination = await api.getProductCombination(product.product_attribute_id);
if (combination) {
const w = parseFloat(combination.weight);
if (!isNaN(w)) p.weight = w;
}
}
if (psProduct.type == "pack" && psProduct.associations.product_bundle) {
p.isPack = true;
p.pack = [];
for (const packItem of psProduct.associations.product_bundle) {
const psItem = await api.getProduct(packItem.id);
const pData = {
name: getPSMultiLangField(psItem.name),
sourceId: psItem.id,
sku: psItem.reference,
ean: psItem.ean13,
weight: parseFloat(psItem.weight),
qty: parseFloat(packItem.quantity)
};
if (parseInt(packItem.id_product_attribute) > 0) {
const combination = await api.getProductCombination(packItem.id_product_attribute);
if (combination) {
const w = parseFloat(combination.weight);
if (!isNaN(w)) pData.weight = w;
pData.sku = combination.reference || pData.sku;
}
}
try {
const imgUrl = await api.getProductCoverImageUrl(packItem.id);
if (imgUrl) pData.coverImageUrl = imgUrl;
} catch (_) { /* no image */ }
p.pack.push(pData);
}
}
products.push(p);
}
await Promise.all(
products
.filter(p => p.sourceId && p.name)
.map(p => Core.callModule(companyId, 'core/orders', 'product.upsert', {
sourceModule: 'core/prestashop',
sourceId: String(p.sourceId),
sku: p.sku || '',
name: p.name,
unitPrice: p.unitPrice,
ean: p.ean,
coverImageUrl: p.coverImageUrl || undefined,
}).catch(() => {}))
);
const fallbackStatusId = await resolveImportStatusId(companyId, config);
if (!fallbackStatusId) {
Log.error(companyId, 'Cannot import order — no valid order status configured', { orderId });
return;
}
const statusMapping = Array.isArray(config.statusMapping) ? config.statusMapping : [];
const statusId = resolveStatusId(order.current_state, statusMapping, fallbackStatusId);
if (!statusId) {
Log.error(companyId, 'Cannot import order — could not resolve status', {
orderId,
psStateId: order.current_state
});
return;
}
Log.info(companyId, 'Resolved order status', {
orderId,
psStateId: order.current_state,
orbitoStatusId: statusId
});
let res = await api.makeRequest('customers/' + order.id_customer, 'GET', { output_format: "JSON" });
const customer = res.customer;
Log.debug(companyId, "Fetched customer details", { email: customer.email, name: customer.firstname + " " + customer.lastname });
res = await api.makeRequest('addresses/' + order.id_address_delivery, 'GET', { output_format: "JSON" });
const address = res.address;
let carrierName = "Brak wybranej dostawy";
if (order.id_carrier) {
try {
const carrier = await api.getCarrier(order.id_carrier);
if (carrier) {
carrierName = carrier.name || "Brak nazwy";
}
} catch (e) {
Log.warn(companyId, "Error fetching carrier for order", orderId, e.message);
}
}
const currency = await api.getCurrency(order.id_currency);
const country = await api.getCountry(address.id_country);
const hasVatAndCompany = address.vat_number && address.company && address.vat_number.trim() != '' && address.company.trim() != '';
let invoiceDataForOrder = { isNeeded: false };
if ((order.id_address_invoice && order.id_address_invoice !== '0' && String(order.id_address_invoice) !== String(order.id_address_delivery)) || hasVatAndCompany) {
try {
const resInvoiceAddr = await api.makeRequest('addresses/' + order.id_address_invoice, 'GET', { output_format: "JSON" });
const invoiceAddress = resInvoiceAddr.address;
if (invoiceAddress) {
const invoiceCountry = await api.getCountry(invoiceAddress.id_country);
invoiceDataForOrder = {
isNeeded: true,
company: invoiceAddress.company || '',
taxNo: invoiceAddress.vat_number || '',
address: (invoiceAddress.address1 || '') + (invoiceAddress.address2 ? " " + invoiceAddress.address2 : ""),
city: invoiceAddress.city || '',
postCode: invoiceAddress.postcode || '',
country: invoiceCountry ? invoiceCountry.iso_code : ''
};
// Opcjonalnie: można dodać imię i nazwisko z adresu faktury, jeśli są inne i potrzebne
// invoiceDataForOrder.naturalPerson = (invoiceAddress.firstname || '') + ' ' + (invoiceAddress.lastname || '');
} else {
Log.warn(companyId, `Could not fetch invoice address details for address ID: ${order.id_address_invoice}, order ID: ${orderId}`);
}
} catch (e) {
Log.error(companyId, `Error fetching invoice address for order ID ${orderId}, address ID ${order.id_address_invoice}: ${e.message}`);
// W przypadku błędu, invoiceDataForOrder pozostaje { isNeeded: false }
}
}
const pickupPoint = {};
if (order.bl_delivery_point_id || order.bl_delivery_point_name) {
let name = order.bl_delivery_point_name;
let zipCode = order.bl_delivery_point_postcode;
let city = order.bl_delivery_point_city;
let street = order.bl_delivery_point_address;
// punkty odbioru od DPD są zapisywane jako jeden string w address
if (order.bl_delivery_point_address && !order.bl_delivery_point_postcode) {
const addressParts = order.bl_delivery_point_address.split(',', 2);
name = addressParts[0];
street = addressParts[0];
zipCode = addressParts.length > 1 ? addressParts[1].trim().split(" ")[0] : '';
city = addressParts.length > 1 ? (addressParts[1].trim().split(" ")[1] || '') : '';
}
pickupPoint.id = order.bl_delivery_point_id || order.bl_delivery_point_name;
pickupPoint.name = name;
pickupPoint.address = { street, zipCode, city };
}
const discounts = [];
if (parseFloat(order.total_discounts)) {
let net = parseFloat(order.total_discounts_tax_excl);
let gross = parseFloat(order.total_discounts_tax_incl);
let tax = net ? (gross - net) / net : 0;
discounts.push({
name: "Rabat",
amount: Math.round(net * 100) / 100,
gross: Math.round(gross * 100) / 100,
tax: Math.round(tax * 100) / 100
});
}
const totalPaidReal = parseFloat(order.total_paid_real) || 0;
const payments = [];
if (totalPaidReal > 0) {
payments.push({
amount: Math.round(totalPaidReal * 100) / 100,
method: order.payment || 'PrestaShop',
date: new Date(order.date_add),
});
}
const coreOrder = await Core.callModule(companyId, 'core/orders', 'create', {
statusId: statusId,
customer: {
name: customer.firstname + " " + customer.lastname,
email: customer.email,
phone: address.phone || address.phone_mobile
},
source: {
name: "Prestashop",
moduleCode: 'core/prestashop',
sourceId: order.id,
uniqueId: order.reference + ':' + order.id,
},
paymentMethod: order.payment,
currency: currency.iso_code,
delivery: {
type: "carrier",
carrierName: carrierName,
address: {
firstname: address.firstname,
lastname: address.lastname,
company: address.company,
street: address.address1 + (address.address2 ? " " + address.address2 : ""),
city: address.city,
postCode: address.postcode,
country: country.iso_code,
phone: address.phone || address.phone_mobile
},
pickupPoint,
cost: {
amount: parseFloat(order.total_shipping_tax_excl),
},
isCod: (order.payment + "").toLowerCase().includes("pobranie")
},
products,
payments,
discounts,
invoice: invoiceDataForOrder,
createdAt: new Date(order.date_add),
});
if (coreOrder?._id) {
const alreadyPaid = totalPaidReal > 0 && payments.length > 0;
try {
await PsOrder.create({
companyId: new DB.ObjectId(companyId),
shopConfigId: config._id,
psOrderId: parseInt(order.id),
orbitoOrderId: coreOrder._id,
reference: order.reference || '',
syncedAt: new Date(),
paymentSyncedAt: alreadyPaid ? new Date() : undefined,
});
} catch (e) {
Log.warn(companyId, 'PS order mapping save failed', { psOrderId: order.id, error: e.message });
}
}
}
module.exports = { importFromPSOrder };
module.exports = { importFromPSOrder };
+271
View File
@@ -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;
}
};
+235
View File
@@ -0,0 +1,235 @@
const { parseStatusMapping } = require('./status-mapper');
// ID widoków OVE → nazwy pól (withData zbiera po id, metody oczekują name)
const VIEW_ID_ALIASES = {
psShopUrlInput: 'storeUrl',
psApiKeyInput: 'apiKey',
psVersionInput: 'versionCode',
psShopNameInput: 'shopName',
psShopPrefixInput: 'shopPrefix',
psOrderStatusInput: 'orderStatus'
};
/** Pola połączenia — używaj w withData zamiast #form (nie działa w generatePage+target). */
const CONNECTION_WITH_DATA = Object.keys(VIEW_ID_ALIASES);
/** Pełny zapis: połączenie + mapowanie statusów z listy. */
const SAVE_WITH_DATA = [...CONNECTION_WITH_DATA, 'statusMappingList'];
const EMPTY_FORM = {
storeUrl: '',
shopName: '',
shopPrefix: '',
versionCode: '',
orderStatus: '',
psStates: [],
statusMappingRows: [],
hasPsStates: false,
hasApiKey: false
};
function normalizeSelectValue(value) {
if (value == null || value === '') return '';
if (typeof value === 'object') {
return String(value.id ?? value.value ?? value._id ?? '').trim();
}
return String(value).trim();
}
function buildMappingRows(psStates, statusMapping) {
const mapping = Array.isArray(statusMapping) ? statusMapping : [];
const byPsId = new Map();
for (const entry of mapping) {
const psStateId = parseInt(entry.psStateId, 10);
if (Number.isNaN(psStateId)) continue;
byPsId.set(psStateId, normalizeSelectValue(entry.orbitoStatusId));
}
return (Array.isArray(psStates) ? psStates : []).map(state => {
const psStateId = parseInt(state.id ?? state.psStateId, 10);
return {
psStateId: String(psStateId),
psStateName: state.name ?? state.psStateName ?? `Status ${psStateId}`,
psStateColor: state.color ?? state.psStateColor ?? '#cccccc',
orbitoStatusId: byPsId.get(psStateId) || ''
};
});
}
function toFormResponse(doc) {
if (!doc) return { ...EMPTY_FORM };
const psStates = Array.isArray(doc.psStates) ? doc.psStates : [];
const statusMapping = Array.isArray(doc.statusMapping) ? doc.statusMapping : [];
return {
storeUrl: doc.apiUrl || doc.storeUrl || '',
shopName: doc.shopName || '',
shopPrefix: doc.shopPrefix || '',
versionCode: doc.versionCode || '',
orderStatus: doc.orderStatus?.toString?.() ?? doc.orderStatus ?? '',
psStates,
statusMappingRows: buildMappingRows(psStates, statusMapping),
hasPsStates: psStates.length > 0,
hasApiKey: Boolean(doc.apiKey)
};
}
function normalizeFormParams(params = {}) {
if (params == null || typeof params !== 'object') return {};
let flat = params;
if (Array.isArray(flat)) {
flat = flat.find(item => item && typeof item === 'object') || {};
}
if (flat.data && typeof flat.data === 'object' && !Array.isArray(flat.data)) {
flat = { ...flat, ...flat.data };
} else {
flat = { ...flat };
}
for (const [key, value] of Object.entries(flat)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
if ('value' in value) {
flat[key] = value.value;
} else if ('id' in value && (key === 'versionCode' || key === 'orderStatus' || key.endsWith('orbitoStatusId'))) {
flat[key] = value.id;
}
}
}
for (const [viewId, fieldName] of Object.entries(VIEW_ID_ALIASES)) {
if (Object.prototype.hasOwnProperty.call(flat, viewId) && !Object.prototype.hasOwnProperty.call(flat, fieldName)) {
flat[fieldName] = flat[viewId];
}
}
return flat;
}
function hasFormInput(input) {
const formKeys = ['storeUrl', 'apiUrl', 'shopName', 'shopPrefix', 'versionCode', 'orderStatus', 'apiKey'];
return formKeys.some(key => Object.prototype.hasOwnProperty.call(input, key)) || hasMappingInput(input);
}
function hasMappingInput(input) {
if (input.statusMappingRows != null) return true;
return Object.keys(input).some(key => key.startsWith('statusMappingRows.'));
}
function extractStatusMappingRows(input) {
const rows = input.statusMappingRows;
if (Array.isArray(rows)) {
return rows
.map(row => ({
psStateId: parseInt(row?.psStateId, 10),
orbitoStatusId: normalizeSelectValue(row?.orbitoStatusId)
}))
.filter(row => !Number.isNaN(row.psStateId) && row.orbitoStatusId);
}
if (rows && typeof rows === 'object') {
return Object.values(rows)
.map(row => ({
psStateId: parseInt(row?.psStateId, 10),
orbitoStatusId: normalizeSelectValue(row?.orbitoStatusId)
}))
.filter(row => !Number.isNaN(row.psStateId) && row.orbitoStatusId);
}
const indexed = {};
for (const [key, value] of Object.entries(input)) {
const match = key.match(/^statusMappingRows\.(\d+)\.(psStateId|orbitoStatusId)$/);
if (!match) continue;
indexed[match[1]] = indexed[match[1]] || {};
indexed[match[1]][match[2]] = value;
}
return Object.values(indexed)
.map(row => ({
psStateId: parseInt(row.psStateId, 10),
orbitoStatusId: normalizeSelectValue(row.orbitoStatusId)
}))
.filter(row => !Number.isNaN(row.psStateId) && row.orbitoStatusId);
}
function pickString(input, existing, inputKey, existingKey = inputKey) {
if (Object.prototype.hasOwnProperty.call(input, inputKey)) {
return String(input[inputKey] ?? '').trim();
}
const prev = existing?.[existingKey];
if (prev !== undefined && prev !== null && String(prev).trim() !== '') {
return String(prev).trim();
}
return '';
}
function buildSavePayload(params, existing) {
const input = normalizeFormParams(params);
const hasConnectionInput = ['storeUrl', 'apiUrl', 'apiKey', 'shopPrefix', 'shopName', 'versionCode', 'orderStatus']
.some(key => Object.prototype.hasOwnProperty.call(input, key));
const storeUrl = pickString(input, hasConnectionInput ? null : existing, 'storeUrl', 'apiUrl');
const apiKey = Object.prototype.hasOwnProperty.call(input, 'apiKey')
? ((input.apiKey || '').trim() || existing?.apiKey || '')
: (hasConnectionInput ? '' : (existing?.apiKey || ''));
const data = {
apiUrl: storeUrl,
apiKey,
shopPrefix: pickString(input, hasConnectionInput ? null : existing, 'shopPrefix'),
shopName: pickString(input, hasConnectionInput ? null : existing, 'shopName'),
};
const versionCode = normalizeSelectValue(input.versionCode);
if (versionCode || Object.prototype.hasOwnProperty.call(input, 'versionCode')) {
data.versionCode = versionCode;
} else if (existing?.versionCode) {
data.versionCode = existing.versionCode;
}
const orderStatus = normalizeSelectValue(input.orderStatus);
if (orderStatus || Object.prototype.hasOwnProperty.call(input, 'orderStatus')) {
data.orderStatus = orderStatus || null;
} else if (existing?.orderStatus) {
data.orderStatus = existing.orderStatus;
}
const mappingRows = extractStatusMappingRows(input);
if (mappingRows.length) {
data.statusMapping = mappingRows;
} else if (hasMappingInput(input)) {
data.statusMapping = [];
} else if (typeof input.statusMappingJson !== 'undefined' || typeof input.statusMapping !== 'undefined') {
data.statusMapping = parseStatusMapping(input.statusMapping ?? input.statusMappingJson);
} else if (existing?.statusMapping) {
data.statusMapping = existing.statusMapping;
}
if (Array.isArray(existing?.psStates) && existing.psStates.length) {
data.psStates = existing.psStates;
} else if (Array.isArray(input.psStates) && input.psStates.length) {
data.psStates = input.psStates;
}
return data;
}
module.exports = {
EMPTY_FORM,
VIEW_ID_ALIASES,
CONNECTION_WITH_DATA,
SAVE_WITH_DATA,
normalizeSelectValue,
buildMappingRows,
normalizeFormParams,
hasFormInput,
hasMappingInput,
extractStatusMappingRows,
toFormResponse,
buildSavePayload
};
+13
View File
@@ -0,0 +1,13 @@
function methodOk(data = {}) {
return { success: true, ...data };
}
function methodFail(error, extra = {}) {
return {
success: false,
error: String(error || 'Nieznany błąd'),
...extra
};
}
module.exports = { methodOk, methodFail };
+11
View File
@@ -0,0 +1,11 @@
const { DB } = require('@orbito/api-lib');
const schema = new DB.Schema('prestashop_orders_list_state', {
companyId: { type: 'ObjectId' },
filters: { type: 'object', optional: true, default: {} },
updatedAt: { type: 'date', default: () => new Date() },
});
DB.createIndex('prestashop_orders_list_state', { companyId: 1 }, { unique: true });
module.exports = schema;
+20
View File
@@ -0,0 +1,20 @@
const { DB } = require('@orbito/api-lib');
const schema = new DB.Schema('ps_orders', {
companyId: { type: 'ObjectId' },
shopConfigId: { type: 'ObjectId' },
psOrderId: { type: 'number' },
orbitoOrderId: { type: 'ObjectId', optional: true },
reference: { type: 'string', optional: true, default: '' },
syncedAt: { type: 'date', optional: true, default: () => new Date() },
paymentSyncedAt: { type: 'date', optional: true },
});
schema.pre('validate', function (data) {});
schema.post('create', function (data) {});
DB.createIndex('ps_orders', { companyId: 1, psOrderId: 1, shopConfigId: 1 }, { unique: true });
DB.createIndex('ps_orders', { companyId: 1, orbitoOrderId: 1 });
DB.createIndex('ps_orders', { companyId: 1, syncedAt: -1 });
module.exports = schema;
+55
View File
@@ -0,0 +1,55 @@
const { DB } = require('@orbito/api-lib');
const { customAlphabet } = require('nanoid');
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const schema = new DB.Schema('shop_config', {
companyId: { type: 'ObjectId' },
apiUrl: { type: 'string', optional: true },
apiKey: { type: 'string', optional: true },
shopName: { type: 'string', optional: true },
versionCode: { type: 'string', optional: true },
// shopPrefix: prefiks używany w uniqueId zamówienia (np. "PL" -> "PL:389218").
// Na razie tylko przechowywany; nie jest jeszcze wpinany w format uniqueId w imporcie.
shopPrefix: { type: 'string', optional: true },
// orderStatus: domyślny status gdy brak mapowania PS → Orbito
orderStatus: { type: 'ObjectId', optional: true },
// statusMapping: [{ psStateId: 2, orbitoStatusId: "..." }]
statusMapping: {
type: 'array',
items: { type: 'object' },
optional: true,
default: []
},
// Podgląd statusów PS (cache do formularza konfiguracji)
psStatesPreview: { type: 'string', optional: true, default: '' },
// Lista statusów PS pobrana z API (do UI mapowania)
psStates: {
type: 'array',
items: { type: 'object' },
optional: true,
default: []
},
lastOrderId: { type: 'number', optional: true },
createdAt: { type: 'date', default: () => new Date() },
isRemoved: { type: 'boolean', default: false }
});
// Pre-validate hook - calculate summary and update derived fields
schema.pre('validate', async function(data) {
});
schema.post('create', function(data) {
// Hook for post-create actions (e.g., emit events, notifications)
});
DB.createIndex('shop_config', { companyId: 1 });
module.exports = schema;
+163
View File
@@ -0,0 +1,163 @@
const { Core } = require('@orbito/api-lib');
// Helper proxy do modułu zamówień. Widoki PrestaShop (orders.search,
// status.get_with_counts) nie trzymają własnych zamówień — odpytują core/orders.
// MODULE_CODE musi pokrywać się z source.moduleCode ustawianym w OrderImporter
// podczas importu zamówień z PrestaShop ('core/prestashop'), inaczej filtr
// po źródle nie zwróci żadnych zamówień.
const MODULE_CODE = 'core/prestashop';
// Starsze importy mogły zapisać source.moduleCode jako 'prestashop'.
const MODULE_CODES = ['core/prestashop', 'prestashop'];
const ORDERS_MODULE_ID = 'core/orders';
async function callOrdersModule(companyId, method, params) {
return Core.callModule(companyId, ORDERS_MODULE_ID, method, params);
}
// Sprowadza różne kształty odpowiedzi core/orders do { data, pagination }.
function normalizeSearchResult(raw) {
if (!raw) {
return { data: [], pagination: { page: 1, perPage: 20, total: 0 } };
}
if (Array.isArray(raw)) {
return {
data: raw,
pagination: { page: 1, perPage: raw.length, total: raw.length }
};
}
const data = raw.data ?? raw.items ?? raw.results ?? [];
const pagination = raw.pagination ?? {
page: raw.page ?? 1,
perPage: raw.perPage ?? data.length,
total: raw.total ?? data.length
};
return { data, pagination };
}
function isUsableParam(value) {
const trimmed = String(value ?? '').trim();
if (!trimmed) return false;
if (trimmed.startsWith('#')) return false;
if (trimmed.startsWith('$page.')) return false;
if (trimmed.includes('{{') || trimmed.includes('}}')) return false;
return true;
}
function normalizeLegacySearchParams(params = {}) {
const normalized = { ...params };
if (!normalized.query && normalized.searchQuery) {
normalized.query = normalized.searchQuery;
}
if (normalized.isPaid === undefined && normalized.paidOnly === true) {
normalized.isPaid = true;
}
if (normalized.pagination && typeof normalized.pagination === 'object') {
const pagination = normalized.pagination;
if (pagination.page != null && normalized.page == null) {
normalized.page = pagination.page;
}
if (pagination.limit != null && normalized.perPage == null) {
normalized.perPage = pagination.limit;
}
if (pagination.sort && typeof pagination.sort === 'object' && !normalized.sortBy) {
const sortKeys = Object.keys(pagination.sort);
if (sortKeys.length > 0) {
normalized.sortBy = sortKeys[0];
normalized.sortDirection = pagination.sort[sortKeys[0]] >= 0 ? 'asc' : 'desc';
}
}
}
if (!normalized.statusId && Array.isArray(normalized.statuses) && normalized.statuses.length > 0) {
normalized.statusId = normalized.statuses[0];
}
if (!normalized.sortDirection && normalized.sortDir != null && normalized.sortDir !== '') {
const raw = String(normalized.sortDir).trim();
normalized.sortDirection = (raw === '-1' || raw.toLowerCase() === 'desc') ? 'desc' : 'asc';
}
return normalized;
}
// Mapuje parametry z datatable na parametry metody core/orders 'search',
// wymuszając filtr po źródle = zamówienia PrestaShop.
function buildSearchParams(params = {}) {
const cleanParams = normalizeLegacySearchParams({ ...params });
// OVE emit dołącza sourceId widoku — nie jest parametrem wyszukiwania
if (cleanParams.sourceId && !/^[a-f0-9]{24}$/i.test(String(cleanParams.sourceId))) {
delete cleanParams.sourceId;
}
const searchParams = {
page: parseInt(cleanParams.page, 10) || 1,
perPage: parseInt(cleanParams.perPage, 10) || 20,
source: {
moduleCode: MODULE_CODE,
_moduleCodes: MODULE_CODES
}
};
const sortBy = cleanParams.sortBy || cleanParams.sort;
const sortDirection = cleanParams.sortDirection || cleanParams.sortDir;
if (sortBy) searchParams.sortBy = sortBy;
if (sortDirection) searchParams.sortDirection = sortDirection;
if (cleanParams.statusId && isUsableParam(cleanParams.statusId)) searchParams.statusId = cleanParams.statusId;
if (cleanParams._id) searchParams._id = cleanParams._id;
// Pozwól nadpisać/rozszerzyć filtr źródła (np. konkretny shopPrefix w przyszłości).
if (cleanParams.source && typeof cleanParams.source === 'object') {
searchParams.source = { ...searchParams.source, ...cleanParams.source };
}
if (cleanParams.query && isUsableParam(cleanParams.query)) {
searchParams.query = String(cleanParams.query).trim();
}
const passthroughKeys = [
'dateFrom', 'dateTo', 'statusDateFrom', 'statusDateTo',
'orderReference', 'customer', 'customerEmail', 'customerPhone',
'carrierName', 'city', 'postCode', 'country',
'paymentMethod', 'currency', 'note',
'productName', 'productSku', 'productEan',
'priceFrom', 'priceTo', 'isPaid',
];
for (const key of passthroughKeys) {
const value = cleanParams[key];
if (value !== undefined && value !== null && isUsableParam(value)) {
searchParams[key] = value;
}
}
return searchParams;
}
async function searchOrders(companyId, params) {
const searchParams = buildSearchParams(params);
const raw = await callOrdersModule(companyId, 'search', searchParams);
return normalizeSearchResult(raw);
}
async function getOrderStatuses(companyId) {
const raw = await callOrdersModule(companyId, 'status.search', {});
return raw?.results ?? raw?.data ?? (Array.isArray(raw) ? raw : []);
}
module.exports = {
MODULE_CODE,
MODULE_CODES,
ORDERS_MODULE_ID,
callOrdersModule,
normalizeSearchResult,
buildSearchParams,
searchOrders,
getOrderStatuses
};
+125
View File
@@ -0,0 +1,125 @@
// ID widoków OVE → nazwy pól API (withData zbiera po id, jak w config-form.js)
const VIEW_ID_ALIASES = {
filterDateFrom: 'dateFrom',
filterDateTo: 'dateTo',
filterStatusDateFrom: 'statusDateFrom',
filterStatusDateTo: 'statusDateTo',
filterOrderReference: 'orderReference',
filterCustomer: 'customer',
filterCustomerEmail: 'customerEmail',
filterCustomerPhone: 'customerPhone',
filterCarrier: 'carrierName',
filterCity: 'city',
filterPostCode: 'postCode',
filterCountry: 'country',
filterProductName: 'productName',
filterProductSku: 'productSku',
filterProductEan: 'productEan',
filterPaymentMethod: 'paymentMethod',
filterCurrency: 'currency',
filterNote: 'note',
filterPriceFrom: 'priceFrom',
filterPriceTo: 'priceTo',
filterIsPaid: 'isPaid',
ordersSearchInput: 'query',
};
/** Pola filtrów — używaj w withData na przycisku Filtruj (zbiór po id widoku). */
const FILTER_VIEW_WITH_DATA = Object.keys(VIEW_ID_ALIASES);
const FILTER_KEYS = [
...new Set([...Object.values(VIEW_ID_ALIASES), 'statusId', 'sortBy', 'sortDirection', 'sortDir', 'page', 'perPage']),
];
const DEFAULT_SORT = {
sortBy: 'createdAt',
sortDirection: 'desc',
};
function normalizeScalar(value) {
if (value == null) return '';
if (typeof value === 'object') {
if ('value' in value) return normalizeScalar(value.value);
if ('id' in value) return normalizeScalar(value.id);
return '';
}
return String(value).trim();
}
function normalizeSortDirection(sortDirection, sortDir) {
if (sortDirection) {
const dir = String(sortDirection).toLowerCase();
if (dir === 'asc' || dir === 'desc') return dir;
}
if (sortDir != null && sortDir !== '') {
const raw = String(sortDir).trim();
if (raw === '-1' || raw.toLowerCase() === 'desc') return 'desc';
if (raw === '1' || raw.toLowerCase() === 'asc') return 'asc';
}
return DEFAULT_SORT.sortDirection;
}
function normalizeFilterParams(params = {}) {
if (params == null || typeof params !== 'object') return {};
let flat = { ...params };
if (Array.isArray(flat)) {
flat = flat.find(item => item && typeof item === 'object') || {};
}
if (flat.data && typeof flat.data === 'object' && !Array.isArray(flat.data)) {
flat = { ...flat, ...flat.data };
}
for (const [viewId, fieldName] of Object.entries(VIEW_ID_ALIASES)) {
if (Object.prototype.hasOwnProperty.call(flat, viewId) && !Object.prototype.hasOwnProperty.call(flat, fieldName)) {
flat[fieldName] = flat[viewId];
}
}
for (const [key, value] of Object.entries(flat)) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
if ('value' in value) flat[key] = value.value;
else if ('id' in value) flat[key] = value.id;
}
}
const normalized = {};
for (const key of FILTER_KEYS) {
if (!Object.prototype.hasOwnProperty.call(flat, key)) continue;
normalized[key] = normalizeScalar(flat[key]);
}
normalized.sortBy = normalized.sortBy || DEFAULT_SORT.sortBy;
normalized.sortDirection = normalizeSortDirection(normalized.sortDirection, normalized.sortDir);
delete normalized.sortDir;
return normalized;
}
function buildListPageQuery(filters = {}) {
const normalized = normalizeFilterParams(filters);
const parts = [];
for (const [key, value] of Object.entries(normalized)) {
if (!value) continue;
if (key === 'page' || key === 'perPage') continue;
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
return parts.join('&');
}
function buildListPagePath(filters = {}) {
const query = buildListPageQuery(filters);
return query ? `list?${query}` : 'list';
}
module.exports = {
VIEW_ID_ALIASES,
FILTER_VIEW_WITH_DATA,
FILTER_KEYS,
DEFAULT_SORT,
normalizeFilterParams,
buildListPageQuery,
buildListPagePath,
};
+86
View File
@@ -0,0 +1,86 @@
const { DB } = require('@orbito/api-lib');
const { normalizeFilterParams } = require('./orders-filter-form');
const OrdersListState = require('./models/OrdersListState');
// Cache w pamięci — przyspiesza powtórne odczyty w tym samym procesie.
const memoryCache = new Map();
function storageKey(companyId) {
return String(companyId || '');
}
function companyObjectId(companyId) {
if (!companyId) return null;
try {
return new DB.ObjectId(companyId);
} catch (e) {
return null;
}
}
async function getFilters(companyId, instanceId) {
const key = storageKey(companyId);
if (memoryCache.has(key)) {
return { ...(memoryCache.get(key) || {}) };
}
const companyOid = companyObjectId(companyId);
if (!companyOid) return {};
const doc = await OrdersListState.findOne({ companyId: companyOid });
const filters = doc?.filters && typeof doc.filters === 'object' ? { ...doc.filters } : {};
memoryCache.set(key, filters);
return filters;
}
async function mergeFilters(companyId, instanceId, params = {}) {
const incoming = normalizeFilterParams(params);
const current = await getFilters(companyId, instanceId);
const merged = { ...current };
for (const [key, value] of Object.entries(incoming)) {
if (value === '') {
delete merged[key];
} else {
merged[key] = value;
}
}
const key = storageKey(companyId);
memoryCache.set(key, merged);
const companyOid = companyObjectId(companyId);
if (companyOid) {
const existing = await OrdersListState.findOne({ companyId: companyOid });
if (existing) {
await OrdersListState.update(
{ _id: existing._id },
{ filters: merged, updatedAt: new Date() }
);
} else {
await OrdersListState.create({
companyId: companyOid,
filters: merged,
updatedAt: new Date(),
});
}
}
return merged;
}
async function clearFilters(companyId, instanceId) {
const key = storageKey(companyId);
memoryCache.delete(key);
const companyOid = companyObjectId(companyId);
if (companyOid) {
await OrdersListState.delete({ companyId: companyOid });
}
}
module.exports = {
getFilters,
mergeFilters,
clearFilters,
};
+64
View File
@@ -0,0 +1,64 @@
function normalizeStatusId(value) {
if (value == null || value === '') return null;
if (typeof value === 'object' && value._id != null) {
return normalizeStatusId(value._id);
}
const str = String(value).trim();
return /^[a-f0-9]{24}$/i.test(str) ? str : null;
}
function parseStatusMapping(raw) {
if (!raw) return [];
if (Array.isArray(raw)) return raw;
if (typeof raw === 'string') {
const trimmed = raw.trim();
if (!trimmed) return [];
try {
const parsed = JSON.parse(trimmed);
return Array.isArray(parsed) ? parsed : [];
} catch (_) {
throw new Error('statusMapping musi być poprawną tablicą JSON');
}
}
return [];
}
// Mapuje PrestaShop order.current_state (psStateId) na orbitoStatusId.
function resolveStatusId(psStateId, statusMapping, fallbackStatusId) {
const stateId = parseInt(psStateId, 10);
if (!Array.isArray(statusMapping) || Number.isNaN(stateId)) {
return normalizeStatusId(fallbackStatusId);
}
const match = statusMapping.find(entry => parseInt(entry.psStateId, 10) === stateId);
return normalizeStatusId(match?.orbitoStatusId) ?? normalizeStatusId(fallbackStatusId);
}
function formatPsStatesPreview(states) {
if (!Array.isArray(states) || !states.length) {
return 'Brak statusów PrestaShop — najpierw przetestuj połączenie.';
}
return states
.map(s => {
const id = s.id ?? s.psStateId;
const name = extractPsStateName(s.name);
return `${id} — ${name}`;
})
.join('\n');
}
function extractPsStateName(name) {
if (Array.isArray(name)) {
return name[0]?.value ?? name[0] ?? '';
}
return name ?? '';
}
module.exports = {
normalizeStatusId,
parseStatusMapping,
resolveStatusId,
formatPsStatesPreview,
extractPsStateName
};
+18
View File
@@ -0,0 +1,18 @@
const codSuggestionPhrases = [
'cash on delivery',
'cod',
'pobranie',
];
module.exports = {
isLegacyApi: function(versionCode = "") {
// PrestaShop 1.7 and older versions use legacy API
return versionCode.trim() == '1.6' || versionCode.trim() == '1.7';
},
isNameSuggetsCOD: function(name) {
if (!name) return false;
const lowerName = name.toLowerCase();
return codSuggestionPhrases.some(phrase => lowerName.includes(phrase));
}
};