Can i generate Shipment/invoice
using GraphQL in magento 2.4.5 ?
If yes kindly let me know how to generate, any links with brief details also appreciated.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityCan i generate Shipment/invoice
using GraphQL in magento 2.4.5 ?
If yes kindly let me know how to generate, any links with brief details also appreciated.
schema.graphqls
in your module
directory.Here is the code.
type Mutation {
createShipment(input: ShipmentInput!): ShipmentOutput
}
input ShipmentInput {
order_id: Int!
items: [ShipmentItemInput]
}
input ShipmentItemInput {
order_item_id: Int!
qty: Float!
}
type ShipmentOutput {
shipment: Shipment
}
type Shipment {
increment_id: String
trackings: [Tracking]
}
type Tracking {
track_number: String
carrier_code: String
}
Here's an example of how you can create a resolver class that handles the createShipment
mutation in Magento 2:
<?php
namespace Vendor\Module\Model\Resolver;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class CreateShipmentResolver implements ResolverInterface
{
/**
* @var \Magento\Sales\Api\ShipmentRepositoryInterface
*/
private $shipmentRepository;
/**
* @var \Magento\Sales\Api\OrderRepositoryInterface
*/
private $orderRepository;
public function __construct(
\Magento\Sales\Api\ShipmentRepositoryInterface $shipmentRepository,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository
)
{
$this->shipmentRepository = $shipmentRepository;
$this->orderRepository = $orderRepository;
}
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$shipmentDatas = [];
$order = $this->orderRepository->get($args['input']['order_id']);
if (!$order->canShip()) {
throw new GraphQlInputException(__('Order cannot be shipped.'));
}
$items = $args['input']['items'];
$data = [];
foreach ($items as $item) {
$data[$item['order_item_id']] = $item['qty'];
}
$shipment = $this->shipmentRepository->create(
$order,
$data,
__('Shipment Created from GraphQL')
);
$this->shipmentRepository->save($shipment);
$increment_id = $shipment->getIncrementId();
$trackings = $shipment->getAllTracks();
$trackingData = array();
foreach ($trackings as $tracking) {
$trackingData[] = [
'track_number' => $tracking->getNumber(),
'carrier_code' => $tracking->getCarrierCode()
];
}
$shipmentDatas = [
'increment_id' => $increment_id,
'trackings' => $trackingData
];
return $shipmentDatas;
}
}
Let me know if any query.
THANKS.