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 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 
<?php

/* --------------------------------------------------------------
   QuickEditProductPropertiesReader.inc.php 2018-01-17
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2018 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/**
 * Class QuickEditProductPropertiesReader
 *
 * @todo Improve values_price filtering. 
 * 
 * @category   System
 * @package    QuickEdit
 * @subpackage Repositories
 */
class QuickEditProductPropertiesReader implements QuickEditProductPropertiesReaderInterface
{
    /**
     * @var CI_DB_query_builder
     */
    protected $db;
    
    /**
     * @var string
     */
    protected $brutto;
    
    /**
     * @var QuickEditPropertiesOverviewColumns $quickEditPropertiesOverviewColumns
     */
    protected $quickEditPropertiesOverviewColumns;
    
    
    /**
     * QuickEditProductPropertiesReader constructor.
     *
     * @param CI_DB_query_builder                $db                                  Database query builder instance.
     * @param QuickEditPropertiesOverviewColumns $quickEditPropertiesOverviewColumns  QuickEdit properties overview
     *                                                                                columns
     */
    public function __construct(CI_DB_query_builder $db,
                                QuickEditPropertiesOverviewColumns $quickEditPropertiesOverviewColumns)
    {
        $this->db                                 = $db;
        $this->quickEditPropertiesOverviewColumns = $quickEditPropertiesOverviewColumns;
        
        if(PRICE_IS_BRUTTO === 'true')
        {
            $this->brutto = ' / (1 + (`tax_rates`.`tax_rate` / 100))';
        }
    }
    
    
    /**
     * Returns filtered product properties based on the provided filter criteria.
     *
     * @param array $productIds       Array containing the selected product IDs to be processed.
     * @param array $filterParameters Contains the filter parameters.
     *
     * @return array Returns the query result as a pure array, or an empty array when no result is produced.
     */
    public function getFilteredProductProperties(array $productIds, array $filterParameters)
    {
        $this->_join();
        $propertiesOverviewColumns = $this->_delegateFilterToColumn();
        
        foreach($filterParameters as $column => $value)
        {
            $value = preg_replace('/[^\w\s-+<>*.,"\']/', '', $value);
            
            $valueWithoutLetters = preg_replace('/\D/', '', $value);
            
            if($column === 'combiPrice' && empty($valueWithoutLetters))
            {
                return [];
            }
            
            if(is_array($value))
            {
                if($column === 'combiShippingStatusName' || $column === 'combiPriceType')
                {
                    $this->_addSqlWhereGroupCondition($propertiesOverviewColumns[$column], $value);
                }
                else
                {
                    $this->_addSqlWhereBetweenCondition($propertiesOverviewColumns[$column], $value);
                }
                
                continue;
            }
            
            if(strpos($value, '<') === 0 || strpos($value, '>') >= 1)
            {
                $this->_addSqlWhereLessThanCondition($propertiesOverviewColumns[$column], $value);
                
                continue;
            }
            
            if(strpos($value, '>') === 0 || strpos($value, '<') >= 1)
            {
                $this->_addSqlWhereMoreThanCondition($propertiesOverviewColumns[$column], $value);
                
                continue;
            }
            
            if(strpos($value, '*') !== false)
            {
                $this->_addSqlWhereLikeCondition($propertiesOverviewColumns[$column], $value);
                
                continue;
            }
            
            $this->_addSqlWhereCondition($propertiesOverviewColumns[$column], $value);
        }
        
        return $this->db->select($this->_columns())
                        ->where_in('products_properties_index.products_id', $productIds)
                        ->group_by('products_properties_index.products_properties_combis_id, products.products_id')
                        ->get('products_properties_index')
                        ->result_array();
    }
    
    
    /**
     * Returns products that are subject to the specified filter criteria.
     *
     * @param array $productIds       Array containing the selected product IDs to be processed.
     * @param array $filterParameters Contains the filter parameters.
     *
     * @return int Returns the number of product properties found.
     */
    public function getFilteredProductPropertiesCount(array $productIds, array $filterParameters)
    {
        return count($this->getFilteredProductProperties($productIds, $filterParameters));
    }
    
    
    /**
     * Sets the starting point of the pagination and the number of products.
     *
     * @param IntType|null $start  Starting point.
     * @param IntType|null $length Number of products.
     *
     * @return QuickEditProductPropertiesReaderInterface Returns same instance for chained method calls.
     */
    public function paginateProperties(IntType $start = null, IntType $length = null)
    {
        $this->db->limit($length->asInt(), $start->asInt());
        
        return $this;
    }
    
    
    /**
     * Sets the sorting order of the products
     *
     * @param StringType|null $orderBy Sorting order (ASC or DESC)
     *
     * @return QuickEditProductPropertiesReaderInterface Returns same instance for chained method calls.
     */
    public function sortProperties(StringType $orderBy = null)
    {
        $this->db->order_by($orderBy->asString());
        
        return $this;
    }
    
    
    /**
     * Returns the number of all product properties found.
     *
     * @return int Returns the record number.
     */
    public function getProductPropertiesCount()
    {
        return (int)$this->db->count_all('products_properties_combis');
    }
    
    
    /**
     * Specifies the database relationships.
     */
    protected function _join()
    {
        $this->db->join('languages', 'languages.languages_id = ' . $_SESSION['languages_id']);
        $this->db->join('products_properties_combis',
                        'products_properties_combis.products_properties_combis_id = products_properties_index.products_properties_combis_id');
        $this->db->join('products', 'products.products_id = products_properties_index.products_id');
        $this->db->join('products_description', 'products_description.products_id = products.products_id');
        $this->db->join('tax_rates', 'tax_rates.tax_class_id = products.products_tax_class_id');
        $this->db->join('zones_to_geo_zones', 'zones_to_geo_zones.zone_country_id = ' . (int)STORE_COUNTRY
                                              . ' AND tax_rates.tax_zone_id = zones_to_geo_zones.geo_zone_id');

        $this->db->where('products_description.language_id = languages.languages_id');
        $this->db->where('products_properties_index.language_id = languages.languages_id');
    }
    
    
    /**
     * Specifies the where conditions for the database query
     *
     * @param string $column Column name.
     * @param string $value  Condition value.
     */
    protected function _addSqlWhereCondition($column, $value)
    {
        if($column === 'products_properties_combis.combi_price')
        {
            $this->_addSqlWhereRoundCondition($column, $value);
            
            return;
        }
        
        $this->db->where($column, $value);
    }
    
    
    /**
     * Starts and ends a group expression with 'where' condition in conjunction with a round function.
     *
     * @param string $column Column name.
     * @param string $value  Condition value.
     */
    protected function _addSqlWhereRoundCondition($column, $value)
    {
        $this->db->group_start()->where($column . ' = ROUND(' . $value . $this->brutto . ', 4)');
        $this->db->or_where('values_price = ROUND(' . $value . ', 4)');
        $this->db->group_end();
    }
    
    
    /**
     * Starts and ends a group expression with 'where' condition.
     *
     * @param string $column Column name.
     * @param array  $value  Condition value.
     */
    protected function _addSqlWhereGroupCondition($column, array $value)
    {
        $this->db->group_start()->where($column, array_shift($value));
        
        foreach($value as $item)
        {
            $this->db->or_where($column, $item);
        }
        
        $this->db->group_end();
    }
    
    
    /**
     * Starts and ends a group expression with 'like' condition.
     *
     * @param string $column Column name.
     * @param string $value  Condition value.
     */
    protected function _addSqlWhereLikeCondition($column, $value)
    {
        $this->db->where($column . ' LIKE ', str_replace('*', '%', $value));
    }
    
    
    /**
     * Starts and ends a group expression with 'where between' condition.
     *
     * @param string $column Column name.
     * @param array  $value  Condition values.
     */
    protected function _addSqlWhereBetweenCondition($column, array $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'products_properties_combis.combi_price')
        {
            $this->db->group_start()->where($column . ' >= ROUND(' . reset($value) . $this->brutto . ', 4)');
            $this->db->where($column . ' <= ROUND(' . end($value) . $this->brutto . ', 4)');
            $this->db->where('values_price >= ROUND(' . reset($value) . ', 4)');
            $this->db->where('values_price <= ROUND(' . end($value) . ', 4)');
            $this->db->group_end();
            
            return;
        }
        
        $this->db->where($column . ' >= ' . reset($value));
        $this->db->where($column . ' <= ' . end($value));
    }
    
    
    /**
     * Starts and ends a group expression with 'less than' condition.
     *
     * @param string $column Column name.
     * @param string $value  Condition value.
     */
    protected function _addSqlWhereLessThanCondition($column, $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'products_properties_combis.combi_price')
        {
            $this->db->group_start()->where($column . ' < ROUND(' . $value . $this->brutto . ', 4)');
            $this->db->where('values_price < ROUND(' . $value . ', 4)');
            $this->db->group_end();
            
            return;
        }
        
        $this->db->where($column . ' < ', $value);
    }
    
    
    /**
     * Starts and ends a group expression with 'more than' condition.
     *
     * @param string $column Column name.
     * @param string $value  Condition value.
     */
    protected function _addSqlWhereMoreThanCondition($column, $value)
    {
        $value = str_replace(['<', '>'], '', $value);
        
        if($column === 'products_properties_combis.combi_price')
        {
            $this->db->group_start()->where($column . ' > ROUND(' . $value . $this->brutto . ', 4)');
            $this->db->where('values_price > ROUND(' . $value . ', 4)');
            $this->db->group_end();
            
            return;
        }
        
        $this->db->where($column . ' > ', $value);
    }
    
    
    /**
     * Returns the required columns for the overview of the properties.
     *
     * @return array Returns an array of the required columns for the overview of the properties.
     */
    protected function _delegateFilterToColumn()
    {
        $propertiesOverviewColumns = [];
        
        foreach($this->quickEditPropertiesOverviewColumns->serializeColumns() as $columns)
        {
            $propertiesOverviewColumns[$columns['name']] = $columns['field'];
        }
        
        return $propertiesOverviewColumns;
    }
    
    
    /**
     * Provides required columns.
     *
     * @return array Returns an array of the required columns.
     */
    protected function _columns()
    {
        $propertiesOverviewColumns = [];
        
        foreach($this->quickEditPropertiesOverviewColumns->serializeColumns() as $columns)
        {
            $propertiesOverviewColumns[] = $columns['field'];
        }
        
        return array_merge($propertiesOverviewColumns, $this->_addAdditionalColumns());
    }
    
    
    /**
     * Provides additionally required columns.
     *
     * @return array Returns an array of the additional columns.
     */
    protected function _addAdditionalColumns()
    {
        return [
            'products_description.products_name',
            'products_properties_combis.products_properties_combis_id as combi_id',
            'GROUP_CONCAT(DISTINCT products_properties_index.values_name SEPARATOR " / ") as combi_name',
            'SUM(products_properties_index.values_price) as values_price',
            'tax_rates.tax_rate',
        ];
    }
}