123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856 |
- <?php
- /**
- * Created by PhpStorm.
- * User: Mead
- * Date: 2019/8/19
- * Time: 2:11 PM
- */
- namespace App\Http\Controllers\V1;
- use App\Handlers\Activities\CouponActivityHandler;
- use App\Handlers\Activities\RidingCardActivityHandler;
- use App\Handlers\BaseBikeControl;
- use App\Handlers\BikeHandler;
- use App\Handlers\BikeStatusInfoSyncHandler;
- use App\Http\Requests\BikeCloseOrderRequest;
- use App\Http\Requests\OrderBikePositionRequest;
- use App\Http\Requests\OrderPayRequest;
- use App\Http\Requests\OrderPayShowRequest;
- use App\Http\Requests\RelayOrderAutoCloseRequest;
- use App\Http\Requests\RetryBikeRequest;
- use App\Maps\CacheMap;
- use App\Models\AreaSetting;
- use App\Models\Bike;
- use App\Models\CardRidingUserBags;
- use App\Models\CouponsUserBag;
- use App\Models\LocationLogMongodb;
- use App\Models\Order;
- use App\Models\OrderBikeOperate;
- use App\Models\WalletLog;
- use App\Repositories\AreaRepository;
- use App\Repositories\AreaSettingRepository;
- use App\Repositories\BikeRepository;
- use App\Repositories\CardRidingUserBagsRepository;
- use App\Repositories\LocationLogRepository;
- use App\Repositories\OrderBikeOperateRepository;
- use App\Repositories\OrderRepository;
- use App\Transformers\OrderPayTransformer;
- use App\Transformers\OrderTransformer;
- use Carbon\Carbon;
- use Dingo\Api\Http\Request;
- use EasyWeChat\Kernel\Exceptions\HttpException;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Redis;
- use function EasyWeChat\Kernel\Support\generate_sign;
- /**
- * 临时订单管理
- * Class OrderController
- * @package App\Http\Controllers\V1
- */
- class OrderController extends BaseController
- {
- /**
- * 订单列表
- * @param Request $request
- * @param Order $order
- * @return \Dingo\Api\Http\Response|void
- * User: Mead
- */
- public function index(Request $request, Order $order)
- {
- try {
- $query = $order->query();
- if ($year = $request->get('year', date('Y'))) {
- $query->whereYear('created_at', $year);
- }
- if ($month = $request->get('month', date('m'))) {
- $query->whereMonth('created_at', $month);
- }
- $orders = $query->where('user_id', $this->user->id)->orderBy('id', 'desc')->paginate();
- $orders->appends($request->only(['year', 'month']))->withPath(config('app.url') . '/api/orders');
- return $this->response->paginator($orders, OrderTransformer::class);
- } catch (\Exception $exception) {
- return $this->errorException($exception->getMessage());
- }
- }
- /**
- * 支付页面
- * @param OrderPayShowRequest $request
- * @param OrderRepository $orderRepository
- * @return mixed
- * User: Mead
- */
- public function payShow(OrderPayShowRequest $request, OrderRepository $orderRepository, LocationLogRepository $locationLogRepository, AreaSettingRepository $areaSettingRepository, CouponActivityHandler $couponActivityHandler, CardRidingUserBagsRepository $cardRidingUserBagsRepository, RidingCardActivityHandler $ridingCardActivityHandler, OrderBikeOperateRepository $orderBikeOperateRepository, BikeRepository $bikeRepository)
- {
- try {
- $order_no = $request->get('order_no');
- $is_first = $request->get('is_first') ?? false;
- $couponUserBagsId = $request->get('coupon_user_bags_id') ?? '';
- $order = $orderRepository->byNoAndUserId($order_no, $this->user->id);
- // 骑行卡优惠
- $ridingCardActivityHandler->main($order);
- // 判断车是否在停车的区域
- $BikeHandler = new BikeHandler();
- $location = [];
- $is_in_time = (Carbon::now()->diffInSeconds(Carbon::parse($order->end_use_bike_time)) < 15);
- if ($is_in_time) {
- $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
- } else {
- $location = $locationLogRepository->byOrderIdGetLastLocation($order->id, CacheMap::IS_OPEN_MONGODB_DUG);
- }
- $setting = $areaSettingRepository->byAreaId($order->area_id);
- if ($areaSettingRepository->byAreaIdGetIsWholeAreaHuanche($order->area_id) === AreaSetting::WHOLE_AREA_HUANCHE_NO) {
- //检查车是否在停车位置
- $is_in_time = (Carbon::now()->diffInSeconds(Carbon::parse($order->end_use_bike_time)) < 30);
- if (((int)$order->is_admin_settle_order === Order::IS_ADMIN_SETTLE_ORDER_USER) && ($order->dispatch_money > 0) && $is_in_time && (int)$order->status === Order::STATUS_CLOSE_BIKE) {
- // 判断是否在停车点
- if (!is_null($location['lat']) && ($location['lat'] > 0)) {
- $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id);
- if (!$is_huanche['status']) {
- // 不在还车点
- $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
- $order->dispatch_money = $dispatch_money;
- } else {
- $order->dispatch_money = 0;
- }
- $order->order_money = bcadd($order->time_money, $order->dispatch_money, 2);
- //计算优惠金额
- $order->order_money = bcsub($order->order_money, $order->preferential_money, 2);
- $order->pay_money = $order->order_money;
- }
- $is_in_parking = Bike::IN_PARKING_YES;
- if ($order->dispatch_money > 0) {
- $is_in_parking = Bike::IN_PARKING_NO;
- }
- if ($is_in_time) {
- Bike::where('id', $order->bike_id)->update([
- 'is_in_parking' => $is_in_parking
- ]);
- }
- }
- }
- //检查是否在禁停区
- // 如果后台结算 则api 不用再次计算调度费
- if (((int)$order->is_admin_settle_order === Order::IS_ADMIN_SETTLE_ORDER_USER) && (int)$order->status === Order::STATUS_CLOSE_BIKE) {
- if (!is_null($location['lat']) && ($location['lat'] > 0)) {
- $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($location['lat'], $location['lng'], $order->area_id, $location['lat'], $location['lng']);
- if ($is_ban_stop_bike) {
- return $this->errorNoValidation('禁停区域内禁止停车!');
- //
- // // 在禁停区 收取调度费
- // $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id, $location['lat'], $location['lng']);
- //
- //
- // $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
- // $order->dispatch_money = $dispatch_money;
- //
- // $order->order_money = bcadd($order->time_money, $order->dispatch_money, 2);
- // //计算优惠金额
- // $order->order_money = bcsub($order->order_money, $order->preferential_money, 2);
- // $order->pay_money = $order->order_money;
- }
- }
- }
- // $bike = $bikeRepository->byIdGetModel($order->bike_id);
- // $user = $this->user;
- //临时增加用车免费
- // if($bike->put_area_id == 11){
- // $redis = Redis::connection();
- //
- // if($redis->sismember(CacheMap::FREE_MEMBERS,$user->mobile)) {
- // $order->order_money = 0;
- // $order->time_money = 0;
- // $order->pay_money = 0;
- // $order->dispatch_money = 0;
- // }
- // }
- if (bccomp($order->order_money, 0) === 0) {
- $order->status = Order::STATUS_COMPLETE_ORDER;
- if ($order->use_bike_time_length === 0) {
- $order->status = Order::STATUS_CLOSE_ORDER;
- }
- }
- $order->save();
- if ($is_first) {
- // 首次
- $data = $couponActivityHandler->isCouponsByOrder($order);
- if (empty($data['dataYes'])) {
- $userCoupons = [];
- } else {
- // 取最大优惠
- $userCoupons = $data['dataYes'][0];
- }
- } else {
- $userCoupons = $couponActivityHandler->getCouponsByOrderAndId($order, $couponUserBagsId);
- }
- $ridingCard = $cardRidingUserBagsRepository->isExist($this->user->id);
- // 能否选择优惠券
- $couponData = $couponActivityHandler->isCouponsByOrder($order);
- if (count($couponData['dataYes']) + count($couponData['dataNo']) > 0) {
- $is_coupon = true;
- } else {
- $is_coupon = false;
- }
- // 检查用户余额是否够
- $is_user_wallet = true;
- if (empty($userCoupons)) {
- if ($order->pay_money > $this->user->wallet_money) {
- // 余额不够
- $is_user_wallet = false;
- }
- } elseif ($userCoupons['order_wait_pay_money'] > $this->user->wallet_money) {
- // 余额不够
- $is_user_wallet = false;
- }
- $system_off_lock_text = '';
- if (in_array(Order::PREFERENTIAL_FREE_MINUTE, str2arr($order->preferential_type, '-'))) {
- $system_off_lock_text = $areaSettingRepository->byAreaIdGetFreeMinute($order->area_id) . '分钟内免费骑行';;
- }
- // 检查是否系统自动锁车
- $is_system_off_lock = $orderBikeOperateRepository->checkLowPowerOffLock($order->id);
- if ($is_system_off_lock) {
- $system_off_lock_text = $is_system_off_lock->name . ',敬请谅解,如有疑问请致电客服';
- }
- return $this->response->array([
- // 'order' => $order->append(['use_bike_time_length_text', 'pause_bike_time_length_text', 'use_bike_distance_length_text', 'end_use_bike_time_timestamp', 'preferential_type_name'])->toArray(),
- 'orders' => [
- 'id' => $order->id,
- 'no' => $order->no,
- 'bike_no' => $order->bike_no,
- 'use_bike_time_length_text' => $order->use_bike_time_length_text,
- 'use_bike_distance_length_text' => $order->use_bike_distance_length_text,
- 'end_use_bike_time_timestamp' => $order->end_use_bike_time_timestamp,
- 'pay_status' => $order->pay_status,
- 'pay_money' => $order->pay_money,
- 'time_money' => $order->time_money, // 时长费
- 'dispatch_money' => $order->dispatch_money, // 调度费
- 'distance_money' => $order->distance_money, // 里程费用
- 'order_money' => bcadd(bcadd($order->time_money, $order->distance_money, 2), $order->dispatch_money, 2),// 加调度费的总金额
- 'order_total_money' => bcadd($order->time_money, $order->distance_money, 2), // 不加调度费的总金额
- 'order_wait_pay_money' => empty($userCoupons) ? $order->order_money : $userCoupons['order_wait_pay_money'], // 总待支付
- 'total_preferential_money' => empty($userCoupons) ? $order->preferential_money : $userCoupons['total_preferential_money'], // 总优惠
- ],
- 'wallet_pay_status' => $is_user_wallet,
- 'wallet_money' => $this->user->wallet_money,
- 'user_coupon' => [
- 'is_coupon' => $is_coupon,
- 'coupon_preferential_money' => empty($userCoupons) ? '0.00' : $userCoupons['coupon_preferential_money'], // 优惠券优惠的金额
- 'coupon_user_bags_id' => empty($userCoupons) ? 0 : $userCoupons['id'],
- ],
- 'user_card' => [
- 'is_card' => empty($ridingCard) ? false : true,
- 'card' => $ridingCard,
- 'card_preferential_money' => $order->preferential_money, // 没支付之前优惠金额就是 骑行卡优惠的金额
- ],
- 'system_off_lock' => [
- 'is_system_off_lock' => empty($system_off_lock_text) ? false : true,
- 'system_off_lock_text' => $system_off_lock_text
- ],
- ]);
- } catch (\Exception $exception) {
- return $this->errorException($exception->getMessage());
- }
- }
- /**
- * 订单详情页
- * @param OrderPayShowRequest $request
- * @param OrderRepository $orderRepository
- * @return \Dingo\Api\Http\Response
- * User: Mead
- */
- public function show(OrderPayShowRequest $request, OrderRepository $orderRepository)
- {
- try {
- $order_no = $request->get('order_no');
- $order = $orderRepository->byNoAndUserId($order_no, $this->user->id);
- if (!$order) return $this->errorNoValidation('找不到该订单');
- return $this->response->item($order, new OrderPayTransformer());
- } catch (\Exception $exception) {
- return $this->errorException($exception->getMessage());
- }
- }
- /**
- * 订单支付
- * @param OrderPayRequest $request
- * @param OrderRepository $orderRepository
- * User: Mead
- */
- public function pay(OrderPayRequest $request, OrderRepository $orderRepository, CouponActivityHandler $couponActivityHandler, RidingCardActivityHandler $ridingCardActivityHandler)
- {
- try {
- $pay_type = $request->get('pay_type');
- $order_no = $request->get('order_no');
- $couponUserBagsId = $request->get('coupon_user_bags_id') ?? '';
- $order = $orderRepository->byNo($order_no);
- if (!$order) return $this->errorBadRequest('订单不存在');
- if ((int)$order->pay_status === Order::PAY_STATUS_OK) return $this->errorNoValidation('订单已支付');
- if ((int)$order->status === Order::STATUS_COMPLETE_ORDER) return $this->errorNoValidation('订单已完成');
- if (in_array($order->status, [Order::STATUS_PAUSE_BIKE, Order::STATUS_RIDE_BIKE])) return $this->errorNoValidation('订单状态可能出在骑行中,请先锁车');
- $user = $this->user;
- if ($order->user_id !== $user->id) return $this->errorNoValidation('非法操作');
- $user_id = $user['id'];
- $cache_key = "PAY_ORDER_{$user_id}";
- if (Cache::has($cache_key)) {
- return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
- }
- Cache::put($cache_key, 1, Carbon::now()->addSeconds(5));
- // 骑行卡优惠
- $ridingCardActivityHandler->main($order);
- // 优惠券优惠
- $couponActivityHandler->main($order, $couponUserBagsId);
- $order->save();
- $response = '';
- switch ($pay_type) {
- case Order::PAY_TYPE_ACCOUNT:
- //余额支付
- if ($order->order_money > $this->user->wallet_money) {
- // 余额不够
- return $this->errorNoValidation('用户余额不够');
- }
- DB::transaction(function () use ($order, $user, $couponUserBagsId) {
- //添加钱包记录
- WalletLog::log(WalletLog::OPERATE_TYPE_SUB, $order->order_money, $user->id, WalletLog::TYPE_SUB_WALLET_BIKE_ORDER, $order->area_id, $order->id, Order::class);
- //修改订单记录
- $order->pay_status = Order::PAY_STATUS_OK;
- $order->pay_time = now();
- $order->pay_type = Order::PAY_TYPE_ACCOUNT;
- $order->pay_money = $order->order_money;
- $order->status = Order::STATUS_COMPLETE_ORDER;
- if ($order->is_coupon == Order::COUPON_OK) {
- CouponsUserBag::useCoupon($order->id, $couponUserBagsId);
- // 优惠方式
- if ($order->preferential_type == 0) {
- $order->preferential_type = arr2str([Order::PREFERENTIAL_COUPON], '-');
- } else {
- $arr = str2arr($order->preferential_type, '-');
- $order->preferential_type = arr2str(array_merge($arr, [Order::PREFERENTIAL_COUPON]), '-');
- }
- // 更新订单得优惠金额
- $order->coupon_user_bags_id = $couponUserBagsId;
- $order->preferential_money = bcsub(bcadd($order->time_money, $order->dispatch_money, 2), $order->pay_money, 2);
- // 更新优惠券优惠金额
- $order->coupon_preferential_money = bcsub($order->preferential_money, $order->card_preferential_money, 2);
- }
- $order->save();
- });
- $response = [
- 'pay_order_status' => true
- ];
- break;
- case Order::PAY_TYPE_WECHAT:
- //微信支付
- $payment = app('wechat.payment'); // 微信支付
- $username = $user->truename;
- $auth = $user->auth;
- $result = $payment->order->unify([
- 'body' => "用户支付临时骑行订单-" . config('app.name', '未来bike'),
- 'out_trade_no' => $order->no,
- 'trade_type' => 'JSAPI', // 必须为JSAPI
- 'openid' => $auth['credential'], // 这里的openid为付款人的openid
- 'total_fee' => wechat_fee($order->order_money), // 总价
- 'attach' => makeNoTag(Order::NO_TAG)
- ]);
- if ($result['return_code'] === 'FAIL') return $this->errorNoValidation('下单失败');
- // 如果成功生成统一下单的订单,那么进行二次签名
- if ($result['result_code'] === 'FAIL') {
- //判断是否重复下单
- if (in_array($result['err_code'], ['INVALID_REQUEST', 'ORDERCLOSED'])) {
- $order->no = Order::makeNo();
- $order->save();
- $x_no = $order->no;
- $result = $payment->order->unify([
- 'body' => "用户支付临时骑行订单-" . config('app.name', '未来bike'),
- 'out_trade_no' => $order->no,
- 'trade_type' => 'JSAPI', // 必须为JSAPI
- 'openid' => $auth['data']['credential'], // 这里的openid为付款人的openid
- 'total_fee' => wechat_fee($order->order_money), // 总价
- 'attach' => makeNoTag(Order::NO_TAG)
- ]);
- } else {
- return $this->errorNoValidation('下单失败');
- }
- // if ($result['err_code'] === 'INVALID_REQUEST') {
- // $order->no = Order::makeNo();
- // $order->save();
- // $result = $payment->order->unify([
- // 'body' => "用户支付临时骑行订单-" . config('app.name', '未来bike'),
- // 'out_trade_no' => $order->no,
- // 'trade_type' => 'JSAPI', // 必须为JSAPI
- // 'openid' => $auth['credential'], // 这里的openid为付款人的openid
- // 'total_fee' => wechat_fee($order->order_money), // 总价
- // 'attach' => makeNoTag(Order::NO_TAG)
- // ]);
- // } else {
- // return $this->errorNoValidation('下单失败');
- // }
- }
- // 二次签名的参数必须与下面相同
- $params = [
- 'appId' => $auth['identifier'],
- 'timeStamp' => time(),
- 'nonceStr' => $result['nonce_str'],
- 'package' => 'prepay_id=' . $result['prepay_id'],
- 'signType' => 'MD5',
- ];
- // config('wechat.payment.default.key')为商户的key
- $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
- $response = $params;
- $response['order_no'] = $order->no;
- break;
- default:
- return $this->errorBadRequest('支付类型不对');
- break;
- }
- return $this->response->array($response);
- } catch (\Exception $exception) {
- return $this->errorException($exception->getMessage());
- }
- }
- /**
- * 重试开车
- * @param Request $request
- * @param OrderRepository $orderRepository
- * @param BikeRepository $bikeRepository
- * User: Mead
- */
- public function retryOpenLock(RetryBikeRequest $request, OrderRepository $orderRepository, BikeRepository $bikeRepository)
- {
- try {
- $order_no = $request->get('order_no');
- $bike_no = $request->get('bike_no');
- $order = $orderRepository->checkUserIsRetryOpenLock($order_no, $bike_no, $this->user->id);
- if (!$order) return $this->errorNoValidation('没有此订单');
- $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
- if ($second > 60) {
- return $this->errorNoValidation('暂不能操作开车');
- }
- $box_no = $bikeRepository->byIdGetBoxNo($order->bike_id);
- if (!$box_no) return $this->errorNoValidation('找不到该车');
- (new BaseBikeControl($box_no))::openLock();
- return $this->response->array([
- 'status' => 1
- ]);
- } catch (\Exception $exception) {
- return $this->errorNoValidation($exception->getMessage());
- }
- }
- /**
- * 重试锁车
- * @param Request $request
- * @param OrderRepository $orderRepository
- * @param BikeRepository $bikeRepository
- * User: Mead
- */
- public function retryCloseLock(RetryBikeRequest $request, OrderRepository $orderRepository, BikeRepository $bikeRepository)
- {
- try {
- $order_no = $request->get('order_no');
- $bike_no = $request->get('bike_no');
- $order = $orderRepository->checkUserIsRetryOpenLock($order_no, $bike_no, $this->user->id);
- if (!$order) return $this->errorNoValidation('没有此订单');
- $second = Carbon::now()->diffInSeconds(Carbon::parse($order->end_use_bike_time));
- if ($second > 60) {
- return $this->errorNoValidation('暂不能操作关车');
- }
- $box_no = $bikeRepository->byIdGetNoRidingBoxNo($order->bike_id);
- if (!$box_no) return $this->errorNoValidation('找不到该车,或咱不能操作该车');
- (new BaseBikeControl($box_no))::closeLock();
- return $this->response->array([
- 'status' => 1
- ]);
- } catch (\Exception $exception) {
- return $this->errorNoValidation($exception->getMessage());
- }
- }
- /**
- * 临时停车时寻铃
- * @param Request $request
- * @param OrderRepository $orderRepository
- * @param BikeRepository $bikeRepository
- * User: Mead
- */
- public function retryBellLock(RetryBikeRequest $request, OrderRepository $orderRepository, BikeRepository $bikeRepository)
- {
- try {
- $order_no = $request->get('order_no');
- $bike_no = $request->get('bike_no');
- $order = $orderRepository->checkUserIsRetryOpenLock($order_no, $bike_no, $this->user->id);
- if (!$order) return $this->errorNoValidation('没有此订单');
- $box_no = $bikeRepository->byNoGetBoxNO($bike_no);
- $re = (new BaseBikeControl($box_no))::bellBike();
- return $this->response->array([
- 'is_ok' => $re
- ]);
- } catch (\Exception $exception) {
- return $this->errorNoValidation($exception->getMessage());
- }
- }
- /**
- * 系统自动关闭订单(replay端接口)
- * User: Mead
- */
- public function autoCloseOrder(RelayOrderAutoCloseRequest $request, OrderRepository $orderRepository, BikeRepository $bikeRepository, LocationLogRepository $locationLogRepository, AreaSettingRepository $areaSettingRepository)
- {
- try {
- $bike_no = $request->get('bike_no');
- $box_no = $request->get('box_no');
- $type = $request->get('type');
- $key = $request->get('key');
- if ($key !== config('auth.api_token')) {
- return $this->error('key不对');
- }
- $is_bike = $bikeRepository->byBoxNoAndBikeNoCheckRide($box_no, $bike_no);
- if (!$is_bike) {
- return $this->error('找不到该车');
- }
- $order = $orderRepository->byBikeNoGetRideOrder($bike_no);
- if (!$order) {
- return $this->error('找不到合适的订单');
- }
- //获取车的最后位置
- $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
- // 更新车的信息
- $bikeModel = $bikeRepository->byIdGetModel($order->bike_id);
- $bikeModel->is_riding = Bike::RIDING_NO;
- $bikeModel->last_use_bike_end_time = date('Y-m-d H:i:s');
- $bikeModel->save();
- (new BikeStatusInfoSyncHandler())->toBikeWaitRideStatus($bike_no, $location['lng'], $location['lat']);
- // 判断是否经常这样操作(未做)
- (new BaseBikeControl($box_no))::closeLock();
- // 记录日志信息
- OrderBikeOperate::log($order->id, OrderBikeOperate::TYPE_CLONE_BIKE, $order->bike_id, $order->user_id, $location['lat'], $location['lng'], OrderBikeOperate::IS_ADMIN_SYSTEM, "[系统自动:{$type}]");
- // 保存轨迹信息
- $setting = $areaSettingRepository->byAreaId($order->area_id);
- // 是否处于临时停车的状态
- if ((int)$order->status === Order::STATUS_PAUSE_BIKE) {
- $order->pause_bike_time_length += Carbon::now()->diffInMinutes(Carbon::parse($order->pause_bike_time));
- }
- $order->status = Order::STATUS_CLOSE_BIKE;
- $order->end_use_bike_time = now();
- $order->end_use_bike_location = [
- 'latitude' => $location['lat'],
- 'longitude' => $location['lng'],
- ];
- $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
- //计算用车时间
- $order->use_bike_time_length = ceil($second / 60);
- // 计算价格
- if (bccomp($setting->starting_price_time, $order->use_bike_time_length) >= 0) {
- // 起步价时间内只收起步价
- $time_money = $setting->starting_price;
- } else {
- $time_money = $setting->per_money * ceil(bcsub($order->use_bike_time_length, $setting->starting_price_time) / $setting->per_minute);
- $time_money = bcadd($time_money, $setting->starting_price, 2);
- }
- // $time_money = $setting->per_money * ceil($order->use_bike_time_length / $setting->per_minute);
- // 计算是否在免费分钟内
- if ($setting->is_minute_free == AreaSetting::FREE_MINUTE_OK && $setting->many_minute_free >= $order->use_bike_time_length) {
- if ($setting->minute_free_times == 0) {
- $time_money = 0;
- if ($order->preferential_type == 0) {
- $order->preferential_type = arr2str([Order::PREFERENTIAL_FREE_MINUTE], '-');
- } else {
- $arr = str2arr($order->preferential_type, '-');
- $order->preferential_type = arr2str(array_merge($arr, [Order::PREFERENTIAL_FREE_MINUTE]), '-');
- }
- } else {
- $key = sprintf(CacheMap::FREE_MINUTE_USER_ID, $order->user_id);
- app()->redis->sadd($key, $order->id);
- app()->redis->expireat($key, Carbon::tomorrow()->timestamp);
- if (app()->redis->scard($key) <= $setting->minute_free_times) {
- $time_money = 0;
- if ($order->preferential_type == 0) {
- $order->preferential_type = arr2str([Order::PREFERENTIAL_FREE_MINUTE], '-');
- } else {
- $arr = str2arr($order->preferential_type, '-');
- $order->preferential_type = arr2str(array_merge($arr, [Order::PREFERENTIAL_FREE_MINUTE]), '-');
- }
- }
- }
- }
- if ($time_money < 0) {
- $time_money = 0;
- }
- //计算骑行距离
- $order->use_bike_distance_length = bcdiv($location['mileage'], 1000, 2);
- // 判断车是否在停车的区域
- $order->dispatch_money = 0;
- if ($areaSettingRepository->byAreaIdGetIsWholeAreaHuanche($order->area_id) === AreaSetting::WHOLE_AREA_HUANCHE_NO) {
- $BikeHandler = new BikeHandler();
- $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id);
- $bikeModel->is_in_parking = Bike::IN_PARKING_YES;
- if (!$is_huanche['status']) {
- // 不在还车点
- $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
- $order->dispatch_money = $dispatch_money;
- $bikeModel->is_in_parking = Bike::IN_PARKING_NO;
- }
- } else {
- //全区域内可停
- $bikeModel->is_in_parking = Bike::IN_PARKING_YES;
- }
- $order->time_money = $time_money;
- $order->pause_money = 0;
- $order->preferential_money = 0;
- $order->order_money = bcadd($time_money, $order->dispatch_money, 2);
- $order->pay_money = $order->order_money;
- $order->pay_type = Order::PAY_STATUS_NO;
- $order->is_admin_settle_order = Order::IS_ADMIN_SETTLE_ORDER_SYSTEM;
- $order->save();
- $bikeModel->save();
- (new BaseBikeControl($box_no))::closeLock();
- return $this->success();
- } catch (HttpException $exception) {
- return $this->error($exception->getMessage());
- }
- }
- /**
- * 骑行订单车辆位置 orderBikePosition
- *
- * @param OrderBikePositionRequest $request
- * @return void
- * @author Fx
- *
- */
- public function orderBikePosition(OrderBikePositionRequest $request)
- {
- try {
- $bike_no = $request->get('bike_no');
- $position = LocationLogMongodb::getNewestLocationByBikeNo($bike_no);
- // Log::info($position);
- return $this->response->array($position);
- } catch (\Exception $exception) {
- return $this->errorException($exception->getMessage());
- }
- }
- /**
- *
- * Author: Mead
- */
- public function expectOrderMoney(BikeCloseOrderRequest $request, BikeRepository $bikeRepository, OrderRepository $orderRepository, AreaSettingRepository $areaSettingRepository, LocationLogRepository $locationLogRepository)
- {
- $bike_no = $request->get('bike_no');
- $order_no = $request->get('order_no');
- $lat = $request->get('lat');
- $lng = $request->get('lng');
- try {
- $order = $orderRepository->byNo($order_no);
- if (!$order) return $this->errorBadRequest('非法请求');
- $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
- if ($second < AreaSetting::CLOSE_BIKE_TIME) {
- Cache::put('ORDER:expectOrderMoney:' . $order->id, true, Carbon::now()->addSeconds(60));
- //小于60秒直接锁车
- return [
- 'dispatch_money' => 0,
- 'time_money' => 0,
- 'total_money' => 0
- ];
- }
- $user_id = $this->user['id'];
- $cache_key = "EXPECT_ORDER_MONEY_{$user_id}";
- if (Cache::has($cache_key)) {
- return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
- }
- Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
- $box_no = $bikeRepository->byNoGetBoxNO($order->bike_no);
- (new BaseBikeControl($box_no))::nowBikeLocation();
- $setting = $areaSettingRepository->byAreaId($order->area_id);
- $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
- if ($location['lat'] <= 0) {
- $location['lat'] = $lat;
- $location['lng'] = $lng;
- }
- //计算用车时间
- $use_bike_time_length = ceil($second / 60);
- // 计算价格
- if (bccomp($setting->starting_price_time, $use_bike_time_length) >= 0) {
- // 起步价时间内只收起步价
- $time_money = $setting->starting_price;
- } else {
- $time_money = $setting->per_money * ceil(bcsub($use_bike_time_length, $setting->starting_price_time) / $setting->per_minute);
- $time_money = bcadd($time_money, $setting->starting_price, 2);
- }
- // $time_money = floatval($setting->per_money * ceil($use_bike_time_length / $setting->per_minute));
- // //免费时长
- // if ($setting->is_minute_free == AreaSetting::FREE_MINUTE_OK && $setting->many_minute_free >= $use_bike_time_length) {
- // if ($setting->minute_free_times == 0) {
- // $time_money = 0;
- // } else {
- // $key = sprintf(CacheMap::FREE_MINUTE_USER_ID, $order->user_id);
- // if (app()->redis->scard($key) < $setting->minute_free_times) {
- // $time_money = 0;
- // }
- // }
- // }
- if ($time_money < 0) {
- $time_money = 0;
- }
- //计算骑行距离
- // $use_bike_distance_length = bcdiv($location['mileage'], 1000, 2);
- // $distance_money = 0;
- $BikeHandler = new BikeHandler();
- $dispatch_money = 0;
- // 判断是否在禁停区
- if (!is_null($location['lat']) && ($location['lat'] > 0)) {
- $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($location['lat'], $location['lng'], $order->area_id, $location['lat'], $location['lng']);
- if ($is_ban_stop_bike) {
- return $this->errorNoValidation('禁停区域内禁止停车!');
- // //
- // // 在禁停区 收取调度费
- // $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id, $location['lat'], $location['lng']);
- //
- //
- // $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
- }
- }
- //判断是否全区域内可停
- if ($areaSettingRepository->byAreaIdGetIsWholeAreaHuanche($order->area_id) === AreaSetting::WHOLE_AREA_HUANCHE_OK) {
- Cache::put('ORDER:expectOrderMoney:' . $order->id, true, Carbon::now()->addSeconds(60));
- return [
- 'dispatch_money' => $dispatch_money,
- 'time_money' => $time_money,
- 'total_money' => $time_money
- ];
- }
- // 判断是否在停车点
- $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id, $lat, $lng);
- if (!$is_huanche['status']) {
- (new BaseBikeControl($box_no))::nowBikeLocation();
- // 不在还车点
- $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
- if ($dispatch_money == 0) {
- Cache::put('ORDER:expectOrderMoney:' . $order->id, true, Carbon::now()->addSeconds(60));
- } else {
- Cache::put('ORDER:expectOrderMoney:' . $order->id, false, Carbon::now()->addSeconds(60));
- }
- return [
- 'dispatch_money' => $dispatch_money,
- 'time_money' => $time_money,
- 'total_money' => floatval(bcadd($dispatch_money, $time_money, 2))
- ];
- }
- Cache::put('ORDER:expectOrderMoney:' . $order->id, true, Carbon::now()->addSeconds(60));
- return [
- 'dispatch_money' => 0,
- 'time_money' => $time_money,
- 'total_money' => $time_money
- ];
- } catch (HttpException $exception) {
- return $this->errorNoValidation($exception->getMessage());
- }
- }
- }
|