1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 
<?php
/* --------------------------------------------------------------
   CustomerGroupWriter.inc.php 2018-02-09
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2017 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/**
 * Class CustomerGroupWriter
 *
 * @category   System
 * @package    CustomerGroup
 * @subpackage Repositories
 */
class CustomerGroupWriter implements CustomerGroupWriterInterface
{
    /**
     * @var \CI_DB_query_builder
     */
    protected $queryBuilder;
    
    /**
     * @var \LanguageProvider
     */
    protected $languageProvider;
    
    
    /**
     * CustomerGroupWriter constructor.
     *
     * @param \CI_DB_query_builder $queryBuilder
     * @param \LanguageProvider    $languageProvider
     */
    public function __construct(CI_DB_query_builder $queryBuilder, LanguageProvider $languageProvider)
    {
        $this->queryBuilder     = $queryBuilder;
        $this->languageProvider = $languageProvider;
    }
    
    
    /**
     * Saves customer group entity data in database.
     *
     * @param \CustomerGroupInterface $customerGroup Customer group to be saved.
     *
     * @return $this|\CustomerGroupWriterInterface Same instance for chained method calls.
     */
    public function store(CustomerGroupInterface $customerGroup)
    {
        $lastCustomerGroupId = $this->queryBuilder->select('customers_status_id')
                                                  ->from('customers_status')
                                                  ->order_by('customers_status_id', 'DESC')
                                                  ->get()
                                                  ->row_array()['customers_status_id'];
        
        $customerGroupId = (int)$lastCustomerGroupId + 1;
        
        if(count($customerGroup->getNames()) > 0)
        {
            foreach($customerGroup->getNames() as $languageCode => $name)
            {
                $this->queryBuilder->set([
                                             'customers_status_id'                  => $customerGroupId,
                                             'language_id'                          => $this->languageProvider->getIdByCode(MainFactory::create('LanguageCode',
                                                                                                                                                new StringType($languageCode))),
                                             'customers_status_name'                => $name,
                                             'customers_status_public'              => $customerGroup->getSettings()
                                                                                                     ->isPublic(),
                                             'customers_status_min_order'           => $customerGroup->getConfigurations()
                                                                                                     ->getMinOrder(),
                                             'customers_status_max_order'           => $customerGroup->getConfigurations()
                                                                                                     ->getMaxOrder(),
                                             'customers_status_discount'            => $customerGroup->getConfigurations()
                                                                                                     ->getDiscount(),
                                             'customers_status_ot_discount_flag'    => $customerGroup->getSettings()
                                                                                                     ->isOtDiscountFlag(),
                                             'customers_status_ot_discount'         => $customerGroup->getConfigurations()
                                                                                                     ->getOtDiscount(),
                                             'customers_status_graduated_prices'    => $customerGroup->getSettings()
                                                                                                     ->isGraduatedPrices(),
                                             'customers_status_show_price'          => $customerGroup->getSettings()
                                                                                                     ->isShowPrice(),
                                             'customers_status_show_price_tax'      => $customerGroup->getSettings()
                                                                                                     ->isShowPriceTax(),
                                             'customers_status_add_tax_ot'          => $customerGroup->getSettings()
                                                                                                     ->isAddTaxOt(),
                                             'customers_status_payment_unallowed'   => implode(',',
                                                                                               $customerGroup->getConfigurations()
                                                                                                             ->getUnallowedPaymentModules()),
                                             'customers_status_shipping_unallowed'  => implode(',',
                                                                                               $customerGroup->getConfigurations()
                                                                                                             ->getUnallowedShippingModules()),
                                             'customers_status_discount_attributes' => $customerGroup->getSettings()
                                                                                                     ->isDiscountAttributes(),
                                             'customers_fsk18'                      => $customerGroup->getSettings()
                                                                                                     ->isFsk18(),
                                             'customers_fsk18_display'              => $customerGroup->getSettings()
                                                                                                     ->isFsk18Display(),
                                             'customers_status_write_reviews'       => $customerGroup->getSettings()
                                                                                                     ->isWriteReviews(),
                                             'customers_status_read_reviews'        => $customerGroup->getSettings()
                                                                                                     ->isReadReviews()
                                         ]);
                
                $this->queryBuilder->insert('customers_status');
                $this->_setDefault($customerGroup, $customerGroupId);
            }
        }
        
        $customerGroup->setId(new IntType($customerGroupId));
        $this->_createPersonalOfferTable($customerGroupId)
             ->_createGroupPermissionColumn($customerGroupId, 'categories')
             ->_createGroupPermissionColumn($customerGroupId, 'products');
        
        return $this;
    }
    
    
    /**
     * Updates customer group entity data in database.
     *
     * @param \CustomerGroupInterface $customerGroup Customer group to be  updated.
     *
     * @return $this|\CustomerGroupWriterInterface Same instance for chained method calls.
     */
    public function update(CustomerGroupInterface $customerGroup)
    {
        foreach($customerGroup->getNames() as $languageCode => $name)
        {
            $languageId = $this->languageProvider->getIdByCode(new LanguageCode(new StringType($languageCode)));
            
            $this->queryBuilder->update('customers_status', [
                'customers_status_name'                => $name,
                'customers_status_public'              => $customerGroup->getSettings()->isPublic(),
                'customers_status_min_order'           => $customerGroup->getConfigurations()->getMinOrder(),
                'customers_status_max_order'           => $customerGroup->getConfigurations()->getMaxOrder(),
                'customers_status_discount'            => $customerGroup->getConfigurations()->getDiscount(),
                'customers_status_ot_discount_flag'    => $customerGroup->getSettings()->isOtDiscountFlag(),
                'customers_status_ot_discount'         => $customerGroup->getConfigurations()->getOtDiscount(),
                'customers_status_graduated_prices'    => $customerGroup->getSettings()->isGraduatedPrices(),
                'customers_status_show_price'          => $customerGroup->getSettings()->isShowPrice(),
                'customers_status_show_price_tax'      => $customerGroup->getSettings()->isShowPriceTax(),
                'customers_status_add_tax_ot'          => $customerGroup->getSettings()->isAddTaxOt(),
                'customers_status_payment_unallowed'   => implode(',', $customerGroup->getConfigurations()
                                                                                     ->getUnallowedPaymentModules()),
                'customers_status_shipping_unallowed'  => implode(',', $customerGroup->getConfigurations()
                                                                                     ->getUnallowedShippingModules()),
                'customers_status_discount_attributes' => $customerGroup->getSettings()->isDiscountAttributes(),
                'customers_fsk18'                      => $customerGroup->getSettings()->isFsk18(),
                'customers_fsk18_display'              => $customerGroup->getSettings()->isFsk18Display(),
                'customers_status_write_reviews'       => $customerGroup->getSettings()->isWriteReviews(),
                'customers_status_read_reviews'        => $customerGroup->getSettings()->isReadReviews()
            ], ['customers_status_id' => $customerGroup->getId(), 'language_id' => $languageId]);
        }
        $this->_setDefault($customerGroup, $customerGroup->getId());
        
        return $this;
    }
    
    
    /**
     * Create base data from chosen personal offers table.
     *
     * @param \IntType $customerGroupId
     * @param \IntType $baseId
     *
     * @return \CustomerGroupWriter
     */
    public function createBase(IntType $customerGroupId, IntType $baseId)
    {
        if($customerGroupId->asInt() !== $baseId->asInt())
        {
            $this->queryBuilder->query('INSERT INTO `personal_offers_by_customers_status_' . $customerGroupId->asInt() . '` (`price_id`, `products_id`, `quantity`,`personal_offer`)
                                    SELECT `price_id`, `products_id`, `quantity`,`personal_offer` FROM `personal_offers_by_customers_status_'
                                       . $baseId->asInt() . '`');
        }
        
        return $this;
    }
    
    
    /**
     * Updates the default customer group in the configuration data table.
     *
     * @param \CustomerGroupInterface $customerGroup
     * @param                         $customerGroupId
     *
     * @return \CustomerGroupWriter
     */
    protected function _setDefault(CustomerGroupInterface $customerGroup, $customerGroupId)
    {
        if($customerGroup->isDefault())
        {
            $this->queryBuilder->update('configuration', ['configuration_value' => $customerGroupId],
                                        ['configuration_key' => 'DEFAULT_CUSTOMERS_STATUS_ID']);
        }
        
        return $this;
    }
    
    
    /**
     * Creates an personal offer table with given id as suffix.
     *
     * @param $customerGroupId
     *
     * @return $this
     */
    protected function _createPersonalOfferTable($customerGroupId)
    {
        $this->_dropPersonalOfferTableIfExists($customerGroupId)
             ->_addGroupPermissionToProducts($customerGroupId)
             ->_addGroupPermissionToCategories($customerGroupId)->queryBuilder->query('CREATE TABLE `personal_offers_by_customers_status_'
                                                                                      . $customerGroupId . '` (
                                                                                     `price_id` INT(11) NOT NULL AUTO_INCREMENT,
                                                                                     `products_id` INT(11) NOT NULL DEFAULT \'0\',
                                                                                     `quantity` DECIMAL(15,4) DEFAULT NULL,
                                                                                     `personal_offer` DECIMAL(15,4) DEFAULT NULL,
                                                                                     PRIMARY KEY (`price_id`),
                                                                                     UNIQUE KEY `unique_offer` (`products_id`,`quantity`)
                                                                                     ) ENGINE=InnoDB DEFAULT CHARSET=`utf8`');
        
        return $this;
    }
    
    
    /**
     * Drops personal offer table, if table with id exist.
     *
     * @param $customerGroupId
     *
     * @return $this
     */
    protected function _dropPersonalOfferTableIfExists($customerGroupId)
    {
        $this->queryBuilder->query('DROP TABLE IF EXISTS personal_offers_by_customers_status_' . $customerGroupId);
        
        return $this;
    }
    
    
    /**
     * Add group permission id to products table.
     *
     * @param $customerGroupId
     *
     * @return $this
     */
    protected function _addGroupPermissionToProducts($customerGroupId)
    {
        if($this->_columnNotExists('group_permission_' . $customerGroupId, 'products'))
        {
            $this->queryBuilder->query('ALTER TABLE  `products` ADD  `group_permission_' . $customerGroupId
                                       . '` TINYINT( 1 ) NOT NULL DEFAULT 0');
        }
        
        return $this;
    }
    
    
    /**
     * Add group permission id to categories table.
     *
     * @param $customerGroupId
     *
     * @return $this
     */
    protected function _addGroupPermissionToCategories($customerGroupId)
    {
        if($this->_columnNotExists('group_permission_' . $customerGroupId, 'categories'))
        {
            $this->queryBuilder->query('ALTER TABLE  `categories` ADD  `group_permission_' . $customerGroupId
                                       . '` TINYINT( 1 ) NOT NULL DEFAULT 0');
        }
        
        return $this;
    }
    
    
    /**
     * Check if given column exists in given table.
     *
     * @param $column string
     *
     * @param $table  string
     *
     * @return bool
     */
    protected function _columnNotExists($column, $table)
    {
        $tableColumns = $this->queryBuilder->query('SHOW COLUMNS IN ' . $table . ' LIKE "' . addslashes($column) . '"')
                                           ->result_array();
        
        return count($tableColumns) < 1;
    }
    
    
    /**
     * Creates an group_permission by id column in given table.
     *
     * @param $id    int
     *
     * @param $table string
     *
     * @return $this
     */
    protected function _createGroupPermissionColumn($id, $table)
    {
        if($this->_columnNotExists('group_permission_' . $id, $table))
        {
            $this->queryBuilder->query('ALTER TABLE  `' . $table . '` ADD  `group_permission_' . $id
                                       . '` TINYINT( 1 ) NOT NULL DEFAULT 0');
        }
        
        return $this;
    }
}