We can use sales_order_save_after
, check the condition directly on your observer. However, we should try with Plugin.
app/code/Company/Module/etc/adminhtml/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Sales\Api\OrderRepositoryInterface">
<plugin name="change_user_group"
type="Company\Module\Model\Plugin\ChangeUserGroupPlugin"/>
</type>
</config>
Your Plugin:
<?php
namespace Company\Module\Model\Plugin;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Sales\Model\Order;
class ChangeUserGroupPlugin
{
const ID_CUSTOMER_GROUP_CHANGE = 5; // For example group
/**
* @var CustomerRepositoryInterface
*/
protected $_customerRepository;
/**
* ChangeUserGroupObserver constructor.
* @param CustomerRepositoryInterface $customerRepository
*/
public function __construct(
CustomerRepositoryInterface $customerRepository
)
{
$this->_customerRepository = $customerRepository;
}
/**
* @param \Magento\Sales\Api\OrderRepositoryInterface $subject
* @param \Magento\Sales\Api\Data\OrderInterface $result
* @return mixed
* @throws \Exception
*/
public function afterSave(
\Magento\Sales\Api\OrderRepositoryInterface $subject,
$result
) {
if($result->getState() == Order::STATE_COMPLETE) {
try {
$customerId = $result->getCustomerId();
$customer = $this->_customerRepository->getById($customerId);
$current_group = $customer->getGroupId();
if ($current_group != self::ID_CUSTOMER_GROUP_CHANGE) {
$customer->setGroupId(self::ID_CUSTOMER_GROUP_CHANGE);
$this->_customerRepository->save($customer);
}
}
catch (\Exception $e) {
throw $e;
}
}
return $result;
}
}