common.php 55 KB

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