Ejemplo n.º 1
9
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Clearing permissions... \n");
     // Delete old data
     $response = Action::deleteAllData();
     null !== $response ? $this->error("\n" . $response . "\n") : null;
     $this->info("Permissions cleared... \n");
     try {
         $routeData = $this->getRouteData();
         $roles = Role::all();
         DB::beginTransaction();
         foreach ($routeData as $action => $uri) {
             $action = new Action(['uri' => $uri, 'action' => $action]);
             $action->save();
             $this->savePermissions($roles, $action);
             $this->comment("Added action " . $action->action . "\n");
         }
         $cache = $this->getCacheInstance(['permissions']);
         $cache->flush();
         DB::commit();
     } catch (\Exception $e) {
         DB::rollBack();
         $this->error("\n" . $e->getMessage() . "\n");
     }
 }
Ejemplo n.º 2
0
 public function testTransaction()
 {
     DB::beginTransaction();
     DB::insert('insert into users (name,email,password) values (?,?,?)', ['ceshi', '*****@*****.**', 'ddddd']);
     //        DB::rollback();
     DB::commit();
 }
Ejemplo n.º 3
0
 public function interest()
 {
     DB::beginTransaction();
     Interest::create(['res' => Input::get('id'), 'wanderer' => Session::get(MateMiddleware::$VERIFY)]);
     DB::commit();
     return 'recorded';
 }
 /**
  * Handle the event.
  *
  * @param CurrencyMessageReceivedEvent
  * @return void
  */
 public function handle(CurrencyMessageReceivedEvent $event)
 {
     $timePlaced = new \DateTime($event->message->time_placed);
     $rate = MonthlyRate::where('year', $timePlaced->format('Y'))->where('month', $timePlaced->format('m'))->where('currency_from', $event->message->getAttribute('currency_from'))->where('currency_to', $event->message->getAttribute('currency_to'))->get()->first();
     if (is_null($rate)) {
         $rate = new MonthlyRate();
         $rate->tot_messages = 1;
         $rate->currency_from = $event->message->getAttribute('currency_from');
         $rate->currency_to = $event->message->getAttribute('currency_to');
         $rate->sum_rate = $event->message->getAttribute('rate');
         $rate->month = $timePlaced->format('m');
         $rate->year = $timePlaced->format('Y');
     } else {
         $rate->tot_messages++;
         $rate->sum_rate += $event->message->getAttribute('rate');
     }
     DB::beginTransaction();
     try {
         $rate->save();
         $key = $rate->currency_from . '-' . $rate->currency_to;
         $message = [$key => ['rate' => $rate->avg_rate, 'month' => $rate->month]];
         // Push message in redis to be displayed in the frontend
         $this->pushToSocket($message);
         DB::commit();
     } catch (\ErrorException $e) {
         DB::rollBack();
         // Throw the exception again to signal an error
         // in the processing
         throw $e;
     } catch (\Exception $e) {
         DB::rollBack();
         throw $e;
     }
 }
Ejemplo n.º 5
0
 public function saveTrackerEntry(Request $request)
 {
     // return $request->all();
     $validator = Validator::make($request->all(), ['desc' => 'required|min:5', 'time' => 'required|numeric', 'tags' => 'required', 'project_id' => 'required']);
     if ($request->input('project_id') == 'Select Project') {
         Session::flash('flash_error', 'You need to select the project');
         return redirect()->back()->withInput();
     }
     if ($validator->fails()) {
         return redirect()->back()->withErrors($validator)->withInput();
     }
     try {
         DB::beginTransaction();
         $project = Project::with('client')->find($request->input('project_id'));
         $entry = TimeEntry::create(['desc' => $request->input('desc'), 'user_id' => Auth::user()->id, 'project_id' => $project->id, 'project_name' => $project->name, 'client_name' => $project->client->name, 'time' => $request->input('time')]);
         // adding the entry of the ticket with tags mapping table
         foreach ($request->input('tags') as $key => $value) {
             DB::table('taggables')->insert(['tag_id' => $value, 'taggable_id' => $entry->id, 'taggable_type' => 'ticket', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
         }
         if ($request->input('estimate_id')) {
             DB::table('time_entry_estimates')->insert(['time_entry_id' => $entry->id, 'estimate_id' => $request->input('estimate_id'), 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
             DB::update("UPDATE estimates SET hours_consumed = hours_consumed + :hours WHERE id = :id", ['hours' => $request->input('time'), 'id' => $request->input('estimate_id')]);
         }
         DB::commit();
         Session::flash('flash_message', 'Entry saved');
         return redirect('time-tracker');
     } catch (\PDOException $e) {
         DB::rollBack();
         abort(403, 'Data was not saved. Try again' . $e->getMessage());
     }
 }
Ejemplo n.º 6
0
 public function update(Request $request, $id)
 {
     $departamento = $request->input('departamento');
     if ($departamento != '0') {
         try {
             DB::beginTransaction();
             $usuario = User::find($id);
             $empleado = $usuario->empleado;
             $empleado->nombre = Str::upper($request->input('nombre'));
             $empleado->apellido_paterno = Str::upper($request->input('apellido_paterno'));
             $empleado->apellido_materno = Str::upper($request->input('apellido_materno'));
             $empleado->save();
             $usuario->username = Str::upper($request->input('username'));
             $usuario->password = bcrypt($request->input('password'));
             $usuario->rol_id = $request->input('departamento');
             $usuario->save();
             DB::commit();
             return redirect()->route('usuario.index');
         } catch (QueryException $e) {
             echo $e;
             DB::rollBack();
             return redirect()->route('usuario.edit', $id);
         }
     } else {
         return redirect()->route('usuario.edit', $id);
     }
 }
Ejemplo n.º 7
0
 /**
  * Performs the actual processing
  */
 protected function doProcessing()
 {
     $this->prepareProcessContext();
     // initialization process pipeline
     $initSteps = $this->initProcessSteps();
     if (!empty($initSteps)) {
         $this->context = app(Pipeline::class)->send($this->context)->through($initSteps)->then(function (ProcessContextInterface $context) {
             return $context;
         });
         $this->afterInitSteps();
     }
     // main pipeline (actual processing)
     $steps = $this->processSteps();
     if ($this->databaseTransaction) {
         DB::beginTransaction();
     }
     try {
         $this->context = app(Pipeline::class)->send($this->context)->through($steps)->then(function (ProcessContextInterface $context) {
             if ($this->databaseTransaction) {
                 DB::commit();
             }
             return $context;
         });
     } catch (Exception $e) {
         if ($this->databaseTransaction) {
             DB::rollBack();
         }
         $this->onExceptionInPipeline($e);
         throw $e;
     }
     $this->afterPipeline();
     $this->populateResult();
 }
Ejemplo n.º 8
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function postStore(Request $request)
 {
     $input = $request->all();
     //		return ($input['Administrative']);
     DB::beginTransaction();
     $apps = Application::create($input['REGISTRANT']);
     $input['Administrative']['registrant_id'] = $apps->id;
     $input['Technical']['registrant_id'] = $apps->id;
     if ($request->hasFile("image1")) {
         $destinationPath = 'uploads/a/';
         $fileName = time() . "-" . $request->file('image1')->getClientOriginalName();
         $request->file('image1')->move($destinationPath, $fileName);
         $input['Administrative']['image'] = $fileName;
     }
     if ($request->hasFile('image2')) {
         $destinationPath = 'uploads/t/';
         $fileName = time() . "-" . $request->file('image2')->getClientOriginalName();
         $request->file('image2')->move($destinationPath, $fileName);
         $input['Technical']['image'] = $fileName;
     }
     return 1;
     Administrative::create($input['Administrative']);
     Technical::create($input['Technical']);
     DB::commit();
     return redirect()->back()->withSuccess('Application Submitted Successfully');
 }
Ejemplo n.º 9
0
 /**
  * Veritrans Credit Card
  *
  * 1. Check Order
  * 2. Save Payment
  * 
  * @return Response
  */
 public function veritranscc()
 {
     if (!Input::has('order_id')) {
         return new JSend('error', (array) Input::all(), 'Tidak ada data order id.');
     }
     $errors = new MessageBag();
     DB::beginTransaction();
     //1. Validate Sale Parameter
     $order = Input::only('order_id', 'gross_amount', 'payment_type', 'masked_card', 'transaction_id');
     //1a. Get original data
     $sale_data = \App\Models\Sale::findorfail($order['order_id']);
     //2. Save Payment
     $paid_data = new \App\Models\Payment();
     $payment['transaction_id'] = $sale_data['id'];
     $payment['method'] = $order['payment_type'];
     $payment['destination'] = 'Veritrans';
     $payment['account_name'] = $order['masked_card'];
     $payment['account_number'] = $order['transaction_id'];
     $payment['ondate'] = \Carbon\Carbon::parse($order['transaction_time'])->format('Y-m-d H:i:s');
     $payment['amount'] = $order['gross_amount'];
     $paid_data = $paid_data->fill($payment);
     if (!$paid_data->save()) {
         $errors->add('Log', $paid_data->getError());
     }
     if ($errors->count()) {
         DB::rollback();
         return response()->json(new JSend('error', (array) Input::all(), $errors), 404);
     }
     DB::commit();
     $final_sale = \App\Models\Sale::id($sale_data['id'])->with(['voucher', 'transactionlogs', 'user', 'transactiondetails', 'transactiondetails.varian', 'transactiondetails.varian.product', 'paidpointlogs', 'payment', 'shipment', 'shipment.address', 'shipment.courier', 'transactionextensions', 'transactionextensions.productextension'])->first()->toArray();
     return response()->json(new JSend('success', (array) $final_sale), 200);
 }
Ejemplo n.º 10
0
 /**
  * Creates a type
  *
  * @param null|array $data
  * @return null|TypeModel
  */
 public function create($data = null)
 {
     DB::beginTransaction();
     try {
         if (is_null($data)) {
             throw new NullDataException('The data array is required!');
         }
         foreach ($data as $k => $v) {
             if (!in_array($k, $this->fields)) {
                 throw new CreateTypeException('Please add the correct fields!');
             }
         }
         if (count(array_keys($data)) != count($this->fields)) {
             throw new CreateTypeException('The number of given data is different than required!');
         }
         if (TypeModel::whereName($data['name'])->first()) {
             throw new CreateTypeException('The type name already exists!');
         }
         $type = TypeModel::create($data);
         DB::commit();
         return $type;
     } catch (NullDataException $e) {
         DB::rollBack();
         return $e;
     } catch (CreateTypeException $e) {
         DB::rollBack();
         return $e;
     }
 }
 /**
  * set pasword
  *
  * 1. get activation link
  * 2. validate activation
  * @param activation link
  * @return array of employee
  */
 public function setPassword($activation_link)
 {
     if (!Input::has('activation')) {
         return new JSend('error', (array) Input::all(), 'Tidak ada data activation.');
     }
     $errors = new MessageBag();
     DB::beginTransaction();
     //1. Validate activation Parameter
     $activation = Input::get('activation');
     //1. get activation link
     $employee = Employee::activationlink($activation_link)->first();
     if (!$employee) {
         $errors->add('Activation', 'Invalid activation link');
     }
     //2. validate activation
     $rules = ['password' => 'required|min:8|confirmed'];
     $validator = Validator::make($activation, $rules);
     if ($validator->passes()) {
         $employee->password = $activation['password'];
         $employee->activation_link = '';
         if (!$employee->save()) {
             $errors->add('Activation', $employee->getError());
         }
     } else {
         $errors->add('Activation', $validator->errors());
     }
     if ($errors->count()) {
         DB::rollback();
         return new JSend('error', (array) Input::all(), $errors);
     }
     DB::commit();
     return new JSend('success', ['employee' => $employee->toArray()]);
 }
Ejemplo n.º 12
0
 public function postAddIntrare()
 {
     $rules = array('expeditor' => 'required', 'destinatar' => 'required');
     $errors = array('required' => 'Campul este obligatoriu.');
     $validator = Validator::make(Input::all(), $rules, $errors);
     if ($validator->fails()) {
         return Redirect::back()->with('message', 'Eroare validare formular!')->withErrors($validator)->withInput();
     } else {
         DB::beginTransaction();
         try {
             $numar_inregistrare = DB::table('registru_intrare')->select(DB::raw('max(numar_inregistrare) AS numar_inregistrare'))->where('logical_delete', 0)->get();
             $urmatorul_numar_inregistrare = 0;
             if ($numar_inregistrare[0]->numar_inregistrare > 0) {
                 $urmatorul_numar_inregistrare = $numar_inregistrare[0]->numar_inregistrare;
             }
             $urmatorul_numar_inregistrare++;
             DB::table('registru_intrare')->insertGetId(array('numar_inregistrare' => $urmatorul_numar_inregistrare, 'expeditor' => Input::get('expeditor'), 'numar_inregistrare_expeditor' => Input::get('numar_inregistrare_expeditor'), 'numar_anexe' => Input::get('numar_anexe'), 'continut' => Input::get('continut'), 'destinatar' => Input::get('destinatar'), 'observatii' => Input::get('observatii')));
         } catch (Exception $e) {
             DB::rollback();
             return Redirect::back()->with('message', 'Eroare salvare date: ' . $e)->withInput();
         }
         DB::commit();
         return Redirect::back()->with('message', 'Salvare realizata cu succes!');
     }
 }
Ejemplo n.º 13
0
 /**
  * Reschedule an existing event.
  *
  * @param  Event  $oldEvent
  * @param  array  $data
  * @return Event
  * @throws Exception
  */
 public function reschedule(Event $oldEvent, array $data)
 {
     try {
         DB::beginTransaction();
         // Recreate venue
         $newVenue = $oldEvent->venue->replicate();
         if (is_array($data['venue']) && count($data['venue'])) {
             $newVenue->fill($data['venue']);
         }
         $newVenue->save();
         // Recreate event
         $newEvent = $oldEvent->replicate();
         if (is_array($data['event']) && count($data['event'])) {
             $newEvent->fill($data['event']);
         }
         $newEvent->status_id = EventStatus::ACTIVE;
         $newEvent->venue_id = $newVenue->id;
         $newEvent->save();
         DB::commit();
         return $newEvent;
     } catch (\Exception $e) {
         DB::rollBack();
         throw $e;
     }
 }
Ejemplo n.º 14
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     Model::unguard();
     DB::beginTransaction();
     DB::statement('SET FOREIGN_KEY_CHECKS = 0');
     DB::table('routes')->delete();
     DB::table('contents')->delete();
     DB::table('categories')->delete();
     DB::table('content_types')->delete();
     DB::table('languages')->delete();
     DB::table('group_user')->delete();
     DB::table('user_meta')->delete();
     DB::table('users')->delete();
     DB::table('groups')->delete();
     DB::table('routes')->truncate();
     DB::table('contents')->truncate();
     DB::table('categories')->truncate();
     DB::table('content_types')->truncate();
     DB::table('languages')->truncate();
     DB::table('group_user')->truncate();
     DB::table('user_meta')->truncate();
     DB::table('users')->truncate();
     DB::table('groups')->truncate();
     DB::statement('SET FOREIGN_KEY_CHECKS = 1');
     DB::commit();
     Model::reguard();
 }
Ejemplo n.º 15
0
 function placeOrder($request)
 {
     //@TODO: transaction starts
     //        DB::beginTransaction();
     \Illuminate\Support\Facades\DB::beginTransaction();
     try {
         $order = $this->create($request);
         $orderHasItemsDao = new OrderHasItemsDao();
         $eoahDao = new OrderAddressHistoryDao();
         $eoahDao->create(array('order_id' => $order->id, 'address_id' => $request['address_id']));
         $orderOrderHistoryObj = new OrderHistoryDao();
         foreach ($request['items'] as $value) {
             $orderHasItemsObj = $orderHasItemsDao->create(array('item_id' => $value['_id'], 'order_id' => $order->id, 'quantity' => $value['_quantity']));
             //$orderOrderHistoryObj->addToOrderHistory(array("item_id"=>$value['_id'],'order_id' => $order->id));
         }
         \Illuminate\Support\Facades\DB::commit();
         return $order;
     } catch (\Exception $e) {
         \Illuminate\Support\Facades\DB::rollback();
         //            throw
         print_r($e->getMessage());
         throw new \Exception("Error internal server error", 500);
     }
     // transsaction ends
     //\Illuminate\Support\Facades\Event::fire(new OrderWasMade());
 }
 /**
  * @return callable
  */
 protected function createResourceCallable()
 {
     $createOrderResource = function (Model $model, array $data) {
         if (!empty($data['relationships']['order']['data'])) {
             $orderData = $data['relationships']['order']['data'];
             if (!empty($orderData['type'])) {
                 $orderData = [$orderData];
             }
             foreach ($orderData as $order) {
                 $attributes = array_merge($order['attributes'], ['employee_id' => $model->getKey()]);
                 Orders::create($attributes);
             }
         }
     };
     return function (array $data, array $values, ErrorBag $errorBag) use($createOrderResource) {
         $attributes = [];
         foreach ($values as $name => $value) {
             $attributes[$name] = $value;
         }
         if (!empty($data['id'])) {
             $attributes[$this->getDataModel()->getKeyName()] = $values['id'];
         }
         DB::beginTransaction();
         try {
             $model = $this->getDataModel()->create($attributes);
             $createOrderResource($model, $data);
             DB::commit();
             return $model;
         } catch (\Exception $e) {
             DB::rollback();
             $errorBag[] = new Error('creation_error', 'Resource could not be created');
             throw new \Exception();
         }
     };
 }
Ejemplo n.º 17
0
 /**
  * Update tickets from built plan
  *
  * @param $planId
  * @param $ticketsData
  * @return bool
  */
 public function updateBuiltTickets($planId, $ticketsData)
 {
     $redirect = false;
     $errorMsg = '';
     // Start transaction
     DB::beginTransaction();
     // Start tickets update
     try {
         $ticket = $this->model->where('plan_id', '=', $planId);
         $ticket->update(['tickets' => serialize($ticketsData)]);
     } catch (\Exception $e) {
         $errorMsg = $e->getMessage();
         $redirect = true;
     } catch (QueryException $e) {
         $errorMsg = $e->getErrors();
         $redirect = true;
     } catch (ModelNotFoundException $e) {
         $errorMsg = $e->getErrors();
         $redirect = true;
     }
     // Redirect if errors
     if ($redirect) {
         // Rollback
         DB::rollback();
         // Log to system
         Tools::log($errorMsg, $ticketsData);
         return false;
     }
     // Commit all changes
     DB::commit();
     return true;
 }
Ejemplo n.º 18
0
 public function run()
 {
     if (file_exists(__DIR__ . '/cities.txt') && file_exists(__DIR__ . '/cidr_optim.txt')) {
         DB::table('ipgeobase_cities')->delete();
         $file = file(__DIR__ . '/cities.txt');
         $pattern = '#(\\d+)\\s+(.*?)\\t+(.*?)\\t+(.*?)\\t+(.*?)\\s+(.*)#';
         DB::beginTransaction();
         foreach ($file as $row) {
             if (preg_match($pattern, $row, $out)) {
                 DB::table('ipgeobase_cities')->insert(array('id' => $out[1], 'city' => $out[2], 'region' => $out[3], 'district' => $out[4], 'lat' => $out[5], 'lng' => $out[6], 'country' => ''));
             }
         }
         DB::commit();
         DB::table('ipgeobase_base')->delete();
         $file = file(__DIR__ . '/cidr_optim.txt');
         $pattern = '#(\\d+)\\s+(\\d+)\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+-\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+(\\w+)\\s+(\\d+|-)#';
         DB::beginTransaction();
         foreach ($file as $row) {
             if (preg_match($pattern, $row, $out)) {
                 DB::table('ipgeobase_base')->insert(array('long_ip1' => $out[1], 'long_ip2' => $out[2], 'ip1' => $out[3], 'ip2' => $out[4], 'country' => $out[5], 'city_id' => is_numeric($out[6]) && 0 < (int) $out[6] ? (int) $out[6] : null));
             }
         }
         DB::commit();
         $cities = DB::table('ipgeobase_cities')->join('ipgeobase_base', 'ipgeobase_cities.id', '=', 'ipgeobase_base.city_id')->select('ipgeobase_cities.id', 'ipgeobase_base.country')->get();
         DB::beginTransaction();
         foreach ($cities as $city) {
             DB::table('ipgeobase_cities')->where('id', $city->id)->update(array('country' => $city->country));
         }
         DB::commit();
     }
 }
Ejemplo n.º 19
0
 /**
  * Creates an activity
  *
  * @param null|array $data
  * @return null|ActivityModel
  */
 public function create($data = null)
 {
     DB::beginTransaction();
     try {
         if (is_null($data)) {
             throw new NullDataException('The data array is required!');
         }
         foreach ($data as $k => $v) {
             if (!in_array($k, $this->fields)) {
                 throw new CreateActivityException('Please add the correct fields!');
             }
         }
         if (count(array_keys($data)) != count($this->fields)) {
             throw new CreateActivityException('The number of given data is different than required!');
         }
         $this->checkFields($data);
         $activity = ActivityModel::create($data);
         DB::commit();
         return $activity;
     } catch (NullDataException $e) {
         DB::rollBack();
         return $e;
     } catch (CreateActivityException $e) {
         DB::rollBack();
         return $e;
     }
 }
Ejemplo n.º 20
0
 function add(array $request, $lead_id)
 {
     DB::beginTransaction();
     try {
         $application_id = Application::select('id')->where('ex_lead_id', $lead_id)->first()->id;
         /* For each applicant */
         foreach ($request['title'] as $key => $title) {
             if (!isset($request['applicant_id'][$key])) {
                 $applicant_id = $this->addApplicant($request, $key, $application_id);
             } else {
                 $applicant_id = $request['applicant_id'][$key];
                 $this->editApplicant($request, $key, $applicant_id);
             }
             /* Contact Details */
             $this->addPhoneDetails($request, $key, $applicant_id);
             /* Add code here for additional phones */
             /* Address Details */
             $this->addAddressDetails($request, $key, $applicant_id);
         }
         DB::commit();
         return true;
     } catch (\Exception $e) {
         DB::rollback();
         dd($e);
         return false;
     }
 }
Ejemplo n.º 21
0
 public function clear(Request $request)
 {
     $post = $request->all();
     $comment = $post['comment'];
     $value = $post['amount'];
     $student = $post['regNo'];
     $clearedAt = $post['signedAt'];
     $clearedBy = $post['signedBy'];
     $comment = preg_replace('/[^A-Za-z0-9 _]/', '', $comment);
     $value = preg_replace('/[^0-9]/', '', $value);
     DB::beginTransaction();
     $submit = DB::update("UPDATE charge\n            INNER JOIN comments ON charge.students_studentNo = comments.students_studentNo\n            INNER JOIN cleared_at ON charge.students_studentNo = cleared_at.students_studentNo\n            INNER JOIN cleared_by ON charge.students_studentNo = cleared_by.students_studentNo\n            SET\n            charge.cafeteria_value = '{$value}',\n            charge.queueFlag = charge.queueFlag + 1,\n            comments.cafeteria = '{$comment}',\n            cleared_at.cafeteria_cleared_at = '{$clearedAt}',\n            cleared_by.cafeteria_cleared_by = '{$clearedBy}'\n\n            WHERE charge.students_studentNo = '{$student}'\n            AND comments.students_studentNo = '{$student}'\n            AND cleared_at.students_studentNo = '{$student}'\n            AND cleared_by.students_studentNo='{$student}' ");
     if ($submit) {
         DB::commit();
     } else {
         DB::rollBack();
     }
     // $admin = DB::table('departments')
     //         ->join('administrators','departments.administrator','=','administrators.admin_id')
     //         ->select('administrators.email')->where('departments.department_name','=','Library')
     //         ->pluck('email');
     //Send Mail
     // Mail::send('mails.clear', ['student' => $student ], function($message) use($admin){
     //     $message->to($admin)->from('*****@*****.**', 'Strathmore University')->subject('Clearance');
     // });
     return redirect('/cafeteria');
 }
 /**
  * Handle permissions change
  *
  * @param Request $request
  * @return \Illuminate\Http\RedirectResponse
  */
 public function putAll(Request $request)
 {
     $permissions = Permission::all();
     $input = array_keys($request->input('permissions'));
     try {
         DB::beginTransaction();
         $permissions->each(function ($permission) use($input) {
             if (in_array($permission->id, $input)) {
                 $permission->allow = true;
             } else {
                 $permission->allow = false;
             }
             $permission->save();
         });
         DB::commit();
         flash()->success(trans('permissions.save_success'));
     } catch (\Exception $e) {
         var_dump($e->getMessage());
         die;
         flash()->error(trans('permissions.save_error'));
     }
     try {
         Cache::tags(['permissions'])->flush();
     } catch (\Exception $e) {
         Cache::flush();
     }
     return redirect()->back();
 }
Ejemplo n.º 23
0
 public function create(array $data)
 {
     DB::beginTransaction();
     try {
         $data['status'] = 0;
         if (isset($data['cupom_code'])) {
             $cupom = $this->cupomRepository->findByField('code', $data['cupom_code'])->first();
             $data['cupom_id'] = $cupom->id;
             $cupom->used = 1;
             $cupom->save();
             unset($data['cupom_code']);
         }
         $items = $data['items'];
         unset($data['item']);
         $order = $this->orderRepository->create($data);
         $total = 0;
         foreach ($items as $item) {
             $item['price'] = $this->productRepository->find($item['product_id'])->price;
             $order->items()->create($item);
             $total += $item['price'] * $item['qtd'];
         }
         $order->total = $total;
         if (isset($cupom)) {
             $order->total = $total - $cupom->value;
         }
         $order->save();
         DB::commit();
         return $order;
     } catch (\Exception $e) {
         DB::rollback();
         throw $e;
     }
 }
Ejemplo n.º 24
0
 /**
  * Store a newly created employee in storage
  */
 public function store()
 {
     $validator = Validator::make($input = Input::all(), Personal::rules('create'));
     if ($validator->fails()) {
         return Redirect::back()->withErrors($validator)->withInput();
     }
     DB::beginTransaction();
     try {
         $nombres = $input['nombres'];
         $apellidos = $input['apellidos'];
         $filename = null;
         // Profile Image Upload
         if (Input::hasFile('fotoPersonal')) {
             return "gola a todos";
             $path = public_path() . "/foto/";
             File::makeDirectory($path, $mode = 0777, true, true);
             $image = Input::file('fotoPersonal');
             $extension = $image->getClientOriginalExtension();
             $filename = "{$nombres}_{$input['personalID']}." . strtolower($extension);
             Image::make($image->getRealPath())->fit(872, 724, function ($constraint) {
                 $constraint->upsize();
             })->save($path . $filename);
         }
         $tipo = "Aportante";
         //            return Input::all();
         Personal::create(['personalID' => $input['personalID'], 'emision' => $input['nitcit2'], 'nombres' => ucwords(strtolower($input['nombres'])), 'apellidos' => ucwords(strtolower($input['apellidos'])), 'email' => $input['email'], 'password' => Hash::make($input['password']), 'genero' => $input['genero'], 'tipoPersonal' => $tipo, 'telefono' => $input['telefono'], 'fotoPersonal' => isset($filename) ? $filename : 'default.jpg']);
         Activity::log(['contentId' => $input['personalID'], 'contentType' => 'Personal Aportante', 'user_id' => Auth::admin()->get()->id, 'action' => 'Creando Un Aportante', 'description' => 'Creacion ' . $tipo, 'details' => 'Usuario: ' . Auth::admin()->get()->name, 'updated' => $input['personalID'] ? true : false]);
         //            return Input::all();
     } catch (\Exception $e) {
         DB::rollback();
         throw $e;
     }
     DB::commit();
     return Redirect::route('admin.personal.index')->with('success', "<strong>{$nombres}</strong> exitosamente adicionado en le base de datos");
 }
Ejemplo n.º 25
0
 public function getDeleteApplication($id)
 {
     DB::beginTransaction();
     Application::where('id', $id)->delete();
     Administrative::where('registrant_id', $id)->delete();
     Technical::where('registrant_id', $id)->delete();
     DB::commit();
 }
Ejemplo n.º 26
0
 public function run($userId)
 {
     DB::beginTransaction();
     $user = User::findOrFail($userId);
     $user->profile()->delete();
     $user->delete();
     DB::commit();
 }
Ejemplo n.º 27
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     DB::beginTransaction();
     DB::statement('SET FOREIGN_KEY_CHECKS = 0');
     DB::table($this->argument('table_name'))->truncate();
     DB::statement('SET FOREIGN_KEY_CHECKS = 1');
     DB::commit();
     $this->comment(PHP_EOL . 'Database table "' . $this->argument('table_name') . '" was truncated.' . PHP_EOL);
 }
Ejemplo n.º 28
0
 public function changeStatus(ChangeStatusOrderRequest $request)
 {
     $idOrder = $request->input('id');
     //get current status
     $currentStatus = Order::find($idOrder)->status;
     $newStatus = $request->input('status');
     if ($currentStatus == $this::CANCEL) {
         return redirect_errors('Order canceled cannot changer status!');
     }
     if ($currentStatus == $this::PENDING && $newStatus > $this::DELIVERING) {
         return redirect_errors('Order is Pending can only changer Cancel or Delivering status!');
     }
     if ($currentStatus == $this::DELIVERING && $newStatus > $this::DELIVERED && $newStatus < $this::DELIVERING && $newStatus != $this::CANCEL) {
         return redirect_errors('Order is Delivering can only changer Cancel or Delivered status!');
     }
     if ($currentStatus == $this::DELIVERED && $newStatus < $this::DELIVERED && $newStatus != $this::CANCEL) {
         return redirect_errors('Order is Delivered can only changer Cancel or Charged status!');
     }
     if ($currentStatus == $this::CHARGED) {
         return redirect_errors('Order charged cannot changer status!');
     }
     $model = new Order();
     DB::beginTransaction();
     try {
         $order = $model->find(intval($idOrder));
         $order->status = intval($newStatus);
         $order->save();
         //if cancel then qty return
         if ($newStatus == $this::CANCEL) {
             $model = new Order();
             $order = $model->viewOrder($idOrder);
             $details = $order['order']['detail'];
             foreach ($details as $detail) {
                 $qtyReturn = $detail['quantity'];
                 $currentQty = Cd::find($detail['product_id'])->quantity;
                 $currentBuyTime = Cd::find($detail['product_id'])->buy_time;
                 Cd::find($detail['product_id'])->update(['quantity' => $currentQty + $qtyReturn, 'buy_time' => $currentBuyTime + $qtyReturn]);
             }
             //                $customer=User::find('user_id');
             //                if(is_null($customer)){
             //
             //                }
             //                Mail::send('auth.message_order', ['name' => 'you'],
             //                    function ($message) use ($data) {
             //                        $message
             //                            ->to($data['email'], $data['name'])
             //                            ->from('*****@*****.**')
             //                            ->subject('Your order canceled!');
             //                    });
         }
         DB::commit();
         return redirect()->back()->with('success', 'Updated status');
     } catch (\Exception $e) {
         DB::rollback();
         return redirect_errors('Updated Fails!');
     }
 }
Ejemplo n.º 29
0
 public function store(Request $request)
 {
     DB::beginTransaction();
     $permission = Permission::create($request->only('name', 'display_name', 'description'));
     $role_ids = $request->input('role_ids') ?: [];
     $permission->roles()->sync($role_ids);
     DB::commit();
     flash()->success('Permission baru berhasil ditambahkan.');
     return redirect('permission');
 }
Ejemplo n.º 30
0
 public function delete($id)
 {
     $article = Article::where('id', 'LIKE', $id)->first();
     $page = Page::where('id', 'LIKE', $article->page_id)->first();
     DB::beginTransaction();
     $this->delete_attachments($article->id);
     $article->delete();
     DB::commit();
     return redirect()->route('admin.page', ['name' => $page->name]);
 }