Sfoglia il codice sorgente

课程预约功能相关接口

jun 6 mesi fa
parent
commit
fb075fe733

+ 291 - 227
app/Http/Controllers/Api/Course.php

@@ -4,13 +4,12 @@ use App\Http\Controllers\Api\Api;
 use App\Models\Orders as Model;
 use App\Models\Product;
 use App\Models\Product\Skus as ProductSkus;
-use App\Http\Requests\Api\Orders as Request;
+use App\Http\Requests\Api\Course as Request;
 use App\Models\Business;
 use App\Models\CustomAddr;
-use App\Models\CustomCoupon;
-use App\Models\OrdersAddr;
 use App\Models\OrdersProduct;
-use App\Models\ShopCart;
+use App\Models\CourseSchedule;
+use App\Models\CourseReservation;
 use Illuminate\Support\Facades\DB;
 
 /**
@@ -22,213 +21,93 @@ use Illuminate\Support\Facades\DB;
 class Course extends Api{
 
 	/**
-	 * 创建订单						 	/api/orders/create
+	 * 预约课程					 	/api/course/reservation
 	 *
 	 * @param	string	$car_info		需要下单的产品ID
 	 * @param	string	$buyer_number	需要下单的数量
 	 *
 	 * */
-	public function create(Request $request,Model $Model,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,ProductSkus $ProductSkus,CustomCoupon $CustomCoupon,ShopCart $ShopCart,CustomAddr $CustomAddr){
+	public function reservation(Request $request,Model $Model,OrdersProduct $OrdersProduct,CourseSchedule $CourseSchedule,CourseReservation $CourseReservation){
 		// 接口验签
 		// $this->verify_sign();
 		// 验证参数
-		$request->scene('create')->validate();
+		$request->scene('reservation')->validate();
 		// 检查登录
 		$uid							= $this->checkLogin();
 		// 接收参数
-		$isCart							= request('is_cart',0);
-		$productList					= request('product_list','[]');
-		$customCouponId					= request('custom_coupon_id',1);
-		$addr							= $CustomAddr->getOne(request('addr_id',0));
-		// 如果不存在数据
-		if( !$addr )					return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
-		// 重组数据
-		$addr							= ['contact_name'=>$addr['contact_name'],'contact_phone'=>$addr['contact_phone'],'contact_province'=>$addr['contact_province'],'contact_city'=>$addr['contact_city'],'contact_area'=>$addr['contact_area'],'contact_addr'=>$addr['contact_addr']];
-		// 解码购买信息
-		$buyList						= json_decode($productList,true);
-		// 如果不存在数据
-		if( empty($buyList) )			return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
-		// 查询产品信息
-		$productList					= $Product->getListByIds(array_column($buyList,'product_id'));
-		$skusList						= $ProductSkus->getListByIds(array_column($buyList,'product_skuid'));
-		// 产品以商业公司分组,方便写入订单
-		$orderProduct					= [];
-		// 产品价格同级,用于优惠券计算
-		$productPrice					= [];
-		// 循环处理购买信息
-		foreach ($buyList as $buyInfo) 	{
-			// 如果产品不存在
-			if( empty($productList[$buyInfo['product_id']]) )	return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
-			// 获取产信息
-			$productInfo 				= $productList[$buyInfo['product_id']];
-			// 如果存在SKU
-			if( $buyInfo['product_skuid'] ) {
-				// 判断SKU信息存不存在
-				if( empty($skusList[$buyInfo['product_skuid']]) ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不存在或已下架=>'.$buyInfo['product_skuid']]]);
-				// 如果SKU存在,合并产品信息
-				$productInfo			= array_merge($productInfo,$skusList[$buyInfo['product_skuid']]);
-				// 扣除库存
-				$skusList[$buyInfo['product_skuid']]['stock'] = $skusList[$buyInfo['product_skuid']]['stock'] - $buyInfo['buy_num'];
-			}
-			// 判断库存
-			if( $productInfo['stock'] < $buyInfo['buy_num'] )  return json_send(['code'=>'error','msg'=>'产品库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
-			// 扣除库存
-			$productList[$buyInfo['product_id']]['stock']	= $productList[$buyInfo['product_id']]['stock'] - $buyInfo['buy_num'];
-			// 计算价值
-			$priceTotal					= $buyInfo['buy_num'] * $productInfo['price'];
-			// 购买信息
-			$buyInfo					= ['is_rebate'=>0,'custom_uid'=>$uid,'business_id'=>$productInfo['business_id'],'product_id'=>$buyInfo['product_id'],'buy_num'=>$buyInfo['buy_num'],'price_total'=>$priceTotal,'pay_total'=>$priceTotal,'coupon_total'=>0,'product_name'=>$productInfo['product_name'],'course_id'=>$productInfo['course_id'],'sku_attr_names'=>$productInfo['sku_attr_names'],'product_thumb'=>$productInfo['product_thumb']];
-			// 获取信息
-			if( !isset($orderProduct[$buyInfo['business_id']]) )		$orderProduct[$buyInfo['business_id']] = ['business_id'=>$buyInfo['business_id'],'custom_uid'=>$buyInfo['custom_uid'],'price_total'=>0,'pay_total'=>0,'coupon_total'=>0,'product_list'=>[]];
-			// 订单产品
-			$orderProduct[$buyInfo['business_id']]['price_total']		+= $buyInfo['price_total'];
-			$orderProduct[$buyInfo['business_id']]['pay_total']			+= $buyInfo['price_total'];
-			$orderProduct[$buyInfo['business_id']]['product_list'][]	= $buyInfo;
-			// 商品优惠信息不存在,创建
-			if( !isset($productPrice[$buyInfo['product_id']]) )			$productPrice[$buyInfo['product_id']] = ['price_total'=>0,'rebate_price'=>0];
-			// 计算总价
-			$productPrice[$buyInfo['product_id']]['price_total']		= $productPrice[$buyInfo['product_id']]['price_total'] + $priceTotal;
-		}
-		// 优惠券数据
-		$couponRebate					= $CustomCoupon->getRebatePrice($customCouponId,$uid,$productPrice);
-		// 判断是否使用了优惠券
-		$usedCoupon						= $couponRebate['is_used'];
-		// 获取优惠券扣减金额
-		$productPrice					= $couponRebate['product_price'];
-		// 获取优惠券赠品信息
-		$rebateProduct					= $couponRebate['rebate_product'];
-		// 库存处理
-		foreach ($productList as $key => $value) {
-			$productList[$key]			= ['id'=>$value['id'],'stock'=>$value['stock']];
-		}
-		foreach ($skusList as $key => $value) {
-			$skusList[$key]				= ['id'=>$value['sku_id'],'stock'=>$value['stock']];
-		}
-		// 组合订单数据
-		foreach ($orderProduct as $key => $order) {
-			// 判断哪一家的赠品
-			if( isset($rebateProduct[$order['business_id']]) ){
-				// 循环赠品
-				foreach ( $rebateProduct[$order['business_id']] as $value) {
-					// 没有对应的产品
-					if( !isset($productList[$value['product_id']]) )  $productList[$value['product_id']] = ['id'=>$value['id'],'stock'=>$value['stock']];
-					// 判断库存,如果库存不足,只赠送最后的库存
-					if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] )  $value['buy_num'] = $productList[$value['product_id']]['stock'];
-					// 库存扣减
-					$productList[$value['product_id']]['stock'] = $productList[$value['product_id']]['stock'] - $value['buy_num'];
-					// 追加到订单表
-					$order['product_list'][] = ['is_rebate'=>1,'custom_uid'=>$uid,'business_id'=>$value['business_id'],'product_id'=>$value['product_id'],'buy_num'=>$value['buy_num'],'price_total'=>$value['price_total'],'pay_total'=>$value['pay_total'],'coupon_total'=>$value['coupon_total'],'product_name'=>$value['product_name'],'sku_attr_names'=>$value['sku_attr_names'],'product_thumb'=>$value['product_thumb']];
-				}
-			}
-			// 计算总价格
-			foreach ($order['product_list'] as $k=>$product) {
-				// 商品不存在,不进行扣减
-				if( empty($productPrice[$product['product_id']]['rebate_price']) ) {
-					// 重组
-					$order['product_list'][$k] = $product;
-					continue;
-				}
-				// 总优惠增加
-				$order['coupon_total']	 = $order['coupon_total']  + $productPrice[$product['product_id']]['rebate_price'];
-				// 当前商品的优惠折扣计算
-				$product['coupon_total'] = number_format( $productPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $productPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
-				// 成交小计
-				$product['pay_total']	 = $product['pay_total'] -  $product['coupon_total'];
-				// 重组
-				$order['product_list'][$k] = $product;
-			}
-			// 成交总价
-			$order['pay_total']			= $order['pay_total'] -  $order['coupon_total'];
-			// 成交总价
-			$order['custom_uid']		= $uid;
-			// 重组
-			$orderProduct[$key]			= $order;
-		}
-		// 组合数据,写入订单表,子表
-		DB::beginTransaction();
-		// 写入数据
-		try {
-			// 当前时间
-			$time 						= time();
-			// 更新库存
-			$Product->updateBatch(array_values($productList));
-			// 更新库存
-			$ProductSkus->updateBatch(array_values($skusList));
-			// 循环订单数据
-			foreach ($orderProduct as $order) {
-				// 先获取产品列表,并去除key
-				$productList			= array_values($order['product_list']);
-				// 删除非必要数据
-				unset($order['product_list']);
-				// 创建总订单
-				$orderId				= $Model->add($order);
-				// 如果订单写入失败
-				if( !$orderId )			{
-					// 回退数据
-					DB::rollBack();
-					// 错误提示
-					return 				json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
-				}
-				// 创建子订单
-				foreach ($productList as $key=>$value) {
-					// 增加订单ID
-					$value['order_id']	= $orderId;
-					// 增加订单ID
-					$value['insert_time']= $time;
-					$value['update_time']= $time;
-					// 结果
-					$productList[$key]	= $value;
-				}
-				// 写入子表
-				$result					= $OrdersProduct->query()->insert($productList);
-				// 如果扣减失败
-				if( !$result )												{
-					// 回退数据
-					DB::rollBack();
-					// 提示信息
-					return				json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'子订单创建失败']]);
-				}
-				// 写入订单地址表
-				$addr['order_id']		= $orderId;
-				// 写入订单地址表
-				$result 				= $OrdersAddr->add($addr);
-				// 地址写入失败
-				if( !$result )			{
-					// 回退数据
-					DB::rollBack();
-					// 提示信息
-					return				json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'地址写入失败']]);
-				}
-				// 如果使用了优惠券
-				if( $usedCoupon )		$CustomCoupon->edit($usedCoupon,['status'=>1,'order_id'=>$orderId]);
-				// 购物车
-				if( $isCart )			$ShopCart->query()->where([['custom_uid','=',$uid]])->whereIn('skuid',array_column($buyList,'product_skuid'))->delete();
-			}
-			// 提交数据
-			DB::commit();
-			// 返回结果
-			return						json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
-			// 返回结果
-		} catch (\Throwable $th) {
-			// 回退数据
-			DB::rollBack();
-			// 判断结果,如果库存扣减失败的话
-			if( stripos($th->getMessage(),'UNSIGNED') )  return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'产品库存扣减失败']]);
-			// 下单失败提示
-			return						json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
-		}
+		$ordersProductId				= request('orders_product_id','');
+		$scheduleId					    = request('schedule_id','');
+        //订单课程预约信息
+        $ordersProductInfo              = $OrdersProduct->query()->where('id','=',$ordersProductId)->first();
+        if (!$ordersProductInfo)
+            return json_send(['code'=>'error','msg'=>'订单课程不存在','data'=>['error'=>'订单课程不存在']]);
+        if ($ordersProductInfo['course_number'] <= $ordersProductInfo['reservation_number'])
+            return json_send(['code'=>'error','msg'=>'您购买的课程节数已用完','data'=>['error'=>'您购买的课程节数已用完']]);
+        //上课表信息
+        $courseScheduleInfo             = $CourseSchedule->query()->where('id','=',$scheduleId)->first();
+        if (!$courseScheduleInfo)
+            return json_send(['code'=>'error','msg'=>'预约课程不存在','data'=>['error'=>'预约课程不存在']]);
+        if ($courseScheduleInfo['course_number'] <= $ordersProductInfo['reservation_number'])
+            return json_send(['code'=>'error','msg'=>'此时段课程已预满','data'=>['error'=>'此时段课程已预满']]);
+        $data = [
+            'orders_product_id'         =>  $ordersProductId,
+            'schedule_id'               =>  $scheduleId,
+            'uid'                       =>  $uid,
+            'order_id'                  =>  $ordersProductInfo['order_id'],
+            'product_id'                =>  $ordersProductInfo['product_id'],
+            'course_id'                 =>  $courseScheduleInfo['course_id'],
+            'teacher_id'                =>  $courseScheduleInfo['teacher_id'],
+            'start_time'                =>  $courseScheduleInfo['start_time'],
+            'end_time'                  =>  $courseScheduleInfo['start_time'],
+        ];
+        DB::beginTransaction();
+        // 写入数据
+        try {
+            // 更新订单预约数据
+            $update =  $OrdersProduct->query()->where('id','=',$ordersProductId)->update(['reservation_number'=>$ordersProductInfo['reservation_number']+1]);
+            if (!$update)
+                // 返回结果
+                return						json_send(['code'=>'success','msg'=>'预约失败','data'=>['id'=>null]]);
+            // 更新课程表预约数据
+            $updateSchedule =  $CourseSchedule->query()->where('id','=',$scheduleId)->update(['reservation_number'=>$ordersProductInfo['reservation_number']+1]);
+            if (!$updateSchedule){
+                DB::rollBack();
+                // 错误提示
+                return 				json_send(['code'=>'error','msg'=>'预约失败','data'=>['error'=>'更新课程表预约数据失败']]);
+            }
+            //添加到预约课程表
+            $reservationId		        =   $CourseReservation->add($data);
+            if( !$reservationId )			{
+                // 回退数据
+                DB::rollBack();
+                // 错误提示
+                return 				json_send(['code'=>'error','msg'=>'预约失败','data'=>['error'=>'添加预约失败']]);
+            }
+            // 提交数据
+            DB::commit();
+            // 返回结果
+            return						json_send(['code'=>'success','msg'=>'预约成功','data'=>['id'=>$reservationId]]);
+            // 返回结果
+        } catch (\Throwable $th) {
+            // 回退数据
+            DB::rollBack();
+            // 判断结果,如果库存扣减失败的话
+            if( stripos($th->getMessage(),'UNSIGNED') )  return json_send(['code'=>'error','msg'=>'预约失败','data'=>['error'=>'订单课程修改错误']]);
+            // 下单失败提示
+            return						json_send(['code'=>'error','msg'=>'预约失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
+        }
+
 	}
 
 
 	/**
 	 * 获取上课列表		 /api/course/get_list
-	 * 
-	 * @param	string	$name		    产品名称
+	 *
 	 * @param	int		$page			页码,默认1
 	 * @param	int		$limit			每页条数,默认10条
 	 * 
 	 * */
-	public function get_list(Request $request,Model $Model,OrdersProduct $OrdersProduct,Business $Business){
+	public function get_list(Request $request,Model $Model,OrdersProduct $OrdersProduct){
 		// 接口验签
 		// $this->verify_sign();
         // 验证参数
@@ -236,46 +115,40 @@ class Course extends Api{
 		// 检查登录
 		$uid						= $this->checkLogin();
 		// 接收参数
-		$status						= request('status',0);
+		$status						= request('status',1);
 		$limit						= request('limit',10);
 		// 显示
-		$map						= [['custom_uid','=',$uid]];
+		$map						= [
+                ['orders_product.custom_uid','=',$uid],
+            ];
 		// 查询状态
-		if( $status )				$map[] = ['status','=',$status];
-		// 查询
-		$Paginator					= $Model->query()
+		if( $status )				$map[] = ['orders_product.status','=',$status];
+        $select = [
+            'orders_product.id as orders_product_id',
+            'orders_product.pay_total','orders_product.status',
+            'orders_product.price_total',
+            'orders_product.coupon_total',
+            'orders_product.pay_total',
+            'orders_product.course_id',
+            'orders_product.order_id',
+            'orders_product.course_number',
+            'orders_product.reservation_number',
+            'orders_product.product_id',
+            'course.name as course_name',
+            'course.address',
+            'course.desc',
+            'course.image',
+            ];
+		// 查询订单课程
+		$Paginator					= $OrdersProduct->query()
+            ->join('course','orders_product.course_id','=','course.id')
             ->where($map)
-            ->orderByDesc('id')
-            ->paginate($limit,['id','pay_total','status','price_total','coupon_total','business_id','pay_total','insert_time']);
-		// 订单产品
-		$productList 				= $OrdersProduct->query()
-            ->whereIn('order_id', array_column($Paginator->items(),'id'))
-            ->select(['id as item_id','order_id','product_id','buy_num','is_rebate','sku_attr_names as product_spec','product_name','product_thumb','course_id','course_number'])
-            ->get()
-            ->toArray();
-        //订单已预约节数
-		// 循环处理
-		foreach ($Paginator as $key => $order) {
-			// 商品列表
-			$itemList				= [];
-			// 返回结果
-			foreach ($productList as $item) {
-				// 产品图路径
-				$item['product_thumb']	= path_compat($item['product_thumb']);
-				// 如果是订单的
-				if( $item['order_id'] == $order['id'] ) $itemList[]	= $item;
-			}
-			// 获取子列表
-			$order['state']			= (string) $Model->getState($order['status'],'state');
-			// 获取子列表
-			$order['business_name']	= (string) $Business->getOne($order['business_id'],'name');
-			// 获取子列表
-			$order['contents_class']= 0;
-			// 获取子列表
-			$order['product_list']	= $itemList;
-			// 重组
-			$Paginator[$key]		= $order;
-		}
+            ->whereColumn('orders_product.reservation_number','<','orders_product.course_number')
+            ->orderByDesc('orders_product.id')
+            ->paginate($limit, $select);
+        foreach ($Paginator->items() as &$orders_product) {
+            $orders_product['image']	= path_compat($orders_product['image']);
+        }
 		// 获取数据
 		$data['total']				= $Paginator->total();
 		$data['current_page']		= $Paginator->currentPage();
@@ -285,6 +158,197 @@ class Course extends Api{
 		// 返回结果
 		return						json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
 	}
+    /**
+     * 获取排课列表	 /api/course/get_schedule_list
+     *
+     * */
+    public function get_schedule_list(Request $request,Model $Model,CourseSchedule $CourseSchedule){
+        // 接口验签
+        // $this->verify_sign();
+        // 验证参数
+        $request->scene('get_schedule_list')->validate();
+        // 检查登录
+        $uid						= $this->checkLogin();
+        // 接收参数
+        $status						= request('status',0);
+        $limit						= request('limit',10);
+        $courseId					= request('course_id',10);
+        $ordersProductId			= request('orders_product_id',10);
+        // 显示一周的数据
+        $start                      = strtotime(date('Y-m-d'));
+        $end     = strtotime(date('Y-m-d', strtotime('+7 day')),);
+        $map						= [
+            ['course_schedule.course_id','=',$courseId],
+            ['course_schedule.start_time','>',$start],
+            ['course_schedule.end_time','<',$end],
+        ];
+        // 查询状态
+        if( $status )				$map[] = ['course_schedule.status','=',$status];
+        $select = [
+            'course_schedule.id',
+            'course_schedule.course_id',
+            'course_schedule.teacher_id',
+            'course_schedule.start_time',
+            'course_schedule.end_time',
+            'course_schedule.duration',
+            'course_schedule.course_number',
+            'course_schedule.reservation_number',
+            'course_teacher.name as teacher_name',
+            'course_teacher.desc as teacher_desc',
+            'course.name as course_name',
+            'course.image as course_image',
+            'course.desc as course_desc',
+            'course.address',
+        ];
+        // 查询订单课程
+        $data				= $CourseSchedule->query()
+            ->join('course','course_schedule.course_id','=','course.id')
+            ->join('course_teacher','course_schedule.teacher_id','=','course_teacher.id')
+            ->where($map)
+            ->orderByDesc('course_schedule.start_time')
+            ->select($select)
+            ->get();
+        $list = [];
+        foreach ($data as &$dataItem) {
+            $dataItem['course_image']	= path_compat($dataItem['course_image']);
+            //按老师分组
+            $list[$dataItem['teacher_id']]['name']		    = $dataItem['teacher_name'];
+            $list[$dataItem['teacher_id']]['teacher_id']	= $dataItem['teacher_id'];
+            $list[$dataItem['teacher_id']]['course_id']	    = $dataItem['course_id'];
+            $list[$dataItem['teacher_id']]['list'][]		= $dataItem;
+        }
+        // 返回结果
+        return						json_send(['code'=>'success','msg'=>'获取成功','data'=>$list]);
+    }
+    /**
+     * 预约课程					 	/api/course/reservation_list
+     *
+     * @param int $page 页码,默认1
+     * @param int $limit 每页条数,默认10条
+     *
+     * */
+    public function reservation_list(Request $request,Model $Model,OrdersProduct $OrdersProduct,CourseSchedule $CourseSchedule,CourseReservation $CourseReservation){
+        // 接口验签
+        // $this->verify_sign();
+        // 验证参数
+        $request->scene('reservation_list')->validate();
+        // 检查登录
+        $uid						= $this->checkLogin();
+        // 接收参数
+        $status						= request('status',0);
+        $limit						= request('limit',10);
+        $map						= [
+            ['course_reservation.uid','=',$uid],
+        ];
+        // 查询状态
+        if( $status )				$map[] = ['course_reservation.status','=',$status];
+
+        $select                     =   [
+            'course_reservation.*',
+            'course_teacher.name as teacher_name',
+            'course_teacher.desc as teacher_desc',
+            'course_teacher.pic as teacher_pic',
+            'course.name as course_name',
+            'course.address as course_address',
+        ];
+        $Paginator					= $CourseReservation->query()
+            ->join('course','course_reservation.course_id','=','course.id')
+            ->join('course_teacher','course_reservation.teacher_id','=','course_teacher.id')
+            ->where($map)
+            ->orderByDesc('course_reservation.id')
+            ->paginate($limit, $select);
+        $time = time();
+        foreach ($Paginator->items() as &$reservation) {
+            $reservation['teacher_pic']	= path_compat($reservation['teacher_pic']);
+            switch ($reservation['status']){
+                case 1:
+                    if ($reservation['start_time'] <= $time){
+                        $reservation['status'] = 3;
+                        $reservation['status_name'] = '已完成';
+                    }else{
+                        $reservation['status_name'] = '待上课';
+                    }
+                    break;
+                case 2:
+                    $reservation['status_name'] = '已取消';
+                    break;
+                case 3:
+                    $reservation['status_name'] = '已完成';
+                    break;
+            }
+        }
+        // 获取数据
+        $data['total']				= $Paginator->total();
+        $data['current_page']		= $Paginator->currentPage();
+        $data['per_page']			= $Paginator->perPage();
+        $data['last_page']			= $Paginator->lastPage();
+        $data['data']				= $Paginator->items();
+        // 返回结果
+        return						json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
+    }
+    /**
+     * 取消预约					 	/api/course/cancel_reservation
+     *
+     * @param int $page 页码,默认1
+     * @param int $limit 每页条数,默认10条
+     *
+     * */
+    public function cancel_reservation(Request $request,Model $Model,OrdersProduct $OrdersProduct,CourseSchedule $CourseSchedule,CourseReservation $CourseReservation){
+        // 接口验签
+        // $this->verify_sign();
+        // 验证参数
+        $request->scene('cancel_reservation')->validate();
+        // 检查登录
+        $uid							= $this->checkLogin();
+        // 接收参数
+        $ordersProductId				= request('orders_product_id','');
+        $scheduleId					    = request('schedule_id','');
+        $id					            = request('id','');
+        //订单课程预约信息
+        $time = time();
+        $ordersProductInfo              = $OrdersProduct->query()->where('id','=',$ordersProductId)->first();
+        if (!$ordersProductInfo)
+            return json_send(['code'=>'error','msg'=>'订单课程不存在','data'=>['error'=>'订单课程不存在']]);
+        //上课表信息
+        $courseScheduleInfo             = $CourseSchedule->query()->where('id','=',$scheduleId)->first();
+        if (!$courseScheduleInfo)
+            return json_send(['code'=>'error','msg'=>'预约课程不存在','data'=>['error'=>'预约课程不存在']]);
+        if ($courseScheduleInfo['start_time'] <= $time)
+            return json_send(['code'=>'error','msg'=>'已过上课时间','data'=>['error'=>'已过上课时间']]);
 
+        DB::beginTransaction();
+        // 写入数据
+        try {
+            // 更新订单预约数据
+            $update =  $OrdersProduct->query()->where('id','=',$ordersProductId)->update(['reservation_number'=>$ordersProductInfo['reservation_number']-1]);
+            if (!$update)
+                // 返回结果
+                return						json_send(['code'=>'success','msg'=>'取消预约失败','data'=>['id'=>null]]);
+            //添加到预约课程表
+            // 更新订单预约数据
+            $updateReservation =  $CourseReservation->query()->where('id','=',$id)->update(['status'=>2]);
+            if (!$updateReservation)
+                // 返回结果
+                return						json_send(['code'=>'success','msg'=>'取消预约失败','data'=>['id'=>null]]);
+            if( !$updateReservation )			{
+                // 回退数据
+                DB::rollBack();
+                // 错误提示
+                return 				json_send(['code'=>'error','msg'=>'取消预约失败','data'=>['error'=>'取消预约失败']]);
+            }
+            // 提交数据
+            DB::commit();
+            // 返回结果
+            return						json_send(['code'=>'success','msg'=>'取消预约成功','data'=>['id'=>$updateReservation]]);
+            // 返回结果
+        } catch (\Throwable $th) {
+            // 回退数据
+            DB::rollBack();
+            // 判断结果,如果库存扣减失败的话
+            if( stripos($th->getMessage(),'UNSIGNED') )  return json_send(['code'=>'error','msg'=>'取消预约失败','data'=>['error'=>'订单课程修改错误']]);
+            // 下单失败提示
+            return						json_send(['code'=>'error','msg'=>'取消预约失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
+        }
 
+    }
 }

+ 17 - 1
app/Http/Controllers/Api/Orders.php

@@ -76,8 +76,24 @@ class Orders extends Api{
 			$productList[$buyInfo['product_id']]['stock']	= $productList[$buyInfo['product_id']]['stock'] - $buyInfo['buy_num'];
 			// 计算价值
 			$priceTotal					= $buyInfo['buy_num'] * $productInfo['price'];
+			$courseTotal					= $buyInfo['buy_num'] * $productInfo['course_number'];
 			// 购买信息
-			$buyInfo					= ['is_rebate'=>0,'custom_uid'=>$uid,'business_id'=>$productInfo['business_id'],'product_id'=>$buyInfo['product_id'],'buy_num'=>$buyInfo['buy_num'],'price_total'=>$priceTotal,'pay_total'=>$priceTotal,'coupon_total'=>0,'product_name'=>$productInfo['product_name'],'course_id'=>$productInfo['course_id'],'sku_attr_names'=>$productInfo['sku_attr_names'],'product_thumb'=>$productInfo['product_thumb']];
+			$buyInfo					= [
+                'is_rebate'=>0,
+                'custom_uid'=>$uid,
+                'business_id'=>$productInfo['business_id'],
+                'product_id'=>$buyInfo['product_id'],
+                'buy_num'=>$buyInfo['buy_num'],
+                'price_total'=>$priceTotal,
+                'pay_total'=>$priceTotal,
+                'coupon_total'=>0,
+                'product_name'=>$productInfo['product_name'],
+                'course_id'=>$productInfo['course_id'],
+                'course_number'=>$courseTotal,
+                'sku_attr_names'=>$productInfo['sku_attr_names'],
+                'sku_id'=>$productInfo['sku_id'],
+                'product_thumb'=>$productInfo['product_thumb']
+            ];
 			// 获取信息
 
 			if( !isset($orderProduct[$buyInfo['business_id']]) )		$orderProduct[$buyInfo['business_id']] = ['business_id'=>$buyInfo['business_id'],'custom_uid'=>$buyInfo['custom_uid'],'price_total'=>0,'pay_total'=>0,'coupon_total'=>0,'product_list'=>[]];

+ 50 - 0
app/Http/Requests/Api/Course.php

@@ -0,0 +1,50 @@
+<?php namespace App\Http\Requests\Api;
+
+use App\Http\Requests\BaseRequest;
+use App\Rules\JsonArray;
+/**
+ * 订单验证器
+ * 
+ */
+class Course extends BaseRequest
+{
+    /**
+     * 获取应用于请求的规则
+     *
+     * @return array
+     */
+    public function rules()
+    {
+        // 编辑时排除ID
+        // 返回结果
+        return      [
+            // 有时候我们希望某个字段在第一次验证失败后就停止运行验证规则,只需要将 bail 添加到规则中:
+            // 验证字段,验证规则,提示信息
+            // 'name'       => 'string|max:20',
+            'id'                => 'required|integer|gt:0',
+        ];
+    }
+
+    // 场景列表
+    protected   $scenes         = [
+        'get_list'              => [],
+        'reservation'           => ['orders_product_id','schedule_id'],
+        'get_schedule_list'     => [],
+        'reservation_list'      => [],
+        'cancel_reservation'      => [],
+	];
+
+    /**
+     * 获取已定义验证规则的错误消息
+     *
+     * @return array
+     */
+    public function messages()
+    {
+        return [
+            'orders_product_id.required'   	=> '缺少预约课程,请确认预约课程',
+            'schedule_id.required'   	    => '请选择预约排课',
+        ];
+    }
+
+}

+ 3 - 3
app/Models/CourseReservation.php

@@ -64,11 +64,11 @@ class CourseReservation extends Model
     public function getList($force = false)
     {
         // 结果数据
-        $list                  = $force ? [] : cache('admin:course');
+        $list                  = $force ? [] : cache('admin:course_reservation_list');
         // 不存在数据
         if ( !$list ) {
             // 从数据库获取数据
-            $data              = $this->query()->where(['status'=>0])->get(['id','course_id','teacher_id','start_time','end_time','duration']);
+            $data              = $this->query()->get(['id','schedule_id','insert_time','orders_product_id']);
             // 是否有数据
             $data              = $data ? $data->toArray() : [];
             // 循环处理数据
@@ -79,7 +79,7 @@ class CourseReservation extends Model
                 $list[$value['id']] = $value;
             }
             // 存起来
-            cache(['admin:course_schedule'=>$list]);
+            cache(['admin:course_reservation_list'=>$list]);
         }
         // 返回结果
         return                  $list;

+ 18 - 2
app/Models/OrdersProduct.php

@@ -1,5 +1,6 @@
 <?php namespace App\Models;
 
+use App\Models\Traits\MultipUpdate;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
 /**
@@ -8,7 +9,7 @@ use Illuminate\Database\Eloquent\Model;
  */
 class OrdersProduct extends Model
 {
-    use HasFactory;
+    use HasFactory,MultipUpdate;
 
     // 与模型关联的表名
     protected $table = 'orders_product';
@@ -67,5 +68,20 @@ class OrdersProduct extends Model
     public function idToCode($id){
         return 'kldd'. str_pad($id, 9, '0', STR_PAD_LEFT);;
     }
-
+    /**
+     * 获取订单产品数据
+     *
+     * @param   Array      ID
+     * @param   String     指定字段
+     *
+     */
+    public function getOne($id,$field='')
+    {
+        // 获取列表数据
+        $list                   = $this->getList();
+        // 获取数据
+        $one                    = isset($list[$id]) ? $list[$id] : [];
+        // 返回值
+        return                  empty($field) ? $one : ( isset($one[$field]) ? $one[$field] : null);
+    }
 }

+ 1 - 1
app/Models/Product/Skus.php

@@ -77,7 +77,7 @@ class Skus extends Model
     public function getListByIds($skuIds)
     {
         // 写入数据表
-        $data					= $this->query()->whereIn('id',$skuIds)->where([['status','=',0]])->get(['id as sku_id','attr_names as sku_attr_names','price','stock','status'])->toArray();
+        $data					= $this->query()->whereIn('id',$skuIds)->where([['status','=',0]])->get(['id as sku_id','attr_names as sku_attr_names','price','stock','status','course_number'])->toArray();
         // 列表
         $list                   = [];
         // 循环处理

+ 9 - 1
routes/api.php

@@ -113,4 +113,12 @@ Route::any('custom/set_city',[\App\Http\Controllers\Api\Custom::class,'set_city'
 Route::any('banner/get_list',[\App\Http\Controllers\Api\Banner::class,'get_list']);
 
 // 上课列表
-Route::any('course/get_list',[\App\Http\Controllers\Api\Orders::class,'get_list']);
+Route::any('course/get_list',[\App\Http\Controllers\Api\course::class,'get_list']);
+//预约上课
+Route::any('course/reservation',[\App\Http\Controllers\Api\course::class,'reservation']);
+//课程排课表
+Route::any('course/get_schedule_list',[\App\Http\Controllers\Api\course::class,'get_schedule_list']);
+//我的预约列表
+Route::any('course/reservation_list',[\App\Http\Controllers\Api\course::class,'reservation_list']);
+//取消预约
+Route::any('course/cancel_reservation',[\App\Http\Controllers\Api\course::class,'cancel_reservation']);