0

Good day people,

I have been trying to sort the array in customerOrders creating a new module but is not working.

This is what I have so far:

enter image description here

This is the di.xml file:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\SalesGraphQl\Model\Resolver\CustomerOrders" type="Orienteed\SalesOrder\Model\Resolver\CustomerOrders" />

The module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Orienteed_SalesGraphQl" setup_version="1.0.0">
</module>

the schema.graphqls:

type Customer {
orders(
    filter: CustomerOrdersFilterInput
        @doc(
            description: "Defines the filter to use for searching customer orders."
        )
    currentPage: Int = 1
        @doc(
            description: "Specifies which page of results to return. The default value is 1."
        )
    pageSize: Int = 20
        @doc(
            description: "Specifies the maximum number of results to return at once. The default value is 20."
        )
): CustomerOrders
    @resolver(
        class: "Orienteed\\SalesGraphQl\\Model\\Resolver\\CustomerOrders"
    )
    @cache(cacheable: false)

}

The CustomerOrders.php:

namespace Orienteed\SalesOrder\Model\Resolver;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\InputException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\SalesGraphQl\Model\Formatter\Order as OrderFormatter;
use Magento\SalesGraphQl\Model\Resolver\CustomerOrders\Query\OrderFilter;
use Magento\Store\Api\Data\StoreInterface;

class CustomerOrders extends \Magento\SalesGraphQl\Model\Resolver\CustomerOrders

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

/**
 * @var OrderRepositoryInterface
 */
private $orderRepository;

/**
 * @var OrderFilter
 */
private $orderFilter;

/**
 * @var OrderFormatter
 */
private $orderFormatter;

/**
 * @param OrderRepositoryInterface $orderRepository
 * @param SearchCriteriaBuilder $searchCriteriaBuilder
 * @param OrderFilter $orderFilter
 * @param OrderFormatter $orderFormatter
 */
public function __construct(
    OrderRepositoryInterface $orderRepository,
    SearchCriteriaBuilder $searchCriteriaBuilder,
    OrderFilter $orderFilter,
    OrderFormatter $orderFormatter
) {
    $this->orderRepository = $orderRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->orderFilter = $orderFilter;
    $this->orderFormatter = $orderFormatter;
}

/**
 * @inheritDoc
 */

public function resolve(
    Field $field,
    $context,
    ResolveInfo $info,
    array $value = null,
    array $args = null
) {
    if (false === $context->getExtensionAttributes()->getIsCustomer()) {
        throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
    }
    if ($args['currentPage'] < 1) {
        throw new GraphQlInputException(__('currentPage value must be greater than 0.'));
    }
    if ($args['pageSize'] < 1) {
        throw new GraphQlInputException(__('pageSize value must be greater than 0.'));
    }
    $userId = $context->getUserId();
    /** @var StoreInterface $store */
    $store = $context->getExtensionAttributes()->getStore();
    try {
        $searchResult = $this->getSearchResult($args, (int)$userId, (int)$store->getId());
        $maxPages = (int)ceil($searchResult->getTotalCount() / $searchResult->getPageSize());
    } catch (InputException $e) {
        throw new GraphQlInputException(__($e->getMessage()));
    }

    $ordersArray = [];
    foreach ($searchResult->getItems() as $orderModel) {
       $ordersArray[]= $this->orderFormatter->format($orderModel);
    }
    

   usort($ordersArray, function($element1, $element2) {
        $datetime1 = strtotime($element1['order_date']);
        $datetime2 = strtotime($element2['order_date']);
        return $datetime2 - $datetime1;
    } );


    return [
        'total_count' => $searchResult->getTotalCount(),
        'items' => $ordersArray,
        'page_info' => [
            'page_size' => $searchResult->getPageSize(),
            'current_page' => $searchResult->getCurPage(),
            'total_pages' => $maxPages,
        ]
    ];
}

/**
 * Get search result from graphql query arguments
 *
 * @param array $args
 * @param int $userId
 * @param int $storeId
 * @return \Magento\Sales\Api\Data\OrderSearchResultInterface
 * @throws InputException
 */
private function getSearchResult(array $args, int $userId, int $storeId)
{
    $filterGroups = $this->orderFilter->createFilterGroups($args, $userId, (int)$storeId);
    $this->searchCriteriaBuilder->setFilterGroups($filterGroups);
    if (isset($args['currentPage'])) {
        $this->searchCriteriaBuilder->setCurrentPage($args['currentPage']);
    }
    if (isset($args['pageSize'])) {
        $this->searchCriteriaBuilder->setPageSize($args['pageSize']);
    }
    return $this->orderRepository->getList($this->searchCriteriaBuilder->create());
}

}

The part that I am extending that the original file doesn't have is this, I am trying to order the array in descending order taking into account the date:

usort($ordersArray, function($element1, $element2) { $datetime1 = strtotime($element1['order_date']); $datetime2 = strtotime($element2['order_date']); return $datetime2 - $datetime1; } );

The original path of the CustomerOrders.php is this: mymagento-magento-sync/vendor/magento/module-sales-graph-ql/Model/Resolver/CustomerOrders.php

I did all of this and is not working, can anyone help me with this?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.