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(config) { const statusResult = await Core.callModule( '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(orderId, api, config) { Log.debug( "Checking if BL is supported", { orderId }); let blSupported = await api.isBLSupported(); let endpoint = blSupported ? 'bl_order' : 'orders'; Log.debug( "Fetching order details", { endpoint: endpoint + '/' + orderId }); let { order } = await api.makeRequest(endpoint + '/' + orderId, 'GET', { output_format: "JSON" }); if (!order) { Log.error( "Order not found", orderId); return; } Log.info( "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( "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( '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(config); if (!fallbackStatusId) { Log.error( '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( 'Cannot import order — could not resolve status', { orderId, psStateId: order.current_state }); return; } Log.info( '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( "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( "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( `Could not fetch invoice address details for address ID: ${order.id_address_invoice}, order ID: ${orderId}`); } } catch (e) { Log.error( `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( '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({ 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( 'PS order mapping save failed', { psOrderId: order.id, error: e.message }); } } } module.exports = { importFromPSOrder };