예제 #1
0
 /**
  * Удаляет всё информацию по счёту из БД.
  * @param array $args
  * @return bool true в случае успеха
  */
 public static function delete($userId, $accountId)
 {
     Core::getInstance()->db->query("START TRANSACTION");
     // Удалить счет
     $sql = "\n            UPDATE accounts\n            SET deleted_at=?,\n                updated_at=?\n            WHERE\n                    account_id = ?\n                AND user_id = ?\n            LIMIT 1";
     $now = date('Y-m-d H:i:s');
     Core::getInstance()->db->query($sql, $now, $now, $accountId, $userId);
     // Удалить все операции
     $opModel = new Operation_Model(Core::getInstance()->user);
     $opModel->deleteOperationsByAccountId($accountId);
     Core::getInstance()->db->query("COMMIT");
     $cnt = Core::getInstance()->db->select("\n            SELECT COUNT(*) FROM accounts\n            WHERE account_id = ? AND deleted_at IS NULL\n            ", $accountId);
     return $cnt[0]['COUNT(*)'] == 0;
 }
 public function last(array $args = array())
 {
     $operations = $this->model->getLastOperations(10);
     $this->_setDrain($operations);
     $this->tpl->assign('operations', $operations);
     $this->tpl->assign('name_page', 'operations/last');
 }
 /**
  * Редактирует событие
  * @return void
  */
 function edit()
 {
     $user = Core::getInstance()->user;
     // Определяем массив данных для обработки
     $request = _Core_Request::getCurrent();
     $event_array = array('id' => (int) $request->post['id'], 'chain' => (int) $request->post['chain'], 'type' => (int) $request->post['type'], 'account' => (int) $request->post['account'], 'amount' => (double) str_replace(' ', '', $request->post['amount']), 'category' => (int) $request->post['category'] <= 0 ? null : (int) $request->post['category'], 'date' => Helper_Date::RusDate2Mysql($this->getDateOperation()), 'comment' => (string) $request->post['comment'], 'tags' => isset($request->post['tags']) ? explode(',', $request->post['tags']) : array(), 'convert' => isset($request->post['convert']) ? $request->post['convert'] : 0, 'close' => isset($request->post['close']) ? $request->post['close'] : 0, 'currency' => isset($request->post['currency']) ? $request->post['currency'] : 0, 'toAccount' => isset($request->post['toAccount']) ? $request->post['toAccount'] : null, 'target' => isset($request->post['target']) ? $request->post['target'] : null, 'last' => isset($request->post['last']) ? Helper_Date::RusDate2Mysql($request->post['last']) : '0000-00-00', 'time' => isset($request->post['time']) ? $request->post['time'] : date("H:i:s"), 'every' => isset($request->post['every']) ? (int) $request->post['every'] : 0, 'repeat' => isset($request->post['repeat']) ? (int) $request->post['repeat'] : 1, 'week' => isset($request->post['week']) ? $request->post['week'] : '0000000', 'accepted' => isset($request->post['accepted']) ? (int) $request->post['accepted'] : 0);
     // Напоминания
     $notifications = $this->_readNotificationsFromRequest($request);
     $event_array = array_merge($event_array, $notifications);
     $event = new Calendar_Event(new Calendar_Model($event_array, $user), $user);
     if (!$event->checkData()) {
         $this->tpl->assign('error', array('text' => implode(",\n", $event->getErrors())));
     } else {
         // Если нет цепочки, значит только одна операция
         if ($event_array['chain'] === 0) {
             $operation = new Operation_Model();
             if ($event_array['type'] <= 1) {
                 if ($event_array['type'] == 0) {
                     $event_array['amount'] = abs($event_array['amount']) * -1;
                 } else {
                     $event_array['amount'] = abs($event_array['amount']);
                 }
                 $operation->edit($event_array['type'], $event_array['id'], $event_array['amount'], $event_array['date'], $event_array['category'], $event_array['comment'], $event_array['account'], $event_array['tags'], $event_array['accepted'], $notifications);
             } elseif ($event_array['type'] == 2) {
                 $operation->editTransfer($event_array['id'], $event_array['amount'], $event_array['convert'], $event_array['date'], $event_array['account'], $event_array['toAccount'], $event_array['comment'], $event_array['tags'], $event_array['accepted'], $notifications);
             }
             $this->tpl->assign('result', array('text' => 'Регулярная операция изменена'));
         } else {
             $calendar = new Calendar($user);
             $calendar->edit($event);
             $this->tpl->assign('result', array('text' => 'Регулярные операции изменены'));
         }
         // @FIXME Перенести этот блок кода в календарь
         Core::getInstance()->user->initUserEvents();
         Core::getInstance()->user->save();
         $this->tpl->assign('future', Core::getInstance()->user->getUserEvents('reminder'));
         $this->tpl->assign('overdue', Core::getInstance()->user->getUserEvents('overdue'));
         $this->tpl->assign('calendar', Core::getInstance()->user->getUserEvents('calendar'));
     }
 }
 /**
  * Удаляет указанную категорию
  * @param $args array mixed
  * @return void
  */
 function del($args)
 {
     $catId = 0;
     if (array_key_exists(0, $args) && is_numeric($args[0]) && $args[0]) {
         $catId = (int) $args[0];
     } elseif (isset($this->request->post['id']) && $this->request->post['id']) {
         $catId = (int) $this->request->post['id'];
     }
     // Проверяем, есть ли по категории операции
     if (isset($this->request->post['confirm']) && $this->request->post['confirm'] === 'false' && $this->model->getCountOperationByCategory(Core::getInstance()->user, $catId) > 0) {
         die(json_encode(array("confirm" => array("text" => "Эта категория содержит операции. " . "При удалении категории все операции по ней будут удалены!" . "\n\nВы действительно хотите удалить категорию?", "id" => $catId))));
     }
     // Если удаление подтверждено....
     if (isset($this->request->get['confirmed']) && $this->request->get['confirmed']) {
         // Отмечаем операции неподтверждёнными
         $operation = new Operation_Model();
         $operation->deleteOperationsByCategory(Core::getInstance()->user, $catId);
         // Удаляем категорию (делаем невидимой)
         if ($this->model->del($catId)) {
             $this->tpl->assign('result', array('text' => "Категория успешно удалена.", 'id' => $catId));
         } else {
             $this->tpl->assign('error', array('text' => "Не удалось удалить категорию."));
         }
         //возвращаемся
         if (array_key_exists('redirect', $_SESSION)) {
             _Core_Router::redirect($_SESSION['redirect'], true);
             unset($_SESSION['redirect']);
         }
     } elseif (!isset($request->get['confirmed'])) {
         $confirm = array('title' => 'Удаление категории', 'message' => 'Вы действительно хотите удалить категорию?', 'yesLink' => '/category/del/' . $catId . '?confirmed=1', 'noLink' => $_SERVER['HTTP_REFERER']);
         if ($this->model->getCountOperationByCategory(Core::getInstance()->user, $catId) > 0) {
             $confirm['message'] = "<b>Эта категория содержит операции.</b><br/>" . "При удалении категории все операции по ней будут удалены!<br/><br/>" . "Вы действительно хотите удалить категорию?";
         }
         // Сохраняем в сессии адрес куда идти если согласится
         $_SESSION['redirect'] = $_SERVER['HTTP_REFERER'];
         $this->tpl->assign('confirm', $confirm);
         $this->tpl->assign('name_page', 'confirm');
     } else {
         _Core_Router::redirect('/info');
     }
 }
 /**
  * Тест перевода на долговой счёт
  */
 public function testDebtTransfer()
 {
     $this->_prepareOperation();
     // Долговой счёт
     $options = array('user_id' => $this->userId, 'account_name' => 'Debt account', 'account_currency_id' => myMoney::RUR, 'account_type_id' => Account_Collection::ACCOUNT_TYPE_CREDIT);
     $account = CreateObjectHelper::makeAccount($options);
     $toAccountId = $account['account_id'];
     $options = array('user_id' => $this->userId, 'system_category_id' => Category_Model::DEBT_SYSTEM_CATEGORY_ID);
     $debtCategoryId = CreateObjectHelper::createCategory($options);
     $this->user->init();
     $this->user->save();
     $operation = new Operation_Model($this->user);
     // Перевели 100 рублей с рублёвого на долларовый
     $opId = $operation->addTransfer(100, 0, 0, '2010-01-01', $this->accountId, $toAccountId, 'Комментарий', array('тег 1'));
     $dateFrom = '2009-12-29';
     $dateTo = '2010-01-02';
     $list = $operation->getOperationList($dateFrom, $dateTo);
     $this->assertEquals($debtCategoryId, $list[0]['cat_id'], 'Expected only 1 transfer operation');
 }
예제 #6
0
 /**
  * Закрывает финцель
  *
  * @param int   $targetId
  * @param int   $targetCat
  * @param float $amount
  * @param int   $account
  * @return int ИД расходной операции
  */
 public function CloseOp($targetId = 0, $targetCat = 0, $amount = 0, $account = 0)
 {
     // Обновляем данные финцели
     $userId = Core::getInstance()->user->getId();
     $sql = "UPDATE target SET done=1 WHERE id = ? AND user_id = ?";
     $result = $this->db->select($sql, $targetId, $userId);
     $sql = "SELECT * FROM target WHERE id = ? AND user_id = ?";
     $target = $this->db->select($sql, $targetId, $userId);
     $title = addslashes($target[0]['title']);
     $comment = "Закрытие финансовой цели \\'{$title}\\'";
     $category = null;
     $date = date('Y-m-d');
     // Делаем фактическую операцию перевода на финцель.
     $operation = new Operation_Model(Core::getInstance()->user);
     $operationId = $operation->add(0, -$amount, $date, $category, $comment, $account, null, false);
     return $operation->getOperation($userId, $operationId);
 }
예제 #7
0
 /**
  * Отмечает события как выполненные
  * @param oldUser $user
  * @param array $ids array(int, int, int, ..)
  * @return bool
  */
 public static function acceptEvents(oldUser $user, $ids)
 {
     $operationList = array();
     foreach ($ids as $value) {
         $operationList[] = array('accepted' => '1', 'id' => $value);
     }
     if ($operationList) {
         $operation = new Operation_Model($user);
         return (bool) $operation->editMultiple($operationList);
     }
 }
예제 #8
0
 /**
  * При завершении работы, контроллера
  */
 function __destruct()
 {
     if (!session_id()) {
         session_start();
     }
     // Применение модификаций\удалений моделей (после внедрения TemplateEngine_Json - удалить)
     _Core_ObjectWatcher::getInstance()->performOperations();
     $user = Core::getInstance()->user;
     $this->addToRes('errors', Core::getInstance()->errors);
     //@TODO Удалить потом
     $res = $this->getRes();
     if (isset($_SESSION['resultMessage'])) {
         if (isset($_SESSION['messageSend'])) {
             $res['result'] = array('text' => $_SESSION['resultMessage']);
             unset($_SESSION['resultMessage'], $_SESSION['messageSend']);
         } else {
             $_SESSION['messageSend'] = true;
         }
     }
     if (isset($_SESSION['errorMessage'])) {
         if (isset($_SESSION['errorMessage'])) {
             $res['result'] = array('text' => $_SESSION['errorMessage']);
             unset($_SESSION['errorMessage'], $_SESSION['messageSend']);
         } else {
             $_SESSION['messageSend'] = true;
         }
     }
     if (is_null($user->getId())) {
         $this->tpl->assign('res', $res);
         return false;
     }
     /**
      * Счета
      */
     $accountModel = new Account_Model();
     $accounts = $accountModel->loadAllWithStat($user->getId());
     //Подготавливаем Часто используемые счета
     $oftenAccounts = array();
     $oftenAccount = array();
     foreach ($accounts as $k => $v) {
         $op = new Operation_Model();
         $oftenAccounts[$k] = $op->getNumOfOperationOnAccount($k);
     }
     arsort($oftenAccounts);
     $num = 0;
     foreach ($oftenAccounts as $k => $v) {
         if ($num < 3) {
             $oftenAccount[$k] = $oftenAccounts[$k];
             $num++;
         }
     }
     // Подготавливаем фин.цели
     $targets = array();
     try {
         $targ = $user->getUserTargets();
     } catch (Exception $e) {
         $targ = 0;
     }
     try {
         $info = new Info_Model();
         $infoa = $info->get_data();
     } catch (Exception $e) {
         $infoa = array();
     }
     try {
         $category = new Category_Model();
         $cats = $category->getCategory();
         $cats['recent'] = get_recent_category(10, 0);
     } catch (Exception $e) {
         $cats = null;
     }
     /**
      * Валюты
      */
     $ex = sfConfig::get('ex');
     $userDefaultCurrency = $user->getUserProps('user_currency_default');
     $userCurrencies = array();
     // Все валюты пользователя по курсу к базовой
     foreach ($user->getUserCurrency() as $currencyItem) {
         $userCurrencies[$currencyItem['id']] = array('cost' => number_format($ex->getRate($currencyItem['id'], $userDefaultCurrency), 4, '.', ''), 'name' => $currencyItem['charCode'], 'text' => $currencyItem['abbr']);
     }
     $userCurrencies['default'] = (int) $userDefaultCurrency;
     //валюта по умолчанию
     /**
      * Res
      */
     $res = array_merge($res, array('getNotify' => @$_SESSION['user']['getNotify'], 'tags' => $user->getUserTags(), 'cloud' => $user->getUserTags(true), 'calendar' => array('overdue' => Core::getInstance()->user->getUserEvents('overdue'), 'calendar' => Core::getInstance()->user->getUserEvents('calendar'), 'future' => Core::getInstance()->user->getUserEvents('reminder')), 'accounts' => $accounts, 'accountsRecent' => $oftenAccount, 'user_targets' => $targ['user_targets'], 'popup_targets' => $targ['pop_targets'], 'currency' => $userCurrencies, 'flash' => array('title' => '', 'value' => isset($infoa[0][0]) ? $infoa[0][0] : 0), 'targets_category' => array('1' => 'Квартира', '2' => 'Автомобиль', '3' => 'Отпуск', '4' => 'Финансовая подушка', '6' => 'Свадьба', '7' => 'Бытовая техника', '8' => 'Компьютер', '5' => 'Прочее'), 'errors' => Core::getInstance()->errors, 'budget' => Core::getInstance()->user->getUserBudget(), 'category' => $cats, 'informers' => $infoa));
     if (Core::getInstance()->user->getId() > 0) {
         $res['user'] = array('name' => Core::getInstance()->user->getName());
     }
     $this->tpl->assign('res', $res);
 }