common.php 56 KB

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