| Current Path : /proc/thread-self/root/proc/thread-self/root/home/deltalab/PMS/ims-connector/rest/queries/ |
| Current File : //proc/thread-self/root/proc/thread-self/root/home/deltalab/PMS/ims-connector/rest/queries/order.js |
/* eslint-disable new-cap */
/* eslint-disable no-restricted-syntax */
const axios = require('axios');
const { dotenv } = require('dotenv').config();
const { orderBaseModel } = require('../../models/mongoose/order');
const { orderCustomerModel } = require('../../models/mongoose/order');
const { orderAddressModel } = require('../../models/mongoose/order');
const { orderItemModel } = require('../../models/mongoose/order');
const { orderMoneyModel } = require('../../models/mongoose/order');
const auth = require('./auth');
const restUrl = process.env.MAGENTO_REST_HOST;
/**
* Return a list of products given a partner ID
* @param {string} partnerId
* @returns products
*/
async function readMany(storeName = 'all') {
const method = 'get';
const url = `${restUrl}/${storeName}/V1/orders`;
const criteria = {
searchCriteria: 0,
};
const strCriteria = [];
console.log(url);
for (const key in criteria) {
if (Object.prototype.hasOwnProperty.call(criteria, key)) {
strCriteria.push(`${key}=${criteria[key]}`);
}
}
const token = await auth.getOAuthToken(method, url, criteria);
// const token = await auth.getBearerToken(storeName);
const config = {
method,
url: `${url}?${strCriteria.join('&')}`,
headers: {
Authorization: `OAuth ${token}`,
},
};
const result = await axios(config);
return result.data;
}
async function readOne(storeName = 'all', id) {
const method = 'get';
const url = `${restUrl}/${storeName}/V1/orders`;
const criteria = {
'searchCriteria[filterGroups][0][filters][0][conditionType]': 'eq',
'searchCriteria[filterGroups][0][filters][0][field]': 'increment_id',
'searchCriteria[filterGroups][0][filters][0][value]': id,
};
const strCriteria = [];
for (const key in criteria) {
if (Object.prototype.hasOwnProperty.call(criteria, key)) {
strCriteria.push(`${key}=${criteria[key]}`);
}
}
const token = await auth.getOAuthToken(method, url, criteria);
// const token = await auth.getBearerToken(storeName);
const config = {
method,
url: `${url}?${strCriteria.join('&')}`,
headers: {
Authorization: `OAuth ${token}`,
},
};
const result = await axios(config);
return result.data;
}
/**
* Retrieve an Order object from the response node
* @param {orderBaseModel} order the order to populate
* @param {*} node data collected from oms
* @return the standard order model representation
*/
async function populateOrder(magentoOrder) {
const order = new orderBaseModel();
// mapping magento shit into our data structure
order.omsgid = magentoOrder.increment_id;
order.name = magentoOrder.increment_id;
order.storeId = magentoOrder.store_id;
order.createdAt = magentoOrder.created_at;
order.fullyPaid = true; // need to check where it's defined node.fullyPaid;
order.cashOnDelivery = magentoOrder.payment.method === 'cashondelivery';
order.customer = new orderCustomerModel();
order.customer.displayName = `${magentoOrder.billing_address.firstname} ${magentoOrder.billing_address.lastname}`;
order.customer.email = magentoOrder.billing_address.email;
order.customer.phone = magentoOrder.billing_address.telephone;
order.status = magentoOrder.status; //! == 'complete' ? 'Processing' : 'Fulfilled';
order.shippingAddress = new orderAddressModel();
// Sanity check
if (magentoOrder.extension_attributes.shipping_assignments[0].shipping.address) {
const shipping = magentoOrder.extension_attributes.shipping_assignments[0].shipping.address;
order.shippingAddress.name = `${shipping.company ?? ''} - ${shipping.firstname} ${shipping.lastname} - ${shipping.city}`;
// latitude, longitude??
order.shippingAddress.company = shipping.company;
order.shippingAddress.address1 = shipping.street[0] ?? '';
order.shippingAddress.address2 = shipping.street[1] ?? '';
order.shippingAddress.phone = shipping.telephone;
order.shippingAddress.city = shipping.city;
order.shippingAddress.province = shipping.region ?? '';
order.shippingAddress.zip = shipping.postcode;
order.shippingAddress.country = shipping.country_id;
}
order.totalPriceSet = new orderMoneyModel();
order.totalPriceSet.amount = magentoOrder.base_grand_total;
order.totalPriceSet.currencyCode = magentoOrder.base_currency_code;
// populate the order items iterating over the line items
order.items = [];
const lineItems = magentoOrder.items;
const sanitizedLineItems = getLinesWithoutConfigurableParents(lineItems); //caso particolare: più righe dello stesso item
for (const lineItem of sanitizedLineItems) {
// A little sanity check
const item = new orderItemModel();
item.imsgid = lineItem.item_id;
item.name = lineItem.name;
item.sku = lineItem.sku;
item.title = lineItem.title;
item.quantity = lineItem.qty_ordered;
item.totalPriceSet = new orderMoneyModel();
item.totalPriceSet.amount = lineItem.row_total_incl_tax;
item.totalPriceSet.currencyCode = magentoOrder.store_currency_code;
item.unitPriceSet = new orderMoneyModel();
item.unitPriceSet.amount = lineItem.base_price;
item.unitPriceSet.currencyCode = magentoOrder.store_currency_code;
order.items.push(item);
}
return order;
}
function getLinesWithoutConfigurableParents(lineItems) {
const sanitizedLines = [];
for (let i = 0; i < lineItems.length; i++) {
let found = false;
for (let j = 0; j < lineItems.length; j++) {
if (i === j) {
continue;
}
if (lineItems[i].sku === lineItems[j].sku) {
found = true;
if (lineItems[i].product_type === 'configurable' && lineItems[j].product_type === 'simple') {
//original item is the one to save
sanitizedLines.push(lineItems[i]);
}
}
}
if (!found) {
sanitizedLines.push(lineItems[i]);
}
}
return sanitizedLines;
}
module.exports = {
readMany,
readOne,
populateOrder,
};