common.php 50 KB

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