protected function saveUpSelling()
 {
     $value = waRequest::post('value');
     $this->type_model->updateById($this->type_id, array('upselling' => $value));
     $type_upselling_model = new shopTypeUpsellingModel();
     $type_upselling_model->deleteByField('type_id', $this->type_id);
     if ($value) {
         $rows = array();
         $data = waRequest::post('data', array());
         foreach ($data as $feature => $row) {
             if (!isset($row['feature'])) {
                 continue;
             }
             $rows[] = array('type_id' => $this->type_id, 'feature' => $feature, 'feature_id' => isset($row['feature_id']) ? $row['feature_id'] : null, 'cond' => $row['cond'], 'value' => isset($row['value']) ? is_array($row['value']) ? implode(',', $row['value']) : $row['value'] : '');
         }
         if ($rows) {
             $type_upselling_model->multipleInsert($rows);
         }
         $this->response['type_id'] = $this->type_id;
         $this->response['data'] = array('price' => array('feature' => 'price'), 'tag' => array('feature' => 'tag'), 'type_id' => array('feature' => 'type_id'));
         $type_features_model = new shopTypeFeaturesModel();
         $rows = $type_features_model->getByType($this->type_id);
         foreach ($rows as $row) {
             $this->response['data'][$row['code']] = array('feature' => $row['code'], 'feature_id' => $row['feature_id']);
         }
         $data = $type_upselling_model->getByType($this->type_id);
         foreach ($data as $row) {
             $this->response['data'][$row['feature']] = array('feature_id' => $row['feature_id'], 'feature' => $row['feature'], 'cond' => $row['cond'], 'value' => $row['value']);
         }
         $this->response['html'] = shopSettingsRecommendationsAction::getConditionHTML($data);
         $this->response['data'] = array_values($this->response['data']);
     }
 }
 public function execute()
 {
     $type_model = new shopTypeModel();
     $types = $type_model->getTypes();
     $this->response = array_values($types);
     $this->response['_element'] = 'type';
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $model = new shopTypeModel();
     $data = array();
     $data['id'] = waRequest::post('id', 0, waRequest::TYPE_INT);
     switch (waRequest::post('source', 'custom')) {
         case 'custom':
             $data['name'] = waRequest::post('name');
             $data['icon'] = waRequest::post('icon_url', false, waRequest::TYPE_STRING_TRIM);
             if (empty($data['icon'])) {
                 $data['icon'] = waRequest::post('icon', 'icon.box', waRequest::TYPE_STRING_TRIM);
             }
             if (!empty($data['id'])) {
                 $model->updateById($data['id'], $data);
             } else {
                 $data['sort'] = $model->select('MAX(sort)+1 as max_sort')->fetchField('max_sort');
                 $data['id'] = $model->insert($data);
             }
             break;
         case 'template':
             $data = $model->insertTemplate(waRequest::post('template'), true);
             break;
     }
     if ($data) {
         $data['icon_html'] = shopHelper::getIcon($data['icon'], 'icon.box');
         $data['name_html'] = '<span class="js-type-icon">' . $data['icon_html'] . '</span>
                 <span class="js-type-name">' . htmlspecialchars($data['name'], ENT_QUOTES, 'utf-8') . '</span>';
     }
     $this->response = $data;
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $types_per_page = $this->getConfig()->getOption('types_per_page');
     $values_per_feature = 7;
     $type_model = new shopTypeModel();
     $type_features_model = new shopTypeFeaturesModel();
     $feature_model = new shopFeatureModel();
     $types = $type_model->getAll($type_model->getTableId(), true);
     $type_features_model->countFeatures($types);
     $show_all_features = $feature_model->countAll() < $this->getConfig()->getOption('features_per_page');
     if ($show_all_features) {
         $feature_model = new shopFeatureModel();
         if ($features = $feature_model->getFeatures(true, null, 'id', $values_per_feature)) {
             $show_all_features = count($features);
             $type_features_model->fillTypes($features, $types);
             shopFeatureModel::appendTypeNames($features);
         }
     } else {
         $features = array();
     }
     $this->view->assign('type_templates', shopTypeModel::getTemplates());
     $this->view->assign('show_all_features', $show_all_features);
     $this->view->assign('show_all_types', count($types) - $types_per_page < 3);
     $this->view->assign('types_per_page', $types_per_page);
     $this->view->assign('values_per_feature', $values_per_feature);
     $this->view->assign('icons', (array) $this->getConfig()->getOption('type_icons'));
     $this->view->assign('product_types', $types);
     $this->view->assign('features', $features);
 }
 public function execute()
 {
     $product_id = (int) waRequest::get('id');
     $product = new shopProduct($product_id);
     $type_model = new shopTypeModel();
     $type = $type_model->getById($product['type_id']);
     if ($product['cross_selling'] === null) {
         $product['cross_selling'] = $type['cross_selling'] ? 1 : 0;
     }
     if ($product['upselling'] === null) {
         $product['upselling'] = $type['upselling'];
     }
     // if manually
     if ($product['cross_selling'] == 2 || $product['upselling'] == 2) {
         $related_model = new shopProductRelatedModel();
         $related = $related_model->getAllRelated($product_id);
     } else {
         $related = array();
     }
     if ($type['upselling']) {
         $type_upselling_model = new shopTypeUpsellingModel();
         $data = $type_upselling_model->getByType($type['id']);
         $type['upselling_html'] = shopSettingsRecommendationsAction::getConditionHTML($data);
     }
     if ($type['cross_selling'] && substr($type['cross_selling'], 0, 9) == 'category/') {
         $category_model = new shopCategoryModel();
         $type['category'] = $category_model->getById(substr($type['cross_selling'], 9));
     }
     $this->view->assign(array('type' => $type, 'product' => $product, 'related' => $related));
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $model = new shopTypeModel();
     $model->deleteById(waRequest::post('id'));
 }
 public function execute()
 {
     $id = $this->get('id', true);
     $type_model = new shopTypeModel();
     $type = $type_model->getById($id);
     if ($type) {
         $this->response = $type;
     } else {
         throw new waAPIException('invalid_param', 'Type not found', 404);
     }
 }
 public function execute()
 {
     $hide = waRequest::get('hide');
     if (strlen($hide)) {
         wa()->getUser()->setSettings('shop', 'collapse_types', intval($hide));
         exit;
     } else {
         $type_model = new shopTypeModel();
         wa()->getUser()->setSettings('shop', 'collapse_types', 0);
         $this->view->assign('types', $type_model->getTypes());
     }
 }
 public function execute()
 {
     $asm = new waAppSettingsModel();
     if (waRequest::post()) {
         $conf = waRequest::post('conf');
         if ($conf && is_array($conf)) {
             $conf['affiliate_credit_rate'] = str_replace(',', '.', (double) str_replace(',', '.', ifset($conf['affiliate_credit_rate'], '0')));
             $conf['affiliate_usage_rate'] = str_replace(',', '.', (double) str_replace(',', '.', ifset($conf['affiliate_usage_rate'], '0')));
             foreach ($conf as $k => $v) {
                 $asm->set('shop', $k, $v);
             }
         }
     }
     $enabled = shopAffiliate::isEnabled();
     $def_cur = waCurrency::getInfo(wa()->getConfig()->getCurrency());
     $tm = new shopTypeModel();
     $product_types = $tm->getAll();
     $conf = $asm->get('shop');
     if (!empty($conf['affiliate_product_types'])) {
         $conf['affiliate_product_types'] = array_fill_keys(explode(',', $conf['affiliate_product_types']), true);
     } else {
         $conf['affiliate_product_types'] = array();
     }
     $this->view->assign('conf', $conf);
     $this->view->assign('enabled', $enabled);
     $this->view->assign('product_types', $product_types);
     $this->view->assign('def_cur_sym', ifset($def_cur['sign'], wa()->getConfig()->getCurrency()));
     /**
      * Backend affiliate settings
      *
      * Plugins are expected to return one item or a list of items to to add to affiliate menu.
      * Each item is represented by an array:
      * array(
      *   'id'   => string,  // Required.
      *   'name' => string,  // Required.
      *   'url'  => string,  // Required (unless you hack into JS using 'html' parameter). Content for settings page is fetched from this URL.
      * )
      *
      * @event backend_settings_discounts
      */
     $plugins = wa()->event('backend_settings_affiliate');
     $config = wa('shop')->getConfig();
     foreach ($plugins as $k => &$p) {
         if (substr($k, -7) == '-plugin') {
             $plugin_id = substr($k, 0, -7);
             $plugin_info = $config->getPluginInfo($plugin_id);
             $p['img'] = $plugin_info['img'];
         }
     }
     $this->view->assign('plugins', $plugins);
     $this->view->assign('installer', $this->getUser()->getRights('installer', 'backend'));
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $model = new shopTypeModel();
     $id = waRequest::post('id', 0, waRequest::TYPE_INT);
     $after_id = waRequest::post('after_id', 0, waRequest::TYPE_INT);
     try {
         $model->move($id, $after_id);
     } catch (waException $e) {
         $this->setError($e->getMessage());
     }
 }
Exemple #11
0
 public function grid()
 {
     $this->menuTitle = '店铺列表';
     $page = request::getParam('page', 1);
     $pageSize = request::getParam('pagesize', 20);
     $shopParam = array('page' => $page, 'pageSize' => $pageSize, 'isCount' => true);
     $shopList = $this->shopObj->select($shopParam);
     //获取店铺类型
     $shopTypeObj = new shopTypeModel();
     $shopTypeList = $shopTypeObj->getAllShopType();
     $pageObj = new page();
     $pageStr = $pageObj->showpage($shopList['count'], $page, $pageSize);
     $data = array('shopList' => $shopList, 'shopTypeList' => $shopTypeList, 'pageStr' => $pageStr);
     $this->setView($data);
 }
 public function init()
 {
     $this->addItem('orders', _w('Can manage orders'));
     $this->addItem('settings', _w('Can manage settings'));
     $this->addItem('reports', _w('Can view reports'));
     $this->addItem('pages', _ws('Can edit pages'));
     $this->addItem('design', _ws('Can edit design'));
     $type_model = new shopTypeModel();
     $types = $type_model->getNames();
     $this->addItem('type', _w('Can manage products'), 'list', array('items' => $types, 'hint1' => 'all_checkbox'));
     /**
      * @event rights.config
      * @param waRightConfig $this Rights setup object
      * @return void
      */
     wa()->event('rights.config', $this);
 }
 public function execute()
 {
     $id = waRequest::get('id', null, waRequest::TYPE_INT);
     $service_model = new shopServiceModel();
     $service = array();
     $services = $service_model->getAll('id');
     if ($id !== 0) {
         if (!empty($services)) {
             if ($id && isset($services[$id])) {
                 $service = $services[$id];
             } else {
                 $service = current($services);
             }
         }
     }
     // blank area for adding new service
     if (!$service) {
         $services[] = $this->getEmptyService();
         $type_model = new shopTypeModel();
         $this->assign(array('services' => $services, 'types' => $type_model->getAll(), 'count' => $service_model->countAll(), 'taxes' => $this->getTaxes()));
         return;
     }
     $service_variants_model = new shopServiceVariantsModel();
     $variants = $service_variants_model->get($service['id']);
     $type_services_model = new shopTypeServicesModel();
     $types = $type_services_model->getTypes($service['id']);
     $products_count = 0;
     $selected_types = array();
     foreach ($types as $type) {
         if ($type['type_id']) {
             $selected_types[] = $type['type_id'];
         }
     }
     if (!empty($selected_types)) {
         $product_model = new shopProductModel();
         $products_count = $product_model->countByField(array('type_id' => $selected_types));
     }
     $product_services_model = new shopProductServicesModel();
     $this->assign(array('services' => $services, 'service' => $service, 'products' => $product_services_model->getProducts($service['id']), 'types' => $types, 'products_count' => $products_count, 'variants' => $variants, 'count' => $service_model->countAll(), 'taxes' => $this->getTaxes()));
 }
 public function getType()
 {
     $type_id = waRequest::post('type_id', null, waRequest::TYPE_INT);
     if (!$type_id) {
         return null;
     } else {
         $types = shopTypeModel::extractAllowed(array($type_id));
         if (!$types) {
             return null;
         } else {
             return $type_id;
         }
     }
 }
 public function execute()
 {
     if (!$this->getUser()->isAdmin('shop') && !wa()->getUser()->getRights('shop', 'type.%')) {
         throw new waRightsException('Access denied');
     }
     $this->setLayout(new shopBackendLayout());
     $this->getResponse()->setTitle(_w('Products'));
     $this->view->assign('categories', new shopCategories());
     $tag_model = new shopTagModel();
     $this->view->assign('cloud', $tag_model->getCloud());
     $set_model = new shopSetModel();
     $this->view->assign('sets', $set_model->getAll());
     $collapse_types = wa()->getUser()->getSettings('shop', 'collapse_types');
     if (empty($collapse_types)) {
         $type_model = new shopTypeModel();
         $this->view->assign('types', $type_model->getTypes());
     } else {
         $this->view->assign('types', false);
     }
     $product_model = new shopProductModel();
     $this->view->assign('count_all', $product_model->countAll());
     $review_model = new shopProductReviewsModel();
     $this->view->assign('count_reviews', array('all' => $review_model->count(null, false), 'new' => $review_model->countNew(true)));
     $product_services = new shopServiceModel();
     $this->view->assign('count_services', $product_services->countAll());
     $config = $this->getConfig();
     $this->view->assign('default_view', $config->getOption('products_default_view'));
     /*
      * @event backend_products
      * @return array[string]array $return[%plugin_id%] array of html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar_top_li'] html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar_section'] html output
      */
     $this->view->assign('backend_products', wa()->event('backend_products'));
     $this->view->assign('sidebar_width', $config->getSidebarWidth());
     $this->view->assign('lang', substr(wa()->getLocale(), 0, 2));
 }
 public function execute()
 {
     $direction = waRequest::request('direction', 'import') == 'export' ? 'export' : 'import';
     $profile_helper = new shopImportexportHelper('csv:product:' . $direction);
     $this->view->assign('profiles', $profile_helper->getList());
     $profile = $profile_helper->getConfig();
     if ($direction == 'export') {
         //export section TODO
         $profile['config'] += array('encoding' => 'UTF-8', 'images' => true, 'features' => true, 'domain' => null, 'delimiter' => ';', 'hash' => '');
         $info = array();
         if (!empty($profile['id'])) {
             $path = wa()->getTempPath('csv/download/' . $profile['id']);
             $files = waFiles::listdir($path);
             foreach ($files as $file) {
                 $file_path = $path . '/' . $file;
                 $info[] = array('name' => $file, 'mtime' => filemtime($file_path), 'size' => filesize($file_path));
             }
             usort($info, create_function('$a, $b', 'return (max(-1, min(1, $a["mtime"] - $b["mtime"])));'));
         }
         $this->view->assign('info', array_slice($info, -5, 5, true));
         $set_model = new shopSetModel();
         $this->view->assign('sets', $set_model->getAll());
         $routing = wa()->getRouting();
         $settlements = array();
         $current_domain = null;
         $domain_routes = $routing->getByApp('shop');
         foreach ($domain_routes as $domain => $routes) {
             foreach ($routes as $route) {
                 $settlement = $domain . '/' . $route['url'];
                 if ($current_domain === null) {
                     $current_domain = $settlement;
                 } elseif ($settlement == $profile['config']['domain']) {
                     $current_domain = $settlement;
                 }
                 $settlements[] = $settlement;
             }
         }
         $this->view->assign('current_domain', $current_domain);
         $this->view->assign('settlements', $settlements);
     } else {
         $profile['config'] += array('encoding' => 'UTF-8', 'delimiter' => ';', 'map' => array());
         $base_path = wa()->getConfig()->getPath('root');
         $app_path = array('shop' => wa()->getDataPath(null, false, 'shop'), 'site' => wa()->getDataPath(null, true, 'site'));
         foreach ($app_path as &$path) {
             $path = preg_replace('@^([\\\\/])@', '', str_replace($base_path, '', $path . '/'));
         }
         unset($path);
         $this->view->assign('upload_path', waSystem::getSetting('csv.upload_path', 'path/to/folder/with/source/images/'));
         $this->view->assign('upload_app', waSystem::getSetting('csv.upload_app', 'shop'));
         $this->view->assign('app_path', $app_path);
     }
     $this->view->assign('profile', $profile);
     $type_model = new shopTypeModel();
     $this->view->assign('types', $type_model->getTypes());
     $encoding = array_diff(mb_list_encodings(), array('pass', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit', 'auto'));
     $popular = array_intersect(array('UTF-8', 'Windows-1251', 'ISO-8859-1'), $encoding);
     asort($encoding);
     $encoding = array_unique(array_merge($popular, $encoding));
     $this->view->assign('encoding', $encoding);
     $plugins = wa()->getConfig()->getPlugins();
     $this->view->assign('direction', $direction);
     $this->view->assign('plugin', ifempty($plugins['csvproducts'], array()));
 }
 private function findType(&$data)
 {
     static $types = array();
     /**
      * @var shopTypeModel $model
      */
     static $model;
     if (!empty($data['type_name'])) {
         $type = mb_strtolower(self::flatData($data['type_name']));
         if (!isset($types[$type])) {
             if (!$model) {
                 $model = new shopTypeModel();
             }
             if ($type_row = $model->getByName($type)) {
                 $types[$type] = $type_row['id'];
             } else {
                 if (!$this->data['rights']) {
                     $types[$type] = $data['type_id'] = false;
                 } else {
                     $types[$type] = $model->insert(array('name' => $data['type_name']));
                     if (empty($this->data['types'])) {
                         $this->data['types'] = array();
                     }
                     $this->data['types'][] = intval($types[$type]);
                 }
             }
         }
         $data['type_id'] = $types[$type];
     } else {
         $data['type_id'] = ifempty($data['type_id'], $this->data['type_id']);
     }
     if (isset($data['type_name'])) {
         unset($data['type_name']);
     }
     /* check rights per product type */
     return in_array($data['type_id'], $this->data['types']);
 }
Exemple #18
0
 /**
  * @return array
  */
 public static function getTemplates()
 {
     static $types = null;
     if ($types === null) {
         $types = array();
         $path = wa('shop')->getConfig()->getConfigPath('data/welcome/', false);
         if (file_exists($path)) {
             $files = waFiles::listdir($path, false);
             foreach ($files as $file) {
                 if (preg_match('/^type_([a-z]\\w+)\\.php$/', $file, $matches)) {
                     $types[$matches[1]] = (include $path . $file);
                 }
             }
         }
         $locale_path = $path . 'locale/' . wa()->getUser()->getLocale() . '.php';
         if (file_exists($locale_path)) {
             self::$translate = (include $locale_path);
             if (!is_array(self::$translate)) {
                 self::$translate = array();
             }
         }
         if (!empty($types)) {
             foreach ($types as $id => &$type) {
                 $name = ifempty($type['name'], $id);
                 $type['name'] = ifempty(self::$translate[$name], $name);
                 $type += array('icon' => '', 'description' => '');
             }
         }
     }
     return $types;
 }
 public function execute()
 {
     if ($id = waRequest::get('id', 0, waRequest::TYPE_INT)) {
         #load product
         $this->view->assign('product', $product = new shopProduct($id));
         #load product types
         $type_model = new shopTypeModel();
         $this->view->assign('product_types', $product_types = $type_model->getAll($type_model->getTableId(), true));
         if ($param = waRequest::request('param', array(), waRequest::TYPE_ARRAY_INT)) {
             $type_id = reset($param);
             if (!isset($product_types[$type_id])) {
                 $type_id = $product->type_id;
             }
         } else {
             $type_id = $product->type_id;
         }
         $this->view->assign('type_id', $type_id);
         #load feature's values
         $model = new shopFeatureModel();
         $changed_features = array();
         if ($data = waRequest::post('product')) {
             $changed_features = empty($data['features']) || !is_array($data['features']) ? array() : $data['features'];
             foreach ($changed_features as $code => $value) {
                 if (isset($product->features[$code])) {
                     if (is_array($value)) {
                         $intersect = array_unique(array_merge($value, (array) $product->features[$code]));
                         if (count($value) == count($intersect)) {
                             unset($changed_features[$code]);
                         }
                     } elseif ($value === $product->features[$code]) {
                         unset($changed_features[$code]);
                     }
                 }
             }
         }
         #load changed feature's values
         $this->view->assign('changed_features', $changed_features);
         $codes = array_keys($product->features);
         foreach ($changed_features as $code => $value) {
             if ($value !== '') {
                 $codes[] = $code;
             }
         }
         $codes = array_unique($codes);
         $features = $model->getByType($type_id, 'code');
         foreach ($features as $code => &$feature) {
             $feature['internal'] = true;
             $key = array_search($code, $codes);
             if ($key !== false) {
                 unset($codes[$key]);
             }
         }
         unset($feature);
         if ($codes) {
             $features += $model->getByField('code', $codes, 'code');
         }
         foreach ($features as $code => &$feature) {
             $feature['feature_id'] = intval($feature['id']);
         }
         unset($feature);
         $features = $model->getValues($features);
         $this->view->assign('features', $features);
     }
 }
Exemple #20
0
<?php

wa('shop');
$type_model = new shopTypeModel();
$types = $type_model->select('id,name')->fetchAll('id', true);
$currencies = wa('shop')->getConfig()->getCurrencies();
foreach ($currencies as &$c) {
    $c = $c['title'];
}
$payment_items = $shipping_items = array();
foreach (shopHelper::getPaymentMethods() as $p) {
    $payment_items[$p['id']] = $p['name'];
}
foreach (shopHelper::getShippingMethods() as $s) {
    $shipping_items[$s['id']] = $s['name'];
}
$stock_model = new shopStockModel();
$stocks = $stock_model->select('id,name')->order('sort')->fetchAll('id', true);
return array('params' => array('title' => array('name' => _w('Homepage title <title>'), 'type' => 'input'), 'meta_keywords' => array('name' => _w('Homepage META Keywords'), 'type' => 'input'), 'meta_description' => array('name' => _w('Homepage META Description'), 'type' => 'textarea'), 'url_type' => array('name' => _w('URLs'), 'type' => 'radio_select', 'items' => array(2 => array('name' => _w('Natural'), 'description' => _w('<br>Product URLs: /<strong>category-name/subcategory-name/product-name/</strong><br>Category URLs: /<strong>category-name/subcategory-name/</strong>')), 0 => array('name' => _w('Mixed'), 'description' => _w('<br>Product URLs: /<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/subcategory-name/subcategory-name/...</strong>')), 1 => array('name' => _w('Plain') . ' (WebAsyst Shop-Script)', 'description' => _w('<br>Product URLs: /product/<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/</strong>')))), 'type_id' => array('name' => _w('Published products'), 'type' => 'radio_checkbox', 'items' => array(0 => array('name' => _w('All product types'), 'description' => ''), array('name' => _w('Selected only'), 'description' => '', 'items' => $types))), 'payment_id' => array('name' => _w('Payment options'), 'type' => 'radio_checkbox', 'items' => array(0 => array('name' => _w('All available payment options'), 'description' => ''), array('name' => _w('Selected only'), 'description' => '', 'items' => $payment_items))), 'shipping_id' => array('name' => _w('Shipping options'), 'type' => 'radio_checkbox', 'items' => array(0 => array('name' => _w('All available shipping options'), 'description' => ''), array('name' => _w('Selected only'), 'description' => '', 'items' => $shipping_items))), 'currency' => array('name' => _w('Default currency'), 'type' => 'select', 'items' => $currencies), 'stock_id' => array('name' => _w('Default stock'), 'description' => _w('Select primary stock to which this storefront is associated with. When you process orders from placed via this storefront, selected stock will be automatically offered for product stock update.'), 'type' => 'select', 'items' => $stocks), 'drop_out_of_stock' => array('name' => _w('Force drop out-of-stock products to the bottom of all lists'), 'description' => _w('When enabled, out-of-stock products will be automatically dropped to the bottom of every product list on this storefront, e.g. in product search results, category product filtering, and more.'), 'type' => 'checkbox'), 'ssl' => array('name' => _w('Use HTTPS for checkout and personal accounts'), 'description' => _w('Automatically redirect to secure https:// mode for checkout (/checkout/) and personal account (/my/) pages of your online storefront. Make sure you have valid SSL certificate installed for this domain name before enabling this option.'), 'type' => 'checkbox')), 'vars' => array('category.html' => array('$category.id' => '', '$category.name' => '', '$category.parent_id' => '', '$category.description' => ''), 'index.html' => array('$content' => _w('Core content loaded according to the requested resource: product, category, search results, static page, etc.')), 'product.html' => array('$product.id' => _w('Product id. Other elements of <em>$product</em> available in this template are listed below'), '$product.name' => _w('Product name'), '$product.summary' => _w('Product summary (brief description)'), '$product.description' => _w('Product description'), '$product.rating' => _w('Product average rating (float, 0 to 5)'), '$product.skus' => _w('Array of product SKUs'), '$product.images' => _w('Array of product images'), '$product.categories' => _w('Array of product categories'), '$product.tags' => _w('Array of product tags'), '$product.pages' => _w('Array of product static info pages'), '$product.features' => _w('Array of product features and values'), '$reviews' => _w('Array of product reviews'), '$services' => _w('Array of services available for this product')), 'search.html' => array('$title' => ''), 'list-table.html' => array('$products' => array('$id' => '', '...' => _w('Available vars are listed in the cheat sheet for product.html template'))), 'list-thumbs.html' => array('$products' => array('$id' => '', '...' => _w('Available vars are listed in the cheat sheet for product.html template'))), '$wa' => array('$wa->shop->badgeHtml(<em>$product.code</em>)' => _w('Displays badge of the specified product (<em>$product</em> object)'), '$wa->shop->cart()' => _w('Returns current cart object'), '$wa->shop->categories(<em>$id = 0, $depth = null, $tree = false, $params = false, $route = null</em>)' => _w('Returns array of subcategories of the specified category. Omit parent category for the entire array of categories'), '$wa->shop->category(<em>$category_id</em>)' => _w('Returns category object by <em>$category_id</em>'), '<em>$category</em>.params()' => _w('Array of custom category parameters'), '$wa->shop->compare()' => _w('Returns array of products currently added into a comparison list'), '$wa->shop->crossSelling(<em>$product_id</em>, <em>$limit = 5</em>, <em>$available_only = false</em>)' => _w('Returns array of cross-sell products.<em>$product_id</em> can be either a number (ID of the specified base product) or an array of products IDs') . '. ' . _w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return'), '$wa->shop->currency()' => _w('Returns current currency object'), '$wa->shop->product(<em>$product_id</em>)' => _w('Returns product object by <em>$product_id</em>') . '<br><br> ' . '$product-><strong>productUrl()</strong>: ' . _w('Returns valid product page URL') . '<br>' . '$product-><strong>upSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):' . _w('Returns array of upsell products for the specified product') . '. ' . _w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return') . '<br>' . '$product-><strong>crossSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):' . _w('Returns array of upsell products for the specified product') . '. ' . _w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return') . '<br><br>' . '$product.<strong>id</strong>: ' . _w('Product id. Other elements of <em>$product</em> available in this template are listed below') . '<br>' . '$product.<strong>name</strong>: ' . _w('Product name') . '<br>' . '$product.<strong>description</strong>: ' . _w('Product summary (brief description)') . '<br>' . '$product.<strong>rating</strong>: ' . _w('Product average rating (float, 0 to 5)') . '<br>' . '$product.<strong>skus</strong>: ' . _w('Array of product SKUs') . '<br>' . '$product.<strong>images</strong>: ' . _w('Array of product images') . '<br>' . '$product.<strong>categories</strong>: ' . _w('Array of product categories') . '<br>' . '$product.<strong>tags</strong>: ' . _w('Array of product tags') . '<br>' . '$product.<strong>pages</strong>: ' . _w('Array of product static info pages') . '<br>' . '$product.<strong>features</strong>: ' . _w('Array of product features and values') . '<br>', '$wa->shop->productImgHtml($product, $size, $attributes = array())' => _w('Displays specified $product object’s default image'), '$wa->shop->productImgUrl($product, $size)' => _w('Returns specified $product default image URL'), '$wa->shop->products(<em>search_conditions</em>[,<em>offset</em>[, <em>limit</em>[, <em>options</em>]]])' => _w('Returns array of products by search criteria, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.') . ' ' . _w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'), '$wa->shop->productsCount(<em>search_conditions</em>)' => _w('Returns number of products matching specified search conditions, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.'), '$wa->shop->productSet(<em>set_id</em>)' => _w('Returns array of products from the specified set.') . ' ' . _w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'), '$wa->shop->ratingHtml(<em>$rating, $size = 10, $show_when_zero = false</em>)' => _w('Displays 1—5 stars rating. $size indicates icon size and can be either 10 or 16'), '$wa->shop->settings("<em>option_id</em>")' => _w('Returns store’s general setting option by <em>option_id</em>, e.g. "name", "email", "country"'), '$wa->shop->themePath("<em>theme_id</em>")' => _ws('Returns path to theme folder by <em>theme_id</em>'))), 'blocks' => array());
 /**
  * @param string $field
  * @param mixed $value
  * @param array $info
  * @param array $data
  * @param null $sku_data
  * @return mixed|string
  */
 private function format($field, $value, $info = array(), $data = array(), $sku_data = null)
 {
     /**
      * @todo cpa field
      */
     /**
      * <yml_catalog>
      * <shop>
      * <currencies>
      * <categories>
      * <local_delivery_cost>
      * <offers>
      * <picture>
      * <description> и <name>
      * <delivery>, <pickup> и <store>
      * <adult>
      * <barcode>
      * <cpa> TODO
      * <rec>
      * <param> (name,unit,value)
      * <vendor>
      */
     static $currency_model;
     static $size;
     switch ($field) {
         case 'group_id':
             if ($value === 'auto') {
                 if (!empty($data['market_category'])) {
                     $value = $this->plugin()->isGroupedCategory($data['market_category']) ? $data['id'] : null;
                 } else {
                     $info['format'] = false;
                 }
             }
             break;
         case 'market_category':
             //it's product constant field
             //TODO verify it
             break;
         case 'name':
             if (!empty($sku_data['name']) && !empty($data['name']) && $sku_data['name'] != $data['name']) {
                 $value = sprintf('%s (%s)', $value, $sku_data['name']);
             }
             $value = preg_replace('/<br\\/?\\s*>/', "\n", $value);
             $value = preg_replace("/[\r\n]+/", "\n", $value);
             $value = strip_tags($value);
             $value = trim($value);
             if (mb_strlen($value) > 255) {
                 $value = mb_substr($value, 0, 252) . '...';
             }
             break;
         case 'description':
             $value = preg_replace('/<br\\/?\\s*>/', "\n", $value);
             $value = preg_replace("/[\r\n]+/", "\n", $value);
             $value = strip_tags($value);
             $value = trim($value);
             if (mb_strlen($value) > 512) {
                 $value = mb_substr($value, 0, 509) . '...';
             }
             break;
         case 'barcode':
             //может содержать несколько элементов
             $value = preg_replace('@\\D+@', '', $value);
             if (!in_array(strlen($value), array(8, 12, 13))) {
                 $value = null;
             }
             break;
         case 'sales_notes':
             $value = trim($value);
             if (mb_strlen($value) > 50) {
                 $value = mb_substr($value, 0, 50);
             }
             break;
         case 'typePrefix':
             $model = new shopTypeModel();
             if ($type = $model->getById($value)) {
                 $value = $type['name'];
             }
             break;
         case 'url':
             //max 512
             $value = preg_replace_callback('@([^\\[\\]a-zA-Z\\d_/-\\?=%&,\\.]+)@i', array(__CLASS__, 'rawurlencode'), $value);
             if ($this->data['utm']) {
                 $value .= (strpos($value, '?') ? '&' : '?') . $this->data['utm'];
             }
             $value = 'http://' . ifempty($this->data['base_url'], 'localhost') . $value;
             break;
         case 'oldprice':
             if (empty($value) || empty($this->data['export']['compare_price'])) {
                 $value = null;
                 break;
             }
         case 'price':
             if (!$currency_model) {
                 $currency_model = new shopCurrencyModel();
             }
             if ($sku_data) {
                 if (!in_array($data['currency'], $this->data['currency'])) {
                     $value = $currency_model->convert($value, $data['currency'], $this->data['primary_currency']);
                     $data['currency'] = $this->data['primary_currency'];
                 }
             } else {
                 if (!in_array($data['currency'], $this->data['currency'])) {
                     #value in default currency
                     if ($this->data['default_currency'] != $this->data['primary_currency']) {
                         $value = $currency_model->convert($value, $this->data['default_currency'], $this->data['primary_currency']);
                     }
                     $data['currency'] = $this->data['primary_currency'];
                 } elseif ($this->data['default_currency'] != $data['currency']) {
                     $value = $currency_model->convert($value, $this->data['default_currency'], $data['currency']);
                 }
             }
             break;
         case 'currencyId':
             if (!in_array($value, $this->data['currency'])) {
                 $value = $this->data['primary_currency'];
             }
             break;
         case 'rate':
             if (!in_array($value, array('CB', 'CBRF', 'NBU', 'NBK'))) {
                 $info['format'] = '%0.4f';
             }
             break;
         case 'available':
             if (!empty($sku_data) && isset($sku_data['available']) && empty($sku_data['available'])) {
                 $value = 'false';
             }
             if (is_object($value)) {
                 switch (get_class($value)) {
                     case 'shopBooleanValue':
                         /**
                          * @var $value shopBooleanValue
                          */
                         $value = $value->value ? 'true' : 'false';
                         break;
                 }
             }
             $value = ($value <= 0 || $value === 'false' || empty($value)) && $value !== null && $value !== 'true' ? 'false' : 'true';
             break;
         case 'store':
         case 'pickup':
         case 'delivery':
         case 'adult ':
             if (is_object($value)) {
                 switch (get_class($value)) {
                     case 'shopBooleanValue':
                         /**
                          * @var $value shopBooleanValue
                          */
                         $value = $value->value ? 'true' : 'false';
                         break;
                 }
             }
             $value = empty($value) || $value === 'false' ? 'false' : 'true';
             break;
         case 'picture':
             //max 512
             $values = array();
             $limit = 10;
             if (!empty($sku_data['image_id'])) {
                 $value = array(ifempty($value[$sku_data['image_id']]));
             }
             while (is_array($value) && ($image = array_shift($value)) && $limit--) {
                 if (!$size) {
                     $shop_config = wa('shop')->getConfig();
                     /**
                      * @var $shop_config shopConfig
                      */
                     $size = $shop_config->getImageSize('big');
                 }
                 $values[] = 'http://' . ifempty($this->data['base_url'], 'localhost') . shopImage::getUrl($image, $size);
             }
             $value = $values;
             break;
         case 'page_extent':
             $value = max(1, intval($value));
             break;
         case 'seller_warranty':
         case 'manufacturer_warranty':
         case 'expiry':
             /**
              * ISO 8601, например: P1Y2M10DT2H30M
              */
             $pattern = '@P((\\d+S)?(\\d+M)(\\d+D)?)?(T(\\d+H)?(\\d+M)(\\d+S)?)?@';
             $class = is_object($value) ? get_class($value) : false;
             switch ($class) {
                 case 'shopBooleanValue':
                     /**
                      * @var $value shopBooleanValue
                      */
                     $value = $value->value ? 'true' : 'false';
                     break;
                 case 'shopDimensionValue':
                     /**
                      * @var $value shopDimensionValue
                      */
                     $value = $value->convert('s', false);
                     /**
                      * @var $value int
                      */
                     if (empty($value)) {
                         $value = 'false';
                     } else {
                         $value = $this->formatCustom($value, 'ISO8601');
                     }
                     break;
                 default:
                     $value = (string) $value;
                     if (empty($value) || $value == 'false') {
                         $value = 'false';
                     } elseif (preg_match('@^\\d+$@', trim($value))) {
                         $value = $this->formatCustom(intval($value) * 3600 * 24, 'ISO8601');
                     } elseif (!preg_match($pattern, $value)) {
                         $value = 'true';
                     }
                     break;
             }
             break;
         case 'year':
             if (empty($value)) {
                 $value = null;
             }
             break;
         case 'ISBN':
             /**
              * @todo verify format
              * Код книги, если их несколько, то указываются через запятую.
              * Форматы ISBN и SBN проверяются на корректность. Валидация кодов происходит не только по длине,
              * также проверяется контрольная цифра (check-digit) – последняя цифра кода должна согласовываться
              * с остальными цифрами по определенной формуле. При разбиении ISBN на части при помощи дефиса
              * (например, 978-5-94878-004-7) код проверяется на соответствие дополнительным требованиям к
              * количеству цифр в каждой из частей.
              * Необязательный элемент.
              **/
             break;
         case 'recording_length':
             /**
              * Время звучания задается в формате mm.ss (минуты.секунды).
              **/
             if (is_object($value)) {
                 switch (get_class($value)) {
                     case 'shopDimensionValue':
                         /**
                          * @var $value shopDimensionValue
                          */
                         $value = $value->convert('s', false);
                         break;
                     default:
                         $value = (int) $value;
                         break;
                 }
             }
             $value = sprintf('%02d.%02d', floor($value / 60), $value % 60);
             break;
         case 'weight':
             /**
              * Элемент предназначен для указания веса товара. Вес указывается в килограммах с учетом упаковки.
              * Формат элемента: положительное число с точностью 0.001, разделитель целой и дробной части — точка.
              * При указании более высокой точности значение автоматически округляется следующим способом:
              * — если 4-ый знак после разделителя меньше 5, то 3-й знак сохраняется, а все последующие обнуляются;
              * — если 4-ый знак после разделителя больше или равен 5, то 3-й знак увеличивается на единицу, а все последующие обнуляются.
              **/
             if (is_object($value)) {
                 switch (get_class($value)) {
                     case 'shopDimensionValue':
                         /**
                          * @var $value shopDimensionValue
                          */
                         if ($value->type == 'weight') {
                             $value = $value->convert('kg', '%0.3f');
                         }
                         break;
                     default:
                         $value = floatval($value);
                         break;
                 }
             } else {
                 $value = floatval($value);
             }
             break;
         case 'dimensions':
             /**
              *
              * Элемент предназначен для указания габаритов товара (длина, ширина, высота) в упаковке. Размеры указываются в сантиметрах.
              * Формат элемента: три положительных числа с точностью 0.001, разделитель целой и дробной части — точка. Числа должны быть разделены символом «/» без пробелов.
              * При указании более высокой точности значение автоматически округляется следующим способом:
              * — если 4-ый знак после разделителя меньше 5, то 3-й знак сохраняется, а все последующие обнуляются;
              * — если 4-ый знак после разделителя больше или равен 5, то 3-й знак увеличивается на единицу, а все последующие обнуляются.
              **/
             /**
              * @todo use cm
              *
              */
             $parsed_value = array();
             $class = is_object($value) ? get_class($value) : false;
             switch ($class) {
                 case 'shopCompositeValue':
                     /**
                      * @var $value shopCompositeValue
                      */
                     for ($i = 0; $i < 3; $i++) {
                         $value_item = $value[$i];
                         $class_item = is_object($value_item) ? get_class($value_item) : false;
                         switch ($class_item) {
                             case 'shopDimensionValue':
                                 /**
                                  * @var $value_item shopDimensionValue
                                  */
                                 if ($value_item->type == '3d.length') {
                                     $parsed_value[] = $value_item->convert('cm', '%0.4f');
                                 } else {
                                     $parsed_value[] = sprintf('%0.4f', (string) $value_item);
                                 }
                                 break;
                             default:
                                 $parsed_value[] = sprintf('%0.4f', (string) $value_item);
                                 break;
                         }
                     }
                     break;
                 default:
                     $parsed_value = array_map('floatval', explode(':', preg_replace('@[^\\d\\.,]+@', ':', $value), 3));
                     break;
             }
             foreach ($parsed_value as &$p) {
                 $p = str_replace(',', '.', sprintf('%0.4f', $p));
                 unset($p);
             }
             $value = implode('/', $parsed_value);
             break;
         case 'age':
             /**
              * @todo
              * unit="year": 0, 6, 12, 16, 18
              * unit="month": 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
              */
             if (is_object($value)) {
                 switch (get_class($value)) {
                     case 'shopDimensionValue':
                         /**
                          * @var $value shopDimensionValue
                          */
                         if ($value->type == 'time') {
                             $value = $value->convert('month', false);
                         }
                         break;
                     default:
                         $value = intval($value);
                         break;
                 }
             } else {
                 /**
                  * @var $value shopDimensionValue
                  */
                 if (preg_match('@^(year|month)s?:(\\d+)$@', trim($value), $matches)) {
                     $value = array('unit' => $matches[1], 'value' => intval($matches[2]));
                 } else {
                     $value = intval($value);
                 }
             }
             if (!is_array($value)) {
                 if ($value > 12) {
                     $value = array('unit' => 'year', 'value' => floor($value / 12));
                 } else {
                     $value = array('unit' => 'month', 'value' => intval($value));
                 }
             }
             break;
         case 'country_of_origin':
             /**
              * @todo
              * @see http://partner.market.yandex.ru/pages/help/Countries.pdf
              */
             break;
         case 'local_delivery_cost':
             if ($value !== '') {
                 $value = max(0, floatval($value));
             }
             break;
         case 'days':
             $value = max(1, intval($value));
             break;
         case 'dataTour':
             /**
              * @todo
              * Даты заездов.
              * Необязательный элемент. Элемент <offer> может содержать несколько элементов <dataTour>.
              **/
             break;
         case 'hotel_stars':
             /**
              * @todo
              * Звезды отеля.
              * Необязательный элемент.
              **/
             break;
         case 'room':
             /**
              * @todo
              * Тип комнаты (SNG, DBL, ...).
              * Необязательный элемент.
              **/
             break;
         case 'meal':
             /**
              * @todo
              * Тип питания (All, HB, ...).
              * Необязательный элемент.
              **/
             break;
         case 'date':
             /**
              * @todo
              * Дата и время сеанса. Указываются в формате ISO 8601: YYYY-MM-DDThh:mm.
              **/
             break;
         case 'hall':
             /**
              * @todo
              * max 512
              * Ссылка на изображение с планом зала.
              **/
             //plan - property
             break;
         case 'param':
             $unit = null;
             $name = ifset($info['source_name'], '');
             if ($value instanceof shopDimensionValue) {
                 $unit = $value->unit_name;
                 $value = $value->format('%s');
             } elseif (is_array($value)) {
                 $_value = reset($value);
                 if ($_value instanceof shopDimensionValue) {
                     $unit = $_value->unit_name;
                     $values = array();
                     foreach ($value as $_value) {
                         /**
                          * @var shopDimensionValue $_value
                          */
                         $values[] = $_value->convert($unit, '%s');
                     }
                     $value = implode(', ', $values);
                 } else {
                     if (preg_match('@^(.+)\\s*\\(([^\\)]+)\\)\\s*$@', $name, $matches)) {
                         //feature name based unit
                         $unit = $matches[2];
                         $name = $matches[1];
                     }
                     $value = implode(', ', $value);
                 }
             } elseif (preg_match('@^(.+)\\s*\\(([^\\)]+)\\)\\s*$@', $name, $matches)) {
                 //feature name based unit
                 $unit = $matches[2];
                 $name = $matches[1];
             }
             $value = trim((string) $value);
             if (in_array($value, array(null, false, ''), true)) {
                 $value = null;
             } else {
                 $value = array('name' => $name, 'unit' => $unit, 'value' => trim((string) $value));
             }
             break;
     }
     $format = ifempty($info['format'], '%s');
     if (is_array($value)) {
         /**
          * @var $value array
          */
         reset($value);
         if (key($value) == 0) {
             foreach ($value as &$item) {
                 $item = str_replace('&nbsp;', ' ', $item);
                 $item = str_replace('&', '&amp;', $item);
                 $item = $this->sprintf($format, $item);
             }
             unset($item);
         }
         if (!in_array($field, array('email', 'picture', 'dataTour', 'additional', 'barcode', 'param', 'related_offer'))) {
             $value = implode(', ', $value);
         }
     } elseif ($value !== null) {
         /**
          * @var $value string
          */
         $value = str_replace('&nbsp;', ' ', $value);
         $value = str_replace('&', '&amp;', $value);
         $value = $this->sprintf($format, $value);
     }
     return $value;
 }
 public function execute()
 {
     $model = new shopTypeModel();
     $this->view->assign('types', $model->getTypes());
 }
Exemple #23
0
<?php

$type_model = new shopTypeModel();
$type_model->recount();
 public function execute()
 {
     list($start_date, $end_date, $group_by) = shopReportsSalesAction::getTimeframeParams();
     $mode = waRequest::request('mode', 'sales');
     if ($mode !== 'sales') {
         $mode = 'profit';
     }
     // Top products
     $pm = new shopProductModel();
     $top_products = $pm->getTop(10, $mode, $start_date, $end_date)->fetchAll('id');
     $max_val = 0;
     $product_total_val = 0;
     foreach ($top_products as &$p) {
         $p['profit'] = $p['sales'] - $p['purchase'];
         $p['val'] = $p[$mode];
         $max_val = max($p['val'], $max_val);
         $product_total_val += $p['val'];
     }
     foreach ($top_products as &$p) {
         $p['val_percent'] = round($p['val'] * 100 / ifempty($max_val, 1));
     }
     unset($p);
     // Top services
     $sm = new shopServiceModel();
     $top_services = $sm->getTop(10, $start_date, $end_date)->fetchAll('id');
     $max_val = 0;
     $service_total_val = 0;
     foreach ($top_services as $s) {
         $max_val = max($s['total'], $max_val);
         $service_total_val += $s['total'];
     }
     foreach ($top_services as &$s) {
         $s['total_percent'] = round($s['total'] * 100 / ifempty($max_val, 1));
     }
     unset($s);
     // Total sales or pofit for the period
     $om = new shopOrderModel();
     if ($mode == 'sales') {
         $total_val = $om->getTotalSales($start_date, $end_date);
     } else {
         $total_val = $om->getTotalProfit($start_date, $end_date);
     }
     // Total sales by product type
     $sales_by_type = array();
     $tm = new shopTypeModel();
     $pie_total = 0;
     foreach ($tm->getSales($start_date, $end_date) as $row) {
         $sales_by_type[] = array($row['name'], (double) $row['sales']);
         $pie_total += $row['sales'];
     }
     $sales_by_type[] = array(_w('Services'), $service_total_val);
     $pie_total += $service_total_val;
     if ($pie_total) {
         foreach ($sales_by_type as &$row) {
             $row[0] .= ' (' . round($row[1] * 100 / ifempty($pie_total, 1), 1) . '%)';
         }
         unset($row);
     }
     $def_cur = wa()->getConfig()->getCurrency();
     $this->view->assign('mode', $mode);
     $this->view->assign('def_cur', $def_cur);
     $this->view->assign('total_val', $total_val);
     $this->view->assign('top_products', $top_products);
     $this->view->assign('top_services', $top_services);
     $this->view->assign('product_total_val', $product_total_val);
     $this->view->assign('service_total_val', $service_total_val);
     $this->view->assign('pie_data', array($sales_by_type));
 }
    private function typesAutocomplete($q)
    {
        $result = array();
        $model = new shopTypeModel();
        $value = $model->escape($q, 'like');
        $table = $model->getTableName();
        $sql = <<<SQL
SELECT `icon`,`id`,`name`,`count` FROM {$table}
WHERE
  `name` LIKE '%{$value}%'
ORDER BY `count` DESC
LIMIT 20
SQL;
        foreach ($model->query($sql)->fetchAll('id', true) as $id => $t) {
            $icon = shopHelper::getIcon($t['icon']);
            unset($t['icon']);
            $t['count'] = _w('%d product', '%d products', $t['count']);
            $result[] = array('id' => $id, 'value' => $id, 'name' => $t['name'], 'label' => $icon . implode('; ', array_filter($t)));
        }
        return $result;
    }
 /**
 * @param $data
 * @param array $features строка 1
 строка 2
 * @return string
 */
 public static function getConditionHTML($data, $features = array())
 {
     $result = array();
     foreach ($data as $row) {
         if (empty($row['cond'])) {
             continue;
         }
         if (!empty($row['feature_id'])) {
             if ($features) {
                 $html = $features[$row['feature_id']]['name'];
             } else {
                 $html = $row['feature_name'];
             }
         } else {
             if ($row['feature'] == 'price') {
                 $html = _w('Price');
             } elseif ($row['feature'] == 'tag') {
                 $html = _w('Tags');
             } elseif ($row['feature'] == 'type_id') {
                 $html = _w('Type');
             } else {
                 continue;
             }
         }
         $html .= ' ';
         switch ($row['cond']) {
             case 'between':
                 $v = explode(',', $row['value']);
                 $html .= '<span class="s-plus-minus">' . ($v[1] > 0 ? '+' : '') . $v[1] . '%<br>' . ($v[0] > 0 ? '+' : '') . $v[0] . '%</span>';
                 break;
             case 'contain':
                 $html .= $row['cond'] . ' "' . $row['value'] . '"';
                 break;
             case 'same':
                 $html .= _w('matches base product value');
                 break;
             case 'notsame':
                 $html .= _w('differs from base product value');
                 break;
             case 'all':
             case 'any':
             case 'is':
                 if ($row['cond'] == 'any') {
                     $html .= _w('any of selected values (OR)');
                 } elseif ($row['cond'] == 'all') {
                     $html .= _w('all of selected values (AND)');
                 } else {
                     $html .= _w($row['cond']);
                 }
                 $html .= ' ';
                 if ($row['feature'] == 'type_id') {
                     $type_model = new shopTypeModel();
                     $type = $type_model->getById($row['value']);
                     $html .= $type['name'];
                 } else {
                     $feature_values_model = shopFeatureModel::getValuesModel($features ? $features[$row['feature_id']]['type'] : $row['feature_type']);
                     if (strpos($row['value'], ',') !== false) {
                         $value_ids = explode(',', $row['value']);
                         $values = $feature_values_model->getById($value_ids);
                         foreach ($values as &$v) {
                             $v = $v['value'];
                         }
                         unset($v);
                         $html .= implode(', ', $values);
                     } else {
                         $v = $feature_values_model->getById($row['value']);
                         $html .= $v['value'];
                     }
                 }
                 break;
         }
         $result[] = $html;
     }
     return implode('; ', $result);
 }
 private function setup()
 {
     if ($country = waRequest::post('country')) {
         if (!empty($this->countries[$country])) {
             $path = $this->getConfig()->getConfigPath('data/welcome/', false);
             $country_data = (include $path . "country_{$country}.php");
             # Main country setting
             $model = new waAppSettingsModel();
             $model->set('shop', 'country', $country);
             #currency
             if (!empty($country_data['currency'])) {
                 $currency_model = new shopCurrencyModel();
                 $sort = 0;
                 foreach ($country_data['currency'] as $code => $rate) {
                     // delete old currency info is exists
                     $currency_model->deleteById($code);
                     $currency_model->insert(array('code' => $code, 'rate' => $rate, 'sort' => $sort++), 2);
                     if ($sort == 1) {
                         $model->set('shop', 'currency', $code);
                     }
                 }
             }
             #taxes
             if (!empty($country_data['taxes'])) {
                 foreach ($country_data['taxes'] as $tax_data) {
                     shopTaxes::save($tax_data);
                 }
             }
             #custom code
             $function = 'shopWelcome' . ucfirst($country);
             if (function_exists($function)) {
                 try {
                     call_user_func_array($function, array());
                 } catch (Exception $ex) {
                     //TODO
                 }
             }
         }
     }
     if (!empty($this->types)) {
         $type_model = new shopTypeModel();
         $type_features_model = new shopTypeFeaturesModel();
         $types = waRequest::post('types');
         if (empty($types)) {
             if (!$type_features_model->countAll()) {
                 $types[] = 'default';
             }
         }
         if ($types) {
             foreach ($types as $type) {
                 $type_model->insertTemplate($type);
             }
         }
     }
     $set_model = new shopSetModel();
     $set_model->add(array('id' => 'promo', 'name' => _w('Featured on homepage'), 'type' => shopSetModel::TYPE_STATIC));
     $set_model->add(array('id' => 'bestsellers', 'name' => _w('Bestsellers'), 'type' => shopSetModel::TYPE_DYNAMIC, 'count' => 8, 'rule' => 'rating DESC'));
     // notifications
     $notifications_model = new shopNotificationModel();
     if ($notifications_model->countAll() == 0) {
         $notifications_action = new shopSettingsNotificationsAddAction();
         $notifications = $notifications_action->getTemplates();
         $params_model = new shopNotificationParamsModel();
         $events = $notifications_action->getEvents();
         foreach ($notifications as $event => $n) {
             if ($event == 'order') {
                 continue;
             }
             $data = array('name' => $events[$event]['name'] . ' (' . _w('Customer') . ')', 'event' => $event, 'transport' => 'email', 'status' => 1);
             $id = $notifications_model->insert($data);
             $params = $n;
             $params['to'] = 'customer';
             $params_model->save($id, $params);
             if ($event == 'order.create') {
                 $data['name'] = $events[$event]['name'] . ' (' . _w('Store admin') . ')';
                 $id = $notifications_model->insert($data);
                 $params['to'] = 'admin';
                 $params_model->save($id, $params);
             }
         }
     }
     /* !!! import commented out on welcome screen
        switch (waRequest::post('import')) {
        case 'demo':
        //TODO create demoproducts
        $this->redirect('?action=products');
        break;
        case 'migrate':
        $plugins = $this->getConfig()->getPlugins();
        if (empty($plugins['migrate'])) {
        $url = $this->getConfig()->getBackendUrl(true).'installer/?module=update&action=manager&install=1&app_id[shop/plugins/migrate]=webasyst';
        } else {
        $url = '?action=importexport#/migrate/';
        }
        $this->redirect($url);
        break;
        case 'scratch':
        default: */
     $this->redirect('?action=products#/welcome/');
     //        break;
     //}
 }
Exemple #28
0
 /**
  * Returns information on product's type.
  *
  * @return array|null Product type info array, or null if product has no type
  */
 public function getType()
 {
     $model = new shopTypeModel();
     return $this->type_id ? $model->getById($this->type_id) : null;
 }
 /**
  * Collections /type/1
  *
  * @param int $id - type_id
  * @param bool $auto_title
  */
 protected function typePrepare($id, $auto_title = true)
 {
     $type_model = new shopTypeModel();
     $type = $type_model->getById($id);
     if (!$type) {
         $this->where[] = '0';
         return;
     }
     $this->info = $type;
     if ($auto_title) {
         $this->addTitle($type['name']);
     }
     $this->where[] = "p.type_id = " . (int) $id;
 }
Exemple #30
0
 /**
  * Get product ids and leave only allowed by rights
  *
  * @param array $product_ids
  * @return array
  */
 public function filterAllowedProductIds(array $product_ids)
 {
     if (wa('shop')->getUser()->getRights('shop', 'type.all')) {
         return $product_ids;
     }
     $type_model = new shopTypeModel();
     $types = $type_model->getTypes();
     $type_ids = array_keys($types);
     if (empty($product_ids) || empty($types)) {
         return array();
     }
     $product_ids = array_keys($this->query("\n            SELECT id FROM `{$this->table}`\n            WHERE id IN(" . implode(',', $product_ids) . ")\n                AND type_id IN (" . implode(',', $type_ids) . ")")->fetchAll('id'));
     return $product_ids;
 }