Files
vinoteca/local/modules/jinove.vinoteca/lib/personal/orders.php
T

74 lines
3.0 KiB
PHP

<?php
declare(strict_types=1);
namespace Jinove\Vinoteca\Personal;
use Bitrix\Main\Loader;
use Bitrix\Sale\Internals\BasketTable;
use Bitrix\Sale\Order;
use Bitrix\Sale\OrderStatus;
use Jinove\Vinoteca\Catalog\Media;
use Jinove\Vinoteca\Catalog\Related;
use Jinove\Vinoteca\Money;
class Orders
{
private const FINAL_STATUS = "F";
private const PER_PAGE = 20;
public static function forUser(int $userId, bool $completed, int $page = 1): array
{
if ($userId <= 0 || !Loader::includeModule("sale") || !Loader::includeModule("currency")) {
return ["orders" => [], "more" => false];
}
$statuses = OrderStatus::getAllStatusesNames(LANGUAGE_ID);
$filter = $completed
? ["=USER_ID" => $userId, ["LOGIC" => "OR", ["=STATUS_ID" => self::FINAL_STATUS], ["=CANCELED" => "Y"]]]
: ["=USER_ID" => $userId, "!=STATUS_ID" => self::FINAL_STATUS, "=CANCELED" => "N"];
$orders = [];
$rows = Order::getList([
"select" => ["ID", "ACCOUNT_NUMBER", "DATE_INSERT", "STATUS_ID", "PRICE", "CURRENCY", "CANCELED"],
"filter" => $filter,
"order" => ["ID" => "DESC"],
"limit" => self::PER_PAGE + 1,
"offset" => (max(1, $page) - 1) * self::PER_PAGE,
]);
while ($row = $rows->fetch()) {
$orders[(int)$row["ID"]] = [
"number" => (string)$row["ACCOUNT_NUMBER"],
"date" => $row["DATE_INSERT"]->getTimestamp(),
"statusId" => (string)$row["STATUS_ID"],
"status" => $row["CANCELED"] === "Y" ? "" : (string)($statuses[$row["STATUS_ID"]] ?? ""),
"canceled" => $row["CANCELED"] === "Y",
"total" => Money::format((float)$row["PRICE"], (string)$row["CURRENCY"]),
"items" => [],
];
}
$more = count($orders) > self::PER_PAGE;
$orders = array_slice($orders, 0, self::PER_PAGE, true);
if (!$orders) {
return ["orders" => [], "more" => false];
}
$lines = BasketTable::getList([
"select" => ["ORDER_ID", "PRODUCT_ID", "NAME", "QUANTITY", "PRICE", "CURRENCY"],
"filter" => ["@ORDER_ID" => array_keys($orders)],
"order" => ["ID" => "ASC"],
])->fetchAll();
$productIds = array_map(static fn(array $line): int => (int)$line["PRODUCT_ID"], $lines);
$images = Media::thumbs($productIds, 120, 120);
$products = Related::summariesById($productIds);
foreach ($lines as $line) {
$orders[(int)$line["ORDER_ID"]]["items"][] = [
"name" => (string)$line["NAME"],
"url" => (string)($products[(int)$line["PRODUCT_ID"]]["url"] ?? ""),
"quantity" => (float)$line["QUANTITY"],
"price" => Money::format((float)$line["PRICE"], (string)$line["CURRENCY"]),
"image" => $images[(int)$line["PRODUCT_ID"]] ?? "",
];
}
return ["orders" => array_values($orders), "more" => $more];
}
}