Skip to content

Instantly share code, notes, and snippets.

@mersanuzun
Last active June 14, 2020 09:04
Show Gist options
  • Save mersanuzun/c48347abfbdf7a02f1c61d590424c568 to your computer and use it in GitHub Desktop.
Save mersanuzun/c48347abfbdf7a02f1c61d590424c568 to your computer and use it in GitHub Desktop.
Payment calculator for trendyol.com
var TrendyolPaymentCalculator = (() => {
const $this = {};
const months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']
$this.calculate = async () => {
const calculatableResult = checkForCalculatable();
if (!calculatableResult.isValid) {
console.error(calculatableResult.message);
return;
}
const orders = await getOrders();
const calculateResultByYearly = await calculatePayment(orders);
const overAllResult = await calculateMontlyPayment(orders);
print(calculateResultByYearly);
printMontly(overAllResult);
}
const checkForCalculatable = () => {
if (location.host !== 'www.trendyol.com') {
return {
isValid: false,
message: 'Lütfen www.trendyol.com sayfasinda olduğunuzdan emin olunuz!',
};
} else if (location.pathname + location.hash !== '/hesabim/siparislerim') {
return {
isValid: false,
message: 'Lütfen siparişlerim sayfasında olduğunuzdan emin olunuz!',
};
}
return {
isValid: true,
};
};
const calculatePayment = (orders) => {
return orders.reduce((result, next) => {
const discounts = (next.discounts || [])
.reduce((totalDiscount, nextDiscount) => {
if ((nextDiscount.name || '').toLowerCase().indexOf('dsm') !== -1) {
totalDiscount.dsm += Math.abs(nextDiscount.price)
} else {
totalDiscount.others += Math.abs(nextDiscount.price)
}
return totalDiscount;
}, { dsm: 0, others: 0 });
return {
discounts: {
dsm: result.discounts.dsm + discounts.dsm,
others: result.discounts.others + discounts.others
},
totalPayment: result.totalPayment + next.payment.totalCharges,
}
}, { discounts: { dsm: 0, others: 0 }, totalPayment: 0 })
};
const calculateMontlyPayment = async (orders) => {
const ordersByYear = orders.reduce((result, next) => {
const date = new Date(next.orderDate);
if (date.getFullYear() in result) {
result[date.getFullYear()].push(next);
} else {
result[date.getFullYear()] = [next];
}
return result;
}, {});
const groupedOrders = Object.keys(ordersByYear).reduce((yearResult, orderYear) => {
return {
...yearResult,
[orderYear]: ordersByYear[orderYear].reduce((result, order) => {
const date = new Date(order.orderDate);
const month = date.getMonth() + 1;
if (month in result) {
result[month].push(order);
} else {
result[month] = [order];
}
return result;
}, {})
}
}, {});
return Object.keys(groupedOrders).reduce((yearResult, orderYear) => {
return {
...yearResult,
[orderYear]: Object.keys(groupedOrders[orderYear]).reduce((result, orderMonth) => {
const paymentResult = calculatePayment(groupedOrders[orderYear][orderMonth]);
console.log(paymentResult)
const summaryResult = {
...paymentResult,
count: groupedOrders[orderYear][orderMonth].length,
average: paymentResult.totalPayment / groupedOrders[orderYear][orderMonth].length,
};
return {
...result,
[orderMonth]: summaryResult
}
}, {})
}
}, {})
};
const getOrders = async () => {
let products = [];
let page = 1;
let hasNextPage = true;
let response;
let data;
while(hasNextPage) {
response = await fetch(`https://www.trendyol.com/Orders/GetV2?page=${page}`);
data = JSON.parse((await response.json()).Data);
if (data && data.length > 0) {
page += 1;
products = [...products, ...data];
} else {
hasNextPage = false;
}
}
return products;
};
const print = (calculatedResult) => {
console.table({
'Toplam İndirim': `${toFixed(calculatedResult.totalDiscount)}`,
'Toplam Ödeme': `${toFixed(calculatedResult.totalPayment)}`,
});
};
const printMontly = (calculatedResult) => {
const printableObject = Object.keys(calculatedResult).flatMap((year) => {
return Object.keys(calculatedResult[year]).reduce((mResult, month) => {
const paymentResult = calculatedResult[year][month];
return mResult.concat({
'Yıl': Number(year),
'Ay': months[month - 1],
'Sipariş Adeti': paymentResult.count,
'Toplam Ödeme': toFixed(paymentResult.totalPayment),
'Toplam İndirim': toFixed(paymentResult.discounts.dsm + paymentResult.discounts.others),
'DSM İndirimi': toFixed(paymentResult.discounts.dsm),
'Diğer İndirimler': toFixed(paymentResult.discounts.others),
'Ortalama': toFixed(paymentResult.average),
});
}, [])
});
console.table(printableObject);
};
const toPrice = (price) => {
return price.toLocaleString('tr-TR', { style: 'currency', currency: 'TRY' })
};
const toFixed = (number = 0) => {
return Number(number.toFixed(2)) || '-';
};
return $this;
})();
TrendyolPaymentCalculator.calculate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment