How To

Magento 2: How to Get Custom Column Value of Invoice and Credit Memo using GraphQL

Hello Magento Friends,

In today’s Magento 2 tutorial, I am going to demonstrate How to Get Custom Column Value of Invoice and Credit Memo using GraphQL in Magento 2.

Adding custom columns to the invoice and credit memo tables in the Magento 2 database can be useful for storing information about orders, products, or customers that are not included in the standard Magento 2 database schema. For example, you might want to add a custom column to the invoice table to store information about a specific product that was included in an order, or a custom column to the credit memo table to store information about a refund that was issued for a specific order.

You can use the Magento 2 GraphQL API to retrieve the values of those custom columns for a specific invoice or credit memo. Let’s find out how

Steps to Get Custom Column Value of Invoice and Credit Memo using GraphQL in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside etc folder

app\code\Vendor\Extension\etc\

Then add the code as follows

type Query {
    customerOrders: CustomerOrders @resolver(class: "Magento\\SalesGraphQl\\Model\\Resolver\\Orders") @deprecated(reason: "Use the `customer` query instead.") @cache(cacheable: false)
}

type CustomerOrders @doc(description: "The collection of orders that match the conditions defined in the filter.") {
    items: [CustomerOrder]! @doc(description: "An array of customer orders.")
    page_info: SearchResultPageInfo @doc(description: "Contains pagination metadata.")
    total_count: Int @doc(description: "The total count of customer orders.")
}
type CustomerOrder  { 
    invoices: [Invoice]! @doc(description: "A list of invoices for the order.") @resolver(class: "Vendor\\Extension\\Model\\Resolver\\Invoices")
    credit_memos: [CreditMemo] @doc(description: "A list of credit memos.") @resolver(class: "Vendor\\Extension\\Model\\Resolver\\CreditMemos")
}
type Invoice @doc(description: "Contains invoice details.") {
   custom_fee: Float  @deprecated(reason: "Use the `custom_fee` field instead.")
}
type CreditMemo @doc(description: "Contains CreditMemo details.") {
   custom_fee: Float  @deprecated(reason: "Use the `custom_fee` field instead.")
}

Step 2: After that, create “Invoices.php” file inside Resolver folder

app\code\Vendor\Extension\Model\Resolver\

And include the below-mentioned code

<?php

declare(strict_types=1);

namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\InvoiceInterface;

/**
 * Resolver for Invoice
 */class Invoices implements ResolverInterface
{
    /**
     * @inheritDoc
     */    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        if (!(($value['model'] ?? null) instanceof OrderInterface)) {
            throw new LocalizedException(__('"model" value should be specified'));
        }

        /** @var OrderInterface $orderModel */        $orderModel = $value['model'];
        $invoices = [];
        /** @var InvoiceInterface $invoice */        foreach ($orderModel->getInvoiceCollection() as $invoice) {
            $invoices[] = [
                'id' => base64_encode($invoice->getEntityId()),
                'number' => $invoice['increment_id'],
                'custom_fee' => $invoice->getCustomFee(),
                'model' => $invoice,
                'order' => $orderModel
            ];
        }
        return $invoices;
    }

    /**
     * Get invoice comments in proper format
     *
     * @param InvoiceInterface $invoice
     * @return array
     */    private function getInvoiceComments(InvoiceInterface $invoice): array
    {
        $comments = [];
        foreach ($invoice->getComments() as $comment) {
            if ($comment->getIsVisibleOnFront()) {
                $comments[] = [
                    'timestamp' => $comment->getCreatedAt(),
                    'message' => $comment->getComment()
                ];
            }
        }
        return $comments;
    }
}

Step 3: After that, create “CreditMemos.php” file inside Resolver folder

app\code\Vendor\Extension\Model\Resolver\

Then include the following code

<?php
declare(strict_types=1);

namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\Data\OrderInterface;

/**
 * Resolve credit memos for order
 */class CreditMemos implements ResolverInterface
{
    /**
     * @inheritDoc
     */    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        if (!(($value['model'] ?? null) instanceof OrderInterface)) {
            throw new LocalizedException(__('"model" value should be specified'));
        }

        /** @var OrderInterface $orderModel */        $orderModel = $value['model'];

        $creditMemos = [];
        /** @var CreditmemoInterface $creditMemo */        foreach ($orderModel->getCreditmemosCollection() as $creditMemo) {
            $creditMemos[] = [
                'id' => base64_encode($creditMemo->getEntityId()),
                'number' => $creditMemo->getIncrementId(),
                'custom_fee' => $creditMemo->getCustomFee(),
                'order' => $orderModel,
                'model' => $creditMemo
            ];
        }
        return $creditMemos;
    }
}

Step 4: Finally, run the upgrade and compile commands, then pass the query like below in the server

For Invoice:

{
  customerOrders {
    items {
      order_number
      id
      invoices{
      custom_fee
      }
      
    }
  }
}

For Creditmemo:

{
  customerOrders {
    items {
      order_number
      id
      credit_memos{
      custom_fee
      }
      
    }
  }
}

Output:

For Invoice:

Credit memo:

Conclusion:

In this blog post, we have walked you through the process of using the Magento 2 GraphQL API to retrieve the values of those custom columns for a specific invoice or credit memo.

Related Article,

Magento 2: How to Get Custom Column Value of Order using GraphQL

If you have any questions or need further assistance, please feel free to contact us. We are always happy to help!

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Get Database Value in Shopify Theme App Extension using App Proxy?

In this article, we will learn about how to get database value in the Shopify…

3 hours ago

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

2 days ago

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

4 days ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

1 week ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

1 week ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

1 week ago