B
B
boris tyrepharm2019-09-09 13:34:33
1C-Bitrix
boris tyrepharm, 2019-09-09 13:34:33

Why, when manually adding a product to the order basket, the product is added with the status "not active"?

Greetings! Faced the following problem:
I'm editing an order via API D7: I need to add a product to the order basket.
Below is a code snippet that adds a product to the shopping cart:

<?php
// Данные для примера
$orderId = 100;
$catalogId = 457;
$quantity = 1;
$price = 100;

// Загружаем заказ и получаем его корзину
$orderBx = Sale\Order::loadByAccountNumber($orderId);
$basketBx = $orderBx->getBasket();

// Добавляем товар в корзину заказа
$ProductAdd = $basketBx->createItem('catalog', $catalogId);
                        
// Так как товар добавляется "пустым" (практически без свойств), то подгрузим свойства из БД
$iblock = CIBlockElement::GetByID($catalogId)->GetNext();
$cprice = CPrice::GetList(array(),array("PRODUCT_ID" => $catalogId))->GetNext();
$ccatalog_res = CCatalogProduct::GetByID($catalogId);                         
$measure = CCatalogMeasure::getList(array(),array("ID" => $ccatalog_res['MEASURE']))->GetNext();

$dimensions = serialize(array(
    "WIDTH"     => $ccatalog_res["WIDTH"],
    "HEIGHT"    => $ccatalog_res["HEIGHT"],
    "LENGTH"    => $ccatalog_res["LENGTH"]
));

// Заполним поля товара
$ProductAdd->setFields(array(
    'NAME' 			    => $iblock['NAME'],
    'DETAIL_PAGE_URL'   => $iblock['DETAIL_PAGE_URL'],
    'PRODUCT_ID'	    => $catalogId,
    'PRODUCT_PRICE_ID'  => $cprice['ID'],
    'QUANTITY'		    => $quantity,
    'CURRENCY'		    => Bitrix\Currency\CurrencyManager::getBaseCurrency(),
    'LID' 			    => Bitrix\Main\Context::getCurrent()->getSite(),
    'PRICE' 		    => $price,
    'BASE_PRICE'	    => $price,
    'CUSTOM_PRICE' 	    => 'Y',
    'WEIGHT'		    => $ccatalog_res['WEIGHT'],
    'DIMENSIONS'	    => $dimensions,
    'NOTES'			    => $cprice['CATALOG_GROUP_NAME'],
    'MEASURE_CODE'	    => $measure['CODE'],
    'MEASURE_NAME'	    => $measure['SYMBOL'],
    'CATALOG_XML_ID'    => 'aspro_mshop_catalog_s1',
    'PRODUCT_XML_ID'    => $catalogId,
    'PRODUCT_PROVIDER_CLASS' => 'CCatalogProductProvider',
    'DELAY'			    => 'N',
    'CAN_BUY'		    => 'Y',
    'IGNORE_CALLBACK_FUNC'	=> 'Y'
));
 
// Сохраним товар
$ProductAdd->save();

// Сохраним корзину
$basketBx->save();
?>

After executing the code, the product actually goes to the cart with all the assigned properties and is saved in the order. But when viewing an order through the admin panel, the products sometimes (most likely, when this item was already present in the basket - see screenshot) are marked as crossed out and when hovering over the name, the inscription "Product is not active" appears.
5d762aa91fa5a790524474.png
Can you tell me what could be the problem and how it can be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Gritsuk, 2019-09-10
@winer

<?
\Bitrix\Main\Loader::includeModule("sale");
\Bitrix\Main\Loader::includeModule("catalog");


\Bitrix\Sale\Order::load($orderId);
$basket = $order->getBasket();
$shipmentCollection = $order->getShipmentCollection();

$products = [1, 2, 3];
$quantity = 1;
$newBasketItems = [];

//Добавляем новые товары в корзину
foreach ($products as $productId) {
    $item = $basket->createItem('catalog', $productId);
    $item->setFields(array(
        'QUANTITY' => $quantity,
        'CURRENCY' => \Bitrix\Currency\CurrencyManager::getBaseCurrency(),
        'LID' => $order->getSiteId(),
        'PRODUCT_PROVIDER_CLASS' => 'CCatalogProductProvider',
    ));
    $item->setField("QUANTITY", $quantity);
    $newBasketItems[] = $item;
}

//Теперь эти товары надо добавить в отгрузку. В примере добавляю в первую попавшуюся
foreach ($shipmentCollection as $shipment) {
    if (!$shipment->isSystem()) {
        foreach ($newBasketItems as $newBasketItem) {
            /** @var \Bitrix\Sale\Shipment $shipment */
            $shipmentItemCollection = $shipment->getShipmentItemCollection();
            $shipmentItem = $shipmentItemCollection->createItem($newBasketItem);
            $shipmentItem->setQuantity($item->getQuantity());
        }
        break;
    }
}



//Пересчитываем заказ
$discount = $order->getDiscount();
$result = new \Bitrix\Main\Result();

\Bitrix\Sale\DiscountCouponsManager::clearApply(true);
\Bitrix\Sale\DiscountCouponsManager::useSavedCouponsForApply(true);
$discount->setOrderRefresh(true);
$discount->setApplyResult(array());

$res = $basket->refreshData(array('PRICE', 'COUPONS'));

if (!$res->isSuccess())
    $result->addErrors($res->getErrors());


$res = $discount->calculate();
if (!$res->isSuccess())
    $result->addErrors($res->getErrors());

if (!$order->isCanceled() && !$order->isPaid()) {
    /** @var \Bitrix\Sale\PaymentCollection $paymentCollection */
    if (($paymentCollection = $order->getPaymentCollection()) && count($paymentCollection) == 1) {
        /** @var \Bitrix\Sale\Payment $payment */
        if (($payment = $paymentCollection->rewind()) && !$payment->isPaid()) {
            $payment->setFieldNoDemand('SUM', $order->getPrice());
        }
    }
}

//Сохраняем заказ, а не корзину
//Если обработка идет в каком то событии заказа, то метод save вызывать не надо
$order->save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question