Пример #1
0
 /**
  * Check whether a user is using an address
  * @param $address_id
  * @param $user_id
  * @return int
  */
 public function usage($address_id, $user_id)
 {
     if ($this->usage->where('address_id', '=', $address_id)->where('user', '=', $user_id)->first()) {
         return 1;
     }
     return 0;
 }
Пример #2
0
 /**
  * @return $this
  */
 public function meta()
 {
     $img_url = 'http://d14d0ey1pb5ifb.cloudfront.net/';
     $property = \App\Property::where(['meta_set' => 0, 'status' => '1'])->orderBy('package', 'DESC')->first();
     $address = \App\Address::where(['property_id' => $property->property_id])->first();
     $images = \App\Image::where(['property_id' => $property->property_id])->orderBy('pos', 'ASC')->get();
     return view('dashboard.meta')->with(compact(['property', 'address', 'images', 'img_url']));
 }
Пример #3
0
 /**
  * attempts to find a matching address before creating a new instance
  */
 public static function retrieveOrCreate(array $attributes = [])
 {
     // TODO: look up address attributes to find a match
     $existing_addr = Address::where('street', $attributes['street'])->where('city', $attributes['city'])->where('state', $attributes['state'])->where('zip1', $attributes['zip1'])->first();
     if ($existing_addr) {
         return $existing_addr;
     }
     return Address::create($attributes);
 }
Пример #4
0
 public function getIndex(Request $request)
 {
     $address = \App\Address::where('user_id', '=', \Auth::id())->get()->first();
     if (is_null($address)) {
         \Session::flash('flash_message', 'Please create an address for your account');
         return redirect('addresses/create');
     }
     $accounts = \App\Account::where('user_id', '=', \Auth::id())->orderBy('id', 'ASC')->get();
     return view('account.index')->with('accounts', $accounts);
 }
Пример #5
0
 public function getEdit($id = null)
 {
     $address = \App\Address::where('user_id', '=', \Auth::id())->get()->first();
     if (is_null($address)) {
         \Session::flash('flash_message', 'Address not found');
         return redirect('addresses/create');
     }
     $stateModel = new \App\State();
     $states_for_dropdown = $stateModel->getStatesForDropdown();
     return view('address.edit')->with('address', $address)->with(['states_for_dropdown' => $states_for_dropdown]);
 }
Пример #6
0
 public function addresses($location, $sub_location)
 {
     /*
     $addresses = Address::where('location_id', $location)
     	->where('sub_location_id',$sub_location)
     	->lists('name_eng', 'id');
     */
     $addresses = Address::where('location_id', $location)->where('sub_location_id', $sub_location)->get()->map(function ($key) {
         return ['text' => $key->name_eng, 'value' => $key->id];
     })->toArray();
     return $addresses;
 }
Пример #7
0
 public function anyEntry(Request $request, $id = null)
 {
     if (isset($id) && $id != null) {
         $company = Company::find($id);
         if ($company != null) {
             session(['current_company' => $company->id]);
         } else {
             return redirect('companies');
         }
     } else {
         $id = session('current_company') !== null ? session('current_company') : 0;
         $address_id = session('current_address') !== null ? session('current_address') : 0;
         if ($id) {
             $company = Company::find($id);
             session(["current_company" => $company->id]);
         } else {
             $company = Company::get()->last();
             if ($company) {
                 session(["current_company" => $company->id]);
             } else {
                 $company = new Company();
                 $company->save();
                 session(['current_company' => $company->id]);
             }
         }
     }
     $address = Address::where('module_id', '=', $company->id)->where('module_type', '=', 'App\\Company')->first();
     $address_province = isset($address->province_id) ? $address->province_id : 0;
     $country_province = Province::addSelect('provinces.name as province_name')->where('provinces.id', '=', $address_province)->addSelect('countries.name as country_name')->leftJoin('countries', 'countries.id', '=', 'provinces.country_id')->first();
     if ($country_province) {
         $country_province->toArray();
         $company['province_name'] = $country_province['province_name'];
         $company['country_name'] = $country_province['country_name'];
     } else {
         $company['province_name'] = '';
         $company['country_name'] = '';
     }
     $countries = array();
     $company_type = array();
     $countries = Country::with('provinces')->get()->toArray();
     $company_type = CompanyType::get()->toArray();
     $company->toArray();
     $this->layout->content = view('company.entry', ['company' => $company, 'address' => $address, 'countries' => $countries, 'company_type' => $company_type]);
 }
Пример #8
0
 public function handleCreateMailType()
 {
     // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     // Reduce Credit before approve email
     // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     $receiver_address = Address::where('id', Request::get('receiver_address_id'))->first();
     if (!$receiver_address || $receiver_address->user_id != Auth::user()->id) {
         return redirect('home')->with("error", "มีบางอย่างผิดพลาด");
     }
     $mail_type = DB::table('mailtypes')->where('id', Request::get('mail_type_id'))->first();
     if ($mail_type->price > Auth::user()->credits) {
         return redirect('home')->with('error', 'เครดิตของคุณไม่เพียงพอ');
     }
     $mail = new Mail();
     $mail->user_id = Auth::user()->id;
     $mail->mail_type_id = Request::get('mail_type_id');
     $mail->content = Request::get('content');
     $mail->receiver_name = $receiver_address->name;
     $mail->receiver_address_line_1 = $receiver_address->address_line_1;
     $mail->receiver_address_line_2 = $receiver_address->address_line_2;
     $mail->receiver_address_line_3 = $receiver_address->address_line_3;
     $mail->receiver_postcode = $receiver_address->postcode;
     $mail->status = 0;
     if (Request::get('sender_address_id') != 0) {
         $sender_address = Address::where('id', Request::get('sender_address_id'))->first();
         if (!$sender_address || $sender_address->user_id != Auth::user()->id || $sender_address->is_sender == false) {
             return redirect('home')->with("error", "มีบางอย่างผิดพลาด Test");
         }
         $mail->sender_name = $sender_address->name;
         $mail->sender_address_line_1 = $sender_address->address_line_1;
         $mail->sender_address_line_2 = $sender_address->address_line_2;
         $mail->sender_address_line_3 = $sender_address->address_line_3;
         $mail->sender_postcode = $sender_address->postcode;
     }
     $mail->save();
     $User = User::find(Auth::user()->id);
     $User->credits -= $mail_type->price;
     $User->save();
     return redirect('home')->with("msg", "บันทึกจดหมายของท่านแล้ว");
 }
Пример #9
0
 public function edit(Request $request)
 {
     $user = Auth::user();
     $account = $request->only('user');
     $info = $request->except('user', 'other_address', 'email', '_token');
     $user->update($account['user']);
     $user->info()->update($info);
     if ($request->has('other_address') and $user->is('legal')) {
         $addresses = $request->input('other_address');
         $address_ids = [];
         foreach ($addresses as $address) {
             if (!empty($address)) {
                 $item = $user->addresses()->create(['address' => $address]);
                 $address_ids[] = $item->id;
             }
         }
         Address::where('user_id', $user->id)->whereNotIn('id', $address_ids)->delete();
     }
     $input = $request->all();
     $input['city'] = $user->info->city;
     $input['province'] = $user->info->province;
     return ['hasCallback' => '1', 'callback' => 'user_info', 'hasMsg' => '1', 'msg' => 'data inserted successfully', 'returns' => $input];
 }
Пример #10
0
 public function getUpdatePaymentAddressCustomer()
 {
     View::share(['navigator' => \NavigatorHelper::getNavigatorBarFE(), 'sideBar' => \NavigatorHelper::getSideBarFE()]);
     if (!Session::has('user')) {
         return redirect_errors('You login yet!');
     }
     $user = Session::get('user');
     if ($user['role_id'] != Role::CUS_ROLE_ID) {
         return redirect_errors('You are not Customer!');
     }
     $customer = new Customer();
     $cusInfo = $customer->with('user')->where('user_id', $user['id'])->first()->toArray();
     $current_City = Address::find($cusInfo['city_id'])->id;
     $cities = Address::where('parent_id', 0)->get()->toArray();
     $state = Address::find($cusInfo['state_id'])->toArray();
     return view('change_payment_address.index')->with(['info' => $cusInfo, 'currentCity' => $current_City, 'cities' => $cities, 'state' => $state]);
 }
Пример #11
0
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $user = Auth::user();
     $addresses = Address::where(['customer_id' => $user->id])->get();
     return view('dashboard.customer.addressList', ['addresses' => $addresses]);
 }
Пример #12
0
 /**
  * Starts the checkout process.
  *
  * @param  int  $addressId The address id selected to be copied
  * @return Response
  */
 public function checkOutResume($addressId)
 {
     $user = \Auth::user();
     $cart = Order::ofType('cart')->with('details')->where('user_id', $user->id)->first();
     $cartDetail = OrderDetail::where('order_id', $cart->id)->get();
     $address = Address::find($addressId);
     $totalAmount = 0;
     $totalItems = 0;
     //Checks if the user selected an address that belongs to him/her
     $userAddress = Address::where('user_id', $user->id)->where('id', $address->id)->first();
     if ($userAddress) {
         //Checks if the user has points for the cart price and the store has stock
         $total_points = 0;
         foreach ($cartDetail as $orderDetail) {
             $product = Product::find($orderDetail->product_id);
             $totalItems += $orderDetail->quantity;
             $totalAmount += $orderDetail->quantity * $orderDetail->price;
             if ($product->stock < $orderDetail->quantity) {
                 return redirect()->route('orders.show_cart')->withErrors(array('main_error' => array(trans('store.insufficientStock'))));
             }
         }
         //Checks if the user has points for the cart price
         if ($user->current_points < $total_points && config('app.payment_method') == 'Points') {
             return redirect()->route('orders.show_cart')->withErrors(array('main_error' => array(trans('store.cart_view.insufficient_funds'))));
         } else {
             //Copies the Address to a new one and attaches it to the order or replaces the old one
             $cartAddress = Address::find($cart->address_id);
             if (!$cartAddress) {
                 //if the order does not has an address yet
                 $newAddress = new Address();
                 $newAddress->line1 = $address->line1;
                 $newAddress->line2 = $address->line2;
                 $newAddress->phone = $address->phone;
                 $newAddress->name_contact = $address->name_contact;
                 $newAddress->zipcode = $address->zipcode;
                 $newAddress->city = $address->city;
                 $newAddress->country = $address->country;
                 $newAddress->state = $address->state;
                 $newAddress->save();
                 $cart->address_id = $newAddress->id;
                 $cart->save();
                 $cartAddress = $newAddress;
             } else {
                 //if the order needs to be updated
                 $cartAddress->line1 = $address->line1;
                 $cartAddress->line2 = $address->line2;
                 $cartAddress->phone = $address->phone;
                 $cartAddress->name_contact = $address->name_contact;
                 $cartAddress->zipcode = $address->zipcode;
                 $cartAddress->city = $address->city;
                 $cartAddress->country = $address->country;
                 $cartAddress->state = $address->state;
                 $cartAddress->save();
             }
             $panel = array('center' => ['width' => '12']);
             //Sets the resume option to use the same view
             $isResume = true;
             $is_logged = true;
             return view('orders.cart', compact('cart', 'user', 'panel', 'isResume', 'cartAddress', 'totalItems', 'totalAmount'));
         }
     } else {
         return redirect()->route('orders.show_cart')->withErrors(array('main_error' => array(trans('store.errorOnAddress'))));
     }
 }
 public function saveAddress(Request $request, $territoryId = null, $addressId = null)
 {
     if (!$this->hasAccess($request)) {
         return Response()->json(['error' => 'Access denied.'], 500);
     }
     if (empty($territoryId)) {
         return ['error' => 'Territory not found', 'message' => 'Territory not found'];
     }
     if (Gate::denies('update-addresses')) {
         return Response()->json(['error' => 'Method not allowed'], 403);
     }
     if (!empty($addressId)) {
         try {
             $newAddress = $this->unTransform($request->all(), 'address');
             $address = Address::findOrFail($addressId);
             $street = Street::findOrFail($address->street_id)->first();
             // if(!$street->is_apt_building)
             // $newAddress['lat'] = 0;
             $data = $address->update($newAddress);
         } catch (Exception $e) {
             $data = ['error' => 'Address not updated', 'message' => $e->getMessage()];
         }
     } else {
         // dd($request->all());
         // dd($this->unTransform($request->all(), 'address'));
         try {
             // return ['data' => ['street_street' => empty($request->input('street_street')), 'all' => $request->all()]];
             $transformedData = $this->unTransform($request->all(), 'address');
             if (!empty($request->input('street_street'))) {
                 $transformedData['street'] = [['street' => $request->input('street_street'), 'isAptBuilding' => $request->input('street_isAptBuilding')]];
             }
             // return ['data' => $transformedData];
             $territory = Territory::findOrFail($territoryId);
             if (!empty($transformedData['street'])) {
                 $street = Street::where('street', $transformedData['street'][0]['street'])->first();
                 if (empty($street)) {
                     $street = Street::create($transformedData['street'][0]);
                 }
                 // $addressWithStreet = ($address && $street) ? $address->street()->associate($street) : $address;
                 $transformedData['street_id'] = $street ? $street->id : null;
             }
             $address = Address::where(['address' => $transformedData['address'], 'street_id' => $transformedData['street_id'], 'apt' => !empty($transformedData['apt']) ? $transformedData['apt'] : ''])->first();
             // Address alredy exist?
             if (!empty($address)) {
                 // If inactive, make it active
                 // dd($address);
                 if ($address['inactive']) {
                     $address['inactive'] = 0;
                     $data = $address->update(['inactive', $address['inactive']]);
                 }
                 // If in another territory?
                 if ($territoryId != $address->territory_id) {
                     $territoryBelongs = Territory::findOrFail($address->territory_id);
                     // Error: "This address belongs to territory number []"
                     return Response()->json(['error' => 'This address belongs to territory ' . $territoryBelongs->number . '. Please contact Admin about moving this address.', 'data' => ''], 202);
                 } else {
                     return Response()->json(['error' => 'This address already exists in this territory.', 'data' => ''], 202);
                 }
             } else {
                 $address = !empty($territory) ? $territory->addresses()->create($transformedData) : null;
             }
             $data = $address && !empty($transformedData['notes']) ? $address->notes()->create($transformedData['notes'][0]) : $address;
         } catch (Exception $e) {
             $data = ['error' => 'Address not added', 'message' => $e->getMessage()];
             // {"error":"SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '200-23' for key 'addresses_address_street_id_unique' (SQL: insert into `addresses` (`name`, `address`, `street_id`, `territory_id`, `updated_at`, `created_at`) values (Jean Marc, 200, 23, 34, 2016-01-14 18:36:49, 2016-01-14 18:36:49))"}
         }
     }
     return ['data' => $data];
 }
Пример #14
0
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
    return view('welcome');
});
Route::get('/protected-resource', ['middleware' => 'oauth', function () {
    $usage = \App\Usage::where('user_id', '=', \Auth::user()->id)->where('usageActivity', '=', 1)->first()->address_id;
    $address = \App\Address::where('id', '=', $usage)->first()->address;
    //return Response::json(['address' => $address]);
    //return redirect()->route('shelves', ['address' => $address]);
    return Redirect::to('http://localhost:34000/locate/import?address=' . $address);
}]);
Route::get('/shelves', ['as' => 'shelves'], function () {
    return redirect('http://localhost:34000/cart/cart');
});
Route::get('oauth/authorize', ['as' => 'oauth.authorize.get', 'middleware' => ['check-authorization-params', 'auth'], function () {
    // display a form where the user can authorize the client to access it's data
    $authParams = Authorizer::getAuthCodeRequestParams();
    $formParams = array_except($authParams, 'client');
    $formParams['client_id'] = $authParams['client']->getId();
    return View::make('oauth.authorization_form', ['params' => $formParams, 'client' => $authParams['client']]);
}]);
Route::post('oauth/authorize', ['as' => 'oauth.authorize.post', 'middleware' => ['csrf', 'check-authorization-params', 'auth'], function () {
Пример #15
0
 /**
  * Update the specified resource in storage.
  *
  * @param  Request  $request
  * @param  int  $id
  * @return Response
  */
 public function update(BusinessRegRequest $request, $id)
 {
     $biz = Biz::findorFail($id);
     $biz->name = $request->input('name');
     $biz->contactname = $request->input('contactname');
     $biz->email = $request->input('email');
     $biz->website = $request->input('website');
     $biz->phone1 = $request->input('phone1');
     $biz->phone2 = $request->input('phone2');
     $biz->user_id = \Auth::id();
     $biz->save();
     $add = Address::where('biz_id', $biz->id)->first();
     $add->street = $request->input('address');
     $add->lga_id = $request->input('lga');
     $add->state_id = $request->input('state');
     $add->save();
     $category = $request->input('cats');
     // $catNames= [];
     // $biz->cats()->delete();
     /*  foreach ($category as $cat) {
         if( $existingCat = Cat::where('name', $cat)->first()) {
              $catNames[]= $existingCat;
             }
              else{
                  $newCat = new Cat();
                  $newCat ->name  = $cat;
                  $newCat->save();
              $catNames[]=$newCat;
              }
         }  
             $biz->cats()->saveMany($catNames); */
     $biz->cats()->sync($category);
     $subs = $request->input('sub');
     // $real= [];
     // $biz->subcats()->delete();
     /* foreach ($subs as $sub) {
        if( $existingSub = SubCat::where('name', $sub)->first()) {
             $real[]= $existingSub;
            }
             else{
                 $newSub = new SubCat();
                 $newSub ->name  = $sub;
                 $newCat->save();
             $real[]=$newSub;
             }
        }
            $biz->subcats()->saveMany($real);  */
     $biz->subcats()->sync($subs);
     return redirect("/admin/biz/")->withSuccess("Changes Updated");
 }
Пример #16
0
 /**
  * Start the checkout process for any type of order
  *
  * @param  int  $type_order Type of order to be processed
  * @return Response
  */
 public static function placeOrders($type_order)
 {
     $cart = Order::ofType($type_order)->auth()->whereStatus('open')->orderBy('id', 'desc')->first();
     $show_order_route = $type_order == 'freeproduct' ? 'freeproducts.show' : 'orders.show_cart';
     $cartDetail = OrderDetail::where('order_id', $cart->id)->get();
     $address_id = 0;
     //When address is invalid, it is because it comes from the creation of a free product. You must have a user direction (Default)
     if (is_null($cart->address_id)) {
         $useraddress = UserAddress::auth()->orderBy('default', 'DESC')->first();
         if ($useraddress) {
             $address_id = $useraddress->address_id;
         } else {
             return trans('address.no_registered');
         }
     } else {
         $address_id = $cart->address_id;
     }
     $address = Address::where('id', $address_id)->first();
     //Checks if the user has points for the cart price and the store has stock
     //and set the order prices to the current ones if different
     //Creates the lists or sellers to send mail to
     $total_points = 0;
     $seller_email = array();
     foreach ($cartDetail as $orderDetail) {
         $product = Product::find($orderDetail->product_id);
         $seller = User::find($product->user_id);
         if (!in_array($seller->email, $seller_email)) {
             $seller_email[] = $seller->email;
         }
         $total_points += $orderDetail->quantity * $product->price;
         if ($orderDetail->price != $product->price) {
             $orderDetail->price = $product->price;
             $orderDetail->save();
         }
         if ($product->type != 'item') {
             $virtual = VirtualProduct::where('product_id', $orderDetail->product_id)->get();
             $first = $virtual->first();
             //$first=null;
             //foreach ($virtual as $row){
             //$first=$row;
             //break;
             //}
             switch ($product->type) {
                 case 'key':
                 case 'software_key':
                     $virtualOrder = VirtualProductOrder::where('virtual_product_id', $first->id)->where('order_id', $orderDetail->order_id)->where('status', 1)->get();
                     if (count($virtual) - 1 < count($virtualOrder)) {
                         return trans('store.insufficientStock');
                     }
                     break;
                 default:
                     break;
             }
         } elseif ($product->stock < $orderDetail->quantity) {
             return trans('store.insufficientStock');
         }
     }
     //Checks if the user has points for the cart price
     $user = \Auth::user();
     if ($user->current_points < $total_points && config('app.payment_method') == 'Points') {
         return trans('store.cart_view.insufficient_funds');
     }
     if (config('app.payment_method') == 'Points') {
         $negativeTotal = -1 * $total_points;
         //7 is the action type id for order checkout
         $pointsModified = $user->modifyPoints($negativeTotal, 7, $cart->id);
     } else {
         $pointsModified = true;
     }
     if ($pointsModified) {
         //Separate the order for each seller
         //Looks for all the different sellers in the cart
         $sellers = [];
         foreach ($cartDetail as $orderDetail) {
             if (!in_array($orderDetail->product->user_id, $sellers)) {
                 $sellers[] = $orderDetail->product->user_id;
             }
         }
         foreach ($sellers as $seller) {
             //Creates a new order and address for each seller
             $newOrder = new Order();
             $newOrder->user_id = $user->id;
             $newOrder->address_id = $address->id;
             $newOrder->status = $type_order == 'freeproduct' ? 'paid' : 'open';
             $newOrder->type = $type_order == 'freeproduct' ? 'freeproduct' : 'order';
             $newOrder->seller_id = $seller;
             $newOrder->save();
             $newOrder->sendNotice();
             //moves the details to the new orders
             foreach ($cartDetail as $orderDetail) {
                 if ($orderDetail->product->user_id == $seller) {
                     $orderDetail->order_id = $newOrder->id;
                     $orderDetail->save();
                 }
                 //Increasing product counters.
                 ProductsController::setCounters($orderDetail->product, ['sale_counts' => trans('globals.product_value_counters.sale')], 'orders');
                 //saving tags in users preferences
                 if (trim($orderDetail->product->tags) != '') {
                     UserController::setPreferences('product_purchased', explode(',', $orderDetail->product->tags));
                 }
             }
         }
         //virtual products
         //Changes the stock of each product in the order
         foreach ($cartDetail as $orderDetail) {
             $product = Product::find($orderDetail->product_id);
             $product->stock = $product->stock - $orderDetail->quantity;
             $product->save();
             if ($product->type != 'item') {
                 $virtual = VirtualProduct::where('product_id', $orderDetail->product_id)->where('status', 'open')->get();
                 switch ($product->type) {
                     case 'key':
                         $first = VirtualProduct::where('product_id', $orderDetail->product_id)->where('status', 'cancelled')->first();
                         foreach ($virtual as $row) {
                             $virtualOrder = VirtualProductOrder::where('order_id', $cart->id)->where('virtual_product_id', $first->id)->where('status', 1)->first();
                             if ($virtualOrder) {
                                 $virtualOrder->virtual_product_id = $row->id;
                                 $virtualOrder->order_id = $orderDetail->order_id;
                                 $virtualOrder->status = 2;
                                 $virtualOrder->save();
                                 $row->status = 'paid';
                                 $row->save();
                             } else {
                                 break;
                             }
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
         foreach ($seller_email as $email) {
             $mailed_order = Order::where('id', $newOrder->id)->with('details')->get()->first();
             //Send a mail to the user: Order has been placed
             $data = ['orderId' => $newOrder->id, 'order' => $mailed_order];
             //dd($data['order']->details,$newOrder->id);
             $title = trans('email.new_order_for_user.subject') . " (#{$newOrder->id})";
             Mail::queue('emails.neworder', compact('data', 'title'), function ($message) use($user) {
                 $message->to($user->email)->subject(trans('email.new_order_for_user.subject'));
             });
             //Send a mail to the seller: Order has been placed
             $title = trans('email.new_order_for_seller.subject') . " (#{$newOrder->id})";
             Mail::queue('emails.sellerorder', compact('data', 'title'), function ($message) use($email) {
                 $message->to($email)->subject(trans('email.new_order_for_seller.subject'));
             });
         }
         return;
     } else {
         return trans('store.insufficientFunds');
     }
 }
Пример #17
0
 public function getSenderAddresses()
 {
     // $addresses = DB::table('addresses')->where('user_id', Auth::user()->id)->get();
     $addresses = Address::where("is_sender", true)->where("user_id", Auth::user()->id)->get();
     return response()->json($addresses);
 }
Пример #18
0
 /**
  * Establece una direccion por defecto para el usuario
  * @param Request $request [description]
  * @param integer  $id      ID del usuario
  */
 public function setDefault(Request $request)
 {
     $this->resetDefault();
     $default = Address::where('user_id', \Auth::id())->where('id', $request->get('id'))->update(['default' => 1]);
     return \Response::json(['success' => true, 'url' => '/user/address'], 200);
 }
Пример #19
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     try {
         //Find all freeproducts that can be processed; that is, they are in the correct date range and are active.
         $this->info('----- STARTING THE PROCESS FOR SELECTION OF WINNERS -----');
         $dateactual = date('Y-m-d');
         $freeproducts = FreeProduct::where('status', 1)->where('draw_date', $dateactual)->get();
         if ($freeproducts) {
             $this->info('Free Products to be processed: ' . $freeproducts->count());
             foreach ($freeproducts as $freeproduct) {
                 //Check the total participants. Depending on this the freeproduct be processed. Remember that there is a minimum of participation to select the winners. Still it not defined to do if the minimum is not met.
                 $participants = FreeProductParticipant::where('freeproduct_id', $freeproduct->id)->where('status', 'registered')->get();
                 if ($freeproduct->min_participants <= $participants->count()) {
                     //Select the winners, as defined in the product free draw_number field.
                     $list_winners = [];
                     for ($i = 0; $i < $freeproduct->draw_number; $i++) {
                         $user_winner = $participants->random(1);
                         $list_winners[] = $user_winner->user_id;
                         $user_winner->status = 'winner';
                         $user_winner->save();
                     }
                     $this->info('Total winners -> ' . count($list_winners));
                     //We mail to notify the winners and create an order for you to communicate with the seller of the product. The first is to list all the products contained in the orders associated with that freeproduct
                     //Collection Orders with Products in details
                     $orders = FreeProduct::find($freeproduct->id)->orders()->with('products')->get();
                     //Collection Products
                     $list_products_orders = Collection::make();
                     foreach ($orders as $order) {
                         $list_products_orders = $list_products_orders->merge($order->products);
                     }
                     $this->info('Total Products to prize: ' . count($list_products_orders));
                     $list_awards = [];
                     foreach ($list_winners as $user_id) {
                         $winner = User::find($user_id);
                         $this->info("Processing user -> ID={$winner->id} ");
                         //In this part of the process, we should when creating the freeproduct, indicate how the prizes will be distributed, something like for position, and indicate that many products will be delivered by position. For now, a product be taken at random.
                         do {
                             $product_award = $list_products_orders->random(1);
                             $in_product_award_list = true;
                             if (in_array($product_award->id, $list_awards)) {
                                 $in_product_award_list = false;
                             } else {
                                 $list_awards[] = $product_award->id;
                                 $this->info("Product selected-> ID={$product_award->id} ");
                             }
                         } while (!$in_product_award_list);
                         //Creating the order with the product won user
                         $winner_address = Address::where('user_id', $winner->id)->orderBy('default', 'DESC')->first();
                         $newOrder = new Order();
                         $newOrder->user_id = $winner->id;
                         $newOrder->address_id = $winner_address->id;
                         $newOrder->status = 'pending';
                         $newOrder->type = 'freeproduct';
                         $newOrder->seller_id = $freeproduct->user_id;
                         $newOrder->save();
                         $newOrder->sendNotice();
                         $this->info("Creating order: Result -> ID {$newOrder->id}");
                         //Order detail. Just take the product won
                         $newOrderDetail = new OrderDetail();
                         $newOrderDetail->order_id = $newOrder->id;
                         $newOrderDetail->product_id = $product_award->id;
                         $newOrderDetail->price = $freeproduct->participation_cost;
                         $newOrderDetail->quantity = 1;
                         $newOrderDetail->status = 1;
                         $newOrderDetail->save();
                         //Off product will deliver a prize
                         $product_award->status = 0;
                         $product_award->save();
                         //Notify the user that was selected as winner of that freeproduct
                         $data = ['product' => $product_award];
                         Mail::queue('emails.freeproducts.winner', $data, function ($message) use($winner) {
                             $message->to($winner->email)->subject(trans('email.free_products_winner.subject'));
                         });
                         $this->info('email sent notice that won');
                         //He also sent an email indicating that a new order was created.(tracking)
                         $data = ['orderId' => $newOrder->id];
                         Mail::queue('emails.neworder', $data, function ($message) use($winner) {
                             $message->to($winner->email)->subject(trans('email.new_order_for_user.subject'));
                         });
                         $this->info('email I sent notice that an order for the product won');
                     }
                     //Freeproduct inactive, so they do not take into account again for next draw
                     $freeproduct->status = 0;
                     $freeproduct->save();
                     //Se le notifica al dueno del freeproduct que se seleccionaron a los ganadores
                     $this->info("FreeProduct -> ID={$freeproduct->id} PROCESSED");
                 } else {
                     $this->info("FreeProduct -> ID={$freeproduct->id} The minimum participation condition for the free product does not comply.");
                 }
             }
         }
         $this->info('----- FINISHED THE PROCESS FOR SELECTION OF WINNERS -----');
     } catch (ModelNotFoundException $e) {
         Log::error($e);
         $this->error('They received errors when running the process. View Log File.');
     }
 }
Пример #20
0
 /**
  * Subscription free product, validating the conditions and validity of the same.
  *
  * @param int $id
  *
  * @return Response
  */
 public function subscribe($id)
 {
     $freeproduct = FreeProduct::find($id);
     $user = \Auth::user();
     if ($freeproduct) {
         //It validates that the user has a registered address in the store. Of winning, this address will be used to create you an order (will contain the product to win)
         $useraddress = Address::where('user_id', $user->id)->orderBy('default', 'DESC')->first();
         if ($useraddress) {
             //It verifies that the product is in effect free
             $dateactual = date('Y-m-d');
             if ($freeproduct->start_date >= $dateactual && $freeproduct->end_date >= $dateactual) {
                 //It has enough points to participate
                 if ($user->current_points > $freeproduct->participation_cost) {
                     //Total of Participants
                     $totalparticipants = FreeProductParticipant::where('freeproduct_id', $id)->count();
                     //Total equity investments in the product user free
                     $userholdings = FreeProductParticipant::MyParticipations($id)->count();
                     //Validate that there is still quota to participate
                     if ($freeproduct->max_participants > $totalparticipants) {
                         //Then, the user is not participating or not exceeding the number of shares in the free product
                         if ($freeproduct->max_participations_per_user > $userholdings) {
                             //Subtract points because of user participation
                             $negativeTotal = -1 * $freeproduct->participation_cost;
                             //12 is the action type id for free product checkout
                             $pointsModified = $user->modifyPoints($negativeTotal, 12, $id);
                             if ($pointsModified) {
                                 //If you meet these conditions, the user is registered as a participant free product
                                 $newparticipant = new FreeProductParticipant();
                                 $newparticipant->freeproduct_id = $id;
                                 $newparticipant->user_id = $user->id;
                                 $newparticipant->status = 'registered';
                                 $newparticipant->save();
                                 //Report by email to the participant
                                 $data = ['freeproduct_id' => $id];
                                 Mail::queue('emails.freeproducts.participate', $data, function ($message) use($user) {
                                     $message->to($user->email)->subject(trans('email.free_products_participation.subject'));
                                 });
                                 //It is sent to the view (dashboard) where the user can view their participation in it.
                                 Session::flash('message', trans('freeproduct.congratulations_participate'));
                                 return redirect()->route('freeproducts.show', [$freeproduct->id]);
                             } else {
                             }
                         } else {
                             Session::flash('message', trans('freeproduct.max_participations_for_user'));
                         }
                     } else {
                         Session::flash('message', trans('freeproduct.participations_not_available'));
                     }
                 } else {
                     Session::flash('message', trans('freeproduct.not_enough_point'));
                 }
             } else {
                 Session::flash('message', trans('freeproduct.freeproduct_not_available'));
             }
         } else {
             Session::flash('message', trans('freeproduct.address_not_registered'));
         }
         return redirect()->route('freeproducts.show', [$id]);
     } else {
         Session::flash('message', trans('freeproduct.freeproduct_not_exist'));
         return redirect(route('products'));
     }
 }
	public function postUpdate(Request $request)
	{
		$arr_return = array(
					'status' => 'error',
					'message'=>''
				);
		$time =date('H:i:s', time());
		$id_return_purchaseorder = session('current_returnpurchaseorder') !== null ? session('current_returnpurchaseorder') : 0;
		if($id_return_purchaseorder){
			$returnpurchaseorder = ReturnPurchaseorder::find($id_return_purchaseorder);
			session(['current_returnpurchaseorder' => $returnpurchaseorder['id']]);
			$time = date('H:i:s', strtotime($returnpurchaseorder->date));
		}else{

			$returnpurchaseorder = new ReturnPurchaseorder;
			$returnpurchaseorder->date = date("Y-m-d H:i:s");
			$returnpurchaseorder->created_by = \Auth::user()->id;
			$returnpurchaseorder->save();
			Log::create_log(\Auth::user()->id,'App\ReturnPurchaseorder','Tạo mới đơn hàng trả nhà cung cấp số '.$returnpurchaseorder->id);
			session(['current_returnpurchaseorder' => $returnpurchaseorder->id]);
		}
		$log = '';
		$old_company_id = $returnpurchaseorder->company_id;
		if($returnpurchaseorder->status == 0){
			$address = Address::where('module_id','=',$returnpurchaseorder->id)
						->where('module_type','=','App\ReturnPurchaseorder')->first();
			if(!$address){
				$address = new Address;
			}
			if($request->has('company_id')  && $returnpurchaseorder->company_id != $request->input('company_id')){
				$old = Company::find($returnpurchaseorder->company_id);
				if(!$old){
					$old = (object) ['name'=>''];
				}
				$new = Company::find($request->input('company_id'));
				$log .= 'công ty từ "'.$old->name.'" thành "'.$new->name.'" ';
			}
			if($returnpurchaseorder->company_id == $request->input('company_id')){

				if($request->has('user_id')  && $returnpurchaseorder->user_id != $request->input('user_id')){
					$old = User::find($returnpurchaseorder->user_id);
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$new = User::find($request->input('user_id'));
					$log .= 'người liên hệ từ "'.$old->name.'" thành "'.$new->name.'" ';
				}

				$old_date=date("Y-m-d",strtotime($returnpurchaseorder->date));
				$new_date = date("Y-m-d",strtotime($request->input('date')));
				if($request->has('date')  && $old_date != $new_date){
					$log .= 'ngày từ "'.$old_date.'" thành "'.$new_date.'" ';
				}

				if($request->has('company_phone')  && $returnpurchaseorder->company_phone != $request->input('company_phone')){
					$log .= 'số điện thoại từ "'.$returnpurchaseorder->company_phone.'" thành "'.$request->input('company_phone').'" ';
				}

				if($request->has('company_email')  && $returnpurchaseorder->company_email != $request->input('company_email')){
					$log .= 'email từ "'.$returnpurchaseorder->company_email.'" thành "'.$request->input('company_email').'" ';
				}
				if($request->has('address')  && $address->address != $request->input('address')){
					$log .= 'địa chỉ từ "'.$address->address.'" thành "'.$request->input('address').'" ';
				}
				if($request->has('town_city')  && $address->town_city != $request->input('town_city')){
					$log .= 'quận huyện từ "'.$address->town_city.'" thành "'.$request->input('town_city').'" ';
				}

				if($request->has('province_id')  && $address->province_id != $request->input('province_id')){
					$old = Province::find($address->province_id);
					$new = Province::find($request->input('province_id'));
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$log .= 'tỉnh thành từ "'.$old->name.'" thành "'.$new->name.'" ';
				}
				if($request->has('country_id')  && $address->country_id != $request->input('country_id')){
					$old = Country::find($address->country_id);
					$new = Country::find($request->input('country_id'));
					if(!$old){
						$old = (object) ['name'=>''];
					}
					$log .= 'quốc gia từ "'.$old->name.'" thành "'.$new->name.'" ';
				}
			}
			$returnpurchaseorder->company_id = $request->has('company_id') ? $request->input('company_id') : 0;
			$returnpurchaseorder->user_id = $request->has('user_id') ? $request->input('user_id') : 0;
			$returnpurchaseorder->date = $request->has('date') ? date("Y-m-d H:i:s",strtotime($request->input('date').' '.$time)) : date("Y-m-d H:i:s");
			$returnpurchaseorder->company_phone = $request->has('company_phone') ? $request->input('company_phone') : '';
			$returnpurchaseorder->company_email = $request->has('company_email') ? $request->input('company_email') : '';
			$address_id = isset($returnpurchaseorder->address_id) ? $returnpurchaseorder->address_id : 0;

			

			$address->module_id  = $returnpurchaseorder->id;
			$address->module_type  = 'App\\ReturnPurchaseorder';
			$address->address  = $request->has('address') ? $request->input('address') : '';
			$address->town_city  = $request->has('town_city') ? $request->input('town_city') : '';
			$address->zip_postcode  = $request->has('zip_postcode') ? $request->input('zip_postcode') : '';
			$address->country_id  = $request->has('country_id') ? $request->input('country_id') : 0;
			$address->province_id  = $request->has('province_id') ? $request->input('province_id') : 0;
			$address->save();
			$returnpurchaseorder->address_id = $address->id;
		}else{
			$returnpurchaseorder->sum_amount = 0;
			$returnpurchaseorder->sum_invest = 0;
		}
		$old_status = $returnpurchaseorder->status;
		$returnpurchaseorder->status = $request->has('status')?1:0;
		$check_save_in_stock = true;
		if($returnpurchaseorder->status){
			$arr_mproduct = Mproduct::select('m_products.id','quantity','specification','name','m_product_id','invest')
							->where('module_id', '=', $returnpurchaseorder->id)
							->where('module_type', '=', 'App\ReturnPurchaseorder')
							->leftJoin('products','products.id','=','m_products.product_id')
							->get()->toArray();
			foreach ($arr_mproduct as $key => $mproduct) {
				$returnpurchaseorder->sum_amount = $returnpurchaseorder->sum_amount + $mproduct['invest'];
				$mproduct_po = Mproduct::find($mproduct['m_product_id']);
				$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
				$product_stock->in_stock = $product_stock->in_stock -  ($mproduct['quantity']*$mproduct['specification']);
				if($product_stock->in_stock < 0){
					$check_save_in_stock = false;
					$arr_return['message'] .= 'Số lượng sản phẩm '.$mproduct['name'].' nhập vào lớn hơn số lượng đã nhập<br/><br/>';
				}
			}
		}else{
			if($old_status != $returnpurchaseorder->status){
				$arr_mproduct = Mproduct::select('m_products.id','quantity','specification','name','m_product_id')
								->where('module_id', '=', $returnpurchaseorder->id)
								->where('module_type', '=', 'App\ReturnPurchaseorder')
								->leftJoin('products','products.id','=','m_products.product_id')
								->get()->toArray();
				foreach ($arr_mproduct as $key => $mproduct) {
					$mproduct_po = Mproduct::find($mproduct['m_product_id']);
					$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
					$product_stock->in_stock = $product_stock->in_stock + ($mproduct['quantity']*$mproduct['specification']);
					$product_stock->save();
				}
			}
		}

		if($check_save_in_stock){
			$returnpurchaseorder->updated_by = \Auth::user()->id;
			if($returnpurchaseorder->save()){
				Log::create_log(\Auth::user()->id,'App\ReturnPurchaseorder','Cập nhật '.$log.' đơn hàng trả nhà cung cấp số '.$returnpurchaseorder->id);
				if($returnpurchaseorder->status){
					foreach ($arr_mproduct as $key => $mproduct) {
						$mproduct_po = Mproduct::find($mproduct['m_product_id']);
						$product_stock = ProductStock::where('m_product_id','=',$mproduct_po->id)->first();
						$product_stock->in_stock = $product_stock->in_stock -  ($mproduct['quantity']*$mproduct['specification']);
						$product_stock->save();
					}
				}

				if($old_company_id != $returnpurchaseorder->company_id){
					Mproduct::where('module_id', '=', $returnpurchaseorder->id)
						->where('module_type', '=', 'App\ReturnPurchaseorder')
						->where('company_id','=',$old_company_id)
						->delete();
				}else{
					Mproduct::where('module_id', '=', $returnpurchaseorder->id)
						->where('module_type', '=', 'App\ReturnPurchaseorder')
						->update(['company_id' => $returnpurchaseorder->company_id ]);
				}
				$arr_return['status']= 'success';
			}else{
				$arr_return['message']= 'Saving fail !';
			}
		}
		return $arr_return;
	}
Пример #22
0
 public function listState(Request $request)
 {
     $rules = ['id' => 'required|exists:address'];
     $validator = Validator::make($request->all(), $rules);
     if ($validator->fails()) {
         return json_encode([]);
     }
     $listState = Address::where('parent_id', $request->input('id'))->get()->toArray();
     return $listState;
 }
Пример #23
0
 /**
  * Search for an agent
  * @return \Illuminate\View\View
  */
 public function search()
 {
     $results = \App\Agent::where('agentName', '=', $_POST['search'])->first();
     $agent_id = $results->user_id;
     $addresses = \App\Address::where('agent_id', '=', $agent_id);
     return view('address.manage', compact('results', 'addresses', 'usage'));
 }
Пример #24
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show()
 {
     $user = Auth::user();
     $addresses = Address::where(['customer_id' => $user->id])->get();
     //  $products= Product::where(['supplier_id'=>$user->id,'is_active'=>'1'])->get();
     return view('dashboard.customer.ProfileEdit', ['user' => $user, 'addresses' => $addresses]);
     //    return view('dashboard.customer.homePage');
 }
 protected static function restoreTerritory($data)
 {
     $territory = Territory::where('number', $data->terrNumber)->first();
     // var_dump($territory['id']); exit;
     if (empty($territory)) {
         $territory = Territory::create(['number' => $data->terrNumber, 'location' => $data->street]);
     }
     // var_dump($territory['id']); exit;
     if (!empty($territory['id'])) {
         $bad = ['STREET', 'COURT', 'PLACE', '(PARTIE SUD)', '(PARTIE NORD)', '(BILDING)', '(BUILDING)'];
         $good = ['ST', 'CT', 'PL', '', '', '', ''];
         foreach ($data->addresses as $i => $add) {
             $streetEntry = str_replace($bad, $good, strtoupper(Address::getStreet($add->address)));
             $street = Street::where('street', $streetEntry)->first();
             // var_dump($street); exit;
             if (empty($street)) {
                 /*
                 				$street = Street::create([
                 					'street' => $streetEntry,
                 					'is_apt_building' => 0
                 				]);
                 */
                 // else
                 var_dump($streetEntry);
             }
             // var_dump($street); exit;
             $addressEntry = strtoupper(trim(str_replace($streetEntry, '', $add->address)));
             $address = Address::where(['address' => $addressEntry, 'street_id' => $street['id']])->first();
             if (empty($address)) {
                 /*
                 				$address = Address::create([
                 					'territory_id' => $territory['id'],
                 					'street_id' => $street['id'],
                 					'address' => $addressEntry,
                 					'name' => $add->name,
                 					'phone' => $add->phone
                 				]);
                 */
                 // else
                 var_dump([$addressEntry, $address]);
             }
             // var_dump($address); exit;
         }
     }
 }