123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710 |
- <?php
- // 应用公共文件
- use app\admin\common\User as CommonUser;
- use think\facade\Config;
- use think\facade\Db;
- use think\facade\Cache;
- use think\facade\Filesystem;
- use think\helper\Str;
- use app\admin\model\DataGroup as DataGroupModel;
- use app\admin\model\DataShare as DataShareModel;
- // 应用公共文件
- function app_show($code=0,$message="",$data=[]){
- $result = ['code'=>$code,"message"=>$message,"data"=>$data];
- echo json_encode($result,JSON_UNESCAPED_UNICODE);
- die();
- }
- // 应用公共文件
- function error_show($code=0,$message=""){
- $result = ['code'=>$code,"message"=>$message];
- echo json_encode($result,JSON_UNESCAPED_UNICODE);
- die();
- }
- function GetUserInfo($token){
- $userCommon = \app\admin\common\User::getIns();
- return $userCommon->handle('verifyToken',['token'=>$token]);
- }
- //参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$cookies
- function curl_request($url,$post=''){
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
- curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- if($post) {
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
- }
- curl_setopt($curl, CURLOPT_TIMEOUT, 10);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- $data = curl_exec($curl);
- if (curl_errno($curl)) {
- return curl_error($curl);
- }
- curl_close($curl);
- return $data;
- }
- /**手机号验证
- * @param $mobile
- * @return bool
- */
- function checkMobile($mobile){
- if (!is_numeric($mobile)) {
- return false;
- }
- return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
- }
- function checkTel($tel){
- if (!$tel) {
- return false;
- }
- return preg_match('/^(0[0-9]{2,3}\-)([0-9]{7,8})+(\-[0-9]{1,4})?$/', $tel) ? true : false;
- }
- /**邮箱验证
- * @param $email
- * @return bool
- */
- function checkEmail($email){
- if (!$email) {
- return false;
- }
- return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $email) ? true : false;
- }
- /**
- * @param
- * @return int
- */
- function makeSalt(){
- $salt = rand(10000000,99999999);
- return $salt;
- }
- /**
- * @param $token
- * @return array
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- * @throws \think\exception\DbException
- */
- function VerifyTokens($token){
- $userCommon = CommonUser::getIns();
- $rs = $userCommon->VerifyTokens(['token'=>$token]);
- return json_decode($rs,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function GetUserlist($token,$condition){
- $userCommon = CommonUser::getIns();
- return json_decode($userCommon->GetUserlist($condition), true);
- }
- if(!function_exists("GetFin")){
- function GetFin($uri,$post){
- $host =env("fin.hosturl");
- $data =curl_request($host.$uri,$post);
- return json_decode($data,true);
- }
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function GetAccountall($token, $condition){
- $userCommon = CommonUser::getIns();
- return json_decode($userCommon->GetAccountall($condition), true);
- }
- function GetList($condition){
- $userCommon = CommonUser::getIns();
- return json_decode($userCommon->GetUserlist($condition), true);
- }
- /**
- * @param $token
- * @param $condition ['id'=>1]
- * @return mixed
- */
- function GetInfoById($token,$condition){
- $userCommon = CommonUser::getIns();
- return json_decode($userCommon->GetUserInfo($condition), true);
- }
- function GetInfoNoToken($condition){
- $userCommon = CommonUser::getIns();
- return json_decode($userCommon->GetUserInfo($condition), true);
- }
- function makeNo($str){
- $date=date("mdHis");
- $year = date("Y")-2000;
- $msec=rand(1000,9999);
- return $str.$year.$date.$msec;
- }
- function randomkeys($length) {
- $returnStr='';
- $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';//ABCDEFGHIJKLOMNOPQRSTUVWXYZ
- for($i = 0; $i < $length; $i ++) {
- $returnStr .= $pattern[mt_rand ( 0, strlen($pattern)-1 )]; //生成php随机数
- }
- return $returnStr;
- }
- function tree(){
- }
- /**
- * @param $files
- * @return array
- */
- function UploadImg($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['imgFile' => [
- 'fileSize' => 2*1024*1024,
- 'fileExt' => 'jpg,jpeg,png,bmp,gif',
- 'fileMime' => 'image/jpeg,image/png,image/gif']
- ])->check(['imgFile' => $files]);
- //文件存放路径
- $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
- $url = 'topic' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
- if (is_dir($root . $url) == false) mkdir($root . $url, 0777, true);
- foreach ($files as $file) {
- //文件名
- $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
- $file->move($root . $url, $file_name);
- $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getError();
- }
- }
- /**
- * @param $files
- * @return array
- */
- function UploadFile($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['imgFile' => ['fileSize' => 5*1024*1024, 'fileExt' => 'xlsx,xls,pdf,zip,rar,7z,doc,docx']])->check
- (['imgFile' => $files]);
- foreach ($files as $file) {
- //文件存放路径
- $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
- $url = 'files' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
- //文件名
- $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
- $file->move($root . $url, $file_name);
- $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getError();
- }
- }
- /**
- * @param $files
- * @return array
- */
- function UploadVideo($files)
- {
- $savename = [];
- $files = !is_array($files) ? [$files] : $files;
- try {
- //验证
- validate(['videoFile' => ['fileSize' => 5*1024*1024, 'fileExt' => 'mp4,mp3,avi']])->check(['videoFile' => $files]);
- foreach ($files as $file) {
- //文件存放路径
- $root = config('filesystem.disks.public.root') . DIRECTORY_SEPARATOR;
- $url = 'video' . DIRECTORY_SEPARATOR . date("Ymd") . DIRECTORY_SEPARATOR;
- //文件名
- $file_name = str_replace('.' . $file->getOriginalExtension(), "_" . date('YmdHis') . '.' . $file->getOriginalExtension(), $file->getOriginalName());
- $file->move($root . $url, $file_name);
- $temp = ["url" => $url . $file_name, "name" => $file->getOriginalName()];
- $savename[] = $temp;
- }
- return $savename;
- } catch (\think\exception\ValidateException $e) {
- return $e->getError();
- }
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetpwd($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/passset";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- function resetpasswd($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/passsave";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetinfo($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/usersave";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $token
- * @param $condition
- * @return mixed
- */
- function resetstatus($token,$condition){
- $host = Config::get("app");
- $url = $host["api_host"]."/Api/userstatus";
- $condition['token']=$token;
- $response=curl_request($url,$condition);
- return json_decode($response,true);
- }
- /**
- * @param $data
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- function crea($data,$vio=0)
- {
- $db = Db::name("company_item")->where(['pid'=>$data['id'],'is_del'=>0])->select()->toArray();
- if($vio==1){
- $d = Db::name("depart_user")->where(['itemid'=>$data['id'],'is_del'=>0])->select()->toArray();
- if(empty($d)){
- $data['item']=[];
- }else{
- $data['item']=$d;
- }
- }
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- //var_dump($db);
- foreach ($db as $p){
- $data['child'][]=crea($p,$vio);
- }
- return $data;
- }
- //根据部门id获取部门名称(层级名称)
- function GetPart($id,$data=[]){
- $userCommon = CommonUser::getIns();
- $rs = $userCommon->handle('get_part',['itemid'=>$id]);
- return $rs['data'];
- // $db = Db::name("company_item")->where(['id'=>$id,'is_del'=>0])->find();
- // if($db==false){
- // return [];
- // }
- // $tem=[];
- // $tem['id']=$db['id'];
- // $tem['name']=$db['name'];
- // array_unshift($data,$tem);
- // if($db['pid']==0){
- // // krsort($data);
- // return $data;
- // }else{
- // return GetPart($db['pid'],$data);
- // }
- }
- function stro($data){
- $db=Db::name('cat')->where(['pid'=>$data['id']])->select()->toArray();
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- foreach ($db as $item) {
- $data['child'][]=stro($item);
- }
- return $data;
- }
- function coco($data){
- $db=Db::name('exclusive')->where(['pid'=>$data['id']])->select()->toArray();
- if(empty($db)){
- $data['child']=[];
- return $data;
- }
- foreach ($db as $item) {
- $data['child'][]=coco($item);
- }
- return $data;
- }
- function mai($var,$data=[]){
- $str = Db::name('exclusive')->where(['id'=>$var])->find();
- if($str==false){
- return [];
- }
- $vmn =[];
- $vmn['id'] =$str['id'];
- $vmn['rname'] =$str['name'];
- array_unshift($data,$vmn);
- // $var['id']=made();
- if($str['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return mai($str['pid'],$data);
- }
- }
- //根据分类id获取分类结构数据
- if (function_exists('made') == false) {
- function made($cat_id = 0)
- {
- $key = 'cat_made_id_' . $cat_id;
- if (Cache::has($key)) return Cache::get($key);
- else {
- $rs = get_cat_data($cat_id);
- Cache::set($key, $rs, 3600 * 24);
- return $rs;
- }
- // $str = Db::name('cat')->where(['id'=>$var])->find();
- // if($str==false){
- // return [];
- // }
- // $vmn =[];
- // $vmn['id'] =$str['id'];
- // $vmn['name'] =$str['cat_name'];
- // array_unshift($data,$vmn);
- // // $var['id']=made();
- // if($str['pid']==0){
- // // krsort($data);
- // return $data;
- // }else{
- // return made($str['pid'],$data);
- // }
- }
- }
- if (function_exists('get_cat_data') == false) {
- function get_cat_data($var, $data = [])
- {
- $str = Db::name('cat')
- ->field('id,cat_name,pid')
- ->where(['id' => $var])
- ->findOrEmpty();
- if (empty($str)) return [];
- array_unshift($data, ['id' => $str['id'], 'name' => $str['cat_name']]);
- return $str['pid'] == 0 ? $data : get_cat_data($str['pid'], $data);
- }
- }
- //获取有赞分类信息
- function made_youzan(int $yz_cat_id=0,$data=[]){
- $rs = get_yz_cat_info($yz_cat_id);
- if(empty($rs)) return [];
- $vmn =[];
- $vmn['yz_cat_id'] =$rs['id'];
- $vmn['yz_cat_name'] =$rs['yz_cat_name'];
- array_unshift($data,$vmn);
- if($rs['parent_cid']==0) return $data;
- else return made_youzan($rs['parent_cid'],$data);
- }
- //跨数据库获取有赞分类信息
- if(!function_exists('get_yz_cat_info')){
- function get_yz_cat_info(int $yz_cat_id=0){
- $key = 'yz_cat_item_'.(string)$yz_cat_id;
- $rs = \think\facade\Cache::get($key);
- if(!$rs){
- $rs = Db::connect('mysql_yz')
- ->table('yz_cat')
- ->field('id,yz_cat_name,parent_cid')
- ->where(['id'=>$yz_cat_id,'status'=>1])
- ->findOrEmpty();
- if($rs) \think\facade\Cache::set($key,$rs,36000);
- }
- return $rs;
- }
- }
- function catChild($var,&$data=[]){
- $str = Db::name('cat')->where(['id'=>$var])->find();
- if($str==false){
- return;
- }
- $data[]=$var;
- $lsit = Db::name("cat")->where(["pid"=>$var,"status"=>1,"is_del"=>0])->column("id");
- if(!empty($lsit)){
- foreach ($lsit as $value){
- catChild($value,$data);
- }
- }
- return $data;
- }
- function makeExcluse($var,$data=[]){
- $str = Db::name('exclusive')->where(['id'=>$var])->find();
- if($str==false){
- return [];
- }
- $vmn =[];
- $vmn['id'] =$str['id'];
- $vmn['name'] =$str['name'];
- array_unshift($data,$vmn);
- // $var['id']=made();
- if($str['pid']==0){
- // krsort($data);
- return $data;
- }else{
- return makeExcluse($str['pid'],$data);
- }
- }
- function sear($id){
- $item = Db::name('cat')->where(['id'=>$id])->field("search")->find();
- if($item==false){
- return false;
- }else{
- $temp = Db::name('cat')->where(['pid'=>$id,'is_del'=>0])->select();
- if ($temp==false){
- return false;
- }
- }
- foreach ($temp as $value){
- $value['search']=$item['search']."_".$value['cat_name'];
- $list = Db::name('cat')->save($value);
- sear($value['id']);
- }
- }
- function manger($list=[],$level=1){
- $var = Db::name('cat')->where(['pid'=>$list,'level'=>$level+1])->column("id");
- if(empty($var)){
- return $list;
- }
- $a=array_merge($list,$var);
- return manger($a,$level+1);
- }
- /**
- * @param $files
- * @param string $extend
- * @return array
- * @throws PHPExcel_Exception
- * @throws PHPExcel_Reader_Exception
- */
- function upload_excel($files,$extend="xls")
- {
- // 获取表单上传文件
- try {
- validate([
- 'file' => [
- // 限制文件大小(单位b),这里限制为4M
- //fileSize' => 4 * 1024 * 1024,
- 'fileExt' => 'xlsx,xls'
- ]
- ],
- [
- //'file.fileSize' => '文件太大',
- 'file.fileExt' => '不支持的文件',
- ]
- )->check(['file' => $files]);
- // $name = $files->getOriginalExtension();
- if ($extend == 'xlsx') {
- $objReader = PHPExcel_IOFactory::createReader('Excel2007');
- } else {
- $objReader = PHPExcel_IOFactory::createReader('Excel5');
- }
- $savename = Filesystem::disk('public')->putFile('topic/excel', $files);
- $import_path = root_path() . 'public/storage/' . $savename;
- $spreadsheet = $objReader->load($import_path);
- $sheet = $spreadsheet->getActiveSheet();
- $sheetData = $sheet->toArray();
- if (empty($sheetData) || !is_array($sheetData)) {
- return ['code' => 1003, "msg" => '数据不能为空'];
- }
- $list = [];
- foreach ($sheetData as $key => $value) {
- $list[] = $value;
- }
- return ['code' => 0, "msg" => '数据解析成功', 'data' => $list];
- } catch (think\exception\ValidateException $e) {
- // echo $e->getMessage();
- return ['code' => 1003, "msg" => $e->getMessage()];
- }
- }
- /**
- * @param string $fileName
- * @param array $headArr
- * @param array $data
- */
- function excelSave($fileName = '', $headArr = [], $data = [])
- {
- $objPHPExcel =new PHPExcel();
- $objPHPExcel->getProperties();
- $keyA = 0; // 设置表头
- foreach ($headArr as $v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
- $keyA += 1;
- }
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($data as $key => $rows) { // 行写入
- $span = 0;
- foreach ($rows as $keyName => $value) { // 列写入
- //判断数据是否有数组,如果有数组,转换成字符串
- if(is_array($value)){
- $value = implode("、", $value);
- }
- // 处理长数字改为纯为本
- $objActSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($span). $column)->getStyle()->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_TEXT);
- $objActSheet->setCellValueExplicit(PHPExcel_Cell::stringFromColumnIndex($span). $column,strval($value));
- $span++;
- }
- $column++;
- }
- $file = $fileName. ".xls";
- $dir =root_path() . 'public/storage/report/'.date("YmdHis")."/";
- if(!is_dir($dir)){
- mkdir($dir,0777,true);
- }
- PHPExcel_Settings::setCacheStorageMethod(PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized);
- $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if(!file_exists($url)){
- echo "文件生成失败";
- }
- $saveDir = root_path()."public/storage/zip/";
- if(!is_dir( $saveDir)){
- mkdir($saveDir,0777,true);
- }
- // $datetime = date("YmdHis");
- $file_dir = $saveDir . $fileName . ".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !==
- true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- $zip->addEmptyDir($fileName);
- @$zip->addFile($url,$fileName.DIRECTORY_SEPARATOR.basename($url));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);
- # 6. 检查文件是否存在,并输出文件
- if (! file_exists ( $file_dir )) echo '简历文件不存在';
- ob_clean();
- flush();
- header("Cache-Control: max-age=0");
- header("Content-Description: File Transfer");
- header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
- header("Content-Type: application/octet-stream"); # 流文件输出
- header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
- // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
- // readfile($file_dir); # 输出文件
- $res = read_big_file($file_dir);
- foreach ($res as $val) {
- echo $val;
- }
- @ unlink($file_dir);
- exit();
- }
- //读取大文件
- if (!function_exists('read_big_file')){
- function read_big_file(string $file=''){
- $handle = fopen($file, 'rb');
- while (feof($handle) === false) {
- yield fgets($handle);
- }
- fclose($handle);
- }
- }
- function deldir($path){
- //如果是目录则继续
- if(is_dir($path)){
- //扫描一个文件夹内的所有文件夹和文件并返回数组
- $p = scandir($path);
- //如果 $p 中有两个以上的元素则说明当前 $path 不为空
- if(count($p)>2){
- foreach($p as $val){
- //排除目录中的.和..
- if($val !="." && $val !=".."){
- //如果是目录则递归子目录,继续操作
- if(is_dir($path.$val)){
- //子目录中操作删除文件夹和文件
- deldir($path.$val.'/');
- }else{
- //如果是文件直接删除
- unlink($path.$val);
- }
- }
- }
- }
- }
- //删除目录
- return rmdir($path);
- }
- /**
- * @param string $AddrJson
- */
- function GetAddr($AddrJson = "")
- {
- if ($AddrJson == "") {
- return '';
- }
- $adr = json_decode($AddrJson, true);
- if (!is_array($adr)) {
- return '';
- }
- $addr = '';
- if (isset($adr['provice_code']) && $adr['provice_code'] != '') {
- $provice = Db::name("province")->where(["province_code" => $adr['provice_code']])->find();
- $addr .= isset($provice['name']) ? $provice['name'] : "";
- }
- if (isset($adr['city_code']) && $adr['city_code'] != '') {
- $city = Db::name("city")->where(["city_code" => $adr['city_code']])->find();
- $addr .= isset($city['name']) ? $city['name'] : "";
- }
- if (isset($adr['area_code']) && $adr['area_code'] != '') {
- $area = Db::name("area")->where(["area_code" => $adr['area_code']])->find();
- $addr .= isset($area['name']) ? $area['name'] : "";
- }
- return $addr;
- }
- /**
- * POST 请求
- * @param string $url
- * @param array $param
- * @param boolean $post_file 是否文件上传
- * @return string content
- */
- function post($url,$data,$header=[])
- {
- //对空格进行转义
- $url = str_replace(' ','+',$url);
- $ch = curl_init();
- //设置选项,包括URL
- curl_setopt($ch, CURLOPT_URL, "$url");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch,CURLOPT_TIMEOUT,3); //定义超时3秒钟
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- // POST数据
- // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- // 把post的变量加上
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
- curl_setopt($ch, CURLOPT_HEADER, true);
- //执行并获取url地址的内容
- $output = curl_exec($ch);
- $errorCode = curl_errno($ch);
- //释放curl句柄
- $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- // 根据头大小去获取头信息内容
- $header = substr($output, 0, $headerSize);
- curl_close($ch);
- if(0 !== $errorCode) {
- return false;
- }
- return $header;
- }
- function post2($url,$data,$header=[])
- {
- //对空格进行转义
- $url = str_replace(' ','+',$url);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- //设置选项,包括URL
- curl_setopt($ch, CURLOPT_URL, "$url");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- // POST数据
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- // 把post的变量加上
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //所需传的数组用http_bulid_query()函数处理一下,就ok了
- $output = curl_exec($ch);
- $errorCode = curl_errno($ch);
- curl_close($ch);
- if(0 !== $errorCode) {
- return false;
- }
- return $output;
- }
- function GoldPrice($data,$cost_rate=0){
- $gold = Db::name("gold_price1")->where(["type"=>$data["metal_id"],"is_del"=>0,"status"=>1])->order("addtime desc")
- ->find();
- // $rate = $data['open_fee']/$data['num'] + $data['weight']* $gold["price"] + $data['cost_fee']/(1-$cost_rate) *
- // $data['weight']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'];
- $saleprice = ($data['demo_fee']/$data['num']+$data['delivery_fee']+$data['open_fee']/$data['num']+ $data['weight']*
- $gold["price"] + $data['cost_fee'] *$data['weight'] + $data['packing_fee']+ $data["mark_fee"]+ $data["cert_fee"]+$data['nake_fee']) / (1 - $cost_rate);
- return $saleprice;
- }
- function GoodPrice($data,$cost_rate=0){
- $rate = ($data['open_fee']/$data['num']+ $data['cost_fee']+$data['packing_fee']+$data["mark_fee"]+$data["cert_fee"]+$data['nake_fee'])/(1-$cost_rate
- );
- return $rate;
- }
- function checkRole($roleid,$menu){
- $roleinfo = \think\facade\Db::name('role_action')->where([['role_id','in',$roleid],['status','=',1]])->json(['private_data'])->find();
- if(!empty($roleinfo['private_data'])){
- if(in_array($menu,$roleinfo['private_data'])){
- return true;
- }
- }
- return false;
- }
- /**
- * 根据地址解析省市区
- * @param 详细地址,类似于'北京市顺义区xxx路xxx号'
- */
- if (!function_exists('get_address')) {
- function get_address(string $address = '')
- {
- preg_match('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', $address, $matches);
- if (count($matches) > 1) {
- $province = $matches[count($matches) - 2];
- $address = preg_replace('/(.*?(省|自治区|北京市|天津市|上海市|重庆市|澳门特别行政区|香港特别行政区))/', '', $address, 1);
- }
- preg_match('/(.*?(市|自治州|地区|区划|县|盟))/', $address, $matches);
- if (count($matches) > 1) {
- $city = $matches[count($matches) - 2];
- $address = str_replace($city, '', $address);
- }
- preg_match('/(.*?(区|县|镇|乡|街道|旗|市))/', $address, $matches);
- if (count($matches) > 1) {
- $area = $matches[count($matches) - 2];
- $address = str_replace($area, '', $address);
- }
- return [
- 'province' => isset($province) ? $province : '',
- 'city' => isset($city) ? $city : '',
- 'district' => isset($area) ? $area : '',
- "address" => $address
- ];
- }
- }
- /**
- * 批量生成多个文件excel,生成压缩包
- */
- if (!function_exists('excelSaveBatch')) {
- function excelSaveBatch(array $datas = [])
- {
- $urls = [];
- $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
- if (!is_dir($dir)) {
- mkdir($dir, 0777, true);
- }
- foreach ($datas as $item) {
- $objPHPExcel = new PHPExcel();
- $objPHPExcel->getProperties();
- $keyA = 0; // 设置表头
- foreach ($item['head'] as $v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
- $keyA += 1;
- }
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($item['list'] as $key => $rows) { // 行写入
- $span = 0;
- foreach ($rows as $keyName => $value) { // 列写入
- //判断数据是否有数组,如果有数组,转换成字符串
- if (is_array($value)) {
- $value = implode("、", $value);
- }
- $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
- $span++;
- }
- $column++;
- }
- // var_dump($objActSheet->getActiveCell());
- $file = $item['filename'] . ".xls";
- //$fileName .= "_" . date("Y_m_d", Request()->instance()->time()) . ".xls";
- //$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
- $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if (!file_exists($url)) {
- echo "文件生成失败";
- } else {
- $urls[] = $url;
- }
- }
- $saveDir = root_path() . "public/storage/zip/";
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0777, true);
- }
- $datetime = date("YmdHis");
- $file_dir = $saveDir . $datetime . ".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
- foreach ($urls as $fileName) {
- // @$zip->addFile($fileName);
- @$zip->addFile($fileName, DIRECTORY_SEPARATOR.basename($fileName));
- }
- // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);//删除已生成的文件及目录
- //6. 检查文件是否存在,并输出文件
- if (!file_exists($file_dir)) echo '压缩包文件不存在';
- ob_clean();
- flush();
- header("Cache-Control: max-age=0");
- header("Content-Description: File Transfer");
- header('Content-disposition: attachment; filename=' . basename($file_dir)); # 处理文件名
- header("Content-Type: application/octet-stream"); # 流文件输出
- header("Content-Transfer-Encoding: binary"); # 告诉浏览器,这是二进制文件
- // header('Content-Length: ' . filesize($file_dir)); # 告诉浏览器,文件大小
- // readfile($file_dir);//输出文件
- $res = read_big_file($file_dir);
- foreach ($res as $val) {
- echo $val;
- }
- @unlink($file_dir);
- exit();
- }
- }
- /**
- * 批量生成多个文件excel,生成压缩包,保存到本地,返回文件链接
- * datas 生成器
- * header array 头部字段
- * filename string 文件名
- */
- if (!function_exists('excelSaveFile')) {
- function excelSaveFile($datas, string $filename = '')
- {
- $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
- if (!is_dir($dir)) mkdir($dir, 0777, true);
- // PHPExcel_Settings::setCacheStorageMethod();
- // PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;//单元格缓存为MemoryGZip
- $objPHPExcel = new PHPExcel();
- $keyA = 0; // 设置表头
- $column = 2;
- $objActSheet = $objPHPExcel->getActiveSheet();
- foreach ($datas as $key => $rows) { // 行写入
- //第一行取key作表头
- if($key==0){
- $objPHPExcel->getProperties();
- foreach ($rows as $k=>$v) {
- $colum = PHPExcel_Cell::stringFromColumnIndex($keyA);
- $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $k);
- $keyA += 1;
- }
- }
- //写入列
- $span = 0;
- foreach ($rows as $keyName => $value) {
- //判断数据是否有数组,如果有数组,转换成字符串
- if (is_array($value)) $value = implode("、", $value);
- $objActSheet->setCellValue(PHPExcel_Cell::stringFromColumnIndex($span) . $column, $value);
- $span++;
- }
- $column++;
- }
- $file = $filename . ".xls";
- $objPHPExcel->setActiveSheetIndex(0);
- $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
- $objWriter->save($dir . $file); // 文件通过浏览器下载
- $url = $dir . $file;
- if (!file_exists($url)) throw new Exception('文件生成失败');
- $saveDir = root_path() . "public/storage/zip/" . date('Ymd') . '/';
- if (!is_dir($saveDir)) mkdir($saveDir, 0777, true);
- $file_dir = $saveDir . $filename . ".zip";
- # 5.1 文件打包,提示:使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
- $zip = new \ZipArchive ();
- # 5.2 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
- if ($zip->open($file_dir, \ZipArchive::OVERWRITE) !== true && $zip->open($file_dir, \ZipArchive::CREATE) !== true) echo '无法打开文件或者文件创建失败';
- # 5.3 批量写入压缩包
- // $zip->addEmptyDir($fileName);//往zip压缩包写入空目录
- // foreach ($urls as $fileName) {
- @$zip->addFile($url, DIRECTORY_SEPARATOR . basename($url));
- // }
- // @$zip->addFile($v['file_path'], 'resume'.DIRECTORY_SEPARATOR.basename($headername));
- # 5.4 关闭压缩包写入
- $zip->close();
- @deldir($dir);//删除已生成的文件及目录
- //6. 检查文件是否存在,并输出文件
- if (!file_exists($file_dir)) throw new Exception('压缩包文件不存在');
- // return $file_dir;
- return str_replace(root_path() . "public/", '', $file_dir);
- }
- }
- if (!function_exists('xlswriter')) {
- function xlswriter($datas, string $filename = '')
- {
- $dir = root_path() . 'public/storage/report/' . date("YmdHis") . "/";
- if (!is_dir($dir)) mkdir($dir, 0777, true);
- $config=["path"=>$dir];
- $objPHPExcel = new \Vtiful\Kernel\Excel($config);
- $fileObject = $objPHPExcel->constMemory($filename,"sheet1");
- $format = new \Vtiful\Kernel\Format($fileObject->getHandle());
- foreach ($datas as $key => $rows) { // 行写入
- //第一行取key作表头
- if($key==0){
- $header = array_keys($rows);
- $fileObject->header($header);
- }
- foreach ($rows as $k=>$v) {
- $fileObject->insertText($key,$k,$v);
- }
- }
- $filePath = $fileObject->output();
- // Set Header
- header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- header('Content-Disposition: attachment;filename="' . $filename . '"');
- header('Content-Length: ' . filesize($filePath));
- header('Content-Transfer-Encoding: binary');
- header('Cache-Control: must-revalidate');
- header('Cache-Control: max-age=0');
- header('Pragma: public');
- ob_clean();
- flush();
- if (copy($filePath, 'php://output') === false) {
- // Throw exception
- exit('copy file to path error');
- }
- // Delete temporary file
- @unlink($filePath);
- }
- }
- //通过快递网的api获取物流信息
- if (!function_exists('get_logistics_information')) {
- function get_logistics_information(string $post_code = '', string $phone = '')
- {
- if ($post_code == '') throw new Exception('快递单号不能为空');
- $signer = new \app\admin\common\HuaweiSigner();
- //设置相关参数
- $signer->Key = '1b4cfe41d72d4fbdb6778a5e0193c4b5';
- $signer->Secret = '0fd04c5d5287424eb0d25f8f620aeb78';
- $req = new \app\admin\common\HuaweiRequest('GET', 'http://kuaidi.apistore.huaweicloud.com/kuaidiinfo?nu=' . $post_code . '&phone=' . $phone);
- $req->headers = array(
- 'content-type' => 'application/json',
- 'x-stage' => 'RELEASE',
- );
- $req->body = '';//如果是post/put请求的话,要往请求体中添加内容
- $curl = $signer->Sign($req);
- $response = curl_exec($curl);
- $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
- $curl_error = curl_error($curl);
- curl_close($curl);
- if ($status == 200) return json_decode($response, true);
- else throw new Exception('请求失败:' . $curl_error);
- }
- }
- //获取三级架构
- if (!function_exists('get_top_customer_org')) {
- function get_top_customer_org($var)
- {
- $userCommon = CommonUser::getIns();
- $rs = $userCommon->handle('get_top_customer_org', ['itemid' => is_array($var) ? $var : [$var]]);
- if (is_array($var)) return $rs['data'];
- else return $rs['data'][$var]??[];
- // $str = Db::name('customer_org1')
- // ->field('id,name,pid,level')
- // ->where(['id' => $var])
- // ->find();
- // if ($str == false) {
- // return [];
- // }
- // $vmn = [];
- // $vmn['id'] = $str['id'];
- // $vmn['name'] = $str['name'];
- // $vmn['level'] = $str['level'];
- // array_unshift($data, $vmn);
- // // $var['id']=made();
- // if ($str['pid'] == 0) {
- // // krsort($data);
- // return $data;
- // } else {
- // return get_top_customer_org($str['pid'], $data);
- // }
- }
- }
- //根据某个关键字匹配所有子级部门及用户
- if (!function_exists('get_company_item_user_by_name')) {
- function get_company_item_user_by_name(string $company_name = '',int $depart_id=0)
- {
- $condition = [];
- if($company_name!="") $condition=['company_name' => $company_name];
- if($depart_id!="") $condition=['depart_id' => $depart_id];
- $userCommon =CommonUser::getIns();
- $rs = $userCommon->handle('get_company_item_user_by_name', $condition);
- return $rs['data'] ?? [];
- // $data = [];
- //
- // //查询符合条件的部门id
- // $company_ids = Db::name("company_item")
- // ->field('id,level')
- // ->where(['is_del' => 0])
- // ->whereLike('name', '%' . $company_name . '%')
- // ->select()
- // ->toArray();
- //
- // if (!empty($company_ids)) {
- // $level_temp = $company_ids[0]['level'] + 1;
- // $company_ids = array_column($company_ids, 'id');
- // for ($level = $level_temp; $level > 0; $level++) {
- //
- // if (!empty($company_ids)) {
- // //根据部门id找人
- // $uids = Db::name('depart_user')
- // ->where(['is_del' => 0])
- // ->order('uid')
- // ->whereIn('itemid', $company_ids);
- // if (!$off) $uids->where('status', 1);
- // $uids = $uids->column('uid');
- // $data = array_unique(array_merge($data, $uids));
- //
- // $company_ids = Db::name("company_item")
- // ->where(['is_del' => 0, 'level' => $level])
- // ->whereIn('pid', $company_ids)
- // ->column('id');
- // } else break;
- //
- // }
- //
- // }
- // return $data;
- }
- }
- //获取某个用户所属部门名称
- //$uid int 用户id
- //$get_tops 是否获取多级部门,例如 万宇恒通/采购部/仓储物流,1获取,2不获取(默认)
- if (!function_exists('get_company_name_by_uid')) {
- function get_company_name_by_uid($uid = '', $get_tops = 2)
- {
- $userCommon = CommonUser::getIns();
- $rs = $userCommon->handle('get_company_name_by_uid',['uid'=>$uid,'get_tops'=>$get_tops]);
-
- //为了兼容旧的数据格式
- if(is_array($uid)) return $rs['data'];
- else return $rs['data'][$uid]??[];
- }
- }
- //返回json格式的响应信息,方便中间件记录,目前在abutmenu应用中有用到
- if (!function_exists('json_show')) {
- function json_show(int $code = 0, string $message = '请求成功', array $data = [])
- {
- return json(['code' => $code, 'message' => $message, 'data' => $data]);
- }
- }
- //获取加密后的密码密文
- /**
- * @param $password string 密码明文
- * @param $salt string 盐值(不传的话随机生成一个)
- */
- if (!function_exists('get_encryption_password')) {
- function get_encryption_password(string $password = '',string $salt=''):array
- {
- if($salt=='') $salt = Str::random(mt_rand(10, 30), -1);
- return [
- 'password' => md5($salt . $password . $salt . $salt),
- 'salt' => $salt
- ];
- }
- }
- //检查供应商是否有开通账号
- if (!function_exists('checkHasAccountBySupplierNos')) {
- function checkHasAccountBySupplierNos(array $supplierNo = []): array
- {
- $userCommon = CommonUser::getIns();
- $rs = $userCommon->handle('check_has_account_by_supplierNos', ['supplierNo' => $supplierNo]);
- return $rs['data'];
- }
- }
- //获取当前用户可查看的其他用户id(新版的)
- if (!function_exists('get_group_share_uid')) {
- function get_group_share_uid(int $uid = 0,int $level=2)
- {
- //原始数据
- $data = [DataGroupModel::$type_可编辑 => [$uid], DataGroupModel::$type_只读 => [$uid], DataGroupModel::$type_不共享 => []];
- //用户组
- $group = Db::name('data_group_userid')
- ->alias('a')
- ->leftJoin('data_group b', 'b.id=a.data_group_id')
- ->where([
- 'a.is_del' => DataGroupModel::$delete_正常,
- 'a.status' => DataGroupModel::$status_启用,
- 'a.uid' => $uid,
- 'b.is_del' => DataGroupModel::$delete_正常,
- 'b.status' => DataGroupModel::$status_启用,
- ])->order('a.data_group_id')
- ->column('b.type', 'a.data_group_id');
- $group_user = Db::name('data_group_userid')
- ->where([
- 'is_del' => DataGroupModel::$delete_正常,
- 'status' => DataGroupModel::$status_启用,
- ])->whereIn('data_group_id', array_keys($group))
- ->field('id,data_group_id,uid')
- ->order('uid')
- ->cursor();
- foreach ($group_user as $g_u) {
- $data[$group[$g_u['data_group_id']]][] = $g_u['uid'];
- }
- //当前请求的接口地址
- $api = app('http')->getName() . '/' . request()->pathinfo();
- $menu_id = Db::name('admin_menu')
- ->where(['is_del' => 0, 'menu_api' => $api,'level'=>$level])
- ->value('id', 0);
- if ($menu_id) {
- //共享规则
- $share = Db::name('data_share')
- ->field('id,type,source_uid,source_data_group_id')
- ->where([
- 'is_del' => DataShareModel::$delete_正常,
- 'status' => DataShareModel::$status_启用,
- ])
- ->whereFindInSet('menu_ids', $menu_id)
- ->where(function ($query) use ($uid, $group) {
- return $query->where('uid', $uid)->whereOr('data_group_id', 'in', array_keys($group));
- })
- ->cursor();
- foreach ($share as $s) {
- $source_group_uid = Db::name('data_group_userid')
- ->where([
- 'is_del' => DataGroupModel::$delete_正常,
- 'status' => DataGroupModel::$status_启用,
- 'data_group_id' => $s['source_data_group_id'],
- ])->order('uid')->column('uid');
- //$s['source_uid'] ? [$s['source_uid']] : [] 排除默认值0
- $data[$s['type']] = array_merge($data[$s['type']], $s['source_uid'] ? [$s['source_uid']] : [], $source_group_uid);
- }
- }
- //离职交接权限
- // $resign_uid = Db::name("resign_info")
- // ->where([["hand_uid", "=", $uid], ["is_del", "=", 0], ['status', "=", 4]])
- // ->order('resign_uid')
- // ->column('resign_uid');
- // if (!empty($resign_uid)) $data[DataGroupModel::$type_可编辑] = array_merge($data[DataGroupModel::$type_可编辑], $resign_uid);
- unset($data[DataGroupModel::$type_不共享]);
- $data[DataGroupModel::$type_全部] = array_merge($data[DataGroupModel::$type_可编辑], $data[DataGroupModel::$type_只读]);
- sort($data[DataGroupModel::$type_全部]);
- $data[DataGroupModel::$type_全部] = array_unique($data[DataGroupModel::$type_全部]);
- return $data;
- }
- }
- //获取当前操作人(待办列表)
- if (!function_exists('get_handle_user_list')) {
- //$action_process_id 节点id
- //$holder_id 所有人uid
- //$api_url 接口路径,匹配菜单使用
- //$person_id 供应商负责人(供应商端)
- function get_handle_user_list(int $action_process_id = 0, int $holder_id = 0, string $api_url = '',int $person_id=0)
- {
- //筛选符合流程权限的角色id集合
- $roleids = Db::name('role_process')
- ->where('is_del', 0)
- ->where('role_id', '<>', 1)//排除超级管理员
- ->whereFindInSet('action_data', $action_process_id)
- ->field('role_id')
- ->buildSql();
- //根据角色id筛选用户id
- $data = Db::name('user_role')
- ->where(['is_del' => 0, 'status' => 1])
- ->where('roleid IN ' . $roleids)
- ->column('uid');
- //根据菜单筛选符合条件的共享数据
- $tmp = getUserIdsByShare($api_url,$holder_id);
- $res = array_intersect($tmp, $data);//流程权限和数据权限取交集
- //如果本人有流程权限的话,加入到数组中
- if (in_array($holder_id, $data)) $res[] = $holder_id;
- if ($person_id) $res[] = $person_id;
- sort($res);
- $res = array_unique($res);
- return $res;
- }
- }
- //根据数据权限,筛选符合条件的用户(旧版)
- if (!function_exists('getUserIdsByShare')) {
- function getUserIdsByShare(string $api_url = '', int $holder_id = 0)
- {
- //当前请求的接口地址
- if ($api_url == '') $api_url = app('http')->getName() . '/' . request()->pathinfo();
- $menu_id = Db::name('admin_menu')
- ->where(['is_del' => 0, 'menu_api' => $api_url])
- ->value('id', 0);
- $tmp = [];
- if ($menu_id) {
- //共享规则
- $share = Db::name('role_share')
- ->field('id,to_user,to_group')
- ->where([
- 'share_user' => $holder_id,
- 'is_del' => 0,
- 'status' => 1,
- ])
- ->whereFindInSet('action_collect', $menu_id)
- ->cursor();
- foreach ($share as $s) {
- if ($s['to_user']) $tmp[] = $s['to_user'];
- elseif ($s['to_group']) {
- $group_user = Db::name('role_group')
- ->where([
- 'id' => $s['to_group'],
- 'is_del' => 0,
- 'status' => 1,
- ])->value('group_user');
- $tmp = array_merge($tmp, explode(',', $group_user));
- }
- }
- }
- return $tmp;
- }
- }
- //采购单未操作确认或入库时判断销售单是否存在正进行中的退货
- if(!function_exists("cgd_sale_return")){
- /**
- * @param $cgdNo
- * @return bool
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- function cgd_sale_return($cgdNo){
- $order =Db::name("order_num")->alias("a")
- ->leftJoin("sale_return b","a.orderCode=b.orderCode and b.is_del=0")
- ->where(["a.cgdNo"=>$cgdNo])
- ->whereIn("b.status",[1,2,3,7,8,9,10,11,12])
- ->findOrEmpty();
- return !empty($order);
- }
- }
- //离职交接数据
- if(!function_exists("resign_hand_user")){
- /**
- * @param $uid
- * @param int $ty 1 返回字符串 0 返回数组
- * @return array|string
- */
- function resign_hand_user($uid,$ty=1){
- $uid_arr=[$uid];
- $resign_uids =Db::name("resign_info")->where([["hand_uid","=",$uid],["is_del","=",0],["status","=",4]])
- ->column("resign_uid");
- $uid_arr =array_filter(array_merge($uid_arr,$resign_uids));
- return $ty==1? "(".implode(",",$uid_arr).")":$uid_arr;
- }
- }
- //检查是否有符合条件的活动
- //@param $spuCode string 商品成本编号
- //@param $skuCode string 商品上线编号
- //@param $platform_id int 上线平台id
- //@param $is_stock int 是否库存品
- //@param $price float 售价
- //@param $good_num int 商品数量
- if (!function_exists('check_activity')) {
- function check_activity(string $spuCode = '', string $skuCode = '', int $platform_id = 0, int $is_stock = 0, float $price = 0.00, int $good_num = 0)
- {
- $act = Db::name('activity_info')
- ->alias('ai')
- ->field('ai.id,ai.activity_code,ai.activity_stock,ai.moq_num,ai.activity_price,ai.is_activity,ai.settle_price,ai.cost_price')
- ->join('good_activity ga', 'ga.activity_code=ai.activity_code')
- ->where([
- 'ai.skuCode' => $skuCode,
- 'ai.is_del' => 0,
- 'ai.status' => 1,
- 'ga.status' => 6,
- 'ga.is_del' => 0,
- 'ga.platform_code' => $platform_id,
- 'ga.is_stock' => $is_stock
- ])
- ->where(function ($query) {
- return $query->where('ga.start', '<=', date('Y-m-d H:i:s'))->where('ga.end', '>=', date('Y-m-d H:i:s'));
- })
- ->findOrEmpty();
- if (empty($act)) return $act;//没有符合条件的活动
- else {
- if ($act['moq_num'] > $good_num) return [];//throw new \think\Exception('商品不满足活动价起订量' . $act['moq_num']);,不走活动
- if ($act['activity_stock'] < $good_num) return [];//throw new \think\Exception('商品活动库存剩余' . $act['activity_stock']);
- if ($price < $act['activity_price']) throw new \think\Exception('售价低于活动价' . $act['activity_price']);
- $merge= $act['is_activity'] == 0 ? ['final_price' => $act['activity_price']] : ['final_price' => $act['settle_price']];
- return array_merge($act,$merge);
- }
- }
- }
- //是否使用券后金额 txx活动 用户领券兑换商品 商品转单时注意价格置换为售价
- if(!function_exists('is_discount')){
- /**
- * @param array $order_promotion
- * @return bool
- */
- function is_discount($coupon=[]){
- $bol=false;
- if(!empty($coupon)){
- $title=implode("|",array_unique(array_column($coupon,"promotion_title")));
- $str = stristr($title,"泰直播");
- if($str!=false) $bol=true;
- }
- return $bol;
- }
- }
- if(!function_exists('makeMenu')){
- function makeMenu($row, &$list)
- {
- $list[$row['id']] = $row;
- if ($row['pid'] == 0) {
- return $list;
- }
- $parent = Db::name("admin_menu")
- ->where(["id" => $row['pid'], "status" => 1, "is_del" => 0])
- ->field("id,menu_name,menu_img,menu_url,menu_route,pid,is_show,is_private,menu_type,weight")
- ->findOrEmpty();
- if ($parent == false) return $list;
- makeMenu($parent, $list);
- }
- }
- if (!function_exists('MenuTree')) {
- function MenuTree(&$menuArr, $pid = 0)
- {
- $meun = [];
- foreach ($menuArr as $value) {
- if ($value['pid'] == $pid) {
- if ($value['menu_type'] == 1) $value['child'] = MenuTree($menuArr, $value['id']);
- $meun[] = $value;
- }
- }
- return $meun;
- }
- ;
- }
- if(!function_exists('menuAction')){
- function menuAction($row,&$list=[]){
- $temp=[];
- foreach ($row as $key=>$value){
- if($value['pid']==0){
- $list[]=$value;
- }else{
- $menu=Db::name("admin_menu")
- ->where(["id"=>$value['pid'],"is_del"=>0,"status"=>1])
- ->field("id,menu_name,menu_img,menu_route,menu_url,pid,level,is_show,is_private,menu_type,status")
- ->findOrEmpty();
- if(empty($menu)) continue;
- if(!isset($temp[$value['pid']]))$temp[$value['pid']]=$menu;
- $temp[$value['pid']]['child'][]=$value;
- }
- }
- // $list=$temp;
- if (!empty($temp)){
- menuAction($temp,$list);
- }
- }
- }
- //获取汇总表中的编码和名称
- if (!function_exists('get_headquarters_code_and_name')) {
- function get_headquarters_code_and_name(array $code = []): array
- {
- $userCommon = CommonUser::getIns();
- $res = $userCommon->handle('getCodeAndName', ['code' => $code]);
- return $res['data'];
- }
- }
- function startTime($time){
- return date("Y-m-d 00:00:00",strtotime($time));
- }
- function endTime($time){
- return date('Y-m-d 23:59:59',strtotime($time));
- }
- //获取毛利率
- if (function_exists('get_budget') == false) {
- function get_budget(int $cat_id = 0, string $relaComNo = '', int $platform_id = 0,bool $is_show_more=false)
- {
- if ($is_show_more) {
- $sale_rate_1 = (new \app\admin\model\CompanyCatProfit)->GetAllRate($relaComNo,$cat_id);
- if($sale_rate_1->isEmpty()) return false;
- $sale_rate_2 = (new \app\admin\model\CompanyPlatformCatProfit)->GetAllRate($relaComNo,$cat_id,$platform_id);
- //返回多个字段的和
- return [
- 'rate' => (($sale_rate_1['rate'] ?? 0) + ($sale_rate_2['rate'] ?? 0)) / 100,
- 'order_rate' => (($sale_rate_1['order_rate'] ?? 0) + ($sale_rate_2['order_rate'] ?? 0)) / 100,
- 'money_rate' => (($sale_rate_1['money_rate'] ?? 0) + ($sale_rate_2['money_rate'] ?? 0)) / 100,
- 'low_rate' => (($sale_rate_1['low_rate'] ?? 0) + ($sale_rate_2['low_rate'] ?? 0)) / 100,
- 'sale_rate' => (($sale_rate_1['sale_rate'] ?? 0) + ($sale_rate_2['sale_rate'] ?? 0)) / 100,
- 'lower_rate'=>0,//boss利率,默认0,数据库没有这个值
- ];
- } else {
- $sale_rate_1 = (new \app\admin\model\CompanyCatProfit)->GetRate($relaComNo,$cat_id,"sale_rate");
- if($sale_rate_1==0) return false;
- $sale_rate_2 = (new \app\admin\model\CompanyPlatformCatProfit)->GetRate($relaComNo,$cat_id,$platform_id,'sale_rate');
- return ($sale_rate_1 + $sale_rate_2) / 100;
- } //此时的毛利率要取两个毛利的和
- }
- }
- //获取供应商负责人
- if(function_exists('get_personid_by_supplierNo')==false){
- function get_personid_by_supplierNo(array $codes=[],$type='personid'){
- $res=\app\admin\common\User::getIns()->handle('sGetList',['more_code'=>$codes,'size'=>count($codes)]);
-
- $data=isset($res['data']['list'])&&!empty($res['data']['list']) ? array_column($res['data']['list'],$type,'code'):[];
- unset($res);
- return $data;
- }
- }
- //是否是贵金属
- if(function_exists('cat_is_gold')==false){
- function cat_is_gold($catid,$gold_cat_id=[6]){
- if(in_array($catid,$gold_cat_id)) return true;
- $catlist =Db::name("cat")->where([["pid","in",$gold_cat_id],["is_del","=",0],["status","=",1]])->column("id");
- if(empty($catlist))return in_array($catid,$gold_cat_id);
- else return cat_is_gold($catid,$catlist);
- }
- }
- //是否是渠道
- if(function_exists('channel_is_company')==false){
- function channel_is_company($platform_id,$companyNo){
- // return false;
- $platform=Db::name("platform_channel")
- ->alias("a")
- ->leftJoin("channel b","a.channel_id=b.id")
- ->where(["a.is_del"=>0,"b.is_del"=>0,"b.status"=>1,"a.platform_id"=>$platform_id])
- ->column("b.companyNo");
- if(in_array($companyNo,$platform))return true;
- return false;
- }
- }
- //是否是渠道
- if(function_exists('report_sx')==false){
- function report_sx($day=0){
- if($day>=0 && $day<=1){
- return "A24小时";
- }
- if($day>1 && $day<=2){
- return "B48小时";
- }
- if($day>2 && $day<=7){
- return "C3-7天内";
- }
- if($day>7 && $day<=14){
- return "D14天内";
- }
- if($day>14 && $day<=30){
- return "E30天内";
- }
- if($day>30){
- return "F30天以上";
- }
- return '';
- }
- }
|