<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Model\Service;

use \Magento\Sales\Model\Service\InvoiceService as MagentoInvoiceService;
use \Magento\Sales\Api\Data\InvoiceItemInterface;
use \Magento\Framework\Exception\LocalizedException;

/**
 * Class InvoiceService
 */
class InvoiceService extends MagentoInvoiceService
{
    /**
     * Set quantity to invoice item
     *
     * @param InvoiceItemInterface $item
     * @param float $qty
     * @return $this
     * @throws LocalizedException
     */
    public function setInvoiceItemQuantity(InvoiceItemInterface $item, $qty)
    {
        $qty = ($item->getOrderItem()->getIsQtyDecimal()) ? (float) $qty : (float) $qty;
        $qty = $qty > 0 ? $qty : 0;

        /**
         * Check qty availability
         */
        $qtyToInvoice = sprintf("%F", $item->getOrderItem()->getQtyToInvoice());
        $qty = sprintf("%F", $qty);
        if ($qty > $qtyToInvoice && !$item->getOrderItem()->isDummy()) {
            throw new LocalizedException(
                __('We found an invalid quantity to invoice item "%1".', $item->getName())
            );
        }

        $item->setQty($qty);

        return $this;
    }
}
