/** * 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); }
/** * 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"); }
public function create(array $data) { DB::beginTransaction; // $this->db:: 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['items']); $order = $this->repository->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(); } catch (\Exception $e) { DB::rollback(); throw $e; } }
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!'); } }
/** * @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(); } }; }
/** * 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; }
/** * Handle a registration request for the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function postRegister(Request $request) { if (!$request->ajax()) { return JsonHelper::invalidRequest(); } $flag = ForbiddenUsername::getInstance()->checkName($request->request->get('username')); if ($flag) { return JsonHelper::json('', '用户名非法!', 40002); } $validator = $this->registrar->validator($request->all()); if ($validator->fails()) { return JsonHelper::json('', $validator->messages(), 50001); } try { $this->auth->login($this->registrar->create($request->all())); DB::commit(); return JsonHelper::json('', 'register success', 10000); } catch (DevBaseException $e) { DB::rollback(); if (config('app.debug')) { var_export($e->getMessage()); exit; } return JsonHelper::InternalDbFail(); } }
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; } }
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()); }
/** * Rollback a transaction, * so we remove all data added * to the current test's transaction. **/ public function rollback() { try { DB::rollback(); } catch (\Exception $e) { var_dump($e->getMessage()); } }
/** * Bulk Lead creation * * @param array $data * @param User $user * @throws \SaleBoss\Repositories\Exceptions\RepositoryException * @return mixed */ public function bulkCreate(array $data, User $user = null) { $data = $this->setCreatorId($data, !empty($user) ? $user->id : null); DB::beginTransaction(); try { $this->model->newInstance()->insert($data); } catch (QueryException $e) { DB::rollback(); throw new RepositoryException($e->getMessage()); } DB::commit(); }
/** * Update tester from built plan * * @param $planId * @param $testersData * @return array|bool */ public function updateBuiltTesters($planId, $testersData, $origData) { $redirect = false; $errorMsg = ''; // Start transaction DB::beginTransaction(); // Start testers update try { $query = $this->model->where('plan_id', '=', $planId)->delete(); foreach ($testersData as $tester) { $testerId = $tester['id']; $browsers = $tester['browsers']; $newCount = isset($browsers) ? count(explode(',', $browsers)) : 0; // Formerly selected browsers $oldCount = isset($origData[$testerId]) ? count(explode(',', $origData[$testerId])) : 0; if ($oldCount == $newCount) { $updateStatus = 0; } elseif ($newCount > $oldCount) { $updateStatus = 1; } elseif ($oldCount < $newCount || $oldCount > $newCount) { $updateStatus = -1; } $tester += ['update_status' => $updateStatus, 'update_status_text' => Tools::planTesterChanges($updateStatus)]; $results[] = $tester; // Create new or update if (count($tester['input-ids']) > 0 && !empty($browsers)) { $this->model->create(['plan_id' => $planId, 'user_id' => $testerId, 'browsers' => $browsers]); } } } 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, $testersData); return false; } // Commit all changes DB::commit(); return $results; }
public function table($options) { $this->onInit($options); DB::beginTransaction(); try { $result = $this->controller->handle(); } catch (JarboeValidationException $e) { DB::rollback(); $data = array('status' => false, 'errors' => explode('|', $e->getMessage())); return Response::json($data); } DB::commit(); $this->onFinish(); return $result; }
/** * Add new follow data * * @param $follower_id * @param $followed_id * @throws \Exception */ public function addFollow($follower_id, $followed_id) { try { DB::beginTransaction(); $this->follower_user_id = $follower_id; $this->followed_user_id = $followed_id; $this->date_created = date('Y-m-d H:i:s'); $this->save(); $notification_data = new Notification(); $notification_data->addNotificationNewFollower($follower_id, $followed_id); DB::commit(); } catch (\Exception $e) { DB::rollback(); throw $e; } }
function assign(array $request, $application_id) { DB::beginTransaction(); try { $application = Application::find($application_id); ApplicationLender::create(['description' => $request['description'], 'lender_id' => $request['lender_id'], 'application_id' => $application_id, 'status' => 0]); $application->submitted = 1; $application->save(); DB::commit(); return true; } catch (\Exception $e) { DB::rollback(); dd($e); return false; } }
public function cardCreateAction(Request $request) { $reader_name = $request->input("reader-name"); $sex = $request->input("sex"); $birthday = $request->input("birthday"); $phone = $request->input("phone"); $mobile = $request->input("mobile"); $card_name = $request->input("card-name"); $card_id = $request->input("card-id"); $level = $request->input("level"); $username = $request->input("username"); $password = md5($request->input('password') . "zachary"); if ($sex != '男' && $sex != '女') { return redirect('/admin/cardCreate')->with("msg", "参数错误,请重试"); } if ($reader_name == "" || $sex == "" || $birthday == "" || $phone == "" || $mobile == "" || $card_name == "" || $card_id == "" || $level == "" || $username == "" || $password == "") { return redirect('/admin/cardCreate')->with("msg", "参数错误,请重试"); } //为了防止出现数据不一致的情况,使用事务进行处理 //如果出现错误的话,就将操作回滚,正常则提交 DB::beginTransaction(); try { $reader = new Reader(); $reader['reader-name'] = $reader_name; $reader['sex'] = $sex; $reader['birthday'] = $birthday; $reader['phone'] = $phone; $reader['mobile'] = $mobile; $reader['card-name'] = $card_name; $reader['card-id'] = $card_id; $reader['level'] = $level; $reader['day'] = date('Y-m-d'); $reader->save(); $user = new User(); $user['username'] = $username; $user['password'] = $password; $user['type'] = 1; $user['reader-id'] = $reader['reader-id']; $user->save(); DB::commit(); } catch (Exception $e) { echo $e->getMessage(); DB::rollback(); return redirect('/admin/cardCreate')->with("msg", "出现错误,请重试"); } return redirect('/admin/cardCreate')->with("msg", "创建成功!新的读者证编号为:" . $reader['reader-id']); }
function add(array $request, $lead_id) { DB::beginTransaction(); try { if ($request['action'] == 'edit') { $this->deleteRemoved($lead_id, $request['property_id']); } foreach ($request['applicant_id'] as $key => $applicant) { if (!isset($request['property_id'][$key])) { $property_id = $this->addProperty($request, $key); } else { $property_id = $request['property_id'][$key]; $this->editProperty($request, $key, $property_id); } } DB::commit(); return $property_id; } catch (\Exception $e) { DB::rollback(); dd($e); return false; } }
function add(array $request, $lead_id) { DB::beginTransaction(); try { if ($request['action'] == 'edit') { $this->deleteRemoved($lead_id, $request['income_id']); } if ($request['income'] == 1) { foreach ($request['applicant_id'] as $key => $applicant_id) { if (!isset($request['income_id'][$key])) { $this->addDetails($request, $key); } else { $this->editDetails($request['income_id'][$key], $request, $key); } } } DB::commit(); return true; } catch (\Exception $e) { DB::rollback(); dd($e); return false; } }
/** * Store a queue * * 1. Validate Price Parameter * * @return Response */ public function price() { if (!Input::has('price')) { return new JSend('error', (array) Input::all(), 'Tidak ada data price.'); } $user = \LucaDegasperi\OAuth2Server\Facades\Authorizer::getResourceOwnerId(); $user = json_decode($user, true)['data']; if ($user) { $userid = $user['id']; } else { \App::abort(404); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate Price Parameter $price = Input::get('price'); $price_rules = ['discount_amount' => 'required_without:discount_percentage|numeric', 'discount_percentage' => 'required_without:discount_amount|numeric', 'started_at' => 'required|date_format:"Y-m-d H:i:s"', 'ended_at' => 'required|date_format:"Y-m-d H:i:s"|after:started_at', 'category_ids' => 'required_if:item,category|array', 'tag_ids' => 'required_if:item,tag|array', 'is_labeled' => 'boolean']; $validator = Validator::make($price, $price_rules); if (!$validator->passes()) { $errors->add('Price', $validator->errors()); } else { $products = new \App\Models\Product(); $products = $products->sellable(true); if (isset($price['category_ids'])) { $products = $products->categoriesid($price['category_ids']); } elseif (isset($price['tag_ids'])) { $products = $products->tagsid($price['tag_ids']); } $products = $products->get(['id']); $parameter = $price; $queue = new \App\Models\Queue(); $queue->fill(['user_id' => $userid, 'process_name' => 'broadcast:discount', 'parameter' => json_encode($parameter), 'total_process' => count($products), 'task_per_process' => 1, 'process_number' => 0, 'total_task' => count($products), 'message' => 'Initial Commit']); if (!$queue->save()) { $errors->add('Product', $queue->getError()); } } //End of validate price if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); $final_queue = \App\Models\Queue::id($queue['id'])->first()->toArray(); return new JSend('success', (array) $final_queue); }
/** * @return callable */ protected function updateResourceCallable() { $createOrderResource = $this->createOrderResourceCallable(); return function (Model $model, array $data, array $values, ErrorBag $errorBag) use($createOrderResource) { foreach ($values as $attribute => $value) { $model->{$attribute} = $value; } DB::beginTransaction(); try { $model->update(); $createOrderResource($model, $data); DB::commit(); return $model; } catch (\Exception $e) { DB::rollback(); $errorBag[] = new Error('update_error', 'Resource could not be updated'); throw new \Exception(); } }; }
public function save(array $options = []) { \DB::beginTransaction(); try { $saved = parent::save($options); $id = $this->getParentId(); if ($id && !empty($this->_meta_attributes)) { $dt = Carbon::now(); $meta_table = $this->getMetaTable(); $meta_data = DB::table($meta_table)->where($this->_parent_id, $id)->get(); $meta_attributes = $this->_meta_attributes; foreach ($meta_data as $meta) { $key = $meta->meta_key; if (!array_key_exists($key, $meta_attributes)) { DB::table($meta_table)->where($this->_parent_id, $id)->where('meta_key', $key)->delete(); } else { $value = $meta_attributes[$key]; $type = $this->getMetaType($value); DB::table($meta_table)->where($this->_parent_id, $id)->where('meta_key', $key)->update(['type' => $type, 'meta_value' => $this->encodeValue($type, $value), 'updated_at' => $dt]); } unset($meta_attributes[$key]); } if (count($meta_attributes) > 0) { foreach ($meta_attributes as $key => $value) { $type = $this->getMetaType($value); DB::table($meta_table)->insert([$this->_parent_id => $id, 'type' => $type, 'meta_key' => $key, 'meta_value' => $this->encodeValue($type, $value), 'created_at' => $dt, 'updated_at' => $dt]); } } } DB::commit(); return $saved; } catch (Exception $e) { DB::rollback(); } return false; }
/** * Store a setting * * @return Response */ public function store() { if (!Input::has('setting')) { return new JSend('error', (array) Input::all(), 'Tidak ada data setting.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate StoreSetting Parameter $setting = Input::get('setting'); if (is_null($setting['id'])) { $is_new = true; } else { $is_new = false; } //2. Validate setting parameter //2a. Slider if (!$errors->count() && $setting['type'] == 'slider') { $setting_data = \App\Models\Slider::findornew($setting['id']); $setting_rules = ['started_at' => 'date_format:"Y-m-d H:i:s"', 'ended_at' => 'date_format:"Y-m-d H:i:s"|after:started_at']; $validator = Validator::make($setting, $setting_rules); } elseif (!$errors->count() && in_array($setting['type'], ['about_us', 'why_join', 'term_and_condition'])) { $setting_data = \App\Models\StorePage::findornew($setting['id']); $setting_rules = ['started_at' => 'date_format:"Y-m-d H:i:s"']; $validator = Validator::make($setting, $setting_rules); } elseif (!$errors->count() && in_array($setting['type'], ['url', 'logo', 'facebook_url', 'twitter_url', 'instagram_url', 'email', 'phone', 'address', 'bank_information'])) { $setting_data = \App\Models\Store::findornew($setting['id']); $setting_rules = ['started_at' => 'date_format:"Y-m-d H:i:s"']; $validator = Validator::make($setting, $setting_rules); } else { $setting_data = \App\Models\Policy::findornew($setting['id']); $setting_rules = ['started_at' => 'date_format:"Y-m-d H:i:s"']; $validator = Validator::make($setting, $setting_rules); } if (!$validator->passes()) { $errors->add('StoreSetting', $validator->errors()); } else { //if validator passed, save setting $setting_data = $setting_data->fill($setting); if (!$setting_data->save()) { $errors->add('StoreSetting', $setting_data->getError()); } } //3. save image for slider if (!$errors->count() && isset($setting['images']) && is_array($setting['images']) && $setting_data['type'] == 'slider') { $image_current_ids = []; foreach ($setting['images'] as $key => $value) { if (!$errors->count()) { $image_data = \App\Models\Image::findornew($value['id']); $image_rules = ['thumbnail' => 'required|max:255', 'image_xs' => 'required|max:255', 'image_sm' => 'required|max:255', 'image_md' => 'required|max:255', 'image_lg' => 'required|max:255', 'is_default' => 'boolean']; $validator = Validator::make($value, $image_rules); //if there was image and validator false if (!$validator->passes()) { $errors->add('Image', $validator->errors()); } else { $value['imageable_id'] = $setting_data['id']; $value['imageable_type'] = get_class($setting_data); $image_data = $image_data->fill($value); if (!$image_data->save()) { $errors->add('Image', $image_data->getError()); } else { $image_current_ids[] = $image_data['id']; } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $images = \App\Models\Image::imageableid($setting['id'])->get(['id'])->toArray(); $image_should_be_ids = []; foreach ($images as $key => $value) { $image_should_be_ids[] = $value['id']; } $difference_image_ids = array_diff($image_should_be_ids, $image_current_ids); if ($difference_image_ids) { foreach ($difference_image_ids as $key => $value) { $image_data = \App\Models\Image::find($value); if (!$image_data->delete()) { $errors->add('Image', $image_data->getError()); } } } } } } if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); if ($setting_data['type'] == 'slider') { $final_setting = \App\Models\Slider::id($setting_data['id'])->with(['images'])->first()->toArray(); } else { $final_setting = \App\Models\StoreSetting::id($setting_data['id'])->first()->toArray(); } return new JSend('success', (array) $final_setting); }
public function order() { //get Session option $option = Session::get('option'); //get Cart $cart = Cart::content(); //get type order $type = $option['type']; //payment method $payMethod = Session::get('pay_med'); if ($option['type'] == 'logged') { $order = new Order(); DB::beginTransaction(); try { $idUser = array_get(session('user'), 'id'); $order->user_id = $idUser; $order->delivery_detail_id = 0; $order->comment = $payMethod['comment']; $order->save(); $idOrder = Order::where('user_id', $idUser)->orderBy('id', 'desc')->first()->id; //add order detail and sub amount of product foreach ($cart as $item) { $root_price = Cd::find($item['id'])->root_price; $modelOrderDetail = new OrderDetail(); $modelOrderDetail->order_id = $idOrder; $modelOrderDetail->product_id = $item['id']; $modelOrderDetail->quantity = $item['qty']; $modelOrderDetail->root_price = $root_price; $modelOrderDetail->price = $item->price; $modelOrderDetail->save(); //sub qty product $cd = Cd::find($item['id']); if ($cd->quantity - $item['qty'] <= 0) { throw new QtyCDException(); } $cd->quantity = $cd->quantity - $item['qty']; $cd->buy_time = $cd->buy_time + $item['qty']; $cd->save(); } DB::commit(); $this->clear(); return redirect_success('FrontendController@index', 'Ordered, Check your email to check detail'); } catch (QtyCDException $e) { DB::rollback(); return redirect_errors($e->notify()); } catch (\Exception $e) { DB::rollback(); return redirect_errors("Sorry cannot to this deal!"); } } else { $deliveryDetail = Session::get('shi_add'); $order = new Order(); $modelDeliverDetail = new DeliveryDetail(); $modelDeliverDetail = autoAssignDataToProperty($modelDeliverDetail, $deliveryDetail); // dd($modelDeliverDetail); DB::beginTransaction(); try { $orderHuman = $modelDeliverDetail; $modelDeliverDetail->save(); $newDeliverDetail = new DeliveryDetail(); $delivery = $newDeliverDetail->getDeliveryDetail($deliveryDetail); $order->user_id = 0; $order->delivery_detail_id = $delivery->id; $order->comment = $payMethod['comment']; $order->save(); $idOrder = Order::where('delivery_detail_id', $delivery->id)->first()->id; //add order detail and sub amount of product foreach ($cart as $item) { $modelOrderDetail = new OrderDetail(); $modelOrderDetail->order_id = $idOrder; $modelOrderDetail->product_id = $item['id']; $modelOrderDetail->quantity = $item['qty']; $modelOrderDetail->price = $item['price']; $modelOrderDetail->save(); // $cd = Cd::find($item['id']); if ($cd->quantity - $item['qty'] <= 0) { throw new QtyCDException(); } else { $cd->quantity = $cd->quantity - $item['qty']; } } DB::commit(); $this->clear(); //send // Mail::send('auth.mail_welcome', ['last_name' => $orderHuman->lastname, 'key' => $key_active, 'password' => $pass], function ($message) use ($data) { // $message // ->to($data['email'], $data['name']) // ->from('*****@*****.**') // ->subject('Thank you for your buying!'); // }); return redirect_success('FrontendController@index', 'Ordered, Check your email to check detail'); } catch (QtyCDException $e) { DB::rollback(); return redirect_errors($e->notify()); } catch (\Exception $e) { DB::rollback(); return redirect_errors("Sorry cannot to this deal!"); } } }
/** * Store an employeer * * 1. Save Employee * 2. Save Contacts * 3. Save Private Documents * 4. Save Careers * 5. Save Work Experience * 6. Save Marital Status * @return Response */ public function store($org_id = null) { if (!Input::has('employee')) { return new JSend('error', (array) Input::all(), 'Tidak ada data employee.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate employee Parameter $employee = Input::get('employee'); if (is_null($employee['id'])) { $is_new = true; } else { $is_new = false; } $employee_rules = ['organisation_id' => 'exists:organisations,id', 'uniqid' => 'max:255|unique:persons,uniqid,' . (!is_null($employee['id']) ? $employee['id'] : ''), 'username' => 'max:255|unique:persons,username,' . (!is_null($employee['id']) ? $employee['id'] : ''), 'name' => 'required|max:255', 'prefix_title' => 'max:255', 'suffix_title' => 'max:255', 'place_of_birth' => 'max:255', 'date_of_birth' => 'date_format:"Y-m-d H:i:s"', 'gender' => 'in:female,male', 'password' => 'max:255']; //1a. Get original data $employee_data = \App\Models\Employee::findornew($employee['id']); //1b. Validate Basic Employee Parameter $validator = Validator::make($employee, $employee_rules); if (!$validator->passes()) { $errors->add('Employee', $validator->errors()); } else { //if validator passed, save Employee $employee_data = $employee_data->fill($employee); if (!$employee_data->save()) { $errors->add('Employee', $employee_data->getError()); } } //End of validate Employee //2. Validate Employee contact Parameter if (!$errors->count() && isset($employee['contacts']) && is_array($employee['contacts'])) { $contact_current_ids = []; foreach ($employee['contacts'] as $key => $value) { if (!$errors->count()) { $contact_data = \App\Models\PersonContact::findornew($value['id']); $contact_rules = ['person_id' => 'exists:persons,id|' . ($is_new ? '' : 'in:' . $employee_data['id']), 'person_type' => !$contact_data ? '' : 'in:' . get_class($employee_data), 'item' => 'required|max:255', 'is_default' => 'boolean']; $validator = Validator::make($value, $contact_rules); //if there was contact and validator false if (!$validator->passes()) { $errors->add('contact', $validator->errors()); } else { $value['person_id'] = $employee_data['id']; $value['person_type'] = get_class($employee_data); $contact_data = $contact_data->fill($value); if (!$contact_data->save()) { $errors->add('contact', $contact_data->getError()); } else { $contact_current_ids[] = $contact_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $contacts = \App\Models\PersonContact::personid($employee['id'])->get(['id'])->toArray(); $contact_should_be_ids = []; foreach ($contacts as $key => $value) { $contact_should_be_ids[] = $value['id']; } $difference_contact_ids = array_diff($contact_should_be_ids, $contact_current_ids); if ($difference_contact_ids) { foreach ($difference_contact_ids as $key => $value) { $contact_data = \App\Models\PersonContact::find($value); if (!$contact_data->delete()) { $errors->add('contact', $contact_data->getError()); } } } } } //End of validate employee contact //3. Validate Employee privatedocument Parameter if (!$errors->count() && isset($employee['privatedocuments']) && is_array($employee['privatedocuments'])) { $pd_current_ids = []; foreach ($employee['privatedocuments'] as $key => $value) { if (!$errors->count()) { $param = []; $pd_data = \App\Models\PrivateDocument::findornew($value['id']); $pd_rules = ['document_id' => 'exists:tmp_documents,id|' . ($is_new ? '' : 'in:' . $value['document_id']), 'person_id' => 'exists:persons,id|' . ($is_new ? '' : 'in:' . $employee_data['id'])]; $validator = Validator::make($value, $pd_rules); //if there was privatedocument and validator false if (!$validator->passes()) { $errors->add('privatedocument', $validator->errors()); } else { $value['person_id'] = $employee_data['id']; $pd_data = $pd_data->fill($value); if (!$pd_data->save()) { $errors->add('privatedocument', $pd_data->getError()); } else { $pd_current_ids[] = $pd_data['id']; } } //check template $dd_current_ids = []; foreach ($value['documentdetails'] as $key2 => $value2) { if (!$errors->count()) { $dd_data = \App\Models\DocumentDetail::findornew($value2['id']); $dd_rules = ['person_document_id' => 'exists:persons_documents,id|' . ($is_new ? '' : 'in:' . $pd_data['id']), 'template_id' => 'exists:tmp_templates,id']; $validator = Validator::make($value2, $dd_rules); $template_data = \App\Models\Template::find($value2['template_id']); if ($template_data) { //if there was dd and validator false if (!$validator->passes()) { $errors->add('dd', $validator->errors()); } else { $param[$template_data['type'] == 'date' ? 'on' : strtolower($template_data['type'])] = $value2[$template_data['type'] == 'date' ? 'on' : strtolower($template_data['type'])]; $param['template_id'] = $template_data['id']; $param['person_document_id'] = $pd_data['id']; if (isset($param['on'])) { $param['on'] = date('Y-m-d H:i:s', strtotime($param['on'])); } $dd_data = $dd_data->fill($param); if (!$dd_data->save()) { $errors->add('dd', $dd_data->getError()); } else { $dd_current_ids[] = $dd_data['id']; } } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $dds = \App\Models\DocumentDetail::persondocumentid($pd_data['id'])->get(['id'])->toArray(); $dd_should_be_ids = []; foreach ($dds as $key2 => $value2) { $dd_should_be_ids[] = $value2['id']; } $difference_dd_ids = array_diff($dd_should_be_ids, $dd_current_ids); if ($difference_dd_ids) { foreach ($difference_dd_ids as $key2 => $value2) { $dd_data = \App\Models\DocumentDetail::find($value2); if (!$dd_data->delete()) { $errors->add('dd', $dd_data->getError()); } } } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $privatedocuments = \App\Models\PrivateDocument::personid($employee['id'])->get(['id'])->toArray(); $pd_should_be_ids = []; foreach ($privatedocuments as $key => $value) { $pd_should_be_ids[] = $value['id']; } $difference_privatedocument_ids = array_diff($pd_should_be_ids, $pd_current_ids); if ($difference_privatedocument_ids) { foreach ($difference_privatedocument_ids as $key => $value) { $pd_data = \App\Models\PrivateDocument::find($value); if (!$pd_data->delete()) { $errors->add('privatedocument', $contact_data->getError()); } } } } } //End of validate employee privatedocument //4. Validate Employee career Parameter if (!$errors->count() && isset($employee['careers']) && is_array($employee['careers'])) { $career_current_ids = []; foreach ($employee['careers'] as $key => $value) { if (!$errors->count()) { $career_data = \App\Models\Career::findornew($value['id']); $career_rules = ['person_id' => 'exists:persons,id|' . ($is_new ? '' : 'in:' . $employee_data['id']), 'calendar_id' => 'exists:tmp_calendars,id', 'chart_id' => 'exists:charts,id', 'grade' => 'numeric', 'status' => 'required|in:contract,probation,internship,permanent,others,admin', 'start' => 'required|date_format:"Y-m-d H:i:s"', 'end' => 'date_format:"Y-m-d H:i:s"', 'reason_end_job' => 'required_with:end', 'is_absence' => 'boolean']; $validator = Validator::make($value, $career_rules); //if there was career and validator false if (!$validator->passes()) { $errors->add('career', $validator->errors()); } else { $value['person_id'] = $employee_data['id']; $career_data = $career_data->fill($value); if (!$career_data->save()) { $errors->add('career', $career_data->getError()); } else { $career_current_ids[] = $career_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $careers = \App\Models\Career::personid($employee['id'])->get(['id'])->toArray(); $career_should_be_ids = []; foreach ($careers as $key => $value) { $career_should_be_ids[] = $value['id']; } $difference_career_ids = array_diff($career_should_be_ids, $career_current_ids); if ($difference_career_ids) { foreach ($difference_career_ids as $key => $value) { $career_data = \App\Models\Career::find($value); if (!$career_data->delete()) { $errors->add('career', $career_data->getError()); } } } } } //End of validate employee career //5. Validate Employee workexperience Parameter if (!$errors->count() && isset($employee['workexperiences']) && is_array($employee['workexperiences'])) { $workexperience_current_ids = []; foreach ($employee['workexperiences'] as $key => $value) { if (!$errors->count()) { $workexperience_data = \App\Models\WorkExperience::findornew($value['id']); $workexperience_rules = ['person_id' => 'exists:persons,id|' . ($is_new ? '' : 'in:' . $employee_data['id']), 'position' => 'required|max:255', 'organisation' => 'required|max:255', 'grade' => 'numeric', 'status' => 'required|in:previous', 'start' => 'required|date_format:"Y-m-d H:i:s"', 'end' => 'required|date_format:"Y-m-d H:i:s"', 'reason_end_job' => 'required_with:end', 'is_absence' => 'boolean']; $validator = Validator::make($value, $workexperience_rules); //if there was workexperience and validator false if (!$validator->passes()) { $errors->add('workexperience', $validator->errors()); } else { $value['person_id'] = $employee_data['id']; $workexperience_data = $workexperience_data->fill($value); if (!$workexperience_data->save()) { $errors->add('workexperience', $workexperience_data->getError()); } else { $workexperience_current_ids[] = $workexperience_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $workexperiences = \App\Models\WorkExperience::personid($employee['id'])->get(['id'])->toArray(); $workexperience_should_be_ids = []; foreach ($workexperiences as $key => $value) { $workexperience_should_be_ids[] = $value['id']; } $difference_workexperience_ids = array_diff($workexperience_should_be_ids, $workexperience_current_ids); if ($difference_workexperience_ids) { foreach ($difference_workexperience_ids as $key => $value) { $workexperience_data = \App\Models\WorkExperience::find($value); if (!$workexperience_data->delete()) { $errors->add('workexperience', $workexperience_data->getError()); } } } } } //End of validate employee workexperience //6. Validate Employee ms Parameter if (!$errors->count() && isset($employee['maritalstatuses']) && is_array($employee['maritalstatuses'])) { $ms_current_ids = []; foreach ($employee['maritalstatuses'] as $key => $value) { if (!$errors->count()) { $ms_data = \App\Models\MaritalStatus::findornew($value['id']); $ms_rules = ['person_id' => 'exists:persons,id|' . ($is_new ? '' : 'in:' . $employee_data['id']), 'status' => 'required|max:255', 'on' => 'required|date_format:"Y-m-d H:i:s"']; $validator = Validator::make($value, $ms_rules); //if there was ms and validator false if (!$validator->passes()) { $errors->add('maritalstatus', $validator->errors()); } else { $value['person_id'] = $employee_data['id']; $ms_data = $ms_data->fill($value); if (!$ms_data->save()) { $errors->add('ms', $ms_data->getError()); } else { $ms_current_ids[] = $ms_data['id']; } } } } //if there was no error, check if there were things need to be delete if (!$errors->count()) { $mss = \App\Models\MaritalStatus::personid($employee['id'])->get(['id'])->toArray(); $ms_should_be_ids = []; foreach ($mss as $key => $value) { $ms_should_be_ids[] = $value['id']; } $difference_ms_ids = array_diff($ms_should_be_ids, $ms_current_ids); if ($difference_ms_ids) { foreach ($difference_ms_ids as $key => $value) { $ms_data = \App\Models\MaritalStatus::find($value); if (!$ms_data->delete()) { $errors->add('ms', $ms_data->getError()); } } } } } //End of validate employee ms if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); $final_employee = \App\Models\Employee::id($id)->organisationid($org_id)->with(['privatedocuments', 'privatedocuments.document', 'privatedocuments.documentdetails', 'privatedocuments.documentdetails.template', 'careers', 'careers.calendar', 'careers.chart', 'careers.branch', 'workexperiences', 'maritalstatuses', 'contacts'])->first()->toArray(); return new JSend('success', (array) $final_employee); }
/** * Patch * Update an existing rolegroup. * * @param $payload * @return object **/ public static function update($payload) { # Validate $userId = Guardian::userId(); $user = User::find((int) $userId); $account = $user->accounts->first(); Guardian::check($account->getId(), 'rolegroup:write'); DB::beginTransaction(); try { # Save input (name and description) $rolegroup = Rolegroup::find($payload->id); if (!$rolegroup) { throw new ModelNotFoundException(); } $rolegroup->schemaUpdate((array) $payload); $rolegroup->roles()->detach(); if (isset($payload->roles)) { $roles = Role::find($payload->roles); $rolegroup->roles()->attach($roles); } } catch (\Exception $e) { DB::rollback(); throw $e; } DB::commit(); # Return created rolegroup with respective roles (permissions) return $rolegroup->schema($payload->display); }
/** * Store a newly created in storage */ public function store() { $validator = Validator::make($input = Input::all(), Beneficiario::rules('create')); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } DB::beginTransaction(); try { $nombres = $input['nombres']; $filename = null; // Profile Image Upload if (Input::hasFile('foto')) { $path = public_path() . "/foto/"; File::makeDirectory($path, $mode = 0777, true, true); $image = Input::file('foto'); $extension = $image->getClientOriginalExtension(); $filename = "{$nombres}_{$input['beneficiarioID']}." . strtolower($extension); // Image::make($image->getRealPath())->resize('872','724')->save($path.$filename); Image::make($image->getRealPath())->fit(872, 724, function ($constraint) { $constraint->upsize(); })->save($path . $filename); } Beneficiario::create(['beneficiarioID' => $input['beneficiarioID'], 'responsableID' => $input['nitcit'] . " " . $input['nitcit2'], 'objetivo' => $input['objetivo'], 'nombres' => ucwords(strtolower($input['nombres'])), 'apellidos' => ucwords(strtolower($input['apellidos'])), 'genero' => $input['genero'], 'fechanac' => date('Y-m-d', strtotime($input['fechanac'])), 'telefono' => $input['telefono'], 'fechaing' => date('Y-m-d', strtotime($input['fechaing'])), 'direccion' => ucwords(strtolower($input['direccion'])), 'foto' => isset($filename) ? $filename : 'default.jpg', 'direccionperm' => ucwords(strtolower($input['direccionperm'])), 'iddiagnostico' => $input['iddiag'], 'diagnostico' => $input['diagnostico'], 'fechadiagnostico' => $input['fechadiag'], 'tratamiento' => $input['tratamiento'], 'razon' => $input['razon'], 'duracion' => $input['duracion'], 'referencia' => $input['referencia'], 'lugar' => $input['lugar']]); // Insert into salary table if ($input['montosolicitado'] != '') { Soldonacion::create(['beneficiarioID' => $input['beneficiarioID'], 'tipo' => 'current', 'nota' => 'Primera Solicitud', 'monto' => $input['montosolicitado']]); } // Insert Into Bank Details Zonificacion::create(['beneficiarioID' => $input['beneficiarioID'], 'departamento' => $input['departamento'], 'provincia' => $input['provincia'], 'localidad' => $input['localidad'], 'zona' => $input['zona'], 'canton' => $input['canton'], 'otros' => $input['otros']]); // $tipo = 'responsable'; Personal::create(['beneficiarioID' => $input['beneficiarioID'], 'personalID' => $input['nitcit'], 'emision' => $input['nitcit2'], 'nombres' => $input['nombresReponsable'], 'apellidos' => $input['apellidosResponsable'], 'ocupacion' => $input['ocupacionResponsable'], 'parentesco' => $input['parentesco'], 'tipoPersonal' => $tipo]); $fullname = $input['nombres'] . " " . $input['apellidos']; // -------------- UPLOAD THE DOCUMENTS ----------------- $documents = ['certnac', 'CIprueba', 'solicitud', 'croquis', 'perfil']; foreach ($documents as $document) { if (Input::hasFile($document)) { $path = public_path() . "/beneficiarios_documents/{$document}/"; File::makeDirectory($path, $mode = 0777, true, true); $file = Input::file($document); $extension = $file->getClientOriginalExtension(); $filename = "{$document}_{$input['beneficiarioID']}_{$fullname}.{$extension}"; Input::file($document)->move($path, $filename); Bendocumentos::create(['beneficiarioID' => $input['beneficiarioID'], 'fileName' => $filename, 'type' => $document]); } } // dd(json_encode(Input::all())); // if($this->data['setting']->ben_add==1) // { // $this->data['ben_name'] = $fullname; // $this->data['ben_email'] = $input['email']; // $this->data['ben_password'] = $input['password']; // // Send Employee Add Mail // Mail::send('emails.admin.beneficiarios_add', $this->data, function ($message) use ($input) { // $message->from($this->data['setting']->email, $this->data['setting']->name); // $message->to($input['email'], $input['nombres']." ".$input['apellidos']) // ->subject('Cuenta Creada - ' . $this->data['setting']->website); // }); // } // ********** END UPLOAD THE DOCUMENTS********** } catch (\Exception $e) { DB::rollback(); throw $e; } Activity::log(['contentId' => $input['beneficiarioID'], 'contentType' => 'Beneficiario', 'action' => 'Creacion', 'user_id' => Auth::admin()->get()->id, 'description' => 'Creacion del un Beneficiario', 'details' => 'Usuario: ' . Auth::admin()->get()->name, 'updated' => $input['beneficiarioID'] ? true : false]); DB::commit(); return Redirect::route('admin.beneficiarios.index')->with('success', "<strong>{$fullname}</strong> exitosamente adicionado en le base de datos"); }
/** * Store a Schdule * 1. store Schdule * * @param Schdule * @return Response */ public function store($org_id = null, $cal_id = null) { //check branch $schedule = \App\ThunderID\WorkforceManagementV1\Models\Calendar::id($cal_id)->organisationid($org_id)->first(); if (!$schedule) { \App::abort(404); } if (!Input::has('schedule')) { return new JSend('error', (array) Input::all(), 'Tidak ada data Schdule.'); } $errors = new MessageBag(); DB::beginTransaction(); //1. Validate Schdule Parameter $schedule = Input::get('schedule'); if (is_null($schedule['id'])) { $is_new = true; } else { $is_new = false; } $schedule_rules = ['calendar_id' => 'exists:hrwm_calendars,id|' . ($is_new ? '' : 'in:' . $cal_id), 'name' => 'max:255', 'status' => 'in:DN,CB,UL,HB,L', 'ondate' => 'date_format:"Y-m-d"', 'start' => 'date_format:"H:i:s"', 'end' => 'date_format:"H:i:s"', 'break_idle' => 'numeric']; //1a. Get original data $schedule_data = \App\ThunderID\WorkforceManagementV1\Models\Schedule::findornew($schedule['id']); //1b. Validate Basic Schdule Parameter $validator = Validator::make($schedule, $schedule_rules); if (!$validator->passes()) { $errors->add('schedule', $validator->errors()); } else { //if validator passed, save Schdule $schedule['calendar_id'] = $cal_id; $schedule_data = $schedule_data->fill($schedule); if (!$schedule_data->save()) { $errors->add('schedule', $schedule_data->getError()); } } //End of validate Schdule if ($errors->count()) { DB::rollback(); return new JSend('error', (array) Input::all(), $errors); } DB::commit(); $final_schedule = \App\ThunderID\WorkforceManagementV1\Models\Schedule::id($schedule_data['id'])->first()->toArray(); return new JSend('success', (array) $final_schedule); }
public function postUpdatePaymentAddressCustomer(Requests\UpdateCustomerRequest $request) { $user = Session::get('user'); DB::beginTransaction(); try { //update account $account = User::where('id', $user['id'])->update(['phone' => $request->input('phone')]); //update customer $cus = Customer::where('id', $request->input('id'))->update(['address1' => $request->input('address1'), 'address2' => $request->input('address2'), 'city_id' => $request->input('city_id'), 'state_id' => $request->input('state_id')]); DB::commit(); return redirect_success('FrontendController@index', 'success', 'Your information changed!'); } catch (\Exception $e) { DB::rollback(); return redirect_errors('Cannot update information!'); } }
/** * Atualiza na base os dados de um PID revisado. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { $this->validate($request, ['nome' => 'required|min:5', 'email' => 'required|email', 'url' => 'url', 'tipo_id' => 'exists:pidTipos,idTipo', 'endereco.logradouro' => 'required|min:3|max:150', 'endereco.bairro' => 'required|min:3|max:150', 'endereco.uf' => 'required', 'endereco.cidade_id' => 'required|exists:cidades,idCidade', 'endereco.latitude' => 'numeric', 'endereco.longitude' => 'numeric', 'endereco.localidade_id' => 'exists:localidades,idLocalidade', 'endereco.localizacao_id' => 'exists:localizacoes,idLocalizacao']); $pid = Pid::findOrFail($request['idPid']); $email = $request['session_email']; $pass = $request['session_pass']; $review = DB::table('pid_revisao')->where('email', $email)->where('pass', $pass)->where('valido', 1)->where('submetido', 1)->select('pid_id', 'idRevisao')->get(); if (empty($review)) { return ['error' => 'Acesso Inválido']; } else { if ($review[0]->pid_id != $request['idPid']) { return ['error' => 'Acesso Inválido']; } } DB::beginTransaction(); try { $pid->endereco()->update($request['endereco']); $pid->update($request->all()); $pid->touch(); $telefones = []; foreach ($request['telefones'] as $telefone) { if ($telefone['idTelefone'] == null) { $tel = $pid->telefones()->create($telefone); $telefones[] = $tel->idTelefone; } else { $tel = Telefone::find($telefone['idTelefone']); $tel->update($telefone); $telefones[] = $tel->idTelefone; } } $pid->telefones()->sync($telefones); $instituicoes = []; foreach ($request['instituicoes'] as $instituicao) { $instituicoes[] = $instituicao['idInstituicao']; } $pid->instituicoes()->sync($instituicoes); $iniciativas = []; foreach ($request['iniciativas'] as $iniciativa) { $iniciativas[] = $iniciativa['idIniciativa']; } $pid->iniciativas()->sync($iniciativas); $pid->servicos()->sync($request['servicos']); DB::table('pid_revisao')->where('idRevisao', '=', $review[0]->idRevisao)->update(['valido' => 0, 'updated_at' => Carbon::now()]); DB::commit(); } catch (\Exception $e) { DB::rollback(); abort(400); } finally { unlink(storage_path() . '/revisao/pid_' . $pid->idPid . '.json'); return $this->show($pid->idPid); } }
/** * Update the specified resource in storage. * * @param Request $request * @param int $id * @return Response */ public function update(Request $request, $id) { try { DB::beginTransaction(); $affiliate = $this->CreacionArray($request->all(), 'Affiliate'); $affiliate = $this->CreacionArray($affiliate, 'Dues'); $date = explode('/', $affiliate['date_payment']); $affiliate['date_payment'] = $date[1] . "-" . $date[0] . "-01"; $affiliateDues = $affiliate; unset($affiliateDues['amount_affiliate']); unset($affiliate['amount']); $affiliate['amount'] = $affiliate['amount_affiliate']; unset($affiliate['amount_affiliate']); $comprobacion = $this->duesRepository->token($request->get('token')); if (count($comprobacion) > 1) { $duesPrivateId = $this->duesRepository->getModel()->Where('token', $request->get('token'))->where('type', 'privado')->get(); $duesPrivate = $this->duesRepository->find($duesPrivateId[0]->id); $duesPrivate->fill($affiliateDues); $duesPrivate->update(); $duesAffiliateId = $this->duesRepository->getModel()->Where('token', $request->get('token'))->where('type', 'affiliate')->get(); $duesAffiliate = $this->duesRepository->find($duesAffiliateId[0]->id); $duesAffiliate->fill($affiliate); $duesAffiliate->update(); } else { $comprobacion->fill($affiliateDues); $comprobacion->update(); if ($comprobacion['type'] == 'privado') { $type = 'affiliate'; } elseif ($comprobacion['type'] == 'affiliate') { $type = 'privado'; } $duesAffiliateId = $this->duesRepository->getModel()->Where('affiliate_id', $comprobacion['affiliate_id'])->Where('date_payment', $comprobacion['date_payment'])->where('type', $type)->get(); if (count($duesAffiliateId) > 0) { $duesAffiliate = $this->duesRepository->find($duesAffiliateId[0]->id); $duesAffiliate->fill($affiliate); $duesAffiliate->update(); } } DB::commit(); return $this->exito('Se actualizaron con exito los datos!!!'); } catch (Exception $e) { Log::error($e); DB::rollback(); return $this->errores(['error' => ' se ha generado un error verificar los datos']); } }