common.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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. }