public function execute()
 {
     // filter by stock_id
     $stock_id = waRequest::get('stock_id', null, waRequest::TYPE_INT);
     // order
     $order = waRequest::get('order', null, waRequest::TYPE_STRING_TRIM);
     if ($order != 'asc' && $order != 'desc') {
         $order = 'desc';
     }
     // build where filter
     $where = array();
     if ($this->product_id) {
         $where['product_id'] = $this->product_id;
     }
     if ($stock_id) {
         $where['stock_id'] = $stock_id;
     }
     // offset
     $offset = waRequest::get('offset', 0, waRequest::TYPE_INT);
     // limit
     $total_count = $this->getTotalCount($where);
     // chunk size
     $count = $this->getConfig()->getOption('stocks_log_items_per_page');
     // get list of log items
     $log = $this->getList(array('offset' => $offset, 'limit' => $count, 'where' => $where, 'order' => 'datetime ' . $order . ',id ' . $order));
     // get all stocks
     $stock_model = new shopStockModel();
     $stocks = $stock_model->getAll('id');
     $this->view->assign(array('log' => $log, 'stocks' => $stocks, 'product_id' => $this->product_id, 'stock_id' => $stock_id, 'order' => $order, 'offset' => $offset, 'total_count' => $total_count, 'count' => count($log), 'lazy' => waRequest::get('lazy', false)));
 }
 public function execute()
 {
     $model = new shopStockModel();
     foreach ($this->getEditData() as $id => $item) {
         $model->updateById($id, $item);
     }
     $inventory_stock_id = null;
     foreach ($this->getAddData() as $before_id => $data) {
         foreach ($data as $item) {
             $id = $model->add($item, $before_id);
             if (!empty($item['inventory'])) {
                 $inventory_stock_id = $id;
             }
         }
     }
     if ($inventory_stock_id) {
         // Assign all inventory to this stock
         $product_stocks_model = new shopProductStocksModel();
         $product_stocks_model->insertFromSkus($inventory_stock_id);
     }
     $app_id = $this->getAppId();
     $app_settings_model = new waAppSettingsModel();
     if (waRequest::post('ignore_stock_count')) {
         $app_settings_model->set($app_id, 'ignore_stock_count', 1);
     } else {
         $app_settings_model->set($app_id, 'ignore_stock_count', 0);
     }
     if (waRequest::post('update_stock_count_on_create_order')) {
         $app_settings_model->set($app_id, 'update_stock_count_on_create_order', 1);
     } else {
         $app_settings_model->set($app_id, 'update_stock_count_on_create_order', 0);
     }
 }
 public function execute()
 {
     $model = new shopStockModel();
     if (waRequest::post()) {
         $this->save();
     }
     $this->view->assign('stocks', $model->getAll('id'));
 }
 public function execute()
 {
     $id = $this->get('id', true);
     $stock_model = new shopStockModel();
     $stock = $stock_model->getById($id);
     if (!$stock) {
         throw new waAPIException('invalid_param', 'Stock not found', 404);
     }
     $this->response = $stock;
 }
 public function execute()
 {
     $id = waRequest::post('id', null, waRequest::TYPE_INT);
     $before_id = waRequest::post('before_id', null, waRequest::TYPE_INT);
     if (!$id) {
         $this->errors[] = "Unknown stock";
         return;
     }
     $stock_model = new shopStockModel();
     if (!$stock_model->move($id, $before_id)) {
         $this->errors[] = "Error when move";
     }
 }
 public function backendOrder($param)
 {
     if ($this->getSettings('status')) {
         $stock_model = new shopStockModel();
         $stocks = $stock_model->getAll();
         if ($stocks) {
             return array('action_button' => '<script type="text/javascript" src="' . wa()->getAppStaticUrl('shop') . 'plugins/orderstock/js/editOrder.js?' . date('His') . '"></script>
                           <script type="text/javascript">
                             $(function() { new editOrder(' . $param['id'] . ',' . json_encode($stocks) . ');});
                           </script>');
         }
     }
     return false;
 }
 public function execute()
 {
     $id = (int) waRequest::get('id');
     $html = '';
     $app_settings_model = new waAppSettingsModel();
     $settings = $app_settings_model->get(array('shop', 'fprview'));
     $product = new shopProduct($id);
     $route_params = array('product_url' => $product['url']);
     if (isset($product['category_url'])) {
         $route_params['category_url'] = $product['category_url'];
     }
     $product['frontend_url'] = wa()->getRouteUrl('shop/frontend/product', $route_params);
     $feature_codes = array_keys($product->features);
     $feature_model = new shopFeatureModel();
     $features = $feature_model->getByCode($feature_codes);
     $theme = waRequest::param('theme', 'default');
     $theme_path = wa()->getDataPath('themes', true) . '/' . $theme;
     if (!file_exists($theme_path) || !file_exists($theme_path . '/theme.xml')) {
         $theme_path = wa()->getAppPath() . '/themes/' . $theme;
     }
     switch ($settings['template_type']) {
         case 'plugin':
             $view = wa()->getView();
             $view->assign('features', $features);
             $view->assign('product', $product);
             $view->assign('fprview_settings', $settings);
             $html = $view->fetch(realpath(dirname(__FILE__) . "/../../") . '/templates/Frontend.html');
             break;
         case 'theme':
             if ($settings['template_theme_file'] && file_exists($theme_path . '/' . $settings['template_theme_file'])) {
                 $view = wa()->getView(array('template_dir' => $theme_path));
                 list($services, $skus_services) = $this->getServiceVars($product);
                 $compare = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
                 $stock_model = new shopStockModel();
                 $view->assign(array('sku_services' => $skus_services, 'services' => $services, 'compare' => in_array($product['id'], $compare) ? $compare : array(), 'currency_info' => $this->getCurrencyInfo(), 'stocks' => $stock_model->getAll('id'), 'reviews' => $this->getTopReviews($product['id']), 'rates' => $this->reviews_model->getProductRates($product['id']), 'reviews_total_count' => $this->getReviewsTotalCount($product['id']), 'features' => $features, 'product' => $product));
                 $view->assign('frontend_product', wa()->event('frontend_product', $product, array('menu', 'cart', 'block_aux', 'block')));
                 $template = $this->setThemeTemplate($settings['template_theme_file']);
                 $html = $view->fetch($this->getTemplate());
             }
             break;
         default:
             $html = '';
             break;
     }
     echo $html;
     exit;
 }
Example #8
0
 public function execute()
 {
     $order_id = waRequest::get('id', null, waRequest::TYPE_INT);
     $form = null;
     $order = array();
     $shipping_address = array();
     // Existing order?
     if ($order_id) {
         $order = $this->getOrder($order_id);
         $currency = $order['currency'];
         if ($order['contact_id']) {
             $has_contacts_rights = shopHelper::getContactRights($order['contact_id']);
             $shipping_address = shopHelper::getOrderAddress($order['params'], 'shipping');
             if (!empty($order['contact_id'])) {
                 try {
                     $c = new waContact($order['contact_id']);
                     if ($shipping_address) {
                         $c['address.shipping'] = $shipping_address;
                     }
                     $form = shopHelper::getCustomerForm($c);
                 } catch (waException $e) {
                     // Contact does not exist; ignore. When $form is null, customer data saved in order is shown.
                 }
             }
         } else {
             $has_contacts_rights = shopHelper::getContactRights();
         }
     } else {
         $currency = $this->getConfig()->getCurrency();
         $has_contacts_rights = shopHelper::getContactRights();
         $form = shopHelper::getCustomerForm();
     }
     $stock_model = new shopStockModel();
     $stocks = $stock_model->getAll('id');
     $tax_model = new shopTaxModel();
     $taxes_count = $tax_model->countAll();
     $count_new = $this->order_model->getStateCounters('new');
     /**
      * Backend order edit page
      * @event backend_order_edit
      * @param array $order
      * @return array[string][string] $return[%plugin_id%] html output
      */
     $this->view->assign('backend_order_edit', wa()->event('backend_order_edit', $order));
     $this->view->assign(array('form' => $form, 'order' => $order, 'stocks' => $stocks, 'currency' => $currency, 'count_new' => $count_new, 'taxes_count' => $taxes_count, 'shipping_address' => $shipping_address, 'has_contacts_rights' => $has_contacts_rights, 'customer_validation_disabled' => wa()->getSetting('disable_backend_customer_form_validation'), 'ignore_stock_count' => wa()->getSetting('ignore_stock_count')));
 }
Example #9
0
 public function execute()
 {
     $offset = waRequest::get('offset', 0, waRequest::TYPE_INT);
     $total_count = waRequest::get('total_count', 0, waRequest::TYPE_INT);
     $order = waRequest::get('order', 'desc') == 'desc' ? 'desc' : 'asc';
     if (!$total_count) {
         $total_count = $this->product_model->countProductStocks();
     }
     $data = $this->getProductStocks($offset, $this->getConfig()->getOption('products_per_page'), $order);
     $count = count($data);
     if ($offset === 0) {
         $stock_model = new shopStockModel();
         $this->response(array('product_stocks' => $data, 'total_count' => $total_count, 'count' => $count, 'stocks' => $stock_model->getAll(), 'order' => $order));
     } else {
         $this->product_model = new shopProductModel();
         $this->response(array('product_stocks' => $data, 'total_count' => $total_count, 'count' => $count, 'order' => $order, 'progress' => array('loaded' => _w('%d product', '%d products', $offset + $count), 'of' => sprintf(_w('of %d'), $total_count), 'chunk' => _w('%d product', '%d products', max(0, min($total_count - ($offset + $count), $count))))), true);
     }
 }
 public static function getMapFields($flat = false, $extra_fields = false)
 {
     $fields = array('product' => array('name' => _w('Product name'), 'currency' => _w('Currency'), 'summary' => _w('Summary'), 'description' => _w('Description'), 'badge' => _w('Badge'), 'status' => _w('Status'), 'type_name' => _w('Product type'), 'tags' => _w('Tags'), 'tax_name' => _w('Taxable'), 'meta_title' => _w('Title'), 'meta_keywords' => _w('META Keyword'), 'meta_description' => _w('META Description'), 'url' => _w('Storefront link'), 'images' => _w('Product images')), 'sku' => array('skus:-1:name' => _w('SKU name'), 'skus:-1:sku' => _w('SKU code'), 'skus:-1:price' => _w('Price'), 'skus:-1:available' => _w('Available for purchase'), 'skus:-1:compare_price' => _w('Compare at price'), 'skus:-1:purchase_price' => _w('Purchase price'), 'skus:-1:stock:0' => _w('In stock')));
     if ($extra_fields) {
         $product_model = new shopProductModel();
         $sku_model = new shopProductSkusModel();
         $meta_fields = array('product' => $product_model->getMetadata(), 'sku' => $sku_model->getMetadata());
         $black_list = array('id', "contact_id", "create_datetime", "edit_datetime", "type_id", "image_id", "tax_id", "cross_selling", "upselling", "total_sales", "sku_type", "sku_count", 'sku_id', 'ext', 'price', 'compare_price', 'min_price', 'max_price', 'count', 'rating_count', 'category_id', 'base_price_selectable', 'rating');
         $white_list = array('id_1c' => '1C');
         foreach ($meta_fields['product'] as $field => $info) {
             if (!in_array($field, $black_list)) {
                 $name = ifset($white_list[$field], $field);
                 if (!empty($meta_fields['sku'][$field])) {
                     if (!isset($fields['sku']['skus:-1:' . $field])) {
                         $fields['sku']['skus:-1:' . $field] = $name;
                     }
                 } else {
                     if (!isset($fields['product'][$field])) {
                         $fields['product'][$field] = $name;
                     }
                 }
             }
         }
     }
     $stock_model = new shopStockModel();
     if ($stocks = $stock_model->getAll('id')) {
         foreach ($stocks as $stock_id => $stock) {
             $fields['sku']['skus:-1:stock:' . $stock_id] = _w('In stock') . ' @' . $stock['name'];
         }
     }
     if ($flat) {
         $fields_ = $fields;
         $fields = array();
         $flat_order = array('product:name', 'sku:skus:-1:name', 'sku:skus:-1:sku', 'product:currency');
         foreach ($flat_order as $field) {
             list($type, $field) = explode(':', $field, 2);
             $fields[$field] = $fields_[$type][$field];
             unset($fields_[$type][$field]);
         }
         $fields += $fields_['sku'];
         $fields += $fields_['product'];
     }
     return $fields;
 }
 public function execute()
 {
     $id = waRequest::get('id', null, waRequest::TYPE_INT);
     if (!$id) {
         $this->errors[] = _w("Unknown stock");
         return;
     }
     $model = new shopStockModel();
     $dst_stock = null;
     if (waRequest::post('delete_stock') == '1') {
         $dst_stock = waRequest::post('dst_stock', null, waRequest::TYPE_INT);
         if (!$dst_stock) {
             $this->errors[] = _w("Unknow destination stock");
             return;
         }
     }
     if (!$model->delete($id, $dst_stock)) {
         $this->errors[] = _w("Error when deleting");
     }
 }
Example #12
0
 /**
  * @param int $id
  * @param array $data
  * @param bool $correct
  * @param shopProduct $product
  * @return array
  */
 protected function updateSku($id = 0, $data, $correct = true, shopProduct $product = null)
 {
     /**
      * @var shopProductStocksModel $stocks_model
      */
     static $stocks_model;
     /**
      * @var bool $multi_stock
      */
     static $multi_stock = null;
     /**
      * @var shopFeatureModel $feature_model
      */
     static $feature_model;
     /**
      * @var shopProductFeaturesModel $product_features_model
      */
     static $product_features_model;
     if (isset($data['price'])) {
         $data['price'] = $this->castValue('double', $data['price']);
     }
     if (isset($data['purchase_price'])) {
         $data['purchase_price'] = $this->castValue('double', $data['purchase_price']);
     }
     if (isset($data['compare_price'])) {
         $data['compare_price'] = $this->castValue('double', $data['compare_price']);
     }
     if ($id > 0) {
         if ($product && (!isset($data['virtual']) || !empty($data['virtual']))) {
             #check changes for virtual SKU
             $virtual_sku_defaults = array('price' => $product->base_price_selectable, 'purchase_price' => $product->purchase_price_selectable, 'compare_price' => $product->compare_price_selectable, 'count' => 0);
             $virtual = null;
             foreach ($virtual_sku_defaults as $field => $default) {
                 if (isset($data[$field])) {
                     $value = $data[$field];
                     if (is_array($value)) {
                         $value = max($value);
                     }
                     if ($value != $default) {
                         if ($virtual === null) {
                             $virtual = isset($product->skus[$id]) && !empty($product->skus[$id]['virtual']);
                         }
                         if ($virtual) {
                             $data['virtual'] = 0;
                             $virtual = false;
                         }
                         if (!$virtual) {
                             break;
                         }
                     }
                 }
             }
         }
         if (empty($data['eproduct']) && !empty($data['file_name'])) {
             $file_path = shopProduct::getPath($data['product_id'], "sku_file/{$id}." . pathinfo($data['file_name'], PATHINFO_EXTENSION));
             waFiles::delete($file_path);
             $data['file_name'] = '';
             $data['file_description'] = '';
         } elseif (isset($data['file_name'])) {
             unset($data['file_name']);
         }
         $this->updateById($id, $data);
     } else {
         if (!isset($data['sku'])) {
             $data['sku'] = '';
         }
         $id = $this->insert($data);
     }
     $data['id'] = $id;
     $sku_count = false;
     // if stocking for this sku
     if (isset($data['stock']) && count($data['stock'])) {
         if ($multi_stock === null) {
             $stock_model = new shopStockModel();
             $stocks = $stock_model->getAll($stock_model->getTableId());
             $multi_stock = $stocks ? array_keys($stocks) : false;
         }
         // not multistocking
         if (!$multi_stock || isset($data['stock'][0])) {
             $sku_count = self::castStock($data['stock'][0]);
             unset($data['stock']);
             $this->logCount($data['product_id'], $id, $sku_count);
             // multistocking
         } else {
             $sku_count = 0;
             $missed = array_combine($multi_stock, $multi_stock);
             if (!$stocks_model) {
                 $stocks_model = new shopProductStocksModel();
             }
             // need for track transition from aggregating mode to multistocking mode
             $has_any_stocks = $stocks_model->hasAnyStocks($id);
             if (!$has_any_stocks) {
                 $this->writeOffCount($data['product_id'], $id);
             }
             foreach ($data['stock'] as $stock_id => $count) {
                 if ($stock_id > 0 && isset($missed[$stock_id])) {
                     unset($missed[$stock_id]);
                     $field = array('sku_id' => $id, 'stock_id' => $stock_id, 'product_id' => $data['product_id']);
                     $count = self::castStock($count);
                     $stock = array('count' => $count);
                     if ($count === null) {
                         $sku_count = null;
                     } else {
                         // Once turned into NULL value is not changed
                         if ($sku_count !== null) {
                             $sku_count += $count;
                         }
                     }
                     // there is taking into account stocks log inside this method
                     $stocks_model->set(array_merge($field, $stock));
                     $data['stock'][$stock_id] = $count;
                 }
             }
             //get stock_count for missed stocks
             if ($sku_count !== null && !empty($missed)) {
                 $search = array('stock_id' => $missed, 'sku_id' => $id, 'product_id' => $data['product_id']);
                 foreach ($stocks_model->getByField($search, 'stock_id') as $stock_id => $row) {
                     $count = $row['count'];
                     $data['stock'][$stock_id] = $count;
                     if ($count === null) {
                         $sku_count = null;
                     } else {
                         // Once turned into NULL value is not changed
                         if ($sku_count !== null) {
                             $sku_count += $count;
                         }
                     }
                 }
             }
         }
     }
     if ($sku_count !== false) {
         $data['count'] = $sku_count;
         $this->updateById($id, array('count' => $sku_count));
     }
     if (isset($data['features'])) {
         if (!$feature_model) {
             $feature_model = new shopFeatureModel();
         }
         if (!$product_features_model) {
             $product_features_model = new shopProductFeaturesModel();
         }
         $features = $data['features'];
         $data['features'] = array();
         $skip_values = array('', false, null);
         foreach ($features as $code => $value) {
             if ($feature = $feature_model->getByField('code', $code)) {
                 $model = shopFeatureModel::getValuesModel($feature['type']);
                 $field = array('product_id' => $data['product_id'], 'sku_id' => $id, 'feature_id' => $feature['id']);
                 $product_features_model->deleteByField($field);
                 if (is_array($value)) {
                     if (!empty($value['id'])) {
                         $field['feature_value_id'] = $value['id'];
                     } elseif (isset($value['value']) && !in_array($value['value'], $skip_values, true)) {
                         $field['feature_value_id'] = $model->getId($feature['id'], $code == 'weight' ? $value : $value['value'], $feature['type']);
                     }
                 } elseif (!in_array($value, $skip_values, true)) {
                     $field['feature_value_id'] = $model->getId($feature['id'], $value, $feature['type']);
                     $value = array('value' => $value, 'id' => $field['feature_value_id']);
                 }
                 if (!empty($field['feature_value_id'])) {
                     $product_features_model->insert($field);
                     $data['features'][$code] = $value;
                 }
             } elseif (is_numeric($code) && is_numeric($value)) {
                 if ($feature = $feature_model->getById($code)) {
                     $field = array('product_id' => $data['product_id'], 'sku_id' => $id, 'feature_id' => $code);
                     $product_features_model->deleteByField($field);
                     if (empty($value)) {
                         continue;
                     }
                     $field['feature_value_id'] = $value;
                     $product_features_model->insert($field);
                     $data['features'][$feature['code']] = $feature_model->getValuesModel($feature['type'])->getFeatureValue($value);
                 }
             }
         }
     }
     if ($correct) {
         $product_model = new shopProductModel();
         $product_model->correct($data['product_id']);
     }
     return $data;
 }
 /**
  * Get stocks info for every sku passed through first argument
  *
  * @param array $sku_ids ID of skus
  * @return array
  *
  * Example array(
  *     '<sku_id>' => array(
  *         '<stock_id>' => array(
  *             'name' => '<Name of stock>',
  *             'count' => null|int
  *         )
  *         ...
  *     )
  *     ...
  * )
  *
  */
 public function getBySkuId($sku_ids)
 {
     if (!$sku_ids) {
         return array();
     }
     $sku_ids = (array) $sku_ids;
     $stock_model = new shopStockModel();
     $stocks = $stock_model->select('id, name, NULL as count')->order('sort')->fetchAll('id', true);
     $data = array();
     $sku_id = null;
     foreach ($this->select('*')->where("sku_id IN (" . implode(',', $sku_ids) . ")")->order("sku_id")->fetchAll() as $item) {
         if ($sku_id != $item['sku_id']) {
             $sku_id = $item['sku_id'];
         }
         $data[$sku_id][$item['stock_id']] = $item['count'];
     }
     foreach ($data as $sku_id => $sku_stocks) {
         $data[$sku_id] = $stocks;
         foreach ($sku_stocks as $stock_id => $count) {
             $data[$sku_id][$stock_id]['count'] = $count;
         }
     }
     return $data;
 }
Example #14
0
 public function execute()
 {
     $product = new shopProduct(waRequest::get('id', 0, waRequest::TYPE_INT));
     if (!$product->id) {
         if (waRequest::get('id') == 'new') {
             $product->name = '';
             $product->id = 'new';
             $product->status = 1;
         } else {
             throw new waException("Product not found", 404);
         }
     }
     $counters = array('reviews' => 0, 'images' => 0, 'pages' => 0, 'services' => 0);
     $sidebar_counters = array();
     $config = $this->getConfig();
     /**
      * @var shopConfig $config
      */
     #load product types
     $type_model = new shopTypeModel();
     $product_types = $type_model->getTypes(true);
     $product_types_count = count($product_types);
     if (intval($product->id)) {
         # 1 fill extra product data
         # 1.1 fill product reviews
         $product_reviews_model = new shopProductReviewsModel();
         $product['reviews'] = $product_reviews_model->getReviews($product->id, 0, $config->getOption('reviews_per_page_product'), 'datetime DESC', array('is_new' => true));
         $counters['reviews'] = $product_reviews_model->count($product->id);
         $sidebar_counters['reviews'] = array('new' => $product_reviews_model->countNew());
         $counters['images'] = count($product['images']);
         $product_pages_model = new shopProductPagesModel();
         $counters['pages'] = $product_pages_model->count($product->id);
         $product_services_model = new shopProductServicesModel();
         $counters['services'] = $product_services_model->countServices($product->id);
         $product_stocks_log_model = new shopProductStocksLogModel();
         $counters['stocks_log'] = $product_stocks_log_model->countByField('product_id', $product->id);
         $this->view->assign('edit_rights', $product->checkRights());
     } else {
         $counters += array_fill_keys(array('images', 'services', 'pages', 'reviews'), 0);
         $product['images'] = array();
         reset($product_types);
         $product->type_id = 0;
         if ($product_types_count) {
             if (!$product_types) {
                 throw new waRightsException(_w("Access denied"));
             } else {
                 reset($product_types);
                 $product->type_id = key($product_types);
             }
         } elseif (!$product->checkRights()) {
             throw new waRightsException(_w("Access denied"));
         }
         $this->view->assign('edit_rights', true);
         $product['skus'] = array('-1' => array('id' => -1, 'sku' => '', 'available' => 1, 'name' => '', 'price' => 0.0, 'purchase_price' => 0.0, 'count' => null, 'stock' => array(), 'virtual' => 0));
         $product->currency = $config->getCurrency();
     }
     $this->assignReportsData($product);
     $stock_model = new shopStockModel();
     $taxes_mode = new shopTaxModel();
     $this->view->assign('stocks', $stock_model->getAll('id'));
     $this->view->assign(array('use_product_currency' => wa()->getSetting('use_product_currency'), 'currencies' => $this->getCurrencies(), 'primary_currency' => $config->getCurrency(), 'taxes' => $taxes_mode->getAll()));
     $category_model = new shopCategoryModel();
     $categories = $category_model->getFullTree('id, name, depth, url, full_url, parent_id', true);
     $frontend_urls = array();
     if (intval($product->id)) {
         $routing = wa()->getRouting();
         $domain_routes = $routing->getByApp($this->getAppId());
         foreach ($domain_routes as $domain => $routes) {
             foreach ($routes as $r) {
                 if (!empty($r['private'])) {
                     continue;
                 }
                 if (empty($r['type_id']) || in_array($product->type_id, (array) $r['type_id'])) {
                     $routing->setRoute($r, $domain);
                     $params = array('product_url' => $product->url);
                     if ($product->category_id && isset($categories[$product->category_id])) {
                         if (!empty($r['url_type']) && $r['url_type'] == 1) {
                             $params['category_url'] = $categories[$product->category_id]['url'];
                         } else {
                             $params['category_url'] = $categories[$product->category_id]['full_url'];
                         }
                     }
                     $frontend_url = $routing->getUrl('/frontend/product', $params, true);
                     $frontend_urls[] = array('url' => $frontend_url);
                 }
             }
         }
     } else {
         $frontend_urls[] = array('url' => wa()->getRouteUrl('/frontend/product', array('product_url' => '%product_url%'), true));
     }
     $stuff = intval($product->id) ? $product->url : '%product_url%';
     foreach ($frontend_urls as &$frontend_url) {
         $pos = strrpos($frontend_url['url'], $stuff);
         $frontend_url['base'] = $pos !== false ? rtrim(substr($frontend_url['url'], 0, $pos), '/') . '/' : $frontend_url['url'];
     }
     unset($frontend_url);
     $product_model = new shopProductModel();
     $this->view->assign('storefront_map', $product_model->getStorefrontMap($product->id));
     /**
      * Backend product profile page
      * UI hook allow extends product profile page
      * @event backend_product
      * @param shopProduct $entry
      * @return array[string][string]string $return[%plugin_id%]['title_suffix'] html output
      * @return array[string][string]string $return[%plugin_id%]['action_button'] html output
      * @return array[string][string]string $return[%plugin_id%]['toolbar_section'] html output
      * @return array[string][string]string $return[%plugin_id%]['image_li'] html output
      */
     $this->view->assign('backend_product', wa()->event('backend_product', $product));
     /**
      * @event backend_product_edit
      */
     $this->view->assign('backend_product_edit', wa()->event('backend_product_edit', $product));
     $this->view->assign('categories', $categories);
     $this->view->assign('counters', $counters);
     $this->view->assign('product', $product);
     $this->view->assign('current_author', shopProductReviewsModel::getAuthorInfo(wa()->getUser()->getId()));
     $this->view->assign('reply_allowed', true);
     $this->view->assign('review_allowed', true);
     $this->view->assign('sidebar_counters', $sidebar_counters);
     $this->view->assign('lang', substr(wa()->getLocale(), 0, 2));
     $this->view->assign('frontend_urls', $frontend_urls);
     $tag_model = new shopTagModel();
     $this->view->assign('popular_tags', $tag_model->popularTags());
     $counts = array();
     // Selectable features
     $features_selectable = $product->features_selectable;
     if (is_array($features_selectable)) {
         foreach ($features_selectable as $f) {
             if ($f['selected']) {
                 $counts[] = $f['selected'];
             }
         }
     }
     $feature_model = new shopTypeFeaturesModel();
     $features_selectable_types = $feature_model->getSkuTypeSelectableTypes();
     foreach ($product_types as $type_id => &$type) {
         $type['sku_type'] = empty($features_selectable_types[$type_id]) ? shopProductModel::SKU_TYPE_FLAT : shopProductModel::SKU_TYPE_SELECTABLE;
     }
     $this->view->assign('features', $features_selectable);
     $this->view->assign('duble', '???');
     $this->view->assign('features_counts', $counts);
     #load product types
     $this->view->assign('product_types', $product_types);
     $this->view->assign('sidebar_width', $config->getSidebarWidth());
 }
Example #15
0
<?php

$model = new waModel();
$stock_model = new shopStockModel();
$n = $stock_model->countAll();
$sql = "\n    UPDATE shop_product_skus s JOIN (\n        SELECT sk.id\n        FROM shop_product_skus sk\n        JOIN shop_product_stocks st ON sk.id = st.sku_id\n        GROUP BY sk.id\n        HAVING COUNT( * ) < {$n}) AS t ON s.id = t.id\n    SET s.count = NULL\n";
$model->exec($sql);
$sql = "\n    UPDATE shop_product p\n    JOIN shop_product_skus s ON s.product_id = p.id\n    SET p.count = NULL\n    WHERE s.count IS NULL\n";
$model->exec($sql);
Example #16
0
 public function getStocks($stock_ids)
 {
     if (!$stock_ids) {
         return array();
     }
     $model = new shopStockModel();
     return $model->getById($stock_ids);
 }
Example #17
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());
    public function execute()
    {
        $this->setLayout(new shopFrontendLayout());
        if ($this->params) {
            $product = $this->params;
        } else {
            $product_model = new shopProductModel();
            $product = $product_model->getByField('url', waRequest::param('product_url'));
        }
        if (!$product) {
            throw new waException(_w('Product not found'), 404);
        }
        if ($types = waRequest::param('type_id')) {
            if (!in_array($product['type_id'], (array) $types)) {
                throw new waException(_w('Product not found'), 404);
            }
        }
        $is_cart = waRequest::get('cart');
        if ($is_cart) {
            $this->setLayout(null);
        }
        $product = new shopProduct($product);
        if (!$is_cart) {
            $this->getBreadcrumbs($product);
        }
        // check url
        $product['num'] = 141;
        if ($product['url'] !== urldecode(waRequest::param('product_url'))) {
            $url_params = array('product_url' => $product['url']);
            if ($product['category_id']) {
                $url_params['category_url'] = $product['category_url'];
            }
            $q = waRequest::server('QUERY_STRING');
            $this->redirect(wa()->getRouteUrl('/frontend/product', $url_params) . ($q ? '?' . $q : ''), 301);
        }
        $this->prepareProduct($product);
        $this->addCanonical();
        // get services
        $type_services_model = new shopTypeServicesModel();
        $services = $type_services_model->getServiceIds($product['type_id']);
        $service_model = new shopServiceModel();
        $product_services_model = new shopProductServicesModel();
        $services = array_merge($services, $product_services_model->getServiceIds($product['id']));
        $services = array_unique($services);
        $services = $service_model->getById($services);
        $variants_model = new shopServiceVariantsModel();
        $rows = $variants_model->getByField('service_id', array_keys($services), true);
        foreach ($rows as $row) {
            if (!$row['price']) {
                $row['price'] = $services[$row['service_id']]['price'];
            }
            $services[$row['service_id']]['variants'][$row['id']] = $row;
        }
        $rows = $product_services_model->getByField('product_id', $product['id'], true);
        $skus_services = array();
        foreach ($product['skus'] as $sku) {
            $skus_services[$sku['id']] = array();
        }
        foreach ($rows as $row) {
            if (!$row['sku_id']) {
                // remove disabled services and variantsimg
                if (!$row['status']) {
                    unset($services[$row['service_id']]['variants'][$row['service_variant_id']]);
                } elseif ($row['price'] !== null) {
                    // update price
                    $services[$row['service_id']]['variants'][$row['service_variant_id']]['price'] = $row['price'];
                }
                if ($row['status'] == shopProductServicesModel::STATUS_DEFAULT) {
                    // update default
                    $services[$row['service_id']]['variant_id'] = $row['service_variant_id'];
                }
            } else {
                if (!$row['status']) {
                    $skus_services[$row['sku_id']][$row['service_id']][$row['service_variant_id']] = false;
                } else {
                    $skus_services[$row['sku_id']][$row['service_id']][$row['service_variant_id']] = $row['price'];
                }
            }
        }
        foreach ($skus_services as $sku_id => &$sku_services) {
            $sku_price = $product['skus'][$sku_id]['price'];
            foreach ($services as $service_id => $service) {
                if (isset($sku_services[$service_id])) {
                    if ($sku_services[$service_id]) {
                        foreach ($service['variants'] as $v) {
                            if (!isset($sku_services[$service_id][$v['id']]) || $sku_services[$service_id][$v['id']] === null) {
                                $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($v['price'], $service['currency'], $sku_price, $product['currency']));
                            } elseif ($sku_services[$service_id][$v['id']]) {
                                $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($sku_services[$service_id][$v['id']], $service['currency'], $sku_price, $product['currency']));
                            }
                        }
                    }
                } else {
                    foreach ($service['variants'] as $v) {
                        $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($v['price'], $service['currency'], $sku_price, $product['currency']));
                    }
                }
            }
        }
        unset($sku_services);
        // disable service if all variants disabled
        foreach ($skus_services as $sku_id => $sku_services) {
            foreach ($sku_services as $service_id => $service) {
                if (is_array($service)) {
                    $disabled = true;
                    foreach ($service as $v) {
                        if ($v !== false) {
                            $disabled = false;
                            break;
                        }
                    }
                    if ($disabled) {
                        $skus_services[$sku_id][$service_id] = false;
                    }
                }
            }
        }
        foreach ($services as $s_id => &$s) {
            if (!$s['variants']) {
                unset($services[$s_id]);
                continue;
            }
            if ($s['currency'] == '%') {
                foreach ($s['variants'] as $v_id => $v) {
                    $s['variants'][$v_id]['price'] = $v['price'] * $product['skus'][$product['sku_id']]['price'] / 100;
                }
                $s['currency'] = $product['currency'];
            }
            if (count($s['variants']) == 1) {
                $v = reset($s['variants']);
                if ($v['name']) {
                    $s['name'] .= ' ' . $v['name'];
                }
                $s['variant_id'] = $v['id'];
                $s['price'] = $v['price'];
                unset($s['variants']);
                foreach ($skus_services as $sku_id => $sku_services) {
                    if (isset($sku_services[$s_id]) && isset($sku_services[$s_id][$v['id']])) {
                        $skus_services[$sku_id][$s_id] = $sku_services[$s_id][$v['id']][1];
                    }
                }
            }
        }
        unset($s);
        uasort($services, array('shopServiceModel', 'sortServices'));
        $this->view->assign('sku_services', $skus_services);
        $this->view->assign('services', $services);
        $compare = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
        $this->view->assign('compare', in_array($product['id'], $compare) ? $compare : array());
        if (!$is_cart) {
            $this->view->assign('reviews', $this->getTopReviews($product['id']));
            $this->view->assign('rates', $this->reviews_model->getProductRates($product['id']));
            $this->view->assign('reviews_total_count', $this->getReviewsTotalCount($product['id']));
            $meta_fields = $this->getMetafields($product);
            $title = $meta_fields['meta_title'] ? $meta_fields['meta_title'] : $product['name'];
            wa()->getResponse()->setTitle($title);
            wa()->getResponse()->setMeta('keywords', $meta_fields['meta_keywords']);
            wa()->getResponse()->setMeta('description', $meta_fields['meta_description']);
            $feature_codes = array_keys($product->features);
            $feature_model = new shopFeatureModel();
            $features = $feature_model->getByCode($feature_codes);
            $this->view->assign('features', $features);
        }
        $this->view->assign('currency_info', $this->getCurrencyInfo());
        /**
         * @event frontend_product
         * @param shopProduct $product
         * @return array[string][string]string $return[%plugin_id%]['menu'] html output
         * @return array[string][string]string $return[%plugin_id%]['cart'] html output
         * @return array[string][string]string $return[%plugin_id%]['block_aux'] html output
         * @return array[string][string]string $return[%plugin_id%]['block'] html output
         */
        $this->view->assign('frontend_product', wa()->event('frontend_product', $product, array('menu', 'cart', 'block_aux', 'block')));
        $sku_stocks = array();
        foreach ($product->skus as $sku) {
            $sku_stocks[$sku_id] = array($sku['count'], $sku['stock']);
        }
        $stock_model = new shopStockModel();
        $this->view->assign('stocks', $stock_model->getAll('id'));
        $duble = db_query("SELECT * FROM shop_product where id=" . $product['id']);
        $dubles = mysql_fetch_assoc($duble);
        $dubles_sku = db_query("SELECT * FROM shop_product_skus where product_id=" . $product['id'] . " and  id=" . $dubles['sku_id']);
        $dubl_sku = mysql_fetch_assoc($dubles_sku);
        $dubles_prod = db_query("SELECT * FROM shop_product_skus where product_id!=" . $product['id'] . " and  sku='" . $dubl_sku['sku'] . "' Group by product_id");
        while ($dubl_product = mysql_fetch_array($dubles_prod)) {
            $dubles_img_pr = db_query("SELECT * FROM shop_product p, shop_product_images img where p.id=" . $dubl_product['product_id'] . " and img.product_id=" . $dubl_product['product_id'] . "");
            $dubles_img = mysql_fetch_assoc($dubles_img_pr);
            if ($dubles_img['status'] != 0) {
                $koldz = substr($dubles_img['product_id'], -2, 2);
                $kolds = str_replace($koldz, '', $dubles_img['product_id']);
                if (preg_match_all("#\\d#", $kolds) < 2) {
                    $kolds = '0' . $kolds;
                }
                if ($kolds == 0) {
                    $kolds = '00';
                }
                $alt_test = db_query("SELECT * FROM shop_product_features_selectable where feature_id=12 and  product_id=" . $dubles_img['product_id'] . "");
                $alt_t = mysql_fetch_assoc($alt_test);
                $alt_value = db_query("SELECT * FROM shop_feature_values_color where id=" . $alt_t['value_id'] . "");
                $alt = mysql_fetch_assoc($alt_value);
                $dubl_p = $dubl_p . ' <a  class="duble_prod"  href="http://' . $_SERVER['HTTP_HOST'] . '/index.php/' . $dubles_img['url'] . '" >
		 
		 
		 <img alt="' . $alt['value'] . '" title="' . $alt['value'] . '"  style="width:50px" src="/wa-data/public/shop/products/' . $koldz . '/' . $kolds . '/' . $dubles_img['product_id'] . '/images/' . $dubles_img['id'] . '/' . $dubles_img['id'] . '.96x96.jpg"/></a>';
                $dubl_p2 = $dubl_p2 . '<a onclick="doubl(' . $dubles_img['product_id'] . ')" class="duble_prod" >
		 
		 
		 <img alt="' . $alt['value'] . '" title="' . $alt['value'] . '" style="width:50px" src="/wa-data/public/shop/products/' . $koldz . '/' . $kolds . '/' . $dubles_img['product_id'] . '/images/' . $dubles_img['id'] . '/' . $dubles_img['id'] . '.96x96.jpg"/></a>';
            }
            $dubl_p = $dubl_p;
            $dubl_p2 = $dubl_p2;
        }
        $this->view->assign('duble', $dubl_p);
        $this->view->assign('duble2', $dubl_p2);
        $this->view->assign('duble_list', $dubl_p);
        $product['num'] = $_GET['num'];
        $this->view->assign('numis', $_GET['num']);
        $this->setThemeTemplate($is_cart ? 'product.cart.html' : 'product.html');
    }
 public function execute($data = null)
 {
     if (wa()->getEnv() == 'frontend') {
         // Now we are in frontend, so fill stock_id for items. Stock_id get from storefront-settings
         // But:
         //   - some skus may have not any stock
         //   - stock_id from storefront isn't setted (empty)
         $sku_ids = array();
         foreach ($data['items'] as $item) {
             if ($item['type'] == 'product') {
                 $sku_ids[] = (int) $item['sku_id'];
             }
         }
         $product_stocks_model = new shopProductStocksModel();
         $sku_ids = $product_stocks_model->filterSkusByNoStocks($sku_ids);
         $sku_ids_map = array_fill_keys($sku_ids, true);
         // storefront stock-id
         $stock_id = waRequest::param('stock_id');
         $stock_model = new shopStockModel();
         if (!$stock_id || !$stock_model->stockExists($stock_id)) {
             $stock_id = $stock_model->select('id')->order('sort')->limit(1)->fetchField();
         }
         foreach ($data['items'] as &$item) {
             if ($item['type'] == 'product') {
                 if (!isset($sku_ids_map[$item['sku_id']])) {
                     // have stocks
                     $item['stock_id'] = $stock_id;
                 }
             }
         }
     }
     $currency = wa()->getConfig()->getCurrency(false);
     $rate_model = new shopCurrencyModel();
     $row = $rate_model->getById($currency);
     $rate = $row['rate'];
     // Save contact
     if (isset($data['contact'])) {
         if (is_numeric($data['contact'])) {
             $contact = new waContact($data['contact']);
         } else {
             /**
              * @var waContact $contact
              */
             $contact = $data['contact'];
             if (!$contact->getId()) {
                 $contact->save();
                 // if user has been created
                 if ($contact['password']) {
                     $signup_action = new shopSignupAction();
                     $signup_action->send($contact);
                 }
             }
         }
     } else {
         $data['contact'] = $contact = wa()->getUser();
     }
     $subtotal = 0;
     foreach ($data['items'] as &$item) {
         if ($currency != $item['currency']) {
             $item['price'] = shop_currency($item['price'], $item['currency'], null, false);
             if (!empty($item['purchase_price'])) {
                 $item['purchase_price'] = shop_currency($item['purchase_price'], $item['currency'], null, false);
             }
             $item['currency'] = $currency;
         }
         $subtotal += $item['price'] * $item['quantity'];
     }
     unset($item);
     if ($data['discount'] === '') {
         $data['total'] = $subtotal;
         $data['discount'] = shopDiscounts::apply($data);
     }
     $shipping_address = $contact->getFirst('address.shipping');
     if (!$shipping_address) {
         $shipping_address = $contact->getFirst('address');
     }
     $billing_address = $contact->getFirst('address.billing');
     if (!$billing_address) {
         $billing_address = $contact->getFirst('address');
     }
     $discount_rate = $subtotal ? $data['discount'] / $subtotal : 0;
     $taxes = shopTaxes::apply($data['items'], array('shipping' => isset($shipping_address['data']) ? $shipping_address['data'] : array(), 'billing' => isset($billing_address['data']) ? $billing_address['data'] : array(), 'discount_rate' => $discount_rate));
     $tax = $tax_included = 0;
     foreach ($taxes as $t) {
         if (isset($t['sum'])) {
             $tax += $t['sum'];
         }
         if (isset($t['sum_included'])) {
             $tax_included += $t['sum_included'];
         }
     }
     $order = array('state_id' => 'new', 'total' => $subtotal - $data['discount'] + $data['shipping'] + $tax, 'currency' => $currency, 'rate' => $rate, 'tax' => $tax_included + $tax, 'discount' => $data['discount'], 'shipping' => $data['shipping'], 'comment' => isset($data['comment']) ? $data['comment'] : '');
     $order['contact_id'] = $contact->getId();
     // Add contact to 'shop' category
     $contact->addToCategory('shop');
     // Save order
     $order_model = new shopOrderModel();
     $order_id = $order_model->insert($order);
     // Create record in shop_customer, or update existing record
     $scm = new shopCustomerModel();
     $scm->updateFromNewOrder($order['contact_id'], $order_id);
     // save items
     $items_model = new shopOrderItemsModel();
     $parent_id = null;
     foreach ($data['items'] as $item) {
         $item['order_id'] = $order_id;
         if ($item['type'] == 'product') {
             $parent_id = $items_model->insert($item);
         } elseif ($item['type'] == 'service') {
             $item['parent_id'] = $parent_id;
             $items_model->insert($item);
         }
     }
     // Order params
     if (empty($data['params'])) {
         $data['params'] = array();
     }
     $data['params']['auth_code'] = self::generateAuthCode($order_id);
     $data['params']['auth_pin'] = self::generateAuthPin();
     // Save params
     $params_model = new shopOrderParamsModel();
     $params_model->set($order_id, $data['params']);
     $log_model = new waLogModel();
     $log_model->add('order_create', $order_id, null, $order['contact_id']);
     return array('order_id' => $order_id, 'contact_id' => wa()->getEnv() == 'frontend' ? $contact->getId() : wa()->getUser()->getId());
 }
Example #20
0
 /**
  * Returns HTML code of stock icon (normal, low, critical).
  *
  * @param int|null $count SKU stock count; if not specified, normal icon is returned
  * @param int|null $stock_id Id of stock whose limit settings must be taken into account; if not specified, default values 5 and 2 are used
  * @param bool $include_text Whether text '*** items left' must be added to icon
  * @return string
  */
 public static function getStockCountIcon($count, $stock_id = null, $include_text = false)
 {
     static $stocks = array();
     if (!$stocks) {
         $model = new shopStockModel();
         $stocks = $model->getAll('id');
     }
     if ($count === null) {
         $icon = "<i class='icon10 status-green' title='" . _w("In stock") . "'></i>";
     } else {
         if (!$stock_id || empty($stocks[$stock_id])) {
             $bounds = array('critical_count' => shopStockModel::CRITICAL_DEFAULT, 'low_count' => shopStockModel::LOW_DEFAULT);
         } else {
             $bounds = $stocks[$stock_id];
         }
         if ($count <= $bounds['critical_count']) {
             $icon = "<i class='icon10 status-red' title='" . _w("Out of stock") . "'></i>";
             $warn = 's-stock-warning-none';
         } elseif ($count > $bounds['critical_count'] && $count <= $bounds['low_count']) {
             $icon = "<i class='icon10 status-yellow' title='" . _w("Low stock") . "'></i>";
             $warn = 's-stock-warning-low';
         } else {
             $icon = "<i class='icon10 status-green' title='" . _w("In stock") . "'></i>";
             $warn = '';
         }
         if ($count !== null && $include_text) {
             $icon .= "<span class='small {$warn}'>{$count} left</span>";
         }
     }
     return $icon;
 }
 private function workupList(&$list, $fields)
 {
     if (!$list) {
         return;
     }
     foreach ($list as &$v) {
         $v['icon'] = shopProductStocksLogModel::getIcon($v['type']);
         if (!$v['description']) {
             if ($v['after_count'] === null) {
                 $v['description'] = _w('In stock value updated to ∞');
             } else {
                 $v['description'] = sprintf(_w('In stock value updated to %d'), $v['after_count']);
             }
         } else {
             if ($v['type'] == self::TYPE_ORDER) {
                 $v['description'] = sprintf(_w($v['description']), '<a href="?action=orders#/order/' . $v['order_id'] . '/">' . shopHelper::encodeOrderId($v['order_id']) . '</a>');
             }
         }
     }
     unset($v);
     $stock_ids = array();
     foreach ($list as $v) {
         $stock_ids[] = $v['stock_id'];
     }
     $model = new shopStockModel();
     $stocks = $model->getByField('id', array_unique($stock_ids), 'id');
     foreach ($list as &$v) {
         if (isset($stocks[$v['stock_id']])) {
             $v['stock_name'] = $stocks[$v['stock_id']]['name'];
         }
     }
     unset($v);
     foreach ($fields as $f) {
         if ($f == 'sku_name') {
             $sku_ids = array();
             foreach ($list as $v) {
                 $sku_ids[] = $v['sku_id'];
             }
             $model = new shopProductSkusModel();
             $skus = $model->select('id,sku,name')->where("id IN(" . implode(',', array_unique($sku_ids)) . ")")->fetchAll('id');
             foreach ($list as &$v) {
                 if (isset($skus[$v['sku_id']])) {
                     $v['sku_name'] = $skus[$v['sku_id']]['name'];
                     if ($v['sku_name']) {
                         if ($skus[$v['sku_id']]['sku']) {
                             $v['sku_name'] .= ' (' . $skus[$v['sku_id']]['sku'] . ')';
                         }
                     } else {
                         if ($skus[$v['sku_id']]['sku']) {
                             $v['sku_name'] = $skus[$v['sku_id']]['sku'];
                         }
                     }
                 }
             }
             unset($v);
         }
         if ($f == 'product_name') {
             $product_ids = array();
             foreach ($list as $v) {
                 $product_ids[] = $v['product_id'];
             }
             $model = new shopProductModel();
             $products = $model->select('id,name')->where("id IN (" . implode(',', array_unique($product_ids)) . ")")->fetchAll('id');
             foreach ($list as &$v) {
                 if (isset($products[$v['product_id']])) {
                     $v['product_name'] = $products[$v['product_id']]['name'];
                 }
             }
             unset($v);
         }
     }
 }
Example #22
0
<?php

$stock_model = new shopStockModel();
$n = $stock_model->countAll();
if ($n > 0) {
    // repair invariant: all N stocks exists, but sku_cout IS NULL
    $sql = "\n    UPDATE shop_product_skus s JOIN (        \n        SELECT sk.id, SUM(st.count) cnt\n        FROM shop_product_skus sk\n        JOIN shop_product_stocks st ON sk.id = st.sku_id\n        WHERE sk.count IS NULL\n        GROUP BY sk.id\n        HAVING COUNT( * ) = {$n}\n    ) AS t ON s.id = t.id\n    SET s.count = t.cnt";
    $stock_model->exec($sql);
    $product_model = new shopProductModel();
    $product_model->correctCount();
}
 public function execute()
 {
     $stock_model = new shopStockModel();
     $this->response = $stock_model->getAll();
     $this->response['_element'] = 'stock';
 }
Example #24
0
 /**
  * Get aggregated data about placing products(skus) in stocks
  *
  * @see getProductStocks
  *
  * @param int|array $product_id
  * @param string $order
  * @return array
  */
 public function getProductStocksByProductId($product_id, $order = 'desc')
 {
     if (!$product_id) {
         return array();
     }
     $product_ids = (array) $product_id;
     $product_ids_str = implode(',', $product_ids);
     $order = $order == 'desc' || $order == 'DESC' ? 'DESC' : 'ASC';
     // necessary models
     $stock_model = new shopStockModel();
     $product_images_model = new shopProductImagesModel();
     // stock ids of items ordered by sort
     $stock_ids = array_keys($stock_model->getAll('id'));
     // get products
     $sql = "\n            SELECT id, name, count, image_id\n            FROM {$this->table}\n            WHERE id IN ( {$product_ids_str} )\n            ORDER BY count {$order}\n        ";
     $data = array();
     $image_ids = array();
     foreach ($this->query($sql) as $item) {
         $data[$item['id']] = array('id' => $item['id'], 'name' => $item['name'], 'url_crop_small' => null, 'count' => $item['count'], 'skus' => array(), 'stocks' => array());
         if ($item['image_id'] != null) {
             $image_ids[] = $item['image_id'];
         }
     }
     if (!$data) {
         return array();
     }
     $product_ids = array_keys($data);
     $product_ids_str = implode(',', $product_ids);
     $images = $product_images_model->getByField('id', $image_ids, 'product_id');
     $size = wa()->getConfig()->getImageSize('crop_small');
     // get for skus number of stocks in which it presents
     $sql = "\n            SELECT sk.id, COUNT(sk.id) num_of_stocks\n            FROM shop_product_skus sk\n            JOIN shop_product_stocks st ON sk.id = st.sku_id\n            WHERE sk.product_id IN ( {$product_ids_str} )\n            GROUP BY sk.id\n        ";
     $num_of_stocks = $this->query($sql)->fetchAll('id', true);
     // get info about skus and stocks
     $sql = "SELECT\n                    sk.product_id,\n                    sk.id AS sku_id,\n                    sk.name AS sku_name,\n                    sk.count,\n\n                    pst.stock_id,\n                    pst.count AS stock_count\n                FROM shop_product_skus sk\n                LEFT JOIN shop_product_stocks pst ON pst.sku_id = sk.id\n                WHERE sk.product_id IN ( {$product_ids_str} )\n                ORDER BY sk.product_id, sk.count {$order}, sk.id";
     $stocks_count = count($stock_ids);
     // temporary aggragating info about stocks
     $sku_stocks = array();
     if ($stocks_count) {
         $sku_stocks = array_fill(0, $stocks_count, array());
     }
     $sku_id = 0;
     $product_id = 0;
     $p_product = null;
     foreach ($this->query($sql) as $item) {
         // another product
         if ($product_id != $item['product_id']) {
             $product_id = $item['product_id'];
             $p_product =& $data[$product_id];
             if (isset($images[$product_id])) {
                 $p_product['url_crop_small'] = shopImage::getUrl($images[$product_id], $size);
             }
         }
         // another sku
         if ($sku_id != $item['sku_id']) {
             $sku_id = $item['sku_id'];
             $p_product['skus'][$sku_id] = array('id' => $sku_id, 'name' => $item['sku_name'], 'count' => $item['count'], 'num_of_stocks' => isset($num_of_stocks[$sku_id]) ? $num_of_stocks[$sku_id] : 0);
         }
         // aggregate info about stocks
         if ($item['stock_id'] !== null) {
             $sku_stocks[$item['stock_id']][$sku_id] = $item['stock_count'];
         }
     }
     // lay out stocks info
     if (!empty($sku_stocks)) {
         foreach ($data as &$product) {
             foreach ($stock_ids as $stock_id) {
                 foreach ($product['skus'] as $sku_id => $sku) {
                     $product['stocks'][$stock_id][$sku_id] = array('id' => $sku_id, 'name' => $sku['name'], 'count' => isset($sku_stocks[$stock_id][$sku_id]) ? $sku_stocks[$stock_id][$sku_id] : null, 'num_of_stocks' => $sku['num_of_stocks']);
                 }
             }
         }
         unset($product);
     }
     return $data;
 }