common.php 56 KB

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