public function run() { $ids = array_reverse(Yii::app()->{$this->_type}->getPositions()); $totalCount = count($ids); $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $ids); if (!empty($ids)) { $criteria->order = 'FIELD(t.id, ' . implode(',', $ids) . ')'; } $collections = Collection::model()->published()->with('series:published')->findAll(); foreach ($collections as $collectionKey => &$collection) { $seriesArr = $collection->series; foreach ($seriesArr as $seriesKey => $series) { $series->goods = Good::model()->published()->series($series->id)->findAll($criteria); if (empty($series->goods)) { unset($seriesArr[$seriesKey]); } } $collection->series = $seriesArr; if (empty($collection->series)) { unset($collections[$collectionKey]); } } $this->render($this->view, array('collections' => $collections)); }
public function loadModel($id) { if (($model = Good::model()->findByPk($id)) === null) { throw new CHttpException(404, 'Страница не найдена'); } return $model; }
/** * Show good info * @param $id good id */ public function actionView($id) { $good = Good::model()->with(array('category' => array('select' => 'id,name,alias'), 'goodAttrVals' => array('select' => 'value,attr_value_id,attr_id'), 'goodAttrVals.attrValue', 'goodAttrVals.attr' => array('select' => 'name,type,template,attr_group_id'), 'goodAttrVals.attr.attrGroup', 'ratings' => array('select' => 'id,value'), 'goodImages'))->findByPk($id, '', array('order' => 'attrGroup.pos, attr.pos')); if ($good === null) { throw new CHttpException(404, 'Запрашиваемая вами страница не найдена.'); } $this->render('good', array('good' => $good)); }
/** * Set good quantity in shopping card */ public function actionSetGoodQuantity() { if (!isset($_POST['good_id']) || !isset($_POST['quantity'])) { echo 'fail'; return; } $good = Good::model()->findByPk($_POST['good_id']); Yii::app()->shoppingCart->update($good, $_POST['quantity']); echo 'success'; }
public function getIndex() { if (Auth::user()->grade == 1) { $branch = Branch::take(10)->get(); } else { $branch = Branch::where('user_id', Auth::user()->id)->take(10)->get(); } // 提醒 // $notice = Notice::where('user_id', Auth::user()->id)->where('read', '0')->orderBy('timeline', 'desc')->take(10)->get(); return View::make('index')->with('goods', Good::orderBy('store')->take(10)->get())->with('branch', $branch)->with('notice', $notice); }
public function actionShow($alias) { $good = Good::model()->published()->with('series', 'material', 'color', 'technique', 'producer')->findByAlias($alias); if (!$good) { throw new CHttpException(404); } // Определяем следующий товар $nextProduct = $good->getNextProduct(); // Определяем предыдущий товар $prevProduct = $good->getPrevProduct(); Yii::app()->watched->put($good); $this->currentCollection = $good->series->collection; $this->render('good', array('model' => $good, 'nextProduct' => $nextProduct, 'prevProduct' => $prevProduct)); }
protected function beforeAction($action) { $actions = array('index', 'create'); if (in_array($action->id, $actions)) { $this->item_id = (int) Yii::app()->getRequest()->getParam('item_id'); if (!$this->item_id) { throw new CHttpException(400, 'Не установлен ID товара'); } if (($this->item = Good::model()->findByPk($this->item_id)) === null) { throw new CHttpException(404, 'Товар не найден'); } } return parent::beforeAction($action); }
public function actionRemove($id) { $id = (int) $_GET['id']; $model = Good::model()->findByPk($id); if ($model !== null) { Yii::app()->favorite->remove($model->getId()); } if (Yii::app()->getRequest()->getIsAjaxRequest()) { //$this->renderPartial('_favorite', $data, false, true); Yii::app()->ajax->success(); } else { $this->redirect($model->url); } }
public function run() { $ids = array_reverse(Yii::app()->{$this->_type}->getPositions()); $totalCount = count($ids); if ($this->limit > 0) { $ids = array_slice($ids, 0, $this->limit); } $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $ids); $criteria->limit = $this->limit; if (!empty($ids)) { $criteria->order = 'FIELD(t.id, ' . implode(',', $ids) . ')'; } $models = Good::model()->published()->findAll($criteria); $this->render($this->view, array('models' => $models, 'totalCount' => $totalCount)); }
public function run() { if (empty($this->model) || $this->model->related_products == '') { return; } $relatedProducts = explode(',', $this->model->related_products); array_walk($relatedProducts, function ($data) { return (int) trim($data); }); $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $relatedProducts); $criteria->order = 't.series_id ASC, t.sort ASC'; if ($this->limit > 0) { $criteria->limit = (int) $this->limit; } $models = Good::model()->published()->findAll($criteria); $this->render($this->view, array('models' => $models, 'model' => $this->model)); }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = Good::model()->findByPk((int) $id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
public function postCreate() { $branch_id = Input::get('branch_id'); $picking = Session::get('picking'); if (array_key_exists($branch_id, $picking)) { $branch_picking = $picking[$branch_id]; if (count($branch_picking['items']) == 0) { return Redirect::to('picking/add/' . $branch_id)->with('error', '出货清单为空,请添加货品清单再生成出货单!'); } else { $branch = Branch::find($branch_id); $user_id = (int) Auth::user()->id; // 发货单 // $delivery = new Delivery(); $delivery->bn = $branch_picking['order_id']; $delivery->ship_name = $branch->name; $delivery->ship_addr = $branch->address; $delivery->ship_mobile = $branch->mobile; $delivery->t_begin = $this->__time(); $delivery->branch_id = $branch_id; $delivery->user_id = $user_id; $delivery->money = Input::get('items_price'); $delivery->status = '1'; $delivery->pay_status = '0'; $delivery->warehouse_id = Input::get('warehouse_id'); $delivery->save(); $item_num = 0; // 发货单货品 // foreach ($branch_picking['items'] as $item) { $item_num += $item['num'] + $item['presentation_num']; // 统计发货数量 $good_info = Good::find($item['good_id']); $good_info->sell = $good_info->sell + ($item['num'] + $item['presentation_num']) * $good_info->unit; $good_info->store = $good_info->store - ($item['num'] + $item['presentation_num']) * $good_info->unit; $good_info->save(); $product_info = Product::find($item['id']); $product_info->sell = $product_info->sell + ($item['num'] + $item['presentation_num']) * $good_info->unit; $product_info->store = $product_info->store - ($item['num'] + $item['presentation_num']) * $good_info->unit; $product_info->save(); $delivery_item = new DeliveryItems(); $delivery_item->delivery_id = $delivery->id; $delivery_item->branch_id = $branch->id; $delivery_item->good_id = $item['good_id']; $delivery_item->product_id = $item['id']; $delivery_item->good_name = $item['name']; $delivery_item->spec_info = ''; $delivery_item->number = $item['num'] * $good_info->unit; $delivery_item->presentation = $item['presentation_num'] * $good_info->unit; $delivery_item->price = $item['price']; $delivery_item->money = $item['price'] * $item['num']; $delivery_item->life_date = $product_info->life_date; $delivery_item->warehouse_id = $product_info->warehouse_id; $delivery_item->save(); // 日志 // $this->__goodLog($item['good_id'], $item['id'], 'picking'); } // 清空出货清单 // Session::forget('picking.' . $branch_id); // 重置最后发货、回访时间 // $branch->last_visit_at = $branch->last_ship_at = $this->__time(); // 合同存量 // if ($branch->stock) { if ($branch->stock > $item_num) { $branch->stock = $branch->stock - $item_num; } else { $branch->stock = 0; } } $branch->save(); return Redirect::to('picking/view/' . $delivery->id)->with('success', '出货单生成成功!'); } } }
/** * Show all user reviews for good */ public function actionAllReviews() { if (Yii::app()->request->isAjaxRequest && isset($_POST['good_id'])) { $time_start = microtime(); if ($this->beginCache('good-reviews-all' . $_POST['good_id'], array('dependency' => array('class' => 'system.caching.dependencies.CDbCacheDependency', 'sql' => 'SELECT MAX(id) FROM review WHERE good_id=' . $_POST['good_id']), 'duration' => 3600))) { $good = Good::model()->findByPk($_POST['good_id']); foreach ($good->reviews as $review) { $this->renderPartial('review', array('review' => $review)); } $this->endCache(); } $time_end = microtime(); if (YII_DEBUG) { echo $time_end - $time_start; } $sql_stats = YII::app()->db->getStats(); if (YII_DEBUG) { echo '<div>' . $sql_stats[0] . ' запросов к БД, время выполнения запросов - ' . $sql_stats[1] . '</div>'; } } }
/** * Список программ: **/ public function getItemsList() { return CHtml::listData(Good::model()->findAll(), 'id', 'title'); }
/** * Возвращает модель по указанному идентификатору * Если модель не будет найдена - возникнет HTTP-исключение. * @param integer идентификатор нужной модели */ public function loadModel($id) { $model = Good::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, Yii::t('CatalogModule.catalog', 'Page was not found!')); } return $model; }
public function getPrevProduct($filter = array()) { // Условие выборки по порядку $criteria = new CDbCriteria(); $criteria->addCondition('t.series_id = :series_id AND t.sort <= :sort AND t.id <> :id'); $criteria->params = array(':series_id' => $this->series_id, ':sort' => $this->sort, ':id' => $this->id); $criteria->order = 't.sort DESC'; $prevProduct = Good::model()->published()->find($criteria); if ($prevProduct === null) { $criteria = new CDbCriteria(); $criteria->compare('t.series_id', $this->series_id); $criteria->order = 't.sort DESC'; $prevProduct = Good::model()->published()->find($criteria); } return $prevProduct; }
/** * Fill good rating by random data * @return void */ public function actionRandomData() { $users = array(1, 2, 3); $all_goods = Good::model()->findAll(); foreach ($all_goods as $good) { $sum = 0; $count = 0; foreach ($users as $user) { if (rand(1, 5) == 5) { continue; } $count++; $user_mark = rand(1, 5); $sum += $user_mark; $user_rating = new Rating(); $user_rating->good_id = $good->id; $user_rating->user_id = $user; $user_rating->value = $user_mark; $user_rating->save(); } if ($count != 0) { $good->rating = round($sum / $count * 100); $good->update(array('rating')); } echo $good->id . '<br>'; flush(); } }
public function actionIndex() { $dataProvider = new CActiveDataProvider(Good::model()->published(), array('criteria' => new CDbCriteria(array('limit' => self::GOOD_PER_PAGE, 'order' => 't.create_time DESC')))); $this->render('index', array('dataProvider' => $dataProvider)); }
function parseXml($xml, $dataType) { $contragentUrl = "Company"; $array = array(); switch ($dataType) { case "customerOrder": $ordersForThisDateCounter = 0; $ordersValidForThisDateCounter = 0; $ordersWithValidContragentForThisDateCounter = 0; foreach ($xml->customerOrder as $customerOrder) { $isDeleted = false; foreach ($customerOrder->children() as $child) { if ($child->getName() == "deleted") { $isDeleted = true; } } if (!$isDeleted) { $ordersForThisDateCounter++; $newOrder = new CustomerOrder($customerOrder); if ($newOrder->areAllFieldsValid()) { $ordersValidForThisDateCounter++; $filterCompanyString = urlencode("uuid=" . $newOrder->getSourceAgentUuid()); $contragentData = getXmlFromMoysklad($contragentUrl, "?filter=" . $filterCompanyString); try { $contragentXml = new SimpleXmlElement($contragentData); $address = (string) $contragentXml->company->requisite["actualAddress"]; $contragentName = (string) $contragentXml->company["name"]; if (!empty($address)) { $ordersWithValidContragentForThisDateCounter++; $newOrder->setAddress($address); $newOrder->setContragentName($contragentName); $array[$newOrder->getUuid()] = $newOrder; $GLOBALS["numberOfOrders"]++; } } catch (Exception $e) { //echo "Выброшено исключение: ?filter=".$filterCompanyString."<br>"; } } } } $GLOBALS["ordersForThisDateCounter"] = $ordersForThisDateCounter; $GLOBALS["ordersValidForThisDateCounter"] = $ordersValidForThisDateCounter; $GLOBALS["ordersWithValidContragentForThisDateCounter"] = $ordersWithValidContragentForThisDateCounter; break; case "good": foreach ($xml->good as $good) { $newGood = new Good($good); $array[$newGood->getUuid()] = $newGood; } break; case "service": foreach ($xml->service as $service) { $newServiceUuid = (string) $service->uuid; $newServiceName = (string) $service["name"]; $array[$newServiceUuid] = $newServiceName; } break; case "courier": foreach ($xml->employee as $courier) { $newCourier = new Courier($courier); if ($newCourier->areAllFieldsValid() && $newCourier->getIsCourier() && $newCourier->getIsActive()) { $array[$newCourier->getUuid()] = $newCourier; } } break; case "warehouse": foreach ($xml->warehouse as $warehouse) { $newWarehouse = new Warehouse($warehouse); $array[$newWarehouse->getUuid()] = $newWarehouse; } break; } return $array; }
?> "> <img height="16" border="0" width="16" src="/images/duru.gif" title="Каталог товаров" alt="*!*"><?php echo $model->name; ?> </a> <span style="font-size: 87%;"><?php $cat = Category::model()->findByPk($model->id); if ($cat->isLeaf()) { echo Good::model()->count('category_id=' . $cat->id); } else { $categories = $cat->descendants()->findAll(); $sum = 0; foreach ($categories as $category) { if ($category->isLeaf()) { $sum = $sum + Good::model()->count('category_id=' . $category->id); } } echo $sum; } ?> </span> <div class="subcat"> <?php if (!$cat->isLeaf()) { $categories = $cat->children()->findAll(); $i = 0; foreach ($categories as $category) { echo CHtml::link($category->name, $this->createUrl('catalog/view', array('name' => $category->alias))); $i++; if ($i > 7) {
public function postRecoverEmptyGood($goodEmptyId) { $good_empty = GoodEmpty::find($goodEmptyId); $branch = Branch::find($good_empty->branch_id); $delivery = new Delivery(); $delivery->bn = date("YmdHis", time()) . $this->random(4, 1); $delivery->ship_name = $branch->name; $delivery->ship_addr = $branch->address; $delivery->ship_mobile = $branch->mobile; $delivery->t_begin = $this->__time(); $delivery->branch_id = $branch->id; $delivery->user_id = Auth::user()->id; $delivery->money = '0'; $delivery->status = '1'; $delivery->pay_status = '0'; $delivery->warehouse_id = Input::get('warehouse_id'); $delivery->type = '1'; $delivery->save(); $good_info = Good::find($good_empty->good_id); // 计算实际兑换量 // $empty_num = floor($good_empty->empty / $good_info->unit / $good_info->empty_unit); $empty = $empty_num * $good_info->unit; $good_info->empty = $good_info->empty + $empty; $good_info->store = $good_info->store - $empty; $good_info->save(); $product_info = Product::find(Input::get('item_id')); $product_info->empty = $product_info->empty + $empty; $product_info->store = $product_info->store - $empty; $product_info->save(); $delivery_item = new DeliveryItems(); $delivery_item->delivery_id = $delivery->id; $delivery_item->branch_id = $branch->id; $delivery_item->good_id = $good_info->id; $delivery_item->product_id = $product_info->id; $delivery_item->good_name = $good_info->name; $delivery_item->spec_info = ''; $delivery_item->number = $empty; $delivery_item->presentation = 0; $delivery_item->price = 0; $delivery_item->money = 0; $delivery_item->life_date = $product_info->life_date; $delivery_item->warehouse_id = $product_info->warehouse_id; $delivery_item->save(); // 日志 // $this->__goodLog($good_info->id, $product_info->id, 'empty'); $branch->last_visit_at = $branch->last_ship_at = $this->__time(); $branch->save(); $good_empty->delivery_id = $delivery->id; $good_empty->save(); return Redirect::to('picking/view/' . $delivery->id)->with('success', '兑换成功!'); }
/** * Search goods */ public function actionSearch() { if (!isset($_POST['feature'])) { echo 'Категория пуста'; return; } //print_r($_POST); $catId = $_POST['category_id']; if (isset($_POST['brand'])) { foreach ($_POST['brand'] as $key => $value) { $brands[] = $key; } } $price = $_POST['price']; $res = array(); $first_step = true; foreach ($_POST['feature'] as $featureId => $feature) { if (!empty($feature) || $feature == '0') { $attr = Attr::model()->cache(3600)->findByPk($featureId); if ($attr->type == '2' && $feature == '2') { continue; } if ($attr->type == '3' && empty($feature['min']) && empty($feature['max'])) { continue; } $criteria = new CDbCriteria(); $criteria->compare('category_id', $catId, false); if (!empty($brands)) { $criteria->compare('brand_id', $brands, false); } if (!empty($price) && !empty($price['min'])) { $criteria->condition .= ' AND price >= ' . $price["min"]; } if (!empty($price) && !empty($price['max'])) { $criteria->condition .= ' AND price <= ' . $price["max"]; } $criteria->join = 'left join good_attr_val v ON v.good_id=t.id'; if ($attr->type == '1') { $values = array(); foreach ($feature as $key => $value) { if ($value == '1') { $values[] = $key; } } $criteria->compare('v.attr_value_id', $values); } if ($attr->type == '2') { $criteria->condition .= ' AND v.value=' . $feature . ' and v.attr_id=' . $attr->id; } if ($attr->type == '3') { if (!empty($feature['min']) && !empty($feature['max'])) { $criteria->condition .= ' AND v.value>=' . $feature['min'] . ' AND v.value<=' . $feature['max'] . ' AND v.attr_id =' . $attr->id; } elseif (!empty($feature['min']) && empty($feature['max'])) { $criteria->condition .= ' AND v.value>=' . $feature['min'] . ' AND v.attr_id =' . $attr->id; } elseif (empty($feature['min']) && !empty($feature['max'])) { $criteria->condition .= ' AND v.value<=' . $feature['max'] . ' AND v.attr_id =' . $attr->id; } } $goods = Good::model()->with(array('goodImages'))->findAll($criteria); $good_ids = array(); foreach ($goods as $good) { $good_ids[] = $good->id; } //echo 'id=' . $featureId . '<br>'; if (empty($res) && $first_step) { //print_r($good_ids);echo '<br>'; $res = $good_ids; if (empty($res) && !$first_step) { echo 'Ничего не найдено по этим критериям'; return; } $first_step = FALSE; continue; } if (empty($good_ids)) { echo 'Ничего не найдено по этим критериям'; return; } foreach ($res as $good_id) { if (!in_array($good_id, $good_ids)) { unset($res[array_search($good_id, $res)]); } } } } if ($first_step) { $criteria = new CDbCriteria(); $criteria->compare('category_id', $catId, false); if (!empty($brands)) { $criteria->compare('brand_id', $brands, false); } if (!empty($price) && !empty($price['min'])) { $criteria->condition .= ' AND price >= ' . $price["min"]; } if (!empty($price) && !empty($price['max'])) { $criteria->condition .= ' AND price <= ' . $price["max"]; } if (!empty($_POST['order'])) { $criteria->order = $_POST['order'] . ' '; } $count = Good::model()->count($criteria); $pages = new CPagination($count); $pages->pageSize = 10; $pages->setCurrentPage($_POST['page']); $pages->applyLimit($criteria); $goods = Good::model()->with(array('goodImages'))->findAll($criteria); } else { if (count($res) == 0) { echo 'Ничего не найдено по этим критериям'; return; } $new_res = array(); foreach ($res as $value) { $new_res[] = $value; } $count = count($new_res); $criteria = new CDbCriteria(); $pages = new CPagination($count); $pages->pageSize = 10; $pages->setCurrentPage($_POST['page']); $pages->applyLimit($criteria); $criteria->compare('id', $new_res); if (!empty($_POST['order'])) { $criteria->order = $_POST['order'] . ' '; } $goods = Good::model()->with(array('goodImages'))->findAll($criteria); } $this->renderPartial('search-result', array('goods' => $goods, 'pages' => $pages, 'count' => $count)); }
/** * Return 3 random goods * @return Good[] random goods */ public function similar() { $goods = Good::model()->with(array('goodImages'))->findAll(array('condition' => 'price <> 0', 'order' => 'RAND()', 'limit' => 3)); return $goods; }
function getContent($args) { global $structureMgr, $templatesMgr, $authenticationMgr; $userId = $authenticationMgr->getUserID(); $userData = $authenticationMgr->getUserData($userId, ''); $userName = $userData['FirstName'] . " " . $userData['LastName']; $this->setItemData('userData', $userData); $this->setItemData('userName', $userName); $blocks = $templatesMgr->getValidTags($templatesMgr->getTemplate(-1, GetCfg("TemplatesPath") . "/Cart/cart.xml"), array("container", "goods", "cart", "emptycart", "order", "quickorder", "login", "comment")); $sessionID = $authenticationMgr->getSessionID(); $tpl = $blocks["container"]; $goodsline = $blocks["goods"]; $qr = mysql_query("SELECT p.sID, p.accID, p.ptID, ShortTitle, salePrice, accCount, ptPercent, p.accPlantID, logotype, p.smallPicture, s.MetaDesc, s.pms_sID, pc.PicturePath FROM pm_as_parts p \n LEFT JOIN pm_structure s ON (p.sID = s.sID) \n\t\t\t\t\t\t\t LEFT JOIN pm_as_producer ap ON (ap.accPlantID = p.accPlantID)\n LEFT JOIN pm_as_cart c ON (c.accID = p.accID)\n LEFT JOIN pm_as_pricetypes pt ON (pt.ptID = p.ptID)\n LEFT JOIN pm_as_categories pc ON (s.pms_sID = pc.sID)\n WHERE c.sessionID='{$sessionID}'"); if (!$qr) { trigger_error("Error getting cart items - \n" . mysql_error(), PM_FATAL); } $goodsCount = mysql_num_rows($qr); $goods = ""; $cardSum = 0; $curSum = 0; $sum = 0; $total = 0; if (mysql_num_rows($qr) > 0) { $cat = new Catalogue(); //goods list from $qr $goodsArray = array(); while (false !== ($r = mysql_fetch_assoc($qr))) { /* if ($catItem["ptPercent"] == 0) $firstPrice = "<strong>" . round($catItem["salePrice"] - ($catItem["salePrice"] * 5 / 100)) . "</strong>"; else $firstPrice = "<strong><font class=\"".$typeClass."\">" . round($catItem["salePrice"] - ($catItem["salePrice"] * $catItem["ptPercent"] / 100)) . "</font></strong>"; */ $gl = $goodsline; $URL = $structureMgr->getPathByPageID($r['sID'], false); $isCardInCart = Cart::isItemInCart(GetCfg('Club.GoodID')); $isClubMember = isset($userData['cardID']) && $userData['cardID'] != '0' || $isCardInCart; switch ($r['ptID']) { case 1: if ($userData['cardID'] || $isCardInCart) { $curPrice = round($r["salePrice"] - $r["salePrice"] * 5 / 100); } else { $curPrice = $r['salePrice']; } $cardPrice = round($r["salePrice"] - $r["salePrice"] * 5 / 100); break; case 2: if ($userData['cardID'] || $isCardInCart) { $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); } else { $curPrice = $r['salePrice']; } $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; case 3: if ($userData['cardID'] || $isCardInCart) { $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); } else { $curPrice = $r['salePrice']; } $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; case 4: if ($userData['cardID'] || $isCardInCart) { $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); } else { $curPrice = $r['salePrice']; } $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; case 5: $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; case 6: $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; case 7: $curPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); $cardPrice = round($r["salePrice"] - $r["salePrice"] * $r["ptPercent"] / 100); break; default: $curPrice = $r['salePrice']; $cardPrice = $r['salePrice']; break; } $curPrice *= $r["accCount"]; $cardPrice *= $r["accCount"]; $price = $r['salePrice'] * $r["accCount"]; //must calc as needed $priceCells = '<td class="gray"><p> <a href="%good_link%" class="bluem" target="_blank">%good_name%</a></p></td> <td><strong>%card_price%</strong></td> <td>%cur_price%</td>'; if ($isClubMember) { $priceCells = '<td>%cur_price%</td>'; } $gl = str_replace("%good_name%", $r['ShortTitle'], $gl); $gl = str_replace("%good_link%", $URL, $gl); $gl = str_replace("%card_price%", $cardPrice . " * " . $r["accCount"], $gl); $gl = str_replace("%cur_price%", $curPrice . " * " . $r["accCount"], $gl); $gl = str_replace("%price%", $price . " * " . $r["accCount"], $gl); $gl = str_replace("%good_count%", $r['accCount'], $gl); $gl = str_replace("%goodID%", $r['accID'], $gl); $cardSum += $cardPrice; $curSum += $curPrice; $sum += $price; $total += $r['accCount']; //echo "$curSum in Cart<br>"; if (file_exists(GetCfg("ROOT") . $r["PicturePath"] . "/" . $r["sID"] . ".gif")) { $r["smallPicture"] = $r["PicturePath"] . "/" . $r["sID"] . ".gif"; } else { if ($r["logotype"] == NULL) { $r["smallPicture"] = "/products/empty.gif"; } else { $r["smallPicture"] = $r["logotype"]; } } $good = new Good(array('goodID' => $r['sID'], 'good_name' => $r['ShortTitle'], 'PicturePath' => $r['PicturePath'], 'good_link' => $URL, 'card_price' => $cardPrice, 'smallPicture' => $r["smallPicture"], 'cur_price' => $curPrice, 'price' => $price, 'good_count' => $r['accCount'])); foreach ($r as $var => $val) { $good->setItemData($var, $val); } $good->setItemData('priceClass', $this->getPriceClass($r['ptID'])); $good->setItemData('ptID', $r['ptID']); $good->setItemData('ptPercent', $r['ptPercent']); $good->setItemData('props', $props = $cat->getCatItemProperties($r['sID'], "CatItem", $structureMgr->getParentPageID($r['sID']))); $this->goods[$r['sID']] = $good; $imgRes = mysql_query("SELECT accPlantName, logotype FROM pm_as_producer WHERE accPlantID = '{$r["accPlantID"]}'"); if (mysql_num_rows($imgRes) > 0) { $imgRow = mysql_fetch_assoc($imgRes); $this->goods[$r['sID']]->setItemData('accPlantName', $imgRow['accPlantName']); $this->goods[$r['sID']]->setItemData('logotype', $imgRow['logotype']); } $goods .= $gl; } $tcart = $blocks["cart"]; } else { $tcart = $blocks["emptycart"]; } if ($total > 0) { $order = $blocks["order"]; $qorder = $blocks["quickorder"]; if ($authenticationMgr->getUserID() == 1) { $blocks["login"] = str_replace("%currentpath%", getenv("REQUEST_URI"), $blocks["login"]); $order = str_replace("%right%", $blocks["login"], $order); $order = str_replace("%left%", $qorder, $order); } else { $order = str_replace("%right%", $blocks["comment"], $order); $order = str_replace("%left%", $qorder, $order); //echo $order; } } else { $order = ""; } $ret = ''; $isCardInCart = Cart::isItemInCart(GetCfg('Club.GoodID')); $isClubMember = isset($userData['cardID']) && $userData['cardID'] != '0' || $isCardInCart; $this->setItemData('isCardInCart', $isCardInCart); $this->setItemData('isClubMember', $isClubMember); $this->setItemData('userID', $userId); $this->userData = $userData; $carName = 'марка автомобиля не определена'; if ($userId > 1 && $isClubMember && $userData['carID'] != 0) { $carRow = mysql_fetch_assoc(mysql_query("SELECT * FROM pm_as_cars WHERE carID='{$userData['carID']}'")); $carName = "ВАЗ " . $carRow['carModel'] . (isset($carRow['carName']) && $carRow['carName'] != '' ? "({$carRow['carName']})" : ''); } $this->setItemData('carName', $carName); if ($userId == 1) { $ret .= '<p><strong>Внимание!:</strong></p> <p>Для вашего удобства мы предлагаем вам:</p> <p><a href="/registration" class="levm"><img src="/images/arr_gray2.gif" width="7" height="9" border="0" align="absmiddle"/>Зарегестрироваться</a><br/> <a href="/main/club" class="levm"><img src="/images/arr_gray2.gif" width="7" height="9" border="0" align="absmiddle"/>Стать членом клуба</a></p>'; } elseif ($userId > 1 && !$isClubMember) { $ret .= '<p><strong>Внимание:</strong></p> <p>Для вашего удобства мы предлагаем вам:</p> <a href="/main/club" class="levm"><img src="/images/arr_gray2.gif" width="7" height="9" border="0" align="absmiddle"/>Стать членом клуба</a></p>'; } elseif ($userId > 1 && $isClubMember) { $carName = 'марка автомобиля не определена'; if ($userData['carID'] != 0) { $carRow = mysql_fetch_assoc(mysql_query("SELECT * FROM pm_as_cars WHERE carID='{$userData['carID']}'")); $carName = "ВАЗ " . $carRow['carModel'] . (isset($carRow['carName']) && $carRow['carName'] != '' ? "({$carRow['carName']})" : ''); } $ret .= '<p><strong>Здравствуйте!</strong></p> <p>' . $userName . '</p> <p>№ Вашей карты: ' . ($userData['cardID'] == '0' ? 'Будет присвоен после оплаты.' : $userData['cardID']) . '</p> <p>' . $carName . '</p> <p> <a href="#" class="levm"><img src="/images/arr_gray2.gif" width="7" height="9" border="0" align="absmiddle"/>Изменить анкету </a> <a href="#" class="levm"><img src="/images/arr_gray2.gif" width="7" height="9" border="0" align="absmiddle"/>Выход (log out)</a></p> '; } $club = $ret; $this->setItemData('cart', $tcart); $this->setItemData('cardsum', $cardSum); $this->setItemData('cursum', $curSum); $this->setItemData('sum', $sum); $this->setItemData('total', $total); $this->setItemData('goods', $goods); $this->setItemData('order', $order); $this->setItemData('club', $club); $dost = new Template('blockdost', $this); $this->setItemData('blockdost', $dost->getContent()); if ($userId == 1) { $header = new Template('header', 'Быстрый заказ'); $of = new Template('orderQuick'); $orderForm = $header->getContent() . $of->getContent(); } else { $header = new Template('header', 'Контактная информация'); $of = new Template('orderUser', $this->getItemData('userData')); $orderForm = $header->getContent() . $of->getContent(); } $this->setItemData('orderForm', $orderForm); $cartTpl = new Template('cart', $this); $tpl = $cartTpl->getContent(); $msg = _get("msg"); if ($msg == 1) { $msg = '<div class="podbor">Заполните пожалуйства поле "Ваше имя"</div>'; } elseif ($msg == 2) { $msg = '<div class="podbor">Заполните пожалуйства поле "Ваше имя"</div>'; } return $msg . $tpl; }
public function postCapsule($goodId) { $rules['capsule_unit'] = 'required'; $validator = Validator::make(Input::all(), $rules); if ($validator->fails()) { return Redirect::to('goods/capsule/' . $goodId)->withErrors($validator)->withInput(); } $good = Good::find($goodId); $good->capsule_unit = Input::get('capsule_unit'); $good->save(); return Redirect::to('goods')->with('success', '货品 ' . $good->name . ' 瓶盖兑换费用设置成功!'); }
/** * Отправление подтверждения пользователю и уведомления админу * @param DictionaryData $type * @return FeedbackForm $feedbackForm */ protected function _processForm($type) { if ($type->id == Feedback::TYPE_CALLBACK) { $feedbackForm = new CallbackForm('insert'); } elseif ($type->id == Feedback::TYPE_ORDER) { $feedbackForm = new OrderForm('insert'); } elseif ($type->id == Feedback::TYPE_REVIEW) { $feedbackForm = new ReviewForm('insert'); } else { $feedbackForm = new FeedbackForm('insert'); } $formName = get_class($feedbackForm); $this->performAjaxValidation($feedbackForm); if (Yii::app()->getRequest()->getIsPostRequest() && !empty($_POST[$formName])) { $feedbackForm->setAttributes($_POST[$formName]); // Проверка if ($feedbackForm->validate()) { $feedback = new Feedback(); $feedback->type_id = $type->id; $feedback->type = $type; $feedback->setAttributes($feedbackForm->getAttributes()); if ($type->id == Feedback::TYPE_ORDER && isset($_POST['productId']) && !empty($_POST['productId'])) { Yii::import("application.modules.catalog.models.Good"); $product = Good::model()->findByPk((int) $_POST['productId']); if (is_null($product)) { throw new CHttpException('404'); } $feedback->theme = 'Заявка на товар "' . $product->title . '"'; $feedback->text = '<p>Ссылка на товар: ' . CHtml::link($product->title, $product->getPermaLink()) . '</p>'; } // Сохранение if ($feedback->save()) { // Отправка уведомлений if (Yii::app()->getModule('feedback')->sendConfirmation) { $this->_feedbackConfirmationEmail($feedback); } $successMessage = $type->id == Feedback::TYPE_ORDER ? 'Ваше сообщение отправлено! Спасибо! В ближайшее время наши менеджеры свяжутся с Вами!' : 'Ваше сообщение отправлено! Спасибо!'; if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->success($successMessage); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, $successMessage); } } else { var_dump($feedback->getErrors()); exit; // Ошибка сохранения if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->failure(Yii::t('FeedbackModule.feedback', 'There is an error when trying to send message! Please try later!')); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('FeedbackModule.feedback', 'There is an error when trying to send message! Please try later!')); } } // Обновляем страницу $this->refresh(); } else { // Ошибка валидации if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->failure('Пожалуйста, проверьте правильность заполнения формы'); } } } return $feedbackForm; }