Service.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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\DB;
  7. use Illuminate\Support\Facades\Redis;
  8. use Illuminate\Support\Facades\Storage;
  9. /**
  10. * 公用的公共服务
  11. * @package App\Models
  12. */
  13. class Service
  14. {
  15. public $log;
  16. public $total = 0;
  17. public function __construct()
  18. {
  19. }
  20. //分页共用
  21. public function limit($db, $columns, $request)
  22. {
  23. $per_page = $request['page_size'] ?? 100;
  24. $page = $request['page_index'] ?? 1;
  25. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  26. $data['total'] = $return['total'];
  27. $data['data'] = $return['data'];
  28. return $data;
  29. }
  30. //分页共用2
  31. public function limitData($db, $columns, $request)
  32. {
  33. $per_page = $request['page_size'] ?? 1000;
  34. $page = $request['page_index'] ?? 1;
  35. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  36. return $return['data'];
  37. }
  38. //抽象一个查询条件,省的每天写很多行
  39. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  40. {
  41. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  42. switch ($type) {
  43. case 'time':
  44. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  45. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  46. $db = $db->where($words, $formula, $data[$word]);
  47. break;
  48. case 'like':
  49. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  50. break;
  51. case 'in':
  52. if (is_array($data[$word])) {
  53. $db = $db->wherein($words, $data[$word]);
  54. } else {
  55. $db = $db->wherein($words, explode(',', $data[$word]));
  56. }
  57. break;
  58. default:
  59. $db = $db->where($words, $formula, $data[$word]);
  60. break;
  61. }
  62. return $db;
  63. }
  64. return $db;
  65. }
  66. //判断是否为空
  67. protected function isEmpty($data, $word)
  68. {
  69. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  70. return true;
  71. }
  72. //递归处理数据成子父级关系
  73. public function makeTree($parentId, &$node)
  74. {
  75. $tree = [];
  76. foreach ($node as $key => $value) {
  77. if ($value['parent_id'] == $parentId) {
  78. $tree[$value['id']] = $value;
  79. unset($node[$key]);
  80. if (isset($tree[$value['id']]['children'])) {
  81. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  82. } else {
  83. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  84. }
  85. }
  86. }
  87. return $tree;
  88. }
  89. //进行递归处理数组的排序问题
  90. public function set_sort_circle($data){
  91. foreach ($data as $k=>$v){
  92. // var_dump($v);die;
  93. if(isset($v['children'])&&!empty($v['children'])){
  94. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  95. }
  96. }
  97. $data = array_merge($data);
  98. return $data;
  99. }
  100. //根据编码规则获取每一级的code
  101. public function get_rule_code($code, $rule)
  102. {
  103. $rules = [];
  104. $num = 0;
  105. foreach ($rule as $v) {
  106. $num += $v['num'];
  107. $code = substr($code, 0, $num);
  108. if (strlen($code) != $num) continue;
  109. $rules[] = $code;
  110. }
  111. return $rules;
  112. }
  113. function curlOpen($url, $config = array())
  114. {
  115. $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');
  116. $arr = array_merge($arr, $config);
  117. $ch = curl_init();
  118. curl_setopt($ch, CURLOPT_URL, $url);
  119. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  120. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  121. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  122. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  123. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  124. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  125. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  126. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  127. if($arr['ssl'])
  128. {
  129. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  130. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  131. }
  132. if(!empty($arr['cookie']))
  133. {
  134. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  135. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  136. }
  137. if(!empty($arr['proxy']))
  138. {
  139. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  140. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  141. if(!empty($arr['userpwd']))
  142. {
  143. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  144. }
  145. }
  146. //ip�Ƚ����⣬�ü�ֵ��ʾ
  147. if(!empty($arr['header']['ip']))
  148. {
  149. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  150. unset($arr['header']['ip']);
  151. }
  152. $arr['header'] = array_filter($arr['header']);
  153. if(!empty($arr['header']))
  154. {
  155. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  156. }
  157. if($arr['request'] === 'put'){
  158. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  159. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  160. }elseif($arr['post'] != false)
  161. {
  162. curl_setopt($ch, CURLOPT_POST, true);
  163. if(is_array($arr['post']) && $arr['isupfile'] === false)
  164. {
  165. $post = http_build_query($arr['post']);
  166. }
  167. else
  168. {
  169. $post = $arr['post'];
  170. }
  171. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  172. }
  173. $result = curl_exec($ch);
  174. curl_close($ch);
  175. return $result;
  176. }
  177. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  178. foreach ($data as $node) {
  179. if ($node['parent_id'] == $pid) {
  180. $id = $prefix . $node['id'];
  181. $result[] = $id;
  182. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  183. }
  184. }
  185. return $result;
  186. }
  187. function getLongestStr($arr = [], $searchStr){
  188. if(empty($arr) || ! $searchStr) return '';
  189. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  190. $longest = '';
  191. foreach ($arr as $str) {
  192. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  193. $longest = $str;
  194. }
  195. }
  196. return $longest;
  197. }
  198. function getAllDescendants($data, $id) {
  199. $result = array(); // 存储结果的数组
  200. foreach ($data as $node) {
  201. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  202. $result[] = $node['id'];
  203. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  204. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  205. }
  206. }
  207. return $result;
  208. }
  209. //后台端 某些需要限制请求频率的接口
  210. //需要主动删除 Redis::del($key)
  211. public function limitingSendRequest($key,$value=0){
  212. $prefix = config('app.name') . ':';
  213. $key = $prefix . $key;
  214. if(! empty($value)) $value = 1;
  215. // 使用Redis Facade设置,当键名不存在时才设置成功
  216. if (Redis::setnx($key, $value)) return [true, ''];
  217. return [false,'操作频繁!'];
  218. }
  219. public function delLimitingSendRequest($key){
  220. $prefix = config('app.name') . ':';
  221. $key = $prefix . $key;
  222. Redis::del($key);
  223. }
  224. //后台端 某些需要限制请求频率的接口 有过期时间
  225. public function limitingSendRequestBackgExpire($key,$ttl = 5){
  226. $prefix = config('app.name') . ':';
  227. $key = $prefix . $key;
  228. if($ttl < 5) $ttl = 5;
  229. // 使用Redis Facade设置,当键名不存在时才设置成功
  230. if (Redis::setnx($key, 1)) {
  231. Redis::expire($key, $ttl); //多少秒后过期
  232. return [true, ''];
  233. }
  234. return [false,'操作频繁, 请在 ' . $ttl . '秒后重试'];
  235. }
  236. //前端传来的时间段 转换为时间戳
  237. //精确到秒
  238. function changeDateToTimeStampAboutRange($time_range, $is_end = true){
  239. if(empty($time_range[0]) || empty($time_range[1])) return [];
  240. // 创建一个 DateTime 对象并设置时区为 UTC
  241. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  242. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  243. // 将时区设置为 PRC
  244. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  245. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  246. // 将日期时间格式化为特定格式
  247. $formattedDate = $dateTime->format('Y-m-d');
  248. $formattedDate1 = $dateTime1->format('Y-m-d');
  249. $str = " 23:59:59";
  250. if(! $is_end) $str = " 00:00:00";
  251. $return = [];
  252. $return[] = strtotime($formattedDate . " 00:00:00");
  253. $return[] = strtotime($formattedDate1 . $str);
  254. return $return;
  255. }
  256. //前端传来的时间段 转换为时间戳
  257. //精确到日
  258. function changeDateToNewDate($time_range){
  259. if(empty($time_range[0]) || empty($time_range[1])) return [];
  260. // 创建一个 DateTime 对象并设置时区为 UTC
  261. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  262. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  263. // 将时区设置为 PRC
  264. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  265. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  266. // 将日期时间格式化为特定格式
  267. $formattedDate = $dateTime->format('Y-m-d');
  268. $formattedDate1 = $dateTime1->format('Y-m-d');
  269. $return = [];
  270. $return[] = strtotime($formattedDate);
  271. $return[] = strtotime($formattedDate1);
  272. return $return;
  273. }
  274. function changeDateToNewDate2($time){
  275. if(empty($time_range)) return [];
  276. // 创建一个 DateTime 对象并设置时区为 UTC
  277. $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC'));
  278. // 将时区设置为 PRC
  279. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  280. // 将日期时间格式化为特定格式
  281. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  282. $formattedDate1 = $dateTime->format('Y-m-d 23:59:59');
  283. $return = [];
  284. $return[] = strtotime($formattedDate);
  285. $return[] = strtotime($formattedDate1);
  286. return $return;
  287. }
  288. //前端传来的时间 转为时间戳
  289. //精确到分
  290. function changeDateToDateMin($time){
  291. if(empty($time)) return '';
  292. // 创建一个 DateTime 对象并设置时区为 UTC
  293. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  294. // 将时区设置为 PRC
  295. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  296. // 将日期时间格式化为特定格式
  297. $formattedDate = $dateTime->format('Y-m-d H:i');
  298. return strtotime($formattedDate);
  299. }
  300. //前端传来的时间 转为时间戳
  301. //精确到日
  302. function changeDateToDate($time, $is_end = false){
  303. if(empty($time)) return '';
  304. // 创建一个 DateTime 对象并设置时区为 UTC
  305. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  306. // 将时区设置为 PRC
  307. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  308. $str = "00:00:00";
  309. if($is_end) $str = "23:59:59";
  310. // 将日期时间格式化为特定格式
  311. $formattedDate = $dateTime->format('Y-m-d ' . $str);
  312. return strtotime($formattedDate);
  313. }
  314. /**
  315. * 检查数字是否合法,并可验证其正负性和小数位数
  316. *
  317. * @param mixed $number 要检查的值
  318. * @param int $decimals 允许的最大小数位数(默认 2)
  319. * @param string|null $sign 要求的符号:'positive' 大于 0 , 'negative' 小于0, 'zero' 等于0, 'non-negative' 大于或等于 0, 'non-positive' 小于或等于 0 null 表示不限制
  320. * @param bool $strict 是否严格模式(不允许整数传字符串等)
  321. * @return array ['valid' => bool, 'error' => string|null, 'info' => array]
  322. */
  323. public function checkNumber($number, $decimals = 2, $sign = null, $strict = false)
  324. {
  325. $result = [
  326. 'valid' => false,
  327. 'error' => null,
  328. 'info' => []
  329. ];
  330. // 1. 类型检查
  331. if ($strict) {
  332. if (!is_numeric($number) || is_bool($number)) {
  333. $result['error'] = '必须是数字类型';
  334. return $result;
  335. }
  336. } else {
  337. // 宽松模式:允许字符串数字
  338. if (!is_numeric($number)) {
  339. $result['error'] = '不是有效数字';
  340. return $result;
  341. }
  342. }
  343. $num = (float)$number; // 统一转为浮点数处理
  344. // 2. 正负号检查
  345. if ($sign !== null) {
  346. switch ($sign) {
  347. case 'positive':
  348. if ($num <= 0) {
  349. $result['error'] = '数字必须大于 0';
  350. return $result;
  351. }
  352. break;
  353. case 'negative':
  354. if ($num >= 0) {
  355. $result['error'] = '数字必须小于 0';
  356. return $result;
  357. }
  358. break;
  359. case 'zero':
  360. if ($num != 0) {
  361. $result['error'] = '数字必须等于 0';
  362. return $result;
  363. }
  364. break;
  365. case 'non-negative': // 大于等于 0
  366. if ($num < 0) {
  367. $result['error'] = '数字必须大于或等于 0';
  368. return $result;
  369. }
  370. break;
  371. case 'non-positive': // 小于等于 0
  372. if ($num > 0) {
  373. $result['error'] = '数字必须小于或等于 0';
  374. return $result;
  375. }
  376. break;
  377. default:
  378. $result['error'] = "不支持的符号类型: '{$sign}'";
  379. return $result;
  380. }
  381. }
  382. // 3. 小数位数检查
  383. // 将数字转为标准格式,避免科学计数法
  384. $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0
  385. if ($numStr === '' || $numStr === '-') {
  386. $numStr = '0';
  387. }
  388. // 检查是否有小数点
  389. if (strpos($numStr, '.') === false) {
  390. $decimalPlaces = 0;
  391. } else {
  392. $parts = explode('.', $numStr);
  393. $decimalPlaces = strlen($parts[1]);
  394. }
  395. if ($decimalPlaces > $decimals) {
  396. $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)";
  397. return $result;
  398. }
  399. // 4. 附加信息
  400. $result['valid'] = true;
  401. $result['info'] = [
  402. 'original' => $number,
  403. 'value' => $num,
  404. 'decimal_places' => $decimalPlaces,
  405. 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'),
  406. ];
  407. return $result;
  408. }
  409. public function getTopId($id, $data) {
  410. foreach ($data as $item) {
  411. if ($item['id'] == $id) {
  412. if ($item['parent_id'] == 0) {
  413. // 找到最顶级的id
  414. return $item['id'];
  415. } else {
  416. // 继续递归查找父级
  417. return $this->getTopId($item['parent_id'], $data);
  418. }
  419. }
  420. }
  421. // 如果没有找到匹配的id,则返回null或者其他你希望的默认值
  422. return 0;
  423. }
  424. // 递归查找所有父级id
  425. public function findParentIds($id, $data) {
  426. $parentIds = [];
  427. foreach ($data as $item) {
  428. if ($item['id'] == $id) {
  429. $parentId = $item['parent_id'];
  430. if ($parentId) {
  431. $parentIds[] = $parentId;
  432. $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data));
  433. }
  434. break;
  435. }
  436. }
  437. return $parentIds;
  438. }
  439. // 递归查找所有子级id
  440. public function findChildIds($id, $data) {
  441. $childIds = [];
  442. foreach ($data as $item) {
  443. if ($item['parent_id'] == $id) {
  444. $childId = $item['id'];
  445. $childIds[] = $childId;
  446. $childIds = array_merge($childIds, $this->findChildIds($childId, $data));
  447. }
  448. }
  449. return $childIds;
  450. }
  451. public function getDataFile($data){
  452. foreach ($data as $key => $value){
  453. if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]);
  454. }
  455. return $data;
  456. }
  457. // 校验域名是否通畅可达
  458. // $domain baidu.com 不要带http这些协议头
  459. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  460. function isDomainAvailable($domain) {
  461. $ip = gethostbyname($domain);
  462. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  463. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  464. return true;
  465. }
  466. public function delStorageFile($old, $new = [], $dir = "upload_files/"){
  467. foreach ($old as $value){
  468. if(! in_array($value, $new)){
  469. $filename_rep = "/api/uploadFiles/";
  470. $filename = str_replace($filename_rep, "", $value);
  471. $filePath = $dir . $filename;
  472. if (Storage::disk('public')->exists($filePath)) {
  473. // 文件存在 进行删除操作
  474. Storage::disk('public')->delete($filePath);
  475. }
  476. }
  477. }
  478. }
  479. public function showTimeAgo($time, $time_big){
  480. // 计算时间差(秒)
  481. $diffInSeconds = $time_big - $time;
  482. // 将时间差转换为更易处理的单位
  483. $diffInMinutes = floor($diffInSeconds / 60);
  484. $diffInHours = floor($diffInSeconds / 3600);
  485. $diffInDays = floor($diffInSeconds / (3600 * 24));
  486. // 根据时间差生成描述性文本
  487. if ($diffInSeconds < 60) {
  488. $timeAgo = '刚刚';
  489. } elseif ($diffInMinutes < 60) {
  490. $timeAgo = $diffInMinutes . '分钟前';
  491. } elseif ($diffInHours < 24) {
  492. $timeAgo = $diffInHours . '小时前';
  493. } elseif ($diffInDays < 2) {
  494. $timeAgo = '昨天';
  495. } elseif ($diffInDays < 7) {
  496. $timeAgo = $diffInDays . '天前';
  497. } elseif ($diffInDays < 15) {
  498. $timeAgo = '一周前';
  499. } elseif ($diffInDays < 30) {
  500. $timeAgo = '半个月内';
  501. } else {
  502. // 如果超过半个月,可以使用具体的日期格式
  503. $crtTimeDate = date('Y-m-d', $time);
  504. $timeAgo = '在 ' . $crtTimeDate;
  505. }
  506. return $timeAgo;
  507. }
  508. // 递归函数,用于在数据结构中查找值
  509. function findLabelsByValue($data, $valuesToFind, &$foundLabels) {
  510. foreach ($data as $item) {
  511. if (isset($item['value']) && in_array($item['value'], $valuesToFind)) {
  512. // 如果找到值,则添加其label到结果数组中
  513. $foundLabels[] = $item['label'];
  514. // 移除已找到的值,避免重复查找
  515. $key = array_search($item['value'], $valuesToFind);
  516. if ($key !== false) {
  517. unset($valuesToFind[$key]);
  518. }
  519. }
  520. if (isset($item['children']) && !empty($item['children'])) {
  521. // 递归调用自身来查找子节点
  522. $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels);
  523. }
  524. // 如果所有值都已找到,则停止递归
  525. if (empty($valuesToFind)) {
  526. break;
  527. }
  528. }
  529. }
  530. public function changeAndReturnDate($date_int){
  531. $int = intval($date_int);
  532. $bool = (string)$int === $date_int;
  533. if(! $bool || $date_int < 0) return [false, '日期不正确'];
  534. $epoch = strtotime("1900-01-01 00:00:00");
  535. $days = $date_int - 1;
  536. $seconds = $days * 86400;
  537. return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))];
  538. }
  539. function findTopLevelId($data, $id) {
  540. // 遍历数据,查找给定ID的节点
  541. foreach ($data as $item) {
  542. if ($item['id'] == $id) {
  543. // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点
  544. if ($item['parent_id'] === 0) {
  545. return $item['id'];
  546. } else {
  547. // 否则,继续寻找其父节点的最顶层节点
  548. return $this->findTopLevelId($data, $item['parent_id']);
  549. }
  550. }
  551. }
  552. // 如果没有找到给定ID的节点,返回null或抛出异常
  553. return 0;
  554. }
  555. function returnDays($time = [], $is_mirco_time = false){
  556. // 示例时间戳
  557. $timestamp1 = $time[0];
  558. $timestamp2 = $time[1];
  559. // 计算时间差
  560. $difference = abs($timestamp2 - $timestamp1);
  561. // 将时间差转换为天数
  562. $days = floor($difference / (60 * 60 * 24));
  563. if($is_mirco_time) $days = $days / 1000;
  564. return $days;
  565. }
  566. public function post_helper($url, $data, $header = [], $timeout = 30){
  567. $ch = curl_init();
  568. curl_setopt($ch, CURLOPT_URL, $url);
  569. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  570. curl_setopt($ch, CURLOPT_ENCODING, '');
  571. curl_setopt($ch, CURLOPT_POST, 1);
  572. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  573. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  574. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  575. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  576. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  577. $r = curl_exec($ch);
  578. if ($r === false) {
  579. // 获取错误号
  580. $errorNumber = curl_errno($ch);
  581. // 获取错误信息
  582. $errorMessage = curl_error($ch);
  583. $message = "cURL Error #{$errorNumber}: {$errorMessage}";
  584. return [false, $message];
  585. }
  586. curl_close($ch);
  587. return [true, json_decode($r, true)];
  588. }
  589. function isOverThreeMonths($timestamp1, $timestamp2, $default_month = 3) {
  590. $date1 = new \DateTime();
  591. $date1->setTimestamp($timestamp1);
  592. $date2 = new \DateTime();
  593. $date2->setTimestamp($timestamp2);
  594. // 计算两个日期的间隔
  595. $interval = $date1->diff($date2);
  596. // 总月数 = 年差 * 12 + 月差
  597. $months = $interval->y * 12 + $interval->m;
  598. if ($months >= $default_month) {
  599. return [false, "时间区间须在" . $default_month . "个月内"];
  600. }elseif ($months == 3 && ($interval->d > 0 || $interval->h > 0 || $interval->i > 0 || $interval->s > 0)) {
  601. return [false, "时间区间须在" . $default_month . "个月内"];
  602. }
  603. return [true, ''];
  604. }
  605. public function countTotal($rows, $config = [])
  606. {
  607. if (empty($rows)) return [];
  608. $total = [];
  609. foreach ($config as $col) {
  610. $key = $col['key'] ?? null;
  611. if (!$key) continue;
  612. $decimals = $col['decimals'] ?? 2; // 默认保留 2 位
  613. // 1. 基础字段累加
  614. if (!empty($col['sum']) && $col['sum'] == 1) {
  615. $sum = '0';
  616. foreach ($rows as $row) {
  617. $sum = bcadd($sum, (string)($row[$key] ?? 0), $decimals);
  618. }
  619. $total[$key] = $sum;
  620. }
  621. // 2. 公式字段
  622. if (!empty($col['sum']) && $col['sum'] == 2 && !empty($col['formula'])) {
  623. $total[$key] = $this->calcFormula($col['formula'], $total, $decimals);
  624. }
  625. }
  626. return $total;
  627. }
  628. /**
  629. * 解析并计算公式(基于 bcmath)
  630. * 例: profit / income * 100
  631. */
  632. public function calcFormula($formula, $values, $decimals = 2)
  633. {
  634. $tokens = preg_split('/\s+/', trim($formula));
  635. $stack = [];
  636. foreach ($tokens as $token) {
  637. if ($token === '') continue;
  638. if (isset($values[$token])) {
  639. $stack[] = $values[$token];
  640. } elseif (is_numeric($token)) {
  641. $stack[] = (string)$token;
  642. } else {
  643. $stack[] = $token;
  644. }
  645. }
  646. $expr = implode(' ', $stack);
  647. return $this->evaluateWithBCMath($expr, $decimals);
  648. }
  649. /**
  650. * 用 bcmath 安全执行表达式 (支持 + - * /)
  651. */
  652. public function evaluateWithBCMath($expr, $decimals = 2)
  653. {
  654. preg_match_all('/(\d+(?:\.\d+)?|[+\/*-])/', $expr, $matches);
  655. $tokens = $matches[0] ?? [];
  656. if (empty($tokens)) return 0;
  657. $output = [];
  658. $ops = [];
  659. foreach ($tokens as $token) {
  660. if (is_numeric($token)) {
  661. $output[] = (string)$token;
  662. } elseif (in_array($token, ['+', '-', '*', '/'])) {
  663. $ops[] = $token;
  664. }
  665. }
  666. $result = array_shift($output);
  667. foreach ($ops as $i => $op) {
  668. $next = $output[$i] ?? '0';
  669. switch ($op) {
  670. case '+':
  671. $result = bcadd($result, $next, $decimals);
  672. break;
  673. case '-':
  674. $result = bcsub($result, $next, $decimals);
  675. break;
  676. case '*':
  677. $result = bcmul($result, $next, $decimals);
  678. break;
  679. case '/':
  680. if (bccomp($next, '0', $decimals) === 0) {
  681. $result = '0'; // 避免除零
  682. } else {
  683. $result = bcdiv($result, $next, $decimals);
  684. }
  685. break;
  686. }
  687. }
  688. return $result;
  689. }
  690. public function generateBillNo($need = [], $length = 5)
  691. {
  692. $type = $need['type'];
  693. $prefix = $need['prefix'] ?? '';
  694. $period = $need['period']; // 示例:202603
  695. // 1. 原子更新:去掉 top_depart_id 维度
  696. // 联合唯一索引应调整为 (bill_type, period)
  697. DB::statement("
  698. INSERT INTO sys_bill_sequences (bill_type, period, current_value)
  699. VALUES (?, ?, 1)
  700. ON DUPLICATE KEY UPDATE current_value = current_value + 1
  701. ", [$type, $period]);
  702. // 2. 获取本次生成的流水号
  703. $sequence = DB::table('sys_bill_sequences')
  704. ->where('bill_type', $type)
  705. ->where('period', $period)
  706. ->value('current_value');
  707. // 3. 拼接输出:前缀 + 周期 + 补齐流水号
  708. return $prefix . $period . str_pad($sequence, $length, '0', STR_PAD_LEFT);
  709. }
  710. }