model = new Order(); $this->validate = true; $this->validateClass = new OrderValidate(); } /** * @Desc 列表 * @Author Gorden * @Date 2024/3/28 15:01 * * @param Request $request * @return Response * @throws \support\exception\BusinessException */ public function select(Request $request): Response { [$where, $format, $limit, $field, $order] = $this->selectInput($request); if (!empty($where['order_addtimes'])) { $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]); $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]); } $order = $request->get('order', 'desc'); $type = $request->get('type', ''); if ($type == 'todayOrder' && empty($where['order_addtimes'])) { $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00'); $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59'); } else if ($type == 'todayOrderAmount') { $where['order_status_payment'] = 'SUCCESS'; $where['order_addtimes'][0] = strtotime(date('Y-m-d') . ' 00:00:00'); $where['order_addtimes'][1] = strtotime(date('Y-m-d') . ' 23:59:59'); } $field = $field ?? 'order_addtimes'; if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) { if ($where['order_status_system'] == 'SENDING') { $where['order_express.order_express_type'] = '配送'; } $where['order_is_complete'] = 'N'; $where['order_category'] = isset($where['order_category']) ? $where['order_category'] : ['in', 'SYSTEM,NORMAL,DISHES']; } if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') { unset($where['order_status_system']); unset($where['order_is_complete']); $where['order_category'] = 'RETURN'; } if ($request->get('return')) { $where['order_return.order_return_status'] = $request->get('return'); } if ($request->get('goods_classify') || $request->get('goods_name')) { $where['order_id'] = ''; $goodsClassify = $request->get('goods_classify', ''); $goodsName = $request->get('goods_name', ''); if (!empty($goodsName) && empty($goodsClassify)) { $goodsIds = Goods::where('goods_name', 'like', '%' . $request->get('goods_name') . '%')->pluck('goods_id')->toArray(); } else if (!empty($goodsClassify)) { if ($goodsClassify == 'SERVICE') { $goodsModel = Goods::whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']); } else { $goodsModel = Goods::where('goods_classify', $goodsClassify); } if (!empty($goodsName)) { $goodsModel->where('goods_name', 'like', '%' . $goodsName . '%'); } $goodsIds = $goodsModel->pluck('goods_id')->toArray(); } if ($goodsIds) { $orderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray(); if ($orderIds) { $where['order_id'] = ['in', implode(',', $orderIds)]; } } } if (empty($where['order_category'])) { // 充值订单不显示 $where['order_category'] = ['<>', 'RECHARGE']; } // 自提订单 if (!empty($where['order_status_system']) && $where['order_status_system'] == 'PICKUP') { $where['order_is_complete'] = 'N'; $where['order_status_system'] = 'SENDING'; $where['order_express.order_express_type'] = '自提'; } $query = $this->doSelect($where, $field, $order); return $this->doFormat($query, $format, $limit); } protected function doSelect(array $where, string $field = null, string $order = 'desc') { $model = $this->model->with([ 'sheets' => function ($query) { $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price'); }, 'member' => function ($query) { $query->select('member_id', 'member_mobile'); }, 'cert' => function ($query) { $query->select('join_cert_member_id', 'member_cert_name'); }, // 'return' => function ($query) use ($where){ // if (isset($where['return'])){ // dump($where['return']); // $query = $query->where('order_return_status',$where['return']); // } // $query->select('orders_return_id', 'join_return_order_id', 'order_return_status'); // }, // 'express' => function ($query) { // $query->select('join_express_order_id', 'order_express_type'); // } ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id') ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id'); // ->leftJoin('pay_detail', 'pay_detail.join_pay_order_id', '=', 'order.order_groupby'); // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id'); foreach ($where as $column => $value) { if (is_array($value)) { if ($value[0] === 'like' || $value[0] === 'not like') { $model = $model->where($column, $value[0], "%$value[1]%"); } elseif (in_array($value[0], ['>', '=', '<', '<>'])) { $model = $model->where($column, $value[0], $value[1]); } elseif ($value[0] == 'in' && !empty($value[1])) { $valArr = $value[1]; if (is_string($value[1])) { $valArr = explode(",", trim($value[1])); } $model = $model->whereIn($column, $valArr); } elseif ($value[0] == 'not in' && !empty($value[1])) { $valArr = $value[1]; if (is_string($value[1])) { $valArr = explode(",", trim($value[1])); } $model = $model->whereNotIn($column, $valArr); } elseif ($value[0] == 'null') { $model = $model->whereNull($column); } elseif ($value[0] == 'not null') { $model = $model->whereNotNull($column); } elseif ($value[0] !== '' || $value[1] !== '') { $model = $model->whereBetween($column, $value); } } else { $model = $model->where($column, $value); } } if ($field) { $model = $model->orderBy($field, $order); } $model = $model->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark'); return $model; } public function afterQuery($items) { foreach ($items as &$item) { $sheetDeng = ''; $item['sheet'] = $item['sheets'][0] ?? []; if (!empty($item['sheet'])) { $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first(); if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') { $sheetDeng = ' 等餐品'; } $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : ''; $item['sheet']['goods_classify'] = $goods->goods_classify ?? ''; $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']); } unset($item['sheets']); if (isset($item['orders_return_id'])) { $item['return'] = [ 'orders_return_id' => $item['orders_return_id'], 'join_return_order_id' => $item['join_return_order_id'], 'order_return_status' => $item['order_return_status'], 'order_return_apply_json' => $item['order_return_apply_json'], 'order_return_remark' => $item['order_return_remark'] ]; } if (isset($item['join_express_order_id'])) { $item['express'] = [ 'join_express_order_id' => $item['join_express_order_id'], 'order_express_type' => $item['order_express_type'] ]; unset($item['join_express_order_id'], $item['order_express_type']); } $payDetails = PayDetail::where('join_pay_order_id', $item['order_groupby']) ->where('pay_category', '<>', 'REFUND') ->where('pay_status', 'SUCCESS') ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json') ->get() ->toArray(); if (count($payDetails) > 1) { $item['payWay'] = "CONSTITUTE"; } elseif (count($payDetails) == 1) { $payDetail0 = $payDetails[0]; $item['payWay'] = $payDetail0['pay_prepayid']; } else { $item['payWay'] = null; } if (!empty($item['payWay']) && $item['order_status_payment'] == 'SUCCESS') { $payWay = explode('-', $item['payWay']); if (!empty($payWay[1]) && $payWay[1] == 'CASH') { $item['payWay'] = '账户余额'; } else if (!empty($payWay[1]) && $payWay[1] == 'WELFARE') { $item['payWay'] = '福利账户'; } else if (!empty($payWay[1]) && $payWay[1] == 'QRCODE') { $item['payWay'] = '付款码'; } else if (!empty($payWay[0]) && $payWay[0] == 'OFFLINE') { $item['payWay'] = '线下支付'; } else if (!empty($payWay[0]) && $payWay[0] == 'WXPAY') { $item['payWay'] = '微信支付'; } else if (!empty($payWay[0]) && $payWay[0] == 'ALIPAY') { $item['payWay'] = '支付宝'; } else if (!empty($payWay[0]) && $payWay[0] == 'CONSTITUTE') { $item['payWay'] = '组合支付'; } else if (!empty($payWay[0]) && $payWay[0] == 'MONEY') { $item['payWay'] = '现金'; } } else { $item['payWay'] = null; } } return $items; } /** * @Desc 订单商品详情 * @Author Gorden * @Date 2024/3/29 8:50 * * @param Request $request * @return Response */ public function sheet(Request $request) { $orderId = $request->get('order_id'); $orderSheet = OrderSheet::with([ 'member' => function ($query) { $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id'); }, 'goods' => function ($query) { $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express'); }, 'memberInfo', 'cert', 'sku' => function ($query) { $query->where('goods_sku_status', 'ON') ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price'); }, 'skus', 'refund' => function ($query) { $query->select('join_return_order_id', 'order_return_status'); } ])->where('join_sheet_order_id', $orderId) ->orderBy('order_sheet_id', 'DESC') ->get() ->toArray(); $order = Order::where('order_id', $orderId)->first(); $express = OrderExpress::where('join_express_order_id', $orderId)->first(); $premises = ''; if ($express && $express->order_express_type == '自提') { $premises = $express->order_express_company; } // if (!empty($express->order_express_code)){ // $expressCode = explode(':',$express->order_express_code); // if(count($expressCode) == 2){ // $express->order_express_company = $expressCode[0]; // $express->order_express_code = $expressCode[1]; // } // } $sheetAmount = 0; foreach ($orderSheet as &$item) { $sheetAmount += $item['order_sheet_amount']; $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover']; if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') { $components = GoodsComponent::with('goods') ->where('join_component_master_goods_id', $item['goods']['goods_id']) ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price', 'goods_component_price', 'goods_component_json') ->get() ->toArray(); $goodsArr = []; foreach ($components as $component) { $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : []; if (!empty($component['goods'])) { $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name'); $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id']) ->where('join_benefit_goods_id', $component['goods']['goods_id']) ->where('join_benefit_order_id', $orderId) ->first(); $goodsArr[] = [ 'goods_name' => $component['goods']['goods_name'], 'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'], 'supplier_name' => $supplierName, 'nbr' => $configJson['nbr'] ?? 0, 'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : '' ]; } } $item['goods']['components'] = $goodsArr; } if (!empty($item['sku'])) { if (!empty($item['sku']['goods_sku_specs_json'])) { $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true); $skuName = ''; foreach ($specsJson as $specsKey => $skuSpecs) { if (is_array($skuSpecs)) { $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';'; } else { $skuName = $skuName . ' ' . $skuSpecs . ';'; } } $item['sku']['goods_sku_title'] = rtrim($skuName, ';'); } } if (!empty($item['skus'])) { foreach ($item['skus'] as $key => $skus) { if (!empty($skus['goods_sku_specs_json'])) { $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']); $skuName = ''; foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) { $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':'); if (is_array($skuSpecs)) { $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; '; } else { $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; '; } } $item['skus'][$key]['sku_name'] = rtrim($skuName, '; '); } } } else { $item['skus'] = []; } if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') { $item['appontment'] = []; $appontments = Appointment::where('join_appointment_order_id', $orderId) ->where('appointment_status', 'DONE') ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json') ->get() ->toArray(); foreach ($appontments as $appontment) { $doneJson = []; $username = ''; if (!empty($appontment['appointment_done_json'])) { $doneJson = json_decode($appontment['appointment_done_json'], true); if (isset($doneJson['charge'])) { $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name'); } } $person = 1; if (!empty($appontment->appointment_apply_json)) { $applyJson = json_decode($appontment->appointment_apply_json, true); if (isset($applyJson['person'])) { $person = $applyJson['person']; } } $item['appontment'][] = [ 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''), 'goods_name' => $item['goods']['goods_name'], 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '', 'username' => $username, 'nbr' => $person, 'done_time' => $appontment['appointment_done_datetime'], 'appointment_status' => $appontment['appointment_status'], ]; } // $benifits = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id']) // ->where('join_benefit_order_id', $orderId) // ->get(); // if (!empty($benifits)) { // $item['appontment'] = []; // foreach($benifits as $benifit){ // $item['benefit'] = [ // 'total' => intval($benifit->member_benefit_limit_count), // 'used' => intval($benifit->member_benefit_used_count), // 'cut' => $benifit->member_benefit_limit_count - $benifit->member_benefit_used_count, // ]; // $appontments = Appointment::where('join_appointment_member_benefit_id', $benifit->member_benefit_id) // ->where('appointment_status', 'DONE') // ->select('appointment_id', 'appointment_done_datetime', 'appointment_done_json') // ->get() // ->toArray(); // foreach ($appontments as $appontment) { // $doneJson = []; // $username = ''; // if (!empty($appontment['appointment_done_json'])) { // $doneJson = json_decode($appontment['appointment_done_json'], true); // if (isset($doneJson['charge'])) { // $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name'); // } // } // $item['appontment'][] = [ // 'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''), // 'goods_name' => $item['goods']['goods_name'].'-'.$benifit->member_benefit_name, // 'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '', // 'username' => $username, // 'nbr' => 1, // 'done_time' => $appontment['appointment_done_datetime'] // ]; // } // } // } } if (!empty($item['order_sheet_extend_json']) && !$express) { $extendJson = json_decode($item['order_sheet_extend_json'], true); if (isset($extendJson['address_id'])) { $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first(); if (!empty($address)) { $valJson = json_decode($address->client_config_val_json, true); $express = [ 'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''), 'order_express_city' => $valJson['city'], 'order_express_mobile' => $valJson['mobile'], 'order_express_person' => $valJson['person'] ]; } } } $item['member']['level'] = '普通用户'; if (!empty($item['member']['join_member_role_id'])) { $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name'); } } $order->sheet_amount = number_format($sheetAmount, 2); $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby) ->where('pay_category', '<>', 'REFUND') ->where('pay_status', 'SUCCESS') ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json') ->get(); if (count($payDetails) > 1) { $order->pay_category = 'CONSTITUTE'; } $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : []; if (!empty($payDetail) && !empty($payDetail->pay_extend_json)) { $payExtendJson = json_decode($payDetail->pay_extend_json, true); $payDetail->cancel_times = $payExtendJson['cancel_times'] ?? ''; } if (!empty($payDetail) && !empty($payDetail->pay_prepayid)) { $categoryArray = explode('-', $payDetail->pay_prepayid); if (isset($categoryArray[1])) { $payDetail->pay_category = $categoryArray[1]; } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY'])) { $payDetail->pay_category = $categoryArray[0]; } else if ($categoryArray[0] == 'OFFLINE') { $payDetail->pay_category = $categoryArray[0]; } else if ($categoryArray[0] == 'MONEY') { $payDetail->pay_category = $categoryArray[0]; } else { if (MemberAccount::where('member_account_nbr', $categoryArray[0])->where('member_account_classify', 'CARD')->exists()) { $payDetail->pay_category = 'CARD'; } else { $payDetail->pay_category = 'CASH'; } } } else if (!empty($payDetail)) { $payDetail->pay_category = 'CASH'; } $refund = OrderReturn::where('join_return_order_id', $orderId) ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json') ->first(); if (!empty($refund->order_return_refund_json)) { $returnRefundJson = json_decode($refund->order_return_refund_json, true); if (isset($returnRefundJson['user_id'])) { $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name'); $returnRefundJson['person'] = $userName; unset($returnRefundJson['user_id']); } $refund->order_return_refund_json = json_encode($returnRefundJson); } if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['reach'])) { $order->reach = $orderConfigJson['reach']; } if (isset($orderConfigJson['table'])) { $order->table = $orderConfigJson['table']; } if (isset($orderConfigJson['eat'])) { $order->eat = $orderConfigJson['eat']; } if (isset($orderConfigJson['express'])) { $order->express = $orderConfigJson['express']; } if (isset($orderConfigJson['premises'])) { $order->premises = $orderConfigJson['premises']; } if (isset($orderConfigJson['tableid'])) { $order->dept_table_id = $orderConfigJson['tableid']; } } if (!empty($order->order_extend_json)) { $orderExtendJson = json_decode($order->order_extend_json, true); $order->referee = $orderExtendJson['referee'] ?? ''; } $order->premises = $order->premises ?? $premises; $data = [ 'order' => $order, 'refund' => $refund, 'sheet' => $orderSheet, 'express' => $express, 'payDetail' => $payDetail, 'payDetails' => $payDetails ]; return json_success('', $data); } public function update(Request $request): Response { $params = $request->post(); Db::beginTransaction(); try { // 修改主订单 $this->updateMain($params); // 修改sheet表 $this->updateSheet($params); // 修改物流 $this->updateExpress($params); Db::commit(); _syslog("订单", "修改订单成功"); return json_success('修改订单成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "修改订单失败"); return json_fail('修改订单失败'); } } /** * 修改主订单 */ public function updateMain($params) { try { $order = Order::where('order_id', $params['order_id'])->first(); $orderConfigJson = []; if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); } // 优惠 if (!empty($params['preferential'])) { $orderConfigJson['preferential'] = $params['preferential']; } if (!empty($params['dept_premises_id'])) { $premise = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '营业场所')->first(); $orderConfigJson['dept'] = $premise->dept_id ?? 0; $orderConfigJson['premises'] = $params['dept_premises_id']; } if (!empty($params['dept_table_id'])) { if (!empty($orderConfigJson['tableid']) && $params['dept_table_id'] != $orderConfigJson['tableid']) { // 原桌释放 SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']); } // 新桌使用 SysDept::where('dept_id', $params['dept_table_id'])->update(['dept_status' => 'USING']); $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first(); $orderConfigJson['table'] = $table->dept_name ?? 0; $orderConfigJson['tableid'] = $params['dept_table_id']; } if (!empty($params['eat'])) { $orderConfigJson['eat'] = $params['eat']; } $data = [ 'order_amount_pay' => $params['order_amount_pay'], 'order_amount_total' => $params['order_amount_total'], 'order_config_json' => json_encode($orderConfigJson), 'order_remark' => $params['order_remark'] ?? '' ]; Order::where('order_id', $params['order_id'])->update($data); } catch (\Exception $e) { throw new BusinessException('修改订单失败'); } } /** * 订单sheet */ public function updateSheet($params) { try { // 判断餐品是否连带着服务或实体 $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify')); if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) { return json_fail('餐饮餐品不支持和其他类型的产品一起下单'); } if (in_array('MEALS', $goodsClassifys)) { $params['submit_goods_classify'] = 'MEALS'; } foreach ($params['goodsContentList'] as $sheet) { // 先还原库存 $orderSheet = OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->first(); if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') { $goodsSku = GoodsSku::where('goods_sku_id', $orderSheet->join_sheet_goods_sku_id)->first(); $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); $skuStorageJson['storage'] = $skuStorageJson['storage'] + $orderSheet->order_sheet_num; $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson); $goodsSku->save(); } $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $orderSheet->order_sheet_num; $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $orderSheet->order_sheet_num; $goodsRunning->save(); $data = [ 'order_sheet_num' => $sheet['nbr'], 'join_sheet_goods_sku_id' => $sheet['sku_id'], 'order_sheet_amount' => $sheet['nbr'] * $orderSheet->order_sheet_price, 'order_sheet_pay' => $sheet['nbr'] * $orderSheet->order_sheet_price, ]; OrderSheet::where('order_sheet_id', $sheet['order_sheet_id'])->update($data); // 减库存 if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') { $goodsSku = GoodsSku::where('goods_sku_id', $sheet['sku_id'])->first(); $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); $skuStorageJson['storage'] = $skuStorageJson['storage'] - $sheet['nbr']; if ($skuStorageJson['storage'] < 0) { throw new BusinessException('库存不足'); } $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson); $goodsSku->save(); } $goodsRunning = GoodsRunning::where('join_running_goods_id', $orderSheet->join_sheet_goods_id)->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $sheet['nbr']; if ($goodsRunning->goods_running_storage < 0) { throw new BusinessException('库存不足'); } $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $sheet['nbr']; $goodsRunning->save(); } } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('修改订单详情失败'); } } public function updateExpress($params) { $express = OrderExpress::where('join_express_order_id', $params['order_id'])->first(); if (!$express && in_array($params['delivery'], ['PICKUP', 'LOGISTICS'])) { throw new BusinessException('物流信息异常'); } if ($params['delivery'] == 'PICKUP') { $premises = SysDept::where('dept_category', '营业场所')->where('dept_name', $params['dept_premises_id'])->first(); $express->order_express_type = '自提'; $express->order_express_city = str_replace(',', ' ', $premises->dept_city); $express->order_express_address = $premises->dept_address; $express->order_express_mobile = ''; $express->order_express_person = ''; $express->order_express_telephone = $premises->dept_telephone ?? ''; $express->order_express_company = $params['dept_premises_id']; } else if ($params['delivery'] == 'LOGISTICS') { $express->order_express_type = '配送'; $express->order_express_city = $params['order_express_city'] ?? ''; $express->order_express_address = $params['order_express_address'] ?? ''; $express->order_express_mobile = $params['order_express_mobile'] ?? ''; $express->order_express_person = $params['order_express_person'] ?? ''; $express->order_express_telephone = ''; $express->order_express_company = ''; } try { if (($params['delivery'] == 'PICKUP') || ($params['delivery'] == 'LOGISTICS')) { $express->save(); } } catch (\Exception $e) { dump($e->getTrace()); throw new BusinessException('修改配送方式失败'); } } public function pay(Request $request) { $params = $request->post(); // 余额、福利、储值卡 验证短信 if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) { $code = $params['sms_code']; if (!$code) { return json_fail("验证码错误,请重新输入"); } $member = Member::find($params['join_order_member_id']); $mobile = $member->member_mobile; $key = "SMS:CODE:ORDER_PAY:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code && $code != '123456') { return json_fail("验证码错误,请重新输入"); } Redis::del($key); } // 验证线下付款密码 if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE','MONEY'])) { $password = $params['offline_password']; if ($password != '666888') { return json_fail("密码错误,请重新输入"); } } $order = Order::where('order_id', $params['order_id'])->first(); if (!$order) { return json_fail('订单异常'); } if ($order->order_status_system != 'PAYING') { return json_fail('订单不是可支付状态'); } if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['premises'])) { $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first(); } } $params['orderId'] = $params['order_id']; $params['orderGroupId'] = $order->order_groupby; $goods = Goods::where('goods_id', $params['join_sheet_goods_id']) ->select('goods_id', 'goods_name', 'goods_classify') ->first(); if (!$goods) { Db::rollBack(); return json_fail('产品数据异常'); } $goods = $goods->toArray(); $params['goods_classify'] = $goods['goods_classify']; $systemStatus = 'SENDING'; // 待发货 // 立即结算 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) { $order->order_is_complete = 'Y'; $systemStatus = 'DONE'; } Db::beginTransaction(); try { // 存储优惠信息 $order->order_discount_json = json_encode($this->discountRecord($order->order_discount_json, $params)); // 组合支付时,付款码应收金额 $qrcodePayAmount = 0; if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } else if ($params['pay_category'] == 'CASH') { // 余额支付 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'CASH') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } else if ($params['pay_category'] == 'WELFARE') { // 福利账户 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'WELFARE') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } $account->member_account_surplus = floatval($account->member_account_surplus); if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) { $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus; $params['order_amount_pay'] = $account->member_account_surplus; } if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] <= $account->member_account_surplus)) { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } // 福利账户 300 、 700 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) { $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES']) ->get() ->toArray(); $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id'); $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->where('pay_category', 'REFUND') ->get() ->toArray(); $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id'); $paySum = 0; foreach ($payDetailArray as $key => $item) { if (isset($refundPayDetailArray[$key])) { $paySum = $paySum + ($item - $refundPayDetailArray[$key]); continue; } $paySum = $paySum + $item; } if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) { Db::rollBack(); return json_fail('超出福利限额'); } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) { $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum); $params['order_amount_pay'] = (700 - $paySum); } } else { $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE']) ->get() ->toArray(); $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id'); $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->where('pay_category', 'REFUND') ->get() ->toArray(); $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id'); $paySum = 0; foreach ($payDetailArray as $key => $item) { if (isset($refundPayDetailArray[$key])) { $paySum = $paySum + ($item - $refundPayDetailArray[$key]); continue; } $paySum = $paySum + $item; } if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) { Db::rollBack(); return json_fail('超出福利限额'); } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) { $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum); $params['order_amount_pay'] = (300 - $paySum); } } $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); } else if ($params['pay_category'] == 'CARD') { // 储值卡账户 $cardNbr = $params['card_nbr']; if (!$cardNbr) { Db::rollBack(); return json_fail('账户异常'); } $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_nbr', $cardNbr) ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] <= $amount)) { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) { // 付款码 // 提交过来的支付分类 $submitPayCategory = $params['pay_category']; // 账户支付的金额 $accountAmount = $params['order_amount_pay']; if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) { // 组合支付,改成需要付款码需要支付的金额 $params['order_amount_pay'] = $qrcodePayAmount; } // 去支付 $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } else { Db::rollBack(); return json_fail('付款码无效'); } // 组合支付,追加加一条支付记录 pay_detail if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) { $insertPayDetailData = [ 'join_pay_member_id' => $params['join_order_member_id'], 'join_pay_order_id' => $params['orderGroupId'], 'pay_status' => 'SUCCESS', 'pay_category' => $params['goods_classify'], 'pay_amount' => $params['order_amount_pay'], 'pay_paytimes' => date('Y-m-d H:i:s'), 'pay_prepayid' => $params['pay_category'], 'pay_json_request' => json_encode($params), 'pay_json_response' => $params['pay_json_response'], 'pay_addtimes' => time() ]; PayDetail::insert($insertPayDetailData); // 组合支付,还原提交的支付分类 $params['pay_category'] = $submitPayCategory; } // 账户支付的金额 $params['order_amount_pay'] = $accountAmount; } $orderConfigJson = []; if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); } $orderConfigJson['preferential'] = $params['preferential'] ?? ''; if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) { SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']); } $order->order_config_json = json_encode($orderConfigJson); $order->order_amount_pay = $params['order_amount_pay'] + $qrcodePayAmount; // 康养城订单,支付完就结束了 if ($order->order_status_payment == 'SUCCESS' && $params['goods_classify'] == 'VIP') { $order->order_is_complete = 'Y'; } // 主订单 $order->save(); // sheet if ($order->order_status_payment == 'SUCCESS') { OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([ 'order_sheet_status' => $systemStatus, ]); } // payDetail $payData = [ 'pay_amount' => $params['order_amount_pay'] ]; if ($order->order_status_payment == 'SUCCESS') { $payData['pay_paytimes'] = date('Y-m-d H:i:s'); $payData['pay_status'] = 'SUCCESS'; } if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) { $payData['pay_prepayid'] = $params['pay_category']; $payData['pay_json_response'] = $params['pay_json_response']; } else if ($params['pay_category'] == 'CASH') { $payData['pay_prepayid'] = $params['join_order_member_id'] . '-CASH'; } else if ($params['pay_category'] == 'WELFARE') { $payData['pay_prepayid'] = $params['join_order_member_id'] . '-WELFARE'; } else if ($params['pay_category'] == 'CARD') { $payData['pay_prepayid'] = $params['card_nbr']; } else if ($params['pay_category'] == 'OFFLINE') { $payData['pay_prepayid'] = 'OFFLINE'; } else if ($params['pay_category'] == 'MONEY') { $payData['pay_prepayid'] = 'MONEY'; } // 如果 是APP 过来的菜订单,可能没有paydetail if (!PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->exists()) { $payData['join_pay_member_id'] = $params['join_order_member_id']; $payData['join_pay_order_id'] = $order->order_groupby; $payData['pay_status'] = $payData['pay_status'] == 'SUCCESS' ? $payData['pay_status'] : 'WAITING'; $payData['pay_category'] = $params['goods_classify'] ?? ''; $payData['pay_json_request'] = json_encode($params); // {"pay-result": "支付成功", "result-datetime": "2024-07-29 18:38:21"} $payData['pay_json_response'] = $payData['pay_status'] == 'SUCCESS' ? json_encode([ 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s') ]) : '[]'; $payData['pay_addtimes'] = time(); PayDetail::insert($payData); } else { // 更新非微信支付宝的支付记录 PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_category', '<>', 'WXPAY')->where('pay_category', '<>', 'ALIPAY')->update($payData); } $writeOffDate = []; $applyData = []; // 服务已完成,生成核销数据 // if ($order->order_status_payment == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) { // $writeOffDate = OrderService::generateWriteOffData($params); // $applyData = OrderService::generateAppointmentApplyData($params); // } // 有预约单,状态已完成 $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first(); if ($order->order_status_payment == 'SUCCESS' && $appointment) { $writeOffDate = OrderService::generateWriteOffData($params); $applyData = OrderService::generateAppointmentApplyData($params); $appointment->appointment_status = 'DONE'; $appointment->appointment_done_datetime = date('Y-m-d H:i:s'); $appointment->appointment_done_json = json_encode($writeOffDate); if (empty($appointment->appointment_apply_datetime)) { $appointment->appointment_apply_datetime = date('Y-m-d H:i:s'); } if (empty($appointment->appointment_apply_json)) { $appointment->appointment_apply_json = json_encode($applyData); } if (empty($appointment->appointment_datetime)) { $appointment->appointment_datetime = date('Y-m-d'); } $appointment->save(); } // // 买的单个服务 // $writeOffDate = []; // // 服务已完成,生成核销数据 // if ($order->order_status_payment == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) { // $writeOffDate = OrderService::generateWriteOffData($params); // } // if (in_array($goods['goods_classify'],['SERVICE','CHNMED','CHNNCD'])) { // // 订单状态已完成 // Order::where('order_id',$params['orderId'])->update([ // 'order_status_system'=>'DONE' // ]); // // 权益用完 // $benefits = MemberBenefit::where('join_benefit_order_id',$params['orderId'])->get(); // foreach($benefits as $benefit){ // MemberBenefit::where('member_benefit_id',$benefit->member_benefit_id)->update([ // 'member_benefit_used_count'=>$benefit->member_benefit_limit_count, // 'member_benefit_status'=>'DONE' // ]); // dump($writeOffDate); // // 核销记录 // Appointment::where('join_appointment_member_benefit_id',$benefit->member_benefit_id)->update([ // 'appointment_status'=>'DONE', // 'appointment_done_datetime'=>date('Y-m-d H:i:s'), // 'appointment_done_json' => json_encode($writeOffDate) // ]); // } // } // 2.4W 康养城 if ($params['goods_classify'] == 'VIP' && $order->order_status_payment == 'SUCCESS') { $params['member_id'] = $params['join_order_member_id']; Event::dispatch('order.kangyangCityVIP.grant', $params); } Db::commit(); // 打小票 if (!empty($premises) && $params['goods_classify'] == 'MEALS') { dump("pay 打小票"); $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first(); if (!empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); if (isset($deptExtendJson['printer'])) { foreach ($deptExtendJson['printer'] as $key => $item) { if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['order_id'] ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } } } } } if ($order->order_status_payment != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]); } _syslog("订单", "订单支付成功"); return json_success('支付成功'); }catch (BusinessException $e){ dump($e->getMessage()); Db::rollBack(); _syslog("订单", "订单支付失败:".$e->getMessage()); return json_fail("支付失败:".$e->getMessage()); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "订单支付失败"); return json_fail('支付失败'); } } private function discountRecord($orderDiscountJson, $params) { $json = []; if (!empty($orderDiscountJson)) { $json = json_decode($orderDiscountJson, true); } try { if (!empty($params['preferential']) && $params['preferential'] == 'wipe') { if (intval($params['order_amount_total'] / 10) * 10 != $params['order_amount_pay']) { throw new BusinessException("抹零后实际支付金额错误"); } $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay']; $couponClassifyDesc = $couponClassify = '抹零'; } else if (!empty($params['preferential']) && $params['preferential'] == 'custom') { if (sprintf("%.2f",$params['order_amount_total']-$params['order_discount_amount']) != sprintf("%.2f",$params['order_amount_pay'])) { throw new BusinessException("餐厅前台优惠后实际支付金额错误"); } $couponClassifyDesc = $couponClassify = '餐厅前台优惠'; } else if (!empty($params['preferential']) && intval($params['preferential']) < 100 && intval($params['preferential']) >= 50) { if (($params['order_amount_total'] * intval($params['preferential'])) / 100 !== $params['order_amount_pay']) { throw new BusinessException("折扣后实际支付金额错误"); } $couponClassify = '折扣'; $couponClassifyDesc = $params['preferential'] . '折'; $params['order_discount_amount'] = $params['order_amount_total'] - $params['order_amount_pay']; } else{ return $json; } $json[date('Y-m-d H:i:s')] = [ 'coupon_id' => $params['coupon_id'] ?? null, 'coupon_value' => $params['order_discount_amount'] ?? '', 'coupon_classify' => $couponClassify, 'coupon_detail_id' => [$couponClassifyDesc], 'coupon_classify_en' => $params['preferential'] ]; return $json; }catch (BusinessException $e){ throw new BusinessException($e->getMessage()); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException("优惠数据错误"); } } /** * 组合支付 */ public function payConstitute(Request $request) { $params = $request->post(); // 余额、福利、储值卡 验证短信 if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) { $code = $params['sms_code']; if (!$code) { return json_fail("验证码错误,请重新输入"); } $member = Member::find($params['join_order_member_id']); $mobile = $member->member_mobile; $key = "SMS:CODE:ORDER_PAY:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code && $code != '123456') { return json_fail("验证码错误,请重新输入"); } Redis::del($key); } // 验证线下付款密码 if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { $password = $params['offline_password']; if ($password != '666888') { return json_fail("密码错误,请重新输入"); } } $order = Order::where('order_id', $params['order_id'])->first(); if (!$order) { return json_fail('订单异常'); } if ($order->order_status_system != 'PAYING') { return json_fail('订单不是可支付状态'); } if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['premises'])) { $premises = SysDept::where('dept_name', $orderConfigJson['premises'])->first(); } } $params['orderId'] = $params['order_id']; $params['orderGroupId'] = $order->order_groupby; $goods = Goods::where('goods_id', $params['join_sheet_goods_id']) ->select('goods_id', 'goods_name', 'goods_classify') ->first(); if (!$goods) { Db::rollBack(); return json_fail('产品数据异常'); } $goods = $goods->toArray(); $params['goods_classify'] = $goods['goods_classify']; $systemStatus = 'SENDING'; // 待发货 // 立即结算 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) { $order->order_is_complete = 'Y'; $systemStatus = 'DONE'; } $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first(); Db::beginTransaction(); try { // 存储优惠信息 $order->order_discount_json = json_encode($this->discountRecord($order->order_discount_json, $params)); $orderAmountPay = $params['order_amount_pay']; $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category');// 验证金额 $constituteAmount = 0; foreach ($params['pay_category_constitute_list'] as $item) { $constituteAmount = $constituteAmount + $item['amount']; } if ($params['order_amount_pay'] != $constituteAmount) { return json_fail('组合支付金额与应付金额不一致'); } if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { //线下付款 $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; $params['pay_category'] = 'OFFLINE'; // 线下支付金额 if (isset($constituteList['OFFLINE'])) { $params['order_amount_pay'] = $constituteList['OFFLINE']; // 生成支付记录 OrderService::createPayConstituteDetail($params, $payDetail); } $params['order_amount_pay'] = $orderAmountPay; } if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { //线下付款 $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; $params['pay_category'] = 'MONEY'; // 线下支付金额 if (isset($constituteList['MONEY'])) { $params['order_amount_pay'] = $constituteList['MONEY']; // 生成支付记录 OrderService::createPayConstituteDetail($params, $payDetail); } $params['order_amount_pay'] = $orderAmountPay; } if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'CASH') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } if (isset($constituteList['CASH'])) { $params['order_amount_pay'] = $constituteList['CASH']; $params['pay_category'] = $params['join_order_member_id'] . '-CASH'; } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); // 生成支付记录 OrderService::createPayConstituteDetail($params, $payDetail); $params['order_amount_pay'] = $orderAmountPay; $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户 $cardNbr = $params['card_nbr']; if (!$cardNbr) { Db::rollBack(); return json_fail('账户异常'); } $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_nbr', $cardNbr) ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } // 储值卡账户支付金额 if (isset($constituteList['CARD'])) { $params['order_amount_pay'] = $constituteList['CARD']; $params['pay_category'] = $cardNbr; } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); // 生成支付记录 OrderService::createPayConstituteDetail($params, $payDetail); $params['order_amount_pay'] = $orderAmountPay; $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码 if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) { // 付款码支付金额 $params['order_amount_pay'] = $constituteList['QRCODE']; // 调支付 $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $order->order_status_system = 'PAYING'; $order->order_status_payment = 'PENDING'; $order->order_is_complete = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $order->order_status_system = $systemStatus; $order->order_status_payment = 'SUCCESS'; } } else { Db::rollBack(); return json_fail('付款码无效'); } } // 生成支付记录 OrderService::createPayConstituteDetail($params, $payDetail); // 账户支付的金额 $params['order_amount_pay'] = $orderAmountPay; } $orderConfigJson = []; if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); } $orderConfigJson['preferential'] = $params['preferential'] ?? ''; if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) { SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']); } $order->order_config_json = json_encode($orderConfigJson); $order->order_amount_pay = $params['order_amount_pay']; // 主订单 $order->save(); // sheet if ($order->order_status_payment == 'SUCCESS') { OrderSheet::where('join_sheet_order_id', $params['order_id'])->update([ 'order_sheet_status' => $systemStatus, ]); } // 清除paydetail 中的未支付记录 PayDetail::where('join_pay_order_id', $params['orderGroupId'])->where('pay_status', '<>', 'SUCCESS')->delete(); $writeOffDate = []; $applyData = []; // 有预约单,状态已完成 $appointment = Appointment::where('join_appointment_order_id', $params['order_id'])->first(); if ($order->order_status_payment == 'SUCCESS' && $appointment) { $writeOffDate = OrderService::generateWriteOffData($params); $applyData = OrderService::generateAppointmentApplyData($params); $appointment->appointment_status = 'DONE'; $appointment->appointment_done_datetime = date('Y-m-d H:i:s'); $appointment->appointment_done_json = json_encode($writeOffDate); if (empty($appointment->appointment_apply_datetime)) { $appointment->appointment_apply_datetime = date('Y-m-d H:i:s'); } if (empty($appointment->appointment_apply_json)) { $appointment->appointment_apply_json = json_encode($applyData); } if (empty($appointment->appointment_datetime)) { $appointment->appointment_datetime = date('Y-m-d'); } $appointment->save(); } Db::commit(); // 打小票 if (!empty($premises) && $params['goods_classify'] == "MEALS") { dump('payCons 打小票'); $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first(); if (!empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); if (isset($deptExtendJson['printer'])) { foreach ($deptExtendJson['printer'] as $key => $item) { if (strpos($key, '结算') !== false && $order->order_status_payment == 'SUCCESS') { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['order_id'] ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } } } } } if ($order->order_status_payment != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]); } _syslog("订单", "订单支付成功"); return json_success('支付成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "订单支付失败"); return json_fail('支付失败'); } } /** * 删除订单 */ public function delete(Request $request): Response { $params = $request->post(); Db::beginTransaction(); try { $order = Order::where('order_id', $params['order_id']) ->where('order_status_system', 'CANCEL') ->orWhere(function ($query) use ($params) { $query->whereIn('order_status_system', ['WAITING', 'SENDING'])->where('order_category', 'SYSTEM')->where('order_id', $params['order_id']); }) ->first(); if (!$order) { return json_fail('此订单不允许删除'); } $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first(); if ($payDetail) { $payType = explode('-', $payDetail->pay_prepayid); // 余额支付 if (isset($payType[1]) && $payType[1] == 'CASH') { $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id) ->where('member_account_classify', 'CASH') ->first(); $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount; $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount; $memberAccount->save(); } // 员工福利支付 if (isset($payType[1]) && $payType[1] == 'WELFARE') { $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id) ->where('member_account_classify', 'WELFARE') ->first(); $memberAccount->member_account_expend = $memberAccount->member_account_expend - $payDetail->pay_amount; $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payDetail->pay_amount; $memberAccount->save(); } // 删支付记录 $payDetail->delete(); } // 删收货信息 OrderExpress::where('join_express_order_id', $params['order_id'])->delete(); // 删订单详情 OrderSheet::where('join_sheet_order_id', $params['order_id'])->delete(); // 删主订单 Order::where('order_id', $params['order_id'])->delete(); Db::commit(); _syslog("订单", "删除订单成功"); return json_success('删除订单成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "删除订单失败"); return json_fail('删除订单失败'); } } /** * 取消订单 */ public function cancelOrder(Request $request) { $orderId = $request->post('order_id', ''); if (!$orderId) { return json_fail('参数异常'); } Db::beginTransaction(); try { $order = Order::where('order_id', $orderId)->first(); if (empty($order)) { return json_fail('订单数据异常'); } if ($order->order_status_system != 'PAYING' || $order->order_category != 'DISHES') { return json_fail('仅未支付的餐饮订单可以取消!'); } // sheet 表 OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'CANCEL']); // payDetail 表 PayDetail::where('join_pay_order_id', $order->order_groupby)->update([ 'pay_status' => 'CANCEL', 'pay_extend_json' => json_encode(['cancel_times' => date('Y-m-d H:i:s')]) ]); if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) { SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']); } } $order->order_is_complete = 'Y'; $order->order_status_system = 'CANCEL'; $order->order_status_payment = 'CANCEL'; $order->save(); Db::commit(); return json_success(''); } catch (\Exception $e) { Db::rollBack(); return json_fail('订单取消失败'); } } public function insert(Request $request): Response { $params = $request->post(); // 判断餐品是否连带着服务或实体 $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify')); if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) { return json_fail('餐饮餐品不支持和其他类型的产品一起下单'); } if (in_array('MEALS', $goodsClassifys)) { $params['submit_goods_classify'] = 'MEALS'; } if (!empty($params['dept_premises_id'])) { $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first(); } $params['goods_classify'] = $goodsClassifys[0]; Db::beginTransaction(); try { // 存储优惠信息 $params['order_discount_json'] = json_encode($this->discountRecord([], $params)); // 验证库存 foreach ($params['goodsContentList'] as $goods) { // 减库存,规格和总库存 if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') { $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first(); $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) { $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr']; } if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) { throw new BusinessException('库存不足'); } } $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr']; if ($goodsRunning->goods_running_storage < 0) { throw new BusinessException('库存不足'); } } // 余额、福利、储值卡 验证短信 if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['CASH', 'CARD', 'WELFARE'])) { $code = $params['sms_code']; if (!$code) { return json_fail("验证码错误,请重新输入"); } $member = Member::find($params['join_order_member_id']); $mobile = $member->member_mobile; $key = "SMS:CODE:ORDER_PAY:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code && $code != '123456') { return json_fail("验证码错误,请重新输入"); } Redis::del($key); } // 验证线下付款密码 if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE','MONEY'])) { $password = $params['offline_password']; if ($password != '666888') { return json_fail("密码错误,请重新输入"); } } // 下单账户 if (empty($params['join_order_member_id']) && !empty($params['mobile'])) { if (Member::where('member_mobile', $params['mobile'])->exists()) { Db::rollBack(); return json_fail('会员已存在'); } $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('YmdHis') . random_string(6, 'up'); // 创建会员 MemberService::createMember($params); } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) { $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id'); } if (empty($params['join_order_member_id'])) { Db::rollBack(); return json_fail("检查下单账户"); } $qrcodePayAmount = 0; $params['orderId'] = 'OD' . date('YmdHis') . random_string(6, 'up'); $params['orderGroupId'] = 'OD' . date('YmdHis') . random_string(6, 'up'); $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up'); $systemStatus = 'SENDING'; // 待发货 // 立即结算 if ($params['settlement_now'] == 'Y') { $params['order_is_complete'] = 'Y'; if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) { $systemStatus = 'DONE'; } } if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) { if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])){ $params['pay_category'] = $params['pay_category_sub']; } $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CASH') { // 余额支付 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'CASH') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { return json_fail('账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); if ($params['pay_constitute'] == 'N') { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'WELFARE') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } $account->member_account_surplus = floatval($account->member_account_surplus); if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)) { $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus; $params['order_amount_pay'] = $account->member_account_surplus; } if ($params['pay_constitute'] == 'N') { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } // 福利账户 300 、 700 if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS'])) { $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->whereIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES']) ->get() ->toArray(); $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id'); $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->where('pay_category', 'REFUND') ->get() ->toArray(); $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id'); $paySum = 0; foreach ($payDetailArray as $key => $item) { if (isset($refundPayDetailArray[$key])) { $paySum = $paySum + ($item - $refundPayDetailArray[$key]); continue; } $paySum = $paySum + $item; } if ($params['pay_constitute'] == 'N' && 700 - $paySum < $params['order_amount_pay']) { Db::rollBack(); return json_fail('超出福利限额'); } else if ($params['pay_constitute'] == 'Y' && 700 - $paySum < $params['order_amount_pay']) { $qrcodePayAmount = $params['order_amount_pay'] - (700 - $paySum); $params['order_amount_pay'] = (700 - $paySum); } } else { $payDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->whereNotIn('pay_category', ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'DESHES', 'REFUND', 'RECHARGE']) ->get() ->toArray(); $payDetailArray = array_column($payDetails, 'pay_amount', 'join_pay_order_id'); $refundPayDetails = PayDetail::where('join_pay_member_id', $params['join_order_member_id']) ->where('pay_status', 'SUCCESS') ->where('pay_prepayid', $params['join_order_member_id'] . '-WELFARE') ->where('pay_category', 'REFUND') ->get() ->toArray(); $refundPayDetailArray = array_column($refundPayDetails, 'pay_amount', 'join_pay_order_id'); $paySum = 0; foreach ($payDetailArray as $key => $item) { if (isset($refundPayDetailArray[$key])) { $paySum = $paySum + ($item - $refundPayDetailArray[$key]); continue; } $paySum = $paySum + $item; } if ($params['pay_constitute'] == 'N' && 300 - $paySum < $params['order_amount_pay']) { Db::rollBack(); return json_fail('超出福利限额'); } else if ($params['pay_constitute'] == 'Y' && 300 - $paySum < $params['order_amount_pay']) { $qrcodePayAmount = $params['order_amount_pay'] - (300 - $paySum); $params['order_amount_pay'] = (300 - $paySum); } } $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); } else if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'CARD') { // 储值卡账户 $cardNbr = $params['card_nbr']; if (!$cardNbr) { Db::rollBack(); return json_fail('账户异常'); } $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_nbr', $cardNbr) ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); if ($params['pay_constitute'] == 'N') { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) { // 付款码 // 提交过来的支付分类 $submitPayCategory = $params['pay_category']; // 账户支付的金额 $accountAmount = $params['order_amount_pay']; if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) { // 组合支付,支付金额改成需要付款码需要支付的金额 $params['order_amount_pay'] = $qrcodePayAmount; } if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount <= 0) { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } // 不组合或者组合后需要付款码的金额>0 if ($params['pay_constitute'] == 'N' || ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0)) { $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else { Db::rollBack(); return json_fail('付款码无效'); } // 组合支付,追加加一条支付记录 pay_detail if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0 && $params['order_status_payment'] == 'SUCCESS') { $insertPayDetailData = [ 'join_pay_member_id' => $params['join_order_member_id'], 'join_pay_order_id' => $params['orderGroupId'], 'pay_status' => 'SUCCESS', 'pay_category' => $params['goods_classify'], 'pay_amount' => $params['order_amount_pay'], 'pay_paytimes' => date('Y-m-d H:i:s'), 'pay_prepayid' => $params['pay_category'], 'pay_json_request' => json_encode($params), 'pay_json_response' => $params['pay_json_response'], 'pay_addtimes' => time() ]; PayDetail::insert($insertPayDetailData); // 组合支付,还原提交的支付分类 $params['pay_category'] = $submitPayCategory; } // 账户支付的金额 $params['order_amount_pay'] = $accountAmount; } } $orderConfigJson = []; // 优惠 if (!empty($params['preferential'])) { $orderConfigJson['preferential'] = $params['preferential']; } // 配送方式 if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店 $orderConfigJson['premises'] = $params['dept_premises_id']; } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') { // $params['order_express_json'] = json_encode([ // 'express' => 'Y', // ]); } $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount; if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) { // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first(); if (!$premises) { Db::rollBack(); return json_fail('门店不存在,请重新选择'); } $params['submit_premises_id'] = $premises->dept_id; } if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_premises_id'])) { $table = ''; if (!empty($params['dept_table_id'])) { $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first(); } $orderConfigJson['premises'] = $params['dept_premises_id']; $orderConfigJson['dept'] = $premises->dept_id ?? 0; $orderConfigJson['reach'] = "00:00"; $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null; $orderConfigJson['express'] = "到店吃"; $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null; if (!empty($params['eat'])) { $orderConfigJson['eat'] = $params['eat'] ?? null; } if ($params['settlement_now'] == 'N' && !empty($params['dept_table_id'])) { // 桌台设为使用中 SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->update(['dept_status' => 'USING']); } } $params['order_config_json'] = json_encode($orderConfigJson); // 写入主订单 $this->insertMain($params); // 订单详情 $sheetId = $this->insertSheet($params); // 支付记录 $params['order_amount_pay'] = $params['order_amount_pay'] - $qrcodePayAmount; $this->insertPayDetail($params); $params['order_express_goods'] = json_encode(['sheet' => [$sheetId]]); if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') { $params['order_express_type'] = '配送'; // 入配送 $this->saveExpress($params); } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') { $params['order_express_type'] = '自提'; if (!$premises) { throw new BusinessException('自提门店不存在'); } $params['order_express_city'] = $premises->dept_city; $params['order_express_address'] = $premises->dept_address; $params['order_express_telephone'] = $premises->dept_telephone; $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]); $this->saveExpress($params); } else if (isset($params['delivery']) && $params['delivery'] == 'ARRIVAL') { $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first(); $params['order_express_type'] = '到店'; if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $params['order_express_type'] = '堂食'; } if (!$premises) { throw new BusinessException('门店不存在'); } $params['order_express_city'] = $premises->dept_city; $params['order_express_address'] = $premises->dept_address; $params['order_express_telephone'] = $premises->dept_telephone; $this->saveExpress($params); } // 买的单个服务 // $writeOffDate = []; // $applyData = []; // // 服务已完成,生成核销数据 // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) { // $writeOffDate = OrderService::generateWriteOffData($params); // $applyData = OrderService::generateAppointmentApplyData($params); // } // if (in_array($goods['goods_classify'],['SERVICE','CHNMED','CHNNCD'])) { // // 预约表 // for ($i = 0; $i < intval($params['order_sheet_num']); $i++) { // $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(6, 'up'); // // 入预约记录 // $this->insertAppointment($params, $writeOffDate,$applyData); // } // $goods['skuId'] = $params['join_sheet_goods_sku_id']; // $goods['category'] = $goods['goods_classify']; // // 权益表 // $this->insertMemberBenefit($params, $goods); // } elseif ($goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个 // $params['packageId'] = $params['join_sheet_goods_id']; // $components = GoodsComponent::with([ // 'goods' => function ($query) { // $query->select('goods_id', 'goods_name', 'goods_classify'); // } // ])->where('join_component_master_goods_id', $params['join_sheet_goods_id']) // ->get() // ->toArray(); // $orderSheetNum = $params['order_sheet_num']; // foreach ($components as $component) { // $params['order_sheet_num'] = $orderSheetNum; // $componentJson = json_decode($component['goods_component_json'], true); // $params['join_sheet_goods_sku_id'] = $componentJson['sku_id']; // $params['join_sheet_goods_id'] = $component['join_component_goods_id']; // $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up'); // $params['order_sheet_num'] = $params['order_sheet_num'] * $componentJson['nbr']; // for ($i = 0; $i < intval($params['order_sheet_num']); $i++) { // $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(8, 'up'); // // 入预约记录 // $this->insertAppointment($params, $writeOffDate); // } // $goods['goods_id'] = $component['join_component_goods_id']; // $goods['goods_name'] = $component['goods']['goods_name']; // $goods['goods_classify'] = $component['goods']['goods_classify']; // $goods['skuId'] = $params['join_sheet_goods_sku_id']; // $goods['category'] = 'SERVICE'; // // 权益表 // $this->insertMemberBenefit($params, $goods); // } // } // 2.4W 康养城 if ($params['goods_classify'] == 'VIP' && $params['order_status_payment'] == 'SUCCESS') { $params['member_id'] = $params['join_order_member_id']; Event::dispatch('order.kangyangCityVIP.grant', $params); } Db::commit(); // 打小票 if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { dump("insert 打小票"); if ($premises->dept_category != '餐厅') { $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first(); } else { $restaurant = $premises; } if (!empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); if (isset($deptExtendJson['printer'])) { foreach ($deptExtendJson['printer'] as $key => $item) { if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['orderId'], 'order_batch' => '' ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['orderId'], 'order_batch' => '' ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } } } } } if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]); } _syslog("订单", "创建订单成功"); return json_success('创建订单成功'); } catch (BusinessException $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", $e->getMessage()); return json_fail($e->getMessage()); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", "创建订单失败"); return json_fail('创建订单失败'); } } /** * 组合支付下单 */ public function insertConstitute(Request $request): Response { $params = $request->post(); // 判断餐品是否连带着服务或实体 $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify')); if (in_array('MEALS', $goodsClassifys) && count($goodsClassifys) > 1) { return json_fail('餐饮餐品不支持和其他类型的产品一起下单'); } if (in_array('MEALS', $goodsClassifys)) { $params['submit_goods_classify'] = 'MEALS'; } if (!empty($params['dept_premises_id'])) { $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first(); } Db::beginTransaction(); try { // 存储优惠信息 $params['order_discount_json'] = json_encode($this->discountRecord([], $params)); $orderAmountPay = $params['order_amount_pay']; $constituteList = array_column($params['pay_category_constitute_list'], 'amount', 'category'); // 验证金额 $constituteAmount = 0; foreach ($params['pay_category_constitute_list'] as $item) { $constituteAmount = $constituteAmount + $item['amount']; } if ($params['order_amount_pay'] != $constituteAmount) { return json_fail('组合支付金额与应付金额不一致'); } $params['goods_classify'] = $goodsClassifys[0]; // 验证库存 OrderService::checkGoodsStorage($params); // 余额、福利、储值卡 验证短信 if (!empty($params['pay_category_constitute']) && !in_array('OFFLINE', $params['pay_category_constitute']) && !in_array('MONEY', $params['pay_category_constitute']) && !in_array('QRCODE', $params['pay_category_constitute']) && (in_array('CASH', $params['pay_category_constitute']) || in_array('CARD', $params['pay_category_constitute']) || in_array('WELFARE', $params['pay_category_constitute']))) { $code = $params['sms_code']; if (!$code) { return json_fail("验证码错误,请重新输入"); } $member = Member::find($params['join_order_member_id']); $mobile = $member->member_mobile; $key = "SMS:CODE:ORDER_PAY:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code && $code != '123456') { return json_fail("验证码错误,请重新输入"); } Redis::del($key); } // 验证线下付款密码 if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute']) || in_array('MONEY', $params['pay_category_constitute'])) { $password = $params['offline_password']; if ($password != '666888') { return json_fail("密码错误,请重新输入"); } } // 下单账户 if (empty($params['join_order_member_id']) && !empty($params['mobile'])) { if (Member::where('member_mobile', $params['mobile'])->exists()) { Db::rollBack(); return json_fail('会员已存在'); } $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('YmdHis') . random_string(6, 'up'); // 创建会员 MemberService::createMember($params); } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) { $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id'); } if (empty($params['join_order_member_id'])) { Db::rollBack(); return json_fail("检查下单账户"); } $qrcodePayAmount = 0; $params['orderId'] = 'OD' . date('YmdHis') . random_string(6, 'up'); $params['orderGroupId'] = 'OD' . date('YmdHis') . random_string(6, 'up'); $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up'); $systemStatus = 'SENDING'; // 待发货 // 立即结算 if ($params['settlement_now'] == 'Y') { if (in_array($params['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'MEALS', 'VIP'])) { $params['order_is_complete'] = 'Y'; $systemStatus = 'DONE'; } } if (!empty($params['pay_category_constitute']) && in_array('OFFLINE', $params['pay_category_constitute'])) { // 线下支付 $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; $params['pay_category'] = 'OFFLINE'; // 线下支付金额 if (isset($constituteList['OFFLINE'])) { $params['order_amount_pay'] = $constituteList['OFFLINE']; // 生成支付记录 OrderService::createPayDetail($params); } $params['order_amount_pay'] = $orderAmountPay; } if (!empty($params['pay_category_constitute']) && in_array('MONEY', $params['pay_category_constitute'])) { // 现金支付 $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; $params['pay_category'] = 'MONEY'; // 现金支付金额 if (isset($constituteList['MONEY'])) { $params['order_amount_pay'] = $constituteList['MONEY']; // 生成支付记录 OrderService::createPayDetail($params); } $params['order_amount_pay'] = $orderAmountPay; } if (!empty($params['pay_category_constitute']) && in_array('CASH', $params['pay_category_constitute'])) { // 余额支付 $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_classify', 'CASH') ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { return json_fail('账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; if (isset($constituteList['CASH'])) { $params['order_amount_pay'] = $constituteList['CASH']; $params['pay_category'] = $params['join_order_member_id'] . '-CASH'; } if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; // 生成支付记录 OrderService::createPayDetail($params); $params['order_amount_pay'] = $orderAmountPay; } // if ($params['settlement_now'] == 'Y' && $params['pay_category'] == 'WELFARE') { // 福利账户 // $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) // ->where('member_account_classify', 'WELFARE') // ->where('member_account_status', 'ACTIVED') // ->first(); // if (!$account) { // Db::rollBack(); // return json_fail('账户异常'); // } // $account->member_account_surplus = floatval($account->member_account_surplus); // if ($params['pay_constitute'] == 'N' && ($params['order_amount_pay'] > $account->member_account_surplus)) { // Db::rollBack(); // return json_fail('账户余额不足'); // } // if($params['pay_constitute'] == 'Y' && ($params['order_amount_pay'] > $account->member_account_surplus)){ // $qrcodePayAmount = $params['order_amount_pay'] - $account->member_account_surplus; // $params['order_amount_pay'] = $account->member_account_surplus; // } // if ($params['pay_constitute'] == 'N') { // $params['order_status_system'] = $systemStatus; // $params['order_status_payment'] = 'SUCCESS'; // } // $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; // $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; // $account->save(); // } if (!empty($params['pay_category_constitute']) && in_array('CARD', $params['pay_category_constitute'])) { // 储值卡账户 $cardNbr = $params['card_nbr']; if (!$cardNbr) { Db::rollBack(); return json_fail('储值卡账户异常'); } $account = MemberAccount::where('join_account_member_id', $params['join_order_member_id']) ->where('member_account_nbr', $cardNbr) ->where('member_account_status', 'ACTIVED') ->first(); if (!$account) { Db::rollBack(); return json_fail('储值卡账户异常'); } $amount = $account->member_account_surplus + $account->member_account_added; // 储值卡账户支付金额 if (isset($constituteList['CARD'])) { $params['order_amount_pay'] = $constituteList['CARD']; $params['pay_category'] = $cardNbr; } if ($params['pay_constitute'] == 'N' && (!$account || $params['order_amount_pay'] > $amount)) { Db::rollBack(); return json_fail('储值卡账户余额不足'); } if ($params['pay_constitute'] == 'Y' && (!$account || $params['order_amount_pay'] > $amount)) { $qrcodePayAmount = $params['order_amount_pay'] - $amount; $params['order_amount_pay'] = $amount; } if ($params['order_amount_pay'] > $account->member_account_surplus) { $cut = $account->member_account_added - ($params['order_amount_pay'] - $account->member_account_surplus); $account->member_account_surplus = 0; $account->member_account_added = $cut; } else { $account->member_account_surplus = $account->member_account_surplus - $params['order_amount_pay']; } $account->member_account_expend = $account->member_account_expend + $params['order_amount_pay']; $account->save(); $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; // 生成支付记录 OrderService::createPayDetail($params); $params['order_amount_pay'] = $orderAmountPay; } //!empty($params['pay_category_constitute']) && in_array('CARD',$params['pay_category_constitute']) // if(($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])){ // 付款码 if (!empty($params['pay_category_constitute']) && in_array('QRCODE', $params['pay_category_constitute']) && !empty($params['qrcode_nbr'])) { // 付款码 // 需要付款码的金额>0 if (isset($constituteList['QRCODE']) && $constituteList['QRCODE'] > 0) { // 付款码支付金额 $params['order_amount_pay'] = $constituteList['QRCODE']; // 调支付 $result = OrderService::qrcodePay($params); $result = json_encode($result); $params['pay_json_response'] = $result; $result = json_decode($result, true); $prefix = substr($params['qrcode_nbr'], 0, 2); if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $params['pay_category'] = 'WXPAY'; if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $params['pay_category'] = 'ALIPAY'; if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) { $params['order_status_system'] = 'PAYING'; $params['order_status_payment'] = 'PENDING'; $params['order_is_complete'] = 'N'; // Db::rollBack(); // return json_fail('支付失败'); } else { $params['order_status_system'] = $systemStatus; $params['order_status_payment'] = 'SUCCESS'; } } else { Db::rollBack(); return json_fail('二维码错误'); } // 生成支付记录 OrderService::createPayDetail($params); // 账户支付的金额 $params['order_amount_pay'] = $orderAmountPay; } } $orderConfigJson = []; // 优惠 if (!empty($params['preferential'])) { $orderConfigJson['preferential'] = $params['preferential']; } // 配送方式 if (isset($params['delivery']) && ($params['delivery'] == 'PICKUP' || $params['delivery'] == 'ARRIVAL')) { // 自提/ 到店 $orderConfigJson['premises'] = $params['dept_premises_id']; } else if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') { // $params['order_express_json'] = json_encode([ // 'express' => 'Y', // ]); } $params['order_amount_pay'] = $params['order_amount_pay'] + $qrcodePayAmount; if (isset($params['delivery']) && in_array($params['delivery'], ['PICKUP', 'ARRIVAL']) && !empty($params['dept_premises_id'])) { // $premises = SysDept::where('dept_name',$params['dept_premises_id'])->where('dept_category','营业场所')->first(); if (!$premises) { Db::rollBack(); return json_fail('门店不存在,请重新选择'); } $params['submit_premises_id'] = $premises->dept_id; } if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS' && !empty($params['dept_table_id'])) { $table = SysDept::where('dept_id', $params['dept_table_id'])->where('dept_category', '桌台')->first(); $orderConfigJson['premises'] = $params['dept_premises_id']; $orderConfigJson['dept'] = $premises->dept_id; $orderConfigJson['reach'] = "00:00"; $orderConfigJson['table'] = !empty($table) ? $table->dept_name : null; $orderConfigJson['express'] = "堂食"; $orderConfigJson['tableid'] = $params['dept_table_id'] ?? null; if (!empty($params['eat'])) { $orderConfigJson['eat'] = $params['eat'] ?? null; } } $params['order_config_json'] = json_encode($orderConfigJson); // 写入主订单 $this->insertMain($params); // 订单详情 $sheetId = $this->insertSheet($params); $params['order_express_goods'] = json_encode(['sheet' => $sheetId]); if (isset($params['delivery']) && $params['delivery'] == 'LOGISTICS') { $params['order_express_type'] = '配送'; // 入配送 $this->saveExpress($params); } else if (isset($params['delivery']) && $params['delivery'] == 'PICKUP') { $params['order_express_type'] = '自提'; if (!$premises) { throw new BusinessException('自提门店不存在'); } $params['order_express_city'] = $premises->dept_city; $params['order_express_address'] = $premises->dept_address; $params['order_express_telephone'] = $premises->dept_telephone; $params['order_express_extend_json'] = json_encode(['pick_code' => random_string(4, 'number')]); $this->saveExpress($params); } else if ($params['delivery'] == 'ARRIVAL') { $premises = SysDept::where('dept_name', $params['dept_premises_id'])->first(); $params['order_express_type'] = '到店'; if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $params['order_express_type'] = '堂食'; } if (!$premises) { throw new BusinessException('门店不存在'); } $params['order_express_city'] = $premises->dept_city; $params['order_express_address'] = $premises->dept_address; $params['order_express_telephone'] = $premises->dept_telephone; $this->saveExpress($params); } // 买的单个服务 // $writeOffDate = []; // $applyData = []; // // 服务已完成,生成核销数据 // if ($params['order_status_payment'] == 'SUCCESS' && in_array($goods['goods_classify'], ['SERVICE','CHNMED','CHNNCD', 'PACKAGE'])) { // $writeOffDate = OrderService::generateWriteOffData($params); // $applyData = OrderService::generateAppointmentApplyData($params); // } // if (in_array($goods['goods_classify'],['SERVICE','CHNMED','CHNNCD'])) { // // 预约表 // for ($i = 0; $i < intval($params['order_sheet_num']); $i++) { // $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(6, 'up'); // // 入预约记录 // $this->insertAppointment($params, $writeOffDate,$applyData); // } // $goods['skuId'] = $params['join_sheet_goods_sku_id']; // $goods['category'] = $goods['goods_classify']; // // 权益表 // $this->insertMemberBenefit($params, $goods); // } elseif ($goods['goods_classify'] == 'PACKAGE') { // 一个套餐买多个 // $params['packageId'] = $params['join_sheet_goods_id']; // $components = GoodsComponent::with([ // 'goods' => function ($query) { // $query->select('goods_id', 'goods_name', 'goods_classify'); // } // ])->where('join_component_master_goods_id', $params['join_sheet_goods_id']) // ->get() // ->toArray(); // $orderSheetNum = $params['order_sheet_num']; // foreach ($components as $component) { // $params['order_sheet_num'] = $orderSheetNum; // $componentJson = json_decode($component['goods_component_json'], true); // $params['join_sheet_goods_sku_id'] = $componentJson['sku_id']; // $params['join_sheet_goods_id'] = $component['join_component_goods_id']; // $params['benefitId'] = 'BF' . date('YmdHis') . random_string(6, 'up'); // $params['order_sheet_num'] = $params['order_sheet_num'] * $componentJson['nbr']; // for ($i = 0; $i < intval($params['order_sheet_num']); $i++) { // $params['appointmentId'] = 'AP' . date('YmdHis') . random_string(8, 'up'); // // 入预约记录 // $this->insertAppointment($params, $writeOffDate); // } // $goods['goods_id'] = $component['join_component_goods_id']; // $goods['goods_name'] = $component['goods']['goods_name']; // $goods['goods_classify'] = $component['goods']['goods_classify']; // $goods['skuId'] = $params['join_sheet_goods_sku_id']; // $goods['category'] = 'SERVICE'; // // 权益表 // $this->insertMemberBenefit($params, $goods); // } // } // 2.4W 康养城 if ($params['goods_classify'] == 'VIP' && intval($params['order_amount_pay']) == 24000 && $params['order_status_payment'] == 'SUCCESS') { $params['member_id'] = $params['join_order_member_id']; Event::dispatch('order.kangyangCityVIP.grant', $params); } Db::commit(); // 打小票 if (!empty($premises) && isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { // if (!empty($premises)){ if ($premises->dept_category != '餐厅') { $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first(); } else { $restaurant = $premises; } if (!empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); if (isset($deptExtendJson['printer'])) { foreach ($deptExtendJson['printer'] as $key => $item) { if (strpos($key, '结算') !== false && $params['order_status_payment'] == 'SUCCESS') { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['orderId'], 'order_batch' => '' ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['orderId'], 'order_batch' => '' ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } } } } } if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') { _syslog("订单", "支付异常,检查是否有轮询"); return json_throw(2001, '支付异常', ['order_id' => $params['orderId']]); } _syslog("订单", "创建订单成功"); return json_success('创建订单成功'); } catch (BusinessException $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", $e->getMessage()); return json_fail($e->getMessage()); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("订单", "创建订单失败"); return json_fail('创建订单失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:30 * * @param $params * @return void * @throws BusinessException */ public function insertMain($params) { try { $orderCategory = 'NORMAL'; if (!empty($params['order_category'])) { $orderCategory = $params['order_category']; } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $orderCategory = 'DISHES'; } else if (isset($params['goods_classify'])) { $orderCategory = $params['goods_classify']; } if (empty($params['order_extend_json'])) { $params['order_extend_json'] = []; } else { if (is_json($params['order_extend_json'])) { $params['order_extend_json'] = json_decode($params['order_extend_json'], true); } } // 推荐人 $params['order_extend_json']['referee'] = $params['referee'] ?? ''; $data = [ 'order_id' => $params['orderId'], 'order_groupby' => $params['orderGroupId'], 'join_order_member_id' => $params['join_order_member_id'], 'order_name' => date('Y-m-d H:i:s') . '-订单', 'order_amount_total' => $params['order_amount_total'], 'order_amount_pay' => $params['order_amount_pay'], 'order_category' => $orderCategory, 'order_is_complete' => $params['order_is_complete'] ?? 'N', 'order_status_system' => $params['order_status_system'], 'order_status_payment' => $params['order_status_payment'], 'order_status_storage' => $params['order_status_storage'], 'order_platform' => $params['order_platform'], 'order_remark' => $params['order_remark'] ?? '', 'order_discount_json' => $params['order_discount_json'], 'order_config_json' => $params['order_config_json'] ?? '[]', 'order_express_json' => $params['order_express_json'] ?? '[]', 'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]', 'order_addtimes' => time() ]; Order::insert($data); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('订单创建信息失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:25 * * @param $params * @return void * @throws BusinessException */ public function insertSheet($params) { try { $orderSheetIds = []; foreach ($params['goodsContentList'] as $goods) { //{"unit": "份", "table": null, "premises": "15"} $price = floatval($goods['goods_sales_price']); $extendJson['unit'] = $goods['sku_name']; if (isset($params['submit_premises_id'])) { $extendJson['premises'] = $params['submit_premises_id']; } if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') { $extendJson['table'] = null; } $data = [ 'join_sheet_member_id' => $params['join_order_member_id'], 'join_sheet_order_id' => $params['orderId'], 'join_sheet_goods_id' => $goods['goods_id'], 'join_sheet_goods_sku_id' => $goods['sku_id'], 'order_sheet_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING', 'order_sheet_category' => (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') ? 'DISHES' : 'NORMAL', 'order_sheet_num' => $goods['nbr'], 'order_sheet_price' => $goods['goods_sales_price'], 'order_sheet_amount' => $price * $goods['nbr'], 'order_sheet_pay' => $price * $goods['nbr'], 'order_sheet_task_status' => 'NONE', 'order_sheet_remark' => $params['order_remark'] ?? '', 'order_sheet_addtimes' => time(), 'order_sheet_extend_json' => json_encode($extendJson) ]; $orderSheetId = OrderSheet::insertGetId($data); $orderSheetIds[] = $orderSheetId; // 减库存,规格和总库存 if (!isset($params['submit_goods_classify']) || $params['submit_goods_classify'] != 'MEALS') { $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first(); $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) { $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr']; } if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) { throw new BusinessException('库存不足'); } $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson); $goodsSku->save(); } $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr']; if ($goodsRunning->goods_running_storage < 0) { throw new BusinessException('库存不足'); } $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr']; $goodsRunning->save(); } return $orderSheetIds; } catch (\support\exception\BusinessException $e) { dump($e->getMessage() . '||' . $e->getLine()); throw new BusinessException($e->getMessage()); } catch (\Exception $e) { dump($e->getMessage() . '||' . $e->getLine()); throw new BusinessException('订单创建失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:35 * * @param $params * @return void * @throws BusinessException */ public function insertPayDetail($params) { try { if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) { $payPrepayid = $params['pay_category']; } else if ($params['pay_category'] == 'OFFLINE') { $payPrepayid = 'OFFLINE'; } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') { $payPrepayid = 'OFFLINE_ALIPAY'; } else if ($params['pay_category'] == 'OFFLINE_WXPAY') { $payPrepayid = 'OFFLINE_WXPAY'; } else if ($params['pay_category'] == 'MONEY') { $payPrepayid = 'MONEY'; } else { $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category']; } $data = [ 'join_pay_member_id' => $params['join_order_member_id'], 'join_pay_order_id' => $params['orderGroupId'], 'pay_status' => $params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING', 'pay_category' => $params['goods_classify'], 'pay_amount' => $params['order_amount_pay'], 'pay_prepayid' => $payPrepayid, 'pay_paytimes' => date('Y-m-d H:i:s'), 'pay_json_request' => json_encode($params), 'pay_json_response' => $params['pay_json_response'] ?? '[]', 'pay_remark' => $params['order_remark'] ?? '', 'pay_addtimes' => time() ]; PayDetail::insert($data); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('创建支付记录失败'); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 10:50 * * @param $params * @return void * @throws BusinessException */ public function insertAppointment($params, $writeOffDate, $applyData = []) { try { $data = [ 'appointment_id' => $params['appointmentId'], 'join_appointment_member_id' => $params['join_order_member_id'], 'join_appointment_goods_id' => $params['join_sheet_goods_id'], 'join_appointment_goods_sku_id' => $params['join_sheet_goods_sku_id'], 'join_appointment_order_id' => $params['orderId'], 'join_appointment_member_benefit_id' => $params['benefitId'], 'appointment_classify' => $params['goods_classify'], 'appointment_status' => $params['order_status_system'] == 'DONE' ? 'DONE' : 'INIT', 'appointment_category' => 'NORMAL', 'appointment_platform' => 'SYSTEM', 'appointment_addtimes' => time(), 'appointment_datetime' => $params['order_status_system'] == 'DONE' ? date('Y-m-d') : '', 'appointment_apply_datetime' => $params['order_status_system'] == 'DONE' ? date('Y-m-d H:i:s') : '', 'appointment_apply_json' => $params['order_status_system'] == 'DONE' && $applyData ? json_encode($applyData) : '[]', 'appointment_done_datetime' => $params['order_status_system'] == 'DONE' ? date('Y-m-d H:i:s') : '', 'appointment_remark' => $params['order_remark'] ?? '', 'appointment_done_json' => $params['order_status_system'] == 'DONE' && $writeOffDate ? json_encode($writeOffDate) : '[]' ]; Appointment::insert($data); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException("创建权益记录失败"); } } /** * @Desc * @Author Gorden * @Date 2024/6/7 11:05 * * @param $params * @param $goods * @return void * @throws BusinessException */ public function insertMemberBenefit($params, $goods) { try { $data = [ 'member_benefit_id' => $params['benefitId'], 'join_benefit_member_id' => $params['join_order_member_id'], 'join_benefit_package_id' => $params['packageId'] ?? '', 'join_benefit_goods_id' => $goods['goods_id'], 'join_benefit_goods_sku_id' => $goods['skuId'] ?? '', 'join_benefit_order_id' => $params['orderId'], 'member_benefit_status' => 'ACTIVED', 'member_benefit_category' => $goods['category'], 'member_benefit_name' => $goods['goods_name'], 'member_benefit_limit_count' => $params['order_sheet_num'], 'member_benefit_used_count' => $params['order_status_system'] == 'DONE' ? $params['order_sheet_num'] : 0, 'member_benefit_remark' => $params['order_remark'] ?? '', 'member_benefit_addtimes' => time() ]; MemberBenefit::insert($data); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('创建会员权益失败'); } } public function addDishes(Request $request) { $params = $request->post(); $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify')); if (!in_array('MEALS', $goodsClassifys) || count($goodsClassifys) > 1) { return json_fail('餐饮餐品不支持和其他类型的产品一起下单'); } Db::beginTransaction(); try { $order = Order::where('order_id', $params['order_id'])->first(); $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first(); $sheet = OrderSheet::where('join_sheet_order_id', $params['order_id'])->orderBy('order_sheet_addtimes', 'DESC')->first(); $sheetComponentJson = []; if (!empty($sheet->order_sheet_component_json)) { $sheetComponentJson = json_decode($sheet->order_sheet_component_json, true); } $sheetComponentJson['order_batch'] = date('YmdHis'); foreach ($params['goodsContentList'] as $goods) { //{"unit": "份", "table": null, "premises": "15"} $price = floatval($goods['goods_sales_price']); $data = [ 'join_sheet_member_id' => $order->join_order_member_id, 'join_sheet_order_id' => $params['order_id'], 'join_sheet_goods_id' => $goods['goods_id'], 'join_sheet_goods_sku_id' => $goods['sku_id'], 'order_sheet_status' => 'PAYING', 'order_sheet_category' => 'DISHES', 'order_sheet_num' => $goods['nbr'], 'order_sheet_price' => $goods['goods_sales_price'], 'order_sheet_amount' => $price * $goods['nbr'], 'order_sheet_pay' => $price * $goods['nbr'], 'order_sheet_task_status' => 'NONE', 'order_sheet_remark' => $params['order_remark'] ?? '', 'order_sheet_component_json' => json_encode($sheetComponentJson), 'order_sheet_addtimes' => time(), 'order_sheet_extend_json' => $sheet->order_sheet_extend_json ?? '[]' ]; if ($params['give'] == 1) { $data['order_sheet_status'] = 'FREE'; $data['order_sheet_amount'] = 0; $data['order_sheet_pay'] = 0; } $order->order_amount_total = $order->order_amount_total + $data['order_sheet_amount']; $order->order_amount_pay = $order->order_amount_pay + $data['order_sheet_pay']; if ($payDetail) { $payDetail->pay_amount = $payDetail->pay_amount + $data['order_sheet_pay']; } // 减总库存 $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr']; if ($goodsRunning->goods_running_storage < 0) { throw new BusinessException('库存不足'); } $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr']; $goodsRunning->save(); OrderSheet::insertGetId($data); } $order->save(); if ($payDetail) { $payDetail->save(); } Db::commit(); // 打小票 $restaurant = SysDept::where('dept_name', $params['dept_premises_id'])->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first(); if (!empty($restaurant) && !empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); if (isset($deptExtendJson['printer'])) { foreach ($deptExtendJson['printer'] as $key => $item) { if ((strpos($key, '前台') !== false || strpos($key, '后厨') !== false)) { $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $key ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $params['order_id'], 'order_batch' => $sheetComponentJson['order_batch'] ] ] ]; $result = json_decode(http_post_json(getenv('VOTE_MENU_URL'), $voteData), true); if ($result['success'] == false) { // throw new BusinessException("加菜成功,小票打印失败,请在订单中心手动打印"); } } } } } return json_success('加菜成功'); } catch (BusinessException $e) { return json_fail($e->getMessage()); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); return json_fail('加菜失败'); } } /** * 减菜 */ public function cutMeals(Request $request) { $sheetId = $request->post('sheet_id', ''); $sheet = OrderSheet::where('order_sheet_id', $sheetId)->first(); if (!$sheet) { return json_fail("参数异常"); } if (OrderSheet::where('join_sheet_order_id', $sheet->join_sheet_order_id)->count() <= 1) { return json_fail("不能清空菜单"); } Db::beginTransaction(); try { $order = Order::where('order_id', $sheet->join_sheet_order_id)->first(); $order->order_amount_total = $order->order_amount_total - $sheet->order_sheet_amount; $order->order_amount_pay = $order->order_amount_pay - $sheet->order_sheet_pay; $order->save(); $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first(); if (!empty($payDetail)) { $payDetail->pay_amount = $payDetail->pay_amount - $sheet->order_sheet_pay; $payDetail->save(); } // $sheet->order_sheet_num = 0; // $sheet->order_sheet_amount = 0; // $sheet->order_sheet_pay = 0; $sheet->delete(); Db::commit(); return json_success('success'); } catch (\Exception $e) { Db::rollBack(); return json_fail('减菜失败'); } } /** * @Desc 发货 * @Author Gorden * @Date 2024/7/16 8:43 * * @param Request $request * @return Response */ public function delivery(Request $request) { // 验证 $validate = new OrderExpressValidate(); if (!$validate->scene('delivery')->check($request->post())) { return json_fail($validate->getError()); } $params = $request->post(); $params['order_express_addtimes'] = !empty($params['order_express_addtimes']) ? strtotime($params['order_express_addtimes']) : time(); Db::beginTransaction(); try { $expressExtendJson = []; if ($params['express_type'] == '自提') { $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first(); if (!$model) { $model = new OrderExpress(); } if (!empty($model->order_express_extend_json)) { $expressExtendJson = json_decode($model->order_express_extend_json, true); // 如果有取件码 if (isset($expressExtendJson['pick_code'])) { if (empty($params['order_express_pick_code']) || $params['order_express_pick_code'] != $expressExtendJson['pick_code']) { Db::rollBack(); return json_fail("取件码错误"); } } } $premises = SysDept::where('dept_name', $params['order_express_premises'])->first(); if (!$premises) { return json_fail("门店不存在,请重新填写"); } $params['order_express_company'] = $params['order_express_premises']; $params['order_express_city'] = str_replace(',', ' ', $premises->dept_city); $params['order_express_address'] = $premises->dept_address; $params['order_express_code'] = ''; $orderData = [ 'order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE' ]; $orderSheetData = [ 'order_sheet_status' => 'CONFIRM' ]; // 7天后自动完成 // $redis = Redis::connection(); // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days")); // $redis->sadd($key, $params['order_id']); // $model = new OrderExpress(); } else { $orderData = [ 'order_status_system' => 'RECVING', 'order_status_storage' => 'EXPRESSING' ]; $orderSheetData = [ 'order_sheet_status' => 'RECVING' ]; // 15天后自动完成订单 $redis = Redis::connection(); $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+15 days")); $redis->sadd($key, $params['order_id']); $model = OrderExpress::where('join_express_order_id', $params['order_id'])->first(); if (!$model) { $model = new OrderExpress(); // $sheet = OrderSheet::where('join_sheet_order_id', $request->post('order_id')) // ->select('join_sheet_goods_id') // ->first(); // if(!empty($sheet->order_sheet_extend_json)){ // $extendJson = json_decode($sheet->order_sheet_extend_json,true); // $address = ClientConfig::where('client_config_id',$extendJson['address_id'])->first(); // $params[''] // } } } // 该订单状态 Order::where('order_id', $request->post('order_id'))->update($orderData); // 该订单Sheet状态 OrderSheet::where('join_sheet_order_id', $request->post('order_id'))->update($orderSheetData); // 入配送记录表 $model->join_express_order_id = $params['order_id']; if (isset($params['order_express_goods'])) { $model->order_express_goods = $params['order_express_goods']; } if (isset($params['order_express_company'])) { $model->order_express_company = $params['order_express_company']; } if (isset($params['order_express_code'])) { $model->order_express_code = $params['order_express_code']; } if (isset($params['order_express_city'])) { $model->order_express_city = $params['order_express_city']; } if (isset($params['order_express_address'])) { $model->order_express_address = $params['order_express_address']; } if (isset($params['order_express_mobile'])) { $model->order_express_mobile = $params['order_express_mobile']; } if (isset($params['order_express_telephone'])) { $model->order_express_telephone = $params['order_express_telephone']; } if (isset($params['order_express_person'])) { $model->order_express_person = $params['order_express_person']; } $model->order_express_remark = $params['order_express_remark'] ?? null; $model->order_express_addtimes = $params['order_express_addtimes'] ?? time(); $expressExtendJson['delivery_time'] = date('Y-m-d H:i:s'); $model->order_express_extend_json = json_encode($expressExtendJson); $model->save(); // 事件通知 Event::dispatch('client_message.delivery', $params); Db::commit(); _syslog("订单", "发货成功"); return json_success('发货成功'); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); _syslog("订单", "发货失败"); return json_fail('发货失败'); } } public function writeOff(Request $request) { $memberId = $request->post('member_id', ''); $benefitId = $request->post('benefit_id', ''); $nbr = $request->post('nbr'); $times = $request->post('times', ''); $code = $request->post('sms_code', ''); if (!$memberId || !$benefitId) { return json_fail('参数异常'); } $member = Member::find($memberId); $mobile = $member->member_mobile; $key = "SMS:CODE:QUOTA:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code) { return json_fail("验证码错误,请重新输入"); } Redis::del($key); $benefit = MemberBenefit::where('member_benefit_id', $benefitId) ->where('join_benefit_member_id', $memberId) ->first(); if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) { return json_fail('可核销数量不足'); } if (!$times) { $times = date('Y-m-d H:i:s'); } else { $times = date('Y-m-d H:i:s', strtotime($times)); } Db::beginTransaction(); try { // 减额度 $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr; // 用完了 if ($benefit->member_benefit_limit_count <= $benefit->member_benefit_used_count) { $benefit->member_benefit_status = 'DONE'; if (!empty($benefit->join_benefit_order_id)) { Order::where('order_id', $benefit->join_benefit_order_id)->update(['order_status_system' => 'DONE']); } } $benefit->save(); // 记录核销 $params = [ 'dept_premises_id' => $request->post('dept_premises_id'), 'order_remark' => $request->post('remark'), 'write_off_member_id' => $request->post('write_off_member_id'), 'join_order_member_id' => $memberId ]; $writeOffData = OrderService::generateWriteOffData($params); $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId) ->where('appointment_status', 'INIT') ->limit($nbr) ->get(); foreach ($appointments as $appointment) { Appointment::where('appointment_id', $appointment->appointment_id)->update([ 'appointment_status' => 'DONE', 'appointment_datetime' => $times, 'appointment_apply_datetime' => $times, 'appointment_doing_datetime' => $times, 'appointment_done_datetime' => $times, 'appointment_done_json' => json_encode($writeOffData) ]); } Db::commit(); _syslog("订单", "核销成功"); return json_success('核销成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "核销失败"); return json_fail('核销失败'); } } /** * 核销餐饮 */ public function writeOffDishes(Request $request) { $orderId = $request->post('order_id', ''); $memberId = $request->post('member_id', ''); $times = $request->post('times', ''); $code = $request->post('sms_code', ''); if (!$memberId || !$orderId) { return json_fail('参数异常'); } $member = Member::find($memberId); $mobile = $member->member_mobile; $key = "SMS:CODE:DISHES:" . $mobile; $redisCode = Redis::get($key); if ($code == '' || $redisCode != $code) { return json_fail("验证码错误,请重新输入"); } Redis::del($key); if (!$times) { $times = date('Y-m-d H:i:s'); } else { $times = date('Y-m-d H:i:s', strtotime($times)); } try { Db::beginTransaction(); // 记录核销 $params = [ 'dept_premises_id' => $request->post('dept_premises_id'), 'order_remark' => $request->post('remark'), 'write_off_member_id' => $request->post('write_off_member_id'), 'join_order_member_id' => $memberId ]; $writeOffData['charge'] = OrderService::generateWriteOffData($params); $writeOffData['charge']['order_id'] = $orderId; $writeOffData['charge']['member_id'] = $memberId; $writeOffData['charge']['order_code'] = random_string(10, 'number'); $writeOffData['express'] = 'N'; $order = Order::where('order_id', $orderId)->first(); if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (isset($orderConfigJson['tableid']) && !empty($orderConfigJson['tableid'])) { SysDept::where('dept_id', $orderConfigJson['tableid'])->where('dept_category', '桌台')->update(['dept_status' => 'ACTIVED']); } } Order::where('order_id', $orderId)->update([ 'order_express_json' => json_encode($writeOffData), 'order_is_complete' => 'Y', 'order_status_system' => 'DONE' ]); OrderSheet::where('join_sheet_order_id', $orderId)->update([ 'order_sheet_status' => 'DONE' ]); Db::commit(); _syslog("订单", "核销餐品成功"); return json_success('核销成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "核销餐品失败"); return json_fail('核销失败'); } } public function writeOffBenefit(Request $request) { $memberId = $request->post('member_id', ''); $benefitList = $request->post('benefitList', []); $times = $request->post('times', ''); $code = $request->post('sms_code', ''); if (!$memberId || empty($benefitList)) { return json_fail('参数异常'); } if (empty($code)) { return json_fail('请输入验证码'); } $benefitIds = []; foreach ($benefitList as $benefit) { if (isset($benefit['nbr']) && intval($benefit['nbr']) > 0) { $benefitIds[] = $benefit['member_benefit_id']; } } if (empty($benefitIds)) { return json_fail("请填写有效的核销数量"); } $member = Member::find($memberId); $mobile = $member->member_mobile; $key = "SMS:CODE:WRITE_OFF:" . $mobile; $redisCode = Redis::get($key); if ($redisCode != $code) { return json_fail("验证码错误,请重新输入"); } $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds) ->where('join_benefit_member_id', $memberId) ->get() ->toArray(); foreach ($benefits as $benefit) { foreach ($benefitList as $list) { if ($list['member_benefit_id'] == $benefit['member_benefit_id'] && intval($list['nbr'] > ($benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']))) { return json_fail('可核销数量不足'); } } } if (!$times) { $times = date('Y-m-d H:i:s'); } else { $times = date('Y-m-d H:i:s', strtotime($times)); } try { Db::beginTransaction(); // 核销数据 $params = [ 'dept_premises_id' => $request->post('dept_premises_id'), 'order_remark' => $request->post('remark'), 'write_off_member_id' => $request->post('write_off_member_id'), 'join_order_member_id' => $memberId ]; $writeOffData = OrderService::generateWriteOffData($params); // 开始减额度 foreach ($benefits as $benefit) { foreach ($benefitList as $list) { if ($list['member_benefit_id'] == $benefit['member_benefit_id']) { $usedCount = $benefit['member_benefit_used_count'] + intval($list['nbr']); // 用完了 if ($benefit['member_benefit_limit_count'] <= $usedCount && !empty($benefit['join_benefit_order_id'])) { Order::where('order_id', $benefit['join_benefit_order_id'])->update(['order_status_system' => 'DONE']); } // 更新benefit 表 MemberBenefit::where('member_benefit_id', $benefit['member_benefit_id'])->update(['member_benefit_used_count' => $usedCount]); // 更新Appointment 表 $appointments = Appointment::where('join_appointment_member_benefit_id', $benefit['member_benefit_id']) ->where('appointment_status', 'INIT') ->limit(intval($list['nbr'])) ->get(); foreach ($appointments as $appointment) { Appointment::where('appointment_id', $appointment->appointment_id)->update([ 'appointment_status' => 'DONE', 'appointment_datetime' => $times, 'appointment_apply_datetime' => $times, 'appointment_doing_datetime' => $times, 'appointment_done_datetime' => $times, 'appointment_done_json' => json_encode($writeOffData) ]); } } } } Redis::del($key); Db::commit(); _syslog("订单", "核销成功"); return json_success('核销成功'); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); _syslog("订单", "核销失败"); return json_fail('核销失败'); } } public function myOrder(Request $request) { $page = $request->get('page', 1); $pageSize = $request->get('pageSize', 1); $datetime = $request->get('order_addtimes', []); $goodsName = $request->get('goods_name', ''); $memberId = $request->get('member_id', ''); if (!$memberId) { return json_fail('查询错误'); } $goodsIds = []; if (!empty($goodsName)) { $goodsIds = Goods::where('goods_name', 'like', '%' . $goodsName . '%')->pluck('goods_id')->toArray(); } $sheet = OrderSheet::with([ 'goods' => function ($query) { $query->select('goods_id', 'goods_name', 'goods_cover'); }, 'order' => function ($query) { $query->select('order_id', 'order_status_system', 'order_status_payment', 'order_status_storage'); }, 'refund' => function ($query) { $query->select('join_return_order_id', 'orders_return_id', 'order_return_status'); }, ]) ->leftJoin('order', 'order.order_id', 'order_sheet.join_sheet_order_id') ->where('join_sheet_member_id', $memberId) ->where('order.order_category', '<>', 'RECHARGE') ->when(!empty($datetime), function ($query) use ($datetime) { $datetime[0] = strtotime($datetime[0]); $datetime[1] = strtotime($datetime[1]); $query->whereBetween('order_sheet_addtimes', $datetime); }) ->when(!empty($goodsIds), function ($query) use ($goodsIds) { $query->whereIn('join_sheet_goods_id', $goodsIds); }); $total = $sheet->count(); $rows = $sheet ->orderBy('order_sheet_addtimes', 'desc') ->forPage($page, $pageSize) ->get() ->toArray(); foreach ($rows as &$item) { if (!empty($item->goods->goods_cover)) { $item->goods->goods_cover = getenv('STORAGE_DOMAIN') . $item->goods->goods_cover; } } return json_success('', compact('rows', 'page', 'pageSize', 'total')); } public function saveExpress($params) { try { $express = new OrderExpress(); $express->order_express_type = $params['order_express_type']; $express->join_express_order_id = $params['orderId']; $express->order_express_goods = $params['order_express_goods']; $express->order_express_city = $params['order_express_city']; $express->order_express_address = $params['order_express_address']; $express->order_express_mobile = $params['order_express_mobile'] ?? ''; $express->order_express_telephone = $params['order_express_telephone'] ?? ''; $express->order_express_person = $params['order_express_person'] ?? ''; $express->order_express_company = $params['dept_premises_id'] ?? ''; $express->order_express_extend_json = $params['order_express_extend_json'] ?? '[]'; $express->order_express_addtimes = time(); $express->save(); } catch (\Exception $e) { dump($e->getMessage()); throw new BusinessException('物流信息保存失败'); } } // TODO 确认收货(完成订单) // public function confirm($id) // { // $order = Order::where('order_id', $id)->first(); // if (empty($order)) { // return json_fail("暂无数据"); // } // // Db::beginTransaction(); // try { // // 主订单 // Order::where('order_id', $id)->update(['order_status_system' => 'CONFIRM']); // } catch (\Exception $e) { // // } // } /** * @Desc 退款 * @Author Gorden * @Date 2024/7/8 8:40 * * @param Request $request * @return Response */ public function doRefund(Request $request) { $orderId = $request->post('order_id', ''); $amount = $request->post('refund_amount', 0); $password = $request->post('refund_password', ''); if (!$orderId || !$amount || !$password) { return json_fail('参数异常'); } if ($password != '123456') { return json_fail('支付密码错误'); } $return = OrderReturn::where('join_return_order_id', $orderId) ->first(); if (!$return) { return json_fail("退款订单异常"); } $order = Order::where('order_id', $return->join_return_order_id)->first(); if (!$order) { return json_fail("订单异常"); } if ($order->order_is_complete == 'Y' || $order->order_is_complete == 'R') { return json_fail('订单已完成,无法退款'); } if ($amount > $order->order_amount_pay) { return json_fail('退款金额不能超过订单金额'); } $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_status', 'SUCCESS')->first(); if (!$payDetail) { return json_fail("支付信息异常异常"); } // 在线支付返回 $payJsonResponse = []; if (!empty($payDetail->pay_json_response)) { $payJsonResponse = json_decode($payDetail->pay_json_response, true); } $res = '[]'; $data = '[]'; try { Db::beginTransaction(); // 订单主表 Order::where('order_id', $return->join_return_order_id)->update(['order_is_complete' => 'R']); // 订单详情 OrderSheet::where('join_sheet_order_id', $return->join_return_order_id)->update(['order_sheet_status' => 'RETURNED']); // return 表 $return->order_return_status = 'DONE'; $return->order_return_refund_json = json_encode(['amount' => $amount, 'datetime' => date('Y-m-d H:i:s'), 'user_id' => JwtToken::getCurrentId()]); $return->save(); $payType = explode('-', $payDetail->pay_prepayid); // 区分账户余额支付和在线支付 if ($payDetail->pay_prepayid == 'WXPAY') { // 退款 $data = [ 'type' => 'app', 'out_trade_no' => $order->order_groupby, 'out_refund_no' => $return->orders_return_id, 'total_fee' => $payDetail->pay_amount * 100, 'refund_fee' => $amount * 100, 'refund_desc' => '退款', ]; $res = Pay::wechat(config('payment.wxpay'))->refund($data); $resArray = json_decode($res, true); if (!$resArray['result_code'] == 'SUCCESS' || !$resArray['return_code'] == 'SUCCESS') { throw new PayException("退款失败"); } } else if ($payDetail->pay_prepayid == 'ALIPAY') { // 退款 $data = [ 'out_trade_no' => $order->order_groupby, 'refund_amount' => $amount, ]; $res = Pay::alipay(config('payment.alipay'))->refund($data); $resArray = json_decode($res, true); if ($resArray['fund_change'] != 'Y' || $resArray['msg'] != 'Success') { throw new PayException("退款失败"); } } else if (isset($payType[1]) && $payType[1] == 'CASH') { // 余额支付 $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id) ->where('member_account_classify', 'CASH') ->first(); $account->member_account_expend = $account->member_account_expend - $amount; $account->member_account_surplus = $account->member_account_surplus + $amount; $account->save(); $data = [ 'type' => 'REFUND', 'member_id' => $order->join_order_member_id, 'order_id' => $return->join_return_order_id, 'return_id' => $return->orders_return_id ]; $res = json_encode([ 'status' => 'SUCCESS' ]); } else if (isset($payType[1]) && $payType[1] == 'WELFARE') { // 员工福利支付 $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id) ->where('member_account_classify', 'WELFARE') ->first(); $account->member_account_expend = $account->member_account_expend - $amount; $account->member_account_surplus = $account->member_account_surplus + $amount; $account->save(); $data = [ 'type' => 'REFUND', 'member_id' => $order->join_order_member_id, 'order_id' => $return->join_return_order_id, 'return_id' => $return->orders_return_id ]; $res = json_encode([ 'status' => 'SUCCESS' ]); } else if (count($payType) == 1 && !in_array($payDetail->pay_prepayid, ['W06', 'A01'])) { // 卡支付 $account = MemberAccount::where('join_account_member_id', $order->join_order_member_id) ->where('member_account_nbr', $payType[0]) ->where('member_account_classify', 'CARD') ->first(); $account->member_account_expend = $account->member_account_expend - $amount; $account->member_account_surplus = $account->member_account_surplus + $amount; $account->save(); $data = [ 'type' => 'REFUND', 'nbr' => $account->member_account_nbr, 'member_id' => $order->join_order_member_id, 'order_id' => $return->join_return_order_id, 'return_id' => $return->orders_return_id ]; $res = json_encode([ 'status' => 'SUCCESS' ]); } // if (!empty($payDetail->pay_prepayid) && in_array($payDetail->pay_prepayid, ['WXPAY', 'ALIPAY'])) { // $responseJson = []; // if (!empty($payDetail->pay_json_response)) { // $responseJson = json_decode($payDetail->pay_json_response, true); // if (!isset($responseJson['trxid'])) { // throw new PayException("支付信息异常"); // } // } // $data = [ // 'randomstr' => random_string(32), // 'reqsn' => $return->join_return_order_id, // 'oldtrxid' => $responseJson['trxid'], // 'trxamt' => $amount * 100, // // ]; // // $tlpay = new Tlpay(); // $res = $tlpay->refund($data); // // $resArray = json_decode($res, true); // if (AppUtil::validSign($resArray)) { // if ($resArray['retcode'] != 'SUCCESS' || $resArray['trxstatus'] != '0000') { // throw new PayException('退款失败,原因:' . $resArray['errmsg']); // } // } // } // 生成payDetail $payDetailData = [ 'join_pay_member_id' => $order->join_order_member_id, 'join_pay_order_id' => $order->order_groupby, 'pay_status' => 'SUCCESS', 'pay_category' => 'REFUND', 'pay_amount' => $amount, 'pay_paytimes' => date('Y-m-d H:i:s'), 'pay_json_request' => json_encode($data), 'pay_json_response' => $res, 'pay_prepayid' => $payType[0] . (!empty($payType[1]) ? '-' . $payType[1] : ''), 'pay_addtimes' => time() ]; PayDetail::insert($payDetailData); Db::commit(); // 事件通知 Event::dispatch('client_message.refund', $order->join_order_member_id); _syslog("退款", "发起退款", json_decode($res), $data); return json_success("退款成功"); } catch (PayException $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("退款", "发起退款", $e->getMessage(), $data); return json_fail($e->getMessage()); } catch (\Exception $e) { Db::rollBack(); dump($e->getMessage()); dump($e->getTrace()); _syslog("退款", "发起退款", $e->getMessage(), $data); if (strpos($e->getMessage(), '余额不足') !== false) { return json_fail("基本账户余额不足,请充值后重新发起"); } return json_fail("数据更新失败"); } } public function exportOrder(Request $request) { [$where, $format, $limit, $field, $order] = $this->selectInput($request); if (!empty($request->get('order_ids'))) { $where['order_id'] = ['in', $request->get('order_ids')]; } if (!empty($where['order_addtimes'])) { $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]); $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]); } $order = $request->get('order', 'desc'); $field = $field ?? 'order_addtimes'; if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) { $where['order_is_complete'] = 'N'; } if (!empty($where['order_status_system']) && $where['order_status_system'] == 'RETURN') { unset($where['order_status_system']); unset($where['order_is_complete']); $where['order_category'] = 'RETURN'; } $query = $this->doSelect($where, $field, $order); _syslog("订单", "导出订单"); return $this->exportDoFormat($query, $format, 1000); } /** * 执行真正查询,并返回格式化数据 * @param $query * @param $format * @param $limit * @return Response */ protected function exportDoFormat($query, $format, $limit): Response { $methods = [ 'select' => 'formatSelect', 'tree' => 'formatTree', 'table_tree' => 'formatTableTree', 'normal' => 'formatNormal', ]; $paginator = $query->paginate($limit); $total = $paginator->total(); $items = $paginator->items(); $items = call_user_func([$this, "exportAfterQuery"], $items); $format_function = $methods[$format] ?? 'formatNormal'; return call_user_func([$this, $format_function], $items, $total); } public function benefitList(Request $request) { $orderIds = $request->get('order_ids', []); if (empty($orderIds)) { return json_fail("请选择需要核销的订单"); } $orders = order::whereIn('order_id', $orderIds) ->with([ 'benefit' => function ($query) { $query->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count'); }, 'member' => function ($query) { $query->select('member_id', 'member_mobile'); }, // 'sheets'=>function($query){ // $query->select('join_sheet_order_id','join_sheet_goods_id'); // } // 'goods'=>function($query){ // $query->select('goods_id','goods_name'); // } ]) ->select('order_id', 'join_order_member_id', 'order_is_complete', 'order_status_system') ->where("order_is_complete", 'N') ->whereIn("order_category", ['NORMAL', 'SYSTEM']) ->orderBy('order_addtimes', 'DESC') ->get() ->toArray(); $memberId = array_unique(array_column($orders, 'join_order_member_id')); if (count($memberId) > 1) { return json_fail("不可同时核销多人订单"); } $data = []; foreach ($orders as $order) { $orderOne = $order; foreach ($order['benefit'] as $benefit) { $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']); $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']); $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']; $orderOne['benefit'] = $benefit; $orderOne['member_benefit_id'] = $benefit['member_benefit_id']; $data[] = $orderOne; } } if (empty($data)) { return json_fail("您选择的产品没有可核销的服务"); } return json_success('', $data); } public function chooseBenefitList(Request $request) { $benefitIds = $request->get('benefit_ids', []); $memberId = $request->get('member_id', []); if (empty($benefitIds)) { return json_fail('请选择需要核销的服务'); } if (empty($memberId)) { return json_fail('没有会员信息,请联系管理员'); } $benefits = MemberBenefit::whereIn('member_benefit_id', $benefitIds) ->where('member_benefit_status', 'ACTIVED') ->where('join_benefit_member_id', $memberId) ->select('join_benefit_order_id', 'member_benefit_id', 'member_benefit_name', 'member_benefit_limit_count', 'member_benefit_used_count') ->orderBy('member_benefit_addtimes', 'DESC') ->get() ->toArray(); foreach ($benefits as &$benefit) { $benefit['member_benefit_limit_count'] = intval($benefit['member_benefit_limit_count']); $benefit['member_benefit_used_count'] = intval($benefit['member_benefit_used_count']); $benefit['unused'] = $benefit['member_benefit_limit_count'] - $benefit['member_benefit_used_count']; } $member = Member::where('member_id', $memberId)->select('member_id', 'member_mobile')->first()->toArray(); return json_success('', ['benefits' => $benefits, 'member' => $member]); } public function customPrinter(Request $request) { $orderId = $request->post('order_id', ''); $printer = $request->post('printer', []); $premiseName = $request->post('premise', ''); if (empty($orderId) || empty($premiseName)) { return json_fail('参数异常'); } if (empty($printer)) { return json_fail('请选择打印设备'); } $premises = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->where('dept_status', 'ACTIVED')->first(); $restaurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first(); $order = Order::where('order_id', $orderId)->first(); try { foreach ($printer as $print) { if (strpos($print, '结算') !== false && $order->order_status_payment != 'SUCCESS') { return json_fail('无法打印未支付的结账单'); } if (!empty($premises) || $restaurant) { if (empty($restaurant)) { $restaurant = SysDept::where('dept_super_id', $premises->dept_id)->where('dept_category', '餐厅')->first(); } if (!empty($restaurant->dept_extend_json)) { $deptExtendJson = json_decode($restaurant->dept_extend_json, true); $voteData = [ 'func' => 'procActionToPrinter', 'sign' => '', 'data' => [ 'printer_premises' => $restaurant->dept_id, 'printer_device' => [ $print ], 'printer_action' => 'ExecPrintOrder', 'printer_data' => [ 'order_id' => $orderId ] ] ]; http_post_json(getenv('VOTE_MENU_URL'), $voteData); } } } return json_success('打印完成'); } catch (\Exception $e) { return json_fail("存在错误,票据未全部打印"); } } protected function exportAfterQuery($items) { $data = []; foreach ($items as $key => $item) { $goodsClassify = '--'; $goodsName = '--'; if (!empty($item['sheet'])) { $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first(); $goodsClassify = $goods->goods_classify ?? ''; $goodsName = $goods->goods_name ?? '--'; } $systemStatus = ''; if ($item['order_is_complete'] == 'Y') { $systemStatus = '已完成'; } elseif ($item['order_is_complete'] == 'R') { $systemStatus = '售后已完成'; } $data[$key] = [ 'goods_classify' => !empty($goods) && isset(self::$goodsClassify[$goods->goods_classify]) ? self::$goodsClassify[$goods->goods_classify] : '其他订单', 'order_id' => $item['order_id'], 'member' => (!empty($item['cert']) ? $item['cert']['member_cert_name'] : substr($item['member']['member_mobile'], -4) . '用户') . '-' . $item['member']['member_mobile'], 'goods_name' => $goodsName, 'nbr' => !empty($item['sheet']) ? intval($item['sheet']['order_sheet_num']) : '--', 'order_amount_total' => $item['order_amount_total'], 'order_amount_pay' => $item['order_amount_pay'], 'order_status_system' => !empty($systemStatus) ? $systemStatus : self::$systemStatus[$item['order_status_system']], 'order_status_payment' => self::$paymentStatus[$item['order_status_payment']], 'order_addtimes' => date('Y-m-d H:i:s', strtotime($item['order_addtimes'])) ]; } return $data; } /** * @Desc 查询订单状态 * @Author Gorden * @Date 2024/8/19 11:55 * * @param Request $request * @return Response|void */ public function getOrderPayStatus(Request $request) { $orderId = $request->get('order_id', ''); if (!$orderId) { return json_fail('订单不存在'); } $order = Order::where('order_id', $orderId)->first(); if (!$order) { return json_fail('订单不存在'); } if ($order->order_status_payment == 'SUCCESS') { return json_success('success'); } $payDetailType = PayDetail::where('join_pay_order_id', $order->order_groupby)->pluck('pay_prepayid')->toArray(); try { Db::beginTransaction(); if (in_array('WXPAY', $payDetailType)) { $result = Pay::wechat(config('payment.wxpay'))->find($order->order_groupby, 'pos'); $result = json_decode(json_encode($result), true); if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') { if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) { $order->order_is_complete = 'Y'; $order->order_status_system = 'DONE'; $order->order_status_payment = 'SUCCESS'; } else { $order->order_status_system = 'SENDING'; } $order->save(); // Sheet OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']); // 支付记录 PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'WXPAY')->update(['pay_status' => 'SUCCESS']); Db::commit(); return json_success('success'); } } else if (in_array('ALIPAY', $payDetailType)) { $result = Pay::alipay(config('payment.alipay'))->find($order->order_groupby); $result = json_decode(json_encode($result), true); if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') { if (in_array($order->order_category, ['SERVICE', 'CHNMED', 'CHNNCD', 'DISHES', 'MEALS', 'VIP'])) { $order->order_is_complete = 'Y'; $order->order_status_system = 'DONE'; $order->order_status_payment = 'SUCCESS'; } else { $order->order_status_system = 'SENDING'; } $order->save(); // Sheet OrderSheet::where('join_sheet_order_id', $orderId)->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']); // 支付记录 PayDetail::where('join_pay_order_id', $order->order_groupby)->where('pay_prepayid', 'ALIPAY')->update(['pay_status' => 'SUCCESS']); Db::commit(); return json_success('success'); } } Db::rollBack(); return json_fail('没有查询到记录'); } catch (\Exception $e) { Db::rollBack(); return json_fail('查询失败'); } } /** * @Desc 修改订单状态-挂账 * @Author Gorden * @Date 2024/8/20 15:58 * * @param Request $request * @return Response */ public function updateStatus(Request $request) { $orderId = $request->post('order_id', ''); $orderStatusPayment = $request->post('order_status_payment', ''); $order = Order::where('order_id', $orderId) ->select('order_id', 'order_status_payment', 'order_config_json') ->first(); Db::beginTransaction(); try { if ($orderStatusPayment == 'AWAITING' && $order->order_status_payment != 'PENDING') { return json_fail('当前订单不允许挂账'); } // 挂账,释放餐桌 if ($order->order_status_payment == 'PENDING' && $orderStatusPayment == 'AWAITING') { $order->order_status_payment = $orderStatusPayment; // 如果有餐桌,释放 if (!empty($order->order_config_json)) { $orderConfigJson = json_decode($order->order_config_json, true); if (!empty($orderConfigJson['tableid'])) { SysDept::where('dept_id', $orderConfigJson['tableid'])->update(['dept_status' => 'ACTIVED']); } } } $order->save(); Db::commit(); return json_success('success'); } catch (\Exception $e) { Db::rollBack(); return json_fail('修改订单状态失败'); } } public static $goodsClassify = [ // goodsClassify: {GOODS:"健康产品订单",SERVICE:"服务订单",DEVICE:"设备订单",SPECIAL:"专题业务订单",PACKAGE:"套餐订单",RECHARGE:"充值订单",OTHER:"其他订单"}, 'GOODS' => "产品订单", 'SERVICE' => "服务订单", 'DEVICE' => '设备订单', 'SPECIAL' => '专题业务订单', 'PACKAGE' => '套包订单', 'RECHARGE' => '充值订单', 'OTHER' => '其他订单', 'DISHES' => '餐饮订单' ]; // systemStatus: {BEING:"待生效",PAYING:"待支付",PENDING:"待确认",WAITING:"待受理",SENDING:"待发货",RECVING:"待收货",SIGNED:"已签收",CONFIRM:"确认收货"}, // paymentStatus: {PENDING:"待支付",CANCEL:"取消支付",SUCCESS:"支付成功"}, public static $systemStatus = [ 'BEING' => '待生效', 'PAYING' => "待支付", 'PENDING' => "待确认", 'WAITING' => "待使用", 'SENDING' => "待发货", 'RECVING' => "待收货", 'SIGNED' => "已签收", 'CONFIRM' => "确认收货", 'DONE' => '已完成', 'CANCEL' => '已取消' ]; public static $paymentStatus = [ 'WAITING' => "待支付", 'PENDING' => "待支付", 'CANCEL' => "取消支付", 'SUCCESS' => "支付成功" ]; }