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));
 }
 public function execute()
 {
     $order_id = waRequest::post('order_id', null, waRequest::TYPE_INT);
     if ($order_id) {
         $order_model = new shopOrderModel();
         $order = $order_model->getOrder($order_id);
         $customer_model = new shopCustomerModel();
         $customer = $customer_model->getById($order['contact_id']);
         $customer_model->updateById($order['contact_id'], array('is_spamer' => 1));
         $plugin = waSystem::getInstance()->getPlugin('orderantispam');
         $action_id = $plugin->getSettings('action_id');
         $workflow = new shopWorkflow();
         $action = $workflow->getActionById($action_id);
         $action->run($order_id);
         // counters
         $state_counters = $order_model->getStateCounters();
         $pending_counters = (!empty($state_counters['new']) ? $state_counters['new'] : 0) + (!empty($state_counters['processing']) ? $state_counters['processing'] : 0) + (!empty($state_counters['paid']) ? $state_counters['paid'] : 0);
         // update app coutner
         wa('shop')->getConfig()->setCount($state_counters['new']);
         $script = "<script>";
         $script .= "\$.order_list.updateCounters(" . json_encode(array('state_counters' => $state_counters, 'common_counters' => array('pending_counters' => $pending_counters))) . ");";
         $script .= "\$.order.reload();</script>";
         $this->response['script'] = $script;
     }
 }
 public function postExecute($order_id = null, $result = null)
 {
     $data = parent::postExecute($order_id, $result);
     $log_model = new waLogModel();
     $log_model->add('order_complete', $order_id);
     $order_model = new shopOrderModel();
     if (is_array($order_id)) {
         $order = $order_id;
         $order_id = $order['id'];
     } else {
         $order = $order_model->getById($order_id);
     }
     shopCustomers::recalculateTotalSpent($order['contact_id']);
     if ($order !== null) {
         $log_model = new shopOrderLogModel();
         $state_id = $log_model->getPreviousState($order_id);
         $app_settings_model = new waAppSettingsModel();
         $update_on_create = $app_settings_model->get('shop', 'update_stock_count_on_create_order');
         if (!$update_on_create && $state_id == 'new') {
             // jump through 'processing' state - reduce
             // for logging changes in stocks
             shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_ORDER, 'Order %s was completed', array('order_id' => $order_id));
             $order_model = new shopOrderModel();
             $order_model->reduceProductsFromStocks($order_id);
             shopProductStocksLogModel::clearContext();
         }
         $order_model->recalculateProductsTotalSales($order_id);
     }
     return $data;
 }
 public function postExecute($order_id = null, $result = null)
 {
     $data = parent::postExecute($order_id, $result);
     if ($order_id != null) {
         $log_model = new waLogModel();
         $log_model->add('order_restore', $order_id);
         $order_model = new shopOrderModel();
         $app_settings_model = new waAppSettingsModel();
         if ($this->state_id != 'refunded') {
             // for logging changes in stocks
             shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_ORDER, 'Order %s was restored', array('order_id' => $order_id));
             $update_on_create = $app_settings_model->get('shop', 'update_stock_count_on_create_order');
             if ($update_on_create) {
                 $order_model->reduceProductsFromStocks($order_id);
             } else {
                 if (!$update_on_create && $this->state_id != 'new') {
                     $order_model->reduceProductsFromStocks($order_id);
                 }
             }
             shopProductStocksLogModel::clearContext();
         }
         $order = $order_model->getById($order_id);
         if ($order && $order['paid_date']) {
             shopAffiliate::applyBonus($order_id);
             shopCustomers::recalculateTotalSpent($order['contact_id']);
         }
     }
     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 (!($order_id = waRequest::post('id', 0, 'int'))) {
         throw new waException('No order id given.');
     }
     if (!($action_id = waRequest::post('action_id'))) {
         throw new waException('No action id given.');
     }
     $workflow = new shopWorkflow();
     // @todo: check action availablity in state
     $action = $workflow->getActionById($action_id);
     if ($html = $action->getHTML($order_id)) {
         // display html
         echo $html;
     } else {
         // perform action and reload
         $result = $action->run($order_id);
         // counters
         $order_model = new shopOrderModel();
         $state_counters = $order_model->getStateCounters();
         $pending_counters = (!empty($state_counters['new']) ? $state_counters['new'] : 0) + (!empty($state_counters['processing']) ? $state_counters['processing'] : 0) + (!empty($state_counters['paid']) ? $state_counters['paid'] : 0);
         // update app coutner
         wa('shop')->getConfig()->setCount($state_counters['new']);
         echo "<script>";
         echo "\$.order_list.updateCounters(" . json_encode(array('state_counters' => $state_counters, 'common_counters' => array('pending_counters' => $pending_counters))) . ");";
         echo "\$.order.reload();</script>";
     }
 }
 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 ordersCollection($params)
 {
     /**
      * @var shopOrdersCollection $collection
      */
     $collection = $params['collection'];
     $hash = $collection->getType();
     $filters = self::parseHash(urldecode($hash));
     $model = new shopOrderModel();
     foreach ($filters as $k => $v) {
         $key = $model->escape($k);
         $value = $model->escape($v);
         if (empty($value)) {
             continue;
         }
         if (substr($key, 0, 15) == 'update_datetime') {
             $operators = array("_from" => ">=", "_to" => "<=");
             if (array_key_exists(substr($key, 15), $operators)) {
                 $operator = $operators[substr($key, 15)];
                 $collection->addWhere("o.update_datetime" . $operator . "'" . date('Y-m-d', strtotime($value)) . "'");
             }
         } elseif (substr($key, 0, 7) == 'params.') {
             $model_params = new shopOrderParamsModel();
             $params_table_name = $model_params->getTableName();
             $collection->addJoin($params_table_name, "o.id=:table.order_id AND :table.name='" . substr($key, 7) . "'", ":table.value" . $this->getWhere($value));
         } elseif ($model->fieldExists($key)) {
             $title[] = $key . $this->getWhere($value);
             $collection->addWhere("o." . $key . $this->getWhere($value));
         }
     }
     return true;
 }
Esempio n. 9
0
 public function onCount()
 {
     if (!wa()->getUser()->getRights('shop', 'orders')) {
         return null;
     }
     $order_model = new shopOrderModel();
     return $order_model->getStateCounters('new');
 }
Esempio n. 10
0
 public function postExecute($order_id = null, $result = null)
 {
     if (!$result) {
         return;
     }
     $order_model = new shopOrderModel();
     if (is_array($order_id)) {
         $order = $order_id;
         $order_id = $order['id'];
     } else {
         $order = $order_model->getById($order_id);
     }
     $data = is_array($result) ? $result : array();
     $data['order_id'] = $order_id;
     $data['action_id'] = $this->getId();
     $data['before_state_id'] = $order['state_id'];
     if ($this->state_id) {
         $data['after_state_id'] = $this->state_id;
     } else {
         $data['after_state_id'] = $order['state_id'];
     }
     $order_log_model = new shopOrderLogModel();
     $data['id'] = $order_log_model->add($data);
     $update = isset($result['update']) ? $result['update'] : array();
     $update['update_datetime'] = date('Y-m-d H:i:s');
     $data['update'] = $update;
     if ($this->state_id) {
         $update['state_id'] = $this->state_id;
     }
     $order_model->updateById($order['id'], $update);
     $order_params_model = new shopOrderParamsModel();
     if (isset($update['params'])) {
         $order_params_model->set($order['id'], $update['params'], false);
     }
     $order['params'] = $order_params_model->get($order_id);
     // send notifications
     shopNotifications::send('order.' . $this->getId(), array('order' => $order, 'customer' => new waContact($order['contact_id']), 'status' => $this->getWorkflow()->getStateById($data['after_state_id'])->getName(), 'action_data' => $data));
     /**
      * @event order_action.callback
      * @event order_action.pay
      * @event order_action.ship
      * @event order_action.process
      * @event order_action.delete
      * @event order_action.restore
      * @event order_action.complete
      * @event order_action.comment
      *
      * @param array[string]mixed $data
      * @param array[string]int $data['order_id']
      * @param array[string]int $data['action_id']
      * @param array[string]int $data['before_state_id']
      * @param array[string]int $data['after_state_id']
      * @param array[string]int $data['id'] Order log record id
      */
     wa('shop')->event('order_action.' . $this->getId(), $data);
     return $data;
 }
 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);
     }
 }
Esempio n. 12
0
 public function execute()
 {
     list($start_date, $end_date, $group_by) = shopReportsSalesAction::getTimeframeParams();
     // Init by-day arrays with zeroes.
     $by_day = array();
     // Data for main graph: 'yyyy-mm-dd' => array(...)
     $sales_by_day = array();
     // Total sales data
     $om = new shopOrderModel();
     foreach ($om->getSales($start_date, $end_date, $group_by) as $date => $row) {
         $sales_by_day[$date] = $row['total'];
         $by_day[$date] = array('date' => $date, 'total_percent' => 0, 'total' => 0);
     }
     // Max profit in a single day
     $max_day_profit = 0;
     // Totals for period, in default currency
     $total = array('profit' => 0, 'purchase' => 0, 'shipping' => 0, 'sales' => 0, 'tax' => 0);
     // Loop over all days of a period that had at least one order paid,
     // and gather data into vars listed above.
     foreach ($om->getProfit($start_date, $end_date, $group_by) as $row) {
         $sales = ifset($sales_by_day[$row['date']], 0);
         $profit = $sales - $row['purchase'] - $row['shipping'] - $row['tax'];
         $max_day_profit = max($max_day_profit, $profit);
         $by_day[$row['date']]['total'] = $profit;
         $total['sales'] += $sales;
         $total['profit'] += $profit;
         $total['purchase'] += $row['purchase'];
         $total['shipping'] += $row['shipping'];
         $total['tax'] += $row['tax'];
     }
     // Data for main chart
     $profit_data = array();
     foreach ($by_day as &$d) {
         $d['total_percent'] = $max_day_profit ? $d['total'] * 100 / ifempty($max_day_profit, 1) : 0;
         $profit_data[] = array($d['date'], $d['total']);
     }
     unset($d);
     // Data for pie chart
     $pie_data = array();
     $pie_total = $total['shipping'] + $total['profit'] + $total['purchase'] + $total['tax'];
     if ($pie_total) {
         $pie_data[] = array(_w('Shipping') . ' (' . round($total['shipping'] * 100 / ifempty($pie_total, 1), 1) . '%)', (double) $total['shipping']);
         $pie_data[] = array(_w('Profit') . ' (' . round($total['profit'] * 100 / ifempty($pie_total, 1), 1) . '%)', (double) $total['profit']);
         $pie_data[] = array(_w('Product purchases') . ' (' . round($total['purchase'] * 100 / ifempty($pie_total, 1), 1) . '%)', (double) $total['purchase']);
         $pie_data[] = array(_w('Tax') . ' (' . round($total['tax'] * 100 / ifempty($pie_total, 1), 1) . '%)', (double) $total['tax']);
         $pie_data = array($pie_data);
     }
     $def_cur = wa()->getConfig()->getCurrency();
     $this->view->assign('total', $total);
     $this->view->assign('by_day', $by_day);
     $this->view->assign('def_cur', $def_cur);
     $this->view->assign('group_by', $group_by);
     $this->view->assign('pie_data', $pie_data);
     $this->view->assign('profit_data', $profit_data);
     $this->view->assign('avg_profit', $by_day ? round($total['profit'] / count($by_day), 2) : 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);
         }
     }
 }
 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;
     }
 }
Esempio 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(&$params)
 {
     if (!wa()->getUser()->getRights('shop', 'orders')) {
         return null;
     }
     $contact_id = $params;
     $om = new shopOrderModel();
     $total_orders = $om->countByField('contact_id', $contact_id);
     if (!$total_orders) {
         return null;
     }
     return array('html' => '', 'url' => wa()->getAppUrl('shop') . '?module=customers&action=profileTab&id=' . $contact_id, 'count' => 0, 'title' => _wd('shop', 'Shop') . ($total_orders ? ' (' . $total_orders . ')' : ''));
 }
Esempio n. 17
0
 public function execute()
 {
     $curm = new shopCurrencyModel();
     $currencies = $curm->getAll('code');
     $coupm = new shopCouponModel();
     $coupons = $coupm->order('id DESC')->fetchAll('code');
     foreach ($coupons as &$c) {
         $c['enabled'] = self::isEnabled($c);
         $c['hint'] = self::formatValue($c, $currencies);
     }
     unset($c);
     $order_model = new shopOrderModel();
     $count_new = $order_model->getStateCounters('new');
     $this->view->assign(array('coupons' => $coupons, 'order_count_new' => $count_new));
 }
 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 postExecute($order_id = null, $result = null)
 {
     $data = parent::postExecute($order_id, $result);
     if ($order_id != null) {
         $log_model = new waLogModel();
         $log_model->add('order_process', $order_id);
         $app_settings_model = new waAppSettingsModel();
         if (!$app_settings_model->get('shop', 'update_stock_count_on_create_order')) {
             // for logging changes in stocks
             shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_ORDER, 'Order %s was processed', array('order_id' => $order_id));
             $order_model = new shopOrderModel();
             $order_model->reduceProductsFromStocks($order_id);
             shopProductStocksLogModel::clearContext();
         }
     }
     return $data;
 }
 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);
 }
Esempio n. 21
0
 private function getOrder($order_id)
 {
     $order = $this->order_model->getOrder($order_id, true, true);
     if (!$order) {
         throw new waException("Unknow order", 404);
     }
     $order['shipping_id'] = ifset($order['params']['shipping_id'], '') . '.' . ifset($order['params']['shipping_rate_id'], '');
     $sku_ids = array();
     foreach ($order['items'] as $item) {
         foreach ($item['skus'] as $sku) {
             if (empty($sku['fake'])) {
                 $sku_ids[] = $sku['id'];
             }
         }
     }
     $sku_stocks = $this->getSkuStocks(array_unique($sku_ids));
     $subtotal = 0;
     $product_ids = array();
     foreach ($order['items'] as $i) {
         $product_ids[] = $i['id'];
         $subtotal += $i['item']['price'] * $i['item']['quantity'];
     }
     $order['subtotal'] = $subtotal;
     $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']);
     }
     foreach ($order['items'] as &$item) {
         if (isset($values['skus'][$item['item']['sku_id']])) {
             $w = $values['skus'][$item['item']['sku_id']];
         } else {
             $w = isset($values[$item['id']]) ? $values[$item['id']] : 0;
         }
         $this->workupItems($item, $sku_stocks);
         $item['quantity'] = $item['item']['quantity'];
         $item['weight'] = $w;
     }
     unset($item);
     return $order;
 }
 public function execute()
 {
     $id = waRequest::post('id');
     if (!$id) {
         $this->errors = _w("Unknown state");
         return;
     }
     $order_model = new shopOrderModel();
     if ($order_model->countByField('state_id', $id)) {
         $this->errors = _w("Cannot delete order status while there are active orders in this status");
         return;
     }
     $config = shopWorkflow::getConfig();
     if (isset($config['states'][$id])) {
         unset($config['states'][$id]);
     }
     shopWorkflow::setConfig($config);
 }
Esempio n. 23
0
 /**
  * @param array $params deleted contact_id
  * @return array|void
  */
 public function execute(&$params)
 {
     waLocale::loadByDomain('shop');
     // TODO: take a look to other models related with contacts
     $links = array();
     $product_reviews_model = new shopProductReviewsModel();
     $order_model = new shopOrderModel();
     foreach ($params as $contact_id) {
         $links[$contact_id] = array();
         if ($count = $product_reviews_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('shop', 'Reviews author'), 'links_number' => $count);
         }
         if ($count = $order_model->countByField('contact_id', $contact_id)) {
             $links[$contact_id][] = array('role' => _wd('shop', 'Order customer'), 'links_number' => $count);
         }
     }
     return $links;
 }
 public function execute()
 {
     $order_id = waRequest::get('order_id', null, waRequest::TYPE_INT);
     $customer_id = waRequest::get('customer_id', null, waRequest::TYPE_INT);
     $order_id = $order_id ? $order_id : null;
     $currency = waRequest::get('currency');
     if (!$currency && $order_id) {
         $order_model = new shopOrderModel();
         $order = $order_model->getOrder($order_id);
         $currency = $order['currency'];
     }
     $product_id = waRequest::get('product_id', 0, waRequest::TYPE_INT);
     if (!$product_id) {
         $this->errors[] = _w("Unknown product");
         return;
     }
     $sku_id = waRequest::get('sku_id', 0, waRequest::TYPE_INT);
     if ($sku_id) {
         $sku = $this->getSku($sku_id, $order_id);
         $skus = shopPricePlugin::prepareSkus(array($sku_id => $sku), $customer_id);
         if (!empty($skus[$sku_id])) {
             $sku = $skus[$sku_id];
         }
         $this->response['sku'] = $sku;
         $this->response['service_ids'] = array_keys($sku['services']);
     } else {
         $product = $this->getProduct($product_id, $order_id);
         $products = shopPricePlugin::prepareProducts(array($product_id => $product), $customer_id, $currency);
         if (!empty($products[$product_id])) {
             $product = $products[$product_id];
         }
         $product['skus'] = shopPricePlugin::prepareSkus($product['skus'], $customer_id, $currency);
         foreach ($product['skus'] as &$sku) {
             if (isset($sku['price'])) {
                 $sku['price_str'] = wa_currency($sku['price'], $currency);
                 $sku['price_html'] = wa_currency_html($sku['price'], $currency);
             }
         }
         unset($sku);
         $this->response['product'] = $product;
         $this->response['sku_ids'] = array_keys($product['skus']);
         $this->response['service_ids'] = array_keys($product['services']);
     }
 }
Esempio n. 25
0
 /**
  * @param int[] $params Deleted contact_id
  * @see waEventHandler::execute()
  * @return void
  */
 public function execute(&$params)
 {
     $contact_ids = $params;
     // We need some info about (not yet) deleted contacts to save into order params.
     // The idea is to pretend that orders were created by guests with no auth.
     $c = new waContactsCollection('id/' . implode(',', $contact_ids));
     $contacts = $c->getContacts('name,phone,email');
     foreach ($contacts as &$contact) {
         if (is_array($contact['phone'])) {
             $phone = reset($contact['phone']);
             if (is_array($phone)) {
                 if (isset($phone['value'])) {
                     $phone = $phone['value'];
                 } else {
                     $phone = '';
                 }
             }
             $contact['phone'] = $phone;
         }
         if (is_array($contact['email'])) {
             $email = reset($contact['email']);
             $contact['email'] = $email;
         }
     }
     $order_model = new shopOrderModel();
     $order_params_model = new shopOrderParamsModel();
     $product_reviews_model = new shopProductReviewsModel();
     foreach ($contacts as $contact) {
         // Insert customer info into params of their orders
         $order_ids = array_keys($order_model->select('id')->where('contact_id=:contact_id', array('contact_id' => $contact['id']))->fetchAll('id'));
         $order_params_model->set($order_ids, $this->extractContactInfo($contact), false);
         // Insert contact name into their reviews
         $product_reviews_model->updateByField('contact_id', $contact['id'], array('contact_id' => 0, 'name' => $contact['name'], 'auth_provider' => null));
     }
     // Update orders as if they were created by guests with no auth
     $order_model->updateByField('contact_id', $contact_ids, array('contact_id' => null));
     // Forget the customer
     $scm = new shopCustomerModel();
     $scm->deleteById($contact_ids);
     // Forget that this user created coupons
     $coupm = new shopCouponModel();
     $coupm->updateByField('create_contact_id', $contact_ids, array('create_contact_id' => 0));
     // !!! TODO: take a look to other models related with contacts
 }
 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 postExecute($order_id = null, $result = null)
 {
     $data = parent::postExecute($order_id, $result);
     if ($order_id != null) {
         $log_model = new waLogModel();
         $log_model->add('order_delete', $order_id);
         $order_model = new shopOrderModel();
         $app_settings_model = new waAppSettingsModel();
         if ($data['before_state_id'] != 'refunded') {
             $update_on_create = $app_settings_model->get('shop', 'update_stock_count_on_create_order');
             // for logging changes in stocks
             shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_ORDER, 'Order %s was deleted', array('order_id' => $order_id));
             if ($update_on_create) {
                 $order_model->returnProductsToStocks($order_id);
             } else {
                 if (!$update_on_create && $data['before_state_id'] != 'new') {
                     $order_model->returnProductsToStocks($order_id);
                 }
             }
             shopProductStocksLogModel::clearContext();
         }
         $order = $order_model->getById($order_id);
         if ($order && $order['paid_date']) {
             // Remember paid_date in log params for Restore action
             $olpm = new shopOrderLogParamsModel();
             $olpm->insert(array('name' => 'paid_date', 'value' => $order['paid_date'], 'order_id' => $order_id, 'log_id' => $data['id']));
             // Empty paid_date and update stats so that deleted orders do not affect reports
             $order_model->updateById($order_id, array('paid_date' => null, 'paid_year' => null, 'paid_month' => null, 'paid_quarter' => null));
             $order_model->recalculateProductsTotalSales($order_id);
             shopCustomers::recalculateTotalSpent($order['contact_id']);
         }
     }
     return $data;
 }
 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';
 }
Esempio n. 29
0
 public function execute()
 {
     if (!wa()->getUser()->getRights('shop', 'orders')) {
         throw new waException(_w("Access denied"));
     }
     $this->setLayout(new shopBackendLayout());
     $this->getResponse()->setTitle(_w('Orders'));
     $config = $this->getConfig();
     $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);
     $cm = new shopCouponModel();
     /*
      * @event backend_orders
      * @return array[string]array $return[%plugin_id%] array of html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar_top_li'] html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar_bottom_li'] html output
      * @return array[string][string]string $return[%plugin_id%]['sidebar_section'] html output
      */
     $backend_orders = wa()->event('backend_orders');
     $this->getLayout()->assign('backend_orders', $backend_orders);
     $this->view->assign(array('states' => $this->getStates(), 'user_id' => $this->getUser()->getId(), 'contacts' => array(), 'default_view' => $config->getOption('orders_default_view'), 'coupons_count' => $cm->countActive(), 'state_counters' => $state_counters, 'pending_count' => $pending_count, 'all_count' => $order_model->countAll(), 'storefronts' => $order_model->getStorefrontCounters(), 'backend_orders' => $backend_orders));
 }
 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);
     }
 }