common.php 49 KB

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