diff --git a/app/controller/api/Archives.php b/app/controller/api/Archives.php deleted file mode 100644 index 4fc8f4a..0000000 --- a/app/controller/api/Archives.php +++ /dev/null @@ -1,272 +0,0 @@ -json(0, 'success', $data); - } - - /** - * 病种问题文章列表 分类问题 - * - * @return Json - */ - public function diseaseQuestion(): Json - { - $diseaseId = input('disease_id/d', 0); - - try { - $data = ArchivesRepository::getInstance()->diseaseQuestion($diseaseId); - - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 恒美小课堂 - * - * @return Json - * @throws Exception - */ - public function course(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $courseId = input('course_id/d', 0); - $page = input('page/d', 1); - $size = input('size/d', 20); - - try { - $data = ArchivesRepository::getInstance()->course($accountId, $courseId, $page, $size); - - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 热门推荐 - * - * @return Json - * @throws Exception - */ - public function hot(): Json - { - $categoryId = input('category_id/d', 0); - $page = input('page/d', 1); - $size = input('size/d', 20); - $keyword = input('keyword/s', ''); - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $where[] = ['hot', '=', 1]; - if (!empty($keyword)) { - - $keyword = trim($keyword); - $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%']; - AccountRecord::saveSearch($accountId, $keyword); - } - $data = ArchivesRepository::getInstance()->category($accountId, $categoryId, $where, $page, $size); - - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 获取指定栏目内容列表 - * - * @return Json - * @throws Exception - */ - public function category(): Json - { - $categoryId = input('category_id/d', 0); - $page = input('page/d', 1); - $size = input('size/d', 20); - $keyword = input('keyword/s', ''); - $diseaseIds = input('disease_id/s', '');//病种 多个用逗号分隔 - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $where = []; - if (!empty($keyword)) { - $keyword = trim($keyword); - $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%']; - AccountRecord::saveSearch($accountId, $keyword); - } - - if (!empty($diseaseIds)) { - $where[] = ['disease_id', 'in', explode(',', $diseaseIds)]; - } - - $data = ArchivesRepository::getInstance()->category($accountId, $categoryId, $where, $page, $size); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 获取关于我们栏目内容列表 - * - * @return Json - * @throws Exception - */ - public function about(): Json - { - $categoryId = input('category_id/d', 0); - $page = input('page/d', 1); - $size = input('size/d', 20); - $exceptId = input('except_id/d', 0); - $keyword = input('keyword/s', ''); - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $where = []; - if (!empty($keyword)) { - $keyword = trim($keyword); - $where[] = ['title|subtitle|disease_name|doctor_name', 'like', '%'.$keyword.'%']; - AccountRecord::saveSearch($accountId, $keyword); - } - - if ($exceptId > 0) { - $where[] = ['id', '<>', $exceptId]; - } - - $order = ['published_at' => 'desc']; - - $data = ArchivesRepository::getInstance()->about($accountId, $categoryId, $where, $page, $size, $order); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 内容详情 - * - * @return Json - * @throws Exception - */ - public function detail(): Json - { - $id = input('id/d', 0); - $shareId = input('share_id/d', 0);//分享人ID - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = ArchivesRepository::getInstance()->detail($id, $accountId, $shareId); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '获取详情失败'); - } - - } - - /** - * 点赞、收藏 - */ - public function record(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $archiveId = $this->request->param('archive_id/d', 0); - $action = $this->request->param('action/s', ''); - - try { - ArchivesRepository::getInstance()->record($accountId, $archiveId, $action); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 取消 点赞、收藏 - */ - public function unRecord(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $archiveId = $this->request->param('archive_id/d', 0); - $action = $this->request->param('action/s', ''); - - try { - ArchivesRepository::getInstance()->unRecord($accountId, $archiveId, $action); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 用户内容收藏列表 - */ - public function collects(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $categoryId = $this->request->param('category_id/d', 0); - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 10); - - $page = $page <= 0 ? 1 : $page; - $size = $size <= 0 ? 10 : $size; - $data = ArchivesRepository::getInstance()->accountCollects($accountId, $categoryId, $page, $size); - return $this->json(0, 'success', $data); - } -} \ No newline at end of file diff --git a/app/controller/api/Common.php b/app/controller/api/Common.php deleted file mode 100644 index f86a43c..0000000 --- a/app/controller/api/Common.php +++ /dev/null @@ -1,94 +0,0 @@ -scene('send_sms')->check($input)) { - return $this->json(4001, '参数错误'); - } - if (!in_array($input['type'], ['register', 'login', 'binding'])) { - return $this->json(4002, '参数错误'); - } - - CommonRepository::getInstance()->sendSms($input['phone'], $input['type']); - return $this->json(); - } - - /** - * 查看轮播图可视位置配置信息 - */ - public function slidePositions(): Json - { - $repo = OperationRepository::getInstance(); - $list = $repo->slidePositions(); - return $this->json(0, 'success', $list); - } - - - /** - * 轮播图 - */ - public function slides(): Json - { - $size = $this->request->param('size/d', 0); - $position = trim($this->request->param('position/s', '')); - if (empty($position)) { - return $this->json(); - } - - try { - $repo = OperationRepository::getInstance(); - $list = $repo->slideListByPosition($position, $size); - } catch (\Exception $e) { - $list = new Collection(); - } - - return $this->json(0, 'success', $list); - } - - /** - * 获取快递公司列表 - * - * @throws ModelNotFoundException - * @throws DbException - * @throws DataNotFoundException - */ - public function expressList(): Json - { - $list = OrderRepository::getInstance()->allExpress(); - return $this->json(0, 'success', $list); - } - -} \ No newline at end of file diff --git a/app/controller/api/DepartmentGoodsListLog.php b/app/controller/api/DepartmentGoodsListLog.php deleted file mode 100644 index 017c31c..0000000 --- a/app/controller/api/DepartmentGoodsListLog.php +++ /dev/null @@ -1,63 +0,0 @@ -request->param(); - $validate = new GoodsValidate(); - if (!$validate->scene('base')->check($params)) { - return $this->json(4001, $validate->getError()); - } - - $data = GoodsRepository::getInstance()->list(); - - return $this->json(0, 'success', $data); - } - - /** - * 获取分类列表 - * - * @return Json - * @throws Exception - */ - public function category() - { - $params = $this->request->param(); - $validate = new GoodsValidate(); - if (!$validate->scene('base')->check($params)) { - return $this->json(4001, $validate->getError()); - } - - $data = GoodsRepository::getInstance()->categoryList(); - - return $this->json(0, 'success', $data); - } - - public function testApiClassMethod() - { - $header = $this->request->header(); - $all = $this->request->param(); - $get = input('get.'); - $post = input('post.'); - return $this->json(0, 'success', ['cost'=>$cost ?? 0]); - } -} \ No newline at end of file diff --git a/app/controller/api/Index.php b/app/controller/api/Index.php deleted file mode 100644 index a6d062e..0000000 --- a/app/controller/api/Index.php +++ /dev/null @@ -1,100 +0,0 @@ - 0, 'msg' => 'I am index']); - } - - /** - * 测试用 - * - * @return Json - * @throws RepositoryException - */ - public function test(): Json - { - $userId = $this->request->middleware('userInfo')['user_id'] ?? 0; - $user = AccountRepository::getInstance()->info($userId, []); - - return json(['code' => 0, 'msg' => 'I am test ', 'data' => $user]); - } - - public function login(): Json - { - $userId = $this->request->middleware('userInfo')['user_id'] ?? 0; - return json(['code' => 0, 'msg' => 'I am login '.$userId]); - } - - public function notify() - { - $beginNotifyList = AccountRepository::getInstance()->getBeginNotifyList(); - // $res = Queue::later(3, NotifySms::class, $beginNotifyList); - // $getSuccessList = AccountRepository::getInstance()->getSuccessList(); - return $this->json(0, 'success', $beginNotifyList); - } - - - /** - * 小程序个性装修配置 - */ - public function miniProgramSetting(): Json - { - $conf = ExtraConfig::miniProgram(); - return $this->json(0, 'success', $conf); - } - - /** - * 推荐显示的热搜词 - */ - public function hotKeywords(): Json - { - try { - $type = input('type/s',""); - $list = HotKeyword::allRecommends($type); - } catch (\Exception $e) { - $list = new Collection(); - } - - return $this->json(0, 'success', $list); - } - - /** - * 清理过期足迹 - * - * @return Json - */ - public function clearFootmarks(): Json - { - try { - //清理N天以前的数据 - $day = 30; - $time = date('Y-m-d H:i:s', time() - $day * 86400); - $count = AccountFootmarks::where('created_at', '<', $time)->count(); - AccountFootmarks::where('created_at', '<', $time)->delete(); - return $this->json(0, '成功清理足迹(条):'.$count); - } catch (\Exception $e) { - return $this->json(5000, '清理足迹失败'); - } - } - -} \ No newline at end of file diff --git a/app/controller/api/Level.php b/app/controller/api/Level.php deleted file mode 100644 index 29b895c..0000000 --- a/app/controller/api/Level.php +++ /dev/null @@ -1,39 +0,0 @@ -request->user['user_id'] ?? 0; - $user = Account::findById($userId); - if (empty($user)) { - return json(['code' => 6001, 'msg' => '未登录']); - } - $level = AccountRepository::getInstance()->getUserLevel($user["coin_total"]); - $nextLevel = AccountRepository::getInstance()->getUserNextLevel($level["value"]); - - if (!empty($nextLevel)) { - $nextLevel["disparity"] = ( $nextLevel["value"] - $user['coin_total']); - } - return $this->json(0, "ok", [ - "level" => $level, - "nextLevel" => $nextLevel, - "nickname" => $user['nickname'], - "headimgurl" => $user['headimgurl'], - ]); - } - - -} \ No newline at end of file diff --git a/app/controller/api/Order.php b/app/controller/api/Order.php deleted file mode 100644 index 4b9c80e..0000000 --- a/app/controller/api/Order.php +++ /dev/null @@ -1,406 +0,0 @@ -request->isPost()) { - $params = $this->request->param(); - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = OrderRepository::getInstance()->createOrder($accountId, $params); - OrderRepository::getInstance()->updateSpuStock([]); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('订单创建失败', $e, 'error', 'order'); - return $this->json(5000, '订单创建失败'); - } - } - return $this->json(4002, '请求错误'); - } - - /** - * 购物车列表 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function shoppingCart(): Json - { - $params = $this->request->param(); - $accountId = $this->request->user['user_id'] ?? 0; - $type = $params['type'] ?? ''; - $page = $params['page'] ?? 1; - $size = $params['size'] ?? 20; - - $data = OrderRepository::getInstance()->shoppingCart($accountId, $type, $page, $size); - - return $this->json(0, 'success', $data); - } - - /** - * 添加购物车 - * - * @return Json - * @throws Exception - */ - public function shoppingCartAdd(): Json - { - if ($this->request->isPost()) { - $params = $this->request->param(); - $accountId = $this->request->user['user_id'] ?? 0; - $rules = [ - 'sku_id|商品' => 'require|number', - 'num|数量' => 'require|number', - ]; - - $validate = $this->validateByApi($params, $rules); - if ($validate !== true) { - return $validate; - } - - try { - OrderRepository::getInstance()->shoppingCartAdd($accountId, $params['sku_id'], $params['num'] ?? 1); - return $this->json(); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('购物车添加失败', $e); - return $this->json(5000, '购物车添加失败'); - } - } - return $this->json(4002, '请求错误'); - } - - /** - * 购物车商品数量变更 - * - * @return Json - * @throws Exception - */ - public function shoppingCartChangeNum(): Json - { - if ($this->request->isPost()) { - $params = $this->request->param(); - $rules = [ - 'id|ID' => 'require|number', - 'num|数量' => 'require|number', - ]; - - $validate = $this->validateByApi($params, $rules); - if ($validate !== true) { - return $validate; - } - try { - OrderRepository::getInstance()->shoppingCartChangeNum($params['id'], $params['num']); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('购物车数量加减失败', $e); - return $this->json(5000, '操作失败'); - } - - return $this->json(); - } - return $this->json(4002, '请求错误'); - } - - /** - * 购物车商品删除 - * - * @return Json - */ - public function shoppingCartDel(): Json - { - if ($this->request->isPost()) { - $id = input('post.id/d', 0); - $accountId = $this->request->user['user_id'] ?? 0; - if (!$id) { - return $this->json(4001, '参数错误'); - } - - try { - OrderRepository::getInstance()->shoppingCartDel($accountId, $id); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('购物车数量加减失败', $e); - return $this->json(5000, '操作失败'); - } - - return $this->json(); - } - return $this->json(4002, '请求错误'); - } - - /** - * 订单准备信息 - * 结算页面 获取商品数据及汇总金额 - * @return Json - */ - public function prepareInfo(): Json - { - if ($this->request->isPost()) { - $params = $this->request->param(); - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = OrderRepository::getInstance()->prepareInfo($accountId, $params); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('获取订单前置信息失败', $e, 'error', 'order'); - return $this->json(5000, '订单信息获取失败'); - } - - return $this->json(0, 'success', $data); - } - return $this->json(4002, '请求错误'); - } - - /** - * 支付成功通知 - * 结算页面 获取商品数据及汇总金额 - * - * @return Json - * @throws Exception - */ - public function paid(): Json - { - if ($this->request->isPost()) { - $params = $this->request->param(); - $accountId = $this->request->user['user_id'] ?? 0; - $rules = [ - 'order_coding|订单编号' => 'require', - ]; - - $validate = $this->validateByApi($params, $rules); - if ($validate !== true) { - return $validate; - } - - try { - if (OrderRepository::getInstance()->setPaid($params['order_coding'])) { - return $this->json(); - } - return $this->json(4003, '支付失败'); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('支付成功通知操作失败', $e); - return $this->json(5000, '操作失败'); - } - } - return $this->json(4002, '请求错误'); - } - - /** - * 订单验收 - 确认收货 - * - * @return Json - */ - public function accepted(): Json - { - if (!$this->request->isPost()) { - return $this->json(4002, '请求错误'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $orderId = $this->request->param('order_id', 0); - - try { - OrderRepository::getInstance()->orderAccepted($orderId, $accountId); - - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 发货 - * - * @return Json - */ - public function ship(): Json - { - if (!$this->request->isPost()) { - return $this->json(4002, '请求错误'); - } - - $orderId = $this->request->param('order_id', 0); - $expressId = $this->request->param('express_id', 0); - $expressNumber = $this->request->param('express_number', 0); - - try { - OrderRepository::getInstance()->orderShipping($orderId, $expressId, $expressNumber); - - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 查询订单物流 - * - * @return Json - */ - public function logistics(): Json - { - $orderCoding = input('order_coding'); - - try { - $res = OrderRepository::getInstance()->logistics($orderCoding); - return $this->json(0, 'success', $res); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('物流查询失败', $e); - return $this->json(5000, '获取物流信息失败'); - } - } - - /** - * 取消订单 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function cancel(): Json - { - if (!$this->request->isPost()) { - return $this->json(4002, '请求错误'); - } - - $orderCoding = $this->request->param('order_coding', 0); - $reason = $this->request->param('remarks', ''); - - try { - OrderRepository::getInstance()->setClosed($orderCoding, OrderModel::STATUS_CLOSED, $reason); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 订单付款 - * - * @return Json - * @throws Exception - */ - public function pay(): Json - { - if (!$this->request->isPost()) { - return $this->json(4002, '请求错误'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $orderCoding = $this->request->param('order_coding', 0); - - try { - $res = OrderRepository::getInstance()->pay($orderCoding, $accountId); - return $this->json(0, 'success', $res); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } - } - - /** - * 购物车数量 - * - * @return Json - * @throws Exception - */ - public function shoppingCartCount(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $type = $this->request->param('type/s', 'spu'); - - try { - $count = OrderRepository::getInstance()->shoppingCartCount($accountId, $type); - return $this->json(0, 'success', ['count' => $count]); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } - } - - /** - * 商品sku核验 - * - */ - public function check(): Json - { - $orderCoding = input('order_coding/s', ''); - $id = input('id/d', 0); - $checkBy = input('check_user/d', 0); - $num = input('num/d', 1); - - try { - OrderRepository::getInstance()->check($orderCoding, $id, $num, $checkBy); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('订单商品核验失败', $e); - return $this->json(5000, '订单商品核验失败'); - } - return $this->json(); - } - - /** - * 商品sku核验结果 - * - */ - public function checkResult(): Json - { - $orderCoding = input('order_coding/s', ''); - $id = input('id/d', 0); - $notCheckNum = input('not_check_num/d', 0); - - try { - $res = OrderRepository::getInstance()->checkResult($orderCoding, $id, $notCheckNum); - return $this->json(0, 'success', ['result' => (int) $res]); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - OrderRepository::log('订单商品核验结果获取失败', $e); - return $this->json(5000, '订单商品核验结果获取失败'); - } - } -} \ No newline at end of file diff --git a/app/controller/api/Recharge.php b/app/controller/api/Recharge.php deleted file mode 100644 index ac16370..0000000 --- a/app/controller/api/Recharge.php +++ /dev/null @@ -1,152 +0,0 @@ -json("4001", "参数错误"); - } - $recharge = RechargeRepository::getInstance()->getModel()->where(["order_num" => $orderNum])->lock(true)->find(); - if (empty($recharge)) { - return $this->json("4001", "订单不存在"); - } - if ($recharge['state'] == RechargeModel::state_on) { - return $this->json(); - } - $business = BusinessRepository::getInstance()->getModel()->where(["code" => $recharge['business_code']])->lock(true)->find(); - if (empty($business)) { - return $this->json("4001", "商家不存在"); - } - //查询 交易成功判断条件: return_code、result_code和trade_state都为SUCCESS - $res = WechatPay::getInstance()->order->queryByOutTradeNumber($orderNum); - if ($res['return_code'] == 'SUCCESS') { // return_code 表示通信状态,不代表支付状态 - if (isset($res['result_code']) && $res['result_code'] == 'SUCCESS') { - if (isset($res['trade_state']) && $res['trade_state'] == 'SUCCESS') { - Db::startTrans(); - try { - //这里确定支付成功 - $total_fee = $res['total_fee'] / 100; - //加余额 - $business->save(["balance" => ($business["balance"] + $total_fee)]); - //修改支付状态 - $recharge->save([ - "money" => $total_fee, - "state" => RechargeModel::state_on, - "update_time" => date("Y-m-d H:i:s"), - "balance" => $business->balance - ]); - Db::commit(); - return $this->json(); - } catch (RepositoryException $e) { - Db::rollback(); - return $this->json("5001", $e->getMessage()); - } catch (\Exception $e) { - Db::rollback(); - return $this->json("5001", "充值失败"); - } - } - } - } - return $this->json("4001", "未支付成功"); - } - - /** - * 微信的回调 - * - * @throws \EasyWeChat\Kernel\Exceptions\Exception - */ - public function notify(){ - if ($this->request->isPost()) { - $app = WechatPay::getInstance(); - $response = $app->handlePaidNotify(function ($message, $fail) { - // $aa = '{"appid":"wxa02e44170bc722cd","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1605090111","nonce_str":"60f7d8a1e4ac8","openid":"oKrEm0ehgsy2ZTWzEva4tbLuUgFw","out_trade_no":"16268555858753004863","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DB3F6CDCB7FBB3B9DDF7C0CC8BBD5AAD","time_end":"20210721162000","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001200202107217942681078"}'; - // $message = json_decode($aa, true); - $m = json_encode($message, JSON_UNESCAPED_UNICODE); - - $recharge = RechargeRepository::getInstance()->getModel()->where(["order_num" => $message['out_trade_no']])->lock(true)->find(); - if (empty($recharge)) { - $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功,但系统查无此订单 info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'error'); - return true;//订单不存在 - } - if ($recharge['state'] == RechargeModel::state_on) { - return true;//订单已经支付 - } - $business = BusinessRepository::getInstance()->getModel()->where(["code" => $recharge['business_code']])->lock(true)->find(); - if (empty($business)) { - $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功,但商家不存在 info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'error'); - return true; - } - - - if ($message['return_code'] == 'SUCCESS') { // return_code 表示通信状态,不代表支付状态 - if (isset($message['result_code']) && $message['result_code'] == 'SUCCESS') { - if (isset($message['trade_state']) && $message['trade_state'] == 'SUCCESS') { - Db::startTrans(); - try { - //这里确定支付成功 - $total_fee = $message['total_fee'] / 100; - //加余额 - $business->save(["balance" => ($business["balance"] + $total_fee)]); - //修改支付状态 - $recharge->save([ - "money" => $total_fee, - "state" => RechargeModel::state_on, - "update_time" => date("Y-m-d H:i:s"), - "balance" => $business->balance - ]); - Db::commit(); - //记录日志 - $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功 info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'info'); - return true; - } catch (RepositoryException $e) { - Db::rollback(); - $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功-修改订单状态失败-RepositoryException info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'info'); - return $fail('Order status edit failed.'); - } catch (\Exception $e) { - Db::rollback(); - $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功-修改订单状态失败-Exception info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'info'); - return $fail('Order status edit failed.'); - } - } - } - } - return $fail('通信失败,请稍后再通知我'); - }); - - $response->send(); - } - } - /** - * 记录订单日志 - * - * @param string $message - * @param string $type - */ - private function log(string $message, string $type = 'info'): void - { - Log::channel('order')->write($message, $type); - } -} \ No newline at end of file diff --git a/app/controller/api/Sign.php b/app/controller/api/Sign.php deleted file mode 100644 index e81ecac..0000000 --- a/app/controller/api/Sign.php +++ /dev/null @@ -1,181 +0,0 @@ -request->user['user_id'] ?? 0; - if ($userId == 0) { - return $this->json(6001, "请先登录"); - } - - $account = Account::findOne(["id" => $userId], []); - if (empty($account)) { - return $this->json(6001, "请先登录"); - } - - //更新连续签到次数 - AccountRepository::getInstance()->checkContinuitySign($account); - - $weekDate = getLatelyWeekDate(); - - $weedSignInOnlineRecord = AccountRepository::getInstance()->weedSignInOnlineRecord($userId, $weekDate["1"]["date"], strtotime($weekDate["7"]["date"]) + 86399); - - foreach ($weedSignInOnlineRecord as $item) { - $w = date("w", strtotime($item['created_at'])); - if ($w == 0) { - $weekDate["1"]["record"] = $item["score"]; - } else { - $weekDate[$w]["record"] = $item["score"]; - } - $weekDate[$w]['is_sign'] = AccountSignOnline::COMMON_ON;//当天是否签到 - } - $todaySignIn = AccountSignOnline::COMMON_OFF; - foreach ($weekDate as &$item) { - - $key = date("m.d", strtotime($item['date'])); - if (!isset($item['record'])) { - $item['record'] = $score; - $item['is_sign'] = AccountSignOnline::COMMON_OFF;//当天是否签到 - } - - if ($key == date("m.d")) { - $key = "今天"; - - if ($item['is_sign'] == AccountSignOnline::COMMON_ON) { - $todaySignIn = AccountSignOnline::COMMON_ON; - } - } elseif ($key == (date("m.d", strtotime("+1 day")))) { - $key = "明天"; - } - $item["key"] = $key; - - - } - - return $this->json(0, "操作成功", [ - "sign_record" => $weekDate, - "reward_score" => $score, - "user_score" => $account['score'], - "today_sign_in" => $todaySignIn, - ]); - } - - /** - * 签到记录 - * */ - - public function onlineSignRecord() - { - $userId = $this->request->user['user_id'] ?? 0; - if ($userId == 0) { - return $this->json(6001, "请先登录"); - } - - $page = input("page/d", 1); - $size = input("size/d", 10); - - $record = AccountRepository::getInstance()->onlineSignRecordList($userId, $page, $size); - if ($record->isEmpty()) { - return $this->json(4001, "没有更多"); - } - return $this->json(0, "ok", $record); - } - - /** - * 线上签到 - * */ - public function onlineSingIn(): Json - { - //检查是否已经签到 - $userId = $this->request->user['user_id'] ?? 0; - if ($userId == 0) { - return $this->json(6001, "请先登录"); - } - - $check = AccountRepository::getInstance()->checkSignInOnline($userId); - if ($check) { - return $this->json(4003, "今天已经签到了,请明天再来"); - } - $account = Account::findOne(["id" => $userId], [], function ($q) { - return $q->lock(true); - }); - if (empty($account)) { - return $this->json(6001, "请先登录"); - } - - //更新连续签到次数 - AccountRepository::getInstance()->checkContinuitySign($account); - - Config::load('extra/base', 'base'); - $baseConfig = config('base'); - $score = isset($baseConfig['sign_score']) ? abs($baseConfig['sign_score']) : 1; - - Db::startTrans(); - try { - AccountRepository::getInstance()->SignInOnline($account, $score); - Db::commit(); - return $this->json(); - } catch (Exception $e) { - Db::rollback(); - $this->json(4003, "签到失败"); - } catch (RepositoryException $e) { - Db::rollback(); - $this->json(4003, "签到失败"); - } - - } - - - /** - * 线下签到 - * */ - public function SingIn(): Json - { - //检查是否已经签到 - $userId = $this->request->user['user_id'] ?? 0; - if ($userId == 0) { - return $this->json(6001, "请先登录"); - } - - $check = AccountRepository::getInstance()->checkSignIn($userId); - if ($check) { - return $this->json(4003, "今天已经签到了,请明天再来"); - } - Db::startTrans(); - try { - AccountRepository::getInstance()->SignIn($userId); - Db::commit(); - return $this->json(); - } catch (Exception $e) { - Db::rollback(); - $this->json(4003, "签到失败"); - } catch (RepositoryException $e) { - Db::rollback(); - $this->json(4003, "签到失败"); - } - - } - -} \ No newline at end of file diff --git a/app/controller/api/Spu.php b/app/controller/api/Spu.php deleted file mode 100644 index 63212aa..0000000 --- a/app/controller/api/Spu.php +++ /dev/null @@ -1,335 +0,0 @@ - Disease::getListByPid(0, ['pid', 'name', 'id', 'sort']), - 'doctor_roles' => AccountRole::findAccountRolesByGroupName(AccountRole::ROLE_GROUP_DOCTOR), - 'activity' => SpuModel::activity(), - ]; - - return $this->json(0, 'success', $list); - } - - /** - * 获取已发布的商品列表 - * - * @return Json - * @throws RepositoryException - * @throws Exception - */ - public function list(): Json - { - $repo = SpuRepository::getInstance(); - - $fields = SpuModel::spuListFields(); - - $params = input(); - $params['fields'] = $fields; - $params['is_score'] = SpuModel::COMMON_OFF;//排除积分商品 - - $list = $repo->listForFront($params, function ($q) { - return $q->with([ - 'activity_info' => function ($query) { - $query->withoutField('content'); - } - ]); - }); - - return $this->json(0, 'success', $list); - } - - /** - * 获取已发布的积分商品列表 - * - * @return Json - * @throws RepositoryException - * @throws Exception - */ - public function score(): Json - { - $repo = SpuRepository::getInstance(); - - $type = input('type/s', SpuModel::TYPE_NORMAL);//normal=综合 newest=最新 - $sortField = input('sort_field/s', '');// score=积分 num=兑换量 - $sortValue = input('sort_value/s', '');//desc=降序 asc=升序 - - $rules = [ - 'page|页数' => 'integer|gt:0', - 'size|每页数量' => 'integer|gt:0', - 'type|类型' => 'in:newest,'.SpuModel::TYPE_NORMAL, - 'sort_field|排序字段' => 'in:score,amount', - 'sort_value|排序值' => 'in:asc,desc', - ]; - - $message = [ - 'type.in' => '类型错误', - '$sortField.in' => '排序字段错误', - 'sort_value.in' => '排序值错误', - ]; - - $params = input(); - - $validate = $this->validateByApi($params, $rules, $message); - if ($validate !== true) { - return $validate; - } - - $order = [];//排序 - - // 综合排序 - if ($type === SpuModel::TYPE_NORMAL) { - $order = [ - 'sort' => 'desc', - 'id' => 'desc', - ]; - } - - // 最新排序 - if ($type === 'newest') { - $order = ['published_at' => 'desc']; - } - - // 兑换量排序 - if (!empty($sortField)) { - if (empty($sortValue)) { - return $this->json(4003, '排序参数错误'); - } - $order = [ - $sortField => $sortValue - ]; - } - - $params['is_score'] = SpuModel::COMMON_ON; - $params['fields'] = SpuModel::scoreListFields(); - - $list = $repo->listForFront($params, function ($q) { - return $q->with([ - 'activity_info' => function ($query) { - $query->withoutField('content'); - } - ]); - }, $order); - - return $this->json(0, 'success', $list); - } - - /** - * 收藏列表 - * - * @return Json - * @throws Exception - */ - public function collection(): Json - { - $rules = [ - 'page|页数' => 'integer', - 'size|每页数量' => 'integer', - ]; - - $params = input(); - $page = $params['page'] ?? 1; - $size = $params['size'] ?? 10; - $accountId = $this->request->user['user_id'] ?? 0; - - - $params['page'] = 1; - $params['size'] = 0; - - $validate = $this->validateByApi($params, $rules); - if ($validate !== true) { - return $validate; - } - - //获取收藏相关 - $collection = AccountRecord::where('type', AccountRecord::TYPE_SPU) - ->where('action', AccountRecord::ACTION_COLLECT) - ->where('account_id', $accountId) - ->where('is_record', AccountRecord::COMMON_ON) - ->order('recorded_at', 'desc'); - - $total = $collection->count(); - if ($total <= 0) { - return $this->json(0, 'success', [ - 'total' => 0, - 'current' => $page, - 'size' => $size, - 'list' => new Collection(), - ]); - } - - $recordList = $collection->page($page)->limit($size)->field('relation_id,recorded_at')->select(); - - $where = []; - $where[] = ['id', 'in', $recordList->column('relation_id')]; - - $list = SpuRepository::getInstance()->listForFront($params, function ($q) { - return $q->with([ - 'activity_info' => function ($query) { - $query->withoutField('content'); - } - ]); - }, [], $where); - - $data = []; - $spuList = $list['list']->toArray(); - foreach ($recordList as $record) { - foreach ($spuList as $key => $spu) { - if ($record['relation_id'] == $spu['id']) { - $data[] = $spu; - unset($spuList[$key]); - } - } - } - - $list['total'] = $total; - $list['current'] = $page; - $list['size'] = $size; - $list['list'] = $data; - - return $this->json(0, 'success', $list); - } - - - /** - * SPU 详情 - */ - public function detail(): Json - { - $repo = SpuRepository::getInstance(); - $id = input('id/d', 0); - $shareId = input('share_id/d', 0);//分享人ID - $isActivity = input('is_activity/d', 0);//分享人ID - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = $repo->detail($id, $accountId, $shareId, (bool) $isActivity); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - $repo->log($e->getMessage(), $e); - return $this->json(5000, '获取详情失败'); - } - } - - /** - * 获取指定活动商品的拼团列表 仅限拼团活动商品 - */ - public function groupList(): Json - { - $id = input('id/d', 0); - - try { - $data = OrderRepository::getInstance()->getGroupList($id); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - SpuRepository::log($e->getMessage(), $e); - return $this->json(5000, '获取拼团列表失败'); - } - } - - /** - * 收藏 - */ - public function record(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $id = $this->request->param('id/d', 0); - $action = $this->request->param('action/s', ''); - - try { - if ($accountId <= 0 || $id <= 0) { - return $this->json(4001, '无效请求'); - } - - if (!in_array($action, AccountRecord::allowActions())) { - return $this->json(4001, '操作类型参数错误'); - } - - if (!SpuModel::findById($id)) { - return $this->json(4001, '商品不存在'); - } - - AccountRecord::record($accountId, AccountRecord::TYPE_SPU, $action, $id); - } catch (Exception $e) { - Log::error('[商品记录失败]'.$e->getMessage()); - return $this->json(5000, '操作失败'); - } - - return $this->json(); - } - - /** - * 取消 收藏 - */ - public function unRecord(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $id = $this->request->param('id/d', 0); - $action = $this->request->param('action/s', ''); - - try { - if ($accountId <= 0 || $id <= 0) { - return $this->json(4001, '无效请求'); - } - - if (!in_array($action, AccountRecord::allowActions())) { - return $this->json(4001, '操作类型参数错误'); - } - - if (!SpuModel::findById($id)) { - return $this->json(4001, '商品不存在'); - } - - AccountRecord::unRecord($accountId, $id, AccountRecord::TYPE_SPU, $action); - } catch (Exception $e) { - Log::error('[取消商品记录失败]'.$e->getMessage()); - return $this->json(5000, '操作失败'); - } - - return $this->json(); - } -} \ No newline at end of file diff --git a/app/controller/api/Statistics.php b/app/controller/api/Statistics.php deleted file mode 100644 index ebe8f5c..0000000 --- a/app/controller/api/Statistics.php +++ /dev/null @@ -1,77 +0,0 @@ -select()->toArray(); - - return $this->json(0, 'success', $data); - } - - /** - * 上报 - * - * @return Json - * @throws Exception - */ - public function report(): Json - { - $data = input(); - $accountId = $this->request->user['user_id'] ?? 0; - - if (empty($data)) { - return $this->json(); - } - - if (!is_array($data)) { - $data = json_decode($data, true); - } - - $insert = []; - if (count($data) > 1000) { - //TODO 太大就分片处理 - - } else { - foreach ($data as $d) { - if (!isset($d['e']) || !isset($d['t'])) { - return $this->json(4001, '参数错误'); - } - $arr = []; - $arr['event_id'] = (int) ($d['e'] ?? 0); - $arr['account_id'] = $accountId; - $arr['content_id'] = (int) ($d['c'] ?? 0); - $t = (strlen($d['t']) == 13) ? $d['t'] / 1000 : $d['t']; - $arr['created_at'] = date('Y-m-d H:i:s', $t); - - $insert[] = $arr; - } - } - - // 若量大 时间长 可丢入队列操作 - if (count($insert) > 0) { - (new AccountFootmarks())->saveAll($insert); - } - - return $this->json(); - } -} \ No newline at end of file diff --git a/app/controller/api/User.php b/app/controller/api/User.php index 6b314d4..4d7308d 100644 --- a/app/controller/api/User.php +++ b/app/controller/api/User.php @@ -1,70 +1,23 @@ request->user['user_id'] ?? 0; - return json(['code' => 0, 'msg' => 'Index page , I am '.$userId]); - } - /** * 登录 成功返回token及用户信息 * @@ -275,1890 +228,4 @@ class User extends Base } - /** - * 获取用户信息 - * - * @return Json - */ - public function info(): Json - { - try { - - $accountId = $this->request->user['user_id'] ?? 0; - - $fields = [ - 'id', 'coding', 'real_name', 'nickname', 'headimgurl', 'gender', 'mobile', - 'province', 'city', 'county', 'country', 'birthday', - 'score', 'status', 'position', 'invite_code', 'channel', - 'is_staff', 'is_active', "continuity_sign", "last_sign_online", 'coin_total', 'coin', 'phone_active' - ]; - $repo = AccountRepository::getInstance(); - $user = $repo->infoWithRelation($accountId, $fields); - - //更新连续签到次数 - AccountRepository::getInstance()->checkContinuitySign($user); - - if (empty($user)) { - return $this->json(4004, '没有相关的用户记录'); - } - - $user->headimgurl = File::convertCompleteFileUrl($user->headimgurl ?? ''); - - // 职工身份,校验纠正当前用户是否为职工 - $isWorker = (empty($user->worker) || $user->worker['status'] == Staff::STATUS_DISABLE) ? self::BOOL_FALSE : self::BOOL_TRUE; - $user['is_staff'] = $isWorker ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE; - - /** - * 补充信息: - * 文章收藏量、分享注册用户量(包含2级) - */ - $user->collects = $repo->countRecordByAction(AccountRecord::TYPE_CONTENT, AccountRecord::ACTION_COLLECT, $accountId); - $user->share_users = $repo->shareAccountCount($accountId); - $user->unread_messages = $repo->countUnReadMessage($accountId); - - $user = $user->toArray(); - $user = arrayNullToString($user); - - $user['rules'] = $repo->getAccountRules($user['id']); - $user['order_count'] = OrderRepository::getInstance()->orderCount($accountId); - $user["level"] = $repo->getUserLevel($user['coin_total']); - - unset($user['worker']); - return $this->json(0, 'success', $user); - - } catch (Exception $e) { - return $this->json(4000, '没有相关的用户记录'.$e->getMessage()); - } - } - - /** - * 首页优惠券 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function homeCoupon(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - - //是否有可领取的推荐优惠券(进入首页时弹出) - $homeCoupon = AccountCoupon::homeCoupon($accountId); - $data['has_coupon'] = (int) !empty($homeCoupon); - $data['home_coupon'] = $homeCoupon; - return $this->json(0, 'success', $data); - } - - /** - * 修改用户资料 - * 修改内容范围:姓名、昵称、联系电话、性别、地址(省、市、区/县) - * array $params 键值对形式 - */ - public function editInfo() - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $params = $this->request->param(); - $validate = new UserValidate(); - if (!$validate->scene('edit')->check($params)) { - return $this->json(4001, $validate->getError()); - } - - $accountId = $this->request->user['user_id'] ?? 0; - try { - AccountRepository::getInstance()->accountEditInfo($accountId, $params); - } catch (RepositoryException $e) { - return $this->json(4002, $e->getMessage()); - } catch (Exception $e) { - return $this->json(5000, '资料修改失败'); - } - return $this->json(); - } - - - /** - * 临时登录 通过openid登录 仅用于接口测试阶段 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function tempLogin(): Json - { - $params = $this->request->param(); - - if (!isset($params['openid'])) { - return $this->json(4001, '参数错误'); - } - - if (!$user = AccountRepository::getInstance()->findByOpenID($params['openid'])) { - return $this->json(4004, '账号不存在'); - } - - $data = [ - 'token' => Jwt::generate(['user_id' => $user['id'], 'nickname' => $user['nickname']]), - 'expire' => Jwt::expire() - ]; - - return $this->json(0, 'success', $data); - } - - /** - * 获取自主预约的参数信息 - * 支持7天内预约 - * - * @return Json - */ - public function appointmentParameters(): Json - { - $resp = [ - 'types' => [], - 'days' => [], - 'times' => [], - 'types_appointment' => [], - ]; - - try { - $repo = AccountRepository::getInstance(); - $timesResp = $repo->appointmentPeriodNormalList(); - $typesResp = $repo->appointmentTypes(['id', 'title', 'max']); - - $days = $repo->appointmentAllowDays(); - $times = $timesResp['list']->toArray(); - $types = $typesResp->toArray(); - $nowTime = time(); - - $typesAppointment = []; - $hadCountList = $repo->appointmentPeriodGroupCount(reset($days), end($days)); - foreach ($types as $type) { - $allowMax = $type['max']; - $daysTimes = []; - - foreach ($days as $day) { - $dayTimes = []; - foreach ($times as $time) { - $hadCount = $hadCountList[$type['id']][$day][$time['id']] ?? 0; - $isFull = false; - $disable = false; - $timeList = $repo->parsePeriodToTime($time['name']); - $endTime = 0; - if (!empty($timeList)) { - $endTime = strtotime($day.' '.$timeList['end']); - } - if ($hadCount >= $allowMax) { - $isFull = true; - $disable = true; - } - if ($endTime <= $nowTime) { - $disable = true; - } - $time['is_full'] = $isFull ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE; - $time['disable'] = $disable ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE; - $dayTimes[] = $time; - } - - $daysTimes[] = [ - 'day' => $day, - 'times' => $dayTimes - ]; - } - - $typesAppointment[] = [ - 'type' => $type, - 'days_times' => $daysTimes - - ]; - } - - // 现阶段暂不做工作日排班安排,默认7天内均可预约 - $daysList = []; - $weekList = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; - $weekStatus = AccountRepository::BOOL_TRUE; - foreach ($days as $day) { - $daysList[] = [ - 'week' => $weekList[date('w', strtotime($day))], - 'day' => $day, - 'status' => $weekStatus - ]; - } - - $resp = [ - 'types' => $types, - 'days' => $daysList, - 'times' => $times, - 'types_appointment' => $typesAppointment, - ]; - - } catch (TraitException $e) { - - } - - return $this->json(0, 'success', $resp); - } - - /** - * 查询指定预约类型下某天禁选的时间段 - * 已约满、时间段已过(超时) - */ - public function appointmentPeriodFull(): Json - { - $typeId = $this->request->param('type_id/d', 0); - $appointmentDay = $this->request->param('day/s', ''); - - if ($typeId <= 0 || empty($appointmentDay) || !strtotime($appointmentDay)) { - return $this->json(); - } - $appointmentDay = date('Y-m-d', strtotime($appointmentDay)); - - try { - $repo = AccountRepository::getInstance(); - - $type = $repo->appointmentTypeInfo($typeId); - if (empty($type)) { - return $this->json(); - } - - $hadCountList = $repo->appointmentPeriodGroupCount($appointmentDay, $appointmentDay, [$typeId]); - $typeDayCounts = $hadCountList[$typeId][$appointmentDay] ?? []; - $timesResp = $repo->appointmentPeriodNormalList(); - $times = $timesResp['list']->toArray(); - $nowTime = time(); - - $disablePeriods = []; - foreach ($times as $time) { - $hadCount = $typeDayCounts[$time['id']] ?? 0; - $timeList = $repo->parsePeriodToTime($time['name']); - $endTime = 0; - $disable = false; - $isFull = false; - if (!empty($timeList)) { - $endTime = strtotime($appointmentDay.' '.$timeList['end']); - } - if ($endTime <= $nowTime || $hadCount >= $type['max']) { - $disable = true; - $isFull = ($hadCount >= $type['max']); - } - - if ($disable) { - $time['is_full'] = $isFull ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE; - $time['disable'] = AccountRepository::BOOL_TRUE; - $disablePeriods[] = $time; - } - } - - return $this->json(0, 'success', $disablePeriods); - } catch (TraitException $e) { - return $this->json(); - } - } - - /** - * 提交预约申请 - */ - public function appointmentApply(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $params = $this->request->param(); - - try { - AccountRepository::getInstance()->addAppointment($accountId, $params); - } catch (TraitException $e) { - return $this->json(4001, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 用户预约记录 - * - * @return Json - */ - public function appointmentList(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 10); - - $page = $page <= 0 ? 1 : $page; - $size = $size <= 0 ? 10 : $size; - - try { - $repo = AccountRepository::getInstance(); - $resp = $repo->appointmentList($accountId, $page, $size); - $statusTextList = $repo->appointmentStatusTextList(); - foreach ($resp['list'] as $item) { - $item['status_text'] = ''; - // 现阶段预约完成,小程序端不显示状态描述 - if ($item['status'] != Appointment::STATUS_OVER) { - $item['status_text'] = $statusTextList[$item['status']] ?? ''; - } - } - - } catch (TraitException $e) { - $resp = [ - 'total' => 0, - 'current' => $page, - 'size' => $size, - 'list' => new Collection(), - ]; - } - - return $this->json(0, 'success', $resp); - } - - /** - * 取消预约 - */ - public function appointmentCancel(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $appointId = $this->request->param('appointment_id/d', 0); - try { - AccountRepository::getInstance()->cancelAppointment($accountId, $appointId); - } catch (TraitException $e) { - return $this->json(4001, $e->getMessage()); - } - - return $this->json(); - } - - /** - * 搜索历史 - * - * @return Json - */ - public function searchHistory(): Json - { - $page = input('page/d', 1); - $size = input('size/d', 10); - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = AccountRecord::findSearch($accountId, $page, $size); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 搜索历史 - * - * @return Json - */ - public function clearSearch(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - - try { - AccountRecord::clearSearch($accountId); - return $this->json(0, 'success'); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 个人分享中心 - * 统计:累计积分、累计绑定的客户数量(包含2级分销) - */ - public function shareCount(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - - $res = [ - 'score' => 0, - 'user_count' => [ - 'first' => 0, - 'second' => 0, - 'total' => 0, - ], - 'order_count' => 0, - ]; - - try { - $repo = AccountRepository::getInstance(); - $account = $repo->findById($accountId); - if (!empty($account)) { - $res['score'] = $account['score'] ?? 0; - $res['user_count'] = $repo->shareAccountCount($accountId); - - } - } catch (Exception $e) { - - } - - return $this->json(0, 'success', $res); - } - - /** - * 查看分享绑定用户的信息 - */ - public function shareUsers(): Json - { - $accountId = $this->request->user['user_id'] ?? 2; - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 10); - $grade = $this->request->param('grade/s', 'first'); // 层级[first|second] - - if (!in_array($grade, [AccountRepository::SHARE_GRADE_FIRST, AccountRepository::SHARE_GRADE_SECOND])) { - return $this->json(4001, '层级参数错误'); - } - - $page = $page <= 0 ? 1 : $page; - $size = $size <= 0 ? 10 : $size; - - $list = AccountRepository::getInstance()->shareUsers($accountId, $grade, $page, $size); - - return $this->json(0, 'success', $list); - } - - /** - * 生成用户个人海报 - */ - public function personalPoster(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $bgImg = $this->request->param('bg_src/s', ''); - $bgImg = empty($bgImg) ? '' : File::convertCompleteFileUrl($bgImg); - - try { - $account = AccountRepository::getInstance()->findById($accountId); - if (empty($account)) { - return $this->json(4000, '无效请求'); - } - - $domain = $this->request->domain(); - $inviteCode = $account['invite_code'] ?: md5($account['id']); - $inviteUrl = $domain.'/share?invite_code='.$inviteCode; - $logoImg = app()->getRootPath().'public/static/images/icon-logo.jpg'; - - $result = Builder::create() - ->writer(new PngWriter()) - ->writerOptions([]) - ->data($inviteUrl) - ->encoding(new Encoding('UTF-8')) - ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) - ->size(300) - ->margin(10) - ->roundBlockSizeMode(new RoundBlockSizeModeMargin()) - ->logoPath($logoImg) - ->logoResizeToHeight(100) - ->logoResizeToWidth(100) - ->logoPunchoutBackground(true) - ->build(); - - $dataUri = $result->getDataUri(); - $posterData = GdTool::generatePoster($dataUri, $bgImg); - - return $this->json(0, 'success', ['poster' => $posterData]); - } catch (Exception $e) { - AccountRepository::log('个人海报生成失败', $e); - return $this->json(5000, '个人海报生成失败'); - } - } - - /** - * 用户操作记录 分享、咨询 - * - * @return Json - * @throws Exception - */ - public function record(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $params = input('post.'); - - $rules = [ - 'type|操作类型' => 'require|in:content,other', - 'action|操作' => 'require', - ]; - - if (isset($params['type']) && $params['type'] == AccountRecord::TYPE_CONTENT) { - $rules['id|ID'] = 'require'; - } - - $validate = $this->validateByApi($params, $rules, ['type.in' => '类型错误', 'id.require' => '此类型 ID必传']); - - if ($validate !== true) { - return $validate; - } - - try { - $relationId = $params['id'] ?? 0; - $relationId = is_numeric($relationId) ? $relationId : 0; - AccountRecord::record($accountId, $params['type'], $params['action'], $relationId); - } catch (Exception $e) { - AccountRepository::log('记录用户操作失败', $e); - return $this->json(5001, '操作失败'); - } - - return $this->json(); - } - - /** - * 个人二维码 - */ - public function personalQr(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - try { - $account = AccountRepository::getInstance()->findById($accountId); - if (empty($account)) { - return $this->json(4000, '无效请求'); - } - - $nonceStr = uniqid(); - $qrDataStr = json_encode([ - 'user_coding' => $account['coding'], - 'nonce_str' => $nonceStr, - ]); - $logoImg = File::convertCompleteFileUrl($account['headimgurl']); - if (empty($logoImg)) { - $logoImg = app()->getRootPath().'public/static/images/icon-logo.jpg'; - } - - $result = Builder::create() - ->writer(new PngWriter()) - ->writerOptions([]) - ->data($qrDataStr) - ->encoding(new Encoding('UTF-8')) - ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) - ->size(300) - ->margin(10) - ->roundBlockSizeMode(new RoundBlockSizeModeMargin()) - ->logoPath($logoImg) - ->logoResizeToHeight(100) - ->logoResizeToWidth(100) - ->logoPunchoutBackground(true) - ->build(); - - $dataUri = $result->getDataUri(); - - return $this->json(0, 'success', ['qr' => $dataUri, 'nonce_str' => $nonceStr]); - } catch (Exception $e) { - AccountRepository::log('个人二维码生成失败', $e); - return $this->json(5000, '个人二维码生成失败'); - } - } - - /** - * 用户签到 - * 线下客服扫码:绑定客户关系 - */ - public function signIn(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - Log::info('用户签到绑定:'); - Log::info(json_encode($this->request->param(), JSON_UNESCAPED_UNICODE)); - - $accountId = $this->request->user['user_id'] ?? 0; - $userCoding = $this->request->param('user_coding/s', ''); - $nonceStr = $this->request->param('nonce_str/s', ''); - - if (empty($userCoding)) { - return $this->json(4000, '无效请求'); - } - - try { - $repo = AccountRepository::getInstance(); - $signAccount = $repo->findByUserCoding($userCoding); - if (empty($signAccount)) { - return $this->json(4001, '签到失败,没有相关的用户记录'); - } - - // 记录扫码日志 - ScanLog::log($signAccount['id'], $accountId, $nonceStr); - - $boundSign = $repo->getBoundService($signAccount['id'], CustomerReceive::ACTION_OFFLINE_SIGN); - if ($boundSign) { - $signAccount->save(['is_sign' => Account::COMMON_ON]); - return $this->json(0, '签到成功'); - } - - $signData = [ - 'customer_aid' => $signAccount['id'], - 'worker_aid' => $accountId, - 'created_at' => date('Y-m-d H:i:s'), - 'action' => CustomerReceive::ACTION_OFFLINE_SIGN, - 'pid' => 0, - 'path' => ',0,' - ]; - $boundService = $repo->getBoundService($signAccount['id'], CustomerReceive::ACTION_ONLINE_SERVICE); - if ($boundService) { - $signData['pid'] = $boundService['id']; - $signData['path'] = $boundService['path'].$boundService['id'].','; - } - - CustomerReceive::create($signData); - $signAccount->save(['is_sign' => Account::COMMON_ON, 'customer_service' => $accountId]); - - } catch (Exception $e) { - return $this->json(5000, '签到失败'); - } - - return $this->json(); - } - - /** - * 二维码打卡 - * 线下二维码扫码器扫码打卡 - */ - public function signByQr() - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - Log::info('扫码器提交内容:'); - Log::info(file_get_contents("php://input")); - - try { - $input = file_get_contents("php://input"); -// $input = 'vgdecoderesult={"user_coding":"210000000013","nonce_str":"618e1ad5bdded"}&&devicenumber=111&&otherparams='; - $info = []; - parse_str($input, $info); - - $parseInfo = json_decode($info['vgdecoderesult'], true); - $userCoding = $parseInfo['user_coding'] ?? ''; - $nonceStr = $parseInfo['nonce_str'] ?? ''; - - $deviceNumber = $info['devicenumber'] ?? ''; - - $repo = AccountRepository::getInstance(); - $signAccount = $repo->findByUserCoding($userCoding); - if (empty($signAccount)) { - return 'code=4000'; - } - - // 记录扫码日志 - ScanLog::log($signAccount['id'], 0, $nonceStr, ScanLog::TYPE_SIGN, ScanLog::ACTION_SCAN_BY_MACHINE, $deviceNumber); - - return 'code=0000'; - } catch (Exception $e) { - return 'code=4000'; - } - } - - /** - * 检测扫码是否成功 - * - * @return Json - */ - public function checkScan(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - if (empty($accountId)) { - return $this->json(4002, '请先登录'); - } - - $nonceStr = $this->request->param('nonce_str/s', ''); - if (empty($nonceStr)) { - return $this->json(4001, '随机字符串必填'); - } - - return $this->json(0, 'success', ['result' => (int) ScanLog::isScan($accountId, $nonceStr)]); - } - - /** - * 投诉与建议类型选择列表 - * (问题类型列表) - */ - public function feedbackTypes(): Json - { - $list = AccountRepository::getInstance()->feedbackTypes(); - return $this->json(0, 'success', $list); - } - - /** - * 提交反馈意见 - */ - public function addFeedback(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $params = [ - 'type_id' => $this->request->param('type_id/d', 0), - 'content' => postFilter($this->request->param('content/s', '')), - 'user_name' => postFilter($this->request->param('user_name/s', '')), - 'user_phone' => postFilter($this->request->param('user_phone/s', '')), - ]; - - try { - AccountRepository::getInstance()->addFeedback($accountId, $params); - } catch (TraitException $e) { - return $this->json(4001, $e->getMessage()); - } - - return $this->json(0, '您已提交成功,感谢您的反馈!'); - } - - /** - * 用户消息 - */ - public function messages(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 10); - $type = $this->request->param('type/s', ''); - - $page = $page <= 0 ? 1 : $page; - $size = $size <= 0 ? 10 : $size; - - $repo = AccountRepository::getInstance(); - $whereMap = []; - $fields = [ - 'id', 'type', 'target', 'title', 'summary', 'content', 'status', - 'sort', 'created_at', 'send_at' - ]; - $orders = ['sort' => 'desc', 'id' => 'desc']; - $regTime = ''; - $account = $repo->findById($accountId); - if ($account) { - $regTime = $account['created_at'] ?? ''; - } - - if ($type == 'reminders') { - $whereMap[] = ['type', '=', $type]; - } - - $resp = $repo->messageList($whereMap, $fields, $page, $size, function ($q) use ($accountId, $regTime) { - return $q->whereTime('send_at', '<=', date('Y-m-d H:i:s')) - ->when(!empty($regTime), function ($q3) use ($regTime) { - $q3->whereTime('send_at', '>=', $regTime); - }) - ->where(function ($q3) use ($accountId) { - $q3->whereRaw('(target = "part" and find_in_set("'.$accountId.'", target_list)) or target <> "part"'); - }); - }, $orders); - - $msgIds = $resp['list']->column('id'); - $hadReadMsgIds = $repo->getHadReadMessageIds($accountId, $msgIds); - $msgTypeTextList = $repo->messageTypeTextList(); - foreach ($resp['list'] as $item) { - $item['type_text'] = $msgTypeTextList[$item['type']] ?? ''; - $item['is_read'] = in_array($item['id'], $hadReadMsgIds) ? AccountRepository::BOOL_TRUE : AccountRepository::BOOL_FALSE; - } - - // todo 获取列表后更新阅览日志记录 - $repo->addReadLogs($accountId, $msgIds); - - return $this->json(0, 'success', $resp); - } - - /** - * 查看消息详情 - * 添加阅览日志记录 - */ - public function messageInfo(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $msgId = $this->request->param('message_id/d', 0); - - $repo = AccountRepository::getInstance(); - $fields = [ - 'id', 'type', 'target', 'title', 'summary', 'content', 'target_list', - 'status', 'sort', 'created_at', 'send_at' - ]; - $message = $repo->messageInfo($msgId, $fields); - if (empty($message)) { - return $this->json(4004, '没有相关的消息记录'); - } - - if ($message['target'] == Message::TARGET_PART) { - $targetList = empty($message['target_list']) ? [] : explode(',', $message['target_list']); - if (!in_array($accountId, $targetList)) { - return $this->json(4001, '没有查看权限'); - } - } elseif (!empty($message['send_at']) && strtotime($message['send_at']) > time()) { - return $this->json(4001, '没有查看权限'); - } - - $repo->addReadLogs($accountId, [$msgId]); - - $msgTypeTextList = $repo->messageTypeTextList(); - $message['type_text'] = $msgTypeTextList[$message['type']] ?? ''; - $message['is_read'] = AccountRepository::BOOL_TRUE; - unset($message['target_list']); - - return $this->json(0, 'success', $message); - } - - /** - * 医生列表 - */ - public function doctorList(): Json - { - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 10); - $keyword = $this->request->param('keyword/s', ''); - - $page = $page <= 0 ? 1 : $page; - $size = $size <= 0 ? 10 : $size; - - $repo = AccountRepository::getInstance(); - - $whereMap = []; - $fields = []; - $searchName = ''; - if (!empty($keyword)) { - /** - * 关键词查询范围:问题、病种、医生姓名 - */ - $doctorIds = $repo->searchRelationDoctorIds($keyword); - if (count($doctorIds)) { - $whereMap[] = ['id', 'in', $doctorIds]; - } else { - $searchName = $keyword; - } - } - - $resp = $repo->findDoctorListByWhere($whereMap, $fields, $page, $size, [], function ($q) use ($searchName) { - if (empty($searchName)) { - return $q; - } else { - // 二维数组JSON查询 - return $q->whereRaw('(JSON_CONTAINS(`extra`, JSON_OBJECT("name", "'.$searchName.'")) or (`name` like "'.$searchName.'%") )'); - } - }); - - $list = $resp['list']->toArray(); - $diseaseFields = ['disease_id', 'disease_name', 'disease_pid']; - $accountFields = [ - 'id', 'coding', 'real_name', 'nickname', 'headimgurl', 'gender', 'mobile', - 'province', 'city', 'county', 'country', 'birthday', 'status', 'invite_code', - ]; - - foreach ($list as &$item) { - $diseases = []; - foreach ($item['diseases'] as $disease) { - $diseases[$disease['disease_id']] = arrayKeysFilter($disease, $diseaseFields); - } - $item['diseases'] = array_values($diseases); - - $account = arrayKeysFilter($item['account'], $accountFields); - $account['headimgurl'] = File::convertCompleteFileUrl($account['headimgurl'] ?? ''); - $item['account'] = $account; - } - unset($item); - - $resp['list'] = arrayNullToString($list); - - return $this->json(0, 'success', $resp); - } - - /** - * 医生详情 - */ - public function doctorInfo(): Json - { - $doctorId = $this->request->param('doctor_id/d', 0); - - $repo = AccountRepository::getInstance(); - $whereMap = ['id' => $doctorId]; - $doctor = $repo->findDoctorByWhere($whereMap); - if (empty($doctor)) { - return $this->json(4004, '没有相关的记录'); - } - $doctor = $doctor->toArray(); - - // 过滤负责的病种,避免重复 - $diseases = []; - $diseaseFields = ['disease_id', 'disease_name', 'disease_pid']; - foreach ($doctor['diseases'] as $item) { - $diseases[$item['disease_id']] = arrayKeysFilter($item, $diseaseFields); - } - $doctor['diseases'] = array_values($diseases); - - // 管理的前端用户信息过滤 - $accountFields = [ - 'id', 'coding', 'real_name', 'nickname', 'headimgurl', 'gender', 'mobile', - 'province', 'city', 'county', 'country', 'birthday', 'status', 'invite_code', - ]; - $account = arrayKeysFilter($doctor['account'], $accountFields); - $account['headimgurl'] = File::convertCompleteFileUrl($account['headimgurl'] ?? ''); - $doctor['account'] = $account; - - // null空值转换 - $doctor = arrayNullToString($doctor); - return $this->json(0, 'success', $doctor); - } - - - /** - * 客户足迹 - * - * @return Json - */ - public function footmarks(): Json - { - $page = input('page/d', 1); - $size = input('size/d', 20); - $customerId = input('customer_id/d', 0); //指定查询的客户 默认全部 - $keyword = input('keyword/s', ''); //用户姓名或电话 - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $data = AccountRepository::getInstance()->footmarks($accountId, $customerId, $keyword, $page, $size); - - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 前台权限列表 - * - * @return Json - */ - public function ruleList(): Json - { - try { - $data = AccountRule::field('id,title,name,sort') - ->order('sort', 'desc') - ->order('id', 'asc') - ->select(); - - return $this->json(0, 'success', $data); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 获取已绑定线上客服的客户列表 - */ - public function getBindServiceList(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $keyword = input('keyword/s', ''); - $page = input('page/d', 1); - $size = input('size/d', 20); - $type = input('type/s', '');//mine个人绑定的客户 其他获取全部 - - try { - $where = []; - $where[] = ['customer_service', '>', 0]; - if ($type == 'mine') { - $where[] = ['customer_service', '=', $accountId]; - } - - if (!empty($keyword)) { - $where[] = ['nickname|mobile', 'like', '%'.$keyword.'%']; - } - - $list = Account::findList($where, ['id', 'nickname', 'mobile', 'customer_service'], $page, $size, function ($q) { - return $q->with([ - 'serviceList' => function ($query) { - $query->field('id,account_id,name,phone'); - } - ])->order('id', 'desc'); - - }); - - $list['list'] = $list['list']->each(function ($item) { - if (!$item->serviceList) { - $item->serviceList = new Staff(); - $item->serviceList->id = 0; - $item->serviceList->account_id = 0; - $item->serviceList->name = '所属员工已失效'; - $item->serviceList->phone = ''; - } - if (isset($item->serviceList->phone)) { - $item->serviceList->phone = !empty($item->serviceList->phone) ? stringDesensitization($item->serviceList->phone) : ''; - } - - $item->service = $item->serviceList; - unset($item->serviceList); - - if (isset($item->mobile)) { - $item->mobile = !empty($item->mobile) ? stringDesensitization($item->mobile) : ''; - } - }); - - return $this->json(0, 'success', $list); - } catch (Exception $e) { - Log::error('获取客户绑定列表失败'.$e->getMessage()); - return $this->json(5000, '获取客户绑定列表失败!'); - } - - } - - /** - * 随机绑定客服(线上客服) - */ - public function randBindService(): Json - { - // 目前关掉随机绑定客服功能 - return $this->json(); - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - - try { - $repo = AccountRepository::getInstance(); - - if (!$account = $repo->findById($accountId)) { - return $this->json(4001, '请先登录'); - } - - $boundService = $repo->getBoundService($accountId, CustomerReceive::ACTION_ONLINE_SERVICE); - if ($boundService) { - return $this->json(0, '绑定成功'); - } - - // 客服列表 - $servicerList = Staff::getStaff(Staff::ROLE_CUSTOMER_ONLINE); - - if ($servicerList['total'] <= 0) { - return $this->json(4002, '还没有客服!'); - } - - $accountIds = $servicerList['list']->where('status', Staff::COMMON_ON)->column('account_id'); - $servicerId = $accountIds[array_rand($accountIds)];//随机获取一个客服ID - - $boundData = [ - 'customer_aid' => $accountId, - 'worker_aid' => $servicerId, - 'action' => CustomerReceive::ACTION_ONLINE_SERVICE, - 'pid' => 0, - 'path' => ',0,', - 'created_at' => date('Y-m-d H:i:s') - ]; - - CustomerReceive::create($boundData); - $account->save(['customer_service' => $servicerId]); - - } catch (Exception $e) { - Log::error('随机绑定客服失败'.$e->getMessage()); - return $this->json(5000, '绑定失败!'); - } - - return $this->json(); - } - - /** - * 用户绑定客服人员(线上客服) - */ - public function bindService(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - Log::info('线上客服绑定:'); - Log::info(json_encode($this->request->param(), JSON_UNESCAPED_UNICODE)); - $accountId = $this->request->user['user_id'] ?? 0; - $serviceCoding = $this->request->param('service_coding/s', ''); - if (empty($serviceCoding)) { - return $this->json(4000, '无效请求'); - } - - try { - $repo = AccountRepository::getInstance(); - $serviceAccount = $repo->findByUserCoding($serviceCoding); - if (empty($serviceAccount)) { - return $this->json(4001, '绑定客服失败!没有相关的客服记录'); - } - - $boundService = $repo->getBoundService($accountId, CustomerReceive::ACTION_ONLINE_SERVICE); - if ($boundService) { - return $this->json(0, '绑定成功'); - } - - $service = $repo->findServiceByWhere(['account_id' => $serviceAccount['id']]); - if (empty($service)) { - return $this->json(4002, '绑定客服失败!没有相关的客服记录'); - } elseif ($service['status'] == staff::STATUS_DISABLE) { - return $this->json(4003, '绑定客服失败!该客服账号已被冻结'); - } - - $boundData = [ - 'customer_aid' => $accountId, - 'worker_aid' => $serviceAccount['id'], - 'action' => CustomerReceive::ACTION_ONLINE_SERVICE, - 'pid' => 0, - 'path' => ',0,' - ]; - - CustomerReceive::create($boundData); - - } catch (Exception $e) { - return $this->json(5000, '绑定失败!'); - } - - return $this->json(); - } - - /** - * 客服二维码 - * @return Json - */ - public function serviceQr(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - try { - $account = AccountRepository::getInstance()->findById($accountId); - if (empty($account)) { - return $this->json(4000, '无效请求'); - } - - $qrDataStr = $this->request->domain().'/bind-servicer?coding='.$account['coding']; - $logoImg = app()->getRootPath().'public/static/images/icon-logo.jpg'; - - $result = Builder::create() - ->writer(new PngWriter()) - ->writerOptions([]) - ->data($qrDataStr) - ->encoding(new Encoding('UTF-8')) - ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) - ->size(300) - ->margin(10) - ->roundBlockSizeMode(new RoundBlockSizeModeMargin()) - ->logoPath($logoImg) - ->logoResizeToHeight(100) - ->logoResizeToWidth(100) - ->logoPunchoutBackground(true) - ->build(); - - $dataUri = $result->getDataUri(); - - return $this->json(0, 'success', ['qr' => $dataUri]); - } catch (Exception $e) { - AccountRepository::log('客服二维码生成失败', $e); - return $this->json(5000, '客服二维码生成失败'); - } - } - - /** - * 客户列表 - * - * @return Json - * @throws Exception - */ - public function customer(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $type = input('type/s', 'all'); - $page = input('page/d', 1); - $size = input('size/d', 20); - - try { - if ($accountId == 0) { - return $this->json(6001, '请先登录'); - } - - $where = []; - if ($type !== 'all') { - $where[] = ['channel', '=', $type]; - } - $field = ['id', 'nickname', 'real_name', 'headimgurl', 'mobile', 'channel', 'created_at', 'customer_service']; - $data = AccountRepository::getInstance()->customerList($where, $field, $accountId, $page, $size); - $data['list'] = $data['list']->each(function ($item) { - $item->real_name = $item->real_name ?? ''; - unset($item->tags); - }); - return $this->json(0, 'success', $data); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - ArchivesRepository::log($e->getMessage(), $e); - return $this->json(5000, '操作失败'); - } - } - - /** - * 来源渠道列表 - * - * @return Json - * @throws Exception - */ - public function channel(): Json - { - return $this->json(0, 'success', Account::channelTextList()); - } - - /** - * 客户分配(分配给在线客服) - * - * @return Json - * @throws Exception - */ - public function customerAllot(): Json - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $params = input('post.'); - - $rules = [ - 'customer_id|客户' => 'require|number', - 'staff_id|员工' => 'require|number', - ]; - - $validate = $this->validateByApi($params, $rules); - - if ($validate !== true) { - return $validate; - } - - try { - if (!$staff = Staff::findOne(['account_id' => $accountId])) { - return $this->json(4001, '你不是员工'); - } - - $staffRules = explode(',', $staff['rules']); - - if (!in_array('customer-allot', $staffRules)) { - return $this->json(4002, '无此权限'); - } - - CustomerReceive::allotService($params['customer_id'], $params['staff_id']); - } catch (RepositoryException $e) { - return $this->json(4001, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('分配客户失败', $e); - return $this->json(5001, '操作失败'); - } - - return $this->json(); - } - - /** - * 客服列表 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function servicerList(): Json - { - $roleName = 'customer-online';//在线客服的角色 - $roleId = AccountRole::where('name', $roleName)->value('id'); - $serviceList = Staff::whereRaw('FIND_IN_SET('.$roleId.', account_roles)') - ->field('name,account_id as id') - ->order('id', 'asc') - ->select(); - - return $this->json(0, 'success', $serviceList); - } - - /** - * 绑定手机 - * - * @return bool|Json - * @throws Exception - */ - public function bindPhone() - { - if (!$this->request->isPost()) { - return $this->json(4000, '无效请求'); - } - - $accountId = $this->request->user['user_id'] ?? 0; - $params = input('post.'); - - $rules = [ - 'encryptedData|加密数据' => 'require', - 'iv|IV' => 'require', - ]; - - $validate = $this->validateByApi($params, $rules); - - if ($validate !== true) { - return $validate; - } - - try { - if (!$account = Account::findById($accountId)) { - return $this->json(4000, '用户不存在'); - } - // 解密手机相关数据 若存在手机则覆盖 - $minApp = WechatApplets::getInstance(); - $sessionKey = $this->request->user['session_key'] ?? ''; - $decryptData = $minApp->encryptor->decryptData($sessionKey, $params['iv'], $params['encryptedData']); - $phone = $decryptData['phoneNumber'] ?? ''; // 通过iv和加密数据 解密出手机号 - - if ($phone) { - $account->save(['mobile' => $phone, 'phone_active' => Account::COMMON_ON]); - } - return $this->json(0, 'success', ['phone' => $phone]); - } catch (Exception $e) { - AccountRepository::log('手机绑定失败', $e); - return $this->json(5001, '手机绑定失败'); - } - } - - /** - * 领取优惠券 - * - * @return Json - * @throws Exception - */ - public function getCoupon(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $couponID = input('coupon_id/d', 0); - - try { - AccountRepository::getInstance()->getCoupon($accountId, $couponID); - return $this->json(); - } catch (ApiRedirectException $e) { - return $this->json(302, $e->getMessage()); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('领取优惠券失败', $e); - return $this->json(5001, '领取优惠券失败'); - } - } - - /** - * 展示体验券 生成token - * - * @return Json - * @throws Exception - */ - public function exhibitionExperienceCoupon(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $couponID = input('coupon_id/d', 0); - try { - $coupon = AccountRepository::getInstance()->userCouponInfo($accountId, $couponID); - $time = time(); - //不存在 - if (empty($coupon) || !isset($coupon['coupon'])) { - return $this->json(4002, "优惠券不存在"); - } - //状态异常 - if ($coupon['status'] != AccountCoupon::STATUS_NORMAL) { - return $this->json(4002, "优惠券状态已经不能使用"); - } - //未开始 - if (strtotime($coupon['coupon']["begin_at"]) > $time) { - return $this->json(4002, "优惠券还未到开始使用时间"); - } - //过期 - - if (strtotime($coupon['coupon']["end_at"]) < $time) { - return $this->json(4002, "优惠券已过期"); - } - - if ($coupon['is_taste'] != AccountCoupon::COMMON_ON) { - return $this->json(4002, "优惠券不是体验券"); - } - - $secret = AccountRepository::getInstance()->createExperienceCouponQR($accountId, $couponID); - - $url = ($this->request->domain()."/api/staff/coupon/write-off-experience-coupon?account_id=$accountId&&coupon_id=$couponID&&secret=$secret"); - - return $this->json(0, "success", ["url" => $url, "secret" => $secret]); - } catch (ApiRedirectException $e) { - return $this->json(302, $e->getMessage()); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('获取优惠券失败', $e); - return $this->json(5001, '获取优惠券失败'); - } - } - - /** - * 获取优惠券列表 - * - * @return Json - * @throws Exception - */ - public function getCouponList(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $status = input('status/s', AccountCoupon::STATUS_NORMAL); - $page = input('page/d', 1); - $size = input('size/d', 0); - - try { - $data = AccountRepository::getInstance()->couponList($status, $accountId, $page, $size); - return $this->json(0, 'success', $data); - } catch (Exception $e) { - AccountRepository::log('获取优惠券列表失败', $e); - return $this->json(5001, '获取优惠券列表失败'); - } - } - - /** - * 获取地址列表 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function address(): Json - { - $userId = $this->request->user['user_id'] ?? 0; - $list = AccountRepository::getInstance()->findAddressByUid($userId); - - return $this->json(0, 'success', $list); - } - - /** - * 保存地址 - * - * @return Json - */ - public function addressSave(): Json - { - $userId = $this->request->user['user_id'] ?? 0; - $params = $this->request->param(); - $validate = new UserValidate(); - $params['user_id'] = $userId; - - if (!$validate->scene('address')->check($params)) { - return $this->json(4000, $validate->getError()); - } - - AccountRepository::getInstance()->saveAddress($params); - - return $this->json(); - } - - /** - * 地址详情 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function addressInfo(): Json - { - if (!$id = input('id/d', 0)) { - return $this->json(4000, '参数错误'); - } - - $info = AccountRepository::getInstance()->findAddressById($id); - - return $this->json(0, 'success', $info); - } - - /** - * 地址删除 - * - * @return Json - */ - public function addressDel(): Json - { - if (!$id = input('id/d', 0)) { - return $this->json(4000, '参数错误'); - } - - AccountRepository::getInstance()->delAddress($id); - - return $this->json(); - } - - /** - * 孔雀币管理页面 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function coinLoad() - { - $accountId = $this->request->user['user_id']; - $account = Account::findById($accountId); - if (empty($account)) { - return $this->json(6001, '未登录'); - } - - Config::load('extra/coin_withdrawal', 'coin_withdrawal'); - $coinWithdrawal = config('coin_withdrawal'); - - - //审核中的提现金额 - $withdrawalIng = AccountRepository::getInstance()->withdrawalIng($accountId); - //已经提现金额 - $withdrawald = AccountRepository::getInstance()->withdrawald($accountId); - - $key = $account['is_staff'] ? "withdrawal_proportion_staff" : "withdrawal_proportion_account"; - return $this->json(0, "ok", - [ - "coin" => $account["coin"], - "withdrawal_ing" => $withdrawalIng, - "withdrawald" => $withdrawald, - "withdrawal_proportion" => $coinWithdrawal[$key] ?? ["coin" => 0, "money" => 0], - ]); - } - - /** - * 提现和获取孔雀币记录列表 - * - * @param $type string coin / withdrawal - * @return Json - */ - public function withdrawalAndGetCoinList() - { - $page = input('page/d', 1); - $limit = input('size/d', 10); - $type = input("type/s", "coin"); - $accountId = $this->request->user['user_id']; - //如果是获取列表 - if ($type == AccountDataLog::TYPE_COIN) { - $items = AccountDataLog::findList([ - ["account_id", "=", $accountId,], - ["type", "=", AccountDataLog::TYPE_COIN], - ["action", "not in", [AccountDataLog::ACTION_WITHDRAWAL, AccountDataLog::ACTION_WITHDRAWAL_RETURN]], - - ], [], $page, $limit, - null, ["id" => "desc"]); - } else { - $items = AccountDataLog::findList([ - ["account_id", "=", $accountId,], - ["type", "=", AccountDataLog::TYPE_COIN], - ["action", "in", [AccountDataLog::ACTION_WITHDRAWAL, AccountDataLog::ACTION_WITHDRAWAL_RETURN]], - - ], [], $page, $limit, - null, ["id" => "desc"]); - } - - return $this->json(0, '操作成功', $items); - } - - /** - * 孔雀币收支记录 - * - * @return Json - * @throws Exception - */ - public function coinLog(): Json - { - $page = input('page/d', 1); - $limit = input('size/d', 10); - $type = input("type/s", "in"); //in=收入 out=支出 默认in - $accountId = $this->request->user['user_id'] ?? 0; - - $where = []; - $where[] = ["account_id", "=", $accountId]; - $where[] = ["type", "=", AccountDataLog::TYPE_COIN]; - if ($type == 'in') { - $where[] = ["num", ">", 0]; - } - if ($type == 'out') { - $where[] = ["num", "<", 0]; - } - $items = AccountDataLog::findList($where, [], $page, $limit, null, ['id' => 'desc']); - - return $this->json(0, '操作成功', $items); - } - - /** - * 积分收支记录 - * - * @return Json - * @throws Exception - */ - public function scoreLog(): Json - { - $page = input('page/d', 1); - $limit = input('size/d', 10); - $type = input("type/s", "in"); //in=收入 out=支出 默认in - $accountId = $this->request->user['user_id'] ?? 0; - - $where = []; - $where[] = ["account_id", "=", $accountId]; - $where[] = ["type", "=", AccountDataLog::TYPE_SCORE]; - if ($type == 'in') { - $where[] = ["num", ">", 0]; - } - if ($type == 'out') { - $where[] = ["num", "<", 0]; - } - $items = AccountDataLog::findList($where, [], $page, $limit, null, ['id' => 'desc']); - - return $this->json(0, '操作成功', $items); - } - - /** - * 孔雀币管理页面 - * - * @return Json - * @throws DataNotFoundException - * @throws DbException - * @throws ModelNotFoundException - */ - public function scoreLoad(): Json - { - $accountId = $this->request->user['user_id']; - $account = Account::findById($accountId); - if (empty($account)) { - return $this->json(6001, '未登录'); - } - - return $this->json(0, "ok", - [ - "score" => $account["score"], - "share" => AccountRepository::getInstance()->shareAccountCount($accountId), - ]); - } - - /** - * 发起提现孔雀币 - * - * @param $type string coin / withdrawal - * @return Json - */ - public function withdrawalCoin() - { - $coin = input("coin/d", 0); - $accountId = $this->request->user['user_id']; - $account = Account::findOne(["id" => $accountId], [], function ($q) { - return $q->lock(true); - }); - if (empty($account)) { - return $this->json(6001, '未登录'); - } - if ($coin <= 0) { - return $this->json(4000, '提现孔雀币不能小于0'); - } - - //换算出 1元 = 多少孔雀币 - - - try { - //本次提现共计金额 - $totalMoney = AccountRepository::getInstance()->transformationCoinOrMoney($coin, "money", $account['is_staff']); - $totalMoney = $totalMoney / 100;//分转元 - if ($account['coin'] < $coin) { - return $this->json(4004, '孔雀币不足'); - } - - $key = ($account['is_staff'] ? AccountDataLog::withdrawal_proportion_staff : AccountDataLog::withdrawal_proportion_account); - $coinWithdrawal = config('coin_withdrawal'); - $withdrawalProportion = $coinWithdrawal[$key]; - } catch (Exception $e) { - return $this->json(5004, '提现失败'); - } catch (RepositoryException $e) { - return $this->json(5005, $e->getMessage()); - } - - //条件满足 开始写入提现 - Db::startTrans(); - try { - //写入--积分孔雀币日志 - AccountDataLog::log($account['id'], - "提现-扣除孔雀币", - $coin * -1, - AccountDataLog::TYPE_COIN, - AccountDataLog::ACTION_WITHDRAWAL, - $account[AccountDataLog::TYPE_COIN] - $coin - ); - - //写入提现记录 - $accountCoinWithdrawalData = [ - "account_id" => $account['id'], - "coin_number" => $coin, - "role" => ($account["is_staff"] == 0) ? AccountCoinWithdrawal::$role_account : AccountCoinWithdrawal::$role_staff, - "money" => $totalMoney, - "proportion" => $withdrawalProportion["coin"].":".$withdrawalProportion["money"], - "status" => AccountCoinWithdrawal::$status_default, - "created_at" => date("Y-m-d H:i:s"), - ]; - AccountCoinWithdrawal::create($accountCoinWithdrawalData); - - //扣除孔雀币 - $account->save(["coin" => ($account["coin"] - $coin)]); - Db::commit(); - return $this->json(); - - } catch (Exception $e) { - Db::rollback(); - return $this->json(5000, "提现失败-2"); - } catch (RepositoryException $e) { - Db::rollback(); - return $this->json(5000, "提现失败-3"); - } - } - - /** - * 获取孔雀币抵扣金额 - * - * @return Json - * @throws Exception - */ - public function getCoinPrice(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $amount = input('amount/f', 0); - $type = input('get_type/s', 'money');//获取类型 money=根据孔雀币获取金额 coin=根据金额获取孔雀币 - - try { - if (!$account = AccountRepository::getInstance()->findById($accountId)) { - return $this->json(4001, '用户不存在'); - } - if ($type == 'money') { - $amount = AccountRepository::getInstance() - ->transformationCoinOrMoney($amount, 'money', $account['is_staff'] == 1); - } else { - $amount = AccountRepository::getInstance() - ->transformationCoinOrMoney($amount, 'coin', $account['is_staff'] == 1); - } - return $this->json(0, 'success', ['amount' => $amount]); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('获取孔雀币抵扣金额失败', $e); - return $this->json(5001, '获取孔雀币抵扣金额失败'); - } - } - - /** - * 我的订单 - * - * @return Json - * @throws RepositoryException - */ - public function order(): Json - { - $userId = $this->request->user['user_id'] ?? 0; - $page = $this->request->param('page/d', 1); - $size = $this->request->param('size/d', 20); - $tag = $this->request->param('tag/s', 'all'); - - $res = OrderRepository::getInstance()->mine($userId, $tag, $page, $size); - return $this->json(0, 'success', $res); - } - - /** - * 立即免拼 需要单人开团允许 - * - * @return Json - */ - public function openOne(): Json - { - $userId = $this->request->user['user_id'] ?? 0; - $coding = input('order_coding/s'); - - try { - if (empty($coding)) { - return $this->json(4001, '参数错误'); - } - OrderRepository::getInstance()->openOne($userId, $coding); - return $this->json(); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('立即免拼失败', $e); - return $this->json(5001, '立即免拼失败'); - } - } - - /** - * 订单详情 - * - * @return Json - * @throws RepositoryException - */ - public function orderDetail(): Json - { - $id = input('id/d', 0); - $userId = $this->request->user['user_id'] ?? 0; - - $res = OrderRepository::getInstance()->detail($id); - if (!$res) { - return $this->json(4000, '订单不存在'); - } - - if ($res['account_id'] !== $userId) { - return $this->json(4000, '不是您的订单'); - } - - return $this->json(0, 'success', $res); - } - - - /** - * 我的海报列表 - * - * @return Json - */ - public function poster(): Json - { - $page = input('page/d', 1); - $size = input('size/d', 10); - $userId = $this->request->user['user_id'] ?? 0; - - try { - $list = AccountRepository::getInstance()->poster($userId, $page, $size); - return $this->json(0, 'success', $list); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('获取个人海报列表失败', $e); - return $this->json(5001, '海报列表获取失败'); - } - } - - /** - * 生成用户指定海报 - */ - public function posterInfo(): Json - { - $accountId = $this->request->user['user_id'] ?? 0; - $src = $this->request->param('poster_src/s', ''); - $domain = $this->request->domain(); - try { - $posterData = AccountRepository::getInstance()->posterInfo($accountId, $src, $domain); - - return $this->json(0, 'success', ['poster' => $posterData]); - } catch (RepositoryException $e) { - return $this->json(4000, $e->getMessage()); - } catch (Exception $e) { - AccountRepository::log('个人海报生成失败', $e); - return $this->json(5000, '个人海报生成失败'); - } - } - } \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..b796593 --- /dev/null +++ b/index.html @@ -0,0 +1,40 @@ + + +
+ +