RentBikeController.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Mead
  5. * Date: 2019/11/6
  6. * Time: 8:53 PM.
  7. */
  8. namespace App\Http\Controllers\V1;
  9. use App\Handlers\BaseBikeControl;
  10. use App\Handlers\BikeHandler;
  11. use App\Handlers\BikeStatusInfoSyncHandler;
  12. use App\Handlers\ConvertHandler;
  13. use App\Http\Requests\RetryBikeRequest;
  14. use App\Jobs\CloseRentOrderJob;
  15. use App\Maps\CacheMap;
  16. use App\Models\Area;
  17. use App\Models\AreaSetting;
  18. use App\Models\Bike;
  19. use App\Models\RentOrder;
  20. use App\Models\RentOrderBikeOperate;
  21. use App\Models\User;
  22. use App\Models\WalletLog;
  23. use App\Repositories\AreaRepository;
  24. use App\Repositories\AreaSettingRepository;
  25. use App\Repositories\BikeRepository;
  26. use App\Repositories\LocationLogRepository;
  27. use App\Repositories\OrderRepository;
  28. use App\Repositories\PunishmentOrderRepository;
  29. use App\Repositories\RentOrderBikeOperateRepository;
  30. use App\Repositories\RentOrderRepository;
  31. use App\Repositories\UserRepository;
  32. use App\Transformers\RentOrderTransformer;
  33. use App\Transformers\RentUseOrderTransformer;
  34. use Carbon\Carbon;
  35. use Dingo\Api\Http\Request;
  36. use Illuminate\Support\Facades\Log;
  37. use function EasyWeChat\Kernel\Support\generate_sign;
  38. use Illuminate\Support\Facades\Cache;
  39. use Illuminate\Support\Facades\DB;
  40. use Illuminate\Support\Facades\Redis;
  41. use Symfony\Component\HttpKernel\Exception\HttpException;
  42. /**
  43. * 日租车模块
  44. * Class RentBikeController
  45. * @package App\Http\Controllers\V1
  46. */
  47. class RentBikeController extends BaseController
  48. {
  49. /**
  50. * 租车下单
  51. * User: Mead.
  52. */
  53. public function storeOrder(Request $request, BikeRepository $bikeRepository, RentOrderRepository $rentOrderRepository, OrderRepository $orderRepository, AreaSettingRepository $areaSettingRepository, PunishmentOrderRepository $punishmentOrderRepository, UserRepository $userRepository)
  54. {
  55. try {
  56. $type = $request->get('type');
  57. $bike_no = $request->get('bike_no');
  58. $area_id = $request->get('area_id');
  59. $lat = $request->get('lat');
  60. $lng = $request->get('lng');
  61. $cache_key = "OPEN_RENT_BIKE_ORDER_{$bike_no}";
  62. if (Cache::has($cache_key)) {
  63. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  64. }
  65. Cache::put($cache_key, 1, Carbon::now()->addSeconds(5));
  66. $bike = $bikeRepository->byNoIsCanRentBikeGetModel($bike_no);
  67. if (!$bike) {
  68. return $this->errorNoValidation('该车暂不能用');
  69. }
  70. //以车的区域为主
  71. if ($bike->put_area_id !== $area_id) {
  72. $area_id = $bike->put_area_id;
  73. }
  74. $setting = $areaSettingRepository->byAreaId($area_id);
  75. $user = $this->user;
  76. // 判断区域是否需要缴纳押金
  77. if($setting['is_deposit'] == AreaSetting::DEPOSIT_OK) {
  78. // 判断用户押金,授权,认证,手机号状态是否正常
  79. if (User::DEPOSIT_NO === (int)$user->is_deposit) {
  80. return $this->errorNoValidation('请您先交纳押金');
  81. }
  82. }
  83. // if ((int)$user->deposit_type === User::DEPOSIT_CARD && (int)$user->is_deposit === User::DEPOSIT_OK) {
  84. // // 押金类型为免押金卡 判断是否过期
  85. // if (!$userRepository->isDepositCardExpired($user->id)) {
  86. // return $this->errorNoValidation('免押金卡已到期,请您先交纳押金');
  87. // }
  88. // }
  89. if (User::BIND_MOBILE_NO === (int)$user->is_bind_mobile) {
  90. return $this->errorNoValidation('请先绑定您的手机号');
  91. }
  92. if (User::CARD_NO === (int)$user->is_card_certified) {
  93. return $this->errorNoValidation('请您先完善实名认证');
  94. }
  95. if (User::RIDE_BIKE_AGE_NO === (int)$user->is_match_ride_age) {
  96. return $this->errorNoValidation('未成年人禁止骑车');
  97. }
  98. if (!$setting->is_open_day_rent) {
  99. return $this->errorNoValidation('该区域租车暂不开放,敬请期待!');
  100. }
  101. $punish = $punishmentOrderRepository->checkNoPayModel($user->id);
  102. if (!$punish) return $this->errorNoValidation('您有罚单未支付,请先处理');
  103. // 判断用户是否有为支付的订单
  104. if ($orderRepository->byUserIdCheckIsExistRideOrder($user->id)) {
  105. return $this->errorNoValidation('您有未完成的订单,请先处理');
  106. }
  107. if ($rentOrderRepository->byUserIdCheckIsExistRideOrder($user->id)) {
  108. return $this->errorNoValidation('您有未完成的租车订单,请先处理');
  109. }
  110. // 判断用户是否在车的距离范围内
  111. $options = ['SORT' => 'ASC'];
  112. $redis = Redis::connection();
  113. $nearby_bikes = $redis->georadius(Bike::REDIS_BIKE_LOCATION_TAG, $lng, $lat, 1, 'km', $options);
  114. if (!in_array($bike->bike_no, $nearby_bikes)) {
  115. return $this->errorNoValidation('小主,咱俩有点远!');
  116. }
  117. $user_id = $this->user->id;
  118. $cache_key = "RIDE_RENT_ORDER_{$user_id}";
  119. if (Cache::has($cache_key)) {
  120. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  121. }
  122. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  123. //不同类型处理价格(暂不用)
  124. // 下单
  125. $rent_money = $setting->day_rent_money;
  126. $users = User::find($user['id']);
  127. $settingConfig = [
  128. 'rent_money' => $setting->day_rent_money,
  129. 'rent_time' => $setting->day_rent_hours,
  130. 'over_rent_time_money' => $setting->per_hours_day_rent_timeout_money,
  131. 'over_rent_time_max_money' => $setting->day_rent_capping_money,
  132. ];
  133. $data = [
  134. 'user_id' => $user['id'],
  135. 'no' => RentOrder::makeNo(),
  136. 'type' => RentOrder::TYPE_DAY_RENT,
  137. 'bike_no' => $bike_no,
  138. 'bike_id' => $bike->id,
  139. 'area_id' => $area_id,
  140. 'phone_detail' => $users->userPhoneDetail->detail ?? '',
  141. 'start_use_bike_location' => [
  142. 'latitude' => $lat,
  143. 'longitude' => $lng,
  144. ],
  145. 'rent_money' => $rent_money,
  146. 'rent_preferential_money' => 0.00,
  147. 'rent_total_money' => $rent_money,
  148. 'status' => RentOrder::STATUS_WAIT_PAY_RENT_MONEY,
  149. 'setting' => $settingConfig,
  150. ];
  151. $order = RentOrder::create($data);
  152. // $this->dispatch(new CloseRentOrderJob($order, Carbon::now()->addMinutes(10)));
  153. // 更新用户的区域id
  154. if (!$user->register_area_id) {
  155. $user->register_area_id = $area_id;
  156. $user->save();
  157. }
  158. $order->status = RentOrder::STATUS_RENT_BIKE;
  159. $order->start_use_bike_time = now();
  160. $order->return_end_bike_time = Carbon::now()->addHours($settingConfig['rent_time'])->toDateTimeString();
  161. $order->save();
  162. $bike->is_rent = Bike::RENT_YES;
  163. $bike->is_riding = Bike::RIDING_YES;
  164. $bike->save();
  165. //同步redis
  166. (new BikeStatusInfoSyncHandler())->toBikeRideStatus(BikeStatusInfoSyncHandler::ROLE_USER, $bike->bike_no, [
  167. 'id' => $order->id,
  168. 'bike_id' => $order->bike_id,
  169. 'area_id' => $order->area_id,
  170. 'is_rent' => 1,
  171. ]);
  172. $params['no'] = $order->no;
  173. return $this->response->array($params);
  174. } catch (\Exception $exception) {
  175. return $this->errorNoValidation($exception->getMessage());
  176. }
  177. }
  178. public function useOrder(Request $request, RentOrderRepository $rentOrderRepository)
  179. {
  180. try {
  181. $no = $request->get('no');
  182. $order = $rentOrderRepository->byNo($no);
  183. return $this->response->item($order, RentUseOrderTransformer::class);
  184. } catch (\Exception $exception) {
  185. }
  186. }
  187. /**
  188. * @param Request $request
  189. * @param RentOrderRepository $rentOrderRepository
  190. *
  191. * @return \Dingo\Api\Http\Response
  192. * User: Mead
  193. */
  194. public function show(Request $request, RentOrderRepository $rentOrderRepository)
  195. {
  196. try {
  197. $no = $request->get('no');
  198. $order = $rentOrderRepository->byNo($no);
  199. return $this->response->item($order, new RentOrderTransformer());
  200. } catch (\Exception $exception) {
  201. }
  202. }
  203. /**
  204. * 结束租车
  205. * User: Mead.
  206. */
  207. public function closeOrder(Request $request, RentOrderRepository $rentOrderRepository, BikeRepository $bikeRepository, LocationLogRepository $locationLogRepository, AreaSettingRepository $areaSettingRepository)
  208. {
  209. try {
  210. $bike_no = $request->get('bike_no');
  211. $order_no = $request->get('order_no');
  212. $lat = $request->get('lat');
  213. $lng = $request->get('lng');
  214. $order = $rentOrderRepository->byNoGetRideOrder($order_no);
  215. if (!$order) {
  216. return $this->errorNoValidation('订单不存在或订单已结算');
  217. }
  218. if (Bike::RIDING_YES === (int)$order->bike_is_riding) {
  219. return $this->errorNoValidation('请先关锁再还车');
  220. }
  221. if ($rentOrderRepository->checkUserMoreCloseOrder($this->user->id)) {
  222. return $this->errorNoValidation('您今天太频繁操作车辆');
  223. }
  224. $user_id = $this->user->id;
  225. $cache_key = "RIDE_CLOSE_RENT_ORDER_{$user_id}";
  226. if (Cache::has($cache_key)) {
  227. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  228. }
  229. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  230. //获取车的最后位置
  231. $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
  232. if ($location['lat'] <= 0) {
  233. $location['lat'] = $order->end_use_bike_location['latitude'];
  234. $location['lng'] = $order->end_use_bike_location['longitude'];
  235. if ($location['lat'] <= 0) {
  236. $location['lat'] = $lat;
  237. $location['lng'] = $lng;
  238. }
  239. }
  240. // 更新车的信息
  241. $bikeModel = $bikeRepository->byIdGetModel($order->bike_id);
  242. $bikeModel->is_riding = Bike::RIDING_NO;
  243. $bikeModel->is_rent = Bike::RENT_NO;
  244. $bikeModel->save();
  245. //更新redis
  246. (new BikeStatusInfoSyncHandler())->toBikeWaitRideStatus($order->bike_no, $location['lng'], $location['lat']);
  247. // 判断是否经常这样操作(未做)
  248. $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
  249. if ($second <= AreaSetting::CLOSE_BIKE_TIME) {
  250. // 关闭订单
  251. $order->status = RentOrder::STATUS_CLOSE_ORDER;
  252. $order->end_use_bike_location = [
  253. 'latitude' => $lat,
  254. 'longitude' => $lng,
  255. ];
  256. $order->end_use_bike_time = now();
  257. $order->rent_money = 0;
  258. $order->save();
  259. //退钱
  260. // 记录临时关锁
  261. return $this->response->item($order, RentOrderTransformer::class);
  262. }
  263. //检查是否在禁停区
  264. $BikeHandler = new BikeHandler();
  265. $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($location['lat'], $location['lng'], $order->area_id, $lat, $lng);
  266. if ($is_ban_stop_bike) {
  267. return $this->errorNoValidation('禁停区域内禁止停车!');
  268. }
  269. // 结束订单
  270. $setting = $order->setting;
  271. $money = 0.00;
  272. $over_hours = 0;
  273. //是否需要收取超出费用
  274. $is_over_time = (strtotime($order->return_end_bike_time) < time());
  275. if ($is_over_time) {
  276. //超出时间
  277. $over_hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->return_end_bike_time)) / 60);
  278. $hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->start_use_bike_time)) / 60);
  279. if ($hours > 24) {
  280. //超过1天
  281. $day = ceil($hours / 24);
  282. $end_hours = $hours % 24;
  283. //日封顶租金*天
  284. $money = bcmul($setting['over_rent_time_max_money'], ($day - 1), 2);
  285. // $money = bcadd($money, $setting['rent_money'], 2);
  286. if ($end_hours > $setting['rent_time']) {
  287. // 超过一天 又超过8小时
  288. // (超时费 + 日封顶租金*天)
  289. $money = bcadd(bcmul(($end_hours - $setting['rent_time']), $setting['over_rent_time_money'], 2), $money, 2);
  290. }
  291. } else {
  292. // 不超过1天 但是超过8小时
  293. $money = bcmul($over_hours, $setting['over_rent_time_money'], 2);
  294. // (超时费 + 基础租金) 是否大于日封顶租金
  295. $total_money = bcadd($money, $setting['rent_money'], 2);
  296. if ($total_money > $setting['over_rent_time_max_money']) {
  297. $money = bcsub($setting['over_rent_time_max_money'], $setting['rent_money'], 2);
  298. }
  299. }
  300. }
  301. //计算骑行距离
  302. $order->use_bike_distance_length = bcdiv($location['mileage'], 1000, 2);
  303. // 日租结算
  304. $order->time_money = $money;
  305. $order->distance_money = 0.00;
  306. $order->preferential_money = 0.00;
  307. $order->over_hours = $over_hours;
  308. // 租金 + 超时费
  309. $order->total_money = bcadd($money, $order->rent_money, 2);
  310. $order->pay_money = $order->total_money;
  311. //判断是否收取调度费
  312. if ($order->dispatch_money > 0) {
  313. $order->total_money = bcadd($order->total_money, $order->dispatch_money, 2);
  314. }
  315. if ($order->total_money > 0) {
  316. $order->status = RentOrder::STATUS_CLOSE_RENT_BIKE;
  317. } else {
  318. $order->status = RentOrder::STATUS_COMPLETE_ORDER;
  319. }
  320. //计算用车时间 (分)
  321. $order->use_bike_time_length = ceil($second / 60);
  322. // 车辆最后位置 (防止定位失败的情况)
  323. if (empty($order->end_use_bike_location)) {
  324. $order->end_use_bike_location = [
  325. 'latitude' => $lat,
  326. 'longitude' => $lng,
  327. ];
  328. }
  329. $order->end_use_bike_time = Carbon::now();
  330. $order->order_total_money = $order->total_money;
  331. $order->save();
  332. // 删除redis订单
  333. if (RentOrder::STATUS_COMPLETE_ORDER === (int)$order->status) {
  334. (new BikeStatusInfoSyncHandler())->toBikeWaitRideStatus($order->bike_no, $location['lng'], $location['lat']);
  335. }
  336. return $this->response->item($order, RentOrderTransformer::class);
  337. } catch (HttpException $exception) {
  338. return $this->errorNoValidation($exception->getMessage(), $exception->getStatusCode());
  339. }
  340. }
  341. public function payShow(Request $request, RentOrderRepository $rentOrderRepository, RentOrderBikeOperateRepository $rentOrderBikeOperateRepository)
  342. {
  343. try {
  344. $order_no = $request->get('order_no');
  345. $order = $rentOrderRepository->byNoAndUserId($order_no, $this->user->id);
  346. if (!$order) {
  347. return $this->errorNoValidation('订单不存在!');
  348. }
  349. // 检查用户余额是否够
  350. $is_user_wallet = true;
  351. if ($order->pay_money > $this->user->wallet_money) {
  352. // 余额不够
  353. $is_user_wallet = false;
  354. }
  355. if (bccomp($order->total_money, 0) === 0) {
  356. $order->pay_type = RentOrder::PAY_STATUS_OK;
  357. $order->status = RentOrder::STATUS_CLOSE_ORDER;
  358. }
  359. $order->save();
  360. // 检查是否系统自动锁车
  361. $is_system_off_lock = $rentOrderBikeOperateRepository->checkLowPowerOffLock($order->id);
  362. $is_coupon = false;
  363. $userCoupons = [];
  364. $ridingCard = [];
  365. return $this->response->array([
  366. 'order' => $order->append(['use_bike_time_length_text', 'use_bike_distance_length_text', 'end_use_bike_time_timestamp'])->toArray(),
  367. 'orders' => [
  368. 'id' => $order->id,
  369. 'no' => $order->no,
  370. 'bike_no' => $order->bike_no,
  371. 'use_bike_time_length_text' => $order->use_bike_time_length_text,
  372. 'use_bike_distance_length_text' => $order->use_bike_distance_length_text,
  373. 'end_use_bike_time_timestamp' => $order->end_use_bike_time_timestamp,
  374. 'pay_status' => $order->pay_status,
  375. 'pay_money' => $order->pay_money,
  376. 'time_money' => $order->time_money, // 时长费
  377. 'rent_money' => $order->rent_money, // 租费
  378. 'dispatch_money' => $order->dispatch_money, // 调度费
  379. 'distance_money' => $order->distance_money, // 里程费用
  380. 'total_money' => $order->total_money,// 加调度费的总金额
  381. 'order_total_money' => bcadd($order->rent_money, $order->time_money, 2), // 不加调度费的总金额
  382. 'order_wait_pay_money' => empty($userCoupons) ? $order->total_money : $userCoupons['order_wait_pay_money'], // 总待支付
  383. 'total_preferential_money' => empty($userCoupons) ? $order->preferential_money : $userCoupons['total_preferential_money'], // 总优惠
  384. ],
  385. 'wallet_pay_status' => $is_user_wallet,
  386. 'wallet_money' => $this->user->wallet_money,
  387. 'user_coupon' => [
  388. 'is_coupon' => $is_coupon,
  389. 'coupon_preferential_money' => empty($userCoupons) ? '0.00' : $userCoupons['coupon_preferential_money'], // 优惠券优惠的金额
  390. 'coupon_user_bags_id' => empty($userCoupons) ? 0 : $userCoupons['id'],
  391. ],
  392. 'user_card' => [
  393. 'is_card' => empty($ridingCard) ? false : true,
  394. 'card' => $ridingCard,
  395. 'card_preferential_money' => $order->preferential_money, // 没支付之前优惠金额就是 骑行卡优惠的金额
  396. ],
  397. 'system_off_lock' => [
  398. 'is_system_off_lock' => empty($is_system_off_lock) ? false : true,
  399. 'system_off_lock_text' => '电量过低,系统自动还车,敬请谅解,如有疑问请致电客服'
  400. ],
  401. ]);
  402. } catch (\Exception $exception) {
  403. return $this->errorException($exception->getMessage());
  404. }
  405. }
  406. public function pay(Request $request, RentOrderRepository $rentOrderRepository)
  407. {
  408. try {
  409. $pay_type = $request->get('pay_type');
  410. $order_no = $request->get('order_no');
  411. $order = $rentOrderRepository->byNo($order_no);
  412. if (!$order) {
  413. return $this->errorBadRequest('订单不存在');
  414. }
  415. if (RentOrder::STATUS_COMPLETE_ORDER === (int)$order->status) {
  416. return $this->errorNoValidation('订单已完成');
  417. }
  418. if (RentOrder::STATUS_CLOSE_ORDER === (int)$order->status) {
  419. return $this->errorNoValidation('订单已关闭');
  420. }
  421. if (RentOrder::PAY_STATUS_OK === (int)$order->pay_status) {
  422. return $this->errorNoValidation('订单已支付');
  423. }
  424. if (RentOrder::STATUS_RENT_BIKE === (int)$order->status) {
  425. return $this->errorNoValidation('请先结束租车订单,再支付');
  426. }
  427. $user = $this->user;
  428. if ($order->user_id !== $user->id) {
  429. return $this->errorNoValidation('非法操作');
  430. }
  431. $response = '';
  432. $user_id = $user['id'];
  433. $cache_key = "PAY_RENT_ORDER_{$user_id}";
  434. if (Cache::has($cache_key)) {
  435. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  436. }
  437. Cache::put($cache_key, 1, Carbon::now()->addSeconds(5));
  438. switch ($pay_type) {
  439. case RentOrder::PAY_TYPE_ACCOUNT:
  440. //余额支付
  441. if (bccomp($order->total_money, $this->user->wallet_money) === 1) {
  442. // 余额不够
  443. return $this->errorNoValidation('用户余额不够');
  444. }
  445. DB::transaction(function () use ($order, $user) {
  446. //添加钱包记录
  447. WalletLog::log(WalletLog::OPERATE_TYPE_SUB, $order->total_money, $user->id, WalletLog::TYPE_SUB_WALLET_RENT_ORDER_MONEY, $order->area_id, $order->id, RentOrder::class);
  448. //修改订单记录
  449. $order->pay_status = RentOrder::PAY_STATUS_OK;
  450. $order->pay_money = $order->total_money;
  451. $order->pay_time = now();
  452. $order->pay_type = RentOrder::PAY_TYPE_ACCOUNT;
  453. $order->status = RentOrder::STATUS_COMPLETE_ORDER;
  454. $order->order_total_money = $order->total_money;
  455. $order->save();
  456. });
  457. $response = [
  458. 'pay_order_status' => true,
  459. ];
  460. break;
  461. case RentOrder::PAY_TYPE_WECHAT:
  462. //微信支付
  463. $payment = app('wechat.payment'); // 微信支付
  464. $username = $user->truename;
  465. $auth = $user->auth;
  466. $order->over_no = RentOrder::makeOverNo();
  467. $order->save();
  468. $result = $payment->order->unify([
  469. 'body' => "用户支付日租车租车费用-" . config('app.name', '未来bike'),
  470. 'out_trade_no' => $order->no,
  471. 'trade_type' => 'JSAPI', // 必须为JSAPI
  472. 'openid' => $auth['credential'], // 这里的openid为付款人的openid
  473. 'total_fee' => wechat_fee($order->total_money), // 总价
  474. 'attach' => makeNoTag(RentOrder::NO_TAG),
  475. 'notify_url' => config('app.url') . '/api/payments/wechat-rent-notify',
  476. ]);
  477. if ($result['return_code'] === 'FAIL') return $this->errorNoValidation('下单失败');
  478. // 如果成功生成统一下单的订单,那么进行二次签名
  479. if ($result['result_code'] === 'FAIL') {
  480. //判断是否重复下单
  481. if ($result['err_code'] === 'INVALID_REQUEST') {
  482. $order->no = RentOrder::makeNo();
  483. $order->save();
  484. $result = $payment->order->unify([
  485. 'body' => "用户支付日租车租车费用-" . config('app.name', '未来bike'),
  486. 'out_trade_no' => $order->no,
  487. 'trade_type' => 'JSAPI', // 必须为JSAPI
  488. 'openid' => $auth['credential'], // 这里的openid为付款人的openid
  489. 'total_fee' => wechat_fee($order->total_money), // 总价
  490. 'attach' => makeNoTag(RentOrder::NO_TAG),
  491. 'notify_url' => config('app.url') . '/api/payments/wechat-rent-notify',
  492. ]);
  493. } elseif ($result['err_code'] === 'ORDERPAID') {
  494. $order->pay_status = RentOrder::PAY_STATUS_OK;
  495. $order->pay_time = now();
  496. $order->pay_type = RentOrder::PAY_TYPE_WECHAT;
  497. $order->pay_money = $order->total_money;
  498. $order->order_total_money = $order->pay_money;
  499. $order->status = RentOrder::STATUS_COMPLETE_ORDER;
  500. $order->save();
  501. $order->pay_rent_over_order_callback();
  502. return $this->errorNoValidation('订单已支付,请勿重复支付!');
  503. } else {
  504. return $this->errorNoValidation('下单失败');
  505. }
  506. }
  507. if ('SUCCESS' === $result['return_code'] && 'SUCCESS' === $result['result_code']) {
  508. // 二次签名的参数必须与下面相同
  509. $params = [
  510. 'appId' => $auth['identifier'],
  511. 'timeStamp' => time(),
  512. 'nonceStr' => $result['nonce_str'],
  513. 'package' => 'prepay_id=' . $result['prepay_id'],
  514. 'signType' => 'MD5',
  515. ];
  516. // config('wechat.payment.default.key')为商户的key
  517. $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
  518. $response = $params;
  519. } else {
  520. return $this->errorNoValidation('下单失败');
  521. }
  522. break;
  523. default:
  524. return $this->errorBadRequest('支付类型不对');
  525. break;
  526. }
  527. $response['order_no'] = $order->no;
  528. return $this->response->array($response);
  529. } catch (\Exception $exception) {
  530. return $this->errorNoValidation($exception->getMessage());
  531. }
  532. }
  533. /**
  534. * 开锁
  535. * User: Mead.
  536. */
  537. public function openBike(Request $request, RentOrderRepository $rentOrderRepository, BikeRepository $bikeRepository)
  538. {
  539. try {
  540. $order_no = $request->get('order_no');
  541. $lat = $request->get('lat');
  542. $lng = $request->get('lng');
  543. $order = $rentOrderRepository->byNoGetRideOrder($order_no);
  544. if (!$order) {
  545. return $this->errorNoValidation('订单不存在');
  546. }
  547. if ($order->user_id !== $this->user->id) {
  548. return $this->errorNoValidation('非法操作');
  549. }
  550. $user_id = $this->user['id'];
  551. $cache_key = "RENT_ORDER_OPEN_BIKE_{$user_id}";
  552. if (Cache::has($cache_key)) {
  553. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  554. }
  555. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  556. $box_no = $bikeRepository->byIdGetBoxNo($order->bike_id);
  557. (new BaseBikeControl($box_no))::openLock();
  558. (new BikeStatusInfoSyncHandler())->toBikeRentRideStatus($order->bike_no);
  559. // 记录日志信息
  560. RentOrderBikeOperate::log($order->id, RentOrderBikeOperate::TYPE_OPEN_BIKE, $order->bike_id, $this->user->id, $lat, $lng);
  561. $order->bike_is_riding = Bike::RIDING_YES;
  562. $order->save();
  563. //增加次数
  564. Cache::remember('increment_use_bike', 1, function () use ($order) {
  565. return RentOrder::where('id', $order->id)->increment('use_bike_count');
  566. });
  567. return $this->success();
  568. } catch (\Exception $exception) {
  569. return $this->errorNoValidation($exception->getMessage());
  570. }
  571. }
  572. /**
  573. * 关锁
  574. * User: Mead.
  575. */
  576. public function closeBike(Request $request, RentOrderRepository $rentOrderRepository, BikeRepository $bikeRepository, LocationLogRepository $locationLogRepository)
  577. {
  578. try {
  579. $order_no = $request->get('order_no');
  580. $lat = $request->get('lat');
  581. $lng = $request->get('lng');
  582. $order = $rentOrderRepository->byNoGetRideOrder($order_no);
  583. if (!$order) {
  584. return $this->errorNoValidation('订单不存在');
  585. }
  586. if ($order->user_id !== $this->user->id) {
  587. return $this->errorNoValidation('非法操作');
  588. }
  589. $user_id = $this->user['id'];
  590. $cache_key = "RENT_ORDER_CLOSE_BIKE_{$user_id}";
  591. if (Cache::has($cache_key)) {
  592. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  593. }
  594. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  595. $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
  596. if ($location['lat'] <= 0) {
  597. $location['lat'] = $lat;
  598. $location['lng'] = $lng;
  599. }
  600. $order->end_use_bike_location = [
  601. 'latitude' => $location['lat'],
  602. 'longitude' => $location['lng'],
  603. ];
  604. $order->bike_is_riding = Bike::RIDING_NO;
  605. $order->save();
  606. //最后骑行时间
  607. $bikeModel = $bikeRepository->byIdGetModel($order->bike_id);
  608. $bikeModel->last_use_bike_end_time = date('Y-m-d H:i:s');
  609. $bikeModel->save();
  610. $box_no = $bikeRepository->byIdGetBoxNo($order->bike_id);
  611. (new BaseBikeControl($box_no))::closeLock();
  612. // 记录日志信息
  613. RentOrderBikeOperate::log($order->id, RentOrderBikeOperate::TYPE_CLONE_BIKE, $order->bike_id, $this->user->id, $lat, $lng);
  614. (new BikeStatusInfoSyncHandler())->toBikeRentWaitRideStatus($order->bike_no);
  615. return $this->success();
  616. } catch (\Exception $exception) {
  617. return $this->errorNoValidation($exception->getMessage());
  618. }
  619. }
  620. /**
  621. * 日租订单列表页.
  622. *
  623. * @param Request $request
  624. * @param RentOrder $rentOrder
  625. * User: Mead
  626. */
  627. public function orders(Request $request, RentOrder $rentOrder)
  628. {
  629. try {
  630. $query = $rentOrder->query();
  631. $query->where('pay_status', RentOrder::PAY_STATUS_OK);
  632. if ($year = $request->get('year', date('Y'))) {
  633. $query->whereYear('created_at', $year);
  634. }
  635. if ($month = $request->get('month', date('m'))) {
  636. $query->whereMonth('created_at', $month);
  637. }
  638. $orders = $query->where('user_id', $this->user->id)->orderBy('id', 'desc')->paginate();
  639. $orders->appends($request->only(['year', 'month']))->withPath(config('app.url') . '/api/rent/orders');
  640. return $this->response->paginator($orders, RentOrderTransformer::class);
  641. } catch (\Exception $exception) {
  642. return $this->errorException($exception->getMessage());
  643. }
  644. }
  645. /**
  646. * 检查是否在还车点
  647. * User: Mead.
  648. */
  649. public function checkBikeIsInStopParking(Request $request, BikeRepository $bikeRepository, RentOrderRepository $rentOrderRepository, AreaSettingRepository $areaSettingRepository, LocationLogRepository $locationLogRepository, AreaRepository $areaRepository)
  650. {
  651. $bike_no = $request->get('bike_no');
  652. $order_no = $request->get('order_no');
  653. $user_lat = $request->get('lat');
  654. $user_lng = $request->get('lng');
  655. try {
  656. $order = $rentOrderRepository->byNo($order_no);
  657. if (!$order) {
  658. return $this->errorBadRequest('非法请求');
  659. }
  660. $user_id = $this->user['id'];
  661. $cache_key = "RENT_ORDER_CHECK_BIKE_IS_PARK_{$user_id}";
  662. if (Cache::has($cache_key)) {
  663. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  664. }
  665. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  666. $box_no = $bikeRepository->byNoGetBoxNO($order->bike_no);
  667. (new BaseBikeControl($box_no))::nowBikeLocation();
  668. $setting = $areaSettingRepository->byAreaId($order->area_id);
  669. $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
  670. if ($location['lat'] <= 0) {
  671. $location['lat'] = $order->end_use_bike_location['latitude'];
  672. $location['lng'] = $order->end_use_bike_location['longitude'];
  673. if ($location['lat'] <= 0) {
  674. $location['lat'] = $user_lat;
  675. $location['lng'] = $user_lng;
  676. }
  677. }
  678. //检查是否在骑行区域
  679. $area = $areaRepository->byIdGetModelRedis($order->area_id);
  680. if (!$area) {
  681. $area = Area::where('id', $order->area_id)->first();
  682. }
  683. $is_out_area = $this->isOutArea($location['lat'], $location['lng'], $area);
  684. if (!$is_out_area) {
  685. return $this->errorNoValidation('超出骑行区域,暂不能还车');
  686. }
  687. //检查是否在禁停区
  688. $BikeHandler = new BikeHandler();
  689. $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($location['lat'], $location['lng'], $order->area_id, $user_lat, $user_lng);
  690. if ($is_ban_stop_bike) {
  691. return $this->errorNoValidation('禁停区域内禁止停车!');
  692. }
  693. // //运动中不能锁车
  694. // if ($location['speed']) {
  695. // (new BaseBikeControl($box_no))::nowBikeLocation();
  696. //
  697. // return $this->errorNoValidation('运动中不能关锁', 450);
  698. // }
  699. //判断是否全区域内可停
  700. if ($areaSettingRepository->byAreaIdGetIsWholeAreaHuanche($order->area_id) === AreaSetting::WHOLE_AREA_HUANCHE_OK) {
  701. return [
  702. 'is_dispatch' => true,
  703. 'is_stop_bike' => true,
  704. 'dispatch_money' => 0,
  705. ];
  706. }
  707. // 判断是否在停车点
  708. $BikeHandler = new BikeHandler();
  709. $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id, $user_lat, $user_lng);
  710. if (!$is_huanche['status']) {
  711. // 不在还车点
  712. $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
  713. RentOrder::where('id', $order->id)->update([
  714. 'dispatch_money' => $dispatch_money,
  715. ]);
  716. return [
  717. 'is_dispatch' => false,
  718. 'is_stop_bike' => false,
  719. 'dispatch_money' => $dispatch_money,
  720. ];
  721. }
  722. return [
  723. 'is_dispatch' => true,
  724. 'is_stop_bike' => true,
  725. 'dispatch_money' => 0,
  726. ];
  727. } catch (HttpException $exception) {
  728. return $this->errorNoValidation($exception->getMessage(), $exception->getStatusCode());
  729. }
  730. }
  731. /**
  732. * 判断是否在骑行区.
  733. *
  734. * @param $lat
  735. * @param $lng
  736. * @param $box_no
  737. * User: Mead
  738. */
  739. private function isOutArea($lat, $lng, $area)
  740. {
  741. try {
  742. $location = [
  743. 'latitude' => $lat,
  744. 'longitude' => $lng,
  745. ];
  746. $fences = $area['area_fence'];
  747. $centre = $area['area_centre'];
  748. $radius = $area['area_radius'];
  749. // 判断是否在骑行区域
  750. $ConvertHandler = (new ConvertHandler());
  751. $is_out_area = $ConvertHandler->is_point_in_polygon($location, $fences);
  752. return $is_out_area;
  753. } catch (\Exception $exception) {
  754. return $this->errorNoValidation($exception->getMessage());
  755. }
  756. }
  757. /**
  758. * 寻铃
  759. * @param Request $request
  760. * @param OrderRepository $orderRepository
  761. * @param BikeRepository $bikeRepository
  762. * User: Fx
  763. */
  764. public function retryBell(RetryBikeRequest $request, RentOrderRepository $rentOrderRepository, BikeRepository $bikeRepository)
  765. {
  766. try {
  767. $order_no = $request->get('order_no');
  768. $bike_no = $request->get('bike_no');
  769. $order = $rentOrderRepository->checkUserIsRetryOpenLock($order_no, $bike_no, $this->user->id);
  770. if (!$order) return $this->errorNoValidation('没有此订单');
  771. $box_no = $bikeRepository->byNoGetBoxNO($bike_no);
  772. $re = (new BaseBikeControl($box_no))::bellBike();
  773. return $this->response->array([
  774. 'is_ok' => $re
  775. ]);
  776. } catch (\Exception $exception) {
  777. return $this->errorNoValidation($exception->getMessage());
  778. }
  779. }
  780. /**
  781. * 检查是否可以结束订单
  782. * @param Request $request
  783. * @param BikeRepository $bikeRepository
  784. * @param RentOrderRepository $rentOrderRepository
  785. * @param LocationLogRepository $locationLogRepository
  786. * @param AreaRepository $areaRepository
  787. * @return array|void
  788. * Author: Mead
  789. */
  790. public function checkBikeIsRidingArea(Request $request, BikeRepository $bikeRepository, RentOrderRepository $rentOrderRepository, LocationLogRepository $locationLogRepository, AreaRepository $areaRepository)
  791. {
  792. $bike_no = $request->get('bike_no');
  793. $order_no = $request->get('order_no');
  794. $user_lat = $request->get('lat');
  795. $user_lng = $request->get('lng');
  796. try {
  797. $order = $rentOrderRepository->byNo($order_no);
  798. if (!$order) {
  799. return $this->errorBadRequest('非法请求');
  800. }
  801. $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
  802. if ($second < AreaSetting::CLOSE_BIKE_TIME) {
  803. //小于60秒直接锁车
  804. return [
  805. 'is_close_order' => true,
  806. ];
  807. }
  808. $user_id = $this->user['id'];
  809. $cache_key = "RENT_ORDER_CHECK_BIKE_IS_RIDING_PARK_{$user_id}";
  810. if (Cache::has($cache_key)) {
  811. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  812. }
  813. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  814. $box_no = $bikeRepository->byNoGetBoxNO($order->bike_no);
  815. (new BaseBikeControl($box_no))::nowBikeLocation();
  816. $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
  817. if ($location['lat'] <= 0) {
  818. $location['lat'] = $order->end_use_bike_location['latitude'];
  819. $location['lng'] = $order->end_use_bike_location['longitude'];
  820. if ($location['lat'] <= 0) {
  821. $location['lat'] = $user_lat;
  822. $location['lng'] = $user_lng;
  823. }
  824. }
  825. //检查是否在骑行区域
  826. $area = $areaRepository->byIdGetModelRedis($order->area_id);
  827. if (!$area) {
  828. $area = Area::where('id', $order->area_id)->first();
  829. }
  830. $is_out_area = $this->isOutArea($location['lat'], $location['lng'], $area);
  831. if (!$is_out_area) {
  832. return $this->errorNoValidation('超出骑行区域,暂不能还车');
  833. }
  834. //检查是否在禁停区
  835. $BikeHandler = new BikeHandler();
  836. $is_ban_stop_bike = $BikeHandler->byLocationCheckIsInBanStopParking($location['lat'], $location['lng'], $order->area_id, $user_lat, $user_lng);
  837. if ($is_ban_stop_bike) {
  838. return $this->errorNoValidation('禁停区域内禁止停车!');
  839. }
  840. return [
  841. 'is_close_order' => false,
  842. ];
  843. } catch (HttpException $exception) {
  844. return $this->errorNoValidation($exception->getMessage(), $exception->getStatusCode());
  845. }
  846. }
  847. /**
  848. * Author: Mead
  849. */
  850. public function expectRentOrderMoney(Request $request, BikeRepository $bikeRepository, RentOrderRepository $rentOrderRepository, AreaSettingRepository $areaSettingRepository, LocationLogRepository $locationLogRepository, AreaRepository $areaRepository)
  851. {
  852. $bike_no = $request->get('bike_no');
  853. $order_no = $request->get('order_no');
  854. $user_lat = $request->get('lat');
  855. $user_lng = $request->get('lng');
  856. try {
  857. $order = $rentOrderRepository->byNo($order_no);
  858. if (!$order) {
  859. return $this->errorBadRequest('非法请求');
  860. }
  861. $second = Carbon::now()->diffInSeconds(Carbon::parse($order->start_use_bike_time));
  862. if ($second < AreaSetting::CLOSE_BIKE_TIME) {
  863. //小于60秒直接锁车
  864. return [
  865. 'dispatch_money' => 0,
  866. 'time_money' => 0,
  867. 'rent_total_money' => 0,
  868. 'total_money' => 0,
  869. ];
  870. }
  871. $user_id = $this->user['id'];
  872. $cache_key = "RENT_ORDER_EXPECT_MONEY_{$user_id}";
  873. if (Cache::has($cache_key)) {
  874. return $this->errorNoValidation('您提交的太频繁了,请一会再提交!');
  875. }
  876. Cache::put($cache_key, 1, Carbon::now()->addSeconds(3));
  877. $box_no = $bikeRepository->byNoGetBoxNO($order->bike_no);
  878. (new BaseBikeControl($box_no))::nowBikeLocation();
  879. $setting = $areaSettingRepository->byAreaId($order->area_id);
  880. $money = 0.00;
  881. $over_hours = 0;
  882. //是否需要收取超出费用
  883. $is_over_time = (strtotime($order->return_end_bike_time) < time());
  884. if ($is_over_time) {
  885. //超出时间
  886. $over_hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->return_end_bike_time)) / 60);
  887. $hours = ceil(Carbon::now()->diffInMinutes(Carbon::parse($order->start_use_bike_time)) / 60);
  888. if ($hours > 24) {
  889. //超过1天
  890. $day = ceil($hours / 24);
  891. $end_hours = $hours % 24;
  892. //日封顶租金*天
  893. $money = bcmul($setting['over_rent_time_max_money'], ($day - 1), 2);
  894. // $money = bcadd($money, $setting['rent_money'], 2);
  895. if ($end_hours > $setting['rent_time']) {
  896. // 超过一天 又超过8小时
  897. // (超时费 + 日封顶租金*天)
  898. $money = bcadd(bcmul(($end_hours - $setting['rent_time']), $setting['over_rent_time_money'], 2), $money, 2);
  899. }
  900. } else {
  901. // 不超过1天 但是超过8小时
  902. $money = bcmul($over_hours, $setting['over_rent_time_money'], 2);
  903. // (超时费 + 基础租金) 是否大于日封顶租金
  904. $total_money = bcadd($money, $setting['rent_money'], 2);
  905. if ($total_money > $setting['over_rent_time_max_money']) {
  906. $money = bcsub($setting['over_rent_time_max_money'], $setting['rent_money'], 2);
  907. }
  908. }
  909. }
  910. $location = $locationLogRepository->byBikeNoGetLastLocation($order->bike_no, CacheMap::IS_OPEN_MONGODB_DUG);
  911. //计算骑行距离
  912. // $order->use_bike_distance_length = bcdiv($location['mileage'], 1000, 2);
  913. if ($location['lat'] <= 0) {
  914. $location['lat'] = $order->end_use_bike_location['latitude'];
  915. $location['lng'] = $order->end_use_bike_location['longitude'];
  916. if ($location['lat'] <= 0) {
  917. $location['lat'] = $user_lat;
  918. $location['lng'] = $user_lng;
  919. }
  920. }
  921. $money = floatval($money);
  922. $total_money = floatval(bcadd($money, $order->rent_total_money, 2));
  923. $rent_total_money = floatval($order->rent_total_money);
  924. //判断是否全区域内可停
  925. if ($areaSettingRepository->byAreaIdGetIsWholeAreaHuanche($order->area_id) === AreaSetting::WHOLE_AREA_HUANCHE_OK) {
  926. return [
  927. 'dispatch_money' => 0,
  928. 'time_money' => $money,
  929. 'rent_total_money' => $rent_total_money,
  930. 'total_money' => $total_money,
  931. ];
  932. }
  933. // 判断是否在停车点
  934. $BikeHandler = new BikeHandler();
  935. $is_huanche = $BikeHandler->byLocationCheckIsInStopParking($location['lat'], $location['lng'], $order->area_id, $user_lat, $user_lng);
  936. if (!$is_huanche['status']) {
  937. // 不在还车点
  938. $dispatch_money = $BikeHandler->byDistanceGetDistanceMoney($is_huanche['distance'], $setting);
  939. RentOrder::where('id', $order->id)->update([
  940. 'dispatch_money' => $dispatch_money,
  941. ]);
  942. return [
  943. 'dispatch_money' => $dispatch_money,
  944. 'time_money' => $money,
  945. 'rent_total_money' => $rent_total_money,
  946. 'total_money' => floatval(bcadd($total_money, $dispatch_money, 2)),
  947. ];
  948. }
  949. return [
  950. 'dispatch_money' => 0,
  951. 'time_money' => $money,
  952. 'rent_total_money' => $rent_total_money,
  953. 'total_money' => $total_money,
  954. ];
  955. } catch (HttpException $exception) {
  956. return $this->errorNoValidation($exception->getMessage(), $exception->getStatusCode());
  957. }
  958. }
  959. }