Advertisement
Orion55

Untitled

Feb 12th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 12.75 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use App\Http\Requests;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Pagination\LengthAwarePaginator;
  8. use Exception;
  9. use Mail;
  10. use Auth;
  11. use App\Http\Controllers\DeponModel;
  12. use App\Http\Controllers\SettingsModel;
  13. use App\Http\Controllers\LoggerController;
  14.  
  15. class DeponController extends Controller
  16. {
  17.     private $logger;
  18.     protected $deponModel;
  19.     protected $settingsModel;
  20.  
  21.     public function __construct(DeponModel $deponModel, SettingsModel $settingsModel, LoggerController $LoggerController)
  22.     {
  23.         //подключаем модель доступа к Ораклу
  24.         $this->deponModel = $deponModel;
  25.         //подключаем модель параметров
  26.         $this->settingsModel = $settingsModel;
  27.         //подключаем лог
  28.         $this->logger = $LoggerController->getLogger('depon');
  29.     }
  30.  
  31.     public function  index(Request $request)
  32.         //вывод списка депозитных счетов
  33.     {
  34.         $perPage = 12;
  35.         $currentPage = $request->get('page', 1);
  36.         $accs = $this->deponModel->selectRows(($currentPage - 1) * $perPage, $currentPage * $perPage);
  37.         //пагинация
  38.         $accs1 = $this->deponModel->selectContnum();
  39.         $paginator = new LengthAwarePaginator($accs1, count($accs1), $perPage, $currentPage);
  40.         $paginator->setPath($request->getBasePath());
  41.         return view('main.index', compact('accs', 'paginator'));
  42.     }
  43.  
  44.  
  45.     public function search(Request $request)
  46.         //поиск
  47.     {
  48.         $this->validate($request, ['searchField' => 'required']);
  49.         $request->flashOnly('searchField');
  50.         $accs = $this->deponModel->selectSearch($request->searchField);
  51.         return view('main.index', compact('accs'));
  52.     }
  53.  
  54.     public function clear()
  55.         //отмена формы
  56.     {
  57.         return redirect('/depon');
  58.     }
  59.  
  60.     public function edit($id = '')
  61.         //редактирование депозитного счета
  62.     {
  63.         if (empty($id)): return redirect('/depon'); endif;
  64.         $dep = $this->deponModel->selectRow($id);
  65.         return view('main.edit', compact('dep'));
  66.     }
  67.  
  68.     private function sendReport($dataArray)
  69.         //отчет о проделанной операции (закрытие счета, изменение суммы) - посылаем письмо и пишем в лог
  70.     {
  71.         $emailDepon = $this->settingsModel->getDeponEmail();
  72.  
  73.         $data = ['contnum' => $dataArray["contnum"], 'totalsum' => $dataArray["totalsum"], 'enddate' => $dataArray["enddate"], 'closedate' => $dataArray["closedate1"], 'email' => $emailDepon, 'subject' => $dataArray["messageString"]];
  74.         try {
  75.             Mail::queue('email.deponclose', $data, function ($message) use ($data) {
  76.                 $message->to($data['email']);
  77.                 $message->subject($data['subject']);
  78.             });
  79.         } catch (Exception $e) {
  80.             $this->logger->addError($e->getMessage());
  81.         }
  82.         $this->logger->addInfo($dataArray["messageString"]);
  83.     }
  84.  
  85.     public function editPost(Request $request, $id = '')
  86.         //нажата кнопка изменить сумму договора
  87.     {
  88.         if (empty($id)): return redirect('/depon'); endif;
  89.         $this->validate($request, ['totalsum' => 'required|numeric']);
  90.  
  91.         try {
  92.             $this->deponModel->changeSum($request->totalsum, $id);
  93.  
  94.             $dataАrray = [
  95.                 "messageString" => 'Сумма договора ' . $request->contnum . ' успешно изменена на ' . $request->totalsum . '!',
  96.                 "contnum" => $request->contnum,
  97.                 "totalsum" => $request->totalsum,
  98.                 "enddate" => $request->enddate,
  99.                 "closedate1" => null,
  100.                 "sess" => $request->session()
  101.             ];
  102.             $this->sendReport($dataАrray);
  103.             return redirect('/depon')->with('status', 'success')->with('message', $dataАrray["messageString"]);
  104.         } catch (Exception $e) {
  105.             $parametr = 'Сумму договора не удалось изменить! ' . $e->getMessage();
  106.             $this->logger->addError($parametr);
  107.             return redirect('/depon')->with('errors', $parametr);
  108.         }
  109.     }
  110.  
  111.     public function closeContract(Request $request, $id = '')
  112.         //закрыть депозитный договор
  113.     {
  114.         if (empty($id)): return redirect('/depon'); endif;
  115.         $this->validate($request, ['closedate' => 'required|date']);
  116.         try {
  117.             $this->deponModel->closeContract($request->closedate, $id);
  118.  
  119.             $dataАrray = [
  120.                 "messageString" => 'Договор ' . $request->contnum . ' успешно закрыт!',
  121.                 "contnum" => $request->contnum,
  122.                 "totalsum" => $request->totalsum,
  123.                 "enddate" => $request->enddate,
  124.                 "closedate1" => $request->closedate,
  125.                 "sess" => $request->session()
  126.             ];
  127.             $this->sendReport($dataАrray);
  128.             return redirect('/depon')->with('status', 'success')->with('message', $dataАrray["messageString"]);
  129.         } catch (Exception $e) {
  130.             $parametr = 'Договор не удалось закрыть! ' . $e->getMessage();
  131.             $this->logger->addError($parametr);
  132.             return redirect('/depon')->with('errors', $parametr);
  133.         }
  134.     }
  135.  
  136.     public function getSettings()
  137.         //выводим настройки для этого отчета
  138.     {
  139.         return view('main.sett', ['email' => $this->settingsModel->getDeponEmail()]);
  140.     }
  141.  
  142.     public function postSettings(Request $request)
  143.         //сохраняем настройки отчета (email)
  144.     {
  145.         $this->validate($request, ['depon_email' => 'required']);
  146.         $this->settingsModel->setDeponEmail($request->depon_email);
  147.         return redirect('/depon');
  148.     }
  149. }<?php
  150.  
  151. namespace App\Http\Controllers;
  152.  
  153. use DB;
  154. use Exception;
  155.  
  156. class DeponModel extends Controller
  157. {
  158.     private $oracleConnect;
  159.  
  160.     public function __construct()
  161.     {
  162.         //подключаемся к БД Оракл
  163.         $this->oracleConnect = DB::connection('oracle');
  164.     }
  165.  
  166.     public function selectSearch($searchValue)
  167.         //выбор записи подходящие под поиск
  168.     {
  169.         $sqlQuery = "select t.contnum, t.totalsum, t.enddate, t.closedate, t.contstatus, rowidtochar (rowid) row1 from MBCONT t where contnum like ?";
  170.         $argument = '%' . $searchValue . '%';
  171.         return $this->oracleConnect->select($sqlQuery, array($argument));
  172.     }
  173.  
  174.     public function selectContnum()
  175.         //выбрать все договоры
  176.     {
  177.         return $this->oracleConnect->select('select t.contnum from MBCONT t');
  178.     }
  179.  
  180.     public function selectRows($startNum, $lastNum)
  181.         //выбрать часть договоров (для паганиции)
  182.     {
  183.         $sqlQuery = "SELECT contnum, totalsum, enddate, closedate, contstatus, rowidtochar (rowid) row1
  184.                      FROM (SELECT t.contnum,
  185.                                   t.totalsum,
  186.                                   t.enddate,
  187.                                   t.closedate,
  188.                                   t.contstatus,
  189.                                   row_number() over(order by t.contstatus asc, t.enddate) rnk
  190.                              FROM mbcont t)
  191.                     WHERE rnk BETWEEN ? AND ?";
  192.         return $this->oracleConnect->select($sqlQuery, [$startNum, $lastNum]);
  193.     }
  194.  
  195.     public function selectRow($number)
  196.         //выбрать одну запись
  197.     {
  198.         $sqlQuery = "select t.contnum, t.totalsum, t.enddate, t.closedate, rowidtochar (?) row1 from MBCONT t where rowid = CHARTOROWID(?)";
  199.         $argument = $number;
  200.         return $this->oracleConnect->selectOne($sqlQuery, [$argument, $argument]);
  201.     }
  202.  
  203.     public function changeSum($sum, $id)
  204.         //изменить сумму договора
  205.     {
  206.         $this->oracleConnect->beginTransaction();
  207.         try {
  208.             $sqlQuery = "update mbcont t set t.totalsum = ? where rowid = CHARTOROWID (?)";
  209.             $this->oracleConnect->update($sqlQuery, [$sum, $id]);
  210.         } catch (Exception $e) {
  211.             $this->oracleConnect->rollBack();
  212.             throw $e;
  213.         }
  214.         $this->oracleConnect->commit();
  215.     }
  216.  
  217.     public function closeContract($date, $id)
  218.         //закрыть депозитный договор
  219.     {
  220.         $this->oracleConnect->beginTransaction();
  221.         try {
  222.             $sqlQuery = "update mbcont t set t.closedate = to_date(?, 'dd-mm-yyyy'), t.ContStatus = 2 where rowid = CHARTOROWID(?)";
  223.             $this->oracleConnect->update($sqlQuery, [$date, $id]);
  224.         } catch (Exception $e) {
  225.             $this->oracleConnect->rollBack();
  226.             throw $e;
  227.         }
  228.         $this->oracleConnect->commit();
  229.     }
  230. }
  231. <?php
  232.  
  233. namespace App\Http\Controllers;
  234.  
  235. use Monolog\Logger;
  236. use Monolog\Handler\RotatingFileHandler;
  237. use Monolog\Processor\WebProcessor;
  238. use Monolog\Formatter\LineFormatter;
  239. use Auth;
  240.  
  241.  
  242. class LoggerController extends Controller
  243. {
  244.     private $channels = [];
  245.  
  246.     public function getLogger($channelName)
  247.         //получить или создать логгер
  248.     {
  249.         if (!array_key_exists($channelName, $this->channels)) {
  250.             $this->createLogger($channelName);
  251.         }
  252.         return $this->channels[$channelName];
  253.     }
  254.  
  255.     private function createLogger($channelName)
  256.         //создать логгер
  257.     {
  258.         $logger = new Logger($channelName);
  259.         $parametr = 'logs\\' . $channelName . '.' . 'log';
  260.         $handler = new RotatingFileHandler(storage_path($parametr), Logger::INFO);
  261.  
  262.         $user = Auth::user();
  263.         $handler->setFormatter(new LineFormatter("[%datetime%] %channel%.%level_name%: " . 'User Name: ' . $user->getAttributeValue('name') . ' | User Email: ' . $user->getAttributeValue('email') . ' | ' . "%message% %extra% %context%\n"));
  264.         $logger->pushHandler($handler);
  265.         $logger->pushProcessor(new WebProcessor);
  266.  
  267.         $this->channels[$channelName] = $logger;
  268.         return $logger;
  269.     }
  270. }<?php
  271.  
  272. /*
  273. |--------------------------------------------------------------------------
  274. | Application Routes
  275. |--------------------------------------------------------------------------
  276. |
  277. | Here is where you can register all of the routes for an application.
  278. | It's a breeze. Simply tell Laravel the URIs it should respond to
  279. | and give it the controller to call when that URI is requested.
  280. |
  281. */
  282.  
  283. Route::get('/', 'DeponController@index')->middleware('auth');
  284.  
  285. // Authentication Routes...
  286. Route::get('auth/login', 'Auth\AuthController@getLogin');
  287. Route::post('auth/login', 'Auth\AuthController@postLogin');
  288. Route::get('auth/logout', 'Auth\AuthController@getLogout');
  289.  
  290. // Registration Routes...
  291. Route::get('auth/register', 'Auth\AuthController@getRegister');
  292. Route::post('auth/register', 'Auth\AuthController@postRegister');
  293.  
  294. //заходят только авторизованные пользователи
  295.  
  296. Route::group(['middleware' => 'auth'], function () {
  297.     $d = 'depon.';
  298.     Route::get('/depon', ['as' => $d . 'index', 'uses' => 'DeponController@index']);
  299.     Route::post('/depon', ['as' => $d . 'search', 'uses' => 'DeponController@search']);
  300.     Route::get('/depon/clear', ['as' => $d . 'cancel', 'uses' => 'DeponController@clear']);
  301.     Route::get('/depon/edit/{id?}', ['as' => $d . 'edit', 'uses' => 'DeponController@edit']);
  302.     Route::post('/depon/edit/{id?}', ['as' => $d . 'editpost', 'uses' => 'DeponController@editPost']);
  303.     Route::post('/depon/close/{id?}', ['as' => $d . 'close', 'uses' => 'DeponController@closeContract']);
  304.     Route::get('/depon/settings', ['as' => 'settings.get', 'uses' => 'DeponController@getSettings']);
  305.     Route::post('/depon/settings', ['as' => 'settings.post', 'uses' => 'DeponController@postSettings']);
  306. });
  307.  
  308. Route::resource('user', 'UserController');
  309.  
  310. Route::get('test', function () {
  311.     Echo 'Ok!';
  312. });<?php
  313.  
  314. namespace App\Http\Controllers;
  315.  
  316. use Illuminate\Http\Request;
  317.  
  318. use App\Http\Requests;
  319. use App\Http\Controllers\Controller;
  320. use DB;
  321.  
  322. class SettingsModel extends Controller
  323. {
  324.     public function getDeponEmail()
  325.         //получить email для отправки отчета
  326.     {
  327.         return DB::table('settings')->where('parametername', 'depon_email')->value('parametervalue');
  328.     }
  329.  
  330.     public function setDeponEmail($email)
  331.         //установить email для отчета
  332.     {
  333.         DB::table('settings')->where('parametername', 'depon_email')->update(['parametervalue' => $email]);
  334.     }
  335. }
  336. 
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement