BaseLogic.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\basic;
  8. use plugin\saiadmin\app\cache\UserInfoCache;
  9. use plugin\saiadmin\exception\ApiException;
  10. use support\think\Db;
  11. /**
  12. * 逻辑层基础类
  13. * @package app\service
  14. * @method static where($data) think-orm的where方法
  15. * @method static find($id) think-orm的find方法
  16. * @method static findOrEmpty($id) think-orm的findOrEmpty方法
  17. * @method static hidden($data) think-orm的hidden方法
  18. * @method static order($data) think-orm的order方法
  19. * @method static save($data) think-orm的save方法
  20. * @method static create($data) think-orm的create方法
  21. * @method static saveAll($data) think-orm的saveAll方法
  22. * @method static update($data, $where, $allow = []) think-orm的update方法
  23. * @method static select() think-orm的select方法
  24. * @method static count($data) think-orm的count方法
  25. * @method static max($data) think-orm的max方法
  26. * @method static min($data) think-orm的min方法
  27. * @method static sum($data) think-orm的sum方法
  28. * @method static avg($data) think-orm的avg方法
  29. */
  30. class BaseLogic
  31. {
  32. /**
  33. * @var object 模型注入
  34. */
  35. protected $model;
  36. /**
  37. * @var object 管理员信息
  38. */
  39. protected $adminInfo;
  40. /**
  41. * 排序字段
  42. * @var string
  43. */
  44. protected string $orderField = '';
  45. /**
  46. * 排序方式
  47. * @var string
  48. */
  49. protected string $orderType = 'ASC';
  50. /**
  51. * 初始化
  52. * @param $user
  53. * @return void
  54. */
  55. public function init($user): void
  56. {
  57. $this->adminInfo = $user;
  58. }
  59. /**
  60. * 设置排序字段
  61. * @param $field
  62. * @return void
  63. */
  64. public function setOrderField($field): void
  65. {
  66. $this->orderField = $field;
  67. }
  68. /**
  69. * 设置排序方式
  70. * @param $type
  71. * @return void
  72. */
  73. public function setOrderType($type): void
  74. {
  75. $this->orderType = $type;
  76. }
  77. /**
  78. * 数据库事务操作
  79. * @param callable $closure
  80. * @param bool $isTran
  81. * @return mixed
  82. */
  83. public function transaction(callable $closure, bool $isTran = true): mixed
  84. {
  85. return $isTran ? Db::transaction($closure) : $closure();
  86. }
  87. /**
  88. * 添加数据
  89. * @param $data
  90. * @return mixed
  91. */
  92. public function add($data): mixed
  93. {
  94. $this->model->save($data);
  95. return $this->model->getKey();
  96. }
  97. /**
  98. * 修改数据
  99. * @param $id
  100. * @param $data
  101. * @return mixed
  102. */
  103. public function edit($id, $data): mixed
  104. {
  105. $model = $this->model->findOrEmpty($id);
  106. if ($model->isEmpty()) {
  107. throw new ApiException('数据不存在');
  108. }
  109. return $model->save($data);
  110. }
  111. /**
  112. * 读取数据
  113. * @param $id
  114. * @return mixed
  115. */
  116. public function read($id): mixed
  117. {
  118. $model = $this->model->findOrEmpty($id);
  119. if ($model->isEmpty()) {
  120. throw new ApiException('数据不存在');
  121. }
  122. return $model;
  123. }
  124. /**
  125. * 删除数据
  126. * @param $ids
  127. */
  128. public function destroy($ids)
  129. {
  130. $this->model->destroy($ids);
  131. }
  132. /**
  133. * 搜索器搜索
  134. * @param array $searchWhere
  135. * @return mixed
  136. */
  137. public function search(array $searchWhere = []): mixed
  138. {
  139. $withSearch = array_keys($searchWhere);
  140. $data = $searchWhere;
  141. foreach ($withSearch as $k => $v) {
  142. if ($data[$v] === '') {
  143. unset($data[$v]);
  144. unset($withSearch[$k]);
  145. }
  146. }
  147. return $this->model->withSearch($withSearch, $data);
  148. }
  149. /**
  150. * 分页查询数据
  151. * @param $query
  152. * @return mixed
  153. */
  154. public function getList($query): mixed
  155. {
  156. $saiType = request()->input('saiType', 'list');
  157. $page = request()->input('page', 1);
  158. $limit = request()->input('limit', 10);
  159. $orderBy = request()->input('orderBy', '');
  160. $orderType = request()->input('orderType', $this->orderType);
  161. if (empty($orderBy)) {
  162. $orderBy = $this->orderField !== '' ? $this->orderField : $this->model->getPk();
  163. }
  164. $query->order($orderBy, $orderType);
  165. if ($saiType === 'all') {
  166. return $query->select()->toArray();
  167. }
  168. return $query->paginate($limit, false, ['page' => $page])->toArray();
  169. }
  170. /**
  171. * 获取全部数据
  172. * @param $query
  173. * @return mixed
  174. */
  175. public function getAll($query): mixed
  176. {
  177. $orderBy = request()->input('orderBy', '');
  178. $orderType = request()->input('orderType', $this->orderType);
  179. if (empty($orderBy)) {
  180. $orderBy = $this->orderField !== '' ? $this->orderField : $this->model->getPk();
  181. }
  182. $query->order($orderBy, $orderType);
  183. return $query->select()->toArray();
  184. }
  185. /**
  186. * 转换列表列
  187. * @param $data
  188. * @param $fields
  189. * @return mixed
  190. */
  191. public function trandformListColumn($data, $fields = ['site', 'agent', 'game', 'auth', 'author', 'media', 'pay_channel', 'game_pay_channel', 'ip','pay_channel_id'])
  192. {
  193. if (in_array('site', $fields)) {
  194. $agentSiteList = Db::connect('db_advert')->table('agent_site')->field('id,name')->select()->toArray();
  195. $agentSiteList = array_column($agentSiteList, 'name', 'id');
  196. }
  197. if (in_array('agent', $fields)) {
  198. $agentList = Db::connect('db_advert')->table('agent_list')->field('id,name')->select()->toArray();
  199. $agentList = array_column($agentList, 'name', 'id');
  200. }
  201. if (in_array('game', $fields)) {
  202. $gameList = Db::connect('db_center')->table('pf_game')->field('id,name,os,ios_appid')->select()->toArray();
  203. $gameList = array_column($gameList, null, 'id');
  204. }
  205. if (in_array('auth', $fields)) {
  206. $authList = Db::connect('db_system')->table('sa_system_user')->field('id,username')->select()->toArray();
  207. $authList = array_column($authList, 'username', 'id');
  208. }
  209. if (in_array('author', $fields)) {
  210. $authorList = Db::connect('db_system')->table('sa_system_user')->field('id,username')->select()->toArray();
  211. $authorList = array_column($authorList, 'username', 'id');
  212. }
  213. if (in_array('media', $fields)) {
  214. $mediaList = Db::connect('db_advert')->table('media_list')->field('id,name')->select()->toArray();
  215. $mediaList = array_column($mediaList, 'name', 'id');
  216. }
  217. if (in_array('pay_channel', $fields)) {
  218. $payChannelList = Db::connect('db_center')->table('pay_channel')->field('id,name')->where('status', 1)->select()->toArray();
  219. $payChannelList = array_column($payChannelList, 'name', 'id');
  220. }
  221. if (in_array('game_pay_channel', $fields)) {
  222. $gamePayChannelList = Db::connect('db_center')->table('pay_channel')->field(field: 'id,name')->where('status', 1)->select()->toArray();
  223. $gamePayChannelList = array_column($gamePayChannelList, 'name', 'id');
  224. }
  225. foreach ($data as &$value) {
  226. if (!empty($agentSiteList)) {
  227. $value['site_name'] = $agentSiteList[$value['site_id']] ?? '';
  228. }
  229. if (!empty($agentList)) {
  230. $value['agent_name'] = $agentList[$value['agent_id']] ?? '';
  231. }
  232. if (!empty($gameList)) {
  233. $value['game_name'] = $gameList[$value['game_id']]['name'] ?? '';
  234. $value['game_os'] = $gameList[$value['game_id']]['os'] ?? '';
  235. $value['ios_appid'] = $gameList[$value['game_id']]['ios_appid'] ?? '';
  236. }
  237. if (!empty($authList)) {
  238. $value['auth_name'] = $authList[$value['auth_id']] ?? '';
  239. }
  240. if (!empty($authorList)) {
  241. $value['author_name'] = $authorList[$value['author_id']] ?? '';
  242. }
  243. if (!empty($mediaList)) {
  244. $value['media_name'] = $mediaList[$value['media_id']] ?? '';
  245. }
  246. if (!empty($payChannelList)) {
  247. $value['pay_channel_name'] = $payChannelList[$value['pay_channel_id']] ?? '';
  248. }
  249. if (!empty($gamePayChannelList)) {
  250. $value['alipay_wap_name'] = $gamePayChannelList[$value['alipay_wap']] ?? '-';
  251. $value['inapp_name'] = $gamePayChannelList[$value['inapp']] ?? '-';
  252. $value['wechat_wap_name'] = $gamePayChannelList[$value['wechat_wap']] ?? '-';
  253. $value['wechat_scan_name'] = $gamePayChannelList[$value['wechat_scan']] ?? '-';
  254. $value['wechat_jsapi_name'] = $gamePayChannelList[$value['wechat_jsapi']] ?? '-';
  255. }
  256. // if (in_array('pay_channel_id', $fields)) {
  257. // $value['pay_channel_name'] = $gamePayChannelList[$value['pay_channel_id']] ?? '';
  258. // }
  259. if (in_array('ip', $fields)) {
  260. $value['ip'] = $value['ip'] ? $value['ip'] ."(". getIpLocation($value['ip']) .")" : '';
  261. }
  262. }
  263. unset($value);
  264. return $data;
  265. }
  266. /**
  267. * 获取上传的导入文件
  268. * @param $file
  269. * @return string
  270. */
  271. public function getImport($file): string
  272. {
  273. $full_dir = runtime_path() . '/resource/';
  274. if (!is_dir($full_dir)) {
  275. mkdir($full_dir, 0777, true);
  276. }
  277. $ext = $file->getUploadExtension() ?: null;
  278. $full_path = $full_dir . md5(time()) . '.' . $ext;
  279. $file->move($full_path);
  280. return $full_path;
  281. }
  282. /**
  283. * 方法调用
  284. * @param $name
  285. * @param $arguments
  286. * @return mixed
  287. */
  288. public function __call($name, $arguments)
  289. {
  290. // TODO: Implement __call() method.
  291. return call_user_func_array([$this->model, $name], $arguments);
  292. }
  293. /**
  294. * 根据权限搜索器
  295. * @param array $searchWhere
  296. * @param array $withSearch 搜索器
  297. * @return mixed
  298. */
  299. public function searchByAuth(array $searchWhere = []): mixed
  300. {
  301. $withSearch = array_keys($searchWhere);
  302. $data = $searchWhere;
  303. foreach ($withSearch as $k => $v) {
  304. if ($data[$v] === '') {
  305. unset($data[$v]);
  306. unset($withSearch[$k]);
  307. }
  308. }
  309. $userAuthCache = new UserInfoCache(getCurrentInfo()['id']);
  310. $userInfo = $userAuthCache->getUserInfo();
  311. // Todo 1、游戏权限
  312. $authGameList = $userInfo['deptList']['game_list'];
  313. if ($authGameList != '*') {
  314. $authGameIds = explode(',', $authGameList);
  315. if (!empty($data['game_id'])) {
  316. $inputGameIds = is_array($data['game_id']) ? $data['game_id'] : explode(',', $data['game_id']);
  317. $data['game_id'] = array_values(array_intersect($inputGameIds, $authGameIds)); // 如果传入了game_id,则取权限交集
  318. } else {
  319. // 如果没传入game_id,则取权限
  320. $data['game_id'] = $authGameIds;
  321. }
  322. }
  323. // Todo 2、 如果自定义了数据权限
  324. if($userInfo['data_permission']){
  325. // Todo 2.1、广告数据权限
  326. $userId = $userInfo['id'];
  327. $deptId = $userInfo['deptList']['id'];
  328. // 广告权限,自己 or 全部
  329. $authAdPermission = $userInfo['ad_permission'];
  330. // Todo 2.1.1、仅自己
  331. if ($authAdPermission == 1) {
  332. $data['auth_id'] = [$userId];
  333. } else{
  334. // Todo 2.1.2、自己部门
  335. $underUserIds = Db::connect('db_system')->table('sa_system_user')->where('dept_id', 'in', $deptId)->column('id');
  336. if (!empty($data['auth_id'])) { // 如果传入了负责人ID,则取交集
  337. $data['auth_id'] = array_values(array_intersect($data['auth_id'], array_values($underUserIds)));
  338. } else { // 如果没有传入负责人ID, 则取当前用户以及下面组员
  339. $data['auth_id'] = array_values($underUserIds);
  340. }
  341. }
  342. // Todo 2.2、看指定游戏的自然量
  343. $authNormalGameList = $userInfo['normal_game_list']; // 可看自然量的游戏
  344. if($data['game_id'] && $authNormalGameList){
  345. if($authNormalGameList=="*"){
  346. $data['normal_game_id'] = $data['game_id'];
  347. }else{
  348. $data['normal_game_id'] = array_values(array_intersect(explode(',', $authNormalGameList), $data['game_id']));
  349. }
  350. }
  351. }
  352. return $data;
  353. }
  354. // Todo 公共 whereRaw 子句
  355. protected function getCommonWhereRaw($params): string
  356. {
  357. $eqParams = ["user_name", "media_id", "site_id", "agent_id", "vt", "server_id", "server_name"];
  358. $inParams = ["game_id", "auth_id"];
  359. $betweenParams = ["tdate", "reg_date", "pay_date"];
  360. $timeParams = ["reg_time", "pay_time", "login_time"];
  361. $DateTimeParams = ["create_time"];
  362. // Todo And条件
  363. $whereRaw = " 1=1 ";
  364. foreach ($params as $key => $value) {
  365. if (in_array($key, $eqParams)) {
  366. $whereRaw .= " AND `{$key}`='{$value}'";
  367. } elseif (in_array($key, $inParams) && !empty($value)) {
  368. $value = is_string($value) ? explode(',', $value) : $value;
  369. $whereRaw .= " AND `{$key}` IN ('" . implode("','", $value) . "')";
  370. } elseif (in_array($key, $betweenParams) && !empty($value)) {
  371. $whereRaw .= " AND `{$key}` BETWEEN '{$value[0]}' AND '{$value[1]}'";
  372. } elseif (in_array($key, $DateTimeParams) && !empty($value)) {
  373. $value[0] = $value[0] . ' 00:00:00';
  374. $value[1] = $value[1] . ' 23:59:59';
  375. $whereRaw .= " AND `{$key}` BETWEEN '{$value[0]}' AND '{$value[1]}'";
  376. } elseif (in_array($key, $timeParams) && !empty($value)) {
  377. $value[0] = strtotime($value[0] . ' 00:00:00');
  378. $value[1] = strtotime($value[1] . ' 23:59:59');
  379. $whereRaw .= " AND `{$key}` BETWEEN '{$value[0]}' AND '{$value[1]}'";
  380. }
  381. }
  382. // Todo 自然量走 Or 条件
  383. $whereOr = [];
  384. if (!empty($params['normal_game_id'])) {
  385. foreach ($params['normal_game_id'] as $gameId) {
  386. $whereOr[] = "(game_id = {$gameId} AND auth_id=0)";
  387. }
  388. }
  389. $whereOr = $whereOr ? implode(' OR ', $whereOr) : "";
  390. return $whereRaw . ($whereOr ? " OR {$whereOr}" : "");
  391. }
  392. // 合并表查询
  393. public function generateUnionList($namePrefix, $range, $whereRaw = '', $field = '*', $group = null): array
  394. {
  395. $finalSql = $this->generateUnionSql($namePrefix, $range, $whereRaw, $field, $group);
  396. // echo $finalSql . "\n";
  397. return Db::connect('db_data_report')->table($finalSql)->group($group)->select()->toArray();
  398. }
  399. public function generateUnionSql($namePrefix, $range, $whereRaw = '', $field = '*', $group = null): string
  400. {
  401. // $db = Db::connect('db_game_log');
  402. // $unionQuery = [];
  403. // foreach ($monthRange as $month){
  404. // $tableName = 'sdk_login_log_' . $month;
  405. // $unionQuery[] = $db->table($tableName)->whereRaw(where: $whereRaw)->buildSql();
  406. // }
  407. // $fullSql = "(" . implode(' UNION ALL ', $unionQuery) . ") as unTable";
  408. $sqlParts = [];
  409. $unionSql = "(";
  410. foreach ($range as $ext) {
  411. if($namePrefix){
  412. $tableName = $namePrefix . '_' . $ext;
  413. }else{
  414. $tableName = $ext;
  415. }
  416. $sql = "(";
  417. $sql .= "SELECT {$field} FROM {$tableName} WHERE {$whereRaw}";
  418. if($group) $sql .= " GROUP BY {$group}";
  419. $sql .= ")";
  420. $sqlParts[] = $sql;
  421. }
  422. $unionSql .= implode(" UNION ALL ", $sqlParts);
  423. $unionSql .= ") AS union_table";
  424. return $unionSql;
  425. }
  426. }