common.php 49 KB

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