Skip to content

Commit

Permalink
Маленький предварительный рефакторинг модуля price и перевод его на п…
Browse files Browse the repository at this point in the history
…оддержку шаблонов mustache
  • Loading branch information
SleepWalker committed Mar 24, 2013
1 parent 85db8e6 commit de4fa03
Show file tree
Hide file tree
Showing 10 changed files with 173 additions and 159 deletions.
2 changes: 1 addition & 1 deletion .initialCss/price/style.css
Expand Up @@ -14,7 +14,7 @@
}

.priceDownload a {
display:block;
display:inline-block;
line-height: 28px;
font-size: 15px;
background:url('../images/icon_excel.png') no-repeat;
Expand Down
4 changes: 2 additions & 2 deletions protected/modules/price/admin/AdminAction.php
Expand Up @@ -149,12 +149,12 @@ public function actionIndex()
. CHtml::endForm();
?>
<hr />
<form action="" method="post" style="display:inline-block;text-align:center;">
<?php
echo CHtml::beginForm('', 'post', array('style' => 'display:inline-block;text-align:center;'));
echo CHtml::submitButton('Очистить БД от всех прайсов', array('name'=>'flush'));
echo ' ' . CHtml::submitButton('Очистить ФС от всех прайсов', array('name'=>'unlink'));
echo CHtml::endForm();
?>
</form>
<p>
<ul>
<li><b>Очистить БД от всех прайсов</b> - полностью очищает базу данных от содержимого прайсов. (использовать, когда нужно обновить прайсы в базе данных)</li>
Expand Down
4 changes: 2 additions & 2 deletions protected/modules/price/components/HPriceBase.php
Expand Up @@ -436,11 +436,11 @@ protected function queryArray(array $array)
}
$connection->createCommand($catsSql)->execute();

// получаем категории
// получаем id категорий для вставки в основную таблицу прайсов
foreach(array_keys($cats) as $catId)
{
// переключаем модель на нужную нам таблицу
$allCats = PriceCat::model('price_' . $catId)->findAll();
$allCats = PriceCat::model($catId)->findAll();
foreach($allCats as $cat)
{
$catTockens['{' . $catId . $cat->name . '}'] = $cat->primaryKey;
Expand Down
91 changes: 69 additions & 22 deletions protected/modules/price/controllers/PriceController.php
Expand Up @@ -9,7 +9,7 @@
*/
class PriceController extends Controller
{
//TODO: можно сохранять прайсы в защищенной дириктории и выдавать их по экшену только необходимым людям
//TODO: нужно сохранять прайсы в защищенной дириктории и выдавать их по экшену только необходимым людям
public $layout='//layouts/column3';
/**
* @return array action filters
Expand Down Expand Up @@ -49,7 +49,7 @@ public function actionIndex()
{
$config = HPrice::getConfig();

$choseInvitation = $priceChoises[''] = 'Не важно';
$chooseInvitation = $priceChoises[''] = 'Не важно';
// меню фильтрации по файлам прайсов
foreach($config as $price)
if(isset($price['id']))
Expand All @@ -61,38 +61,85 @@ public function actionIndex()
{
if(!isset($cats[$curCat . '_id']))
{
$catsData = PriceCat::model($curCat)->findAllByAttributes(array('file_id' => (int)$_GET['Price']['file_id']));
$label = isset($config['attributeLabels'][$curCat])
? $config['attributeLabels'][$curCat]
: 'Категория';
$cats[$curCat . '_id'][''] = $choseInvitation;
if(isset($_GET['Price']['file_id']))
$catsData = PriceCat::model($curCat)->findAllByAttributes(array('file_id' => (int)$_GET['Price']['file_id']));
else
$catsData = PriceCat::model($curCat)->findAll();

$cats[$curCat . '_id'][''] = $chooseInvitation;
foreach($catsData as $cat)
$cats[$curCat . '_id'][$cat->primaryKey] = $cat->name;
}
}
}

$priceDownloadMenu = array();
// список файлов в директории
foreach( new DirectoryIterator(HPrice::getPricePath()) as $file) {
if( $file->isFile() === TRUE && substr($file->getBasename(), 0, 1) != '.')
$priceDownloadMenu[HPrice::getPriceUrl() . '/' . $file->getBasename()] = $file->getBasename();
}

$prod = new Price('search');
if($_GET['Price'])
$prod->attributes = $_GET['Price'];

$dataProvider = $prod->search();
$this->render('index', array(
'brands' => $brands,
'cats' => $cats,


$this->pushAside(array(
'block_filter',
'prod' => $prod,
'config' => $config,
'priceChoises' => $priceChoises,
'dataProvider' => $dataProvider,
'priceDownloadMenu' => $priceDownloadMenu,
'cats' => $cats,
),
array(
'title' => 'Фильтр',
'position' => 'top',
));

// колонки для таблицы
// TODO: перенести в модель всю инфу о колонках
$columns = array(
'code',
'name',
'price',
);

foreach(array_keys($cats) as $cat)
$columns[] = str_replace('_id', 'Name', $cat);


// TODO: названия колонок должны генерироваться в модели
if(is_array(($extra = $config['extraLabels'])))
foreach($extra as $attribute => $name)
$columns[] = array(
'name' => $name,
'header' => $name,
'value' => '$data->extra["' . $attribute . '"]',
);

$priceTable = $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>$columns,
'pager'=>array(
'cssFile'=>false,
'header'=>false,
'maxButtonCount' => 8,
),
'cssFile'=>false,
'summaryText' => false,
'enableHistory' => true,
), true);


$priceDownloadMenu = array();
// список прайсов
foreach( new DirectoryIterator(HPrice::getPricePath()) as $file) {
if( $file->isFile() === TRUE && substr($file->getBasename(), 0, 1) != '.')
$priceDownloadMenu[] = array(
'name' => $file->getBasename(),
'link' => HPrice::getPriceUrl() . '/' . $file->getBasename(),
);
}

$this->render('index', array(
'priceTable' => $priceTable,
'priceDownloadMenu' => array(
'elements' => $priceDownloadMenu,
),
));
}
}
20 changes: 16 additions & 4 deletions protected/modules/price/models/Price.php
Expand Up @@ -113,7 +113,6 @@ public function attributeLabels()

return array_merge(array(
'code' => 'Код',
'cat_id' => 'Категория',
'name' => 'Наименование товара',
'price' => 'Цена, грн.',
'min' => 'От',
Expand Down Expand Up @@ -188,17 +187,30 @@ public function __get($name)
{
$tableId = $matches[1];
if(!isset(self::$catNames[$tableId]))
{
// в методе {@link PriceCat::findAll()} сразу после выборки
// будет заполнен необходимый нам массив {@link Price::$catNames}
$models = PriceCat::model($tableId)->findAll();
}
PriceCat::model($tableId)->findAll();

return self::$catNames[$tableId][$this->{$tableId . '_id'}];
}
return parent::__get($name);
}

/**
* Добавляет функционал необходимый для переопределенного геттера
*
* @param mixed $att
* @access public
* @return void
*/
public function __isset($att)
{
if(preg_match('/^(\w+)Name$/', $att))
return true;

return parent::__isset($att);
}

/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
Expand Down
20 changes: 17 additions & 3 deletions protected/modules/price/models/PriceCat.php
Expand Up @@ -19,7 +19,7 @@ class PriceCat extends CActiveRecord
* @property string $tableName таблица для которой инициализируется модель по умолчанию,
* если при вызове метода {@link PriceCat::model()} не задать другую
*/
private $tableName = 'price_cat';
private $_tableName = 'price_cat';

/**
* @property array $_models используется аналогичным образом как и такая же переменная в родительском классе
Expand Down Expand Up @@ -52,7 +52,7 @@ public static function model($tableName = false, $className=__CLASS__)
else
{
$model=self::$_models[$tableName.$className]=new $className(null);
$model->tableName = $tableName;
$model->_tableName = $tableName;
$model->_md=new CActiveRecordMetaData($model);
$model->attachBehaviors($model->behaviors());
return $model;
Expand All @@ -64,7 +64,7 @@ public static function model($tableName = false, $className=__CLASS__)
*/
public function tableName()
{
return $this->tableName;
return $this->_tableName;
}

/**
Expand Down Expand Up @@ -126,6 +126,8 @@ public function attributeLabels()
public function findAll($condition='',$params=array())
{
$models = parent::findAll($condition,$params);

// кешируем названия категорий
if(!isset(Price::$catNames[$tableId]))
{
$tableId = str_replace('price_','', $this->tableName());
Expand All @@ -134,4 +136,16 @@ public function findAll($condition='',$params=array())
}
return $models;
}

/**
* Returns the meta-data for this AR
* @return CActiveRecordMetaData the meta for this AR class.
*/
public function getMetaData()
{
if($this->_md!==null)
return $this->_md;
else
return $this->_md=self::model($this->tableName())->_md;
}
}
34 changes: 34 additions & 0 deletions protected/modules/price/views/price/block_filter.php
@@ -0,0 +1,34 @@
<?php
echo '<div class="form hAsideCharFilter" id="priceFilter">';
$action = preg_replace('/\?[^\?]*$/','',$_SERVER["REQUEST_URI"]);
$form = $this->beginWidget('CActiveForm', array(
'id'=>'priceFilterForm',
'method'=>'get',
'action'=>$action,
'enableAjaxValidation'=>false,
'enableClientValidation'=>false,
));

echo '<p class="row" style="margin-top: 0;padding-top: 0;">' . $form->labelEx($prod, 'name') . $form->textField($prod, 'name') . '</p>';
// FIXME: убрано до лучших времен. нужно либо сделать настроку отображения фильтрации
// по файлам в админке, либо отказаться от этого функционала
// echo '<p class="row">' . $form->labelEx($prod, 'file_id') . $form->dropDownList($prod, 'file_id', $priceChoises) . '</p>';
foreach($cats as $columnId => $cat)
echo '<p class="row">' . $form->labelEx($prod, $columnId) . $form->dropDownList($prod, $columnId, $cat) . '</p>';

$this->widget('ext.jui.HFilterRangeSlider', array(
'model'=>$prod,
'attribute'=>'min',
'maxAttribute'=>'max',
// additional javascript options for the slider plugin
'options'=>array(
'range'=>true,
'min'=>$prod->minValue,
'max'=>$prod->maxValue,
),
));
echo '<p class="row" align="center"><br /><br />' . CHtml::submitButton('Поиск') . '</p>';

$this->endWidget();

echo '</div>';
32 changes: 32 additions & 0 deletions protected/modules/price/views/price/index.mustache
@@ -0,0 +1,32 @@
{{# hamster }}
{{# title }}Прайсы{{/ title }}
{{!$this->breadcrumbs = array($this->pageTitle);}}

<h1>{{ title }}</h1>
{{/ hamster }}

{{# priceDownloadMenu }}
<section class="priceDownload">
<a href="" id="priceDownloadLink">Скачать прайсы</a>
<ul>
{{# elements }}
<li><a href="{{ link }}">{{ name }}</a></li>
{{/ elements }}
</ul>
</section>
{{/ priceDownloadMenu }}

{{# hamster.js }}
{{! скрипт для анимации и отображения прайсов }}
$(function() {
$('#priceDownloadLink').click(function() {
$(this).next().show('normal');
$(this).remove();
return false;
});
});
{{/ hamster.js }}

{{! выводим таблицу с прайсами }}
{{{ priceTable }}}

0 comments on commit de4fa03

Please sign in to comment.