common.php 53 KB

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