/**
  * Проверка корректности подсчёта баланса
  */
 public function testStat()
 {
     $login = '******' . mktime();
     $pass = '******';
     $options = array('user_login' => $login, 'user_pass' => sha1($pass), 'user_active' => 1, 'user_new' => 0, 'user_currency_default' => myMoney::UAH);
     CreateObjectHelper::makeUser($options);
     $user = new oldUser($login, $pass);
     // Счета
     $options = array('user_id' => $user->getId(), 'account_name' => 'USD Account For stat test', 'account_currency_id' => myMoney::USD);
     $account = CreateObjectHelper::makeAccount($options);
     $operation = new Operation_Model($user);
     $options = array('user_id' => $user->getId());
     $catId = CreateObjectHelper::createCategory($options);
     $dateFrom = '2009-12-29';
     $dateTo = '2010-01-02';
     $rate = sfConfig::get('ex')->getRate(myMoney::UAH, myMoney::USD);
     $usdSpent = 100;
     $uahSpent = $usdSpent / $rate;
     $opId = $operation->add(Operation::TYPE_EXPENSE, $usdSpent, '2010-01-01', $catId, 'Комментарий', $account['account_id'], array('тег 1'));
     $stat = $operation->getOperationList($dateFrom, $dateTo, null, null, -1, null, null, null, true);
     $this->assertEquals(round($uahSpent, 2), round(abs($stat), 2), 'Expected 100 dollars have been spent');
 }
 /**
  * Редактирует событие
  * @param $args array mixed Какие-нибудь аргументы
  * @return void
  */
 function edit(array $args = array())
 {
     //тип редактируемой операции
     $operationId = 0;
     $operation = array();
     if (array_key_exists(0, $args) && is_numeric($args[0]) && $args[0]) {
         $operationId = (int) $args[0];
     } elseif (isset($this->request->post['id']) && $this->request->post['id']) {
         $operationId = $this->request->post['id'];
     }
     // Получаем данные по редактируемой операции (а если нет ид, то и даных фиг..)
     if ($operationId) {
         $operation = $this->model->getOperation(Core::getInstance()->user->getId(), $operationId);
         $initType = $operation['type'];
     } else {
         $operation = array();
     }
     if (_Core_Request::getCurrent()->method == 'POST') {
         // Определяем массив данных для обработки
         $operation = array('id' => $operationId, 'type' => isset($this->request->post['type']) ? $this->request->post['type'] : $operation['type'], 'account' => $this->request->post['account'], 'amount' => $this->request->post['amount'], 'category' => isset($this->request->post['category']) ? $this->request->post['category'] : null, 'date' => null, 'comment' => isset($this->request->post['comment']) ? $this->request->post['comment'] : '', 'tags' => isset($this->request->post['tags']) ? $this->request->post['tags'] : $operation['tags'], 'convert' => isset($this->request->post['convert']) ? $this->request->post['convert'] : array(), 'close' => isset($this->request->post['close']) ? $this->request->post['close'] : array(), 'currency' => isset($this->request->post['currency']) ? $this->request->post['currency'] : array(), 'toAccount' => isset($this->request->post['toAccount']) ? $this->request->post['toAccount'] : null, 'target' => isset($this->request->post['target']) ? $this->request->post['target'] : null, 'accepted' => isset($this->request->post['accepted']) ? (int) $this->request->post['accepted'] : 1);
         // Если дата передана массивом (PDA) ...
         if (is_array($this->request->post['date'])) {
             $operation['date'] = $this->request->post['date']['day'] . '.' . $this->request->post['date']['month'] . '.' . $this->request->post['date']['year'];
         } elseif (empty($this->request->post['date'])) {
             $operation['date'] = date("d.m.Y");
         } else {
             $operation['date'] = $this->request->post['date'];
         }
         $operation = $this->model->checkData($operation);
         if (is_null($operation['type'])) {
             $this->model->errorData['id'] = 'Не удалось изменить операцию';
         }
         // Если нет ошибок - проводим операцию
         if (count($this->model->errorData) == 0) {
             //если изменили тип операции
             if ($operation['type'] != $initType) {
                 if ($initType == Operation::TYPE_TARGET) {
                     $this->model->deleteTargetOperation($operation['id']);
                 } else {
                     $this->model->deleteOperation($operation['id']);
                 }
                 //удалили операцию. вот теперь создадим новую
                 switch ($operation['type']) {
                     //Расход
                     case Operation::TYPE_WASTE:
                         $operation['amount'] = abs($operation['amount']) * -1;
                         $this->model->add($operation['type'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                         break;
                         // Доход
                     // Доход
                     case Operation::TYPE_PROFIT:
                         $this->model->add($operation['type'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                         break;
                         // Перевод со счёта
                     // Перевод со счёта
                     case Operation::TYPE_TRANSFER:
                         $operation['category'] = -1;
                         $this->model->addTransfer($operation['amount'], $operation['convert'], $operation['currency'], $operation['date'], $operation['account'], $operation['toAccount'], $operation['comment'], $operation['tags']);
                         break;
                         // Перевод на финансовую цель
                     // Перевод на финансовую цель
                     case Operation::TYPE_TARGET:
                         $target = new Targets_Model();
                         $target->addTargetOperation($operation['account'], $operation['target'], $operation['amount'], $operation['comment'], $operation['date'], $operation['close']);
                         //@FIXME Сделать автоматическое получение нового списка операций, при удачном добавлении
                         //exit(json_encode($target->getLastList(0, 100)));
                         break;
                 }
             }
             // а иначе редактируем по старому, конкретную операцию
             switch ($operation['type']) {
                 case Operation::TYPE_WASTE:
                     //Расход
                     $operation['amount'] = abs($operation['amount']) * -1;
                     $this->model->edit($operation['type'], $operation['id'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                     break;
                 case Operation::TYPE_PROFIT:
                     //Доход
                     $operation['amount'] = abs($operation['amount']);
                     $this->model->edit($operation['type'], $operation['id'], $operation['amount'], $operation['date'], $operation['category'], $operation['comment'], $operation['account'], $operation['tags']);
                     break;
                 case Operation::TYPE_TRANSFER:
                     // Перевод со счёта
                     $operation['category'] = null;
                     $this->model->editTransfer($operation['id'], $operation['amount'], $operation['convert'], $operation['date'], $operation['account'], $operation['toAccount'], $operation['comment'], $operation['tags']);
                     break;
                 case Operation::TYPE_TARGET:
                     // Перевод на финансовую цель см. в модуле фин.цели
                     $target = new Targets_Model();
                     $target->editTargetOperation($operation['id'], $operation['amount'], $operation['date'], $operation['target'], $operation['account'], $operation['comment'], $operation['close']);
                     break;
             }
             // #856. fixed by Jet. выводим разные сообщения для обычной и PDA версии
             $text = '';
             if (_Core_TemplateEngine::getResponseMode($this->request) == "json") {
                 $text = "Операция успешно изменена.";
             } else {
                 $text = "Операция успешно изменена. <a href='/operation/last'>последние операции</a>";
             }
             $this->tpl->assign('result', array('text' => $text));
         } else {
             $this->tpl->assign('error', array('text' => implode(" \n", $this->model->errorData)));
         }
     }
     // Переделываем дату изменённую в checkData для вставки в mysql обратно в человеческий вид
     $operation['date'] = date('d.m.Y', strtotime($operation['date']));
     $this->tpl->assign('operation', $operation);
     $this->tpl->assign('name_page', 'operations/edit');
 }
 /**
  * Закрывает финцель
  *
  * @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);
 }