Service.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\OperationLog;
  4. use App\Model\Depart;
  5. use App\Model\Employee;
  6. use Illuminate\Support\Facades\Redis;
  7. use Illuminate\Support\Facades\Storage;
  8. /**
  9. * 公用的公共服务
  10. * @package App\Models
  11. */
  12. class Service
  13. {
  14. public $log;
  15. public $total = 0;
  16. public function __construct()
  17. {
  18. }
  19. //分页共用
  20. public function limit($db, $columns, $request)
  21. {
  22. $per_page = $request['page_size'] ?? 9999;
  23. $page = $request['page_index'] ?? 1;
  24. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  25. $data['total'] = $return['total'];
  26. $data['data'] = $return['data'];
  27. return $data;
  28. }
  29. //分页共用2
  30. public function limitData($db, $columns, $request)
  31. {
  32. $per_page = $request['page_size'] ?? 1000;
  33. $page = $request['page_index'] ?? 1;
  34. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  35. return $return['data'];
  36. }
  37. //抽象一个查询条件,省的每天写很多行
  38. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  39. {
  40. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  41. switch ($type) {
  42. case 'time':
  43. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  44. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  45. $db = $db->where($words, $formula, $data[$word]);
  46. break;
  47. case 'like':
  48. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  49. break;
  50. case 'in':
  51. if (is_array($data[$word])) {
  52. $db = $db->wherein($words, $data[$word]);
  53. } else {
  54. $db = $db->wherein($words, explode(',', $data[$word]));
  55. }
  56. break;
  57. default:
  58. $db = $db->where($words, $formula, $data[$word]);
  59. break;
  60. }
  61. return $db;
  62. }
  63. return $db;
  64. }
  65. //判断是否为空
  66. protected function isEmpty($data, $word)
  67. {
  68. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  69. return true;
  70. }
  71. //递归处理数据成子父级关系
  72. public function makeTree($parentId, &$node)
  73. {
  74. $tree = [];
  75. foreach ($node as $key => $value) {
  76. if ($value['parent_id'] == $parentId) {
  77. $tree[$value['id']] = $value;
  78. unset($node[$key]);
  79. if (isset($tree[$value['id']]['children'])) {
  80. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  81. } else {
  82. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  83. }
  84. }
  85. }
  86. return $tree;
  87. }
  88. //进行递归处理数组的排序问题
  89. public function set_sort_circle($data){
  90. foreach ($data as $k=>$v){
  91. // var_dump($v);die;
  92. if(isset($v['children'])&&!empty($v['children'])){
  93. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  94. }
  95. }
  96. $data = array_merge($data);
  97. return $data;
  98. }
  99. //根据编码规则获取每一级的code
  100. public function get_rule_code($code, $rule)
  101. {
  102. $rules = [];
  103. $num = 0;
  104. foreach ($rule as $v) {
  105. $num += $v['num'];
  106. $code = substr($code, 0, $num);
  107. if (strlen($code) != $num) continue;
  108. $rules[] = $code;
  109. }
  110. return $rules;
  111. }
  112. function curlOpen($url, $config = array())
  113. {
  114. $arr = array('post' => false,'referer' => $url,'cookie' => '', 'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)', 'timeout' => 100, 'return' => true, 'proxy' => '', 'userpwd' => '', 'nobody' => false,'header'=>array(),'gzip'=>true,'ssl'=>true,'isupfile'=>false,'returnheader'=>false,'request'=>'post');
  115. $arr = array_merge($arr, $config);
  116. $ch = curl_init();
  117. curl_setopt($ch, CURLOPT_URL, $url);
  118. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  119. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  120. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  121. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  122. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  123. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  124. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  125. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  126. if($arr['ssl'])
  127. {
  128. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  129. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  130. }
  131. if(!empty($arr['cookie']))
  132. {
  133. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  134. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  135. }
  136. if(!empty($arr['proxy']))
  137. {
  138. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  139. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  140. if(!empty($arr['userpwd']))
  141. {
  142. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  143. }
  144. }
  145. //ip�Ƚ����⣬�ü�ֵ��ʾ
  146. if(!empty($arr['header']['ip']))
  147. {
  148. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  149. unset($arr['header']['ip']);
  150. }
  151. $arr['header'] = array_filter($arr['header']);
  152. if(!empty($arr['header']))
  153. {
  154. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  155. }
  156. if($arr['request'] === 'put'){
  157. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  158. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  159. }elseif($arr['post'] != false)
  160. {
  161. curl_setopt($ch, CURLOPT_POST, true);
  162. if(is_array($arr['post']) && $arr['isupfile'] === false)
  163. {
  164. $post = http_build_query($arr['post']);
  165. }
  166. else
  167. {
  168. $post = $arr['post'];
  169. }
  170. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  171. }
  172. $result = curl_exec($ch);
  173. curl_close($ch);
  174. return $result;
  175. }
  176. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  177. foreach ($data as $node) {
  178. if ($node['parent_id'] == $pid) {
  179. $id = $prefix . $node['id'];
  180. $result[] = $id;
  181. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  182. }
  183. }
  184. return $result;
  185. }
  186. function getLongestStr($arr = [], $searchStr){
  187. if(empty($arr) || ! $searchStr) return '';
  188. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  189. $longest = '';
  190. foreach ($arr as $str) {
  191. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  192. $longest = $str;
  193. }
  194. }
  195. return $longest;
  196. }
  197. function getAllDescendants($data, $id) {
  198. $result = array(); // 存储结果的数组
  199. foreach ($data as $node) {
  200. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  201. $result[] = $node['id'];
  202. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  203. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  204. }
  205. }
  206. return $result;
  207. }
  208. //后台端 某些需要限制请求频率的接口
  209. //需要主动删除 Redis::del($key)
  210. public function limitingSendRequestBackg($key,$value=0){
  211. $prefix = config('app.name') . ':';
  212. $key = $prefix . $key;
  213. if(! empty($value)) $value = 1;
  214. // 使用Redis Facade设置,当键名不存在时才设置成功
  215. if (Redis::setnx($key, $value)) return [true, ''];
  216. return [false,'操作频繁!'];
  217. }
  218. public function dellimitingSendRequestBackg($key){
  219. $prefix = config('app.name') . ':';
  220. $key = $prefix . $key;
  221. Redis::del($key);
  222. }
  223. //后台端 某些需要限制请求频率的接口 有过期时间
  224. public function limitingSendRequestBackgExpire($key,$ttl = 5){
  225. $prefix = config('app.name') . ':';
  226. $key = $prefix . $key;
  227. if($ttl < 5) $ttl = 5;
  228. // 使用Redis Facade设置,当键名不存在时才设置成功
  229. if (Redis::setnx($key, 1)) {
  230. Redis::expire($key, $ttl); //多少秒后过期
  231. return [true, ''];
  232. }
  233. return [false,'操作频繁, 请在 ' . $ttl . '秒后重试'];
  234. }
  235. //前端传来的时间段 转换为时间戳
  236. //精确到秒
  237. function changeDateToTimeStampAboutRange($time_range){
  238. if(empty($time_range[0]) || empty($time_range[1])) return [];
  239. // 创建一个 DateTime 对象并设置时区为 UTC
  240. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  241. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  242. // 将时区设置为 PRC
  243. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  244. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  245. // 将日期时间格式化为特定格式
  246. $formattedDate = $dateTime->format('Y-m-d');
  247. $formattedDate1 = $dateTime1->format('Y-m-d');
  248. $return = [];
  249. $return[] = strtotime($formattedDate . " 00:00:00");
  250. $return[] = strtotime($formattedDate1 . " 23:59:59");
  251. return $return;
  252. }
  253. //前端传来的时间段 转换为时间戳
  254. //精确到日
  255. function changeDateToNewDate($time_range){
  256. if(empty($time_range[0]) || empty($time_range[1])) return [];
  257. // 创建一个 DateTime 对象并设置时区为 UTC
  258. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  259. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  260. // 将时区设置为 PRC
  261. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  262. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  263. // 将日期时间格式化为特定格式
  264. $formattedDate = $dateTime->format('Y-m-d');
  265. $formattedDate1 = $dateTime1->format('Y-m-d');
  266. $return = [];
  267. $return[] = strtotime($formattedDate);
  268. $return[] = strtotime($formattedDate1);
  269. return $return;
  270. }
  271. function changeDateToNewDate2($time){
  272. if(empty($time_range)) return [];
  273. // 创建一个 DateTime 对象并设置时区为 UTC
  274. $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC'));
  275. // 将时区设置为 PRC
  276. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  277. // 将日期时间格式化为特定格式
  278. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  279. $formattedDate1 = $dateTime->format('Y-m-d 23:59:59');
  280. $return = [];
  281. $return[] = strtotime($formattedDate);
  282. $return[] = strtotime($formattedDate1);
  283. return $return;
  284. }
  285. //前端传来的时间 转为时间戳
  286. //精确到分
  287. function changeDateToDateMin($time){
  288. if(empty($time)) return '';
  289. // 创建一个 DateTime 对象并设置时区为 UTC
  290. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  291. // 将时区设置为 PRC
  292. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  293. // 将日期时间格式化为特定格式
  294. $formattedDate = $dateTime->format('Y-m-d H:i');
  295. return strtotime($formattedDate);
  296. }
  297. //前端传来的时间 转为时间戳
  298. //精确到日
  299. function changeDateToDate($time){
  300. if(empty($time)) return '';
  301. // 创建一个 DateTime 对象并设置时区为 UTC
  302. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  303. // 将时区设置为 PRC
  304. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  305. // 将日期时间格式化为特定格式
  306. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  307. return strtotime($formattedDate);
  308. }
  309. /**
  310. * 用于用户行为操作日志记录
  311. * @param $insert
  312. * @return void
  313. */
  314. public function insertLog($insert){
  315. OperationLog::dispatch($insert);
  316. }
  317. public function checkNumber($number, $decimals = 2){
  318. if(! is_numeric($number) || $number < 0) return false;
  319. $formattedNumber = number_format($number, $decimals, '.', '');
  320. if($formattedNumber != $number) return false;
  321. return true;
  322. }
  323. public function getDepart($user){
  324. if(empty($user)) return 0;
  325. return $user['depart_select']['depart_id'];
  326. }
  327. public function getMyTopDepart($user){
  328. if(empty($user)) return 0;
  329. //当前门店
  330. $current_top_depart_id = $user['depart_top'][0] ?? [];
  331. $current_top_depart_id = $current_top_depart_id['depart_id'] ?? 0;
  332. return $current_top_depart_id;
  333. }
  334. public function returnOrderEditErrorCommon($current_top_depart_id, $order_top_depart_id){
  335. if($current_top_depart_id != $order_top_depart_id){
  336. $depart_map = Depart::whereIn('id', [$current_top_depart_id, $order_top_depart_id])
  337. ->pluck('title', 'id')
  338. ->toArray();
  339. $current_top_depart_title = $depart_map[$current_top_depart_id] ?? "";
  340. $order_top_depart_title = $depart_map[$order_top_depart_id] ?? "";
  341. return [false, "单据所属门店:" . $order_top_depart_title . ",当前所在门店:" . $current_top_depart_title . ",操作失败"];
  342. }
  343. return [true, ''];
  344. }
  345. public function getTopId($id, $data) {
  346. foreach ($data as $item) {
  347. if ($item['id'] == $id) {
  348. if ($item['parent_id'] == 0) {
  349. // 找到最顶级的id
  350. return $item['id'];
  351. } else {
  352. // 继续递归查找父级
  353. return $this->getTopId($item['parent_id'], $data);
  354. }
  355. }
  356. }
  357. // 如果没有找到匹配的id,则返回null或者其他你希望的默认值
  358. return 0;
  359. }
  360. // 递归查找所有父级id
  361. public function findParentIds($id, $data) {
  362. $parentIds = [];
  363. foreach ($data as $item) {
  364. if ($item['id'] == $id) {
  365. $parentId = $item['parent_id'];
  366. if ($parentId) {
  367. $parentIds[] = $parentId;
  368. $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data));
  369. }
  370. break;
  371. }
  372. }
  373. return $parentIds;
  374. }
  375. // 递归查找所有子级id
  376. public function findChildIds($id, $data) {
  377. $childIds = [];
  378. foreach ($data as $item) {
  379. if ($item['parent_id'] == $id) {
  380. $childId = $item['id'];
  381. $childIds[] = $childId;
  382. $childIds = array_merge($childIds, $this->findChildIds($childId, $data));
  383. }
  384. }
  385. return $childIds;
  386. }
  387. public function getDataFile($data){
  388. foreach ($data as $key => $value){
  389. if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]);
  390. }
  391. return $data;
  392. }
  393. // 校验域名是否通畅可达
  394. // $domain baidu.com 不要带http这些协议头
  395. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  396. function isDomainAvailable($domain) {
  397. $ip = gethostbyname($domain);
  398. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  399. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  400. return true;
  401. }
  402. public function delStorageFile($old, $new = [], $dir = "upload_files/"){
  403. foreach ($old as $value){
  404. if(! in_array($value, $new)){
  405. $filename_rep = "/api/uploadFiles/";
  406. $filename = str_replace($filename_rep, "", $value);
  407. $filePath = $dir . $filename;
  408. if (Storage::disk('public')->exists($filePath)) {
  409. // 文件存在 进行删除操作
  410. Storage::disk('public')->delete($filePath);
  411. }
  412. }
  413. }
  414. }
  415. public function showTimeAgo($time, $time_big){
  416. // 计算时间差(秒)
  417. $diffInSeconds = $time_big - $time;
  418. // 将时间差转换为更易处理的单位
  419. $diffInMinutes = floor($diffInSeconds / 60);
  420. $diffInHours = floor($diffInSeconds / 3600);
  421. $diffInDays = floor($diffInSeconds / (3600 * 24));
  422. // 根据时间差生成描述性文本
  423. if ($diffInSeconds < 60) {
  424. $timeAgo = '刚刚';
  425. } elseif ($diffInMinutes < 60) {
  426. $timeAgo = $diffInMinutes . '分钟前';
  427. } elseif ($diffInHours < 24) {
  428. $timeAgo = $diffInHours . '小时前';
  429. } elseif ($diffInDays < 2) {
  430. $timeAgo = '昨天';
  431. } elseif ($diffInDays < 7) {
  432. $timeAgo = $diffInDays . '天前';
  433. } elseif ($diffInDays < 15) {
  434. $timeAgo = '一周前';
  435. } elseif ($diffInDays < 30) {
  436. $timeAgo = '半个月内';
  437. } else {
  438. // 如果超过半个月,可以使用具体的日期格式
  439. $crtTimeDate = date('Y-m-d', $time);
  440. $timeAgo = '在 ' . $crtTimeDate;
  441. }
  442. return $timeAgo;
  443. }
  444. // 递归函数,用于在数据结构中查找值
  445. function findLabelsByValue($data, $valuesToFind, &$foundLabels) {
  446. foreach ($data as $item) {
  447. if (isset($item['value']) && in_array($item['value'], $valuesToFind)) {
  448. // 如果找到值,则添加其label到结果数组中
  449. $foundLabels[] = $item['label'];
  450. // 移除已找到的值,避免重复查找
  451. $key = array_search($item['value'], $valuesToFind);
  452. if ($key !== false) {
  453. unset($valuesToFind[$key]);
  454. }
  455. }
  456. if (isset($item['children']) && !empty($item['children'])) {
  457. // 递归调用自身来查找子节点
  458. $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels);
  459. }
  460. // 如果所有值都已找到,则停止递归
  461. if (empty($valuesToFind)) {
  462. break;
  463. }
  464. }
  465. }
  466. public function changeAndReturnDate($date_int){
  467. $int = intval($date_int);
  468. $bool = (string)$int === $date_int;
  469. if(! $bool || $date_int < 0) return [false, '日期不正确'];
  470. $epoch = strtotime("1900-01-01 00:00:00");
  471. $days = $date_int - 1;
  472. $seconds = $days * 86400;
  473. return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))];
  474. }
  475. function findTopLevelId($data, $id) {
  476. // 遍历数据,查找给定ID的节点
  477. foreach ($data as $item) {
  478. if ($item['id'] == $id) {
  479. // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点
  480. if ($item['parent_id'] === 0) {
  481. return $item['id'];
  482. } else {
  483. // 否则,继续寻找其父节点的最顶层节点
  484. return $this->findTopLevelId($data, $item['parent_id']);
  485. }
  486. }
  487. }
  488. // 如果没有找到给定ID的节点,返回null或抛出异常
  489. return 0;
  490. }
  491. function returnDays($time = [], $is_mirco_time = false){
  492. // 示例时间戳
  493. $timestamp1 = $time[0];
  494. $timestamp2 = $time[1];
  495. // 计算时间差
  496. $difference = abs($timestamp2 - $timestamp1);
  497. // 将时间差转换为天数
  498. $days = floor($difference / (60 * 60 * 24));
  499. if($is_mirco_time) $days = $days / 1000;
  500. return $days;
  501. }
  502. }