Service.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Redis;
  5. /**
  6. * 公用的公共服务
  7. * @package App\Models
  8. */
  9. class Service
  10. {
  11. public $log;
  12. public $total = 0;
  13. public function __construct()
  14. {
  15. }
  16. //分页共用
  17. public function limit($db, $columns, $request)
  18. {
  19. $per_page = $request['page_size'] ?? 40;
  20. $page = $request['page_index'] ?? 1;
  21. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  22. $data['total'] = $return['total'];
  23. $data['data'] = $return['data'];
  24. return $data;
  25. }
  26. //抽象一个查询条件,省的每天写很多行
  27. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  28. {
  29. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  30. switch ($type) {
  31. case 'time':
  32. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  33. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  34. $db = $db->where($words, $formula, $data[$word]);
  35. break;
  36. case 'like':
  37. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  38. break;
  39. case 'in':
  40. if (is_array($data[$word])) {
  41. $db = $db->whereIn($words, $data[$word]);
  42. } else {
  43. $db = $db->whereIn($words, explode(',', $data[$word]));
  44. }
  45. break;
  46. default:
  47. $db = $db->where($words, $formula, $data[$word]);
  48. break;
  49. }
  50. return $db;
  51. }
  52. return $db;
  53. }
  54. //判断是否为空
  55. protected function isEmpty($data, $word)
  56. {
  57. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  58. return true;
  59. }
  60. //递归处理数据成子父级关系
  61. public function makeTree($parentId, &$node)
  62. {
  63. $tree = [];
  64. foreach ($node as $key => $value) {
  65. if ($value['parent_id'] == $parentId) {
  66. $tree[$value['id']] = $value;
  67. unset($node[$key]);
  68. if (isset($tree[$value['id']]['children'])) {
  69. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  70. } else {
  71. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  72. }
  73. }
  74. }
  75. return $tree;
  76. }
  77. //进行递归处理数组的排序问题
  78. public function set_sort_circle($data){
  79. foreach ($data as $k=>$v){
  80. // var_dump($v);die;
  81. if(isset($v['children'])&&!empty($v['children'])){
  82. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  83. }
  84. }
  85. $data = array_merge($data);
  86. return $data;
  87. }
  88. //根据编码规则获取每一级的code
  89. public function get_rule_code($code, $rule)
  90. {
  91. $rules = [];
  92. $num = 0;
  93. foreach ($rule as $v) {
  94. $num += $v['num'];
  95. $code = substr($code, 0, $num);
  96. if (strlen($code) != $num) continue;
  97. $rules[] = $code;
  98. }
  99. return $rules;
  100. }
  101. function curlOpen($url, $config = array())
  102. {
  103. $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');
  104. $arr = array_merge($arr, $config);
  105. $ch = curl_init();
  106. curl_setopt($ch, CURLOPT_URL, $url);
  107. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  108. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  109. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  110. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  111. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  112. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  113. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  114. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  115. if($arr['ssl'])
  116. {
  117. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  118. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  119. }
  120. if(!empty($arr['cookie']))
  121. {
  122. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  123. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  124. }
  125. if(!empty($arr['proxy']))
  126. {
  127. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  128. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  129. if(!empty($arr['userpwd']))
  130. {
  131. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  132. }
  133. }
  134. //ip�Ƚ����⣬�ü�ֵ��ʾ
  135. if(!empty($arr['header']['ip']))
  136. {
  137. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  138. unset($arr['header']['ip']);
  139. }
  140. $arr['header'] = array_filter($arr['header']);
  141. if(!empty($arr['header']))
  142. {
  143. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  144. }
  145. if($arr['request'] === 'put'){
  146. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  147. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  148. }elseif($arr['post'] != false)
  149. {
  150. curl_setopt($ch, CURLOPT_POST, true);
  151. if(is_array($arr['post']) && $arr['isupfile'] === false)
  152. {
  153. $post = http_build_query($arr['post']);
  154. }
  155. else
  156. {
  157. $post = $arr['post'];
  158. }
  159. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  160. }
  161. $result = curl_exec($ch);
  162. curl_close($ch);
  163. return $result;
  164. }
  165. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  166. foreach ($data as $node) {
  167. if ($node['parent_id'] == $pid) {
  168. $id = $prefix . $node['id'];
  169. $result[] = $id;
  170. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  171. }
  172. }
  173. return $result;
  174. }
  175. function getLongestStr($arr = [], $searchStr){
  176. if(empty($arr) || ! $searchStr) return '';
  177. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  178. $longest = '';
  179. foreach ($arr as $str) {
  180. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  181. $longest = $str;
  182. }
  183. }
  184. return $longest;
  185. }
  186. function getAllDescendants($data, $id) {
  187. $result = array(); // 存储结果的数组
  188. foreach ($data as $node) {
  189. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  190. $result[] = $node['id'];
  191. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  192. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  193. }
  194. }
  195. return $result;
  196. }
  197. function changeDateToDateMin($time){
  198. if(empty($time)) return '';
  199. // 创建一个 DateTime 对象并设置时区为 UTC
  200. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  201. // 将时区设置为 PRC
  202. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  203. // 将日期时间格式化为特定格式
  204. $formattedDate = $dateTime->format('Y-m-d H:i:s');
  205. return $formattedDate;
  206. }
  207. //后台端 某些需要限制请求频率的接口
  208. //需要主动删除 Redis::del($key)
  209. public function limitingSendRequestBackgNeed($key,$value=0){
  210. $prefix = config('app.name') . ':';
  211. $key = $prefix . $key;
  212. if(! empty($value)) $value = 1;
  213. // 使用Redis Facade设置,当键名不存在时才设置成功
  214. if (Redis::setnx($key, $value)) return [true, ''];
  215. return [false,'操作频繁!'];
  216. }
  217. public function dellimitingSendRequestBackgNeed($key){
  218. $prefix = config('app.name') . ':';
  219. $key = $prefix . $key;
  220. Redis::del($key);
  221. }
  222. // 校验域名是否通畅可达
  223. // $domain baidu.com 不要带http这些协议头
  224. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  225. function isDomainAvailable($domain) {
  226. $ip = gethostbyname($domain);
  227. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  228. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  229. return true;
  230. }
  231. function changeDateToDate($time, $is_end = false){
  232. if(empty($time)) return '';
  233. // 创建一个 DateTime 对象并设置时区为 UTC
  234. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  235. // 将时区设置为 PRC
  236. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  237. $str = "00:00:00";
  238. if($is_end) $str = "23:59:59";
  239. // 将日期时间格式化为特定格式
  240. $formattedDate = $dateTime->format('Y-m-d ' . $str);
  241. return strtotime($formattedDate);
  242. }
  243. //前端传来的时间段 转换为时间戳
  244. //精确到秒
  245. function changeDateToTimeStampAboutRange($time_range, $is_end = true){
  246. if(empty($time_range[0]) || empty($time_range[1])) return [];
  247. // 创建一个 DateTime 对象并设置时区为 UTC
  248. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  249. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  250. // 将时区设置为 PRC
  251. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  252. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  253. // 将日期时间格式化为特定格式
  254. $formattedDate = $dateTime->format('Y-m-d');
  255. $formattedDate1 = $dateTime1->format('Y-m-d');
  256. $str = " 23:59:59";
  257. if(! $is_end) $str = " 00:00:00";
  258. $return = [];
  259. $return[] = strtotime($formattedDate . " 00:00:00");
  260. $return[] = strtotime($formattedDate1 . $str);
  261. return $return;
  262. }
  263. /**
  264. * 检查数字是否合法,并可验证其正负性和小数位数
  265. *
  266. * @param mixed $number 要检查的值
  267. * @param int $decimals 允许的最大小数位数(默认 2)
  268. * @param string|null $sign 要求的符号:'positive' 大于 0 , 'negative' 小于0, 'zero' 等于0, 'non-negative' 大于或等于 0, 'non-positive' 小于或等于 0 null 表示不限制
  269. * @param bool $strict 是否严格模式(不允许整数传字符串等)
  270. * @return array ['valid' => bool, 'error' => string|null, 'info' => array]
  271. */
  272. public function checkNumber($number, $decimals = 2, $sign = null, $strict = false)
  273. {
  274. $result = [
  275. 'valid' => false,
  276. 'error' => null,
  277. 'info' => []
  278. ];
  279. // 1. 类型检查
  280. if ($strict) {
  281. if (!is_numeric($number) || is_bool($number)) {
  282. $result['error'] = '必须是数字类型';
  283. return $result;
  284. }
  285. } else {
  286. // 宽松模式:允许字符串数字
  287. if (!is_numeric($number)) {
  288. $result['error'] = '不是有效数字';
  289. return $result;
  290. }
  291. }
  292. $num = (float)$number; // 统一转为浮点数处理
  293. // 2. 正负号检查
  294. if ($sign !== null) {
  295. switch ($sign) {
  296. case 'positive':
  297. if ($num <= 0) {
  298. $result['error'] = '数字必须大于 0';
  299. return $result;
  300. }
  301. break;
  302. case 'negative':
  303. if ($num >= 0) {
  304. $result['error'] = '数字必须小于 0';
  305. return $result;
  306. }
  307. break;
  308. case 'zero':
  309. if ($num != 0) {
  310. $result['error'] = '数字必须等于 0';
  311. return $result;
  312. }
  313. break;
  314. case 'non-negative': // 大于等于 0
  315. if ($num < 0) {
  316. $result['error'] = '数字必须大于或等于 0';
  317. return $result;
  318. }
  319. break;
  320. case 'non-positive': // 小于等于 0
  321. if ($num > 0) {
  322. $result['error'] = '数字必须小于或等于 0';
  323. return $result;
  324. }
  325. break;
  326. default:
  327. $result['error'] = "不支持的符号类型: '{$sign}'";
  328. return $result;
  329. }
  330. }
  331. // 3. 小数位数检查
  332. // 将数字转为标准格式,避免科学计数法
  333. $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0
  334. if ($numStr === '' || $numStr === '-') {
  335. $numStr = '0';
  336. }
  337. // 检查是否有小数点
  338. if (strpos($numStr, '.') === false) {
  339. $decimalPlaces = 0;
  340. } else {
  341. $parts = explode('.', $numStr);
  342. $decimalPlaces = strlen($parts[1]);
  343. }
  344. if ($decimalPlaces > $decimals) {
  345. $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)";
  346. return $result;
  347. }
  348. // 4. 附加信息
  349. $result['valid'] = true;
  350. $result['info'] = [
  351. 'original' => $number,
  352. 'value' => $num,
  353. 'decimal_places' => $decimalPlaces,
  354. 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'),
  355. ];
  356. return $result;
  357. }
  358. function isValidPhone($phone) {
  359. return preg_match('/^1(3\d|4[5-9]|5[0-35-9]|6[5-7]|7[0-8]|8\d|9[0-35-9])\d{8}$/', $phone);
  360. }
  361. public function checkArrayRepeat($data, $column, $title = ""){
  362. $ids = array_column($data, $column);
  363. // 检查空值
  364. if (in_array('', $ids, true) || in_array(null, $ids, true)) {
  365. return [false, $title . '不能为空'];
  366. }
  367. // 检查重复
  368. if (count($ids) !== count(array_unique($ids))) {
  369. return [false, $title . '不能重复'];
  370. }
  371. return [true, ''];
  372. }
  373. /**
  374. * 生成单据编号
  375. * @param int $top_depart_id 公司ID
  376. * @param string $type 单据类型标识 (如 'FEE')
  377. * @param string $prefix 编号前缀 (如 'FE')
  378. * @param int $length 流水号长度
  379. * @return string
  380. */
  381. public function generateBillNo($need = [], $length = 5)
  382. {
  383. $top_depart_id = $need['top_depart_id'];
  384. $type = $need['type'];
  385. $prefix = $need['prefix'] ?? '';
  386. $period = $need['period']; // 202603
  387. // 1. 原子更新:存在则自增,不存在则初始化
  388. // 这样处理不需要 select for update,性能最高且并发安全
  389. DB::statement("
  390. INSERT INTO sys_bill_sequences (top_depart_id, bill_type, period, current_value)
  391. VALUES (?, ?, ?, 1)
  392. ON DUPLICATE KEY UPDATE current_value = current_value + 1
  393. ", [$top_depart_id, $type, $period]);
  394. // 2. 获取本次生成的流水号
  395. $sequence = DB::table('sys_bill_sequences')
  396. ->where('top_depart_id', $top_depart_id)
  397. ->where('bill_type', $type)
  398. ->where('period', $period)
  399. ->value('current_value');
  400. // 3. 拼接输出:前缀 + 年月 + 补齐位数的流水号
  401. // 结果示例:FE26030001
  402. return $prefix . $period . str_pad($sequence, $length, '0', STR_PAD_LEFT);
  403. }
  404. function changeDateToMonth($time)
  405. {
  406. if (empty($time)) {
  407. return 0; // 或抛出异常,根据业务决定
  408. }
  409. // 解析输入时间,默认按 UTC 解析(兼容前端 ISO 字符串)
  410. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  411. // 转换为上海时区(PRC)
  412. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  413. // 设置为当月第一天,00:00:00
  414. $dateTime->modify('first day of this month');
  415. $dateTime->setTime(0, 0, 0);
  416. return $dateTime->getTimestamp(); // 推荐使用 getTimestamp() 而非 strtotime
  417. }
  418. }