I created module and there is cron job in module which will run every Monday and it will take all the data of the product from ordered.
What i do if same product order more than 1 customer so i make 1 row and add qty and price but if the price of product change then i create separate row of that product if its ordered after price change and below is my code which work perfectly if price change 1 time but more than 2 its break
$orders = $this->getOrderCollectionByDateRange();
$ordersMerged = [];
$ordersMergedProductsDifferentPrice = [];
foreach ($orders as $order) {
foreach ($order->getAllVisibleItems() as $item) {
$totalPrice = $item->getQtyOrdered() * $item->getPrice();
if (!array_key_exists($item->getSku(), $ordersMerged)) {
// Add new item to $ordersMerged
$item->setOrderCreatedAt($order->getCreatedAt());
$item->setTotalPrice($totalPrice);
$ordersMerged[$item->getSku()] = $item;
} else {
// Check if the same product has different price
if ($ordersMerged[$item->getSku()]->getPrice() != $item->getPrice()) {
// Update qty and price for existing item in $ordersMergedProductsDifferentPrice
if (array_key_exists($item->getSku(), $ordersMergedProductsDifferentPrice) &&
$ordersMergedProductsDifferentPrice[$item->getSku()]->getPrice() == $item->getPrice()
) {
$totalQty =
$ordersMergedProductsDifferentPrice[$item->getSku()]->getQtyOrdered() + $item->getQtyOrdered();
$totalPrice = $totalQty * $item->getPrice();
$ordersMergedProductsDifferentPrice[$item->getSku()]->setQtyOrdered($totalQty);
$ordersMergedProductsDifferentPrice[$item->getSku()]->setTotalPrice($totalPrice);
} else {
// Add new item to $ordersMergedProductsDifferentPrice
$item->setOrderCreatedAt($order->getCreatedAt());
$item->setTotalPrice($totalPrice);
$ordersMergedProductsDifferentPrice[$item->getSku()] = $item;
}
} else {
// Update qty and price for existing item in $ordersMerged
$totalQty = $ordersMerged[$item->getSku()]->getQtyOrdered() + $item->getQtyOrdered();
$totalPrice = $totalQty * $item->getPrice();
$ordersMerged[$item->getSku()]->setQtyOrdered($totalQty);
$ordersMerged[$item->getSku()]->setTotalPrice($totalPrice);
}
}
}
}
foreach ($ordersMerged as $item) {
$data['sku'] = $item->getSku();
$data['name'] = $item->getName();
$data['price'] = $item->getTotalPrice();
$data['qty'] = $item->getQtyOrdered();
$data['created_at'] = $item->getOrderCreatedAt();
$stream->writeCsv($data);
}
foreach ($ordersMergedProductsDifferentPrice as $item) {
$data['sku'] = $item->getSku();
$data['name'] = $item->getName();
$data['price'] = $item->getTotalPrice();
$data['qty'] = $item->getQtyOrdered();
$data['created_at'] = $item->getOrderCreatedAt();
$stream->writeCsv($data);
}
some on suggest me this logic but i dont know how to implement ? logic below
One way simplier way is to create an prices array for each SKU containing the quantity / totalPrice.
Than foreach on each items->prices() to create the csv. No more limit, way more readable code.