Edit File: OrderService.php
<?php namespace App\Services; use App\Jobs\ChangePaymentMethodNotify; use App\Jobs\DelegateAcceptOfferNotify; use App\Jobs\DelegateCreateInvoiceNotify; use App\Jobs\DelegateFinishOrder; use App\Jobs\DelegateMakeOfferNotify; use App\Jobs\DelegatePayWithWallet; use App\Jobs\DelegateWithdrawNotify; use App\Jobs\StoreRefuseOrderNotify; use App\Jobs\StoreAcceptOrderNotify; use App\Jobs\StoreDoneOrderNotify; use App\Jobs\NewOrderNotify; use App\Jobs\OrderIntransitNotify; use App\Jobs\StoreNotify; use App\Jobs\UserAcceptOfferNotify; use App\Jobs\UserRejectOfferNotify; use App\Jobs\UserCancelOrderNotify; use App\Models\DeliveryOffer; use App\Models\Order; use App\Models\OrderImage; use App\Models\WaitingSettlementOrder; use App\Models\OrderProduct; use App\Models\OrderProductAdditive; use App\Models\Product; use App\Models\ProductAdditive; use App\Models\ProductGroup; use App\Models\Profit; use App\Models\Room; use App\Models\RoomMessage; use App\Models\Setting; use App\Models\Store; use App\Models\StoreCommission; use App\Models\User; use App\Models\Vat; use App\Models\WithdrawReason; use App\Services\CouponService; use App\Traits\GeneralTrait; use App\Traits\ApiTrait; use Carbon\Carbon; use Illuminate\Support\Facades\File; use Intervention\Image\Facades\Image; use Auth; class OrderService { use ApiTrait, GeneralTrait; public static function getdirectDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $earthRadius = 6371000; // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $lonDelta = $lonTo - $lonFrom; $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); $in_km = ($angle * $earthRadius) / 1000; $in_km += (40 / 100) * $in_km; $in_km = number_format((float) $in_km, 2, '.', ''); return $in_km; } public static function deliveryPrice($distance = 0) { $settings = Setting::all()->pluck('value', 'key'); $km_price = $settings['km_price']; $starting_fee = $settings['starting_fee']; $delivery_price = $starting_fee + ($distance * $km_price); $data = []; $data['display_delivery_price'] = number_format($delivery_price, 2, '.', ''); $data['delivery_price'] = $delivery_price; return $data; } public static function appPercentage($price = 0) { $settings = Setting::all()->pluck('value', 'key'); $app_percentage = (float)$price * ((float)$settings['app_percentage'] / 100); return number_format($app_percentage, 2, '.', ''); } public static function addedValue($price = 0) { $settings = Setting::all()->pluck('value', 'key'); $added_value = $price * ($settings['added_value'] / 100); return number_format($added_value, 2, '.', ''); } public static function expected_price() { $settings = Setting::all()->pluck('value', 'key'); $data['min'] = $settings['min_expected_price']; $data['max'] = $settings['max_expected_price']; return $data; } public static function uploadOne($file, $directory = 'unknown', $resize1 = null, $resize2 = null) { if (!File::isDirectory('assets/uploads/' . $directory)) { File::makeDirectory('assets/uploads/' . $directory, 0777, true, true); } if (is_file($file)) { $img = Image::make($file); $thumbsPath = 'assets/uploads/' . $directory; $name = time() . '_' . rand(1111, 9999) . '.' . $file->getClientOriginalExtension(); if (null != $resize1) { $img->resize($resize1, $resize2, function ($constraint) { $constraint->aspectRatio(); }); $thumbsPath = 'assets/uploads/' . $directory; $img->save($thumbsPath . '/' . $name); } $img->save($thumbsPath . '/' . $name); return (string) $name; } else { $name = time() . rand(1000000, 9999999) . '.png'; // file_put_contents(base_path().'assets/uploads/' . $directory . '/' . $name, base64_decode($file)); $img = Image::make(base64_decode($file)); if (null != $resize) { $img->resize($resize1, $resize2, function ($constraint) { $constraint->aspectRatio(); }); $thumbsPath = 'assets/uploads/' . $directory; } $img->save($thumbsPath . '/' . $name); return (string) $name; } } public static function uploadFile($file, $directory = 'unknown', $resize1 = null, $resize2 = null) { if (!File::isDirectory('assets/uploads/' . $directory)) { File::makeDirectory('assets/uploads/' . $directory, 0777, true, true); } if (is_file($file)) { $img = Image::make($file); $thumbsPath = 'assets/uploads/' . $directory; $name = time() . '_' . rand(1111, 9999) . '.' . $file->getClientOriginalExtension(); if (null != $resize1) { $img->resize($resize1, $resize2, function ($constraint) { $constraint->aspectRatio(); }); $thumbsPath = 'assets/uploads/' . $directory; $img->save($thumbsPath . '/' . $name); } $img->save($thumbsPath . '/' . $name); return (string) $name; } else { $name = time() . rand(1000000, 9999999) . '.png'; // file_put_contents(base_path().'assets/uploads/' . $directory . '/' . $name, base64_decode($file)); $img = Image::make(base64_decode($file)); if (null != $resize) { $img->resize($resize1, $resize2, function ($constraint) { $constraint->aspectRatio(); }); $thumbsPath = 'assets/uploads/' . $directory; } $img->save($thumbsPath . '/' . $name); return (string) $name; } } public static function failMsg($msg = '', $code = 401): \Illuminate\Http\JsonResponse { return response()->json([ 'user_status' => auth('api')->user() ? auth('api')->user()->status : '', 'key' => 'fail', 'msg' => $msg, 'code' => $code, ]); } public static function initOrderRoom(array $data) { // init room $room = Room::create([ 'userone_id' => $data['userone_id'], 'usertwo_id' => $data['usertwo_id'], 'order_id' => $data['order_id'], 'status' => 'open', ]); // send first message RoomMessage::create([ 'room_id' => $room->id, 'sender_id' => $data['usertwo_id'], 'receiver_id' => $data['userone_id'], 'content' => trans('order.delegate_welcome', ['name' => $data['delegate_name']]), ]); } public static function convert2english($string) { $newNumbers = range(0, 9); $arabic = array('٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'); $string = str_replace($arabic, $newNumbers, $string); return $string; } public static function applyDeliveryOffer($request,$total=0) { $discount=0; $the_discount=0; if(isset($request['store_id'])){ $store = Store::find($request['store_id']); if($store != null){ if( $store->offer=='true' ){ $amount=$store->offer_amount; $type=$store->offer_type; if($type=='percentage'){ $the_discount= $total* $amount/100; }else{ $the_discount= $amount; } $discount +=$the_discount; $discount= number_format($discount, 2, '.', ''); } } } return $discount; } public static function restoreProduct($id) { $orderproducts = OrderProduct::where('order_id' , $id)->get(); foreach($orderproducts as $orderproduct){ $group = ProductGroup::find($orderproduct->group_id); if($group) { $group->in_stock_qty += $orderproduct->qty; $group->update(); } } } public static function createOrder(array $data) { $user = auth('api')->user(); $request = $data['request']; // find store if (isset($request['store_id']) && isset($request['type']) == 'special_stores') { if (isset($request['store_id'])) { $store = Store::find($request['store_id']); // if (!$store || $store->openingHours()['open_status'] != true) { // $msg = trans('stores.not_available'); // $data['fail_msg'] = $msg; // return $data; // } } } //delivery price $distance = 0; $delivery_price = number_format(0, 2, '.', ''); if (isset($request['receive_lat']) && isset($request['receive_long']) && isset($request['deliver_lat']) && isset($request['deliver_long'])) { $distance = static::getdirectDistance($request['receive_lat'], $request['receive_long'], $request['deliver_lat'], $request['deliver_long']); $delivery_price = static::deliveryPrice($distance)['display_delivery_price']; } $request['delivery_price'] = $delivery_price; //app percintage on delivery price $app_percentage = static::appPercentage($delivery_price); $request['app_percentage'] = $app_percentage; // order price $price = 0; $price = number_format($price, 2, '.', ''); $request['price'] = $price; // added value $added_value = static::addedValue($app_percentage); $request['added_value'] = $added_value; // discount $discount = 0; $total = $price + $delivery_price + $app_percentage + $added_value ; if (isset($request['coupon'])) { $coupon_service = new CouponService(); $coupon_service_data = ['coupon' => $request['coupon'], 'delivery_price' => $total]; $discount = $coupon_service->enquiryCoupon($coupon_service_data); if ($discount == false) { $msg = trans('order.wrong_coupon_code'); $data['fail_msg'] = $msg; return $data; } else { $coupon_service->useCoupon($coupon_service_data); } } if(isset($request['deliver_time'])) { $request['deliver_time'] =date('H:i:s',strtotime($request['deliver_time']) ); } if(isset($request['delivery_date'])) { $request['deliver_date'] =date('Y-m-d',strtotime($request['delivery_date']) ); } $delivery_discount = static::applyDeliveryOffer($request,$total); $discount +=$delivery_discount; $discount = number_format($discount, 2, '.', ''); $request['discount'] = $discount; // total_price $total_price = $price + $delivery_price + $app_percentage + $added_value - $discount; $total_price = number_format($total_price, 2, '.', ''); $request['total_price'] = $total_price; if (isset($request['groups']) && isset($request['type']) && $request['type'] == 'special_stores') { $product_exists = false; foreach (json_decode($request['groups']) as $g) { //fing group $group = ProductGroup::find($g->id); if (!$group) { continue; } //new $product = Product::find($group->product_id); if(! $product){ $msg = trans('order.products_not_available'); $data['fail_msg'] = $msg; return $data; } if((OrderProduct::where('group_id' , $group->id)->whereDate('created_at' , Carbon::today())->sum('qty')) > ($group->in_stock_qty - $g->qty) ){ $msg = trans('order.products_not_available'); $data['fail_msg'] = $msg; return $data; } } } // store the main order data $order = Order::create($request + ['user_id' => $user->id]); // special_stores // order products // the main groups if (isset($request['groups']) && isset($request['type']) && $request['type'] == 'special_stores') { //new: at least one group exist foreach (json_decode($request['groups']) as $g) { //fing group $group = ProductGroup::find($g->id); if (!$group) { continue; } // if($group->in_stock_qty < $g->qty ){ // $msg = trans('order.products_not_available'); // $data['fail_msg'] = $msg; // return $data; // } // $qty = $group->in_stock_qty - $g->qty; // $group->update(['in_stock_qty' => $qty]); // find group product $product = $group->product; // store order products // the main groups $orderproduct = OrderProduct::create(['order_id' => $order->id, 'product_id' => $product->id, 'group_id' => $group->id, 'price' => $group->price(), 'qty' => $g->qty]); // main group price $orderproduct_price = $group->price(); // additives $additives_price = 0; if(isset($g->additives)){ foreach ($g->additives as $a) { // find additive $addetive = ProductAdditive::find($a->id); if (!$addetive) { continue; } // store prder product additives $orderproductaddetive = OrderProductAdditive::create(['product_additive_id' => $addetive->id, 'order_product_id' => $orderproduct->id, 'price' => $addetive->price, 'qty' => $a->qty]); // additives price $additives_price += $addetive->price * $a->qty; } } // order main price = the main group price + its additives (* group qty) $price += ($orderproduct_price + $additives_price) * $g->qty; } //update order invoice $order->update(['price' => $price, 'total_price' => $order->total_price + $price, 'have_invoice' => 'true']); } // parcel delivery orders if (isset($request['type']) && $request['type'] == 'parcel_delivery') { $order->update(['have_invoice' => 'true', 'store_status' => 'accepted']); } // google places orders if (isset($request['type']) && $request['type'] == 'google_places') { $order->update(['store_status' => 'accepted']); } //special request orders if (isset($request['type']) && $request['type'] == 'special_request') { $order->update(['store_status' => 'accepted', 'min_expected_price' => static::expected_price()['min'], 'max_expected_price' => static::expected_price()['max']]); } // without delivery orders if (isset($request['needs_delivery']) && $request['needs_delivery'] == 'false') { $delivery_price = 0; $app_percentage = 0; $total_price = $price; $order->update(['delivery_price' => $delivery_price, 'app_percentage' => $app_percentage, 'total_price' => $price, 'needs_delivery' => 'false']); } // upload order images if (isset($request['images'])) { foreach ($request['images'] as $i) { $name = static::uploadFile($i, 'orders'); OrderImage::create(['name' => $name, 'order_id' => $order->id]); } } //send notifications static::sendNotifications($order, $user); // if ($order->needs_delivery == 'true'){ // $citc = new CitcServices(); // $citc->createOrder($order->id); // } return $order; } public static function sendNotifications($order, $user, $type = 'all') { //location and max distance $lat = isset($order->receive_lat) ? doubleval($order->receive_lat) : doubleval($user->lat); $long = isset($order->receive_long) ? doubleval($order->receive_long) : doubleval($user->long); $max_distance = Setting::where('key', 'distance')->first()->value; $distance = floatval(($max_distance * 0.1) / 15); $min_lat = $lat - $distance; $min_long = $long - $distance; $max_lat = $lat + $distance; $max_long = $long + $distance; //fetch nearest delegates $notified_users = User::where('status', 'active') ->where('type', 'delegate') ->where('active', 1) ->where('id', '!=', $user->id) ->where(function ($query) use ($min_lat, $max_lat, $min_long, $max_long) { $query->where('lat', '>=', $min_lat) ->where('lat', '<=', $max_lat) ->where('long', '>=', $min_long) ->where('long', '<=', $max_long); })->orderBy('created_at', 'desc') ->get(); // notify near ,active and available if ($type == 'delegates') { //notifiy delegates dispatch(new NewOrderNotify($notified_users, $order)); } else { //notifiy store if ($order->store_id && $order->store->has_contract == 'true') { $notified_user = $order->store->user; dispatch(new StoreNotify($notified_user, $order)); } else { //notifiy delegates dispatch(new NewOrderNotify($notified_users, $order)); } } } public static function orderEnquiry(array $data) { $user = auth('api')->user(); $request = $data['request']; // price $price = isset($request['price']) ? $request['price'] : 0; //delivery price $distance = 0; $delivery_price = 0; if (isset($request['receive_lat']) && isset($request['receive_long']) && isset($request['deliver_lat']) && isset($request['deliver_long'])) { $distance = static::directDistance($request['receive_lat'], $request['receive_long'], $request['deliver_lat'], $request['deliver_long']); $delivery_price = static::deliveryPrice($distance)['display_delivery_price']; } //app percintage on delivery price $app_percentage = 0; $app_percentage = static::appPercentage($delivery_price); // added value $added_value = static::addedValue($app_percentage); $request['delivery_price']=$delivery_price; // total price $total = (float)$price + (float)$delivery_price + (float)$app_percentage + (float)$added_value ; // discount $discount = 0; $coupon_msg=''; if (isset($request['coupon'])) { $coupon_service = new CouponService(); $coupon_service_data = ['coupon' => isset($request['coupon']) ? $request['coupon'] : '', 'delivery_price' => isset($total) ? $total : '']; $discount = $coupon_service->enquiryCoupon($coupon_service_data); if ($discount == false) { $msg = trans('order.wrong_coupon_code'); $data['fail_msg'] = $msg; return $data; } else{ $coupon_msg = trans('order.success_coupon'); } } $delivery_discount = static::applyDeliveryOffer($request,$total); $discount +=$delivery_discount; $discount = number_format($discount, 2, '.', ''); //here // total price $total_price = (float)$price + (float)$delivery_price + (float)$app_percentage + (float)$added_value - (float)$discount; $total_price = number_format($total_price, 2, '.', ''); $data = []; $data['price'] = number_format($price,2) . ' ' . trans('stores.sar'); $data['delivery_price'] = $delivery_price . ' ' . trans('stores.sar'); $data['app_percentage'] = $app_percentage . ' ' . trans('stores.sar'); $data['added_value'] = $added_value . ' ' . trans('stores.sar'); $data['discount'] = $discount . ' ' . trans('stores.sar'); $data['total_price'] = $total_price . ' ' . trans('stores.sar'); if (isset($request['coupon'])) { $data['has_coupon'] = true; } else { $data['has_coupon'] = false; } $data['coupon_msg'] = $coupon_msg; return $data; } public static function delegateAcceptOrder(array $data) { // $delegate = auth('api')->user(); $delegate = User::findOrFail($data['delegate_id']) ; $request = $data['request']; if (!isset($request['order_id'])) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // find order $order = Order::where('id', $request['order_id'])->where('delegate_id' , null)->where('type', '!=', 'special_request')->where('needs_delivery', 'true')->where('status', '!=', 'closed')->first(); if (! $order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } if ($order->status=='canceled') { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } if ($order->delegate_id !== null) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } $delegate_max_debt = Setting::where('key', 'delegate_max_debt')->first()->value; if ($delegate->wallet < 0 && $delegate->wallet <= (int) $delegate_max_debt * -1) { $msg = trans('order.you_have_to_charge'); $data['fail_msg'] = $msg; return $data; } if (!$order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } //check if delegate withdraw this order before if ($delegate->withdrawReasons()->where('order_id', $order->id)->first()) { $msg = trans('order.you_withdraw_this_order'); $data['fail_msg'] = $msg; return $data; } // assign order to delegate $order->update(['delegate_id' => $delegate->id, 'delivery_status' => 'accepted', 'status' => 'inprogress', 'delegate_acceptance' => date('Y-m-d H:i:s')]); // create the room $room_data = ['userone_id' => $order->user_id, 'usertwo_id' => $delegate->id, 'order_id' => $order->id, 'delegate_name' => $delegate->name]; static::initOrderRoom($room_data); // notify $notified_user = User::find($order->user_id); if ($notified_user) { dispatch(new DelegateAcceptOfferNotify($notified_user, $order , $delegate)); } // $citc = new CitcServices(); // $citc->assignDriverToOrder($order->id); return $data ; } public static function delegateCreateOrderInvoice(array $data) { $delegate = auth('api')->user(); $request = $data['request']; if (!isset($request['image'])) { $msg = trans('order.invoice_required'); $data['fail_msg'] = $msg; return $data; } // find order $order = $delegate->delegateOrders()->where('id', $request['order_id'])->where('status', 'inprogress')->whereIn('type', ['google_places', 'special_request'])->first(); if (!$order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // order price $price = static::convert2english($request['price']); // $price = number_format($price, 2); $price = (float)$price; // total_price $total_price = $order->total_price + $price; // update order $order->update(['price' => $price, 'total_price' => $total_price, 'invoice_image' => static::uploadFile($request['image'], 'invoices'), 'have_invoice' => 'true']); // notify $notified_user = User::find($order->user_id); if ($notified_user) { dispatch(new DelegateCreateInvoiceNotify($notified_user, $order)); } } public static function delegateIntransitOrder(array $data) { $delegate = auth('api')->user(); $request = $data['request']; $order = $delegate->delegateOrders()->where('id', $request['order_id'])->first(); if (!$order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } if ($request['delivery_status']=='delivering' && $order->store_status !== 'delivered') { $msg = trans('order.wait_store_prepared'); $data['fail_msg'] = $msg; return $data; } $order->update(['delivery_status' => $request['delivery_status'] ]); // $order->delivery_status = $request['delivery_status']; // $order->update(); // notify $notified_user = User::find($order->user_id); if ($notified_user) { dispatch(new OrderIntransitNotify($notified_user, $order, $request['delivery_status'])); } // $citc = new CitcServices(); // $citc->executeOrder($order->id); } public function delegateNearWaitingOrders(array $data) { $delegate = auth('api')->user(); //location and max distance $request = $data['request']; $lat = isset($request['lat']) ? doubleval($request['lat']) : doubleval($delegate->lat); $long = isset($request['long']) ? doubleval($request['long']) : doubleval($delegate->long); $max_distance = Setting::where('key', 'distance')->first()->value; $distance = floatval(($max_distance * 0.1) / 15); $min_lat = $lat - $distance; $min_long = $long - $distance; $max_lat = $lat + $distance; $max_long = $long + $distance; // fetch orders $orders = Order::where('status', 'open') ->where('store_status', 'accepted') ->where('user_id', '!=', $delegate->id) ->where('delegate_id',null) ->where('needs_delivery', 'true') ->whereNotIn('id', WithdrawReason::select('order_id')->where('user_id', '=', $delegate->id)->get()->toArray()) ->where(function ($query) use ( $min_lat, $max_lat, $min_long, $max_long) { $query->where('type', 'special_request') ->where('deliver_lat', '>=', $min_lat) ->where('deliver_lat', '<=', $max_lat) ->where('deliver_long', '>=', $min_long) ->where('deliver_long', '<=', $max_long); })->orderBy('created_at', 'desc') ->paginate($this->paginateNum()); return $orders; } public static function makeDeliveryOffer(array $data) { $request = $data['request']; $user = auth('api')->user(); $order = Order::where('status', 'open')->where('type', 'special_request')->where('id', $request['order_id'])->first(); if (!$order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } $delegate_max_debt = Setting::where('key', 'delegate_max_debt')->first()->value; if ($user->wallet < 0 && $user->wallet <= (int) $delegate_max_debt * -1) { $msg = trans('order.you_have_to_charge'); $data['fail_msg'] = $msg; return $data; } //check if delegate withdraw this order before if ($user->withdrawReasons()->where('order_id', $order->id)->first()) { $msg = trans('order.you_withdraw_this_order'); $data['fail_msg'] = $msg; return $data; } // delete previous offers $user->deliveryOffers()->where('order_id', $request['order_id'])->delete(); // create new offer DeliveryOffer::create(['price' => $request['delivery_price'], 'user_id' => $user->id, 'order_id' => $request['order_id']]); // notify $notified_user = User::find($order->user_id); if ($notified_user) { dispatch(new DelegateMakeOfferNotify($notified_user, $order)); } } public static function userAcceptDeliveryOffer(array $data) { $request = $data['request']; $user = auth('api')->user(); // delivery offer $delivery_offer = DeliveryOffer::with('order')->where('status', 'new')->find($request['delivery_offer_id']); if (!$delivery_offer) { $msg = trans('order.offer_not_available'); $data['fail_msg'] = $msg; return $data; } // order $order = $delivery_offer->order()->first(); if (!$order || $order->user_id != $user->id || $order->status != 'open') { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // delegate $delegate = $delivery_offer->user; // update delivery_offer $delivery_offer->status = 'accepted'; $delivery_offer->save(); // reject other delivery_offers DeliveryOffer::where('id', '!=', $request['delivery_offer_id'])->update(['status' => 'rejected']); // update order | assign order to delegate & calc delivery_price & app percentage & added_value and the new total price $discount = 0; $delivery_price = number_format($delivery_offer->price,2, '.', ''); $app_percentage = static::appPercentage($delivery_price); $added_value = static::addedValue($app_percentage); // total_price $total_price = $delivery_price + $app_percentage + $added_value - $discount; $total_price = number_format($total_price, 2, '.', ''); $order->delivery_status = 'accepted'; $order->status = 'inprogress'; $order->delegate_id = $delivery_offer->user_id; $order->delivery_price = $delivery_price; $order->app_percentage = $app_percentage; $order->added_value = $added_value; $order->total_price = $total_price; $order->delegate_acceptance = date('Y-m-d H:i:s'); $order->update(); // create the room $room_data = ['userone_id' => $user->id, 'usertwo_id' => $delivery_offer->user_id, 'order_id' => $order->id, 'delegate_name' => $delegate->name]; static::initOrderRoom($room_data); // notify $notified_user = User::find($order->delegate_id); if ($notified_user) { dispatch(new UserAcceptOfferNotify($notified_user, $order)); } // $citc = new CitcServices(); // $citc->assignDriverToOrder($order->id); } public static function userRejectDeliveryOffer(array $data) { $request = $data['request']; $user = auth('api')->user(); // delivery offer $delivery_offer = DeliveryOffer::where('status', 'new')->where('id', $request['delivery_offer_id'])->first(); if (!$delivery_offer) { $msg = trans('order.offer_not_available'); $data['fail_msg'] = $msg; return $data; } // order $order = $delivery_offer->order()->first(); if (!$order || $order->user_id != $user->id || $order->status != 'open') { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // delegate $delegate = $delivery_offer->user; // update delivery_offer $delivery_offer->status = 'rejected'; $delivery_offer->save(); // notify // $notified_user = User::find($order->delegate_id); if ($delegate) { dispatch(new UserRejectOfferNotify($delegate, $order)); } } public static function changePaymentMethod(array $data) { $request = $data['request']; $user = auth('api')->user(); // find order $order = $user->userOrders()->where('status', '!=', 'finished')->where('id', $request['order_id'])->first(); if (!$order) { $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } if ($order->payment_type != 'cash' && $order->payment_status == 'true') { $msg = trans('order.cant_change_payment_method'); $data['fail_msg'] = $msg; return $data; } $order->update(['payment_type' => $request['payment_type']]); //notify $notified_user = User::find($order->delegate_id); if ($notified_user) { dispatch(new ChangePaymentMethodNotify($notified_user, $order)); } } public static function finishOrder(array $data) { $order = $data['order']; // update user if ($user = $order->user) { $user->num_orders += 1; $user->total_bills += $order->total_price; $user->update(); } // update delegate if ($delegate = $order->delegate) { $delegate->total_delivery_fees += $order->delivery_price; if ($order->payment_type == 'cash') { $delegate->wallet -= ($order->app_percentage + $order->added_value) - $order->discount; } else { $delegate->wallet += $order->price + $order->delivery_price; } $delegate->update(); } $products_app_percentage = 0; if ($order->store && $order->store->has_contract == 'true') { $products_app_percentage = $order->store->commission_type == 'static_price' ? ($order->store->app_commission) : ($order->price * $order->store->app_commission / 100); $order->store->user->wallet -= $products_app_percentage; $order->store->user->update(); #store commission $store_commission = StoreCommission::create([ 'order_id' => $order->id, 'user_id' => $order->store->user->id, 'products_price' => $order->price, 'commission' => $products_app_percentage, ]); } // app profits from delivery and from store there is contract $profit = Profit::create([ 'order_id' => $order->id, 'delivery_app_percentage' => $order->app_percentage, 'added_value' => $order->added_value, 'total_delivery_profits' => $order->added_value + $order->app_percentage, 'products_app_percentage' => $products_app_percentage, 'total_order_profits' => $products_app_percentage + $order->added_value + $order->app_percentage, ]); $vat = Vat::create([ 'order_id' => $order->id, 'added_value' => $order->added_value, 'store_vat' => static::addedValue($profit->products_app_percentage), 'total_vat' => $order->added_value+static::addedValue($profit->products_app_percentage), ]); // update order $order->update(['delivery_status' => 'delivered', 'status' => 'finished']); } public static function cancelOrder(array $data) { $order = $data['order']; $reason = $data['reason']; // update order self::restoreProduct($order->id); $order->update(['status' => 'closed', 'close_reason' => $reason]); //notify if($order->store){ $notified_user = $order->store->user; if ($notified_user) { dispatch(new UserCancelOrderNotify($notified_user, $order)); } } if($order->delegate){ $notified_user = $order->delegate; if ($notified_user) { dispatch(new UserCancelOrderNotify($notified_user, $order)); } } // if ($order->needs_delivery == 'true'){ // $citc = new CitcServices(); // $citc->cancelOrder($order->id); // } } public static function withdrawOrder(array $data) { $order = $data['order']; $reason = $data['reason']; if ($order->payment_status == 'true') { $msg = trans('order.you_cannot_withdraw'); $data['fail_msg'] = $msg; return $data; } // update order $order->update(['status' => 'open', 'delivery_status' => 'pending', 'delegate_id' => null]); WithdrawReason::create(['reason' => $reason, 'user_id' => auth('api')->user()->id, 'order_id' => $order->id]); $notified_user = User::find($order['user_id']); if ($notified_user) { dispatch(new DelegateWithdrawNotify($notified_user, $order)); } } public static function rejectOrder(array $data) { $order = $data['order']; $reason = $data['reason']; if ($order->payment_status == 'true') { $msg = trans('order.you_cannot_withdraw'); $data['fail_msg'] = $msg; return $data; } // update order WithdrawReason::create(['reason' => $reason, 'user_id' => auth('api')->user()->id, 'order_id' => $order->id]); // $notified_user = User::find($order['user_id']); // if ($notified_user) { // dispatch(new DelegateWithdrawNotify($notified_user, $order)); // } } public static function payOrderWithWallet(array $data) { $order = $data['order']; $user = $order->user; // update order $order->update(['payment_status' => 'true', 'payment_type' => 'wallet']); // update user wallet $user->wallet -= $order->total_price; $user->update(); //notify $notified_user = User::find($order->delegate_id); $pay_type = 'wallet'; if ($notified_user) { dispatch(new DelegatePayWithWallet($notified_user, $order)); } } public static function storeOrders(array $data) { $user = Auth::user(); $store = $user->store; if($data['status'] == 'inprogress') { $orders = Order::where('store_id',$store->id) ->whereIn('store_status',['accepted','prepared']) ->orderBy('created_at','desc') ->get(); }else{ $orders = Order::where('store_id',$store->id) ->where('status',$data['status']) ->where('store_status',$data['store_status']) ->orderBy('created_at','desc') ->get(); } return $orders; } public static function storeAcceptOrder(array $data) { $order = $data['order']; $user = Auth::user(); if($order['status'] =='closed'){ $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // update order $order->update(['store_status' => 'accepted' , 'status' => 'inprogress']); //notify $notified_user = $order->user; dispatch(new StoreAcceptOrderNotify($notified_user, $order)); if($order['needs_delivery']=='false'){ $order->update(['status' => 'inprogress']); } if($order['needs_delivery']=='true'){ //send notifications static::sendNotifications($order, $user, 'delegates'); // $citc = new CitcServices(); // $citc->acceptOrder($order->id); } return $data; } public static function storeRejectOrder(array $data) { $order = $data['order']; $reason = $data['reason']; if($order['status'] =='closed'){ $msg = trans('order.not_available'); $data['fail_msg'] = $msg; return $data; } // update order self::restoreProduct($order->id); $order->update(['store_status' => 'rejected', 'status' => 'closed' , 'close_reason' => $reason]); // if ($order->needs_delivery == 'true'){ // $citc = new CitcServices(); // $citc->rejectOrder($order->id); // } //notify $notified_user = $order->user; dispatch(new StoreRefuseOrderNotify($notified_user, $order)); return $data; } public static function storePreparedOrder(array $data) { $order = $data['order']; // update order $order->update(['store_status' => 'prepared']); // //notify // $notified_user = $order->delegate; // dispatch(new StoreDoneOrderNotify($notified_user, $order)); //notify $notified_user = $order->user; dispatch(new StoreDoneOrderNotify($notified_user, $order)); } public static function storeDeliveryOrder(array $data) { $order = $data['order']; // update order $order->update(['store_status' => 'delivered']); WaitingSettlementOrder::create([ 'order_id' => $order->id, 'provider_id' => auth('api')->id(), 'amount' => $order->price - $order->app_percentage, ]); $notified_user = $order->user; dispatch(new StoreDoneOrderNotify($notified_user, $order , 'delivered')); } public static function directDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo) { $earthRadius = 6371000; // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $lonDelta = $lonTo - $lonFrom; $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); $in_km = ($angle * $earthRadius) / 1000; $in_km += (40 / 100) * $in_km; $in_km = number_format((float) $in_km, 2, '.', ''); return $in_km; } }
Back to File Manager