Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Magento B2B - Cannot Assign Customer Group ID #38187

Closed
1 of 5 tasks
portchris opened this issue Nov 15, 2023 · 11 comments
Closed
1 of 5 tasks

Magento B2B - Cannot Assign Customer Group ID #38187

portchris opened this issue Nov 15, 2023 · 11 comments
Assignees
Labels
Issue: needs update Additional information is require, waiting for response Reported on 2.4.6-p3 Indicates original Magento version for the Issue report.

Comments

@portchris
Copy link

portchris commented Nov 15, 2023

Preconditions and environment

  • Magento Enterprise 2.4.6-p3
  • Magento B2B 1.3.3-p3
  • PHP 8.2
  • Varnish 6.5.1
  • Elasticsearch 7.7.1
  • Elasticsuite 2.10.16
  • NGINX Proxy + PHP-FPM 1.23.4
  • MariaDB 10.4.29-MariaDB-1:10.4.29+maria~ubu2004

Steps to reproduce

Install fresh version of Magento:

    composer create-project --repository-url=https://repo.magento.com/ magento/project-enterprise-edition .
    composer require magento/extension-b2b smile/elasticsuite
    composer update --lock

Create DB:

CREATE DATABASE magento246;

Install and deploy

    bin/magento setup:install \
    --base-url=http://magento2-demo.localhost/ \
    --db-host=mysql \
    --db-name=magento246 \
    --db-user=user \
    --db-password=password \
    --admin-firstname=My \
    --admin-lastname=Name \
    --admin-email=email@test.com\
    --admin-user=developer \
    --admin-password=dev@2023 \
    --backend-frontname=admin \
    --language=en_AU \
    --currency=AUD \
    --timezone=Australia/Melbourne \
    --use-rewrites=1 \
    --search-engine=elasticsuite \
    --elasticsearch-host=elasticsearch7 \
    --elasticsearch-index-prefix=demo_ \
    --elasticsearch-port=9200 

    export COMPOSER_MEMORY_LIMIT=-1 && composer -n validate && composer -n install && php ./vendor/bin/ece-patches apply || true && rm -rf generated/* && php bin/magento deploy:mode:set production -s && php bin/magento setup:upgrade && php bin/magento maintenance:enable && php bin/magento module:disable Magento_TwoFactorAuth Magento_AdminAdobeImsTwoFactorAuth && php bin/magento setup:di:compile && touch pub/static/deployed_version.txt && php bin/magento setup:static-content:deploy -f en_AU en_US && php bin/magento cache:flush && php bin/magento cache:enable && php bin/magento maintenance:disable

Login to Admin with newly created user https://magento2-demo.localhost/admin/ navigate to:

Admin > Customers > Companies

Create a new company + admin. Assign default customer group

Then, attempt to change the customer group via:

Admin > Customers > All Customers > Check: Company Admin > Actions: Assign a Customer Group

Expected result

The customer group is updated.

Actual result

The customer group is NOT updated despite a success message displaying.

Additional information

Is this a feature not a bug?

After looking into the code I've found the following:
vendor/magento/module-company/etc/di.xml

    <type name="Magento\Company\Model\SaveHandlerPool">
        <arguments>
            <argument name="handlers" xsi:type="array">
                <item name="defaultRole" xsi:type="object">\Magento\Company\Model\SaveHandler\DefaultRole</item>
                <item name="superUser" xsi:type="object">\Magento\Company\Model\SaveHandler\SuperUser</item>
                <item name="salesRepresentative" xsi:type="object">\Magento\Company\Model\SaveHandler\SalesRepresentative</item>
                <item name="companyStatus" xsi:type="object">\Magento\Company\Model\SaveHandler\CompanyStatus</item>
                <item name="customerGroup" xsi:type="object">\Magento\Company\Model\SaveHandler\CustomerGroup</item>
            </argument>
        </arguments>
    </type>

Magento\Company\Model\SaveHandler\CustomerGroup::execute

        if (!$initialCompany->getId() || $initialCompany->getCustomerGroupId() != $company->getCustomerGroupId()) {
            $customerIds = $this->customerResource->getCustomerIdsByCompanyId($company->getId());
            foreach ($customerIds as $customerId) {
                $customer = $this->customerRepository->getById($customerId);
                $customer->setGroupId($company->getCustomerGroupId());
                $this->customerRepository->save($customer);
            }
        }

So this appears to be purposely negated in favour of the companies customer group. Despite this however, there is still a misleading message to the end user and this feature should either work or not be there at all.

Since this action is still available as a feature, this should still work to some capacity. That being:
If the customer is a company admin, this should be sufficient enough privileges to change the customer's group + company. Else throw a warning message.

Magento WebAPI

Additionally, I have observed that it is no longer possible to update a customer's group ID via Web API. This appears to be a result of the request parameter's being reverted/reset in:

Magento\Customer\Model\Plugin\UpdateCustomer::beforeSave

        if (!isset($bodyParams['customer']['Id']) && $customerId) {
            if ($customerId === $customerSessionId || $customerSessionId === 0) {
                $customer = $this->getUpdatedCustomer($customerRepository->getById($customerId), $customer);
            }
        }

Release note

No response

Triage and priority

  • Severity: S0 - Affects critical data or functionality and leaves users without workaround.
  • Severity: S1 - Affects critical data or functionality and forces users to employ a workaround.
  • Severity: S2 - Affects non-critical data or functionality and forces users to employ a workaround.
  • Severity: S3 - Affects non-critical data or functionality and does not force users to employ a workaround.
  • Severity: S4 - Affects aesthetics, professional look and feel, “quality” or “usability”.
Copy link

m2-assistant bot commented Nov 15, 2023

Hi @portchris. Thank you for your report.
To speed up processing of this issue, make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, Add a comment to the issue:


Join Magento Community Engineering Slack and ask your questions in #github channel.
⚠️ According to the Magento Contribution requirements, all issues must go through the Community Contributions Triage process. Community Contributions Triage is a public meeting.
🕙 You can find the schedule on the Magento Community Calendar page.
📞 The triage of issues happens in the queue order. If you want to speed up the delivery of your contribution, join the Community Contributions Triage session to discuss the appropriate ticket.

@portchris
Copy link
Author

@magento-admin I am working on this.

@engcom-Bravo engcom-Bravo self-assigned this Nov 15, 2023
Copy link

m2-assistant bot commented Nov 15, 2023

Hi @engcom-Bravo. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: 👇

  • 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
  • 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue.
  • 3. Add Area: XXXXX label to the ticket, indicating the functional areas it may be related to.
  • 4. Verify that the issue is reproducible on 2.4-develop branch
    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!
  • 5. Add label Issue: Confirmed once verification is complete.
  • 6. Make sure that automatic system confirms that report has been added to the backlog.

@engcom-Bravo engcom-Bravo added the Reported on 2.4.6-p3 Indicates original Magento version for the Issue report. label Nov 15, 2023
@portchris
Copy link
Author

Module: Magento_Company

As this appears to be specifically related to Magento B2B companies I have created a patch within the Magento_Company module in order not to disturb the Magento_Customer module (used in other flavours of Adobe Commerce). Here is my patch

--- a/vendor/magento/module-company/Controller/Adminhtml/Customer/Index/MassAssignGroup.php
+++ b/vendor/magento/module-company/Controller/Adminhtml/Customer/Index/MassAssignGroup.php
@@ -0,0 +1,156 @@
+<?php
+
+declare(strict_types=1);
+
+namespace Magento\Company\Controller\Adminhtml\Customer\Index;
+
+use Magento\Backend\App\Action\Context;
+use Magento\Company\Api\Data\CompanyInterface;
+use Magento\Company\Api\CompanyManagementInterface;
+use Magento\Company\Api\CompanyRepositoryInterface;
+use Magento\Company\Model\SaveHandler\CustomerGroup;
+use Magento\Company\Model\Company;
+use Magento\Customer\Controller\Adminhtml\Index\MassAssignGroup as Original;
+use Magento\Eav\Model\Entity\Collection\AbstractCollection;
+use Magento\Framework\Exception\CouldNotSaveException;
+use Magento\Framework\Exception\NoSuchEntityException;
+use Magento\Framework\Exception\LocalizedException;
+use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
+use Magento\Ui\Component\MassAction\Filter;
+use Magento\Customer\Api\CustomerRepositoryInterface;
+
+class MassAssignGroup extends Original
+{
+    /**
+     * @var Company|null
+     */
+    private ?CompanyInterface $_company;
+
+    /**
+     * @var CustomerGroup
+     */
+    private CustomerGroup $_customerGroup;
+
+    /**
+     * @var CompanyRepositoryInterface
+     */
+    private CompanyRepositoryInterface $_companyRepository;
+
+    /**
+     * @var CompanyManagementInterface
+     */
+    private CompanyManagementInterface $_companyManagement;
+
+    /**
+     * @param Context $context
+     * @param Filter $filter
+     * @param CustomerGroup $customerGroup
+     * @param CollectionFactory $collectionFactory
+     * @param CompanyRepositoryInterface $companyRepository
+     * @param CompanyManagementInterface $companyManagement
+     * @param CustomerRepositoryInterface $customerRepository
+     */
+    public function __construct(
+        Context $context,
+        Filter $filter,
+        CustomerGroup $customerGroup,
+        CollectionFactory $collectionFactory,
+        CompanyRepositoryInterface $companyRepository,
+        CompanyManagementInterface $companyManagement,
+        CustomerRepositoryInterface $customerRepository
+    ) {
+        parent::__construct(
+            $context,
+            $filter,
+            $collectionFactory,
+            $customerRepository
+        );
+
+        $this->_company = null;
+        $this->_customerGroup = $customerGroup;
+        $this->_companyRepository = $companyRepository;
+        $this->_companyManagement = $companyManagement;
+    }
+
+    /**
+     * Add a warning message to the admin attempting to mass assign a customer to a group.
+     *
+     * @param AbstractCollection $collection
+     * @return \Magento\Backend\Model\View\Result\Redirect
+     */
+    protected function massAction(AbstractCollection $collection)
+    {
+        $resultRedirect = parent::massAction($collection);
+        $groupId = $this
+            ->getRequest()
+            ->getParam('group');
+
+        if ($groupId === null) {
+            return $resultRedirect;
+        }
+
+        foreach ($collection->getAllIds() as $customerId) {
+            try {
+                if (!$this->_isCompanyAdmin((int) $customerId)) {
+                    $this->messageManager->addWarningMessage(
+                        __(
+                            "Cannot assign customer %1 to the group %2 because they are not a company admin.",
+                            $customerId,
+                            $groupId
+                        )
+                    );
+
+                    continue;
+                }
+
+                $company = $companyInitial = $this->_getCompanyByCustomerId((int) $customerId);
+                $company->setCustomerGroupId($groupId);
+                $this->_customerGroup->execute($company, $companyInitial);
+                $this->_companyRepository->save($company);
+            } catch (LocalizedException | NoSuchEntityException | CouldNotSaveException $e) {
+                $this->messageManager->addErrorMessage(
+                    __(
+                        "Error attempting to assign customer %1 to group %2. %3.",
+                        $customerId,
+                        $groupId,
+                        $e->getMessage()
+                    )
+                );
+            }
+        }
+
+        return $resultRedirect;
+    }
+
+    /**
+     * Check if this customer is a company admin, else this operation is not allowed.
+     *
+     * @param int $customerId
+     * @return boolean
+     */
+    private function _isCompanyAdmin(int $customerId): bool
+    {
+        $company = $this->_getCompanyByCustomerId($customerId);
+        if ($company) {
+            $superUserId = (int) $company->getSuperUserId();
+            return $customerId === $superUserId;
+        }
+
+        return false;
+    }
+
+    /**
+     * Return cached company object if already initialised. Otherwise initialise.
+     *
+     * @param int $customerId
+     * @return Company|null
+     */
+    private function _getCompanyByCustomerId(int $customerId): ?CompanyInterface
+    {
+        if ($this->_company === null) {
+            $this->_company = $this->_companyManagement->getByCustomerId($customerId);
+        }
+
+        return $this->_company;
+    }
+}

--- a/vendor/magento/module-company/etc/adminhtml/di.xml
+++ b/vendor/magento/module-company/etc/adminhtml/di.xml
@@ -38,4 +38,8 @@
     <type name="Magento\Catalog\Model\Product\ReservedAttributeList">
         <plugin name="reservedAttributeListPlugin" type="Magento\Company\Plugin\Catalog\Model\Product\ReservedAttributeListPlugin"/>
     </type>
+    <preference
+        for="Magento\Customer\Controller\Adminhtml\Index\MassAssignGroup"
+        type="Magento\Company\Controller\Adminhtml\Customer\Index\MassAssignGroup"
+    />
 </config>

Web API

Additionally, I have a patch here that allows the request data not to be reset:

--- a/vendor/magento/module-customer/Model/Plugin/UpdateCustomer.php
+++ b/vendor/magento/module-customer/Model/Plugin/UpdateCustomer.php
@@ -59,6 +59,11 @@
         if (!isset($bodyParams['customer']['Id']) && $customerId) {
             if ($customerId === $customerSessionId || $customerSessionId === 0) {
                 $customer = $this->getUpdatedCustomer($customerRepository->getById($customerId), $customer);
+
+                /** @var \Magento\Customer\Model\Data\Customer $customer */
+                foreach ($bodyParams['customer'] as $param => $value) {
+                    $customer->setData($param, $value);
+                }
             }
         }

@engcom-Bravo
Copy link
Contributor

engcom-Bravo commented Nov 21, 2023

Hi @portchris,

Thank you for reporting and collaboration.

Verified the issue on Magento 2.4-develop instance with EE edition and the issue is not reproducible.Kindly refer the screenshots.

Screenshot 2023-11-20 at 1 25 55 PM

Customer Group field is not editable.

As per the Magento devdocs only one customer group can be assigned to company at a time we cannot change afterwards.please refer this document https://experienceleague.adobe.com/docs/commerce-admin/b2b/companies/account-company-customer-group.html?lang=en.

Screenshot 2023-11-20 at 1 23 46 PM

Thanks.

@engcom-Bravo engcom-Bravo added the Issue: needs update Additional information is require, waiting for response label Nov 21, 2023
@m2-community-project m2-community-project bot moved this from Ready for Confirmation to Needs Update in Issue Confirmation and Triage Board Nov 21, 2023
@engcom-Bravo
Copy link
Contributor

Hi @portchris,

Kindly provide latest update on this comment #38187 (comment) still you are working on this issue if you are able to reproduce the issue please elaborate the steps to reproduce.Please let us know still if you are facing any issue.

Thanks.

@portchris
Copy link
Author

Hey @engcom-Bravo

If that's the case then perhaps the Mass Action here should be better validated:
image

Because at the moment what's happening is a success message but nothing happens. It appears as a bug.

My patch (above) By the way accounts for this and throws a warning if the customer is NOT a company admin.

@engcom-Bravo
Copy link
Contributor

Hi @portchris,

Thanks for your update.

Verified the issue on Magento 2.4-develop instance and the issue is not reproducible.Kindly refer the screenshots.

Screenshot from 2024-01-15 11-26-24

Mass action is working fine after success message appears for Assign a Customer Group the selected records has been changed for appropriate Group.

Could you please check the issue in Latest Magento 2.4-develop instance and please let us know if we are missing anything.

Thanks.

@portchris
Copy link
Author

Don't forget to install B2B module:

 composer create-project --repository-url=https://repo.magento.com/ magento/project-enterprise-edition .
    composer require magento/extension-b2b smile/elasticsuite
    composer update --lock

@engcom-Bravo
Copy link
Contributor

Hi @portchris,

Thanks for your update.

We have verified the issue Magento 2.4-develop instance with Enterprise edition with b2b modules and the issue is not reproducible,Could you please check the issue in Latest 2.4-develop instance with EE edition.

It is recommended to verify the issue in Magento 2.4-develop instance and let us know if we are missing anything.

Thanks

@engcom-Bravo
Copy link
Contributor

Hi @portchris,

We have noticed that this issue has not been updated since long time.
Hence we assume that this issue is fixed now, so we are closing it. Please feel to raise a fresh ticket or reopen this ticket if you need more assistance on this.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Issue: needs update Additional information is require, waiting for response Reported on 2.4.6-p3 Indicates original Magento version for the Issue report.
Projects
None yet
Development

No branches or pull requests

2 participants