public static function formatValue($c, $curr = null) { static $currencies = null; if ($currencies === null) { if ($curr) { $currencies = $curr; } else { $curm = new shopCurrencyModel(); $currencies = $curm->getAll('code'); } } if ($c['type'] == '$FS') { return _w('Free shipping'); } else { if ($c['type'] === '%') { return waCurrency::format('%0', $c['value'], 'USD') . '%'; } else { if (!empty($currencies[$c['type']])) { return waCurrency::format('%0{s}', $c['value'], $c['type']); } else { // Coupon of unknown type. Possibly from a plugin?.. return ''; } } } }
public function save($data, $id = 0, $not_delete_products = false) { $primary_currency = wa('shop')->getConfig()->getCurrency(); if (empty($data['currency'])) { $data['currency'] = $primary_currency; } $just_inserted = false; if (!$id) { $id = $this->insert(array('name' => $data['name'], 'price' => 0, 'currency' => $data['currency'], 'tax_id' => isset($data['tax_id']) ? $data['tax_id'] : ($data['tax_id'] === null ? null : 0), 'variant_id' => 0)); if (!$id) { return false; } $just_inserted = true; } else { $id = (int) $id; } if ($id) { $this->updateVariants($id, $data['variants']); $this->updateTypes($id, !empty($data['types']) ? $data['types'] : array()); if (!empty($data['products'])) { $this->updateProducts($id, $data['products']); } if (!$just_inserted) { $update = array(); $fields = array('name', 'currency', 'price', 'tax_id'); foreach ($fields as $field) { if (isset($data[$field])) { $update[$field] = $data[$field]; } else { if ($field === 'tax_id' && $data[$field] === null) { $update[$field] = $data[$field]; } } } if ($update) { $this->updateById($id, $update); } } } $currency = $data['currency']; // update primary price if ($currency != '%') { $currency_model = new shopCurrencyModel(); $rate = $currency_model->getRate($currency); } else { $rate = 1; // hack for percents } $sql = "UPDATE `shop_service_variants`\n SET primary_price = price*{$rate}\n WHERE service_id = {$id}"; $this->exec($sql); $sql = "UPDATE `shop_product_services` ps\n SET ps.primary_price = ps.price*{$rate}\n WHERE ps.service_id = {$id} AND ps.price IS NOT NULL"; $this->exec($sql); $sql = "UPDATE `shop_service` s\n JOIN `shop_service_variants` sv ON s.id = sv.service_id AND s.variant_id = sv.id\n SET s.price = sv.primary_price\n WHERE s.id = {$id}"; $this->exec($sql); return $id; }
public function execute() { $code = waRequest::get('code', '', waRequest::TYPE_STRING_TRIM); $model = new shopCurrencyModel(); $currency = $model->getById($code); if (!$currency) { throw new waException(_w("Unknown currency")); } $this->view->assign(array('currency' => $currency, 'currencies' => $model->getCurrencies(), 'product_count' => $this->getProductCount($code))); }
public function __construct($coupon = array()) { waLocale::loadByDomain(array('shop', 'coupon')); waSystem::pushActivePlugin('coupon', 'shop'); $this->data['code'] = ifempty($coupon['code'], ''); $this->data['expire'] = ifempty($coupon['expire_datetime']); $curm = new shopCurrencyModel(); $currencies = $curm->getAll('code'); $this->data['discount'] = shopCouponPlugin::formatValue($coupon, $currencies); waSystem::popActivePlugin(); }
public function execute() { $model = new shopCurrencyModel(); $currencies = $model->getCurrencies(); foreach ($currencies as &$c) { $c['rate'] = $this->formatFloat($c['rate']); } unset($c); $primary = $this->getConfig()->getCurrency(); $system_currencies = $this->getSystemCurrencies(); $this->view->assign(array('currencies' => $currencies, 'primary' => $primary, 'use_product_currency' => wa()->getSetting('use_product_currency'), 'system_currencies' => $system_currencies, 'rest_system_currencies' => array_diff_key($system_currencies, $currencies), 'product_count' => $this->getProductCount($primary))); }
public function execute() { $code = waRequest::post('code', '', waRequest::TYPE_STRING_TRIM); if (!$code) { $this->errors[] = _w("Unknown currency"); return; } $currency_model = new shopCurrencyModel(); if (!$currency_model->setPrimaryCurrency($code, (bool) waRequest::post('convert'))) { $this->errors[] = _w("Error when change"); return; } }
public function execute() { $code = waRequest::post('code', '', waRequest::TYPE_STRING_TRIM); if (!$code) { $this->errors[] = _w("Unknown code"); return; } $currency_model = new shopCurrencyModel(); if (!$currency_model->add($code)) { $this->errors[] = _w("Unknown code"); return; } }
public function execute() { $code = waRequest::get('code', '', waRequest::TYPE_STRING_TRIM); $to = waRequest::post('to', null, waRequest::TYPE_STRING_TRIM); if ($code == $this->getConfig()->getCurrency()) { $this->errors[] = "Couldn't delete primary currency"; return; } if (!$code) { throw new waException(_w("Unknown currency")); } $currency_model = new shopCurrencyModel(); $currency_model->removeCurrency($code, $to); }
public function execute() { $item = waRequest::post('item', '', waRequest::TYPE_STRING_TRIM); $before = waRequest::post('before', null, waRequest::TYPE_STRING_TRIM); if (!$item) { $this->errors[] = _w("Error when move"); return; } $currency_model = new shopCurrencyModel(); if (!$currency_model->move($item, $before)) { $this->errors[] = _w("Error when move"); return; } }
public function execute() { $code = waRequest::post('code', '', waRequest::TYPE_STRING_TRIM); $rate = (double) waRequest::post('rate', 0); if (!$code) { $this->errors[] = _w("Error when change currency"); return; } if ($rate <= 0) { $this->errors[] = _w("Error when change currency"); } $currency_model = new shopCurrencyModel(); if (!$currency_model->changeRate($code, $rate)) { $this->errors[] = _w("Error when change currency"); return; } }
private function convertPrice($price, $from) { if (!$this->currency_model) { $this->currency_model = new shopCurrencyModel(); } if (!$this->primary_currency) { $this->primary_currency = wa('shop')->getConfig()->getCurrency(); } return $this->currency_model->convert($price, $from, $this->primary_currency); }
/** * @param int $id * @return bool */ public function correct($id) { if (!$id) { return false; } $id = (int) $id; $product = $this->getById($id); $product_skus_model = new shopProductSkusModel(); $skus = $product_skus_model->getDataByProductId($id, true); $currency_model = new shopCurrencyModel(); $currency = wa('shop')->getConfig()->getCurrency(); $price = array(); $update_product_data = array(); // aggregate count by stocks for product // Invariant: if at least one sku.count IS NULL this aggregate count IS NULL $product_count = 0; $available_sku_count = 0; foreach ($skus as $sku) { if ($sku['available']) { $available_sku_count++; } $price[] = $this->castValue('double', $sku['price']); $sku_count = 0; $num_of_null = 0; foreach ($sku['stock'] as $count) { if ($count === null) { // turn into NULL and is not longer changing $sku_count = null; $num_of_null++; } else { // Once turned into NULL value is not changed if ($sku_count !== null) { $sku_count += $count; } } } if ($num_of_null == count($sku['stock'])) { // all stock count is null means that not multistocking $sku_count = $sku['count']; } // maintain product_count invariant. See above if ($sku['available']) { if ($sku_count === null) { $product_count = null; } elseif ($product_count !== null) { $product_count += $sku_count; } } } if ($available_sku_count == 0) { $product_count = 0; } if (!$price) { $price[] = 0; } $update_product_data['sku_count'] = count($skus); $update_product_data['min_price'] = $currency_model->convert(min($price), $product['currency'], $currency); $update_product_data['max_price'] = $currency_model->convert(max($price), $product['currency'], $currency); $update_product_data['price'] = $currency_model->convert($skus[$product['sku_id']]['price'], $product['currency'], $currency); if (isset($skus[$product['sku_id']]['compare_price'])) { $update_product_data['compare_price'] = $currency_model->convert($skus[$product['sku_id']]['compare_price'], $product['currency'], $currency); } $update_product_data['count'] = $product_count; $this->updateById($product['id'], $update_product_data); return true; }
private function reset() { /** * @event reset * * Notify plugins about reset all settings * * @param void * @return void */ wa()->event('reset'); //XXX hardcode $tables = array('shop_page', 'shop_page_params', 'shop_category', 'shop_category_params', 'shop_category_products', 'shop_category_routes', 'shop_product', 'shop_product_params', 'shop_product_features', 'shop_product_features_selectable', 'shop_product_images', 'shop_product_pages', 'shop_product_related', 'shop_product_reviews', 'shop_product_services', 'shop_product_skus', 'shop_product_stocks', 'shop_product_stocks_log', 'shop_search_index', 'shop_search_word', 'shop_tag', 'shop_product_tags', 'shop_set', 'shop_set_products', 'shop_stock', 'shop_feature', 'shop_feature_values_dimension', 'shop_feature_values_double', 'shop_feature_values_text', 'shop_feature_values_varchar', 'shop_feature_values_color', 'shop_feature_values_range', 'shop_type', 'shop_type_features', 'shop_type_services', 'shop_type_upselling', 'shop_service', 'shop_service_variants', 'shop_currency', 'shop_customer', 'shop_cart_items', 'shop_order', 'shop_order_items', 'shop_order_log', 'shop_order_log_params', 'shop_order_params', 'shop_affiliate_transaction', 'shop_checkout_flow', 'shop_notification', 'shop_notification_params', 'shop_coupon', 'shop_discount_by_sum', 'shop_tax', 'shop_tax_regions', 'shop_tax_zip_codes', 'shop_affiliate_transaction', 'shop_importexport'); $model = new waModel(); foreach ($tables as $table) { $exist = false; try { $model->query(sprintf("SELECT * FROM `%s` WHERE 0", $table)); $exist = true; $model->query(sprintf("TRUNCATE `%s`", $table)); } catch (waDbException $ex) { if ($exist) { throw $ex; } } } $sqls = array(); $sqls[] = 'UPDATE`shop_type` SET`count` = 0'; $sqls[] = 'UPDATE`shop_set` SET`count` = 0'; foreach ($sqls as $sql) { $model->query($sql); } $ccm = new waContactCategoryModel(); $ccm->deleteByField('app_id', 'shop'); $app_settings_model = new waAppSettingsModel(); $currency_model = new shopCurrencyModel(); $currency_model->insert(array('code' => 'USD', 'rate' => 1.0, 'sort' => 1), 2); $app_settings_model->set('shop', 'currency', 'USD'); $app_settings_model->set('shop', 'use_product_currency', true); $paths = array(); $paths[] = wa()->getDataPath('products', false, 'shop'); $paths[] = wa()->getDataPath('products', true, 'shop'); $paths[] = wa()->getTempPath(); $config_path = wa()->getConfigPath('shop'); foreach (waFiles::listdir($config_path, true) as $path) { if (!in_array($path, array('plugins.php', '..', '.'))) { $paths[] = $config_path . '/' . $path; } } $paths[] = wa()->getCachePath(null, 'shop'); foreach ($paths as $path) { waFiles::delete($path, true); } $path = wa()->getDataPath('products', true, 'shop'); waFiles::write($path . '/thumb.php', '<?php $file = realpath(dirname(__FILE__)."/../../../../")."/wa-apps/shop/lib/config/data/thumb.php"; if (file_exists($file)) { include($file); } else { header("HTTP/1.0 404 Not Found"); } '); waFiles::copy($this->getConfig()->getAppPath('lib/config/data/.htaccess'), $path . '/.htaccess'); echo json_encode(array('result' => 'ok', 'redirect' => '?action=welcome')); exit; }
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()); }
<?php $path = wa()->getDataPath('products', true, 'shop'); waFiles::write($path . '/thumb.php', '<?php $file = realpath(dirname(__FILE__)."/../../../../")."/wa-apps/shop/lib/config/data/thumb.php"; if (file_exists($file)) { include($file); } else { header("HTTP/1.0 404 Not Found"); } '); waFiles::copy(wa()->getAppPath('lib/config/data/.htaccess', 'shop'), $path . '/.htaccess'); $currency_model = new shopCurrencyModel(); $model = new waAppSettingsModel(); $model->set('shop', 'welcome', 1); if ($currency_model->countAll() == 0) { $currency_model->insert(array('code' => 'USD', 'rate' => 1.0, 'sort' => 1), 2); $model->set('shop', 'currency', 'USD'); $model->set('shop', 'use_product_currency', 'true'); } // 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;
public static function discount(&$order, $contact, $apply, $other_discounts) { if (!$contact || !$contact->getId()) { return 0; } $checkout_data = wa()->getStorage()->read('shop/checkout'); if (empty($checkout_data['use_affiliate'])) { return 0; // !!! Will this fail when recalculating existing order? } $usage_rate = (double) wa()->getSetting('affiliate_usage_rate', 0, 'shop'); if ($usage_rate <= 0) { return 0; } $cm = new shopCustomerModel(); $customer = $cm->getById($contact->getId()); if (!$customer || $customer['affiliate_bonus'] <= 0) { return 0; } $order_total = $order['total'] - $other_discounts; $max_bonus = $customer['affiliate_bonus']; if (!empty($order['params']['affiliate_bonus'])) { // Recalculating existing order: take old discount into account $max_bonus += $order['params']['affiliate_bonus']; } $crm = new shopCurrencyModel(); $discount = (double) $crm->convert($max_bonus * $usage_rate, wa()->getConfig()->getCurrency(true), wa()->getConfig()->getCurrency(false)); if ($discount > $order_total) { $discount = $order_total; } if ($discount < $order_total) { $bonus_used = $max_bonus; } else { $bonus_used = (double) $crm->convert($discount, wa()->getConfig()->getCurrency(false), wa()->getConfig()->getCurrency(true)) / $usage_rate; } if (empty($order['params'])) { $order['params'] = array(); } $order['params']['affiliate_bonus'] = $bonus_used; if ($apply) { $balance_change = $max_bonus - $bonus_used - $customer['affiliate_bonus']; if (abs($balance_change) > 0.0001) { if (!empty($order['params']['affiliate_bonus'])) { $message = sprintf_wp('Recalculation of order total, new discount: %s', waCurrency::format('%{s}', $discount, wa()->getConfig()->getCurrency())); } else { $message = sprintf_wp('Discount of %s', waCurrency::format('%{s}', $discount, wa()->getConfig()->getCurrency())); } $atm = new shopAffiliateTransactionModel(); $atm->applyBonus($contact->getId(), $balance_change, ifset($order['id']), $message); } } return $discount; }
public function execute() { $id = waRequest::request('id', 0, 'int'); $m = new shopCouponPluginTemplateModel(); $gen = $m->getById($id); if ($gen) { $gen['value'] = (double) $gen['value']; if (waRequest::request('delete')) { $m->deleteById($id); exit; } } else { if ($id) { throw new waException('Generator not found.', 404); } else { // show form to create new coupon $gen = $m->getEmptyRow(); } } $is_new = false; if (waRequest::post()) { $post_gen = waRequest::post('gen'); if (is_array($post_gen)) { $post_gen = array_intersect_key($post_gen, $gen) + array('type' => '%'); if (empty($post_gen['limit'])) { $post_gen['limit'] = null; } if (!empty($post_gen['value'])) { $post_gen['value'] = (double) str_replace(',', '.', $post_gen['value']); } if ($post_gen['type'] == '%') { $post_gen['value'] = min(max($post_gen['value'], 0), 100); } if (empty($post_gen['expire_hours'])) { $post_gen['expire_hours'] = null; } foreach (array('expire_hours', 'num', 'latin_lowercase', 'latin_uppercase', 'cyr_lowercase', 'cyr_uppercase', 'other') as $k) { if (empty($post_gen[$k])) { $post_gen[$k] = null; } } if ($id) { $m->updateById($id, $post_gen); $gen = $m->getById($id); } else { $post_gen['create_contact_id'] = wa()->getUser()->getId(); try { $id = $m->insert($post_gen); $gen = $m->getById($id); $is_new = true; } catch (waDbException $e) { // Duplicate code. Show error in form. $gen = $post_gen + $gen; } } } } // Coupon types $curm = new shopCurrencyModel(); $currencies = $curm->getAll('code'); $types = self::getTypes($currencies); $this->view->assign('types', $types); $this->view->assign('gen', $gen); $this->view->assign('is_new', $is_new); $this->view->assign('formatted_value', shopCouponPlugin::formatValue($gen, $currencies)); }
/** * @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(' ', ' ', $item); $item = str_replace('&', '&', $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(' ', ' ', $value); $value = str_replace('&', '&', $value); $value = $this->sprintf($format, $value); } return $value; }
public static function settingsPrimaryCurrencies() { $primary = self::getConfigParam('primary_currency'); $currencies = array(); $model = new shopCurrencyModel(); if ($available_currencies = $model->getCurrencies($primary)) { $config = wa('shop')->getConfig(); /** * @var shopConfig $config */ $default = $config->getCurrency(); if (isset($currencies[$default])) { $currencies['auto'] = array('value' => 'auto', 'title' => $default . ' - Основная валюта магазина.', 'rate' => 0); } foreach ($available_currencies as $currency) { $currencies[$currency['code']] = array('value' => $currency['code'], 'title' => $currency['code'] . ' - ' . $currency['title'], 'rate' => $currency['rate']); } } return $currencies; }
public function getCurrencies() { $model = new shopCurrencyModel(); return $model->getCurrencies(); }
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; //} }
protected function getCurrencies() { $model = new shopCurrencyModel(); return $model->getCurrencies(); }
public function execute() { $id = waRequest::request('id', 0, 'int'); $coupm = new shopCouponModel(); $coupon = $coupm->getById($id); if ($coupon) { $coupon['value'] = (double) $coupon['value']; if (waRequest::request('delete')) { $coupm->delete($id); exit; } } else { if ($id) { throw new waException('Coupon not found.', 404); } else { // show form to create new coupon $coupon = $coupm->getEmptyRow(); $coupon['code'] = self::generateCode(); } } // // Process POST data // $duplicate_code_error = null; if (waRequest::post()) { $post_coupon = waRequest::post('coupon'); if (is_array($post_coupon)) { $post_coupon = array_intersect_key($post_coupon, $coupon) + array('code' => '', 'type' => '%'); if (empty($post_coupon['limit'])) { $post_coupon['limit'] = null; } if (!empty($post_coupon['value'])) { $post_coupon['value'] = (double) str_replace(',', '.', $post_coupon['value']); } if (empty($post_coupon['code'])) { throw new waException('Bad parameters', 500); // rely on JS validation } if (!empty($post_coupon['expire_datetime']) && strlen($post_coupon['expire_datetime']) == 10) { $post_coupon['expire_datetime'] .= ' 23:59:59'; } if ($post_coupon['type'] == '%') { $post_coupon['value'] = min(max($post_coupon['value'], 0), 100); } if ($id) { $coupm->updateById($id, $post_coupon); echo '<script>window.location.hash = "#/coupons/' . $id . '";$.orders.dispatch();</script>'; exit; } else { $post_coupon['create_contact_id'] = wa()->getUser()->getId(); $post_coupon['create_datetime'] = date('Y-m-d H:i:s'); try { $id = $coupm->insert($post_coupon); echo '<script>' . 'var counter = $("#s-coupons .count");' . 'var cnt = parseInt(counter.text(), 10) || 0;' . 'counter.text(cnt + 1);' . 'window.location.hash = "#/coupons/' . $id . '";' . '</script>'; exit; } catch (waDbException $e) { // Duplicate code. Show error in form. $coupon = $post_coupon + $coupon; $duplicate_code_error = true; } } } } // Coupon types $curm = new shopCurrencyModel(); $currencies = $curm->getAll('code'); $types = self::getTypes($currencies); // Orders this coupon was used for $orders = array(); $overall_discount = 0; $overall_discount_formatted = ''; if ($coupon['id']) { $om = new shopOrderModel(); $cm = new shopCurrencyModel(); $orders = $om->getByCoupon($coupon['id']); shopHelper::workupOrders($orders); foreach ($orders as &$o) { $discount = ifset($o['params']['coupon_discount'], 0); $o['coupon_discount_formatted'] = waCurrency::format('%{s}', $discount, $o['currency']); if ($discount) { $overall_discount += $cm->convert($discount, $o['currency'], $cm->getPrimaryCurrency()); $o['coupon_discount_percent'] = round($discount * 100.0 / ($discount + $o['total']), 1); } else { $o['coupon_discount_percent'] = 0; } } unset($o); $overall_discount_formatted = waCurrency::format('%{s}', $overall_discount, $cm->getPrimaryCurrency()); } $this->view->assign('types', $types); $this->view->assign('orders', $orders); $this->view->assign('coupon', $coupon); $this->view->assign('duplicate_code_error', $duplicate_code_error); $this->view->assign('overall_discount', $overall_discount); $this->view->assign('overall_discount_formatted', $overall_discount_formatted); $this->view->assign('formatted_value', shopCouponsAction::formatValue($coupon, $currencies)); $this->view->assign('is_enabled', shopCouponsAction::isEnabled($coupon)); }
public function getTotalSkuSalesByProduct($product_id, $product_currency = null) { if ($product_currency) { $currency_model = new shopCurrencyModel(); $rate = $currency_model->getRate($product_currency); if (!$rate) { $rate = 1; } } else { $rate = 1; } $sql = "SELECT sku_id, SUM(oi.price * o.rate * oi.quantity) total, SUM(oi.quantity) quantity,\n SUM(IF(oi.purchase_price > 0, oi.purchase_price*o.rate, ps.purchase_price*" . $this->escape($rate) . ")*oi.quantity) purchase\n FROM " . $this->table . " o\n JOIN shop_order_items oi ON o.id = oi.order_id AND oi.product_id = i:product_id AND oi.type = 'product'\n JOIN shop_product_skus ps ON oi.sku_id = ps.id\n WHERE paid_date >= DATE_SUB(DATE('" . date('Y-m-d') . "'), INTERVAL 30 DAY)\n GROUP BY oi.sku_id"; return $this->query($sql, array('product_id' => $product_id))->fetchAll('sku_id'); }
/** Coupon discounts implementation. */ protected static function byCoupons(&$order, $contact, $apply) { $currency = isset($order['currency']) ? $order['currency'] : wa('shop')->getConfig()->getCurrency(false); $checkout_data = wa('shop')->getStorage()->read('shop/checkout'); if (empty($checkout_data['coupon_code'])) { return 0; // !!! Will this fail when recalculating existing order? } $cm = new shopCouponModel(); $coupon = $cm->getByField('code', $checkout_data['coupon_code']); if (!$coupon || !shopCouponsAction::isEnabled($coupon)) { return 0; } switch ($coupon['type']) { case '$FS': $order['shipping'] = 0; $result = 0; break; case '%': $result = max(0.0, min(100.0, (double) $coupon['value'])) * $order['total'] / 100.0; break; default: // Flat value in currency $result = max(0.0, (double) $coupon['value']); if ($currency != $coupon['type']) { $crm = new shopCurrencyModel(); $result = (double) $crm->convert($result, $coupon['type'], $currency); } break; } if ($apply) { $cm->useOne($coupon['id']); if (empty($order['params'])) { $order['params'] = array(); } $order['params']['coupon_id'] = $coupon['id']; $order['params']['coupon_discount'] = $result; } return $result; }
public function getCurrencies($codes = null) { $model = new shopCurrencyModel(); return $model->getCurrencies($codes); }