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)
 {
     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($oder_id = null)
 {
     // Restore previous state
     $log_model = new shopOrderLogModel();
     $params = array();
     $this->state_id = $log_model->getPreviousState($oder_id, $params);
     // Restore order.paid_*, customer.total_spent and customer.affiliation_bonus
     $paid_date = ifset($params['paid_date']);
     if ($paid_date) {
         $t = strtotime($paid_date);
         $result['update'] = array('paid_year' => date('Y', $t), 'paid_quarter' => floor((date('n', $t) - 1) / 3) + 1, 'paid_month' => date('n', $t), 'paid_date' => date('Y-m-d', $t));
         return $result;
     }
     return true;
 }
 public function postExecute($params = null, $result = null)
 {
     if (is_array($params)) {
         $order_id = $params['order_id'];
     } else {
         $order_id = $params;
     }
     $data = parent::postExecute($order_id, $result);
     $log_model = new waLogModel();
     $log_model->add('order_ship', $order_id);
     $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') {
         // for logging changes in stocks
         shopProductStocksLogModel::setContext(shopProductStocksLogModel::TYPE_ORDER, 'Order %s was shipped', array('order_id' => $order_id));
         // jump through 'processing' state - reduce
         $order_model = new shopOrderModel();
         $order_model->reduceProductsFromStocks($order_id);
         shopProductStocksLogModel::clearContext();
     }
     return $data;
 }
 protected static function sendSms($n, $data)
 {
     $general = wa('shop')->getConfig()->getGeneralSettings();
     /**
      * @var waContact $customer
      */
     $customer = $data['customer'];
     if ($n['to'] == 'customer') {
         $to = $customer->get('phone', 'default');
         $log = sprintf(_w("Notification <strong>%s</strong> sent to customer."), $n['name']);
     } elseif ($n['to'] == 'admin') {
         $to = $general['phone'];
         $log = sprintf(_w("Notification <strong>%s</strong> sent to store admin."), $n['name']);
     } else {
         $to = $n['to'];
         $log = sprintf(_w("Notification <strong>%s</strong> sent to %s."), $n['name'], $n['to']);
     }
     if (!$to) {
         return;
     }
     $view = wa()->getView();
     foreach (array('shipping', 'billing') as $k) {
         $address = shopHelper::getOrderAddress($data['order']['params'], $k);
         $formatter = new waContactAddressOneLineFormatter(array('image' => false));
         $address = $formatter->format(array('data' => $address));
         $view->assign($k . '_address', $address['value']);
     }
     $order_id = $data['order']['id'];
     $data['order']['id'] = shopHelper::encodeOrderId($order_id);
     $view->assign('order_url', wa()->getRouteUrl('/frontend/myOrderByCode', array('id' => $order_id, 'code' => $data['order']['params']['auth_code']), true));
     $view->assign($data);
     $text = $view->fetch('string:' . $n['text']);
     $sms = new waSMS();
     if ($sms->send($to, $text, isset($n['from']) ? $n['from'] : null)) {
         $order_log_model = new shopOrderLogModel();
         $order_log_model->add(array('order_id' => $order_id, 'contact_id' => null, 'action_id' => '', 'text' => '<i class="icon16 mobile"></i> ' . $log, 'before_state_id' => $data['order']['state_id'], 'after_state_id' => $data['order']['state_id']));
     }
 }
示例#6
0
 public function execute()
 {
     $order = $this->getOrder();
     if (!$order) {
         $this->view->assign('order', $order);
         return;
     }
     $workflow = new shopWorkflow();
     $actions = $workflow->getStateById($order['state_id'])->getActions();
     $bottom_buttons = $top_buttons = $buttons = array();
     foreach ($actions as $action) {
         /**
          * @var shopWorkflowAction $action
          */
         if ($action->getOption('top') || $action->getOption('position') == 'top') {
             $top_buttons[] = $action->getButton();
         } elseif ($action->getOption('position') == 'bottom') {
             $bottom_buttons[] = $action->getButton();
         } else {
             $buttons[] = $action->getButton();
         }
     }
     $config = $this->getConfig();
     $last_action_datetime = null;
     $log_model = new shopOrderLogModel();
     $log = $log_model->getLog($order['id']);
     foreach ($log as &$l) {
         if ($l['action_id']) {
             $l['action'] = $workflow->getActionById($l['action_id']);
         }
         if ($order['state_id'] == $l['after_state_id']) {
             $last_action_datetime = $l['datetime'];
         }
     }
     $params = $order['params'];
     $tracking = '';
     if (!empty($params['shipping_id'])) {
         try {
             $plugin = shopShipping::getPlugin(null, $params['shipping_id']);
             if (!empty($params['tracking_number'])) {
                 $tracking = $plugin->tracking($params['tracking_number']);
             }
             if ($custom_fields = $plugin->customFields(new waOrder())) {
                 foreach ($custom_fields as $k => $v) {
                     if (!empty($params['shipping_params_' . $k])) {
                         $custom_fields[$k]['value'] = $params['shipping_params_' . $k];
                     } else {
                         unset($custom_fields[$k]);
                     }
                 }
                 $this->view->assign('custom_fields', $custom_fields);
             }
         } catch (waException $ex) {
             $tracking = $ex->getMessage();
         }
     }
     $this->view->assign('tracking', $tracking);
     $settings = wa('shop')->getConfig()->getCheckoutSettings();
     $form_fields = ifset($settings['contactinfo']['fields'], array());
     $formatter = new waContactAddressSeveralLinesFormatter();
     $shipping_address = shopHelper::getOrderAddress($params, 'shipping');
     $this->view->assign('shipping_address_text', shopHelper::getShippingAddressText($params));
     $shipping_address = $formatter->format(array('data' => $shipping_address));
     $shipping_address = $shipping_address['value'];
     if (isset($form_fields['address.billing'])) {
         $billing_address = shopHelper::getOrderAddress($params, 'billing');
         $billing_address = $formatter->format(array('data' => $billing_address));
         $billing_address = $billing_address['value'];
         if ($billing_address === $shipping_address) {
             $billing_address = null;
         }
     } else {
         $billing_address = null;
     }
     $customer_model = new shopCustomerModel();
     $customer = $customer_model->getById($order['contact_id']);
     $customer_contact = new waContact($order['contact_id']);
     // Customer info
     $main_contact_info = array();
     foreach (array('email', 'phone', 'im') as $f) {
         if ($v = $customer_contact->get($f, 'top,html')) {
             $main_contact_info[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
         }
     }
     $this->view->assign(array('customer' => $customer, 'customer_contact' => $customer_contact, 'main_contact_info' => $main_contact_info, 'currency' => $config->getCurrency(), 'order' => $order, 'params' => $params, 'log' => $log, 'last_action_datetime' => $last_action_datetime, 'bottom_buttons' => $bottom_buttons, 'top_buttons' => $top_buttons, 'buttons' => $buttons, 'filter_params' => $this->getParams(), 'filter_params_str' => $this->getParams(true), 'count_new' => $this->getModel()->getStateCounters('new'), 'timeout' => $config->getOption('orders_update_list'), 'printable_docs' => shopHelper::getPrintForms(array_merge($order, array('params' => $params))), 'billing_address' => $billing_address, 'shipping_address' => $shipping_address, 'shipping_id' => ifset($params['shipping_id'], '') . '.' . ifset($params['shipping_rate_id'], ''), 'offset' => $this->getModel()->getOffset($order['id'], $this->getParams(), true)));
     /**
      * Backend order profile page
      * UI hook allow extends order profile page
      * @event backend_order
      * @param array $order
      * @return array[string][string]string $return[%plugin_id%]['title_suffix'] html output
      * @return array[string][string]string $return[%plugin_id%]['action_button'] html output
      * @return array[string][string]string $return[%plugin_id%]['action_link'] html output
      * @return array[string][string]string $return[%plugin_id%]['info_section'] html output
      */
     $this->view->assign('backend_order', wa()->event('backend_order', $order, array('title_suffix', 'action_button', 'action_link', 'info_section')));
 }
 public function postExecute($order_id = null, $result = null)
 {
     $order_id = $result['order_id'];
     $data = is_array($result) ? $result : array();
     $data['order_id'] = $order_id;
     $data['action_id'] = $this->getId();
     $data['before_state_id'] = '';
     $data['after_state_id'] = 'new';
     $order_log_model = new shopOrderLogModel();
     $order_log_model->add($data);
     /**
      * @event order_action.create
      */
     wa('shop')->event('order_action.create', $data);
     $order_model = new shopOrderModel();
     $order = $order_model->getById($order_id);
     $params_model = new shopOrderParamsModel();
     $order['params'] = $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));
     // Update stock count, but take into account 'update_stock_count_on_create_order'-setting
     $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 placed', array('order_id' => $order_id));
         $order_model->reduceProductsFromStocks($order_id);
         shopProductStocksLogModel::clearContext();
     }
     return $order_id;
 }
 public function execute()
 {
     $id = waRequest::request('id', 0, 'int');
     if (!$id || !wa()->getUser()->getRights('shop', 'orders')) {
         $this->redirect(wa()->getAppUrl());
     }
     // Order
     $om = new shopOrderModel();
     $order = $om->getOrder($id);
     shopHelper::workupOrders($order, true);
     $order['tax'] = (double) $order['tax'];
     $order['discount'] = (double) $order['discount'];
     // Order params
     $opm = new shopOrderParamsModel();
     $order['params'] = $opm->get($order['id']);
     // Order subtotal
     $order_subtotal = 0;
     foreach ($order['items'] as $i) {
         $order_subtotal += $i['price'] * $i['quantity'];
     }
     // Format addresses
     $settings = wa('shop')->getConfig()->getCheckoutSettings();
     $form_fields = ifset($settings['contactinfo']['fields'], array());
     $formatter = new waContactAddressSeveralLinesFormatter();
     $shipping_address = shopHelper::getOrderAddress($order['params'], 'shipping');
     $shipping_address = $formatter->format(array('data' => $shipping_address));
     $shipping_address = $shipping_address['value'];
     if (isset($form_fields['address.billing'])) {
         $billing_address = shopHelper::getOrderAddress($order['params'], 'billing');
         $billing_address = $formatter->format(array('data' => $billing_address));
         $billing_address = $billing_address['value'];
         if ($billing_address === $shipping_address) {
             $billing_address = null;
         }
     } else {
         $billing_address = null;
     }
     // Order history
     $log_model = new shopOrderLogModel();
     $log = $log_model->getLog($order['id']);
     // Customer
     $contact = $customer = self::getCustomer($order);
     $top = array();
     foreach (array('email', 'phone') as $f) {
         if ($v = $contact->get($f, 'top,html')) {
             $top[] = array('id' => $f, 'name' => waContactFields::get($f)->getName(), 'value' => is_array($v) ? implode(', ', $v) : $v);
         }
     }
     // Workflow stuff: actions and state
     $workflow = new shopWorkflow();
     $workflow_state = $workflow->getStateById($order['state_id']);
     $workflow_buttons = array();
     foreach ($workflow_state->getActions() as $a_id => $action) {
         if ($a_id === 'edit' || $a_id === 'delete') {
             continue;
         }
         $workflow_buttons[] = $action->getButton();
     }
     $this->view->assign('top', $top);
     $this->view->assign('log', $log);
     $this->view->assign('order', $order);
     $this->view->assign('uniqid', uniqid('f'));
     $this->view->assign('customer', $customer);
     $this->view->assign('workflow_state', $workflow_state);
     $this->view->assign('workflow_buttons', $workflow_buttons);
     $this->view->assign('shipping_address', $shipping_address);
     $this->view->assign('billing_address', $billing_address);
     $this->view->assign('order_subtotal', $order_subtotal);
     $this->view->assign('currency', ifempty($order['currency'], wa()->getConfig()->getCurrency()));
     wa()->getResponse()->setTitle(_w('Order') . ' ' . $order['id_str']);
     parent::execute();
 }
示例#9
0
 public function execute()
 {
     $fm = new shopFollowupModel();
     $opm = new shopOrderParamsModel();
     $asm = new waAppSettingsModel();
     $olm = new shopOrderLogModel();
     $cm = new shopCustomerModel();
     $om = new shopOrderModel();
     $asm->set('shop', 'last_followup_cli', time());
     $view = wa()->getView();
     $empty_customer = $cm->getEmptyRow();
     $general = wa('shop')->getConfig()->getGeneralSettings();
     foreach ($fm->getAllEnabled() as $f) {
         $between_from = date('Y-m-d', strtotime($f['last_cron_time']) - 24 * 3600);
         $between_to = date('Y-m-d 23:59:59', time() - $f['delay'] - 10 * 3600);
         $orders = $om->where('paid_date >= ? AND paid_date < ?', $between_from, $between_to)->fetchAll('id');
         if ($orders) {
             $f_param_key = 'followup_' . $f['id'];
             // Params for all orders with one query
             $params = $opm->get(array_keys($orders));
             // Customer data for all orders with one query
             $cids = array();
             foreach ($orders as $o) {
                 $cids[] = $o['contact_id'];
             }
             $customers = $cm->getById($cids);
             $sent_count = 0;
             foreach ($orders as $o) {
                 try {
                     // Is there a recipient in the first place?
                     if (empty($o['contact_id'])) {
                         if (waSystemConfig::isDebug()) {
                             waLog::log("Unable to send follow-up #{$f['id']} for order #{$o['id']}: no contact_id");
                         }
                         continue;
                     }
                     // Check that this is the first order of this customer
                     if ($f['first_order_only']) {
                         $first_order_id = $om->select('MIN(id)')->where('contact_id=? AND paid_date IS NOT NULL', $o['contact_id'])->fetchField();
                         if ($first_order_id != $o['id']) {
                             if (waSystemConfig::isDebug()) {
                                 waLog::log("Skipping follow-up #{$f['id']} for order #{$o['id']}: not the first order of a customer.");
                             }
                             continue;
                         }
                     }
                     $o['params'] = ifset($params[$o['id']], array());
                     $source = 'backend';
                     if (!empty($o['params']['storefront'])) {
                         $source = rtrim($o['params']['storefront'], '/') . '/*';
                     }
                     if ($f['source'] && $f['source'] != $source) {
                         continue;
                     }
                     // Make sure we have not send follow-up for this order yet
                     if (isset($o['params'][$f_param_key])) {
                         if (waSystemConfig::isDebug()) {
                             waLog::log("Skipping follow-up #{$f['id']} for order #{$o['id']}: already sent before.");
                         }
                         continue;
                     }
                     shopHelper::workupOrders($o, true);
                     // Recipient info
                     $customer = ifset($customers[$o['contact_id']], $empty_customer);
                     $contact = new shopCustomer($o['contact_id']);
                     $email = $contact->get('email', 'default');
                     // this with throw exception if contact does not exist; that's ok
                     if (!$email) {
                         if (waSystemConfig::isDebug()) {
                             waLog::log("Unable to send follow-up #{$f['id']} for order #{$o['id']}: contact has no email");
                         }
                         continue;
                     }
                     $to = array($email => $contact->getName());
                     if (self::sendOne($f, $o, $customer, $contact, $to, $view, $general)) {
                         $sent_count++;
                         // Write to order log
                         $olm->add(array('order_id' => $o['id'], 'contact_id' => null, 'action_id' => '', 'text' => sprintf_wp("Follow-up <strong>%s</strong> (%s) sent to customer.", htmlspecialchars($f['name']), $f['id']), 'before_state_id' => $o['state_id'], 'after_state_id' => $o['state_id']));
                         // Write to order params
                         $opm->insert(array('order_id' => $o['id'], 'name' => $f_param_key, 'value' => date('Y-m-d H:i:s')));
                     } else {
                         waLog::log("Unable to send follow-up #{$f['id']} for order #{$o['id']}: waMessage->send() returned FALSE.");
                     }
                 } catch (Exception $e) {
                     waLog::log("Unable to send follow-up #{$f['id']} for order #{$o['id']}:\n" . $e);
                 }
             }
             /**
              * Notify plugins about sending followup
              * @event followup_send
              * @param array[string]int $params['sent_count'] number of emails successfully sent
              * @param array[string]int $params['id'] followup_id
              * @return void
              */
             $event_params = $f;
             $event_params['sent_count'] = $sent_count;
             wa()->event('followup_send', $event_params);
         }
         $fm->updateById($f['id'], array('last_cron_time' => $between_to));
     }
 }
 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);
     }
     // Check that order exists and belongs to this user
     $om = new shopOrderModel();
     $order = $om->getOrder($order_id);
     if (!$order || !$this->isAuth($order)) {
         throw new waException(_w('Order not found'), 404);
     }
     if ($order['paid_date']) {
         foreach ($order['items'] as &$i) {
             if (!empty($i['file_name'])) {
                 $i['download_link'] = wa()->getRouteUrl('/frontend/myOrderDownload', array('id' => $order['id'], 'code' => $order['params']['auth_code'], 'item' => $i['id']), true);
             }
         }
         unset($i);
     }
     $workflow = new shopWorkflow();
     $order_params_model = new shopOrderParamsModel();
     $order['params'] = $order_params_model->get($order['id']);
     $order['id_str'] = $encoded_order_id;
     $order['state'] = $workflow->getStateById($order['state_id']);
     // Order subtotal
     $subtotal = 0;
     foreach ($order['items'] as $item) {
         $subtotal += $item['price'] * $item['quantity'];
     }
     // Order comment
     $lm = new shopOrderLogModel();
     $l = $lm->getByField(array('action_id' => 'create', 'order_id' => $order['id']));
     $order['comment'] = ifempty($l['text']);
     $order['payment_name'] = ifset($order['params']['payment_name'], '');
     $order['shipping_name'] = ifset($order['params']['shipping_name'], '');
     // Shipping and billing addresses
     $settings = wa('shop')->getConfig()->getCheckoutSettings();
     $form_fields = ifset($settings['contactinfo']['fields'], array());
     $formatter = new waContactAddressSeveralLinesFormatter();
     $shipping_address = shopHelper::getOrderAddress($order['params'], 'shipping');
     if ($shipping_address) {
         $shipping_address = $formatter->format(array('data' => $shipping_address));
         $shipping_address = $shipping_address['value'];
     }
     if (isset($form_fields['address.billing'])) {
         $billing_address = shopHelper::getOrderAddress($order['params'], 'billing');
         $billing_address = $formatter->format(array('data' => $billing_address));
         $billing_address = $billing_address['value'];
     } else {
         $billing_address = null;
     }
     if (wa()->getUser()->getId() == $order['contact_id']) {
         $contact = wa()->getUser();
     } else {
         $contact = new waContact($order['contact_id']);
     }
     $payment = '';
     if (!empty($order['params']['payment_id']) && !$order['paid_date']) {
         try {
             $plugin = shopPayment::getPlugin(null, $order['params']['payment_id']);
             $payment = $plugin->payment(waRequest::post(), shopPayment::getOrderData($order, $plugin), false);
         } catch (waException $ex) {
             $payment = $ex->getMessage();
         }
     }
     $this->view->assign('payment', $payment);
     $tracking = '';
     if (!empty($order['params']['shipping_id']) && !empty($order['params']['tracking_number'])) {
         try {
             $plugin = shopShipping::getPlugin(null, $order['params']['shipping_id']);
             $tracking = $plugin->tracking($order['params']['tracking_number']);
         } catch (waException $ex) {
             $tracking = $ex->getMessage();
         }
     }
     $this->view->assign('tracking', $tracking);
     $this->view->assign('order', $order);
     $this->view->assign('contact', $contact);
     $this->view->assign('shipping_address', $shipping_address);
     $this->view->assign('billing_address', $billing_address);
     $this->view->assign('subtotal', $subtotal);
     // Set up layout and template from theme
     $this->setThemeTemplate('my.order.html');
     $this->view->assign('my_nav_selected', 'orders');
     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 execute()
 {
     $modelNotifierConfig = new shopNotifierConfigModel();
     $modelNotifierLog = new shopNotifierLogModel();
     $n_date = array('w' => 'week', 'd' => 'days', 'm' => 'hour', 'h' => 'minute');
     $all_notifications = $modelNotifierConfig->getAll();
     foreach ($all_notifications as $notification) {
         $last_event_date = strtotime($modelNotifierLog->getLastDateByConfigId($notification['id']));
         $last_event = strtotime('+' . $notification['repeat_number_time'] . ' ' . $n_date[$notification['repeat_period']], $last_event_date);
         if (date('Y-m-d H:i:s', $last_event) < date('Y-m-d H:i:s')) {
             $states = (array) json_decode($notification['state_name']);
             $last_time = strtotime('-' . $notification['number_time'] . ' ' . $n_date[$notification['period']], $last_event_date);
             $orders = array();
             $orders_new = array();
             foreach ($states as $s) {
                 if ($s == 'new') {
                     $collection = new shopOrdersCollection('search/state_id=new&create_datetime<' . date('Y-m-d H:i:s', $last_time));
                     $orders_new = $collection->getOrders('*,params,items,contact');
                 } else {
                     $states_without_new[] = $s;
                 }
             }
             $state_for_collection = is_array($states_without_new) ? implode('||', $states_without_new) : $states_without_new[0];
             $collection = new shopOrdersCollection('search/state_id=' . $state_for_collection . '&update_datetime<' . date('Y-m-d H:i:s', $last_time));
             $orders = $collection->getOrders('*,params,items,contact');
             if (is_array($orders_new)) {
                 $orders = array_merge($orders, $orders_new);
             }
             $emails = array();
             $notification['data_contact'] = json_decode($notification['data_contact']);
             foreach ($notification['data_contact']->contact as $contact) {
                 $user = new waContact($contact);
                 //                    $email = array();
                 $email = $user->get('email');
                 $emails[$email[0]['value']] = $user->get('name');
             }
             if (!empty($notification['data_contact']->group)) {
                 $modelContactCategory = new waContactCategoryModel();
                 foreach ($notification['data_contact']->group as $group) {
                     $contacts = $modelContactCategory->getByField('category_id', $group);
                     //                      ->query("SELECT * FROM wa_contact_categories WHERE category_id = '".$gr."'")->fetchAll('contact_id');
                     foreach ($contacts as $key => $contact) {
                         $user = new waContact($key);
                         $email = array();
                         $email = $user->get('email');
                         $emails[$email[0]['value']] = $user->get('name');
                     }
                 }
             }
             $view = wa()->getView();
             $shop_config = $general = wa('shop')->getConfig()->getGeneralSettings();
             $from = $shop_config['email'];
             if (!$from) {
                 $from = '*****@*****.**';
             }
             if (!empty($notification['send_email']) && self::isValidEmail($notification['send_email'])) {
                 $from = $notification['send_email'];
             }
             $body = file_get_contents(shopNotifierPlugin::path($notification['template']));
             //TODO: File read error
             if ($notification['group_senders'] == 1) {
                 if ($notification['save_to_order_log'] == 1) {
                     $order_log_model = new shopOrderLogModel();
                     foreach ($orders as $order) {
                         $order_log_model->add(array('order_id' => $order['id'], 'contact_id' => wa()->getUser()->getId(), 'before_state_id' => $order['state_id'], 'after_state_id' => $order['state_id'], 'text' => 'Отправлено уведомление на адреса из оповещания ' . $notification['config_name'], 'action_id' => 'comment'));
                     }
                 }
                 $view->clearAllAssign();
                 $view->assign('orders', $orders);
                 $subject_string = 'Обратите внимание на заказы';
                 $subject = $view->fetch('string:' . $subject_string);
                 $body = $view->fetch('string:' . $body);
                 $message = new waMailMessage($subject, $body);
                 $message->setTo($emails);
                 $message->setFrom($from);
                 $message->send();
             } else {
                 foreach ($orders as $order) {
                     if ($notification['save_to_order_log'] == 1) {
                         $order_log_model = new shopOrderLogModel();
                         $order_log_model->add(array('order_id' => $order['id'], 'contact_id' => wa()->getUser()->getId(), 'before_state_id' => $order['state_id'], 'after_state_id' => $order['state_id'], 'text' => 'Отослано уведомление на емайлы из оповещания ' . $notification['config_name'], 'action_id' => 'comment'));
                     }
                     $view->clearAllAssign();
                     $view->assign('order', $order);
                     $subject_string = 'Заказ ' . shopHelper::encodeOrderId($order['id']);
                     $subject = $view->fetch('string:' . $subject_string);
                     $body = $view->fetch('string:' . $body);
                     $message = new waMailMessage($subject, $body);
                     $message->setTo($emails);
                     $message->setFrom($from);
                     $message->send();
                 }
             }
             $modelNotifierLog->add(array('config_id' => $notification['id']));
         }
     }
 }