common.php 54 KB

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