Question

Change customer group based on how many orders they've done. Silver 1-4 orders Gold 5-6 orders Emerald >10 orders You need to add those groups to Magento(programmatically) and ensure that every placed by customer checks if he meets conditions to go into another group. Bear in min that only completed orders are taken into consideration here, so any customer can be downgraded to the correct tier if it is possible. This should be created using a patch.

Was it helpful?

Solution

You can add an observer on the checkout_submit_all_after event in the etc/webapi_rest/events.xml file.

In the observer class you should inject the following classes and initialize private properties in the constructor

Magento\Customer\Api\CustomerRepositoryInterface to be stored inside $this->customer
Magento\Sales\Model\ResourceModel\Order\CollectionFactory to be stored inside $this->salesOrderCollection

then, in the execute() method of your observer, retrieve the order:

$order = $observer->getData('order');

then load the customer:

$customer = $this->customer->getById($order->getBillingAddress()->getCustomerId());

then count the orders of the customers:

$collection = $this->salesOrderCollection->create();
$collection->addFieldToFilter('customer_id', $customer->getCustomerId());
count($collection)

make your decisions based on your logic and then assign the customer group to the customer entity:

$groupId=6; //replace with your actual group ID
$customer->setGroupId($groupId);
$customer->save();

OTHER TIPS

1)create InstallData file in module setup folder with following code:

<?php
namespace Vendor\Extension\Setup;

use Magento\Framework\Module\Setup\Migration;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Model\GroupFactory;

class InstallData implements InstallDataInterface
{
    protected $groupFactory;

    public function __construct(GroupFactory $groupFactory) {
        $this->groupFactory = $groupFactory;
    }

    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();

        $group = $this->groupFactory->create();
        $group
            ->setCode('New Group')
            ->setTaxClassId(3) 
            ->save();

        $setup->endSetup();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top