0

I want to display value based on customer if a customer is online on fronted, then it shows online in custom column in customer grid and if it is offline or logged out then shows offline in same custom column in customer grid in below picture in Customer Online status it should display online is a customer is online and offline if a customer is offline enter image description here

7

1 Answer 1

0

\Vendor\Module\Setup\Patch\Data\CustomerOnlineStatus.php

<?php
declare(strict_types=1);

namespace Vendor\Module\Setup\Patch\Data;

use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;

class CustomerOnlineStatus implements DataPatchInterface
{
    /**
     * @var CustomerSetupFactory
     */
    protected CustomerSetupFactory $customerSetupFactory;

    /**
     * @var ModuleDataSetupInterface
     */
    protected ModuleDataSetupInterface $setup;

    /**
     * @param CustomerSetupFactory $customerSetupFactory
     * @param ModuleDataSetupInterface $setup
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        ModuleDataSetupInterface $setup
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->setup = $setup;
    }

    /**
     * @inheritDoc
     */
    public static function getDependencies(): array
    {
        return [];
    }

    /**
     * @inheritDoc
     */
    public function getAliases(): array
    {
        return [];
    }

    /**
     * @inheritDoc
     * @throws \Exception
     */
    public function apply()
    {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->setup]);

        try {
            $customerSetup->addAttribute(
                Customer::ENTITY,
                'customer_online_status',
                [
                    'type' => 'text',
                    'backend' => '',
                    'label' => 'Customer Online Status Attribute',
                    'input' => 'text',
                    'source' => '',
                    'visible' => true,
                    'required' => false,
                    'default' => '',
                    'frontend' => '',
                    'unique' => false,
                    'note' => '',
                ]
            );
        } catch (LocalizedException|\Zend_Validate_Exception $e) {
        }
        $attribute = $customerSetup->getEavConfig()->getAttribute(
            Customer::ENTITY,
            'customer_online_status'
        );
        $attribute->setData('used_in_forms', ['customer_account_edit'])
            ->setData('is_used_for_customer_segment', true)
            ->setData('is_system', 0)
            ->setData('is_user_defined', 1)
            ->setData('is_visible', 1)
            ->setData('sort_order', 110)
            ->setData("is_used_in_grid", 1)
            ->setData("is_visible_in_grid", 1)
            ->setData("is_filterable_in_grid", 1)
            ->setData("is_searchable_in_grid", 1);
        $attribute->save();
    }
}

\Vendor\Module\Ui\Component\Listing\Column\CustomerOnlineStatus.php

<?php
declare(strict_types=1);

namespace Vendor\Module\Ui\Component\Listing\Column;

use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Customer\Model\ResourceModel\Visitor\CollectionFactory as VisitorCollectionFactory;
use Magento\Customer\Model\Visitor;

class CustomerOnlineStatus extends Column
{
    /**
     * @var Visitor
     */
    protected Visitor $visitorModel;
    /**
     * @var VisitorCollectionFactory
     */
    protected VisitorCollectionFactory $visitorCollectionFactory;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param Visitor $visitorModel
     * @param VisitorCollectionFactory $visitorCollectionFactory
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        Visitor $visitorModel,
        VisitorCollectionFactory $visitorCollectionFactory,
        array $components = [],
        array $data = []
    ) {
        $this->visitorModel = $visitorModel;
        $this->visitorCollectionFactory = $visitorCollectionFactory;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    /**
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource): array
    {
        if (isset($dataSource['data']['items'])) {
            $entityIds = [];
            foreach ($dataSource['data']['items'] as $item) {
                $entityIds[] = $item['entity_id'];
            }
            $online = $this->getOnlineCustomers($entityIds);
            foreach ($dataSource['data']['items'] as &$item) {
                $item[$this->getName()] = isset($online[$item['entity_id']]) ? __('Logged In') : __('Offline');
            }
        }
        return $dataSource;
    }

    /**
     * @param array $customerIds
     * @return array
     */
    protected function getOnlineCustomers(array $customerIds): array
    {
        $collection = $this->visitorCollectionFactory->create();
        $lastDate = gmdate('U') - $this->visitorModel->getOnlineInterval() * 60;
        $collection->addFieldToFilter('last_visit_at', [
            'from' => $collection->getConnection()->formatDate($lastDate),
        ]);
        $collection->addFieldToFilter('customer_id', [
            'in' => $customerIds,
        ]);

        $online = [];
        foreach ($collection as $visitor) {
            $online[$visitor->getCustomerId()] = true;
        }
        return $online;
    }
}

Vendor\Module/view/adminhtml/ui_component/customer_listing.xml

<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <columns name="customer_columns" class="Magento\Customer\Ui\Component\Listing\Columns">
        <column name="customer_online_status" class="Vendor\Module\Ui\Component\Listing\Column\CustomerOnlineStatus" sortOrder="500">
            <settings>
                <label translate="true">Customer Online Status</label>
            </settings>
        </column>
    </columns>
</listing>
9
  • @ Pyaray Afzel , this code is not working when i logged in for same customer in public window and also in private window , it is consider diff for too Jul 22, 2022 at 8:24
  • its working in my end, Jul 22, 2022 at 9:28
  • but you can change logic according to your needs Jul 22, 2022 at 9:38
  • sure no problem Jul 22, 2022 at 9:48
  • @DivyarajsinhBarad Any idea how to apply these filters Jul 22, 2022 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.