common.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. <?php
  2. // 应用公共文件
  3. use think\facade\Config;
  4. use think\facade\Db;
  5. use think\facade\Filesystem;
  6. use think\helper\Str;
  7. use app\admin\model\DataGroup as DataGroupModel;
  8. use app\admin\model\DataShare as DataShareModel;
  9. // 应用公共文件
  10. function app_show($code=0,$message="",$data=[]){
  11. $result = ['code'=>$code,"message"=>$message,"data"=>$data];
  12. echo json_encode($result,JSON_UNESCAPED_UNICODE);
  13. die();
  14. }
  15. // 应用公共文件
  16. function error_show($code=0,$message=""){
  17. $result = ['code'=>$code,"message"=>$message];
  18. echo json_encode($result,JSON_UNESCAPED_UNICODE);
  19. die();
  20. }
  21. function GetUserInfo($token){
  22. $userCommon = new \app\admin\common\User();
  23. return $userCommon->handle('verifyToken',['token'=>$token]);
  24. // $host = Config::get("app");
  25. // $url = $host["api_host"]."/Api/userinfo";
  26. // $data=[
  27. // "token"=>$token
  28. // ];
  29. // $response=curl_request($url,$data);
  30. //
  31. // return json_decode($response,true);
  32. }
  33. //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
  34. function curl_request($url,$post=''){
  35. $curl = curl_init();
  36. curl_setopt($curl, CURLOPT_URL, $url);
  37. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
  38. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  39. curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
  40. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  41. if($post) {
  42. curl_setopt($curl, CURLOPT_POST, 1);
  43. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
  44. }
  45. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  46. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  47. $data = curl_exec($curl);
  48. if (curl_errno($curl)) {
  49. return curl_error($curl);
  50. }
  51. curl_close($curl);
  52. return $data;
  53. }
  54. /**手机号验证
  55. * @param $mobile
  56. * @return bool
  57. */
  58. function checkMobile($mobile){
  59. if (!is_numeric($mobile)) {
  60. return false;
  61. }
  62. return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
  63. }
  64. function checkTel($tel){
  65. if (!$tel) {
  66. return false;
  67. }
  68. return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
  69. }
  70. /**邮箱验证
  71. * @param $email
  72. * @return bool
  73. */
  74. function checkEmail($email){
  75. if (!$email) {
  76. return false;
  77. }
  78. return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
  79. }
  80. /**
  81. * @param
  82. * @return int
  83. */
  84. function makeSalt(){
  85. $salt = rand(10000000,99999999);
  86. return $salt;
  87. }
  88. /**
  89. * @param $token
  90. * @return array
  91. * @throws \think\db\exception\DataNotFoundException
  92. * @throws \think\db\exception\DbException
  93. * @throws \think\db\exception\ModelNotFoundException
  94. * @throws \think\exception\DbException
  95. */
  96. function VerifyTokens($token){
  97. // $host = Config::get("app");
  98. // $url = $host["api_host"]."/Api/verify_token";
  99. // $data=[
  100. // "token"=>$token
  101. // ];
  102. // $response=curl_request($url,$data);
  103. $userCommon = new \app\admin\common\User();
  104. $rs = $userCommon->VerifyTokens(['token'=>$token]);
  105. return json_decode($rs,true);
  106. }
  107. /**
  108. * @param $token
  109. * @param $condition
  110. * @return mixed
  111. */
  112. function GetUserlist($token,$condition){
  113. $host = Config::get("app");
  114. $url = $host["api_host"]."/Api/getuserlist";
  115. $condition['token']=$token;
  116. $response=curl_request($url,$condition);
  117. return json_decode($response,true);
  118. }
  119. /**
  120. * @param $token
  121. * @param $condition
  122. * @return mixed
  123. */
  124. function GetAccountall($token, $condition){
  125. $host = Config::get("app");
  126. $url = $host["api_host"]."/Api/userall";
  127. $condition['token']=$token;
  128. $response=curl_request($url,$condition);
  129. return json_decode($response,true);
  130. }
  131. function GetList($token,$condition){
  132. $host = Config::get("app");
  133. $url = $host["api_host"]."/Api/userlist";
  134. $condition['token']=$token;
  135. $response=curl_request($url,$condition);
  136. return json_decode($response,true);
  137. }
  138. /**
  139. * @param $token
  140. * @param $condition ['id'=>1]
  141. * @return mixed
  142. */
  143. function GetInfoById($token,$condition){
  144. $host = Config::get("app");
  145. $url = $host["api_host"]."/Api/userinfobyid";
  146. $condition['token']=$token;
  147. $response=curl_request($url,$condition);
  148. return json_decode($response,true);
  149. }
  150. function GetInfoNoToken($condition){
  151. $host = Config::get("app");
  152. $url = $host["api_host"]."/Api/uinfo";
  153. $response=curl_request($url,$condition);
  154. return json_decode($response,true);
  155. }
  156. function makeNo($str){
  157. $date=date("mdHis");
  158. $year = date("Y")-2000;
  159. $msec=rand(1000,9999);
  160. return $str.$year.$date.$msec;
  161. }
  162. function randomkeys($length) {
  163. $returnStr='';
  164. $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
  165. for($i = 0; $i < $length; $i ++) {
  166. $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
  167. }
  168. return $returnStr;
  169. }
  170. function tree(){
  171. }
  172. /**
  173. * @param $files
  174. * @return array
  175. */
  176. function UploadImg($files)
  177. {
  178. $savename = [];
  179. $files = !is_array($files) ? [$files] : $files;
  180. try {
  181. //验证
  182. validate(['imgFile' => ['fileSize' => 10240000, 'fileExt' => 'jpg,jpeg,png,bmp,gif', 'fileMime' => 'image/jpeg,image/png,image/gif']])->check(['imgFile' => $files]);
  183. //文件存放路径
  184. $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
  185. $url = 'topic' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
  186. if (is_dir($root . $url) == false) mkdir($root . $url, 0777, true);
  187. foreach ($files as $file) {
  188. //文件名
  189. $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
  190. $file->move($root . $url, $file_name);
  191. $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
  192. $savename[] = $temp;
  193. }
  194. return $savename;
  195. } catch (\think\exception\ValidateException $e) {
  196. return $e->getError();
  197. }
  198. }
  199. /**
  200. * @param $files
  201. * @return array
  202. */
  203. function UploadFile($files)
  204. {
  205. $savename = [];
  206. $files = !is_array($files) ? [$files] : $files;
  207. try {
  208. //验证
  209. validate(['imgFile' => ['fileSize' => 10240000, 'fileExt' => 'xlsx,xls,pdf,zip,rar,7z,doc,docx']])->check(['imgFile' => $files]);
  210. foreach ($files as $file) {
  211. // $url = Filesystem::disk('public')->putFile('files/' . date("Ymd"), $file, function () use ($file) {
  212. // return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  213. // });
  214. // $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  215. // $temp = ["url" => $url, "name" => $name];
  216. //文件存放路径
  217. $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
  218. $url = 'files' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
  219. //文件名
  220. $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
  221. $file->move($root . $url, $file_name);
  222. $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
  223. $savename[] = $temp;
  224. }
  225. return $savename;
  226. } catch (\think\exception\ValidateException $e) {
  227. return $e->getError();
  228. }
  229. }
  230. /**
  231. * @param $files
  232. * @return array
  233. */
  234. function UploadVideo($files)
  235. {
  236. $savename = [];
  237. $files = !is_array($files) ? [$files] : $files;
  238. try {
  239. //验证
  240. validate(['videoFile' => ['fileSize' => 10240000, 'fileExt' => 'mp4,mp3,avi']])->check(['videoFile' => $files]);
  241. foreach ($files as $file) {
  242. // $url = Filesystem::disk('public')->putFile('video/' . date("Ymd"), $file, function () use ($file) {
  243. // return str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName() . "_" . date('YmdHis'));
  244. // });
  245. // $name = str_replace('.' . $file->getOriginalExtension(), '', $file->getOriginalName());
  246. // $temp = ["url" => $url, "name" => $name];
  247. //文件存放路径
  248. $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
  249. $url = 'video' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
  250. //文件名
  251. $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
  252. $file->move($root . $url, $file_name);
  253. $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
  254. $savename[] = $temp;
  255. }
  256. return $savename;
  257. } catch (\think\exception\ValidateException $e) {
  258. return $e->getError();
  259. }
  260. }
  261. /**
  262. * @param $token
  263. * @param $condition
  264. * @return mixed
  265. */
  266. function resetpwd($token,$condition){
  267. $host = Config::get("app");
  268. $url = $host["api_host"]."/Api/passset";
  269. $condition['token']=$token;
  270. $response=curl_request($url,$condition);
  271. return json_decode($response,true);
  272. }
  273. function resetpasswd($token,$condition){
  274. $host = Config::get("app");
  275. $url = $host["api_host"]."/Api/passsave";
  276. $condition['token']=$token;
  277. $response=curl_request($url,$condition);
  278. return json_decode($response,true);
  279. }
  280. /**
  281. * @param $token
  282. * @param $condition
  283. * @return mixed
  284. */
  285. function resetinfo($token,$condition){
  286. $host = Config::get("app");
  287. $url = $host["api_host"]."/Api/usersave";
  288. $condition['token']=$token;
  289. $response=curl_request($url,$condition);
  290. return json_decode($response,true);
  291. }
  292. /**
  293. * @param $token
  294. * @param $condition
  295. * @return mixed
  296. */
  297. function resetstatus($token,$condition){
  298. $host = Config::get("app");
  299. $url = $host["api_host"]."/Api/userstatus";
  300. $condition['token']=$token;
  301. $response=curl_request($url,$condition);
  302. return json_decode($response,true);
  303. }
  304. /**
  305. * @param $data
  306. * @throws \think\db\exception\DataNotFoundException
  307. * @throws \think\db\exception\DbException
  308. * @throws \think\db\exception\ModelNotFoundException
  309. */
  310. function crea($data,$vio=0)
  311. {
  312. $db = Db::name("company_item")->where(['pid'=>$data['id'],'is_del'=>0])->select()->toArray();
  313. if($vio==1){
  314. $d = Db::name("depart_user")->where(['itemid'=>$data['id'],'is_del'=>0])->select()->toArray();
  315. if(empty($d)){
  316. $data['item']=[];
  317. }else{
  318. $data['item']=$d;
  319. }
  320. }
  321. if(empty($db)){
  322. $data['child']=[];
  323. return $data;
  324. }
  325. //var_dump($db);
  326. foreach ($db as $p){
  327. $data['child'][]=crea($p,$vio);
  328. }
  329. return $data;
  330. }
  331. function GetPart($id,$data=[]){
  332. $userCommon = new \app\admin\common\User();
  333. $rs = $userCommon->handle('get_part',['itemid'=>$id]);
  334. return $rs['data'];
  335. // $db = Db::name("company_item")->where(['id'=>$id,'is_del'=>0])->find();
  336. // if($db==false){
  337. // return [];
  338. // }
  339. // $tem=[];
  340. // $tem['id']=$db['id'];
  341. // $tem['name']=$db['name'];
  342. // array_unshift($data,$tem);
  343. // if($db['pid']==0){
  344. // // krsort($data);
  345. // return $data;
  346. // }else{
  347. // return GetPart($db['pid'],$data);
  348. // }
  349. }
  350. function stro($data){
  351. $db=Db::name('cat')->where(['pid'=>$data['id']])->select()->toArray();
  352. if(empty($db)){
  353. $data['child']=[];
  354. return $data;
  355. }
  356. foreach ($db as $item) {
  357. $data['child'][]=stro($item);
  358. }
  359. return $data;
  360. }
  361. function coco($data){
  362. $db=Db::name('exclusive')->where(['pid'=>$data['id']])->select()->toArray();
  363. if(empty($db)){
  364. $data['child']=[];
  365. return $data;
  366. }
  367. foreach ($db as $item) {
  368. $data['child'][]=coco($item);
  369. }
  370. return $data;
  371. }
  372. function mai($var,$data=[]){
  373. $str = Db::name('exclusive')->where(['id'=>$var])->find();
  374. if($str==false){
  375. return [];
  376. }
  377. $vmn =[];
  378. $vmn['id'] =$str['id'];
  379. $vmn['rname'] =$str['name'];
  380. array_unshift($data,$vmn);
  381. // $var['id']=made();
  382. if($str['pid']==0){
  383. // krsort($data);
  384. return $data;
  385. }else{
  386. return mai($str['pid'],$data);
  387. }
  388. }
  389. function made($var,$data=[]){
  390. $str = Db::name('cat')->where(['id'=>$var])->find();
  391. if($str==false){
  392. return [];
  393. }
  394. $vmn =[];
  395. $vmn['id'] =$str['id'];
  396. $vmn['name'] =$str['cat_name'];
  397. array_unshift($data,$vmn);
  398. // $var['id']=made();
  399. if($str['pid']==0){
  400. // krsort($data);
  401. return $data;
  402. }else{
  403. return made($str['pid'],$data);
  404. }
  405. }
  406. //获取有赞分类信息
  407. function made_youzan(int $yz_cat_id=0,$data=[]){
  408. $rs = get_yz_cat_info($yz_cat_id);
  409. if(empty($rs)) return [];
  410. $vmn =[];
  411. $vmn['yz_cat_id'] =$rs['id'];
  412. $vmn['yz_cat_name'] =$rs['yz_cat_name'];
  413. array_unshift($data,$vmn);
  414. if($rs['parent_cid']==0) return $data;
  415. else return made_youzan($rs['parent_cid'],$data);
  416. }
  417. //跨数据库获取有赞分类信息
  418. if(!function_exists('get_yz_cat_info')){
  419. function get_yz_cat_info(int $yz_cat_id=0){
  420. $key = 'yz_cat_item_'.(string)$yz_cat_id;
  421. $rs = \think\facade\Cache::get($key);
  422. if(!$rs){
  423. $rs = Db::connect('mysql_yz')
  424. ->table('yz_cat')
  425. ->field('id,yz_cat_name,parent_cid')
  426. ->where(['id'=>$yz_cat_id,'status'=>1])
  427. ->findOrEmpty();
  428. if($rs) \think\facade\Cache::set($key,$rs,36000);
  429. }
  430. return $rs;
  431. }
  432. }
  433. function catChild($var,&$data=[]){
  434. $str = Db::name('cat')->where(['id'=>$var])->find();
  435. if($str==false){
  436. return;
  437. }
  438. $data[]=$var;
  439. $lsit = Db::name("cat")->where(["pid"=>$var,"status"=>1,"is_del"=>0])->column("id");
  440. if(!empty($lsit)){
  441. foreach ($lsit as $value){
  442. catChild($value,$data);
  443. }
  444. }
  445. return $data;
  446. }
  447. function makeExcluse($var,$data=[]){
  448. $str = Db::name('exclusive')->where(['id'=>$var])->find();
  449. if($str==false){
  450. return [];
  451. }
  452. $vmn =[];
  453. $vmn['id'] =$str['id'];
  454. $vmn['name'] =$str['name'];
  455. array_unshift($data,$vmn);
  456. // $var['id']=made();
  457. if($str['pid']==0){
  458. // krsort($data);
  459. return $data;
  460. }else{
  461. return makeExcluse($str['pid'],$data);
  462. }
  463. }
  464. function sear($id){
  465. $item = Db::name('cat')->where(['id'=>$id])->field("search")->find();
  466. if($item==false){
  467. return false;
  468. }else{
  469. $temp = Db::name('cat')->where(['pid'=>$id,'is_del'=>0])->select();
  470. if ($temp==false){
  471. return false;
  472. }
  473. }
  474. foreach ($temp as $value){
  475. $value['search']=$item['search']."_".$value['cat_name'];
  476. $list = Db::name('cat')->save($value);
  477. sear($value['id']);
  478. }
  479. }
  480. function manger($list=[],$level=1){
  481. $var = Db::name('cat')->where(['pid'=>$list,'level'=>$level+1])->column("id");
  482. if(empty($var)){
  483. return $list;
  484. }
  485. $a=array_merge($list,$var);
  486. return manger($a,$level+1);
  487. }
  488. /**
  489. * @param $files
  490. * @param string $extend
  491. * @return array
  492. * @throws PHPExcel_Exception
  493. * @throws PHPExcel_Reader_Exception
  494. */
  495. function upload_excel($files,$extend="xls")
  496. {
  497. // 获取表单上传文件
  498. try {
  499. validate([
  500. 'file' => [
  501. // 限制文件大小(单位b),这里限制为4M
  502. //fileSize' => 4 * 1024 * 1024,
  503. 'fileExt' => 'xlsx,xls'
  504. ]
  505. ],
  506. [
  507. //'file.fileSize' => '文件太大',
  508. 'file.fileExt' => '不支持的文件',
  509. ]
  510. )->check(['file' => $files]);
  511. // $name = $files->getOriginalExtension();
  512. if ($extend == 'xlsx') {
  513. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  514. } else {
  515. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  516. }
  517. $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
  518. $import_path = root_path() . 'public/storage/' . $savename;
  519. $spreadsheet = $objReader->load($import_path);
  520. $sheet = $spreadsheet->getActiveSheet();
  521. $sheetData = $sheet->toArray();
  522. if (empty($sheetData) || !is_array($sheetData)) {
  523. return ['code' => 1003, "msg" => '数据不能为空'];
  524. }
  525. $list = [];
  526. foreach ($sheetData as $key => $value) {
  527. $list[] = $value;
  528. }
  529. return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
  530. } catch (think\exception\ValidateException $e) {
  531. // echo $e->getMessage();
  532. return ['code' => 1003, "msg" => $e->getMessage()];
  533. }
  534. }
  535. /**
  536. * @param string $fileName
  537. * @param array $headArr
  538. * @param array $data
  539. */
  540. function excelSave($fileName = '', $headArr = [], $data = [])
  541. {
  542. $objPHPExcel = new PHPExcel();
  543. $objPHPExcel->getProperties();
  544. $keyA = 0; // 设置表头
  545. foreach ($headArr as $v) {
  546. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  547. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  548. $keyA += 1;
  549. }
  550. $column = 2;
  551. $objActSheet = $objPHPExcel->getActiveSheet();
  552. foreach ($data as $key => $rows) { // 行写入
  553. $span = 0;
  554. foreach ($rows as $keyName => $value) { // 列写入
  555. //判断数据是否有数组,如果有数组,转换成字符串
  556. if(is_array($value)){
  557. $value = implode("、", $value);
  558. }
  559. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  560. $span++;
  561. }
  562. $column++;
  563. }
  564. // var_dump($objActSheet->getActiveCell());
  565. $file = $fileName. ".xls";
  566. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  567. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  568. $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
  569. if(!is_dir($dir)){
  570. mkdir($dir,0777,true);
  571. }
  572. PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
  573. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  574. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  575. $objWriter->save($dir . $file); // 文件通过浏览器下载
  576. $url = $dir . $file;
  577. if(!file_exists($url)){
  578. echo "文件生成失败";
  579. }
  580. $saveDir = root_path()."public/storage/zip/";
  581. if(!is_dir( $saveDir)){
  582. mkdir($saveDir,0777,true);
  583. }
  584. $datetime = date("Y-m-d H:i:s");
  585. $file_dir = $saveDir.$datetime.".zip";
  586. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  587. $zip = new \ZipArchive ();
  588. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  589. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
  590. true) echo '无法打开文件或者文件创建失败';
  591. # 5.3 批量写入压缩包
  592. $zip->addEmptyDir($fileName);
  593. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  594. @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
  595. # 5.4 关闭压缩包写入
  596. $zip->close();
  597. @deldir($dir);
  598. # 6. 检查文件是否存在,并输出文件
  599. if (! file_exists ( $file_dir )) echo '简历文件不存在';
  600. ob_clean();
  601. flush();
  602. header("Cache-Control: max-age=0");
  603. header("Content-Description: File Transfer");
  604. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  605. header("Content-Type: application/octet-stream"); # 流文件输出
  606. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  607. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  608. // readfile($file_dir); # 输出文件
  609. $res = read_big_file($file_dir);
  610. foreach ($res as $val) {
  611. echo $val;
  612. }
  613. @ unlink($file_dir);
  614. exit();
  615. }
  616. //读取大文件
  617. if (!function_exists('read_big_file')){
  618. function read_big_file(string $file=''){
  619. $handle = fopen($file, 'rb');
  620. while (feof($handle) === false) {
  621. yield fgets($handle);
  622. }
  623. fclose($handle);
  624. }
  625. }
  626. function deldir($path){
  627. //如果是目录则继续
  628. if(is_dir($path)){
  629. //扫描一个文件夹内的所有文件夹和文件并返回数组
  630. $p = scandir($path);
  631. //如果 $p 中有两个以上的元素则说明当前 $path 不为空
  632. if(count($p)>2){
  633. foreach($p as $val){
  634. //排除目录中的.和..
  635. if($val !="." && $val !=".."){
  636. //如果是目录则递归子目录,继续操作
  637. if(is_dir($path.$val)){
  638. //子目录中操作删除文件夹和文件
  639. deldir($path.$val.'/');
  640. }else{
  641. //如果是文件直接删除
  642. unlink($path.$val);
  643. }
  644. }
  645. }
  646. }
  647. }
  648. //删除目录
  649. return rmdir($path);
  650. }
  651. /**
  652. * @param string $AddrJson
  653. */
  654. function GetAddr($AddrJson=""){
  655. if($AddrJson==""){
  656. return '';
  657. }
  658. $adr = json_decode($AddrJson,true);
  659. if(!is_array($adr)){
  660. return '';
  661. }
  662. $addr='';
  663. if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
  664. $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
  665. $addr.=isset($provice['name']) ? $provice['name']:"";
  666. }
  667. if(isset($adr['city_code'])&&$adr['city_code']!=''){
  668. $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
  669. $addr.=isset($city['name']) ? $city['name']:"";
  670. }
  671. if(isset($adr['area_code'])&&$adr['area_code']!=''){
  672. $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
  673. $addr.=isset($area['name']) ? $area['name']:"";
  674. }
  675. return $addr;
  676. }
  677. /**
  678. * POST 请求
  679. * @param string $url
  680. * @param array $param
  681. * @param boolean $post_file 是否文件上传
  682. * @return string content
  683. */
  684. function post($url,$data,$header=[])
  685. {
  686. //对空格进行转义
  687. $url = str_replace(' ','+',$url);
  688. $ch = curl_init();
  689. //设置选项,包括URL
  690. curl_setopt($ch, CURLOPT_URL, "$url");
  691. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  692. curl_setopt($ch, CURLOPT_HEADER, 0);
  693. curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
  694. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  695. // POST数据
  696. // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  697. curl_setopt($ch, CURLOPT_POST, 1);
  698. // 把post的变量加上
  699. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  700. curl_setopt($ch, CURLOPT_HEADER, true);
  701. //执行并获取url地址的内容
  702. $output = curl_exec($ch);
  703. $errorCode = curl_errno($ch);
  704. //释放curl句柄
  705. $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  706. // 根据头大小去获取头信息内容
  707. $header = substr($output, 0, $headerSize);
  708. curl_close($ch);
  709. if(0 !== $errorCode) {
  710. return false;
  711. }
  712. return $header;
  713. }
  714. function post2($url,$data,$header=[])
  715. {
  716. //对空格进行转义
  717. $url = str_replace(' ','+',$url);
  718. $ch = curl_init();
  719. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  720. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  721. //设置选项,包括URL
  722. curl_setopt($ch, CURLOPT_URL, "$url");
  723. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  724. curl_setopt($ch, CURLOPT_HEADER, 0);
  725. // POST数据
  726. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  727. curl_setopt($ch, CURLOPT_POST, 1);
  728. // 把post的变量加上
  729. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  730. $output = curl_exec($ch);
  731. $errorCode = curl_errno($ch);
  732. curl_close($ch);
  733. if(0 !== $errorCode) {
  734. return false;
  735. }
  736. return $output;
  737. }
  738. function GoldPrice($data,$cost_rate=0){
  739. $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
  740. ->find();
  741. // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
  742. // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
  743. $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
  744. $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
  745. return $saleprice;
  746. }
  747. function GoodPrice($data,$cost_rate=0){
  748. $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
  749. );
  750. return $rate;
  751. }
  752. function checkRole($roleid,$menu){
  753. $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  754. if($roleinfo['private_data']!=""){
  755. $private = explode(",",$roleinfo['private_data']);
  756. if(in_array($menu,$private)){
  757. return true;
  758. }
  759. }
  760. return false;
  761. }
  762. /**
  763. * 根据地址解析省市区
  764. * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
  765. */
  766. if (!function_exists('get_address')) {
  767. function get_address(string $address = '')
  768. {
  769. preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
  770. if (count($matches) > 1) {
  771. $province = $matches[count($matches) - 2];
  772. $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
  773. }
  774. preg_match('/(.*?(市|自治州|地区|区划|县|盟))/', $address, $matches);
  775. if (count($matches) > 1) {
  776. $city = $matches[count($matches) - 2];
  777. $address = str_replace($city, '', $address);
  778. }
  779. preg_match('/(.*?(区|县|镇|乡|街道|旗|市))/', $address, $matches);
  780. if (count($matches) > 1) {
  781. $area = $matches[count($matches) - 2];
  782. $address = str_replace($area, '', $address);
  783. }
  784. return [
  785. 'province' => isset($province) ? $province : '',
  786. 'city' => isset($city) ? $city : '',
  787. 'district' => isset($area) ? $area : '',
  788. "address" => $address
  789. ];
  790. }
  791. }
  792. /**
  793. * 批量生成多个文件excel,生成压缩包
  794. */
  795. if (!function_exists('excelSaveBatch')) {
  796. function excelSaveBatch(array $datas = [])
  797. {
  798. $urls = [];
  799. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  800. if (!is_dir($dir)) {
  801. mkdir($dir, 0777, true);
  802. }
  803. foreach ($datas as $item) {
  804. $objPHPExcel = new PHPExcel();
  805. $objPHPExcel->getProperties();
  806. $keyA = 0; // 设置表头
  807. foreach ($item['head'] as $v) {
  808. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  809. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  810. $keyA += 1;
  811. }
  812. $column = 2;
  813. $objActSheet = $objPHPExcel->getActiveSheet();
  814. foreach ($item['list'] as $key => $rows) { // 行写入
  815. $span = 0;
  816. foreach ($rows as $keyName => $value) { // 列写入
  817. //判断数据是否有数组,如果有数组,转换成字符串
  818. if (is_array($value)) {
  819. $value = implode("、", $value);
  820. }
  821. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  822. $span++;
  823. }
  824. $column++;
  825. }
  826. // var_dump($objActSheet->getActiveCell());
  827. $file = $item['filename'] . ".xls";
  828. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  829. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  830. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  831. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  832. $objWriter->save($dir . $file); // 文件通过浏览器下载
  833. $url = $dir . $file;
  834. if (!file_exists($url)) {
  835. echo "文件生成失败";
  836. } else {
  837. $urls[] = $url;
  838. }
  839. }
  840. $saveDir = root_path() . "public/storage/zip/";
  841. if (!is_dir($saveDir)) {
  842. mkdir($saveDir, 0777, true);
  843. }
  844. $datetime = date("YmdHis");
  845. $file_dir = $saveDir . $datetime . ".zip";
  846. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  847. $zip = new \ZipArchive ();
  848. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  849. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  850. # 5.3 批量写入压缩包
  851. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  852. foreach ($urls as $fileName) {
  853. // @$zip->addFile($fileName);
  854. @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
  855. }
  856. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  857. # 5.4 关闭压缩包写入
  858. $zip->close();
  859. @deldir($dir);//删除已生成的文件及目录
  860. //6. 检查文件是否存在,并输出文件
  861. if (!file_exists($file_dir)) echo '压缩包文件不存在';
  862. ob_clean();
  863. flush();
  864. header("Cache-Control: max-age=0");
  865. header("Content-Description: File Transfer");
  866. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  867. header("Content-Type: application/octet-stream"); # 流文件输出
  868. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  869. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  870. // readfile($file_dir);//输出文件
  871. $res = read_big_file($file_dir);
  872. foreach ($res as $val) {
  873. echo $val;
  874. }
  875. @unlink($file_dir);
  876. exit();
  877. }
  878. }
  879. /**
  880. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  881. * datas 生成器
  882. * header array 头部字段
  883. * filename string 文件名
  884. */
  885. if (!function_exists('excelSaveFile')) {
  886. function excelSaveFile($datas, string $filename = '')
  887. {
  888. // $urls = [];
  889. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  890. if (!is_dir($dir)) mkdir($dir, 0777, true);
  891. // foreach ($datas as $item) {
  892. PHPExcel_Settings::setCacheStorageMethod();
  893. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  894. $objPHPExcel = new PHPExcel();
  895. $keyA = 0; // 设置表头
  896. $column = 2;
  897. $objActSheet = $objPHPExcel->getActiveSheet();
  898. foreach ($datas as $key => $rows) { // 行写入
  899. //第一行取key作表头
  900. if($key==0){
  901. $objPHPExcel->getProperties();
  902. foreach ($rows as $k=>$v) {
  903. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  904. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  905. $keyA += 1;
  906. }
  907. }
  908. //写入列
  909. $span = 0;
  910. foreach ($rows as $keyName => $value) {
  911. //判断数据是否有数组,如果有数组,转换成字符串
  912. if (is_array($value)) $value = implode("、", $value);
  913. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  914. $span++;
  915. }
  916. $column++;
  917. }
  918. $file = $filename . ".xls";
  919. $objPHPExcel->setActiveSheetIndex(0);
  920. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  921. $objWriter->save($dir . $file); // 文件通过浏览器下载
  922. $url = $dir . $file;
  923. if (!file_exists($url)) throw new Exception('文件生成失败');
  924. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  925. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  926. $file_dir = $saveDir . $filename . ".zip";
  927. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  928. $zip = new \ZipArchive ();
  929. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  930. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  931. # 5.3 批量写入压缩包
  932. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  933. // foreach ($urls as $fileName) {
  934. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  935. // }
  936. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  937. # 5.4 关闭压缩包写入
  938. $zip->close();
  939. @deldir($dir);//删除已生成的文件及目录
  940. //6. 检查文件是否存在,并输出文件
  941. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  942. // return $file_dir;
  943. return str_replace(root_path() . "public/", '', $file_dir);
  944. }
  945. }
  946. //通过快递网的api获取物流信息
  947. if (!function_exists('get_logistics_information')) {
  948. function get_logistics_information(string $post_code = '', string $phone = '')
  949. {
  950. if ($post_code == '') throw new Exception('快递单号不能为空');
  951. $signer = new \app\admin\common\HuaweiSigner();
  952. //设置相关参数
  953. $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
  954. $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
  955. $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
  956. $req->headers = array(
  957. 'content-type' => 'application/json',
  958. 'x-stage' => 'RELEASE',
  959. );
  960. $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
  961. $curl = $signer->Sign($req);
  962. $response = curl_exec($curl);
  963. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  964. $curl_error = curl_error($curl);
  965. curl_close($curl);
  966. if ($status == 200) return json_decode($response, true);
  967. else throw new Exception('请求失败:' . $curl_error);
  968. }
  969. }
  970. //获取三级架构
  971. if (!function_exists('get_top_customer_org')) {
  972. function get_top_customer_org($var, $data = [])
  973. {
  974. $str = Db::name('customer_org1')
  975. ->field('id,name,pid,level')
  976. ->where(['id' => $var])
  977. ->find();
  978. if ($str == false) {
  979. return [];
  980. }
  981. $vmn = [];
  982. $vmn['id'] = $str['id'];
  983. $vmn['name'] = $str['name'];
  984. $vmn['level'] = $str['level'];
  985. array_unshift($data, $vmn);
  986. // $var['id']=made();
  987. if ($str['pid'] == 0) {
  988. // krsort($data);
  989. return $data;
  990. } else {
  991. return get_top_customer_org($str['pid'], $data);
  992. }
  993. }
  994. }
  995. //根据某个关键字匹配所有子级部门及用户
  996. /**
  997. * $company_name string 部门名称
  998. * $off bool 是否查询离职人员,默认不查询
  999. */
  1000. if (!function_exists('get_company_item_user_by_name')) {
  1001. function get_company_item_user_by_name(string $company_name = '', bool $off = false)
  1002. {
  1003. $data = [];
  1004. //查询符合条件的部门id
  1005. $company_ids = Db::name("company_item")
  1006. ->field('id,level')
  1007. ->where(['is_del' => 0])
  1008. ->whereLike('name', '%' . $company_name . '%')
  1009. ->select()
  1010. ->toArray();
  1011. if (!empty($company_ids)) {
  1012. $level_temp = $company_ids[0]['level'] + 1;
  1013. $company_ids = array_column($company_ids, 'id');
  1014. for ($level = $level_temp; $level > 0; $level++) {
  1015. if (!empty($company_ids)) {
  1016. //根据部门id找人
  1017. $uids = Db::name('depart_user')
  1018. ->where(['is_del' => 0])
  1019. ->order('uid')
  1020. ->whereIn('itemid', $company_ids);
  1021. if (!$off) $uids->where('status', 1);
  1022. $uids = $uids->column('uid');
  1023. $data = array_unique(array_merge($data, $uids));
  1024. $company_ids = Db::name("company_item")
  1025. ->where(['is_del' => 0, 'level' => $level])
  1026. ->whereIn('pid', $company_ids)
  1027. ->column('id');
  1028. } else break;
  1029. }
  1030. }
  1031. return $data;
  1032. }
  1033. }
  1034. //获取某个用户所属部门名称
  1035. //$uid int 用户id
  1036. //$cache bool 是否启用缓存,(默认启用,不启用的话直接从数据库查)
  1037. //$get_tops 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,1获取,2不获取(默认)
  1038. if (!function_exists('get_company_name_by_uid')) {
  1039. function get_company_name_by_uid($uid = 0, bool $cache = true, $get_tops = 2)
  1040. {
  1041. $userCommon = new \app\admin\common\User();
  1042. $rs = $userCommon->handle('get_company_name_by_uid',['uid'=>$uid,'get_tops'=>$get_tops]);
  1043. //为了兼容旧的数据格式
  1044. if(is_array($uid)) return $rs['data'];
  1045. else return $rs['data'][$uid];
  1046. // $rs = '';
  1047. // $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
  1048. //
  1049. // if ($cache) $rs = \think\facade\Cache::get($key);
  1050. //
  1051. // if (empty($rs)) {
  1052. //
  1053. // $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
  1054. //
  1055. // if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
  1056. // else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
  1057. //
  1058. // \think\facade\Cache::set($key, $rs, 3600);
  1059. // }
  1060. //
  1061. // return $rs;
  1062. }
  1063. }
  1064. //返回json格式的响应信息,方便中间件记录,目前在abutmenu应用中有用到
  1065. if (!function_exists('json_show')) {
  1066. function json_show(int $code = 0, string $message = '请求成功', array $data = [])
  1067. {
  1068. return json(['code' => $code, 'message' => $message, 'data' => $data]);
  1069. }
  1070. }
  1071. //获取加密后的密码密文
  1072. /**
  1073. * @param $password string 密码明文
  1074. * @param $salt string 盐值(不传的话随机生成一个)
  1075. */
  1076. if (!function_exists('get_encryption_password')) {
  1077. function get_encryption_password(string $password = '',string $salt=''):array
  1078. {
  1079. if($salt=='') $salt = Str::random(mt_rand(10, 30), -1);
  1080. return [
  1081. 'password' => md5($salt . $password . $salt . $salt),
  1082. 'salt' => $salt
  1083. ];
  1084. }
  1085. }
  1086. //检查供应商是否有开通账号
  1087. if (!function_exists('checkHasAccountBySupplierNos')) {
  1088. function checkHasAccountBySupplierNos(array $supplierNo = []): array
  1089. {
  1090. return \app\abutment\model\SupplierRelationUser::where('is_del', \app\abutment\model\SupplierUser::$is_del_normal)
  1091. ->whereIn('supplierNo', $supplierNo)
  1092. ->where('status', \app\abutment\model\SupplierUser::$status_normal)
  1093. ->column('uid','supplierNo');
  1094. }
  1095. }
  1096. //获取当前用户可查看的其他用户id(新版的)
  1097. if (!function_exists('get_group_share_uid')) {
  1098. function get_group_share_uid(int $uid = 0)
  1099. {
  1100. //原始数据
  1101. $data = [DataGroupModel::$type_可编辑 => [$uid], DataGroupModel::$type_只读 => [$uid], DataGroupModel::$type_不共享 => []];
  1102. //用户组
  1103. $group = Db::name('data_group_userid')
  1104. ->alias('a')
  1105. ->leftJoin('data_group b', 'b.id=a.data_group_id')
  1106. ->where([
  1107. 'a.is_del' => DataGroupModel::$delete_正常,
  1108. 'a.status' => DataGroupModel::$status_启用,
  1109. 'a.uid' => $uid,
  1110. 'b.is_del' => DataGroupModel::$delete_正常,
  1111. 'b.status' => DataGroupModel::$status_启用,
  1112. ])->order('a.data_group_id')
  1113. ->column('b.type', 'a.data_group_id');
  1114. $group_user = Db::name('data_group_userid')
  1115. ->where([
  1116. 'is_del' => DataGroupModel::$delete_正常,
  1117. 'status' => DataGroupModel::$status_启用,
  1118. ])->whereIn('data_group_id', array_keys($group))
  1119. ->field('id,data_group_id,uid')
  1120. ->order('uid')
  1121. ->cursor();
  1122. foreach ($group_user as $g_u) {
  1123. $data[$group[$g_u['data_group_id']]][] = $g_u['uid'];
  1124. }
  1125. //当前请求的接口地址
  1126. $api = app('http')->getName() . '/' . request()->pathinfo();
  1127. $menu_id = Db::name('admin_menu')
  1128. ->where(['is_del' => 0, 'menu_api' => $api])
  1129. ->value('id', 0);
  1130. if ($menu_id) {
  1131. //共享规则
  1132. $share = Db::name('data_share')
  1133. ->field('id,type,source_uid,source_data_group_id')
  1134. ->where([
  1135. 'is_del' => DataShareModel::$delete_正常,
  1136. 'status' => DataShareModel::$status_启用,
  1137. ])
  1138. ->whereFindInSet('menu_ids', $menu_id)
  1139. ->where(function ($query) use ($uid, $group) {
  1140. return $query->where('uid', $uid)->whereOr('data_group_id', 'in', array_keys($group));
  1141. })
  1142. ->cursor();
  1143. foreach ($share as $s) {
  1144. $source_group_uid = Db::name('data_group_userid')
  1145. ->where([
  1146. 'is_del' => DataGroupModel::$delete_正常,
  1147. 'status' => DataGroupModel::$status_启用,
  1148. 'data_group_id' => $s['source_data_group_id'],
  1149. ])->order('uid')->column('uid');
  1150. //$s['source_uid'] ? [$s['source_uid']] : [] 排除默认值0
  1151. $data[$s['type']] = array_merge($data[$s['type']], $s['source_uid'] ? [$s['source_uid']] : [], $source_group_uid);
  1152. }
  1153. }
  1154. //离职交接权限
  1155. // $resign_uid = Db::name("resign_info")
  1156. // ->where([["hand_uid", "=", $uid], ["is_del", "=", 0], ['status', "=", 4]])
  1157. // ->order('resign_uid')
  1158. // ->column('resign_uid');
  1159. // if (!empty($resign_uid)) $data[DataGroupModel::$type_可编辑] = array_merge($data[DataGroupModel::$type_可编辑], $resign_uid);
  1160. unset($data[DataGroupModel::$type_不共享]);
  1161. $data[DataGroupModel::$type_全部] = array_merge($data[DataGroupModel::$type_可编辑], $data[DataGroupModel::$type_只读]);
  1162. sort($data[DataGroupModel::$type_全部]);
  1163. $data[DataGroupModel::$type_全部] = array_unique($data[DataGroupModel::$type_全部]);
  1164. return $data;
  1165. }
  1166. }
  1167. //获取当前操作人(待办列表)
  1168. if (!function_exists('get_handle_user_list')) {
  1169. //$action_process_id 节点id
  1170. //$holder_id 所有人uid
  1171. //$api_url 接口路径,匹配菜单使用
  1172. //$person_id 供应商负责人(供应商端)
  1173. function get_handle_user_list(int $action_process_id = 0, int $holder_id = 0, string $api_url = '',int $person_id=0)
  1174. {
  1175. //筛选符合流程权限的角色id集合
  1176. $roleids = Db::name('role_process')
  1177. ->where('is_del', 0)
  1178. ->where('role_id', '<>', 1)//排除超级管理员
  1179. ->whereFindInSet('action_data', $action_process_id)
  1180. ->field('role_id')
  1181. ->buildSql();
  1182. //根据角色id筛选用户id
  1183. $data = Db::name('user_role')
  1184. ->where(['is_del' => 0, 'status' => 1])
  1185. ->where('roleid IN ' . $roleids)
  1186. ->column('uid');
  1187. //根据菜单筛选符合条件的共享数据
  1188. $tmp = getUserIdsByShare($api_url,$holder_id);
  1189. $res = array_intersect($tmp, $data);//流程权限和数据权限取交集
  1190. //如果本人有流程权限的话,加入到数组中
  1191. if (in_array($holder_id, $data)) $res[] = $holder_id;
  1192. if ($person_id) $res[] = $person_id;
  1193. sort($res);
  1194. $res = array_unique($res);
  1195. return $res;
  1196. }
  1197. }
  1198. //根据数据权限,筛选符合条件的用户(旧版)
  1199. if (!function_exists('getUserIdsByShare')) {
  1200. function getUserIdsByShare(string $api_url = '', int $holder_id = 0)
  1201. {
  1202. //当前请求的接口地址
  1203. if ($api_url == '') $api_url = app('http')->getName() . '/' . request()->pathinfo();
  1204. $menu_id = Db::name('admin_menu')
  1205. ->where(['is_del' => 0, 'menu_api' => $api_url])
  1206. ->value('id', 0);
  1207. $tmp = [];
  1208. if ($menu_id) {
  1209. //共享规则
  1210. $share = Db::name('role_share')
  1211. ->field('id,to_user,to_group')
  1212. ->where([
  1213. 'share_user' => $holder_id,
  1214. 'is_del' => 0,
  1215. 'status' => 1,
  1216. ])
  1217. ->whereFindInSet('action_collect', $menu_id)
  1218. ->cursor();
  1219. foreach ($share as $s) {
  1220. if ($s['to_user']) $tmp[] = $s['to_user'];
  1221. elseif ($s['to_group']) {
  1222. $group_user = Db::name('role_group')
  1223. ->where([
  1224. 'id' => $s['to_group'],
  1225. 'is_del' => 0,
  1226. 'status' => 1,
  1227. ])->value('group_user');
  1228. $tmp = array_merge($tmp, explode(',', $group_user));
  1229. }
  1230. }
  1231. }
  1232. return $tmp;
  1233. }
  1234. }
  1235. //采购单未操作确认或入库时判断销售单是否存在正进行中的退货
  1236. if(!function_exists("cgd_sale_return")){
  1237. /**
  1238. * @param $cgdNo
  1239. * @return bool
  1240. * @throws \think\db\exception\DataNotFoundException
  1241. * @throws \think\db\exception\DbException
  1242. * @throws \think\db\exception\ModelNotFoundException
  1243. */
  1244. function cgd_sale_return($cgdNo){
  1245. $order =Db::name("order_num")->alias("a")
  1246. ->leftJoin("sale_return b","a.orderCode=b.orderCode and b.is_del=0")
  1247. ->where(["a.cgdNo"=>$cgdNo])
  1248. ->whereIn("b.status",[1,2,3,7])
  1249. ->findOrEmpty();
  1250. return !empty($order);
  1251. }
  1252. }
  1253. //采购单未操作确认或入库时判断销售单是否存在正进行中的退货
  1254. if(!function_exists("resign_hand_user")){
  1255. /**
  1256. * @param $uid
  1257. * @param int $ty 1 返回字符串 0 返回数组
  1258. * @return array|string
  1259. */
  1260. function resign_hand_user($uid,$ty=1){
  1261. $uid_arr=[$uid];
  1262. $resign_uids =Db::name("resign_info")->where([["hand_uid","=",$uid],["is_del","=",0],["status","=",4]])
  1263. ->column("resign_uid");
  1264. $uid_arr =array_filter(array_merge($uid_arr,$resign_uids));
  1265. return $ty==1? "(".implode(",",$uid_arr).")":$uid_arr;
  1266. }
  1267. }
  1268. //检查是否有符合条件的活动
  1269. //@param $spuCode string 商品成本编号
  1270. //@param $skuCode string 商品上线编号
  1271. //@param $platform_id int 上线平台id
  1272. //@param $is_stock int 是否库存品
  1273. //@param $price float 售价
  1274. //@param $good_num int 商品数量
  1275. if (!function_exists('check_activity')) {
  1276. function check_activity(string $spuCode = '', string $skuCode = '', int $platform_id = 0, int $is_stock = 0, float $price = 0.00, int $good_num = 0)
  1277. {
  1278. $act = Db::name('activity_info')
  1279. ->alias('ai')
  1280. ->field('ai.id,ai.activity_code,ai.activity_stock,ai.moq_num,ai.activity_price,ai.is_activity,ai.settle_price')
  1281. ->join('good_activity ga', 'ga.activity_code=ai.activity_code')
  1282. ->where([
  1283. // 'ai.spuCode' => $spuCode,
  1284. 'ai.skuCode' => $skuCode,
  1285. 'ai.is_del' => 0,
  1286. 'ai.status' => 1,
  1287. 'ga.status' => 6,
  1288. 'ga.is_del' => 0,
  1289. 'ga.platform_code' => $platform_id,
  1290. 'ga.is_stock' => $is_stock
  1291. ])
  1292. ->where(function ($query) {
  1293. return $query->where('ga.start', '<=', date('Y-m-d H:i:s'))->where('ga.end', '>=', date('Y-m-d H:i:s'));
  1294. })
  1295. ->findOrEmpty();
  1296. if (empty($act)) return $act;//没有符合条件的活动
  1297. else {
  1298. if ($act['moq_num'] > $good_num) return [];//throw new \think\Exception('商品不满足活动价起订量' . $act['moq_num']);,不走活动
  1299. if ($act['activity_stock'] < $good_num) return [];//throw new \think\Exception('商品活动库存剩余' . $act['activity_stock']);
  1300. if ($price < $act['activity_price']) throw new \think\Exception('售价低于活动价' . $act['activity_price']);
  1301. $merge= $act['is_activity'] == 0 ? ['final_price' => $act['activity_price']] : ['final_price' => $act['settle_price']];
  1302. return array_merge($act,$merge);
  1303. }
  1304. }
  1305. }
  1306. //是否使用券后金额 txx活动 用户领券兑换商品 商品转单时注意价格置换为售价
  1307. if(!function_exists('is_discount')){
  1308. /**
  1309. * @param array $order_promotion
  1310. * @return bool
  1311. */
  1312. function is_discount($coupon=[]){
  1313. $bol=false;
  1314. if(!empty($coupon)){
  1315. $title=implode("|",array_unique(array_column($coupon,"promotion_title")));
  1316. $str = stristr($title,"泰直播");
  1317. if($str!=false) $bol=true;
  1318. }
  1319. return $bol;
  1320. }
  1321. }
  1322. if(!function_exists('makeMenu')){
  1323. function makeMenu($row, &$list)
  1324. {
  1325. $list[$row['id']] = $row;
  1326. if ($row['pid'] == 0) {
  1327. return $list;
  1328. }
  1329. $parent = Db::name("admin_menu")
  1330. ->where(["id" => $row['pid'], "status" => 1, "is_del" => 0])
  1331. ->field("id,menu_name,menu_img,menu_url,menu_route,pid,is_show,is_private,menu_type,weight")
  1332. ->findOrEmpty();
  1333. if ($parent == false) return $list;
  1334. makeMenu($parent, $list);
  1335. }
  1336. }
  1337. if (!function_exists('MenuTree')) {
  1338. function MenuTree(&$menuArr, $pid = 0)
  1339. {
  1340. $meun = [];
  1341. foreach ($menuArr as $value) {
  1342. if ($value['pid'] == $pid) {
  1343. if ($value['menu_type'] == 1) $value['child'] = MenuTree($menuArr, $value['id']);
  1344. $meun[] = $value;
  1345. }
  1346. }
  1347. return $meun;
  1348. }
  1349. ;
  1350. }
  1351. if(!function_exists('menuAction')){
  1352. function menuAction($row,&$list=[]){
  1353. $temp=[];
  1354. foreach ($row as $key=>$value){
  1355. if($value['pid']==0){
  1356. $list[]=$value;
  1357. }else{
  1358. $menu=Db::name("admin_menu")
  1359. ->where(["id"=>$value['pid'],"is_del"=>0,"status"=>1])
  1360. ->field("id,menu_name,menu_img,menu_route,menu_url,pid,level,is_show,is_private,menu_type,status")
  1361. ->findOrEmpty();
  1362. if(empty($menu)) continue;
  1363. if(!isset($temp[$value['pid']]))$temp[$value['pid']]=$menu;
  1364. $temp[$value['pid']]['child'][]=$value;
  1365. }
  1366. }
  1367. // $list=$temp;
  1368. if (!empty($temp)){
  1369. menuAction($temp,$list);
  1370. }
  1371. }
  1372. }
  1373. //获取汇总表中的编码和名称
  1374. if (!function_exists('get_headquarters_code_and_name')) {
  1375. function get_headquarters_code_and_name(array $code = []): array
  1376. {
  1377. $userCommon = new \app\admin\common\User();
  1378. $res = $userCommon->handle('getCodeAndName', ['code' => $code]);
  1379. return $res['data'];
  1380. }
  1381. }