const { Log, Core } = require("@orbito/api-lib"); const PsOrder = require('./models/PsOrder'); const { normalizeStatusId } = require('./status-mapper'); const { paymentTransactionId, parsePrestashopDate, upsertMapping } = require('./automation-jobs'); const { buildProductSourceId, resolveProductMetadata, } = require('./product-metadata'); const DEFAULT_PACK_ITEM_TAX = 0.23; 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; } function normalizeCombinationId(value) { const id = String(value ?? '').trim(); return /^\d+$/.test(id) && id !== '0' ? id : '0'; } function isCombinationForProduct(combination, productId) { return combination && String(combination.id_product ?? '').trim() === String(productId ?? '').trim(); } function resolveProductWeight(product, combination = null) { const baseWeight = Number.parseFloat(product?.weight); if (!combination) return Number.isFinite(baseWeight) ? baseWeight : undefined; // In PrestaShop a combination's weight is an impact added to the base // product weight, not the final weight of the variant. const weightImpact = Number.parseFloat(combination.weight); if (Number.isFinite(baseWeight) && Number.isFinite(weightImpact)) return baseWeight + weightImpact; if (Number.isFinite(baseWeight)) return baseWeight; return Number.isFinite(weightImpact) ? weightImpact : undefined; } function applyCombinationFields(target, combination) { if (!combination) return; if (String(combination.reference || '').trim()) target.sku = combination.reference; if (Object.hasOwn(combination, 'ean13')) target.ean = combination.ean13 || ''; } async function resolvePackItemTax(api, productId, combinationId, context) { try { if (typeof api.getProductTaxRate === 'function') { const tax = await api.getProductTaxRate(productId, combinationId, context); if (Number.isFinite(tax) && tax >= 0 && tax <= 1) return tax; } } catch (error) { Log.warn('Could not resolve PrestaShop pack item VAT; using the default rate', { productId, combinationId, error: error?.message, }); } return DEFAULT_PACK_ITEM_TAX; } 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) { throw new Error(`PrestaShop order ${orderId} not found`); } const addressResponse = await api.makeRequest( 'addresses/' + order.id_address_delivery, 'GET', { output_format: "JSON" } ); const address = addressResponse.address; if (!address) throw new Error(`Delivery address ${order.id_address_delivery} not found`); const productTaxContext = { countryId: address.id_country, stateId: address.id_state, postcode: address.postcode, currencyId: order.id_currency, }; Log.info( "Importing order: " + order.reference); let products = []; for (let product of order.associations.order_rows) { const productId = String(product.product_id); const combinationId = normalizeCombinationId(product.product_attribute_id); 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: buildProductSourceId(productId, combinationId), sku: product.product_reference, ean: product.product_ean13, unitPrice: unitPriceNet, tax: taxRate ? Math.round(taxRate * 100) / 100 : 0, qty: parseFloat(product.product_quantity) }; // Jednorazowa migracja starej tożsamości produktu odbywa się już po // stronie core/products przez synchroniczny kontrakt core/orders. p.previousSourceId = productId; const psProduct = await api.getProduct(productId); Log.debug( "Fetched product details: " + getPSMultiLangField(psProduct.name)); let productCombination = null; if (combinationId !== '0') { const combination = await api.getProductCombination(combinationId); if (isCombinationForProduct(combination, productId)) { productCombination = combination; applyCombinationFields(p, combination); } } const productWeight = resolveProductWeight(psProduct, productCombination); if (productWeight !== undefined) p.weight = productWeight; try { const imgUrl = await api.getProductCoverImageUrl(productId, productCombination); if (imgUrl) p.coverImageUrl = imgUrl; } catch (_) { /* no image available */ } try { const metadata = await resolveProductMetadata(api, psProduct, { sourceId: productId, sku: p.sku, combination: productCombination, requiresCombination: combinationId !== '0', }); if (Object.hasOwn(metadata, 'unitPrice')) { p.baseUnitPrice = metadata.unitPrice; delete metadata.unitPrice; } Object.assign(p, metadata); } catch (_) { /* optional product metadata must not block order import */ } if (psProduct.type == "pack" && psProduct.associations.product_bundle) { p.isPack = true; p.pack = []; for (const packItem of psProduct.associations.product_bundle) { const packProductId = String(packItem.id); const packCombinationId = normalizeCombinationId(packItem.id_product_attribute); const psItem = await api.getProduct(packProductId); const pData = { name: getPSMultiLangField(psItem.name), sourceId: buildProductSourceId(packProductId, packCombinationId), sku: psItem.reference, ean: psItem.ean13, qty: parseFloat(packItem.quantity) }; pData.previousSourceId = packProductId; let packCombination = null; if (packCombinationId !== '0') { const combination = await api.getProductCombination(packCombinationId); if (isCombinationForProduct(combination, packProductId)) { packCombination = combination; applyCombinationFields(pData, combination); } } const packWeight = resolveProductWeight(psItem, packCombination); if (packWeight !== undefined) pData.weight = packWeight; pData.tax = await resolvePackItemTax( api, packProductId, packCombinationId, productTaxContext ); try { const metadata = await resolveProductMetadata(api, psItem, { sourceId: packProductId, sku: pData.sku, combination: packCombination, requiresCombination: packCombinationId !== '0', }); if (Object.hasOwn(metadata, 'unitPrice')) { pData.baseUnitPrice = metadata.unitPrice; delete metadata.unitPrice; } Object.assign(pData, metadata); } catch (_) { /* optional product metadata must not block order import */ } try { const imgUrl = await api.getProductCoverImageUrl(packProductId, packCombination); if (imgUrl) pData.coverImageUrl = imgUrl; } catch (_) { /* no image */ } p.pack.push(pData); } } products.push(p); } const fallbackStatusId = await resolveImportStatusId(config); if (!fallbackStatusId) { throw new Error(`Cannot import order ${orderId} — no valid order status configured`); } // Orbito jest właścicielem statusu. Stan PrestaShop nie może nadpisywać // statusu w Orbito, również przy imporcie nowego zamówienia. Mapowanie // statusów jest używane wyłącznie do synchronizacji Orbito -> PrestaShop. const statusId = fallbackStatusId; Log.info( 'Selected Orbito import status', { orderId, 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 }); 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 createdAt = parsePrestashopDate(order.date_add, new Date(), config.timeZone); const payments = []; if (totalPaidReal > 0) { payments.push({ amount: Math.round(totalPaidReal * 100) / 100, method: order.payment || 'PrestaShop', date: createdAt, transactionId: paymentTransactionId(config, order.id, totalPaidReal), }); } const customerNotes = await api.getCustomerNotes(order.id, order.id_cart, order.gift_message); 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", // własny kod modułu bierzemy z core (po rejestracji), nie z hardcode'u moduleCode: Core.getModuleInfo().code, 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, notes: customerNotes.map(text => ({ text, type: 'customer_message' })), createdAt, }); if (!coreOrder?._id) { throw new Error(`core/orders create did not return an id for PrestaShop order ${order.id}`); } const now = new Date(); await upsertMapping(PsOrder, { shopConfigId: config._id, psOrderId: parseInt(order.id), orbitoOrderId: coreOrder._id, reference: order.reference || '', syncedAt: createdAt, paymentTotalSynced: totalPaidReal, paymentSyncedAt: totalPaidReal > 0 ? now : undefined, paymentCheckedAt: now, nextPaymentCheckAt: now, }); return { status: 'imported', psOrderId: Number(order.id), orbitoOrderId: coreOrder._id }; } module.exports = { importFromPSOrder };