Ejemplo n.º 1
0
 public function execute()
 {
     $form = shopHelper::getCustomerForm();
     if ($form->post()) {
         $customer_validation_disabled = wa()->getSetting('disable_backend_customer_form_validation');
         if ($customer_validation_disabled || $form->isValid()) {
             $c = new waContact();
             if ($customer_validation_disabled) {
                 $errors = array();
                 $c->save($form->post());
             } else {
                 $errors = $c->save($form->post(), true);
             }
             if (!$errors) {
                 $scm = new shopCustomerModel();
                 $scm->createFromContact($c->getId());
                 echo '<script>$.customers.reloadSidebar(); window.location.hash = "#/id/' . $c->getId() . '"</script>';
                 exit;
             }
             // Show errors that waContact returned, e.g. email must be unique.
             foreach ($errors as $fld => $list) {
                 foreach ($list as $err) {
                     $form->errors($fld, $err);
                 }
             }
         }
     }
     $this->view->assign('form', $form);
     $this->view->assign('customer_validation_disabled', wa()->getSetting('disable_backend_customer_form_validation'));
 }
 public function execute()
 {
     $lazy = waRequest::get('lazy', 0, waRequest::TYPE_INT);
     $offset = waRequest::get('offset', 0, waRequest::TYPE_INT);
     $limit = 30;
     $model = new shopDiscountcardsPluginOrderModel();
     $sql = "SELECT count(*) " . $this->getSql();
     $total_count = (int) $model->query($sql)->fetchField();
     $sql = "SELECT * " . $this->getSql() . " LIMIT {$offset}, {$limit}";
     $discountcards_orders = $model->query($sql)->fetchAll();
     $discountcards_model = new shopDiscountcardsPluginModel();
     $order_model = new shopOrderModel();
     $workflow = new shopWorkflow();
     foreach ($discountcards_orders as &$discountcards_order) {
         $order = $order_model->getOrder($discountcards_order['order_id']);
         $discountcards_order['order'] = $order;
         $discountcards_order['order_id_encode'] = shopHelper::encodeOrderId($order['id']);
         if ($discountcard = $discountcards_model->getByField('discountcard', $discountcards_order['discountcard'])) {
             $discountcards_order['_discountcard'] = $discountcard;
         }
         $discountcards_order['state'] = $workflow->getStateById($order['state_id']);
     }
     unset($discountcards_order);
     $this->view->assign(array('discountcards_orders' => $discountcards_orders, 'offset' => $offset, 'limit' => $limit, 'count' => count($discountcards_orders), 'total_count' => $total_count, 'lazy' => $lazy));
 }
Ejemplo n.º 3
0
 public function getProductStocks($offset, $count, $order_by)
 {
     $data = $this->product_model->getProductStocks($offset, $count, $order_by);
     foreach ($data as &$product) {
         $product['icon'] = shopHelper::getStockCountIcon($product['count']);
         foreach ($product['skus'] as &$sku) {
             $sku['icon'] = shopHelper::getStockCountIcon($sku['count']);
         }
         unset($sku);
         foreach ($product['stocks'] as $stock_id => &$stock) {
             foreach ($stock as &$sku) {
                 $sku['icon'] = shopHelper::getStockCountIcon($sku['count'], $stock_id);
             }
         }
         unset($product, $stock, $sku);
     }
     // because javascript doesn't guarantee any particular order for the keys in object
     // make hash-table to array converting
     $data = array_values($data);
     foreach ($data as &$product) {
         $product['skus'] = array_values($product['skus']);
         $product['stocks'] = array_values($product['stocks']);
         foreach ($product['stocks'] as &$stock) {
             $stock = array_values($stock);
         }
         unset($product, $stock);
     }
     return $data;
 }
 public function execute()
 {
     $order_id = waRequest::request('order_id', 0, 'int');
     $id = waRequest::request('id', 0, 'int');
     $to = waRequest::request('to');
     $nm = new shopNotificationModel();
     $n = $nm->getById($id);
     if (!$n) {
         $this->errors = sprintf_wp('%s entry not found', _w('Notification'));
         return;
     }
     $om = new shopOrderModel();
     $o = $om->getById($order_id);
     if (!$o) {
         $this->errors = _w('Order not found');
         return;
     }
     shopHelper::workupOrders($o, true);
     $opm = new shopOrderParamsModel();
     $o['params'] = $opm->get($order_id);
     try {
         $contact = $o['contact_id'] ? new shopCustomer($o['contact_id']) : wa()->getUser();
         $contact->getName();
     } catch (Exception $e) {
         $contact = new shopCustomer(wa()->getUser()->getId());
     }
     $cm = new shopCustomerModel();
     $customer = $cm->getById($contact->getId());
     if (!$customer) {
         $customer = $cm->getEmptyRow();
     }
     $workflow = new shopWorkflow();
     // send notifications
     shopNotifications::sendOne($id, array('order' => $o, 'customer' => $contact, 'status' => $workflow->getStateById($o['state_id'])->getName()), $to);
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $model = new shopTypeModel();
     $data = array();
     $data['id'] = waRequest::post('id', 0, waRequest::TYPE_INT);
     switch (waRequest::post('source', 'custom')) {
         case 'custom':
             $data['name'] = waRequest::post('name');
             $data['icon'] = waRequest::post('icon_url', false, waRequest::TYPE_STRING_TRIM);
             if (empty($data['icon'])) {
                 $data['icon'] = waRequest::post('icon', 'icon.box', waRequest::TYPE_STRING_TRIM);
             }
             if (!empty($data['id'])) {
                 $model->updateById($data['id'], $data);
             } else {
                 $data['sort'] = $model->select('MAX(sort)+1 as max_sort')->fetchField('max_sort');
                 $data['id'] = $model->insert($data);
             }
             break;
         case 'template':
             $data = $model->insertTemplate(waRequest::post('template'), true);
             break;
     }
     if ($data) {
         $data['icon_html'] = shopHelper::getIcon($data['icon'], 'icon.box');
         $data['name_html'] = '<span class="js-type-icon">' . $data['icon_html'] . '</span>
                 <span class="js-type-name">' . htmlspecialchars($data['name'], ENT_QUOTES, 'utf-8') . '</span>';
     }
     $this->response = $data;
 }
 public function execute()
 {
     $id = waRequest::get('id');
     $model = new shopNotificationModel();
     $n = $model->getById($id);
     $params_model = new shopNotificationParamsModel();
     $params = $params_model->getParams($id);
     // Orders used as sample data for testing
     $om = new shopOrderModel();
     $test_orders = $om->where("paid_date IS NOT NULL AND state_id <> 'deleted'")->order('id DESC')->limit(10)->fetchAll('id');
     shopHelper::workupOrders($test_orders);
     $im = new shopOrderItemsModel();
     foreach ($im->getByField('order_id', array_keys($test_orders), true) as $i) {
         $test_orders[$i['order_id']]['items'][] = $i;
     }
     foreach ($test_orders as &$o) {
         $o['items'] = ifset($o['items'], array());
         $o['total_formatted'] = waCurrency::format('%{s}', $o['total'], $o['currency']);
     }
     $this->view->assign('n', $n);
     $this->view->assign('params', $params);
     $this->view->assign('transports', self::getTransports());
     $this->view->assign('events', $this->getEvents());
     $this->view->assign('test_orders', $test_orders);
     $this->view->assign('default_email_from', $this->getConfig()->getGeneralSettings('email'));
     $this->view->assign('sms_from', $this->getSmsFrom());
     $this->view->assign('routes', wa()->getRouting()->getByApp('shop'));
 }
 public function execute()
 {
     $id = (int) waRequest::get('id');
     if ($id) {
         $this->form = shopHelper::getCustomerForm($id);
     }
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waException(_w('Access denied'));
     }
     $this->view->assign('plugins', shopHelper::getPrintForms());
     $this->view->assign('installer', $this->getUser()->getRights('installer', 'backend'));
 }
 public function execute()
 {
     $code = waRequest::param('code');
     $encoded_order_id = waRequest::param('id');
     $order_id = shopHelper::decodeOrderId($encoded_order_id);
     if (!$order_id) {
         // fall back to non-encoded id
         $order_id = $encoded_order_id;
         $encoded_order_id = shopHelper::encodeOrderId($order_id);
     }
     if (!$order_id || $order_id != substr($code, 16, -16)) {
         throw new waException(_w('Order not found'), 404);
     }
     // When user is authorized, check if order belongs to him.
     // When it does, redirect to plain order page.
     if (wa()->getUser()->isAuth()) {
         $om = new shopOrderModel();
         $order = $om->getOrder($order_id);
         if (!$order) {
             throw new waException(_w('Order not found'), 404);
         }
         if ($order['contact_id'] == wa()->getUser()->getId()) {
             $this->redirect(wa()->getRouteUrl('/frontend/myOrder', array('id' => $order_id)));
         }
     }
     // Check auth code
     $opm = new shopOrderParamsModel();
     $params = $opm->get($order_id);
     if (ifset($params['auth_code']) !== $code || empty($params['auth_pin'])) {
         throw new waException(_w('Order not found'), 404);
     }
     // Check auth pin and show order page if pin is correct
     $pin = waRequest::request('pin', wa()->getStorage()->get('shop/pin/' . $order_id));
     if ($pin && $pin == $params['auth_pin']) {
         wa()->getStorage()->set('shop/pin/' . $order_id, $pin);
         parent::execute();
         if (!waRequest::isXMLHttpRequest()) {
             $this->layout->assign('breadcrumbs', self::getBreadcrumbs());
         }
         return;
     }
     //
     // No pin or pin is incorrect: show form to enter pin
     //
     $this->view->assign('wrong_pin', !!$pin);
     $this->view->assign('pin_required', true);
     $this->view->assign('encoded_order_id', $encoded_order_id);
     $this->view->assign('my_nav_selected', 'orders');
     // Set up layout and template from theme
     $this->setThemeTemplate('my.order.html');
     if (!waRequest::isXMLHttpRequest()) {
         $this->setLayout(new shopFrontendLayout());
         $this->getResponse()->setTitle(_w('Order') . ' ' . $encoded_order_id);
         $this->view->assign('breadcrumbs', self::getBreadcrumbs());
         $this->layout->assign('nofollow', true);
     }
 }
 public function createSet($name)
 {
     $id = str_replace('-', '_', shopHelper::transliterate($name));
     $id = $this->set_model->suggestUniqueId($id);
     if (empty($name)) {
         $name = _w('(no-name)');
     }
     return $this->set_model->add(array('id' => $id, 'name' => $name));
 }
 public function createCategory($name)
 {
     $url = shopHelper::transliterate($name, false);
     $url = $this->category_model->suggestUniqueUrl($url);
     if (empty($name)) {
         $name = _w('(no-name)');
     }
     return $this->category_model->add(array('name' => $name, 'url' => $url));
 }
Ejemplo n.º 12
0
 public function execute()
 {
     $id = waRequest::get('id', null, waRequest::TYPE_INT);
     if ($id) {
         $model = new shopOrderModel();
         if ($model->delete($id)) {
             $this->response = shopHelper::workupOrders($model->getOrder($id), true);
         }
     }
 }
Ejemplo n.º 13
0
 public function display()
 {
     $plugin_model = new shopPluginModel();
     if (waRequest::param('payment_id') && is_array(waRequest::param('payment_id'))) {
         $methods = $plugin_model->getById(waRequest::param('payment_id'));
     } else {
         $methods = $plugin_model->listPlugins('payment');
     }
     $shipping = $this->getSessionData('shipping');
     if ($shipping) {
         $disabled = shopHelper::getDisabledMethods('payment', $shipping['id']);
     } else {
         $disabled = array();
     }
     $currencies = wa('shop')->getConfig()->getCurrencies();
     $selected = null;
     foreach ($methods as $key => $m) {
         $method_id = $m['id'];
         if (in_array($method_id, $disabled)) {
             unset($methods[$key]);
             continue;
         }
         $plugin = shopPayment::getPlugin($m['plugin'], $m['id']);
         $plugin_info = $plugin->info($m['plugin']);
         $methods[$key]['icon'] = $plugin_info['icon'];
         $custom_fields = $this->getCustomFields($method_id, $plugin);
         $custom_html = '';
         foreach ($custom_fields as $c) {
             $custom_html .= '<div class="wa-field">' . $c . '</div>';
         }
         $methods[$key]['custom_html'] = $custom_html;
         $allowed_currencies = $plugin->allowedCurrency();
         if ($allowed_currencies !== true) {
             $allowed_currencies = (array) $allowed_currencies;
             if (!array_intersect($allowed_currencies, array_keys($currencies))) {
                 $methods[$key]['error'] = sprintf(_w('Payment procedure cannot be processed because required currency %s is not defined in your store settings.'), implode(', ', $allowed_currencies));
             }
         }
         if (!$selected && empty($methods[$key]['error'])) {
             $selected = $method_id;
         }
     }
     $view = wa()->getView();
     $view->assign('checkout_payment_methods', $methods);
     $view->assign('payment_id', $this->getSessionData('payment', $selected));
     $checkout_flow = new shopCheckoutFlowModel();
     $step_number = shopCheckout::getStepNumber('payment');
     // IF no errors
     $checkout_flow->add(array('step' => $step_number));
     // ELSE
     //        $checkout_flow->add(array(
     //            'step' => $step_number,
     //            'description' => ERROR MESSAGE HERE
     //        ));
 }
 public function execute()
 {
     $om = new shopOrderModel();
     $encoded_order_id = waRequest::param('id');
     $code = waRequest::param('code');
     $order_id = shopHelper::decodeOrderId($encoded_order_id);
     if (!$order_id) {
         // fall back to non-encoded id
         $order_id = $encoded_order_id;
         $encoded_order_id = shopHelper::encodeOrderId($order_id);
     }
     $order = $om->getOrder($order_id);
     if (!$order) {
         throw new waException(_w('Order not found'), 404);
     } elseif (!$this->isAuth($order, $code)) {
         if ($code && $order_id != substr($code, 16, -16)) {
             throw new waException(_w('Order not found'), 404);
         } else {
             $redirect = array('id' => $order_id);
             if (!empty($code)) {
                 $redirect['code'] = $code;
             }
             $url = $code ? '/frontend/myOrderByCode' : '/frontend/myOrder';
             $this->redirect(wa()->getRouteUrl($url, $redirect));
         }
     } elseif ($code && $order['contact_id'] == wa()->getUser()->getId()) {
         $redirect = array('id' => $order_id, 'form_type' => waRequest::param('form_type'), 'form_id' => waRequest::param('form_id'));
         $this->redirect(wa()->getRouteUrl('/frontend/myOrderPrintform', $redirect));
     }
     $order_params_model = new shopOrderParamsModel();
     $order['params'] = $order_params_model->get($order['id']);
     $order['id_str'] = $encoded_order_id;
     switch (waRequest::param('form_type')) {
         case 'payment':
             if (empty($order['params']['payment_id']) || !($payment = shopPayment::getPlugin(null, $order['params']['payment_id']))) {
                 throw new waException(_w('Printform not found'), 404);
             }
             $form_id = waRequest::param('form_id');
             $params = null;
             if (strpos($form_id, '.')) {
                 $form = explode('.', $form_id, 2);
                 $form_id = array_shift($form);
                 $params = array_shift($form);
             }
             print $payment->displayPrintForm(ifempty($form_id, $payment->getId()), shopPayment::getOrderData($order, $payment), intval($params));
             exit;
             break;
         default:
             throw new waException(_w('Printform not found'), 404);
             break;
     }
 }
Ejemplo n.º 15
0
 public function execute()
 {
     if (wa()->getUser()->getRights('shop', 'orders')) {
         $om = new shopOrderModel();
         $orders = $om->order('id DESC')->limit(30)->fetchAll('id');
         shopHelper::workupOrders($orders);
         $this->view->assign('orders', $orders);
     } else {
         $this->view->assign('orders', false);
     }
     wa()->getResponse()->setTitle(_w('Orders'));
     parent::execute();
 }
 public function execute()
 {
     $sku_id = waRequest::post('sku_id', 0, waRequest::TYPE_INT);
     $src_stock = waRequest::post('src_stock', 0, waRequest::TYPE_INT);
     $dst_stock = waRequest::post('dst_stock', 0, waRequest::TYPE_INT);
     $count = waRequest::post('count', 0, waRequest::TYPE_INT);
     if ($src_stock == $dst_stock || !$src_stock || !$dst_stock || !$count) {
         $this->errors[] = _w("Error when transfer");
         return;
     }
     $product_skus_model = new shopProductSkusModel();
     shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_STOCK);
     if (!$product_skus_model->transfer($sku_id, $count, $src_stock, $dst_stock)) {
         $this->errors[] = _w("Error when transfer");
         return;
     }
     shopProductStocksLogModel::clearContext();
     $sku = $product_skus_model->getById($sku_id);
     /*
     $product_stocks_model = new shopProductStocksModel();
     $data = $product_stocks_model->getStocksOfProduct($sku['product_id'], array($src_stock, $dst_stock), 'sku.count DESC');
     
     foreach ($data as &$stock) {
         foreach ($stock as &$stock_sku) {
             $stock_sku['icon'] = shopHelper::getStockCountIcon($stock_sku['count']);
         }
     }
     unset($stock, $stock_sku);
     */
     $stock_skus = array();
     $product_model = new shopProductModel();
     $data = $product_model->getProductStocksByProductId($sku['product_id']);
     if (isset($data[$sku['product_id']])) {
         $data = $data[$sku['product_id']];
         if (isset($data['stocks'][$src_stock])) {
             $stock_skus[$src_stock] = array();
             foreach ($data['stocks'][$src_stock] as $stock_sku) {
                 $stock_sku['icon'] = shopHelper::getStockCountIcon($stock_sku['count'], $src_stock);
                 $stock_skus[$src_stock][] = $stock_sku;
             }
         }
         if (isset($data['stocks'][$dst_stock])) {
             $stock_skus[$dst_stock] = array();
             foreach ($data['stocks'][$dst_stock] as $stock_sku) {
                 $stock_sku['icon'] = shopHelper::getStockCountIcon($stock_sku['count'], $dst_stock);
                 $stock_skus[$dst_stock][] = $stock_sku;
             }
         }
     }
     $this->response = array('stocks' => $stock_skus ? $stock_skus : new stdClass(), 'product_id' => $sku['product_id']);
 }
 protected function getForm()
 {
     $domain = wa()->getRouting()->getDomain();
     $domain_config_path = wa()->getConfig()->getConfigPath('domains/' . $domain . '.php', true, 'site');
     if (file_exists($domain_config_path)) {
         $domain_config = (include $domain_config_path);
     } else {
         $domain_config = array();
     }
     if (!empty($domain_config['personal_fields'])) {
         return parent::getForm();
     }
     return shopHelper::getCustomerForm(null, true);
 }
Ejemplo n.º 18
0
 public function execute()
 {
     $items = waRequest::post('items');
     $product_ids = array();
     foreach ($items as $i) {
         $product_ids[] = $i['product_id'];
     }
     $product_ids = array_unique($product_ids);
     $feature_model = new shopFeatureModel();
     $f = $feature_model->getByCode('weight');
     if (!$f) {
         $values = array();
     } else {
         $values_model = $feature_model->getValuesModel($f['type']);
         $values = $values_model->getProductValues($product_ids, $f['id']);
     }
     $contact = $this->getContact();
     $shipping_address = $contact->getFirst('address.shipping');
     if ($shipping_address) {
         $shipping_address = $shipping_address['data'];
     }
     $shipping_items = array();
     foreach ($items as $i) {
         if (isset($values['skus'][$i['sku_id']])) {
             $w = $values['skus'][$i['sku_id']];
         } else {
             $w = isset($values[$i['product_id']]) ? $values[$i['product_id']] : 0;
         }
         $shipping_items[] = array('name' => '', 'price' => $i['price'], 'quantity' => $i['quantity'], 'weight' => $w);
     }
     $order_id = waRequest::post('order_id');
     if ($order_id) {
         $order_model = new shopOrderModel();
         $order_info = $order_model->getById($order_id);
         $currency = $order_info['currency'];
     } else {
         $currency = $this->getConfig()->getCurrency();
     }
     $total = waRequest::post('subtotal') - waRequest::post('discount');
     $order = array('currency' => $currency, 'contact' => $contact, 'items' => $items, 'total' => waRequest::post('subtotal'));
     if ($order_id) {
         $order['id'] = $order_info['id'];
     }
     $this->response['discount'] = shopDiscounts::calculate($order_info);
     $this->response['shipping_methods'] = shopHelper::getShippingMethods($shipping_address, $shipping_items, array('currency' => $currency, 'total_price' => $total));
     // for saving order in js
     $this->response['shipping_method_ids'] = array_keys($this->response['shipping_methods']);
 }
 public function execute()
 {
     $action_id = waRequest::get('id', null, waRequest::TYPE_STRING_TRIM);
     if (!$action_id) {
         throw new waException('No action id given.');
     }
     $chunk_size = 100;
     $offset = (int) waRequest::get('offset');
     $workflow = new shopWorkflow();
     $order_model = new shopOrderModel();
     // collect orders under which has performed actions
     $updated_orders_ids = array();
     $hash = $this->getHash();
     if ($hash === null) {
         return;
     }
     $collection = new shopOrdersCollection($hash);
     $total_count = $collection->count();
     $orders = $collection->getOrders('*', $offset, $chunk_size);
     foreach ($orders as $order) {
         $actions = $workflow->getStateById($order['state_id'])->getActions();
         if (isset($actions[$action_id])) {
             $actions[$action_id]->run($order['id']);
             $updated_orders_ids[] = $order['id'];
         }
     }
     if (!$updated_orders_ids) {
         return;
     }
     $this->response = array('offset' => $offset + count($orders), 'total_count' => $total_count);
     // sidebar counters
     if ($this->response['offset'] >= $this->response['total_count']) {
         $order_model = new shopOrderModel();
         $state_counters = $order_model->getStateCounters();
         $pending_count = (!empty($state_counters['new']) ? $state_counters['new'] : 0) + (!empty($state_counters['processing']) ? $state_counters['processing'] : 0) + (!empty($state_counters['paid']) ? $state_counters['paid'] : 0);
         $this->response['state_counters'] = $state_counters;
         $this->response['pending_count'] = $pending_count;
     }
     $collection = new shopOrdersCollection('id/' . implode(',', $updated_orders_ids));
     $total_count = $collection->count();
     $orders = $collection->getOrders('*,contact', 0, $total_count);
     // orders for update items in table
     shopHelper::workupOrders($orders);
     $this->response['orders'] = array_values($orders);
 }
Ejemplo n.º 20
0
 /**
  *
  * List available plugins of specified type
  * @param string $type plugin type
  * @param array $options
  * @return array[]
  */
 public function listPlugins($type, $options = array())
 {
     $fields = array('type' => $type);
     if (empty($options['all'])) {
         $fields['status'] = 1;
     }
     $plugins = $this->getByField($fields, $this->id);
     $complementary = $type == self::TYPE_PAYMENT ? self::TYPE_SHIPPING : self::TYPE_PAYMENT;
     $non_available = array();
     if (!empty($options[$complementary])) {
         $non_available = shopHelper::getDisabledMethods($type, $options[$complementary]);
     }
     foreach ($plugins as &$plugin) {
         $plugin['available'] = !in_array($plugin['id'], $non_available);
     }
     unset($plugin);
     return $plugins;
 }
 public function getData($id)
 {
     $data = waRequest::post('info');
     if (!$id) {
         $product_id = waRequest::get('product_id', null, waRequest::TYPE_INT);
         $product = $this->getProduct($product_id);
         $data['product_id'] = $product['id'];
     }
     $data['url'] = trim($data['url'], '/');
     if (!$id && !$data['url']) {
         $data['url'] = shopHelper::transliterate($data['name']);
     }
     if (empty($data['name'])) {
         $data['name'] = '(' . _ws('no-title') . ')';
     }
     $data['status'] = isset($data['status']) ? 1 : 0;
     return $data;
 }
Ejemplo n.º 22
0
 public function execute()
 {
     $contact = wa()->getUser();
     $scm = new shopCustomerModel();
     // Customer orders
     $om = new shopOrderModel();
     $orders = $om->where('contact_id=?', $contact->getId())->order('id DESC')->fetchAll('id');
     // Items for all orders, one query
     $im = new shopOrderItemsModel();
     foreach ($im->getByField('order_id', array_keys($orders), true) as $row) {
         $orders[$row['order_id']]['items'][] = $row;
     }
     // Params for all orders, one query
     $opm = new shopOrderParamsModel();
     foreach ($opm->getByField('order_id', array_keys($orders), true) as $row) {
         $orders[$row['order_id']]['params'][$row['name']] = $row['value'];
     }
     // Prepare order data for template
     $url_tmpl = wa()->getRouteUrl('/frontend/myOrder', array('id' => '%ID%'));
     $workflow = new shopWorkflow();
     foreach ($orders as $k => &$o) {
         if ($o['state_id'] == 'deleted') {
             unset($orders[$k]);
             continue;
         }
         $o['id_str'] = shopHelper::encodeOrderId($o['id']);
         $o['total_formatted'] = waCurrency::format('%{s}', $o['total'], $o['currency']);
         $o['shipping_name'] = ifset($o['params']['shipping_name'], '');
         $o['payment_name'] = ifset($o['params']['payment_name'], '');
         $o['state'] = $workflow->getStateById($o['state_id']);
         $o['url'] = str_replace('%ID%', $o['id'], $url_tmpl);
     }
     $this->view->assign('orders', array_values($orders));
     $this->view->assign('my_nav_selected', 'orders');
     // Set up layout and template from theme
     $this->setThemeTemplate('my.orders.html');
     if (!waRequest::isXMLHttpRequest()) {
         $this->setLayout(new shopFrontendLayout());
         $this->getResponse()->setTitle(_w('Orders'));
         $this->view->assign('breadcrumbs', self::getBreadcrumbs());
         $this->layout->assign('nofollow', true);
     }
 }
 public function execute()
 {
     $id = waRequest::request('id', null, waRequest::TYPE_INT);
     $contact = new waContact($id);
     $contact->getName();
     // Customer orders
     $im = new shopOrderItemsModel();
     $orders_collection = new shopOrdersCollection('search/contact_id=' . $id);
     $orders = $orders_collection->getOrders('*,items,params', 0, 500);
     shopHelper::workupOrders($orders);
     foreach ($orders as &$o) {
         $o['total_formatted'] = waCurrency::format('%{s}', $o['total'], $o['currency']);
         $o['shipping_name'] = ifset($o['params']['shipping_name'], '');
         $o['payment_name'] = ifset($o['params']['payment_name'], '');
     }
     $this->view->assign('orders', $orders);
     $this->view->assign('contact', $contact);
     $this->view->assign('def_cur_tmpl', str_replace('0', '%s', waCurrency::format('%{s}', 0, wa()->getConfig()->getCurrency())));
 }
 private function workupSku(&$sku, $sku_stocks)
 {
     // detaled stocks count icon for sku
     if (empty($sku_stocks[$sku['id']])) {
         $sku['icon'] = shopHelper::getStockCountIcon($sku['count'], null, true);
     } else {
         $icons = array();
         foreach ($sku_stocks[$sku['id']] as $stock_id => $stock) {
             $icon =& $icons[$stock_id];
             $icon = shopHelper::getStockCountIcon($stock['count'], $stock_id) . " ";
             $icon .= $stock['count'] . " ";
             $icon .= "<span class='small'>@" . htmlspecialchars($stock['name']) . "</span>";
             unset($icon);
         }
         //             $sku['icon'] = implode(', ', $icons);
         $sku['icon'] = shopHelper::getStockCountIcon($sku['count'], null, true);
         $sku['icons'] = $icons;
     }
 }
 public function execute()
 {
     $order_id = waRequest::request('order_id', 0, 'int');
     $followup_id = waRequest::request('followup_id', 0, 'int');
     $email = waRequest::request('email');
     $fm = new shopFollowupModel();
     $f = $fm->getById($followup_id);
     if (!$f) {
         $this->errors = sprintf_wp('%s entry not found', _w('Follow-up'));
         return;
     }
     $om = new shopOrderModel();
     $o = $om->getById($order_id);
     if (!$o) {
         $this->errors = _w('Order not found');
         return;
     }
     shopHelper::workupOrders($o, true);
     $opm = new shopOrderParamsModel();
     $o['params'] = $opm->get($order_id);
     try {
         $contact = $o['contact_id'] ? new shopCustomer($o['contact_id']) : wa()->getUser();
         $contact->getName();
     } catch (Exception $e) {
         $contact = new shopCustomer(wa()->getUser()->getId());
     }
     $cm = new shopCustomerModel();
     $customer = $cm->getById($contact->getId());
     if (!$customer) {
         $customer = $cm->getEmptyRow();
     }
     $to = array($email => $contact->getName());
     if (!shopFollowupCli::sendOne($f, $o, $customer, $contact, $to)) {
         $this->errors = "Unable to send follow-up #{$f['id']} for order #{$o['id']}: waMessage->send() returned FALSE.";
         return;
     }
     $this->response = 'ok';
 }
 public function execute()
 {
     $encoded_order_id = waRequest::param('id');
     $order_id = shopHelper::decodeOrderId($encoded_order_id);
     if (!$order_id) {
         // fall back to non-encoded id
         $order_id = $encoded_order_id;
         $encoded_order_id = shopHelper::encodeOrderId($order_id);
     }
     $om = new shopOrderModel();
     $order = $om->getOrder($order_id);
     if (!$order) {
         throw new waException(_w('Order not found'), 404);
     }
     if (!$this->isAuth($order)) {
         throw new waException(_w('The file will be available for download after the order is paid and processed.'), 404);
     }
     // Check auth code
     $opm = new shopOrderParamsModel();
     $params = $opm->get($order_id);
     $code = waRequest::param('code');
     if (ifset($params['auth_code']) !== $code) {
         throw new waException(_w('Order not found'), 404);
     }
     if ($item = ifempty($order['items'][waRequest::param('item')])) {
         $skus_model = new shopProductSkusModel();
         $sku = $skus_model->getById(ifempty($item['sku_id']));
         if ($sku['file_name'] && $sku['file_size']) {
             $file_path = shopProductSkusModel::getPath($sku);
             waFiles::readFile($file_path, $sku['file_name']);
         } else {
             throw new waException(_w('File not found'), 404);
         }
     } else {
         throw new waException(_w('Order item not found'), 404);
     }
 }
 /**
  * Create new waContactField of appropriate type from given array of options.
  */
 public static function createFromOpts($opts, $occupied_keys = array())
 {
     if (!is_array($opts) || empty($opts['_type'])) {
         return null;
     }
     // Generate field_id from name
     $fld_id = shopHelper::transliterate((string) ifset($opts['localized_names'], ''));
     if (!$fld_id) {
         $fld_id = 'f';
     }
     if (strlen($fld_id) > 15) {
         $fld_id = substr($fld_id, 0, 15);
     }
     while (isset($occupied_keys[$fld_id])) {
         if (strlen($fld_id) >= 15) {
             $fld_id = substr($fld_id, 0, 10);
         }
         $fld_id .= mt_rand(0, 9);
     }
     // Create field object of appropriate type
     $options = array('app_id' => 'shop');
     $ftype = strtolower($opts['_type']);
     switch ($ftype) {
         case 'textarea':
             $class = 'waContactStringField';
             $options['input_height'] = 5;
             break;
         case 'radio':
             $class = 'waContactRadioSelectField';
             break;
         default:
             $class = 'waContact' . ucfirst($ftype) . 'Field';
     }
     if (!$ftype || !class_exists($class)) {
         return null;
     }
     return new $class($fld_id, '', $options);
 }
Ejemplo n.º 28
0
 /**
  * @param array $options
  * @return shopProduct
  * @throws waException
  */
 public function duplicate($options = array())
 {
     if (!$this->checkRights()) {
         throw new waRightsException('Access denied');
     }
     $data = $this->data;
     $skip = array('id', 'create_datetime', 'id_1c', 'rating', 'rating_count', 'total_sales', 'image_id', 'contact_id', 'ext', 'count', 'sku_count');
     foreach ($skip as $field) {
         if (isset($data[$field])) {
             unset($data[$field]);
         }
     }
     $duplicate = new shopProduct();
     $this->getStorage(null);
     $sku_files = array();
     $sku_images = array();
     $ignore_select = true;
     foreach (self::$data_storages as $key => $i) {
         $raw = $this->getStorage($key)->getData($this);
         switch ($key) {
             case 'features_selectable':
                 $storage_data = array();
                 if (!$ignore_select) {
                     if ($this->sku_type == shopProductModel::SKU_TYPE_SELECTABLE) {
                         if (!is_array($raw)) {
                             $raw = array();
                         }
                         foreach ($raw as $id => $f) {
                             if (!empty($f['selected'])) {
                                 foreach ($f['values'] as $value_id => &$value) {
                                     if (!empty($value['selected'])) {
                                         $value = array('id' => $value_id);
                                     } else {
                                         unset($f['values'][$value_id]);
                                     }
                                 }
                                 $storage_data[$id] = $f;
                             }
                         }
                     }
                 }
                 break;
             case 'skus':
                 $storage_data = array();
                 $i = 0;
                 foreach ($raw as $sku_id => $sku) {
                     if (!empty($sku['virtual']) || $ignore_select) {
                         if ($file_path = shopProductSkusModel::getPath($sku)) {
                             $sku_files[$sku['id']] = array('file_name' => $sku['file_name'], 'file_description' => $sku['file_description'], 'file_size' => $sku['file_size'], 'file_path' => $file_path);
                         }
                         if (!empty($sku['image_id'])) {
                             $sku_images[$sku['id']] = $sku['image_id'];
                         }
                         foreach (array('id', 'id_1c', 'product_id', 'image_id', 'file_name', 'file_size', 'file_description') as $field) {
                             if (isset($sku[$field])) {
                                 unset($sku[$field]);
                             }
                         }
                         $storage_data[--$i] = $sku;
                     }
                 }
                 break;
             case 'tags':
                 $storage_data = array_values($raw);
                 break;
             case 'categories':
                 $storage_data = array_keys($raw);
                 break;
             default:
                 $storage_data = $raw;
                 break;
         }
         $duplicate->{$key} = $storage_data;
     }
     $counter = 0;
     $data['url'] = shopHelper::genUniqueUrl($this->url, $this->model, $counter);
     $data['name'] = $this->name . sprintf('(%d)', $counter ? $counter : 1);
     $duplicate->save($data);
     $product_id = $duplicate->getId();
     $sku_map = array_combine(array_keys($this->skus), array_keys($duplicate->skus));
     $config = wa('shop')->getConfig();
     $image_thumbs_on_demand = $config->getOption('image_thumbs_on_demand');
     /**
      * @var shopConfig $config
      */
     if ($this->pages) {
         $product_pages_model = new shopProductPagesModel();
         foreach ($this->pages as $page) {
             unset($page['id']);
             unset($page['create_time']);
             unset($page['update_datetime']);
             unset($page['create_contact_id']);
             $page['product_id'] = $duplicate->getId();
             $product_pages_model->add($page);
         }
     }
     #duplicate images
     $product_skus_model = new shopProductSkusModel();
     $images_model = new shopProductImagesModel();
     $images = $images_model->getByField('product_id', $this->getId(), $images_model->getTableId());
     $callback = create_function('$a, $b', 'return (max(-1, min(1, $a["sort"] - $b["sort"])));');
     usort($images, $callback);
     foreach ($images as $id => $image) {
         $source_path = shopImage::getPath($image);
         $original_file = shopImage::getOriginalPath($image);
         $image['product_id'] = $duplicate->getId();
         if ($sku_id = array_search($image['id'], $sku_images)) {
             $sku_id = $sku_map[$sku_id];
         }
         unset($image['id']);
         try {
             if ($image['id'] = $images_model->add($image, $id == $this->image_id)) {
                 waFiles::copy($source_path, shopImage::getPath($image));
                 if (file_exists($original_file)) {
                     waFiles::copy($original_file, shopImage::getOriginalPath($image));
                 }
                 if ($sku_id) {
                     $product_skus_model->updateById($sku_id, array('image_id' => $image['id']));
                 }
                 if (!$image_thumbs_on_demand) {
                     shopImage::generateThumbs($image, $config->getImageSizes());
                     //TODO use dummy copy  with rename files
                 }
             }
         } catch (waDbException $ex) {
             //just ignore it
             waLog::log('Error during copy product: ' . $ex->getMessage(), 'shop.log');
         } catch (waException $ex) {
             if (!empty($image['id'])) {
                 $images_model->deleteById($image['id']);
             }
             waLog::log('Error during copy product: ' . $ex->getMessage(), 'shop.log');
         }
     }
     foreach ($sku_files as $sku_id => $data) {
         $source_path = $data['file_path'];
         unset($data['file_path']);
         $sku_id = $sku_map[$sku_id];
         $sku = array_merge($duplicate->skus[$sku_id], $data);
         $product_skus_model->updateById($sku_id, $data);
         $target_path = shopProductSkusModel::getPath($sku);
         try {
             waFiles::copy($source_path, $target_path);
         } catch (waException $ex) {
             $data = array('file_name' => '', 'file_description' => '', 'file_size' => 0);
             $product_skus_model->updateById($sku_id, $data);
             print $ex->getMessage();
         }
     }
     $product_features_model = new shopProductFeaturesModel();
     $skus_features = $product_features_model->getSkuFeatures($this->id);
     $skus_features_data = array();
     foreach ($skus_features as $sku_id => $features) {
         $sku_id = $sku_map[$sku_id];
         foreach ($features as $feature_id => $feature_value_id) {
             $skus_features_data[] = compact('product_id', 'sku_id', 'feature_id', 'feature_value_id');
         }
     }
     if ($skus_features_data) {
         $product_features_model->multipleInsert($skus_features_data);
     }
     if ($this->sku_type == shopProductModel::SKU_TYPE_SELECTABLE) {
         $product_features_selectable_model = new shopProductFeaturesSelectableModel();
         if ($features_selectable = $product_features_selectable_model->getByField('product_id', $this->id, true)) {
             foreach ($features_selectable as &$feature_selectable) {
                 $feature_selectable['product_id'] = $product_id;
             }
             unset($feature_selectable);
             $product_features_selectable_model->multipleInsert($features_selectable);
         }
     }
     $product_services_model = new shopProductServicesModel();
     if ($services = $product_services_model->getByField('product_id', $this->id, true)) {
         foreach ($services as &$service) {
             unset($service['id']);
             $service['product_id'] = $product_id;
             $service['sku_id'] = ifset($sku_map[$service['sku_id']]);
             unset($service);
         }
         $product_services_model->multipleInsert($services);
     }
     $product_related_model = new shopProductRelatedModel();
     if ($related = $product_related_model->getByField('product_id', $this->id, true)) {
         foreach ($related as &$row) {
             $row['product_id'] = $product_id;
         }
         unset($row);
         $product_related_model->multipleInsert($related);
     }
     $params = array('product' => &$this, 'duplicate' => &$duplicate);
     /**
      * @wa-event product_duplicate
      */
     wa()->event('product_duplicate', $params);
     return $duplicate;
 }
 private function saveSetSettings($id, &$data)
 {
     if (empty($data['count']) || $data['count'] < 0) {
         $data['count'] = 0;
     }
     /**
      * @var shopSetModel $model
      */
     $model = $this->getModel('set');
     if (!$id) {
         if (empty($data['id'])) {
             $id = shopHelper::transliterate($data['name']);
             $data['id'] = $model->suggestUniqueId($id);
         } else {
             $data['id'] = $model->suggestUniqueId($data['id']);
         }
         if (!$this->setSettingsValidate(null, $data)) {
             return false;
         }
         if (empty($data['name'])) {
             $data['name'] = _w('(no-name)');
         }
         $id = $model->add($data);
     } else {
         $set = $model->getById($id);
         if (!$this->setSettingsValidate($set, $data)) {
             return false;
         }
         if (empty($data['name'])) {
             $data['name'] = $set['name'];
         }
         if (!empty($data['id'])) {
             $id = $data['id'];
         } else {
             $id = shopHelper::transliterate($data['name']);
             if ($id != $set['id']) {
                 $id = $model->suggestUniqueId($id);
             }
             $data['id'] = $id;
         }
         $data['edit_datetime'] = date('Y-m-d H:i:s');
         $model->update($set['id'], $data);
     }
     if ($id) {
         $data['id'] = $data;
         /**
          * @event set_save
          * @param array $set
          * @return void
          */
         wa()->event('set_save', $data);
     }
     return $id;
 }
Ejemplo n.º 30
0
 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));
 }