energine
[ class tree: energine ] [ index: energine ] [ all elements ]

Source for file ProductEditor.class.php

Documentation is available at ProductEditor.class.php

  1. <?php
  2.  
  3. /**
  4.  * Содержит класс ProductEditor
  5.  *
  6.  * @package energine
  7.  * @subpackage shop
  8.  * @author dr.Pavka
  9.  * @copyright ColoCall 2006
  10.  * @version $Id$
  11.  */
  12.  
  13. /**
  14.  * Редактор продуктов
  15.  *
  16.  * @package energine
  17.  * @subpackage shop
  18.  * @author dr.Pavka
  19.  */
  20. class ProductEditor extends Grid {
  21.     /**
  22.      * Дерево разделов
  23.      *
  24.      * @var DivisionEditor 
  25.      * @access private
  26.      */
  27.     private $divEditor;
  28.     /**
  29.      * Имя таблицы содержащей дополнительные данные(в эту таблицу будут загружаться данные из системы учета)
  30.      *
  31.      * @var string 
  32.      * @access private
  33.      */
  34.     private $externalTableName;
  35.     
  36.     private $manufacturerEditor;
  37.  
  38.     /**
  39.      * Конструктор класса
  40.      *
  41.      * @param string $name 
  42.      * @param string $module 
  43.      * @param Document $document 
  44.      * @param array $params 
  45.      * @access public
  46.      */
  47.     public function __construct($name$moduleDocument $document,  array $params null{
  48.         parent::__construct($name$module$document,  $params);
  49.         $this->setTableName('shop_products');
  50.         $this->setOrder(array('product_id' => QAL::DESC));
  51.         $this->externalTableName = 'shop_product_external_properties';
  52.     }
  53.  
  54.     /**
  55.      * Возвращает имя таблицы с дополниельными данными
  56.      *
  57.      * @return string 
  58.      * @access protected
  59.      * @final
  60.      */
  61.  
  62.     final protected function getExternalTableName({
  63.         return $this->externalTableName;
  64.     }
  65.     
  66.     /**
  67.      * Выводит дерево разделов
  68.      *
  69.      * @return void 
  70.      * @access protected
  71.      */
  72.  
  73.     protected function showTree({
  74.         $this->request->setPathOffset($this->request->getPathOffset(1);
  75.         
  76.         //$_POST['selectorID'] = Sitemap::getInstance()->getIDByURI(array('shop'));
  77.         $this->divEditor $this->document->componentManager->createComponent(
  78.             'divEditor'
  79.             'share'
  80.             'DivisionEditor'
  81.             array(
  82.                 'action' => 'selector',
  83.                 'configFilename' => 'core/modules/shop/config/ProductDivisionEditor.component.xml'
  84.             )
  85.         );
  86.         $this->divEditor->run();
  87.     }
  88.  
  89.     /**
  90.      * Для метода showTree вызывается свой билдер
  91.      *
  92.      * @return DOMNode 
  93.      * @access public
  94.      */
  95.  
  96.     public function build({
  97.         switch ($this->getAction()){
  98.             case 'showTree':
  99.                 $result $this->divEditor->build();
  100.                 break;
  101.             case 'addManufacturer':
  102.                 $result $this->manufacturerEditor->build();
  103.                 break;
  104.             default:
  105.                 $result parent::build();
  106.         }
  107.         
  108.  
  109.         return $result;
  110.     }
  111.  
  112.     /**
  113.      * Возвращает данные о значения в связанной таблицы
  114.      * Добавлена возможность вызвать окно "добавить производителя" из списка выбора
  115.      *  
  116.      * @return array 
  117.      * @access protected
  118.      */
  119.  
  120.     protected function getFKData($fkTableName$fkKeyName{
  121.         $result $this->dbh->getForeignKeyData($fkTableName$fkKeyName$this->document->getLang())
  122.         if(in_array($this->getAction()array('add''edit')) && $fkKeyName == 'producer_id'){
  123.            $addManufacturerOption  array(
  124.                array(
  125.                    $result[1=> '-1',
  126.                    $result[2=> $this->translate('TXT_ADD_MANUFACTURER'),
  127.                    'label' => $this->translate('TXT_OR')
  128.                )
  129.            )
  130.            if($result[0=== true){
  131.                $result[0$addManufacturerOption;  
  132.            }
  133.            else{
  134.                $result[0array_merge($result[0]$addManufacturerOption);    
  135.            }    
  136.         }
  137.         
  138.         return $result;
  139.     
  140.  
  141.     protected function addManufacturer(){
  142.         $this->request->setPathOffset($this->request->getPathOffset(1);
  143.         $this->manufacturerEditor 
  144.             $this->document->componentManager->createComponent(
  145.                 'manufacturerEditor'
  146.                 'shop'
  147.                 'ManufacturersEditor'
  148.                 array(
  149.                     'action'=>'add',
  150.                     'configFilename' => 'core/modules/shop/config/AddManufacturerForm.component.xml'
  151.                 ));
  152.         $this->manufacturerEditor->run();
  153.     }
  154.  
  155.     /**
  156.       * Для поля smap_id формируется Дерево разделов
  157.       * Добавляются поля product_price, curr_id
  158.       *
  159.       * @return DataDescription 
  160.       * @access protected
  161.       */
  162.  
  163.     protected function createDataDescription({
  164.         $result parent::createDataDescription();
  165.  
  166.         
  167.         if (in_array($this->getAction()array('add''edit'))) {
  168.             $this->addTranslation('FIELD_PP_NAME');
  169.             $this->addTranslation('FIELD_PPV_VALUE');
  170.             $fdPtID $result->getFieldDescriptionByName('pt_id');
  171.             $fdPtID->removeProperty('nullable')
  172.             $fdPtID->setProperty('tabName'$this->translate('TAB_PRODUCT_PARAMS'));
  173.             $result->getFieldDescriptionByName('producer_id')->removeProperty('nullable');
  174.             $smapPIDFieldDescription $result->getFieldDescriptionByName('smap_id');
  175.             $smapPIDFieldDescription->setType(FieldDescription::FIELD_TYPE_STRING);
  176.             $smapPIDFieldDescription->setMode(FieldDescription::FIELD_MODE_READ);
  177.             if ($productPriceFieldDescription $result->getFieldDescriptionByName('product_price')) {
  178.                 $productPriceFieldDescription->setProperty('nullable'false);
  179.                 $productPriceFieldDescription->setType(FieldDescription::FIELD_TYPE_FLOAT);
  180.                 $productPriceFieldDescription->setProperty('title'$this->translate('FIELD_PRODUCT_PRICE'));
  181.                 $productPriceFieldDescription->setProperty('tableName'$this->getExternalTableName());
  182.             }
  183.             if ($productCurrFieldDescription $result->getFieldDescriptionByName('curr_id')) {
  184.                 $productCurrFieldDescription->setType(FieldDescription::FIELD_TYPE_SELECT );
  185.                 $productCurrFieldDescription->setProperty('title'$this->translate('FIELD_CURR_ID'));
  186.                 $productCurrFieldDescription->setProperty('tableName'$this->getExternalTableName());
  187.                 $currencyOptions $this->dbh->selectRequest(
  188.                 'SELECT c.curr_id, curr_name FROM shop_currency c '.
  189.                 'LEFT JOIN shop_currency_translation ct ON ct.curr_id = c.curr_id '.
  190.                 'WHERE ct.lang_id = %s '.
  191.                 'ORDER by curr_order_num'Language::getInstance()->getCurrent()
  192.                 );
  193.                 $productCurrFieldDescription->loadAvailableValues($currencyOptions'curr_id''curr_name');
  194.             }
  195.  
  196.             if($productCountFieldDescription $result->getFieldDescriptionByName('product_count')){
  197.                 $productCountFieldDescription->setType(FieldDescription::FIELD_TYPE_INT);
  198.                 $productCountFieldDescription->setProperty('title'$this->translate('FIELD_PRODUCT_COUNT'));
  199.                 $productCountFieldDescription->setProperty('tableName'$this->getExternalTableName());
  200.             }
  201.         }
  202.         elseif ($this->getAction(== 'getRawData' && ($productCountFieldDescription $result->getFieldDescriptionByName('product_count'))) {
  203.             $productCountFieldDescription->setType(FieldDescription::FIELD_TYPE_INT);
  204.             $productCountFieldDescription->setProperty('title'$this->translate('FIELD_PRODUCT_COUNT'));
  205.         }
  206.         return $result;
  207.     }
  208.  
  209.     /**
  210.      * Для метода edit добавляем данные о полях из внешней таблицы
  211.      *
  212.      * @return array 
  213.      * @access protected
  214.      */
  215.  
  216.     protected function loadData({
  217.         $result parent::loadData();
  218.         if (($this->getType(== self::COMPONENT_TYPE_FORM_ALTER&& isset($result[0]['product_code'])) {
  219.             $productCode $result[0]['product_code'];
  220.             $res $this->dbh->select($this->getExternalTableName()array('product_price''product_count''curr_id')array('product_code' => $productCode));
  221.             if (is_array($res)) {
  222.                 list($res$res;
  223.             }
  224.             else {
  225.                 $res array(
  226.                 'product_price' => 0,
  227.                 'product_count' => 0,
  228.                 'curr_id' => 1
  229.                 );
  230.             }
  231.             foreach ($result as $langID => $data{
  232.                 $result[$langID]['product_price'$res['product_price'];
  233.                 $result[$langID]['product_count'$res['product_count'];
  234.                 $result[$langID]['curr_id'$res['curr_id'];
  235.             }
  236.         }
  237.         elseif ($this->getType(== self::COMPONENT_TYPE_FORM_ADD{
  238.             foreach ($result as $langID => $data{
  239.                 if (isset($result[$langID]['ps_id'])) {
  240.                     $result[$langID]['ps_id'ProductStatusEditor::getDefaultStatus();
  241.                 }
  242.                 $result[$langID]['product_count'1;
  243.             }
  244.         }
  245.         elseif ($this->getAction(== 'getRawData' && is_array($result&& $this->getDataDescription()->getFieldDescriptionByName('product_count')) {
  246.             $ids array_map(create_function('$row''return $row[\'product_id\'];')$result);
  247.             $request  'SELECT product_id, product_count FROM `shop_product_external_properties` prop LEFT JOIN shop_products p ON prop.`product_code` = p.`product_code` WHERE p.product_id IN ('.implode(','$ids).')';
  248.             $res convertDBResult($this->dbh->selectRequest($request)'product_id'true);
  249.             foreach ($result as $key => $row{
  250.                 $result[$key]['product_count'$res[$row['product_id']]['product_count'];
  251.             }
  252.         }
  253.  
  254.  
  255.         return $result;
  256.     }
  257.     /**
  258.      * Для метода редактирования изменяем данные для поля smap_id
  259.      *
  260.      * @return Builder 
  261.      * @access protected
  262.      */
  263.  
  264.     protected function prepare({
  265.         parent::prepare();
  266.         if ($this->getAction(== 'edit'{
  267.             
  268.             $field $this->getData()->getFieldByName('product_id');
  269.             $this->addAttFilesField(
  270.                 'shop_product_uploads',
  271.                 $this->dbh->selectRequest('
  272.                     SELECT files.upl_id, upl_path, upl_name
  273.                     FROM `shop_product_uploads` p2f
  274.                     LEFT JOIN `share_uploads` files ON p2f.upl_id=files.upl_id
  275.                     WHERE product_id = %s
  276.                 '$this->getData()->getFieldByName('product_id')->getRowData(0))
  277.             );
  278.             
  279.             $field $this->getData()->getFieldByName('smap_id');
  280.             $smapSegment '';
  281.             if($field->getRowData(0!== null{
  282.                 $smapSegment Sitemap::getInstance()->getURLByID($field->getRowData(0));
  283.             }
  284.             $smapName simplifyDBResult($this->dbh->select('share_sitemap_translation'array('smap_name')array('smap_id' => $field->getRowData(0)'lang_id' => $this->document->getLang()))'smap_name'true);
  285.  
  286.             for ($i 0$i count(Language::getInstance()->getLanguages())$i++{
  287.                 $field->setRowProperty($i'data_name'$smapName);
  288.                 $field->setRowProperty($i'segment'$smapSegment);
  289.             }
  290.         }
  291.         elseif($this->getAction(== 'add'){
  292.             $this->addAttFilesField('shop_product_uploads');
  293.         }
  294.         /*
  295.         if(in_array($this->getAction(), array('add', 'edit'))){
  296.             $fd = $this->getDataDescription()->getFieldDescriptionByName('producer_id');
  297.             inspect($fd->getAvailableValues());
  298.         }*/   
  299.     }
  300.  
  301.     /**
  302.      * При сохранении генерим thumbnail
  303.      *
  304.      * @return mixed 
  305.      * @access protected
  306.      */
  307.  
  308.     protected function saveData({
  309.         if(($this->getPreviousAction(== 'add'&& (!isset($_POST[$this->getTableName()]['product_segment']|| empty($_POST[$this->getTableName()]['product_segment'])) ){
  310.                $_POST[$this->getTableName()]['product_segment'Translit::transliterate($_POST[$this->getTranslationTableName()][Language::getInstance()->getDefault()]['product_name']'-'true);
  311.         }
  312.         $result parent::saveData();
  313.  
  314.         //Если пустой фильтр  - значит у нас метод вставки
  315.         $filter  $this->saver->getFilter();
  316.         if (empty($filter)) {
  317.             $filter array($this->getPK()=>$this->saver->getResult());
  318.  
  319.         }
  320.  
  321.         //Сохраняем данные в таблице дополнительных свойств
  322.             $productCode $_POST[$this->getTableName()]['product_code'];
  323.             //Удаляем все записи с таким кодом продукта
  324.             $this->dbh->modify(QAL::DELETE$this->getExternalTableName()nullarray('product_code' => $productCode));
  325.  
  326.             $price (isset($_POST[$this->getExternalTableName()]['product_price']))?$_POST[$this->getExternalTableName()]['product_price']:0;
  327.             $count (isset($_POST[$this->getExternalTableName()]['product_count']))?$_POST[$this->getExternalTableName()]['product_count']:0;
  328.             $currency (isset($_POST[$this->getExternalTableName()]['curr_id']))?$_POST[$this->getExternalTableName()]['curr_id']:0;
  329.             //Вставляем записи
  330.             $res $this->dbh->modify(QAL::INSERT $this->getExternalTableName()array('product_code' => $productCode'product_price' => $price'product_count' => $count'curr_id'=> $currency));
  331.         $productID ($this->saver->getMode(== QAL::INSERT)?$this->saver->getResult():$_POST[$this->getTableName()]['product_id'];
  332.         
  333.         if(isset($_POST['shop_product_param_values'])){
  334.             $productParams array_filter($_POST['shop_product_param_values']);
  335.             if(!empty($productParams)){
  336.                 $this->dbh->modify(
  337.                     QAL::DELETE,
  338.                     'shop_product_param_values'
  339.                     null
  340.                     array('product_id'=>$productID)
  341.                 );
  342.                 foreach($productParams as $ppID => $ppValue){
  343.                     $this->dbh->modify(
  344.                        QAL::INSERT,
  345.                        'shop_product_param_values'
  346.                        array(
  347.                            'product_id' => $productID,
  348.                            'pp_id' => $ppID,
  349.                            'pp_value' => $ppValue
  350.                        )
  351.                     );
  352.                 }    
  353.             }
  354.         }
  355.     //записываем данные в таблицу share_sitemap_uploads
  356.         if(isset($_POST['uploads']['upl_id'])){
  357.             foreach ($_POST['uploads']['upl_id'as $uplID){
  358.                 $this->dbh->modify(QAL::INSERT'shop_product_uploads'array('product_id' => $productID'upl_id' => $uplID));
  359.             }
  360.         }
  361.        
  362.         
  363.         
  364.         return $result;
  365.     }
  366.  
  367.     /**
  368.      * Выводит редактор значений парметров
  369.      *
  370.      * @return void 
  371.      * @access protected
  372.      */
  373.  
  374.     protected function loadParams({
  375.         //inspect($_POST);
  376.         $typeId = (int)$_POST['pt_id'];
  377.         $productId = (int)$_POST['product_id'];
  378.         
  379.         $data $this->dbh->selectRequest('
  380.         SELECT p.pp_id, pp_type, pp_name, pp_value FROM `shop_product_params` p
  381.             LEFT JOIN shop_product_params_translation pt On pt.pp_id = p.pp_id
  382.             LEFT JOIN shop_product_param_values pv ON pv.pp_id = p.pp_id and product_id = %s
  383.             WHERE pt_id=%s and pt.lang_id =%s
  384.         '$productId$typeIdLanguage::getInstance()->getDefault());
  385.         
  386.         $JSONResponse array('result' => true'data' => $data);
  387.         
  388.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  389.         $this->response->write(json_encode($JSONResponse));
  390.         $this->response->commit();    
  391.     }
  392. }
В создании документации нам помог: phpDocumentor