common.php 55 KB

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