You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
13 KiB

6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
  1. <?php
  2. namespace App\Controller\v3;
  3. use App\Constants\v3\ErrorCode;
  4. use App\Constants\v3\LogLabel;
  5. use App\Controller\BaseController;
  6. use App\Exception\ErrorCodeException;
  7. use App\Model\v3\Market;
  8. use App\Request\v3\OrderOnlineDetailRequest;
  9. use App\Request\v3\OrderOnlineRequest;
  10. use App\Request\v3\OrderOnlineStateRequest;
  11. use App\Request\v3\UserRequest;
  12. use App\Service\v3\Interfaces\CouponRecServiceInterface;
  13. use App\Service\v3\Interfaces\DistributionPriceServiceInterface;
  14. use App\Service\v3\Interfaces\LocationServiceInterface;
  15. use App\Service\v3\Interfaces\SeparateAccountsServiceInterface;
  16. use App\Service\v3\Interfaces\ShopCartServiceInterface;
  17. use App\Service\v3\SfExpress;
  18. use GuzzleHttp\Client;
  19. use Hyperf\DbConnection\Db;
  20. /** @var Inject 注解使用 */
  21. use Hyperf\Di\Annotation\Inject;
  22. use App\Service\v3\Interfaces\OrderOnlineServiceInterface;
  23. use App\Service\v3\Interfaces\UserBindTelServiceInterface;
  24. use App\Service\v3\Interfaces\AppointmentTimeServiceInterface;
  25. use Psr\Http\Message\ResponseInterface;
  26. use App\Model\v3\UserAddress;
  27. class OrderOnlineController extends BaseController
  28. {
  29. /**
  30. * @Inject
  31. * @var UserBindTelServiceInterface
  32. */
  33. protected $userBindTelService;
  34. /**
  35. * @Inject
  36. * @var CouponRecServiceInterface
  37. */
  38. protected $couponRecService;
  39. /**
  40. * @Inject
  41. * @var AppointmentTimeServiceInterface
  42. */
  43. protected $appointmentTimeService;
  44. /**
  45. * @Inject
  46. * @var OrderOnlineServiceInterface
  47. */
  48. protected $orderOnlineService;
  49. /**
  50. * @Inject
  51. * @var ShopCartServiceInterface
  52. */
  53. protected $shopCartService;
  54. /**
  55. * @Inject
  56. * @var SeparateAccountsServiceInterface
  57. */
  58. protected $separateAccountsService;
  59. /**
  60. * @Inject
  61. * @var LocationServiceInterface
  62. */
  63. protected $locationService;
  64. /**
  65. * @Inject
  66. * @var DistributionPriceServiceInterface
  67. */
  68. protected $distributionPriceService;
  69. /*
  70. * 如果没有绑手机号去绑定页面
  71. * 收货地址接口
  72. * 返回预约送达时间
  73. * 商品数据接口
  74. * 红包独立接口
  75. * 配送费独立接口 可根据距离动态计算费用
  76. * 增值服务接口
  77. * */
  78. public function review(UserRequest $request)
  79. {
  80. $userId = $this->request->input('user_id','');
  81. $marketId = $this->request->input('market_id','');
  82. $shopcartIds = $this->request->input('shopcart_ids','');
  83. //判断用户有没有绑定手机
  84. $telExists = $this->userBindTelService->check($userId);
  85. if(!$telExists){
  86. throw new ErrorCodeException(ErrorCode::NOT_BIND_TEL_ERROR);
  87. }
  88. //获取用户收货地址
  89. $address = UserAddress::query()
  90. ->where('user_id',$userId)
  91. //->where('is_default',1)
  92. ->orderByDesc('is_default')
  93. ->orderByDesc('updated_at')
  94. ->get()->toArray();
  95. $market = Market::find($marketId);
  96. $type = 'bicycling';
  97. $key = config('map.tencent');
  98. $url = 'https://apis.map.qq.com/ws/distance/v1/matrix?mode='.$type.'&from='.$market->lat.','.$market->lng.'&to=';
  99. $client = new Client();
  100. foreach ($address as $item) {
  101. $url .= $item['lat'] . ',';
  102. $url .= $item['lng'] . ';';
  103. }
  104. $url = rtrim($url, ";");
  105. $response = $client->request('GET', $url.'&output=json&key='.$key);
  106. $response = $response->getBody()->getContents();
  107. $resultArr = json_decode($response,true);
  108. $resultArr = $resultArr['result']['rows'][0]['elements'];
  109. $deliveryDistance = config('distance.delivery_distance');
  110. foreach ($address as $key => &$item) {
  111. if($resultArr[$key]['distance'] <= $deliveryDistance){
  112. $item['distance'] = $resultArr[$key]['distance'];
  113. $addressNew[] = $item;
  114. }
  115. }
  116. $collection = collect($addressNew);
  117. $sorted = $collection->sortBy('distance')->sortByDesc('is_default');
  118. $address = $sorted->values()->first();
  119. $res['store_list'] = $this->shopCartService->getGoodsByShopcartId($shopcartIds);
  120. if($address){
  121. $distance = $address['distance'];
  122. if($distance >= 1000){
  123. $distance_text = '距您收货地址 ' . bcdiv($distance,1000,2) . 'km';
  124. }else{
  125. $distance_text = '距您收货地址 ' . $distance . 'm';
  126. }
  127. if($address['is_default'] == 1){
  128. $address['tags'][0] = ['id' => 5,'name' => '默认'];
  129. }else{
  130. $address['tags'][0] = ['id' => 6,'name' => '距离最近'];
  131. }
  132. try {
  133. $weight = 0;
  134. foreach ($res['store_list'] as $item) {
  135. foreach ($item['shopping_cart'] as $v) {
  136. $weight += $v['goods']['weight'] * $v['num'];
  137. }
  138. }
  139. # 因首次进入时是尽快送达,故此处不用处理预约单
  140. $distributionPrice = SfExpress::getInstance()->getDeliveryCost([
  141. 'user_lng' => $address['lng'],
  142. 'user_lat' => $address['lat'],
  143. 'user_address' => $address['address'],
  144. 'weight' => $weight,
  145. 'shop' => [
  146. 'shop_name' => $market->name,
  147. 'shop_phone' => $market->tel,
  148. 'shop_address' => $market->address,
  149. 'shop_lng' => $market->lng,
  150. 'shop_lat' => $market->lat,
  151. ],
  152. ]);
  153. $originalPrice = SfExpress::getInstance()->getOriginDeliveryCost($distributionPrice);
  154. } catch (\Exception $exception) {
  155. return $this->result(500, [], $exception->getMessage());
  156. }
  157. $res['location'] = [
  158. 'address' => $address,
  159. 'distribution_price' => $distributionPrice,
  160. 'original_price' => $originalPrice,
  161. 'distance' => $distance,
  162. 'within' => true,
  163. 'style' => 'strike',
  164. // 'distribution_text' => '¥ '.$distributionPrice .'(' .$distance_text .')'
  165. 'distribution_text' => $distance_text,
  166. 'distribution_price_text' => '¥ '.$distributionPrice,
  167. 'original_price_text' => $originalPrice > $distributionPrice ? '¥ '.$originalPrice : ''
  168. ];
  169. }else{
  170. $res['location'] = [
  171. 'address' => '',
  172. 'distribution_price' => 0,
  173. 'original_price' => 0,
  174. 'distance' => 0,
  175. 'within' => false,
  176. 'style' => 'strike',
  177. 'distribution_text' => '',
  178. 'distribution_price_text' => '¥ 0',
  179. 'original_price_text' => ''
  180. ];
  181. }
  182. //返回预约送达时间 数组
  183. $res['appointment_time'] = $this->appointmentTimeService->get($shopcartIds);
  184. //获取用户优惠券
  185. $coupons = $this->couponRecService->allForOnlineOrderAvailable( $userId, $marketId, explode(',', $shopcartIds) );
  186. $res['coupon'] = [
  187. 'available' => [],
  188. 'not_available' => [],
  189. ];
  190. foreach ($coupons as $key => &$item) {
  191. foreach ($item as $k => &$rec) {
  192. for ($i=0; $i<$rec->number_remain; $i++) {
  193. if ($key == 'available') {
  194. $res['coupon']['available'][] = $rec;
  195. } elseif ($key == 'not_available') {
  196. $res['coupon']['not_available'][] = $rec;
  197. }
  198. }
  199. }
  200. }
  201. // $res['coupon'] = $coupons;
  202. //增值服务接口
  203. $res['value_added_service'] = [
  204. 'text' => '增值服务包含洗菜、切菜、打包等所产生的人工成本费及包装费。',
  205. 'select' => 0,
  206. 'price' => 0,
  207. 'original_price' => 3.5
  208. ];
  209. $total = 0;
  210. foreach ($res['store_list'] as $store)
  211. {
  212. $total = bcadd($total,$store['subtotal'],2);
  213. }
  214. $total = bcadd($total,$res['value_added_service']['price'],2);
  215. $total = bcadd($total,$res['location']['distribution_price'],2);
  216. $res['total'] = $total;
  217. //优惠券排序
  218. $collection = collect($res['coupon']['available']);
  219. $sorted = $collection->sortBy(function ($product, $key) use ($total){
  220. if($product['coupon']['discount_type'] == 2){
  221. return bcmul($total,bcdiv($product['coupon']['discounts'],10,2),2);
  222. }elseif($product['coupon']['discount_type'] == 1){
  223. return bcsub($total,$product['coupon']['discounts'],2);
  224. }
  225. });
  226. $res['coupon']['available'] = $sorted->values()->all();
  227. // 新增返回市场信息
  228. $res['market'] = $market;
  229. return $this->success($res);
  230. }
  231. /**
  232. * 订单详情
  233. * 1、主订单信息,用户配送信息(地址、姓名、电话、配送时间、配送类型)、基础信息(订单ID、订单编号、下单时间、订单金额、付款时间、支付方式、红包优惠、服务站电话、增值服务费)
  234. * 2、子订单以及订单商品,按商户分组,有商户信息(ID、商户名、商户logo),商品信息(id、名字、封面、规格、tag、原价、售价、库存、总销、月销、是否失效、失效原因)
  235. * @param OrderOnlineDetailRequest $request
  236. * @return ResponseInterface
  237. */
  238. public function detailByUser(OrderOnlineDetailRequest $request)
  239. {
  240. $params = $request->validated();
  241. return $this->success(['detail' => $this->orderOnlineService->detailByUser($params['global_order_id'], $params['user_id'])]);
  242. }
  243. /**
  244. * 下单并进行支付,返回支付参数
  245. * 1、用户传参,用户地址ID,用于获取用户地址经纬度来计算配送费
  246. * 2、用户传参,购物车IDs,去获取购物车里的商品详情
  247. * 3、预约送达时间
  248. * 4、优惠券IDs
  249. * 5、订单总金额,用于校验比对
  250. * 6、下单成功,请求支付
  251. * @param OrderOnlineRequest $request
  252. * @return ResponseInterface
  253. */
  254. public function add(OrderOnlineRequest $request){
  255. // 下单
  256. $params = $request->validated();
  257. $couponIds = isset($params['coupon_ids'])&&$params['coupon_ids'] ? explode(',', $params['coupon_ids']) : [];
  258. $data = $this->orderOnlineService->do(
  259. $params['market_id'],
  260. $params['user_id'],
  261. ($params['user_address_id'] ?? 0),
  262. json_decode($params['store_list']),
  263. $params['total_money'],
  264. $params['delivery_time_note'],
  265. ($params['service_money'] ?? 0),
  266. $couponIds,
  267. $params['plat'] ?: '',
  268. ($params['self_take'] ?? 0)
  269. );
  270. return $this->success(['data' => $data]);
  271. }
  272. /**
  273. * 待支付订单重新发起支付
  274. * 1、用户id、订单id
  275. * 2、发起支付
  276. * @param OrderOnlineStateRequest $request
  277. * @return ResponseInterface
  278. */
  279. public function pay(OrderOnlineStateRequest $request)
  280. {
  281. $params = $request->validated();
  282. $data = $this->orderOnlineService->doPay($params['global_order_id'], $params['user_id']);
  283. return $this->success(['data' => $data]);
  284. }
  285. /**
  286. * 取消订单
  287. * @param OrderOnlineStateRequest $request
  288. * @return ResponseInterface
  289. */
  290. public function cancel(OrderOnlineStateRequest $request)
  291. {
  292. $params = $request->validated();
  293. $this->orderOnlineService->undo($params['global_order_id'], $params['user_id']);
  294. return $this->success([]);
  295. }
  296. /**
  297. * 删除订单
  298. * @param OrderOnlineStateRequest $request
  299. * @return ResponseInterface
  300. */
  301. public function del(OrderOnlineStateRequest $request)
  302. {
  303. $params = $request->validated();
  304. $this->orderOnlineService->doDel($params['global_order_id'], $params['user_id']);
  305. return $this->success([]);
  306. }
  307. /**
  308. * 申请退款
  309. * @param OrderOnlineStateRequest $request
  310. * @return ResponseInterface
  311. */
  312. public function applyRefund(OrderOnlineStateRequest $request)
  313. {
  314. $params = $request->validated();
  315. $this->orderOnlineService->doApplyRefund($params['global_order_id'], $params['user_id']);
  316. return $this->success([]);
  317. }
  318. /**
  319. * 完成订单
  320. * @param OrderOnlineStateRequest $request
  321. * @return ResponseInterface
  322. */
  323. public function complete(OrderOnlineStateRequest $request)
  324. {
  325. Db::beginTransaction();
  326. try {
  327. $params = $request->validated();
  328. $this->orderOnlineService->doComplete($params['global_order_id'], $params['user_id']);
  329. $this->separateAccountsService->orderOnlineCompleted($params['global_order_id'], $params['user_id']);
  330. Db::commit();
  331. return $this->success([]);
  332. } catch (\Exception $e) {
  333. Db::rollBack();
  334. $this->log->event(LogLabel::ORDER_COMPLETE_LOG, ['exception' => $e->getMessage()]);
  335. throw new ErrorCodeException(ErrorCode::ORDER_COMPLETE_FAIL);
  336. }
  337. }
  338. }