2

I am using magento B2B feature, which has company-modulea and i created a custom api to create company and company user but am unable to get a welcome when i create using the custom api.

here is following custom api code i used

namespace Custom\OverrideCompany\Model;

use Custom\OverrideCompany\Api\CompanyCustomInterface as CustomCompany;
use Magento\Company\Api\Data\CompanyInterface as CompanyInfo;
use Magento\Company\Model\Company\Save as CompanySave;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\Customer;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Company\Model\Email\Sender;

/**
 * Class that implements interface for data transfer object of company entity.
 *
 * @SuppressWarnings(PHPMD.ExcessivePublicCount)
 */
class CompanyCustom implements CustomCompany
{
    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @var CustomerInterface
     */
    private $customerInterface;

    /**
     * @var CustomerInterface
     */
    private $customerInfo;

    /**
     * @var CustomerFactory
     */
    private $customerLoad;

    /**
     * @var companyInfo
     */
    private $companyInfo;

    /**
     * @var EncryptorInterface
     */
    private $encrypt;

    /**
     * @var CompanySave
     */
    private $CompanySave;

    /**
     * @var \Magento\Company\Model\Email\Sender
     */
    private $companyEmailSender;

    /**
     * @param CustomerRepositoryInterface $customerRepository
     * @param CustomerInterface $customerInfo
     * @param CustomerFactory $customerLoad
     * @param \Magento\Framework\Encryption\EncryptorInterface $encrypt
     * @param \Magento\Company\Api\Data\CompanyInterface $companyInfo
     * @param Sender $companyEmailSender
     * @param \Magento\Company\Model\Company\Save $companySave
     */
    public function __construct(
        CustomerRepositoryInterface $customerRepository,
        CustomerInterface $customerInfo,
        Customer $customerLoad,
        EncryptorInterface $encrypt,
        CompanyInfo $companyInfo,
        Sender $companyEmailSender,
        CompanySave $companySave
    ) {
        $this->customerRepository   = $customerRepository;
        $this->customerInfo         = $customerInfo;
        $this->customerLoad         = $customerLoad;
        $this->encrypt              = $encrypt;
        $this->companyInfo          = $companyInfo;
        $this->companySave          = $companySave;
        $this->companyEmailSender   = $companyEmailSender;
    }

    /**
     * return \Custom\OverrideCompany\Api\CompanyCustomInterface[]
     */
    public function createCompany($companyDetails = null, $customerDetails = null, $customerAddress = null)
    {
        /*
         * Customer admin creation
         *
         */
        $websiteId  = 1;
        $this->customerInfo->setWebsiteId($websiteId);
        $this->customerLoad->setWebsiteId($websiteId);
        $email  = $customerDetails['email'];
        $firstName  = $customerDetails['firstname'];
        $lastName   = $customerDetails['lastname'];
        $customerData = $this->customerLoad->loadByEmail($email);
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $write = $resource->getConnection();
        $companyFlag    = 'true';
        //Checking company already exists
        $company_query = "select entity_id from company where company_email = '".$companyDetails['company_email']."'";
        $companyExist = $write->fetchOne($company_query);
        if ($companyExist) {
            $companyId = $companyExist;
            $companyFlag = 'false';
            $result_data = ["error" => "Company already existed , skiping creation"];
            echo json_encode($result_data);
            exit;
        }

        $company_name_query = 'select entity_id from company where company_name = "'.$companyDetails['company_name'].'"';
        $companyNameExist = $write->fetchOne($company_name_query);
        if ($companyNameExist) {
            $companyId  = $companyNameExist;
            $companyFlag = 'false';
            $result_data = ["error" => "Company Name already existed , skiping creation"];
            echo json_encode($result_data);
            exit;
        }
        if ($customerData->getId()) {
            $customerId = $customerData->getId();
            $result_data = ["error" => "Company admin already exists"];
            echo json_encode($result_data);
            exit; die;
        } else {
            $password   = $customerDetails['password'];
            $account_number   = $customerDetails['account_number'];
            $groupId    = 1;
            $this->customerInfo->setEmail($email);
            $this->customerInfo->setFirstname($firstName);
            $this->customerInfo->setLastname($lastName);
            $this->customerInfo->setGroupId($groupId);
            // $account_number = mt_rand(100000, 999999);
            $this->customerInfo->setCustomAttribute('account_number',$account_number);
            $this->customerInfo->setCustomAttribute('toppik_channel_attribute',$customerDetails['channel']);
            $this->customerInfo->setCustomAttribute('toppik_subchannel_attribute',$customerDetails['sub_channel']);
            $this->customerInfo->setCustomAttribute('customer_source',$customerDetails['customer_source']);
            $this->customerInfo->setCustomAttribute('toppik_customer_type',$customerDetails['customer_type']);


            $hashedPassword = $this->encrypt->getHash($password, true);
            $customerFinal = $this->customerRepository->save($this->customerInfo, $hashedPassword);
            $customerId = $customerFinal->getId();
            /*
             * Customer address creation
             *
             */
            $addresss = $objectManager->get('\Magento\Customer\Model\AddressFactory');
            $address = $addresss->create();
            $defaultBilling = 0;
            $defaultShipping = 0;
            if ($customerAddress['defaultBilling'] == "true") {
                $defaultBilling = 1;
            }
            if ($customerAddress['defaultShipping'] == "true") {
                $defaultShipping = 1;
            }
            $address->setCustomerId($customerId)
                    ->setFirstname($customerAddress['firstname'])
                    ->setLastname($customerAddress['lastname'])
                    ->setCountryId("US")
                    ->setPostcode($customerAddress['postcode'])
                    ->setCity($customerAddress['city'])
                    ->setRegionId($customerAddress['region_id'])
                    ->setTelephone($customerAddress['telephone'])
                    ->setFax($customerAddress['fax'])
                    ->setCompany($companyDetails['company_name'])
                    ->setStreet($customerAddress['street'])
                    ->setIsDefaultBilling($defaultBilling)
                    ->setIsDefaultShipping($defaultShipping)
                    ->setSaveInAddressBook('1');
            $address->save();
        }

        if ($companyFlag == 'true') {

            $companyObj     = $objectManager->create('Magento\Company\Model\Company');
            $companyObj->setCompanyName($companyDetails['company_name']);
            $companyObj->setCompanyEmail($companyDetails['company_email']);
            $companyObj->setStreet($companyDetails['street']);
            $companyObj->setCity($companyDetails['city']);
            $companyObj->setCountryId('US');
            $companyObj->setRegionId($companyDetails['region_id']);
            $companyObj->setPostcode($companyDetails['postcode']);
            $companyObj->setTelephone($companyDetails['telephone']);
            $companyObj->setSuperUserId($customerId);
            $companyObj->setSalesRepresentativeId(48);
            $companyObj->setCustomerGroupId($companyDetails['customer_group_id']);
            $companyObj->setStatus(1);
            $companyObj->save();
            $companyId  = $companyObj->getId();
            // company_advanced_customer_entity
            $insert_CACE_query = "UPDATE company_advanced_customer_entity set company_id = ".$companyId." where customer_id = ".$customerId;
            $write->query($insert_CACE_query);
            // company_credit
            $insert_CC_query = "INSERT INTO company_credit(company_id,balance,currency_code,exceed_limit) VALUES (".$companyId.",'0.0000','USD','0')";
            $write->query($insert_CC_query);
            //company_payment
            $insert_CP_query = "INSERT INTO company_payment(company_id,applicable_payment_method,available_payment_methods,use_config_settings) VALUES (".$companyId.",'0','braintree','1')";
            $write->query($insert_CP_query);
            //company_roles
            $insert_CR_query = "INSERT INTO company_roles(sort_order,role_name,company_id) VALUES ('0','Default User',".$companyId.")";
            $write->query($insert_CR_query);
            $role_id = $write->lastInsertId();
            //company_structure
            $insert_CS_query = "INSERT INTO company_structure(parent_id,entity_id,entity_type,path,position,level) VALUES ('0','".$companyId."','0','0','0','0')";
            $write->query($insert_CS_query);
            $cs_id = $write->lastInsertId();
            $update_CS_query = "UPDATE company_structure set path = '".$cs_id."' where structure_id = ".$cs_id;
            $write->query($update_CS_query);
            //company_permissions
            $permission_array   = ['Magento_Company::index' =>  'allow','Magento_Sales::all' => 'allow','Magento_Sales::place_order' => 'allow','Magento_Sales::payment_account' => 'deny','Magento_Sales::view_orders' => 'allow','Magento_Sales::view_orders_sub' => 'deny','Magento_NegotiableQuote::all' => 'allow','Magento_NegotiableQuote::view_quotes' =>   'allow','Magento_NegotiableQuote::manage' => 'allow','Magento_NegotiableQuote::checkout' => 'allow','Magento_NegotiableQuote::view_quotes_sub' => 'deny','Magento_Company::view' =>'allow','Magento_Company::view_account' => 'allow','Magento_Company::edit_account' =>    'deny','Magento_Company::view_address' => 'allow','Magento_Company::edit_address' =>'deny','Magento_Company::contacts' => 'allow','Magento_Company::payment_information' => 'allow','Magento_Company::user_management' => 'allow','Magento_Company::roles_view' => 'deny','Magento_Company::roles_edit' => 'deny','Magento_Company::users_view' => 'allow','Magento_Company::users_edit' => 'deny','Magento_Company::credit' => 'deny','Magento_Company::credit_history' => 'deny'];
            foreach ($permission_array as $perm_resource => $permission_val) {
                $insert_perm_query = "INSERT INTO company_permissions(role_id,resource_id,permission) VALUES (".$role_id.",'".$perm_resource."','".$permission_val."')";
                $write->query($insert_perm_query);
            }

        } else {

            $insert_CACE_query = "UPDATE company_advanced_customer_entity set company_id = ".$companyId." where customer_id = ".$customerId;
            $write->query($insert_CACE_query);
        }
        $this->companyEmailSender->sendCustomerCompanyAssignNotificationEmail($customerData, $companyId);
        $result_array   = ['sucess' => 'Company created successfully', 'customerId' => $customerId, 'companyId' => $companyId];
        echo json_encode($result_array);
        exit();

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.