Your IP : 216.73.216.220


Current Path : /home/rtorresani/www/app/code/Amasty/RewardsImportEntity/Model/
Upload File :
Current File : //home/rtorresani/www/app/code/Amasty/RewardsImportEntity/Model/PointsLeftCalculator.php

<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) 2023 Amasty (https://www.amasty.com)
 * @package Reward Points Import Entity for Magento 2 (System)
 */

namespace Amasty\RewardsImportEntity\Model;

use Amasty\Rewards\Api\Data\RewardsInterface;
use Amasty\Rewards\Api\RewardsRepositoryInterface;
use Magento\Framework\Api\SearchCriteria;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrderBuilder;

class PointsLeftCalculator
{
    /**
     * @var RewardsRepositoryInterface
     */
    private $rewardsRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    private $searchCriteriaBuilder;

    /**
     * @var SortOrderBuilder
     */
    private $sortOrderBuilder;

    /**
     * @var array
     */
    private $pointsLeftByCustomerIds = [];

    public function __construct(
        RewardsRepositoryInterface $rewardsRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        SortOrderBuilder $sortOrderBuilder
    ) {
        $this->rewardsRepository = $rewardsRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->sortOrderBuilder = $sortOrderBuilder;
    }

    /**
     * @param int $customerId
     * @param float $amount
     * @return float|int
     */
    public function calculate(int $customerId, float $amount)
    {
        if (empty($this->pointsLeftByCustomerIds[$customerId])) {
            $this->pointsLeftByCustomerIds[$customerId] = 0;
        }

        $searchCriteria = $this->prepareSearchCriteria($customerId);
        $rewardTransactions = $this->rewardsRepository->getList($searchCriteria);
        if ($rewardTransactions->getTotalCount() > 0 && empty($this->pointsLeftByCustomerIds[$customerId])) {
            /** @var RewardsInterface $reward */
            foreach ($rewardTransactions->getItems() as $reward) {
                $this->pointsLeftByCustomerIds[$customerId] += max(0, $reward->getPointsLeft() + $amount);
                break;
            }
        } else {
            $this->pointsLeftByCustomerIds[$customerId] += $amount;
        }

        return max(0, $this->pointsLeftByCustomerIds[$customerId]);
    }

    /**
     * @param int $customerId
     * @return SearchCriteria
     */
    private function prepareSearchCriteria(int $customerId): SearchCriteria
    {
        $this->sortOrderBuilder->setField(RewardsInterface::ID);
        $this->sortOrderBuilder->setDescendingDirection();
        $sortByQtyAsc = $this->sortOrderBuilder->create();

        $this->searchCriteriaBuilder->addFilter(RewardsInterface::CUSTOMER_ID, $customerId);
        $this->searchCriteriaBuilder->addSortOrder($sortByQtyAsc);

        return $this->searchCriteriaBuilder->create();
    }
}