common.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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. if($AddrJson==""){
  657. return '';
  658. }
  659. $adr = json_decode($AddrJson,true);
  660. if(!is_array($adr)){
  661. return '';
  662. }
  663. $addr='';
  664. if(isset($adr['provice_code'])&&$adr['provice_code']!=''){
  665. $provice = Db::name("province")->where(["province_code"=>$adr['provice_code']])->find();
  666. $addr.=isset($provice['name']) ? $provice['name']:"";
  667. }
  668. if(isset($adr['city_code'])&&$adr['city_code']!=''){
  669. $city = Db::name("city")->where(["city_code"=>$adr['city_code']])->find();
  670. $addr.=isset($city['name']) ? $city['name']:"";
  671. }
  672. if(isset($adr['area_code'])&&$adr['area_code']!=''){
  673. $area = Db::name("area")->where(["area_code"=>$adr['area_code']])->find();
  674. $addr.=isset($area['name']) ? $area['name']:"";
  675. }
  676. return $addr;
  677. }
  678. /**
  679. * POST 请求
  680. * @param string $url
  681. * @param array $param
  682. * @param boolean $post_file 是否文件上传
  683. * @return string content
  684. */
  685. function post($url,$data,$header=[])
  686. {
  687. //对空格进行转义
  688. $url = str_replace(' ','+',$url);
  689. $ch = curl_init();
  690. //设置选项,包括URL
  691. curl_setopt($ch, CURLOPT_URL, "$url");
  692. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  693. curl_setopt($ch, CURLOPT_HEADER, 0);
  694. curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
  695. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  696. // POST数据
  697. // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  698. curl_setopt($ch, CURLOPT_POST, 1);
  699. // 把post的变量加上
  700. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  701. curl_setopt($ch, CURLOPT_HEADER, true);
  702. //执行并获取url地址的内容
  703. $output = curl_exec($ch);
  704. $errorCode = curl_errno($ch);
  705. //释放curl句柄
  706. $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  707. // 根据头大小去获取头信息内容
  708. $header = substr($output, 0, $headerSize);
  709. curl_close($ch);
  710. if(0 !== $errorCode) {
  711. return false;
  712. }
  713. return $header;
  714. }
  715. function post2($url,$data,$header=[])
  716. {
  717. //对空格进行转义
  718. $url = str_replace(' ','+',$url);
  719. $ch = curl_init();
  720. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  721. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  722. //设置选项,包括URL
  723. curl_setopt($ch, CURLOPT_URL, "$url");
  724. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  725. curl_setopt($ch, CURLOPT_HEADER, 0);
  726. // POST数据
  727. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  728. curl_setopt($ch, CURLOPT_POST, 1);
  729. // 把post的变量加上
  730. curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
  731. $output = curl_exec($ch);
  732. $errorCode = curl_errno($ch);
  733. curl_close($ch);
  734. if(0 !== $errorCode) {
  735. return false;
  736. }
  737. return $output;
  738. }
  739. function GoldPrice($data,$cost_rate=0){
  740. $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
  741. ->find();
  742. // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
  743. // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
  744. $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
  745. $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
  746. return $saleprice;
  747. }
  748. function GoodPrice($data,$cost_rate=0){
  749. $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
  750. );
  751. return $rate;
  752. }
  753. function checkRole($roleid,$menu){
  754. $roleinfo = Db::name("role_action")->where([['role_id',"=",$roleid],["status","=",1]])->find();
  755. if($roleinfo['private_data']!=""){
  756. $private = explode(",",$roleinfo['private_data']);
  757. if(in_array($menu,$private)){
  758. return true;
  759. }
  760. }
  761. return false;
  762. }
  763. /**
  764. * 根据地址解析省市区
  765. * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
  766. */
  767. if (!function_exists('get_address')) {
  768. function get_address(string $address = '')
  769. {
  770. preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
  771. if (count($matches) > 1) {
  772. $province = $matches[count($matches) - 2];
  773. $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
  774. }
  775. preg_match('/(.*?(市|自治州|地区|区划|县|盟))/', $address, $matches);
  776. if (count($matches) > 1) {
  777. $city = $matches[count($matches) - 2];
  778. $address = str_replace($city, '', $address);
  779. }
  780. preg_match('/(.*?(区|县|镇|乡|街道|旗|市))/', $address, $matches);
  781. if (count($matches) > 1) {
  782. $area = $matches[count($matches) - 2];
  783. $address = str_replace($area, '', $address);
  784. }
  785. return [
  786. 'province' => isset($province) ? $province : '',
  787. 'city' => isset($city) ? $city : '',
  788. 'district' => isset($area) ? $area : '',
  789. "address" => $address
  790. ];
  791. }
  792. }
  793. /**
  794. * 批量生成多个文件excel,生成压缩包
  795. */
  796. if (!function_exists('excelSaveBatch')) {
  797. function excelSaveBatch(array $datas = [])
  798. {
  799. $urls = [];
  800. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  801. if (!is_dir($dir)) {
  802. mkdir($dir, 0777, true);
  803. }
  804. foreach ($datas as $item) {
  805. $objPHPExcel = new PHPExcel();
  806. $objPHPExcel->getProperties();
  807. $keyA = 0; // 设置表头
  808. foreach ($item['head'] as $v) {
  809. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  810. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
  811. $keyA += 1;
  812. }
  813. $column = 2;
  814. $objActSheet = $objPHPExcel->getActiveSheet();
  815. foreach ($item['list'] as $key => $rows) { // 行写入
  816. $span = 0;
  817. foreach ($rows as $keyName => $value) { // 列写入
  818. //判断数据是否有数组,如果有数组,转换成字符串
  819. if (is_array($value)) {
  820. $value = implode("、", $value);
  821. }
  822. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  823. $span++;
  824. }
  825. $column++;
  826. }
  827. // var_dump($objActSheet->getActiveCell());
  828. $file = $item['filename'] . ".xls";
  829. //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
  830. //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
  831. $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
  832. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  833. $objWriter->save($dir . $file); // 文件通过浏览器下载
  834. $url = $dir . $file;
  835. if (!file_exists($url)) {
  836. echo "文件生成失败";
  837. } else {
  838. $urls[] = $url;
  839. }
  840. }
  841. $saveDir = root_path() . "public/storage/zip/";
  842. if (!is_dir($saveDir)) {
  843. mkdir($saveDir, 0777, true);
  844. }
  845. $datetime = date("YmdHis");
  846. $file_dir = $saveDir . $datetime . ".zip";
  847. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  848. $zip = new \ZipArchive ();
  849. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  850. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  851. # 5.3 批量写入压缩包
  852. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  853. foreach ($urls as $fileName) {
  854. // @$zip->addFile($fileName);
  855. @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
  856. }
  857. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  858. # 5.4 关闭压缩包写入
  859. $zip->close();
  860. @deldir($dir);//删除已生成的文件及目录
  861. //6. 检查文件是否存在,并输出文件
  862. if (!file_exists($file_dir)) echo '压缩包文件不存在';
  863. ob_clean();
  864. flush();
  865. header("Cache-Control: max-age=0");
  866. header("Content-Description: File Transfer");
  867. header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
  868. header("Content-Type: application/octet-stream"); # 流文件输出
  869. header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
  870. // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
  871. // readfile($file_dir);//输出文件
  872. $res = read_big_file($file_dir);
  873. foreach ($res as $val) {
  874. echo $val;
  875. }
  876. @unlink($file_dir);
  877. exit();
  878. }
  879. }
  880. /**
  881. * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
  882. * datas 生成器
  883. * header array 头部字段
  884. * filename string 文件名
  885. */
  886. if (!function_exists('excelSaveFile')) {
  887. function excelSaveFile($datas, string $filename = '')
  888. {
  889. // $urls = [];
  890. $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
  891. if (!is_dir($dir)) mkdir($dir, 0777, true);
  892. // foreach ($datas as $item) {
  893. PHPExcel_Settings::setCacheStorageMethod();
  894. PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
  895. $objPHPExcel = new PHPExcel();
  896. $keyA = 0; // 设置表头
  897. $column = 2;
  898. $objActSheet = $objPHPExcel->getActiveSheet();
  899. foreach ($datas as $key => $rows) { // 行写入
  900. //第一行取key作表头
  901. if($key==0){
  902. $objPHPExcel->getProperties();
  903. foreach ($rows as $k=>$v) {
  904. $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
  905. $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
  906. $keyA += 1;
  907. }
  908. }
  909. //写入列
  910. $span = 0;
  911. foreach ($rows as $keyName => $value) {
  912. //判断数据是否有数组,如果有数组,转换成字符串
  913. if (is_array($value)) $value = implode("、", $value);
  914. $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
  915. $span++;
  916. }
  917. $column++;
  918. }
  919. $file = $filename . ".xls";
  920. $objPHPExcel->setActiveSheetIndex(0);
  921. $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  922. $objWriter->save($dir . $file); // 文件通过浏览器下载
  923. $url = $dir . $file;
  924. if (!file_exists($url)) throw new Exception('文件生成失败');
  925. $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
  926. if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
  927. $file_dir = $saveDir . $filename . ".zip";
  928. # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
  929. $zip = new \ZipArchive ();
  930. # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
  931. if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
  932. # 5.3 批量写入压缩包
  933. // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
  934. // foreach ($urls as $fileName) {
  935. @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
  936. // }
  937. // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
  938. # 5.4 关闭压缩包写入
  939. $zip->close();
  940. @deldir($dir);//删除已生成的文件及目录
  941. //6. 检查文件是否存在,并输出文件
  942. if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
  943. // return $file_dir;
  944. return str_replace(root_path() . "public/", '', $file_dir);
  945. }
  946. }
  947. //通过快递网的api获取物流信息
  948. if (!function_exists('get_logistics_information')) {
  949. function get_logistics_information(string $post_code = '', string $phone = '')
  950. {
  951. if ($post_code == '') throw new Exception('快递单号不能为空');
  952. $signer = new \app\admin\common\HuaweiSigner();
  953. //设置相关参数
  954. $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
  955. $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
  956. $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
  957. $req->headers = array(
  958. 'content-type' => 'application/json',
  959. 'x-stage' => 'RELEASE',
  960. );
  961. $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
  962. $curl = $signer->Sign($req);
  963. $response = curl_exec($curl);
  964. $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  965. $curl_error = curl_error($curl);
  966. curl_close($curl);
  967. if ($status == 200) return json_decode($response, true);
  968. else throw new Exception('请求失败:' . $curl_error);
  969. }
  970. }
  971. //获取三级架构
  972. if (!function_exists('get_top_customer_org')) {
  973. function get_top_customer_org($var, $data = [])
  974. {
  975. $str = Db::name('customer_org1')
  976. ->field('id,name,pid,level')
  977. ->where(['id' => $var])
  978. ->find();
  979. if ($str == false) {
  980. return [];
  981. }
  982. $vmn = [];
  983. $vmn['id'] = $str['id'];
  984. $vmn['name'] = $str['name'];
  985. $vmn['level'] = $str['level'];
  986. array_unshift($data, $vmn);
  987. // $var['id']=made();
  988. if ($str['pid'] == 0) {
  989. // krsort($data);
  990. return $data;
  991. } else {
  992. return get_top_customer_org($str['pid'], $data);
  993. }
  994. }
  995. }
  996. //根据某个关键字匹配所有子级部门及用户
  997. if (!function_exists('get_company_item_user_by_name')) {
  998. function get_company_item_user_by_name(string $company_name = '')
  999. {
  1000. $userCommon = new \app\admin\common\User();
  1001. $rs = $userCommon->handle('get_company_item_user_by_name', ['company_name' => $company_name]);
  1002. return $rs['data'] ?? [];
  1003. // $data = [];
  1004. //
  1005. // //查询符合条件的部门id
  1006. // $company_ids = Db::name("company_item")
  1007. // ->field('id,level')
  1008. // ->where(['is_del' => 0])
  1009. // ->whereLike('name', '%' . $company_name . '%')
  1010. // ->select()
  1011. // ->toArray();
  1012. //
  1013. // if (!empty($company_ids)) {
  1014. // $level_temp = $company_ids[0]['level'] + 1;
  1015. // $company_ids = array_column($company_ids, 'id');
  1016. // for ($level = $level_temp; $level > 0; $level++) {
  1017. //
  1018. // if (!empty($company_ids)) {
  1019. // //根据部门id找人
  1020. // $uids = Db::name('depart_user')
  1021. // ->where(['is_del' => 0])
  1022. // ->order('uid')
  1023. // ->whereIn('itemid', $company_ids);
  1024. // if (!$off) $uids->where('status', 1);
  1025. // $uids = $uids->column('uid');
  1026. // $data = array_unique(array_merge($data, $uids));
  1027. //
  1028. // $company_ids = Db::name("company_item")
  1029. // ->where(['is_del' => 0, 'level' => $level])
  1030. // ->whereIn('pid', $company_ids)
  1031. // ->column('id');
  1032. // } else break;
  1033. //
  1034. // }
  1035. //
  1036. // }
  1037. // return $data;
  1038. }
  1039. }
  1040. //获取某个用户所属部门名称
  1041. //$uid int 用户id
  1042. //$get_tops 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,1获取,2不获取(默认)
  1043. if (!function_exists('get_company_name_by_uid')) {
  1044. function get_company_name_by_uid($uid = '', $get_tops = 2)
  1045. {
  1046. $userCommon = new \app\admin\common\User();
  1047. $rs = $userCommon->handle('get_company_name_by_uid',['uid'=>$uid,'get_tops'=>$get_tops]);
  1048. //为了兼容旧的数据格式
  1049. if(is_array($uid)) return $rs['data'];
  1050. else return $rs['data'][$uid];
  1051. // $rs = '';
  1052. // $key = 'get_company_name_by_uid_' . $uid.'_'.$get_tops;
  1053. //
  1054. // if ($cache) $rs = \think\facade\Cache::get($key);
  1055. //
  1056. // if (empty($rs)) {
  1057. //
  1058. // $itemid = Db::name('depart_user')->where(['is_del' => 0, 'uid' => $uid])->value('itemid', 0);
  1059. //
  1060. // if ($get_tops) $rs = implode('/', array_column(GetPart($itemid), 'name'));
  1061. // else $rs = Db::name('company_item')->where(['is_del' => 0, 'id' => $itemid])->value('name');
  1062. //
  1063. // \think\facade\Cache::set($key, $rs, 3600);
  1064. // }
  1065. //
  1066. // return $rs;
  1067. }
  1068. }
  1069. //返回json格式的响应信息,方便中间件记录,目前在abutmenu应用中有用到
  1070. if (!function_exists('json_show')) {
  1071. function json_show(int $code = 0, string $message = '请求成功', array $data = [])
  1072. {
  1073. return json(['code' => $code, 'message' => $message, 'data' => $data]);
  1074. }
  1075. }
  1076. //获取加密后的密码密文
  1077. /**
  1078. * @param $password string 密码明文
  1079. * @param $salt string 盐值(不传的话随机生成一个)
  1080. */
  1081. if (!function_exists('get_encryption_password')) {
  1082. function get_encryption_password(string $password = '',string $salt=''):array
  1083. {
  1084. if($salt=='') $salt = Str::random(mt_rand(10, 30), -1);
  1085. return [
  1086. 'password' => md5($salt . $password . $salt . $salt),
  1087. 'salt' => $salt
  1088. ];
  1089. }
  1090. }
  1091. //检查供应商是否有开通账号
  1092. if (!function_exists('checkHasAccountBySupplierNos')) {
  1093. function checkHasAccountBySupplierNos(array $supplierNo = []): array
  1094. {
  1095. return \app\abutment\model\SupplierRelationUser::where('is_del', \app\abutment\model\SupplierUser::$is_del_normal)
  1096. ->whereIn('supplierNo', $supplierNo)
  1097. ->where('status', \app\abutment\model\SupplierUser::$status_normal)
  1098. ->column('uid','supplierNo');
  1099. }
  1100. }
  1101. //获取当前用户可查看的其他用户id(新版的)
  1102. if (!function_exists('get_group_share_uid')) {
  1103. function get_group_share_uid(int $uid = 0)
  1104. {
  1105. //原始数据
  1106. $data = [DataGroupModel::$type_可编辑 => [$uid], DataGroupModel::$type_只读 => [$uid], DataGroupModel::$type_不共享 => []];
  1107. //用户组
  1108. $group = Db::name('data_group_userid')
  1109. ->alias('a')
  1110. ->leftJoin('data_group b', 'b.id=a.data_group_id')
  1111. ->where([
  1112. 'a.is_del' => DataGroupModel::$delete_正常,
  1113. 'a.status' => DataGroupModel::$status_启用,
  1114. 'a.uid' => $uid,
  1115. 'b.is_del' => DataGroupModel::$delete_正常,
  1116. 'b.status' => DataGroupModel::$status_启用,
  1117. ])->order('a.data_group_id')
  1118. ->column('b.type', 'a.data_group_id');
  1119. $group_user = Db::name('data_group_userid')
  1120. ->where([
  1121. 'is_del' => DataGroupModel::$delete_正常,
  1122. 'status' => DataGroupModel::$status_启用,
  1123. ])->whereIn('data_group_id', array_keys($group))
  1124. ->field('id,data_group_id,uid')
  1125. ->order('uid')
  1126. ->cursor();
  1127. foreach ($group_user as $g_u) {
  1128. $data[$group[$g_u['data_group_id']]][] = $g_u['uid'];
  1129. }
  1130. //当前请求的接口地址
  1131. $api = app('http')->getName() . '/' . request()->pathinfo();
  1132. $menu_id = Db::name('admin_menu')
  1133. ->where(['is_del' => 0, 'menu_api' => $api])
  1134. ->value('id', 0);
  1135. if ($menu_id) {
  1136. //共享规则
  1137. $share = Db::name('data_share')
  1138. ->field('id,type,source_uid,source_data_group_id')
  1139. ->where([
  1140. 'is_del' => DataShareModel::$delete_正常,
  1141. 'status' => DataShareModel::$status_启用,
  1142. ])
  1143. ->whereFindInSet('menu_ids', $menu_id)
  1144. ->where(function ($query) use ($uid, $group) {
  1145. return $query->where('uid', $uid)->whereOr('data_group_id', 'in', array_keys($group));
  1146. })
  1147. ->cursor();
  1148. foreach ($share as $s) {
  1149. $source_group_uid = Db::name('data_group_userid')
  1150. ->where([
  1151. 'is_del' => DataGroupModel::$delete_正常,
  1152. 'status' => DataGroupModel::$status_启用,
  1153. 'data_group_id' => $s['source_data_group_id'],
  1154. ])->order('uid')->column('uid');
  1155. //$s['source_uid'] ? [$s['source_uid']] : [] 排除默认值0
  1156. $data[$s['type']] = array_merge($data[$s['type']], $s['source_uid'] ? [$s['source_uid']] : [], $source_group_uid);
  1157. }
  1158. }
  1159. //离职交接权限
  1160. // $resign_uid = Db::name("resign_info")
  1161. // ->where([["hand_uid", "=", $uid], ["is_del", "=", 0], ['status', "=", 4]])
  1162. // ->order('resign_uid')
  1163. // ->column('resign_uid');
  1164. // if (!empty($resign_uid)) $data[DataGroupModel::$type_可编辑] = array_merge($data[DataGroupModel::$type_可编辑], $resign_uid);
  1165. unset($data[DataGroupModel::$type_不共享]);
  1166. $data[DataGroupModel::$type_全部] = array_merge($data[DataGroupModel::$type_可编辑], $data[DataGroupModel::$type_只读]);
  1167. sort($data[DataGroupModel::$type_全部]);
  1168. $data[DataGroupModel::$type_全部] = array_unique($data[DataGroupModel::$type_全部]);
  1169. return $data;
  1170. }
  1171. }
  1172. //获取当前操作人(待办列表)
  1173. if (!function_exists('get_handle_user_list')) {
  1174. //$action_process_id 节点id
  1175. //$holder_id 所有人uid
  1176. //$api_url 接口路径,匹配菜单使用
  1177. //$person_id 供应商负责人(供应商端)
  1178. function get_handle_user_list(int $action_process_id = 0, int $holder_id = 0, string $api_url = '',int $person_id=0)
  1179. {
  1180. //筛选符合流程权限的角色id集合
  1181. $roleids = Db::name('role_process')
  1182. ->where('is_del', 0)
  1183. ->where('role_id', '<>', 1)//排除超级管理员
  1184. ->whereFindInSet('action_data', $action_process_id)
  1185. ->field('role_id')
  1186. ->buildSql();
  1187. //根据角色id筛选用户id
  1188. $data = Db::name('user_role')
  1189. ->where(['is_del' => 0, 'status' => 1])
  1190. ->where('roleid IN ' . $roleids)
  1191. ->column('uid');
  1192. //根据菜单筛选符合条件的共享数据
  1193. $tmp = getUserIdsByShare($api_url,$holder_id);
  1194. $res = array_intersect($tmp, $data);//流程权限和数据权限取交集
  1195. //如果本人有流程权限的话,加入到数组中
  1196. if (in_array($holder_id, $data)) $res[] = $holder_id;
  1197. if ($person_id) $res[] = $person_id;
  1198. sort($res);
  1199. $res = array_unique($res);
  1200. return $res;
  1201. }
  1202. }
  1203. //根据数据权限,筛选符合条件的用户(旧版)
  1204. if (!function_exists('getUserIdsByShare')) {
  1205. function getUserIdsByShare(string $api_url = '', int $holder_id = 0)
  1206. {
  1207. //当前请求的接口地址
  1208. if ($api_url == '') $api_url = app('http')->getName() . '/' . request()->pathinfo();
  1209. $menu_id = Db::name('admin_menu')
  1210. ->where(['is_del' => 0, 'menu_api' => $api_url])
  1211. ->value('id', 0);
  1212. $tmp = [];
  1213. if ($menu_id) {
  1214. //共享规则
  1215. $share = Db::name('role_share')
  1216. ->field('id,to_user,to_group')
  1217. ->where([
  1218. 'share_user' => $holder_id,
  1219. 'is_del' => 0,
  1220. 'status' => 1,
  1221. ])
  1222. ->whereFindInSet('action_collect', $menu_id)
  1223. ->cursor();
  1224. foreach ($share as $s) {
  1225. if ($s['to_user']) $tmp[] = $s['to_user'];
  1226. elseif ($s['to_group']) {
  1227. $group_user = Db::name('role_group')
  1228. ->where([
  1229. 'id' => $s['to_group'],
  1230. 'is_del' => 0,
  1231. 'status' => 1,
  1232. ])->value('group_user');
  1233. $tmp = array_merge($tmp, explode(',', $group_user));
  1234. }
  1235. }
  1236. }
  1237. return $tmp;
  1238. }
  1239. }
  1240. //采购单未操作确认或入库时判断销售单是否存在正进行中的退货
  1241. if(!function_exists("cgd_sale_return")){
  1242. /**
  1243. * @param $cgdNo
  1244. * @return bool
  1245. * @throws \think\db\exception\DataNotFoundException
  1246. * @throws \think\db\exception\DbException
  1247. * @throws \think\db\exception\ModelNotFoundException
  1248. */
  1249. function cgd_sale_return($cgdNo){
  1250. $order =Db::name("order_num")->alias("a")
  1251. ->leftJoin("sale_return b","a.orderCode=b.orderCode and b.is_del=0")
  1252. ->where(["a.cgdNo"=>$cgdNo])
  1253. ->whereIn("b.status",[1,2,3,7])
  1254. ->findOrEmpty();
  1255. return !empty($order);
  1256. }
  1257. }
  1258. //采购单未操作确认或入库时判断销售单是否存在正进行中的退货
  1259. if(!function_exists("resign_hand_user")){
  1260. /**
  1261. * @param $uid
  1262. * @param int $ty 1 返回字符串 0 返回数组
  1263. * @return array|string
  1264. */
  1265. function resign_hand_user($uid,$ty=1){
  1266. $uid_arr=[$uid];
  1267. $resign_uids =Db::name("resign_info")->where([["hand_uid","=",$uid],["is_del","=",0],["status","=",4]])
  1268. ->column("resign_uid");
  1269. $uid_arr =array_filter(array_merge($uid_arr,$resign_uids));
  1270. return $ty==1? "(".implode(",",$uid_arr).")":$uid_arr;
  1271. }
  1272. }
  1273. //检查是否有符合条件的活动
  1274. //@param $spuCode string 商品成本编号
  1275. //@param $skuCode string 商品上线编号
  1276. //@param $platform_id int 上线平台id
  1277. //@param $is_stock int 是否库存品
  1278. //@param $price float 售价
  1279. //@param $good_num int 商品数量
  1280. if (!function_exists('check_activity')) {
  1281. function check_activity(string $spuCode = '', string $skuCode = '', int $platform_id = 0, int $is_stock = 0, float $price = 0.00, int $good_num = 0)
  1282. {
  1283. $act = Db::name('activity_info')
  1284. ->alias('ai')
  1285. ->field('ai.id,ai.activity_code,ai.activity_stock,ai.moq_num,ai.activity_price,ai.is_activity,ai.settle_price')
  1286. ->join('good_activity ga', 'ga.activity_code=ai.activity_code')
  1287. ->where([
  1288. // 'ai.spuCode' => $spuCode,
  1289. 'ai.skuCode' => $skuCode,
  1290. 'ai.is_del' => 0,
  1291. 'ai.status' => 1,
  1292. 'ga.status' => 6,
  1293. 'ga.is_del' => 0,
  1294. 'ga.platform_code' => $platform_id,
  1295. 'ga.is_stock' => $is_stock
  1296. ])
  1297. ->where(function ($query) {
  1298. return $query->where('ga.start', '<=', date('Y-m-d H:i:s'))->where('ga.end', '>=', date('Y-m-d H:i:s'));
  1299. })
  1300. ->findOrEmpty();
  1301. if (empty($act)) return $act;//没有符合条件的活动
  1302. else {
  1303. if ($act['moq_num'] > $good_num) return [];//throw new \think\Exception('商品不满足活动价起订量' . $act['moq_num']);,不走活动
  1304. if ($act['activity_stock'] < $good_num) return [];//throw new \think\Exception('商品活动库存剩余' . $act['activity_stock']);
  1305. if ($price < $act['activity_price']) throw new \think\Exception('售价低于活动价' . $act['activity_price']);
  1306. $merge= $act['is_activity'] == 0 ? ['final_price' => $act['activity_price']] : ['final_price' => $act['settle_price']];
  1307. return array_merge($act,$merge);
  1308. }
  1309. }
  1310. }
  1311. //是否使用券后金额 txx活动 用户领券兑换商品 商品转单时注意价格置换为售价
  1312. if(!function_exists('is_discount')){
  1313. /**
  1314. * @param array $order_promotion
  1315. * @return bool
  1316. */
  1317. function is_discount($coupon=[]){
  1318. $bol=false;
  1319. if(!empty($coupon)){
  1320. $title=implode("|",array_unique(array_column($coupon,"promotion_title")));
  1321. $str = stristr($title,"泰直播");
  1322. if($str!=false) $bol=true;
  1323. }
  1324. return $bol;
  1325. }
  1326. }
  1327. if(!function_exists('makeMenu')){
  1328. function makeMenu($row, &$list)
  1329. {
  1330. $list[$row['id']] = $row;
  1331. if ($row['pid'] == 0) {
  1332. return $list;
  1333. }
  1334. $parent = Db::name("admin_menu")
  1335. ->where(["id" => $row['pid'], "status" => 1, "is_del" => 0])
  1336. ->field("id,menu_name,menu_img,menu_url,menu_route,pid,is_show,is_private,menu_type,weight")
  1337. ->findOrEmpty();
  1338. if ($parent == false) return $list;
  1339. makeMenu($parent, $list);
  1340. }
  1341. }
  1342. if (!function_exists('MenuTree')) {
  1343. function MenuTree(&$menuArr, $pid = 0)
  1344. {
  1345. $meun = [];
  1346. foreach ($menuArr as $value) {
  1347. if ($value['pid'] == $pid) {
  1348. if ($value['menu_type'] == 1) $value['child'] = MenuTree($menuArr, $value['id']);
  1349. $meun[] = $value;
  1350. }
  1351. }
  1352. return $meun;
  1353. }
  1354. ;
  1355. }
  1356. if(!function_exists('menuAction')){
  1357. function menuAction($row,&$list=[]){
  1358. $temp=[];
  1359. foreach ($row as $key=>$value){
  1360. if($value['pid']==0){
  1361. $list[]=$value;
  1362. }else{
  1363. $menu=Db::name("admin_menu")
  1364. ->where(["id"=>$value['pid'],"is_del"=>0,"status"=>1])
  1365. ->field("id,menu_name,menu_img,menu_route,menu_url,pid,level,is_show,is_private,menu_type,status")
  1366. ->findOrEmpty();
  1367. if(empty($menu)) continue;
  1368. if(!isset($temp[$value['pid']]))$temp[$value['pid']]=$menu;
  1369. $temp[$value['pid']]['child'][]=$value;
  1370. }
  1371. }
  1372. // $list=$temp;
  1373. if (!empty($temp)){
  1374. menuAction($temp,$list);
  1375. }
  1376. }
  1377. }
  1378. //获取汇总表中的编码和名称
  1379. if (!function_exists('get_headquarters_code_and_name')) {
  1380. function get_headquarters_code_and_name(array $code = []): array
  1381. {
  1382. $userCommon = new \app\admin\common\User();
  1383. $res = $userCommon->handle('getCodeAndName', ['code' => $code]);
  1384. return $res['data'];
  1385. }
  1386. }