jcfilho
2/2/2018 - 3:18 PM

Creacion de stores, store views y guardado de datos de configuracion

Creacion de stores, store views y guardado de datos de configuracion

<?php

namespace Daytours4u\Configurations\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\Category as CategoryModel;
use Magento\Framework\Registry;
use Psr\Log\LoggerInterface;

use Magento\Framework\Event\ManagerInterface;
use Magento\Store\Model\GroupFactory;
use Magento\Store\Model\ResourceModel\Group;
use Magento\Store\Model\ResourceModel\Store;
use Magento\Store\Model\ResourceModel\Website;
use Magento\Store\Model\StoreFactory;
use Magento\Store\Model\WebsiteFactory;
use Magento\Config\Model\ResourceModel\Config;
use Magento\Framework\Encryption\EncryptorInterface;

class InstallData implements InstallDataInterface
{
    /** @var \Magento\Framework\Logger\Monolog */
    protected $_logger;

    /** @var CategoryFactory $categoryFactory */
    protected $_categoryFactory;

    /**
     * @var \Magento\Catalog\Model\Category
     */
    protected $_categoryModel;

    /**
     * @var \Magento\Catalog\Model\CategoryFactory
     */
    protected $_collectionFactory;

    /**
     * @var Registry
     */
    protected $_registry;
    /**
     * @var WebsiteFactory
     */
    private $websiteFactory;
    /**
     * @var Website
     */
    private $websiteResourceModel;
    /**
     * @var StoreFactory
     */
    private $storeFactory;
    /**
     * @var GroupFactory
     */
    private $groupFactory;
    /**
     * @var Group
     */
    private $groupResourceModel;
    /**
     * @var Store
     */
    private $storeResourceModel;
    /**
     * @var ManagerInterface
     */
    private $eventManager;

    /**
     * @var \Magento\Framework\Encryption\EncryptorInterface
     */
    protected $_encryptor;

    /**
     * @var \Magento\Config\Model\ResourceModel\Config
     */
    protected $_resourceConfig;

    public function __construct(
        CategoryModel $categoryModel,
        CategoryFactory $categoryFactory,
        Registry $registry,
        LoggerInterface $logger,
        WebsiteFactory $websiteFactory,
        Website $websiteResourceModel,
        Store $storeResourceModel,
        Group $groupResourceModel,
        StoreFactory $storeFactory,
        GroupFactory $groupFactory,
        ManagerInterface $eventManager,
        Config $resourceConfig,
        EncryptorInterface $encryptor
    )
    {
        $this->_logger = $logger;
        $this->_categoryModel = $categoryModel;
        $this->_categoryFactory = $categoryFactory;
        $this->_registry = $registry;
        $this->websiteFactory = $websiteFactory;
        $this->websiteResourceModel = $websiteResourceModel;
        $this->storeFactory = $storeFactory;
        $this->groupFactory = $groupFactory;
        $this->groupResourceModel = $groupResourceModel;
        $this->storeResourceModel = $storeResourceModel;
        $this->eventManager = $eventManager;
        $this->_resourceConfig = $resourceConfig;
        $this->_encryptor = $encryptor;

    }

    /**
     * Installs data for a module
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     * @return void
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $this->_registry->register("isSecureArea", true);

        $this->removeStoreViews();
        $this->removeStores();
        $this->removeCategories();

        $this->renameStoreViewByDefault();
        $this->renameStoreByDefault();
        $this->renameRootcategory();
        $this->setCurrencies();
        $this->configurePaypalAccount();
        $this->configureBaintreeAccount();
        $this->configureEbanxCountry();

        $rootCategories = [
            ['name' => 'Argentina', 'code' => 'argentina'],
            ['name' => 'Bsas', 'code' => 'bsas'],
            ['name' => 'Rdj', 'code' => 'rdj'],
            ['name' => 'Saopaulo', 'code' => 'saopaulo'],
            ['name' => 'Chile', 'code' => 'chile']
        ];

        foreach ($rootCategories as $category) {
            $this->createRootCategory($category);
        }

        $stores = [
            [
                'web_site_id' => 1,
                'name' => 'Argentina',
                'code' => 'argentina',
                'stores_view' => [
                    [
                        'code' => 'argentina_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'argentina_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'argentina_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'argentina_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ],
            [
                'web_site_id' => 1,
                'name' => 'Bsas',
                'code' => 'bsas',
                'stores_view' => [
                    [
                        'code' => 'bsas_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'bsas_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'bsas_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'bsas_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ],
            [
                'web_site_id' => 1,
                'name' => 'Rdj',
                'code' => 'rdj',
                'stores_view' => [
                    [
                        'code' => 'rdj_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'rdj_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'rdj_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'rdj_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ],
            [
                'web_site_id' => 1,
                'name' => 'Saopaulo',
                'code' => 'saopaulo',
                'stores_view' => [
                    [
                        'code' => 'saopaulo_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'saopaulo_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'saopaulo_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'saopaulo_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ],
            [
                'web_site_id' => 1,
                'name' => 'Chile',
                'code' => 'chile',
                'stores_view' => [
                    [
                        'code' => 'chile_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'chile_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'chile_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'chile_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ],
            [
                'web_site_id' => 1,
                'name' => 'Uruguay',
                'code' => 'uruguay',
                'stores_view' => [
                    [
                        'code' => 'uruguay_en',
                        'name' => 'English',
                        'default_to_store' => true,
                        'locale' => 'en_US'
                    ],
                    [
                        'code' => 'uruguay_es',
                        'name' => 'Español',
                        'default_to_store' => false,
                        'locale' => 'es_AR'
                    ],
                    [
                        'code' => 'uruguay_pt',
                        'name' => 'Portugues',
                        'default_to_store' => false,
                        'locale' => 'pt_BR'
                    ],
                    [
                        'code' => 'uruguay_fr',
                        'name' => 'Frances',
                        'default_to_store' => false,
                        'locale' => 'fr_FR'
                    ],
                ],
            ]
        ];

        foreach ($stores as $store) {
            $this->createStores($store);
        }

        $storeViewsForColombia = [
            [
                'code' => 'colombia_es',
                'name' => 'Español',
                'locale' => 'es_AR'
            ],
            [
                'code' => 'colombia_pt',
                'name' => 'Portugues',
                'locale' => 'pt_BR'
            ],
            [
                'code' => 'colombia_fr',
                'name' => 'Frances',
                'locale' => 'fr_FR'
            ],
        ];

        foreach ($storeViewsForColombia as $storeView) {
            //Store views for colombia (Colombia is store by default)
            $this->createStoreViewsForColombia($storeView);
        }

        $setup->endSetup();
    }


    /**
     * Remove categories tree
     *
     * @return void
     */
    protected function removeCategories()
    {
        $categories = $this->_categoryFactory->create()->getCollection();

        foreach ($categories as $category) {
            if ($category->getId() > 2) {
                $category->delete();
            }
        }

    }

    /**
     * Rename category default to Colombia
     */

    private function renameRootcategory(){
        $category = $this->_categoryFactory->create()->load(2);
        $category->setName('Colombia');
        $category->setPath('1/2');
        $category->setStoreId(0);
        try {
            $category->save();
        } catch (Exception $e) {
            $this->_logger->debug("-------" . $e->getMessage() . "------");
        }
    }

    /**
     * Create category root to relate with the stores.
     * @param $category_data
     */
    private function createRootCategory($category_data)
    {

        try {

            $category = $this->_categoryFactory->create();
            $category->setName($category_data['name']);
            $category->setIsActive(true);
            $category->setPath(1);
            $category->setStoreId(0);
            $category->save();
            $this->_registry->register($category_data['code'],$category->getId());

        } catch (Exception $e) {

            $this->_logger->debug("-------" . $e->getMessage() . "------");

        }

    }


    /**
     * Remove store views
     *
     * @return void
     */
    protected function removeStoreViews()
    {
        $store_views = $this->storeFactory->create()->getCollection();
        foreach ($store_views as $store_view) {
            if ($store_view->getId() > 1) {
                $store_view->delete();
            }
        }
    }
    /**
     * Remove stores
     *
     * @return void
     */
    protected function removeStores()
    {
        $stores = $this->groupFactory->create()->getCollection();
        foreach ($stores as $store) {
            if ($store->getId() > 1) {
                $store->delete();
            }
        }
    }

    /**
     * Rename storeview default to Colombia english
     */

    private function renameStoreViewByDefault(){
        $storeView = $this->storeFactory->create()->load(1);
        $storeView->setName('English');
        $storeView->setCode('colombia_en');
        $storeView->setData('is_active','1');
        try {
            $storeView->save();
        } catch (Exception $e) {
            $this->_logger->debug("-------" . $e->getMessage() . "------");
        }
    }
    /**
     * Rename store default to Colombia
     */

    private function renameStoreByDefault(){
        $store = $this->groupFactory->create()->load(1);
        $store->setName('Colombia');
        $store->setCode('colombia');
        try {
            $store->save();
        } catch (Exception $e) {
            $this->_logger->debug("-------" . $e->getMessage() . "------");
        }
    }

    private function createStores($data){
        $group = $this->groupFactory->create();
        $group->setWebsiteId($data['web_site_id']);
        $group->setName($data['name']);
        $group->setCode($data['code']);
        $group->setRootCategoryId($this->_registry->registry($data['code']));
        //$group->setDefaultStoreId(3);
        $this->groupResourceModel->save($group);

        $this->createStoreView($data);
        $this->setStoreViewByDefaultToAStore($data);
    }

    private function createStoreView($data){
        $group = $this->groupFactory->create();
        $group->load($data['code'], 'code');
        foreach ($data['stores_view'] as $storeView){

            $website = $this->websiteFactory->create()->load($data['web_site_id']);

            $store = $this->storeFactory->create();
            $store->setCode($storeView['code']);
            $store->setName($storeView['name']);
            $store->setWebsite($website);
            $store->setGroupId($group->getId());
            $store->setData('is_active','1');
            $this->storeResourceModel->save($store);
            // Trigger event to insert some data to the sales_sequence_meta table (fix bug place order in checkout)
            $this->eventManager->dispatch('store_add', ['store' => $store]);
            $this->setLocaleOptionByStoreView($storeView['code'],$storeView['locale']);
        }
    }

    private function setStoreViewByDefaultToAStore($data){
        $group = $this->groupFactory->create()->load($data['code'],'code');
        $storeViewModel = $this->groupFactory->create();
        foreach ($data['stores_view'] as $storeView){
            if($storeView['default_to_store']){
                $storeViewModel->load($storeView['code'],'code');
                $group->setDefaultStoreId($storeViewModel->getId());
                break;
            }
        }
    }

    private function createStoreViewsForColombia($storeView){
        // group id 1 = store by default
        // website id 1 = website by default
        //$group = $this->groupFactory->create()->load(1);
        //$storeViewModel = $this->groupFactory->create();
        $website = $this->websiteFactory->create()->load(1);

        $store = $this->storeFactory->create();
        $store->setCode($storeView['code']);
        $store->setName($storeView['name']);
        $store->setWebsite($website);
        $store->setData('is_active','1');
        $store->setGroupId(1);
        $this->storeResourceModel->save($store);
        $this->eventManager->dispatch('store_add', ['store' => $store]);
        $this->setLocaleOptionByStoreView($storeView['code'],$storeView['locale']);
    }

    private function setLocaleOptionByStoreView($code,$locale){
        $storeView = $this->storeFactory->create()->load($code,'code');
        $this->_resourceConfig->saveConfig('general/locale/code',$locale,'stores',$storeView->getId());
    }

    private function setCurrencies(){
        $this->_resourceConfig->saveConfig('currency/options/allow','USD,ARS,SAR,BRL,GBP,CAD,CLP,COP,EUR','default',0);
    }

    private function configurePaypalAccount(){
        $this->_resourceConfig->saveConfig('payment/paypal_express_bml/active','1','default',0);
        $this->_resourceConfig->saveConfig('paypal/wpp/api_username',$this->_encryptor->encrypt('josecarlosf-facilitator_api1.onetree.com'),'default',0);
        $this->_resourceConfig->saveConfig('paypal/wpp/api_password',$this->_encryptor->encrypt('PJ6ZRSTE5G3T9A9Q'),'default',0);
        $this->_resourceConfig->saveConfig('paypal/wpp/api_signature',$this->_encryptor->encrypt('AaDGXKRfJtkfKjNa8l02wAqao9BiAScsOOHSv8vIZWywPw1zHkwm-S6a'),'default',0);
        $this->_resourceConfig->saveConfig('paypal/wpp/sandbox_flag','1','default',0);
        $this->_resourceConfig->saveConfig('payment/paypal_express/allowspecific','1','default',0);
        $this->_resourceConfig->saveConfig('payment/paypal_express/specificcountry','AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BV,IO,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,AN,NC,NZ,NI,NE,NG,NU,NF,MP,KP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,BL,SH,KN,LC,MF,PM,VC,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UM,VI,UZ,VU,VA,VE,VN,WF,EH,YE,ZM,ZW','default',0);
        $this->_resourceConfig->saveConfig('payment/paypal_billing_agreement/allowspecific','1','default',0);
        $this->_resourceConfig->saveConfig('payment/paypal_billing_agreement/specificcountry','AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BV,IO,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,AN,NC,NZ,NI,NE,NG,NU,NF,MP,KP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,BL,SH,KN,LC,MF,PM,VC,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UM,VI,UZ,VU,VA,VE,VN,WF,EH,YE,ZM,ZW','default',0);
    }

    private function configureBaintreeAccount(){
        $this->_resourceConfig->saveConfig('payment/braintree/merchant_id','xk2sk3wxdrfqhrcj','default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/public_key',$this->_encryptor->encrypt('gpm76m33dkqkffq2'),'default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/private_key',$this->_encryptor->encrypt('b1b32a614ef053f6adfa58c141bef5f7'),'default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/merchant_account_id','xk2sk3wxdrfqhrcj','default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/environment','sandbox','default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/active','1','default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/allowspecific','1','default',0);
        $this->_resourceConfig->saveConfig('payment/braintree/specificcountry','AF,AX,AL,DZ,AS,AD,AO,AI,AQ,AG,AR,AM,AW,AU,AT,AZ,BS,BH,BD,BB,BY,BE,BZ,BJ,BM,BT,BO,BA,BW,BV,IO,VG,BN,BG,BF,BI,KH,CM,CA,CV,KY,CF,TD,CL,CN,CX,CC,CO,KM,CG,CD,CK,CR,CI,HR,CU,CY,CZ,DK,DJ,DM,DO,EC,EG,SV,GQ,ER,EE,ET,FK,FO,FJ,FI,FR,GF,PF,TF,GA,GM,GE,DE,GH,GI,GR,GL,GD,GP,GU,GT,GG,GN,GW,GY,HT,HM,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IM,IL,IT,JM,JP,JE,JO,KZ,KE,KI,KW,KG,LA,LV,LB,LS,LR,LY,LI,LT,LU,MO,MK,MG,MW,MY,MV,ML,MT,MH,MQ,MR,MU,YT,MX,FM,MD,MC,MN,ME,MS,MA,MZ,MM,NA,NR,NP,NL,AN,NC,NZ,NI,NE,NG,NU,NF,MP,KP,NO,OM,PK,PW,PS,PA,PG,PY,PE,PH,PN,PL,PT,QA,RE,RO,RU,RW,WS,SM,ST,SA,SN,RS,SC,SL,SG,SK,SI,SB,SO,ZA,GS,KR,ES,LK,BL,SH,KN,LC,MF,PM,VC,SD,SR,SJ,SZ,SE,CH,SY,TW,TJ,TZ,TH,TL,TG,TK,TO,TT,TN,TR,TM,TC,TV,UG,UA,AE,GB,US,UY,UM,VI,UZ,VU,VA,VE,VN,WF,EH,YE,ZM,ZW','default',0);

    }

    private function configureEbanxCountry(){
        /*express*/
        $this->_resourceConfig->saveConfig('payment/express/secret_key',$this->_encryptor->encrypt('test_ik_togSVzusR0aRb3y9QhKRBw'),'default',0);
        $this->_resourceConfig->saveConfig('payment/express/test_mode','1','default',0);
        $this->_resourceConfig->saveConfig('payment/express/active','0','default',0);
        $this->_resourceConfig->saveConfig('payment/express/allowspecific','1','default',0);
        $this->_resourceConfig->saveConfig('payment/express/specificcountry','BR','default',0);
        /*standard*/
        $this->_resourceConfig->saveConfig('payment/standard/secret_key',$this->_encryptor->encrypt('test_ik_togSVzusR0aRb3y9QhKRBw'),'default',0);
        $this->_resourceConfig->saveConfig('payment/standard/test_mode','1','default',0);
        $this->_resourceConfig->saveConfig('payment/standard/active','1','default',0);
        $this->_resourceConfig->saveConfig('payment/standard/allowspecific','1','default',0);
        $this->_resourceConfig->saveConfig('payment/standard/specificcountry','BR','default',0);

    }

}