| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114 |
- <?php
- error_reporting(E_ERROR | E_PARSE);
- /**
- * 行为绑定
- */
- \think\Hook::add('app_init', 'app\\common\\behavior\\InitConfigBehavior');
-
- use app\common\adapter\AuthAdapter;
- use app\admin\model\User as UserModel;
- use app\admin\model\Field as FieldModel;
- use think\Request;
- use think\Db;
- use extend\email\Email;
- use think\Lang;
- use think\helper\Time;
- use com\IpLocation;
- use app\crm\traits\DataTime;
-
- /**
- * 对象 转 数组
- *
- * @param object $obj 对象
- * @return array
- */
- function object_to_array($obj)
- {
- $obj = (array)$obj;
- foreach ($obj as $k => $v) {
- if (gettype($v) == 'resource') {
- return;
- }
- if (gettype($v) == 'object' || gettype($v) == 'array') {
- $obj[$k] = (array)object_to_array($v);
- }
- }
- return $obj;
- }
-
- /**
- * 数组 转 对象
- *
- * @param array $arr 数组
- * @return object
- */
- function array_to_object($arr)
- {
- if (gettype($arr) != 'array') {
- return;
- }
- foreach ($arr as $k => $v) {
- if (gettype($v) == 'array' || getType($v) == 'object') {
- $arr[$k] = (object)array_to_object($v);
- }
- }
- return (object)$arr;
- }
-
- /**
- * 返回对象
- * @param array $array 响应数据
- */
- function resultArray($array)
- {
- if (isset($array['data'])) {
- $array['error'] = '';
- $code = 200;
- } elseif (is_array($array['error'])) {
- $code = 402; //返回数组格式
- $array['data'] = '';
- } elseif (isset($array['error'])) {
- $code = 400;
- $array['data'] = '';
- }
- return json([
- 'code' => $code,
- 'data' => $array['data'],
- 'error' => $array['error']
- ]);
- }
-
- /**
- * 调试方法
- * @param array $data [description]
- */
- function p($data, $die = 1)
- {
- echo "<pre>";
- print_r($data);
- echo "</pre>";
- if ($die) die;
- }
-
- /**
- * 用户密码加密方法
- * @param string $str 加密的字符串
- * @param [type] $auth_key 加密符
- * @param [string] $username 用户名
- * @return string 加密后长度为32的字符串
- */
- function user_md5($str, $auth_key = '', $username = '')
- {
- return '' === $str ? '' : md5(sha1($str) . md5($str . $auth_key));
- }
-
- /**
- * 金额展示规则,超过1万时以万为单位,低于1万时以千为单位,低于1千时以元为单位
- * @param string $money 金额
- * @return string
- * @author Michael_xu
- */
- function money_view($money)
- {
- $data = '0元';
- if (($money / 10000) > 1) {
- $data = is_int($money / 10000) ? ($money / 10000) . '万' : rand(($money / 10000), 2) . '万';
- } elseif (($money / 1000) > 1) {
- $data = is_int($money / 1000) ? ($money / 1000) . '千' : rand(($money / 1000), 2) . '千';
- } else {
- $data = $money . '元';
- }
- return $data;
- }
-
- /**
- * 高级筛选条件
- * @param $array 条件数组
- * @param $module 相关模块
- * @return string
- * @author Michael_xu
- */
- function where_arr($array = [], $m = '', $c = '', $a = '')
- {
- $userModel = new UserModel();
- $checkStatusList = ['待审核', '审核中', '审核通过', '审核失败', '已撤回', '未提交', '已作废'];
- $checkStatusArray = ['待审核' => 0, '审核中' => 1, '审核通过' => 2, '审核失败' => 3, '已撤回' => 4, '未提交' => 5, '已作废' => 6];
- //查询自定义字段模块多选字段类型
- $check_field_arr = [];
- //特殊字段
-
- //过滤系统参数
- $unset_arr = ['page', 'limit', 'order_type', 'order_field'];
- if (!is_array($array)) {
- return [];
- }
- $types = $c;
- foreach ($array as $k => $v) {
- if (!in_array($k, $unset_arr)) {
- $c = $types . '.';
- if ($k == 'customer_name') {
- $k = 'name';
- $c = 'customer.';
- }
- if ($k == 'contract_name') {
- $k = 'name';
- $c = 'contract.';
- }
- if ($k == 'business_name') {
- $k = 'name';
- $c = 'business.';
- }
- if ($k == 'contacts_name') {
- $k = 'name';
- $c = 'contacts.';
- }
- if ($v['form_type'] == 'date') {
- if (!empty($v['start'])) $v['start'] = date('Y-m-d', $v['start']);
- if (!empty($v['end'])) $v['end'] = date('Y-m-d', $v['end']);
- }
- # 自定义字段的user team_id(非自定义字段)
- if ($v['form_type'] == 'user' && in_array($k, ['team_id'])) {
- // ro_user_id rw_user_id
- if ($v['condition'] == 'in') {
- return "(" . $c . 'ro_user_id' . " like ',%" . $v['value'] . "OR " . $c . 'rw_user_id' . " like ',%" . $v['value'] . ")";
- } elseif ($v['condition'] == 'not in') {
- return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
- } elseif ($v['condition'] == 'isNull') {
- return "(" . $c . 'ro_user_id' . "eq" . $v['value'] . "OR " . $c . 'rw_user_id' . " eq" . $v['value'] . ")";
- } elseif ($v['condition'] == 'isNotNull') {
- return "(" . $c . 'ro_user_id' . "neq" . $v['value'] . "OR " . $c . 'rw_user_id' . " neq" . $v['value'] . ")";
- }
- }
- # 自定义字段的user、structure类型
- if (($v['form_type'] == 'user' && !in_array($k, ['create_user_id', 'owner_user_id'])) || $v['form_type'] == 'structure') {
- if ($v['condition'] == 'is') $v['condition'] = 'contains';
- if ($v['condition'] == 'isNot') {
- return "(" . $c . $k . " not like ',%" . $v['value'][0] . "%,' OR " . $c . $k . " is null)";
- }
- }
- # 处理多选字段的精确搜索
- if ($v['form_type'] == 'checkbox' && !empty($v['value'])) {
- if ($v['condition'] == 'is' && count($v['value']) == 1) $v['value'][0] = ',' . $v['value'][0] . ',';
- if ($v['condition'] == 'is' && count($v['value']) > 1) {
- $checkboxLike = '';
- foreach ($v['value'] as $kk => $vv) {
- $checkboxLike .= $c . $k . " like " . "',%" . $vv . "%,' AND ";
- }
- return "(" . $checkboxLike . "LENGTH(" . $c . $k . ") = LENGTH('" . arrayToString($v['value']) . "'))";
- }
- }
- if ($types == 'contract' && !empty($v['value'])) {
- switch ($k) {
- case 'business_id' :
- $k = 'name';
- $c = 'business.';
- break;
- case 'contacts_id' :
- $contactsIds = [];
- foreach ($v['value'] as $kk => $vv) {
- $contactsIdArray = db('crm_contacts')->whereLike('name', '%' . $vv . '%')->column('contacts_id');
- foreach ($contactsIdArray as $kkk => $vvv) {
- $contactsIds[] = $vvv;
- }
- }
- $v['value'] = array_unique($contactsIds);
- break;
- }
- }
- if ($types == 'receivables' && $v['name'] == '合同编号' && !empty($v['value'])) {
- $k = 'num';
- $c = 'contract.';
- }
- if ($types == 'receivables' && $k == 'plan_id' && !empty($v['value'])) {
- $planIds = [];
- foreach ($v['value'] as $kk => $vv) {
- $planIdArray = db('crm_receivables_plan')->whereLike('num', '%' . $vv . '%')->column('plan_id');
- foreach ($planIdArray as $kkk => $vvv) {
- $planIds[] = $vvv;
- }
- }
- $v['value'] = array_unique($planIds);
- }
- if ($types == 'invoice' && $v['type'] == 'invoice_status' && !empty($v['value'])) {
- foreach ($v['value'] as $kk => $vv) {
- if ($vv == '已开票') $v['value'][$kk] = 1;
- if ($vv == '未开票') $v['value'][$kk] = 0;
- }
- }
- if ($types == 'visit' && $v['type'] == 'contract_name' && !empty($v['value'])) {
- $k = 'num';
- $c = 'contract.';
- }
- if ($types == 'visit' && $v['type'] == 'contacts_name' && !empty($v['value'])) {
- $k = 'name';
- $c = 'contacts.';
- }
- if ($k == 'check_status' && is_array($v) && in_array($v['value'][0], $checkStatusList) && !empty($v['value'])) {
- $v['value'] = $checkStatusArray[$v['value'][0]] ?: '0';
- }
- if (is_array($v)) {
- if ($v['state']) {
- $address_where[] = '%' . $v['state'] . '%';
- if ($v['city']) {
- $address_where[] = '%' . $v['city'] . '%';
- if ($v['area']) {
- $address_where[] = '%' . $v['area'] . '%';
- }
- }
- if ($v['condition'] == 'not_contain') {
- $where[$c . $k] = ['notlike', $address_where, 'OR'];
- } else {
- $where[$c . $k] = ['like', $address_where, 'AND'];
- }
- } elseif (!empty($v['value']['state'])) {
- $addressWhere[] = '%' . $v['value']['state'] . '%';
- if (!empty($v['value']['city'])) $addressWhere[] = '%' . $v['value']['city'] . '%';
- if (!empty($v['value']['area'])) $addressWhere[] = '%' . $v['value']['area'] . '%';
- if ($v['condition'] == 'is') {
- $where[$c . $k] = ['like', $addressWhere, 'AND'];
- } else {
- $where[$c . $k] = ['notlike', $addressWhere, 'OR'];
- }
- } elseif (!empty($v['start']) || !empty($v['end'])) {
- if ($v['start'] && $v['end']) {
- $where[$c . $k] = ['between', [$v['start'], $v['end']]];
- } elseif ($v['start']) {
- $where[$c . $k] = ['egt', $v['start']];
- } else {
- $where[$c . $k] = ['elt', $v['end']];
- }
- } elseif (!empty($v['start_date']) || !empty($v['end_date'])) {
- if ($v['start_date'] && $v['end_date']) {
- $where[$c . $k] = ['between', [$v['start_date'], $v['end_date']]];
- } elseif ($v['start_date']) {
- $where[$c . $k] = ['egt', $v['start_date']];
- } else {
- $where[$c . $k] = ['elt', $v['end_date']];
- }
- } elseif (!empty($v['value']) || $v['value'] === '0') {
- if (in_array($k, $check_field_arr)) {
- $where[$c . $k] = field($v['value'], 'contains');
- } else {
- if ($v['condition'] == 'isNot' || $v['condition'] == 'notContains') {
- $where[$c . $k] = [field($v['value'], $v['condition'], $k), ['null'], 'or'];
- } else {
- $where[$c . $k] = field($v['value'], $v['condition'], $k);
- }
- }
- } elseif (in_array($v['condition'], ['isNull', 'isNotNull', 'in'])) {
- $where[$c . $k] = field($v['value'], $v['condition']);
- } else {
- $where[$c . $k] = $v;
- }
- } elseif (!empty($v)) {
- $where[$c . $k] = field($v);
- } else {
- $where[$c . $k] = $v;
- }
- }
- }
-
- # 商机阶段为赢单、输单、无效的值保存在is_end中,将status_id改为is_end;
- if (!empty($where['business.status_id']) && in_array($where['business.status_id'][1], [1, 2, 3])) {
- $where['business.is_end'] = $where['business.status_id'];
- unset($where['business.status_id']);
- }
-
- return $where ?: [];
- }
-
- /**
- * 高级筛选
- *
- * @param array $param 搜索参数
- * @param string $m 模块:crm log work ...
- * @param string $c 栏目:leads customer ...
- * @param string $a 方法:index save ...
- * @return array
- * @since 2021-05-20
- * @author fanqi
- */
- function advancedQuery($param, $m = '', $c = '', $a = '')
- {
- // 结果数据
- $result = [];
- // 原始前缀
- $prefix = $c . '.';
- // 等于(时间段)类型
- $betweenType = [
- 'year', 'lastYear', 'nextYear', 'firstHalfYear', 'nextHalfYear', 'quarter', 'lastQuarter',
- 'nextQuarter', 'month', 'lastMonth', 'nextMonth', 'week', 'lastWeek', 'nextWeek', 'today',
- 'yesterday', 'tomorrow', 'previous7day', 'previous30day', 'future7day', 'future30day'
- ];
- foreach ($param as $key => $value) {
- // 过滤不能参与搜索的字段类型
- if (!empty($value['form_type']) && in_array($value['form_type'], ['file', 'handwriting_sign', 'desc_text', 'detail_table', 'date_interval'])) continue;
- // 初始化前缀
- $c = $prefix;
- // 清除空格
- if (isset($value['condition'])) $value['condition'] = trim($value['condition']);
- // 处理表前缀和字段名称
- list($c, $key) = advancedQueryParam($c, $key, $value['name']);
-
- if ($key == 'check_status' && !is_array($value)) $result[$c . $key] = $value;
- if ($key == 'status_id' && !is_array($value)) $result[$c . $key] = $value;
- if ($key == 'customer_id' && !is_array($value)) $result['customer.' . $key] = $value;
- if ($key == 'contract_id' && !is_array($value)) $result['contract.' . $key] = $value;
- if ($key == 'business_id' && !is_array($value)) $result['business.' . $key] = $value;
-
- // 仪表盘参数
- if (!empty($value['value'][0]) && empty($value['condition'])) {
- $value['condition'] = 'is';
- $value['form_type'] = 'user';
- }
- if (!empty($value['start']) && !empty($value['end'])) {
- $value['value'][0] = date('Y-m-d H:i:s', $value['start']);
- $value['value'][1] = date('Y-m-d H:i:s', $value['end']);
- $value['form_type'] = 'datetime';
- $value['condition'] = 'between';
- }
- if ($key == 'check_status' && !is_array($value)) {
- unset($value);
- $value['value'][0] = '审核通过';
- $value['form_type'] = 'check_status';
- $value['name'] = '审核状态';
- $value['type'] = 'check_status';
- $value['condition'] = 'is';
- }
-
- if (!empty($value['value'][0]) && in_array($value['value'][0], $betweenType)) {
- $value = advancedQueryHandleDate($value);
- }
-
- // 代办事项
- if (isset($value) && !isset($value['condition']) && !isset($value['value']) && !isset($value['form_type'])) {
- $result[$c . $key] = is_array($value) ? $value : ['in', $value];
- continue;
- }
-
- // 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
- if (isset($value['form_type']) && in_array($value['form_type'], ['module', 'check_status', 'deal_status', 'category', 'text', 'textarea', 'mobile', 'email', 'select', 'boolean_value', 'checkbox', 'location', 'website']) || in_array($key, ['create_user_id', 'owner_user_id'])) {
- $result[$c . $key] = advancedQueryFormatForCommon($value['value'], $value['condition'], $value['form_type'], $key);
- }
-
- // 日期、日期时间、数字、货币、百分数、下次联系时间
- if (isset($value['form_type']) && in_array($value['form_type'], ['date', 'datetime', 'number', 'floatnumber', 'percent', 'next_time'])) {
- $result[$c . $key] = advancedQueryFormatForDate($value);
- }
-
- // 地址(固定字段)、地址(自定义字段)
- if (isset($value['form_type']) && in_array($value['form_type'], ['map_address', 'position'])) {
- $result[$c . $key] = advancedQueryFormatForAddress($value['value'], $value['form_type']);
- }
- // 人员、部门
- if (isset($value['form_type']) && in_array($value['form_type'], ['user', 'structure', 'single_user']) && !in_array($key, ['create_user_id', 'owner_user_id']) && $value['type'] != 'team_id') {
- $result[$c . $key] = advancedQueryFormatForPersonnel($value['value'], $value['condition']);
- }
-
- // 商机状态组
- if (isset($value['form_type']) && $value['form_type'] == 'business_type') {
- if (!empty($value['type_id'])) $result[$c . 'type_id'] = ['eq', $value['type_id']];
- if (!empty($value['status_id']) && in_array($value['status_id'], [1, 2, 3])) $result[$c . 'is_end'] = ['eq', $value['status_id']];
- if (!empty($value['status_id']) && !in_array($value['status_id'], [1, 2, 3])) $result[$c . 'status_id'] = ['eq', $value['status_id']];
- }
-
- // 回款计划
- if (isset($value['form_type']) && $value['form_type'] == 'receivables_plan' && !empty($value['value'])) {
- $result[$c . 'plan_id'] = advancedQueryFormatForPlan($value['value']);
- }
- }
- return $result;
- }
-
- /**
- * 处理高级筛选查询前缀、字段名称
- *
- * @param string $prefix 表前缀
- * @param string $field 字段名
- * @param string $name 字段中文名
- * @return array
- * @since 2021-05-22
- * @author fanqi
- */
- function advancedQueryParam($prefix, $field, $name)
- {
- // 要变更的前缀
- $prefixChange = [
- 'customer_name' => 'customer.',
- 'contacts_name' => 'contacts.',
- 'business_name' => 'business.',
- 'contract_name' => 'contract.',
- 'business_id' => 'business.',
- 'contacts_id' => 'contacts.'
- ];
-
- // 处理客户名称、联系人名称、商机名称、合同名称字段
- if (in_array($field, ['customer_name', 'contacts_name', 'business_name', 'contract_name']) && $name != '合同编号') {
- $prefix = $prefixChange[$field];
- $field = 'name';
- }
- // 处理合同下的商机ID、客户ID字段
- if ($prefix == 'contract.' && in_array($field, ['business_id', 'contacts_id'])) {
- $prefix = $prefixChange[$field];
- $field = 'name';
- }
- // 处理回款、回访下的合同编号
- if (in_array($prefix, ['receivables.', 'visit.']) && $name == '合同编号') {
- $prefix = 'contract.';
- $field = 'num';
- }
- // 处理回访下的联系人
- if ($prefix == 'visit.' && $field == 'contacts_id') {
- $prefix = 'contacts.';
- $field = 'name';
- }
-
- return [$prefix, $field];
- }
-
- /**
- * 回款计划查询条件
- *
- * @param array $data 搜索参数
- * @return array
- * @since 2021-05-22
- * @author fanqi
- */
- function advancedQueryFormatForPlan($data)
- {
- $result = [];
-
- $planIds = db('crm_receivables_plan')->whereIn('num', $data)->column('plan_id');
-
- if (!empty($planIds)) $result = ['in', $planIds];
-
- return $result;
- }
-
- /**
- * 地址(固定字段)、地址(自定义字段)查询条件
- *
- * @param array $data 搜索参数
- * @param string $formType 字段类型
- * @return array
- * @since 2021-05-21
- * @author fanqi
- */
- function advancedQueryFormatForAddress($data, $formType)
- {
- if ($formType == 'map_address') $data = implode(chr(10), $data);
- if ($formType == 'position') {
- $data = array_filter(array_column($data[0], 'name'));
- $data = implode(',', $data);
- }
-
- return ['like', '%' . trim($data) . '%'];
- }
-
- /**
- * 人员、部门、回访人查询条件
- *
- * @param array $data 查询参数
- * @param string $condition 查询条件
- * @return array
- */
- function advancedQueryFormatForPersonnel($data, $condition)
- {
- // 处理查询条件
- if ($condition == 'is') $condition = 'contains';
- if ($condition == 'isNot') $condition = 'notContains';
-
- // 处理查询参数
- $data = advancedQueryDataTransform($data, $condition);
-
- // 搜索条件
- return advancedQueryWhere($condition, $data);
- }
-
- /**
- * 日期、日期时间、数字、货币、百分数查询条件
- *
- * @param array $data 搜索参数、类型、条件
- * @return array
- * @since 2021-05-20
- * @author fanqi
- */
- function advancedQueryFormatForDate($data)
- {
- # 转换日期时间类型格式
- if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][0])) $data['value'][0] = strtotime($data['value'][0]);
- if (in_array($data['form_type'], ['datetime', 'next_time']) && !empty($data['value'][1])) $data['value'][1] = strtotime($data['value'][1]);
-
- return advancedQueryWhere($data['condition'], count($data['value']) == 2 ? $data['value'] : $data['value'][0]);
- }
-
- /**
- * 模块、审核状态、成交状态、产品分类、单行文本、多行文本、网址、手机、邮箱、下拉框、布尔值、多选、定位、创建人、负责人
- *
- * @param array $data 要查询的数据
- * @param string $condition 查询方式
- * @param string $formType 字段类型
- * @return array
- * @since 2021-05-20
- * @author fanqi
- */
- function advancedQueryFormatForCommon($data, $condition, $formType, $key)
- {
- // 处理查询方式
- if (in_array($formType, ['checkbox']) && $condition == 'is') $condition = 'contains';
- if (in_array($formType, ['checkbox']) && $condition == 'isNot') $condition = 'notContains';
-
- // 处理查询参数
- if (in_array($condition, ['contains', 'notContains', 'startWith', 'endWith'])) $data = advancedQueryDataTransform($data, $condition);
-
- // 处理回访形式
- if (in_array($key, ['shape', 'satisfaction'])) {
- array_walk($data, function ($value, $key) use (&$data) {
- $data[$key] = $value . "\r";
- });
- }
-
- // 处理审核状态
- if ($formType == 'check_status') {
- $data[0] = str_replace('待审核', 0, $data[0]);
- $data[0] = str_replace('审核中', 1, $data[0]);
- $data[0] = str_replace('审核通过', 2, $data[0]);
- $data[0] = str_replace('审核失败', 3, $data[0]);
- $data[0] = str_replace('已撤回', 4, $data[0]);
- $data[0] = str_replace('未提交', 5, $data[0]);
- $data[0] = str_replace('已作废', 6, $data[0]);
- }
-
- return advancedQueryWhere($condition, $data);
- }
-
- /**
- * 设置搜索条件
- *
- * @param string $condition 查询方式
- * @param string $data 查询数据
- * @return array
- * @since 2021-05-22
- * @author fanqi
- */
- function advancedQueryWhere($condition, $data)
- {
- $result = [];
-
- // NULL(0)不存在、IS(1)等于、IS_NOT(2)不等于、CONTAINS(3)包含、NOT_CONTAINS(4)不包含、IS_NULL(5)为空、IS_NOT_NULL(6)不为空
- // GT(7)大于、EGT(8)大于等于、LT(9)小于、ELT(10)小于等于、ID(11)通过id、PREFIX(12) 前缀匹配、SUFFIX(13) 后缀匹配、RANGE(14) 数字区间
-
- if ($condition == "in") $result = ['in', $data]; // 等于
- if ($condition == 'is') $result = ['in', $data]; // 等于
- if ($condition == 'isNot') $result = ['notin', $data]; // 不等于
- if ($condition == 'contains') $result = ['like', $data, 'OR']; // 包含
- if ($condition == 'notContains') $result = ['notlike', $data, 'AND']; // 不包含
- if ($condition == 'startWith') $result = ['like', $data, 'OR']; // 开始于
- if ($condition == 'endWith') $result = ['like', $data, 'OR']; // 结束于
- if ($condition == 'gt') $result = ['gt', $data]; // 大于
- if ($condition == 'lt') $result = ['lt', $data]; // 小于
- if ($condition == 'egt') $result = ['egt', $data]; // 大于等于
- if ($condition == 'elt') $result = ['elt', $data]; // 小于等于
- if ($condition == 'between') $result = ['between', $data]; // 处于某个时间段
- if ($condition == 'range') $result = ['between', $data]; // 处于某个时间段
- if ($condition == 'isNull') $result = [['eq', ''], ['null'], 'OR']; // 为空
- if ($condition == 'isNotNull') $result = [['neq', ''], ['not null'], 'AND']; // 不为空
-
- return $result;
- }
-
- /**
- * 处理要查询的数据
- *
- * @param array $data 要查询的数据
- * @param string $condition 查询方式
- * @return mixed
- * @since 2021-05-20
- * @author fanqi
- */
- function advancedQueryDataTransform($data, $condition)
- {
- if (in_array($condition, ['contains', 'notContains'])) {
- array_walk($data, function ($value, $key) use (&$data) {
- $data[$key] = '%' . $value . '%';
- });
- }
-
- if ($condition == 'startWith') {
- array_walk($data, function ($value, $key) use (&$data) {
- $data[$key] = $value . '%';
- });
- }
-
- if ($condition == 'endWith') {
- array_walk($data, function ($value, $key) use (&$data) {
- $data[$key] = '%' . $value;
- });
- }
-
- return $data;
- }
-
- /**
- * 等于(时间段)数据处理
- *
- * @param $data
- * @return array
- * @since 2021-06-11
- * @author fanqi
- */
- function advancedQueryHandleDate($data)
- {
- // 本年度
- if ($data['value'][0] == 'year') {
- $data['value'][0] = date('Y-m-d 00:00:00');
- $data['value'][1] = date('Y-m-d 23:59:59');
- }
-
- // 上一年度
- if ($data['value'][0] == 'lastYear') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 year'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 year'));
- }
-
- // 下一年度
- if ($data['value'][0] == 'nextYear') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 year'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 year'));
- }
-
- // 上半年
- if ($data['value'][0] == 'firstHalfYear') {
- $data['value'][0] = date('Y-01-01 00:00:00');
- $data['value'][1] = date('Y-06-30 23:59:59');
- }
-
- // 下半年
- if ($data['value'][0] == 'nextHalfYear') {
- $data['value'][0] = date('Y-07-01 00:00:00');
- $data['value'][1] = date('Y-12-31 23:59:59');
- }
-
- // 本季度
- if ($data['value'][0] == 'quarter') {
- $season = ceil((date('n')) / 3);
- $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
- $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
- }
-
- // 上一季度
- if ($data['value'][0] == 'lastQuarter') {
- $season = ceil((date('n')) / 3) - 1;
- $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y')));
- $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
- }
-
- // 下一季度
- if ($data['value'][0] == 'nextQuarter') {
- $season = ceil((date('n')) / 3);
- $data['value'][0] = date('Y-m-d H:i:s', mktime(0, 0, 0, $season * 3 + 1, 1, date('Y')));
- $data['value'][1] = date('Y-m-d H:i:s', mktime(23, 59, 59, $season * 3 + 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y')));
- }
-
- // 本月
- if ($data['value'][0] == 'month') {
- $data['value'][0] = date('Y-m-01 00:00:00');
- $data['value'][1] = date('Y-m-31 23:59:59');
- }
-
- // 上月
- if ($data['value'][0] == 'lastMonth') {
- $data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '-1 month'));
- $data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '-1 month'));
- }
-
- // 下月
- if ($data['value'][0] == 'nextMonth') {
- $data['value'][0] = date('Y-m-01 00:00:00', strtotime(date('Y-m-d') . '+1 month'));
- $data['value'][1] = date('Y-m-31 23:59:59', strtotime(date('Y-m-d') . '+1 month'));
- }
-
- // 本周
- if ($data['value'][0] == 'week') {
- $data['value'][0] = date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y')));
- $data['value'][1] = date('Y-m-d 23:59:59', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y')));
- }
-
- // 上周
- if ($data['value'][0] == 'lastWeek') {
- $date = date("Y-m-d");
- $w = date("w", strtotime($date));
- $d = $w ? $w - 1 : 6;
- $start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
- $data['value'][0] = date('Y-m-d', strtotime($start . " - 7 days"));
- $data['value'][1] = date('Y-m-d', strtotime($start . " - 1 days"));
- }
-
- // 下周
- if ($data['value'][0] == 'nextWeek') {
- $date = date("Y-m-d");
- $w = date("w", strtotime($date));
- $d = $w ? $w - 1 : 6;
- $start = date("Y-m-d", strtotime($date . " - " . $d . " days"));
- $data['value'][0] = date('Y-m-d', strtotime($start . " + 7 days"));
- $data['value'][1] = date('Y-m-d', strtotime($start . " + 13 days"));
- }
-
- // 今天
- if ($data['value'][0] == 'today') {
- $data['value'][0] = date('Y-m-d 00:00:00');
- $data['value'][1] = date('Y-m-d 23:59:59');
- }
-
- // 昨天
- if ($data['value'][0] == 'yesterday') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-1 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
- }
-
- // 明天
- if ($data['value'][0] == 'tomorrow') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+1 day'));
- }
-
- // 过去7天
- if ($data['value'][0] == 'previous7day') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-7 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
- }
-
- // 过去30天
- if ($data['value'][0] == 'previous30day') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '-30 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '-1 day'));
- }
-
- // 未来7天
- if ($data['value'][0] == 'future7day') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+7 day'));
- }
-
- // 未来30天
- if ($data['value'][0] == 'future30day') {
- $data['value'][0] = date('Y-m-d 00:00:00', strtotime(date('Y-m-d') . '+1 day'));
- $data['value'][1] = date('Y-m-d 23:59:59', strtotime(date('Y-m-d') . '+30 day'));
- }
-
- return $data;
- }
-
- /**
- * 根据搜索生成where条件
- *
- * @param string $search 搜索内容
- * @param $condition 搜索条件
- * @param $k 搜索字段
- * @return array|Closure|string[]
- */
- function field($search, $condition = '', $k = '')
- {
- switch (trim($condition)) {
- case "is" :
- $where = ['in', $search];
- break;
- case "isNot" :
- $where = ['notin', $search];
- break;
- case "contains" :
- $containsWhere = [];
- foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
- $where = ['like', $containsWhere, 'OR'];
- break;
- case "notContains" :
- $containsWhere = [];
- foreach ((array)$search as $key1 => $value1) $containsWhere[] = '%' . $value1 . '%';
- $where = ['notlike', $containsWhere, 'AND'];
- break;
- case "startWith" :
- $startWithWhere = [];
- foreach ((array)$search as $key1 => $value1) $startWithWhere[] = $value1 . '%';
- $where = ['like', $startWithWhere, 'OR'];
- break;
- case "endWith" :
- $endWithWhere = [];
- foreach ((array)$search as $key1 => $value1) $endWithWhere[] = '%' . $value1;
- $where = ['like', $endWithWhere, 'OR'];
- break;
- case "isNull" :
- $where = ['eq', ''];
- break;
- case "isNotNull" :
- $where = ['neq', ''];
- break;
- case "eq" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, $value1);
- }
- };
- break;
- case "neq" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, '<>', $value1);
- }
- };
- break;
- case "gt" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, '>', $value1);
- }
- };
- break;
- case "egt" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, '>=', $value1);
- }
- };
- break;
- case "lt" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, '<', $value1);
- }
- };
- break;
- case "elt" :
- $where = function ($query) use ($search, $k) {
- foreach ((array)$search as $key1 => $value1) {
- $query->whereOr($k, '<=', $value1);
- }
- };
- break;
- case "in" :
- $where = ['in', $search];
- break;
- default :
- $where = ['eq', $search];
- break;
- }
- return $where;
- }
-
- /**
- * 将单个搜索转换为高级搜索格式
- * @param string $value 搜索内容
- * @param $condition 搜索条件
- * @return array
- * @author Michael_xu
- */
- function field_arr($value, $condition = '')
- {
- if (is_array($value)) {
-
- } else {
- $condition = $condition ?: 'eq';
- $where_arr = ['value' => $value, 'condition' => $condition];
- }
-
- return $where_arr;
- }
-
- /**
- * 记录操作日志
- * @param $id array 操作对象id数组
- * @return
- * @author Michael_xu
- */
- function actionLog($id, $join_user_ids = '', $structure_ids = '', $content = '')
- {
- if (!is_array($id)) {
- $idArr[] = $id;
- } else {
- $idArr = $id;
- }
- $header = Request::instance()->header();
- $authKey = $header['authkey'];
- $cache = cache('Auth_' . $authKey);
- if (!$cache) {
- return false;
- }
- $userInfo = $cache['userInfo'];
- $category = $userInfo['id'] == 1 ? '管理员' : '员工';
-
- $request = request();
- $m = strtolower($request->module());
- $c = strtolower($request->controller());
- $a = strtolower($request->action());
-
- $res_action = true;
- foreach ($idArr as $v) {
- $data = [];
- $data['user_id'] = $userInfo['id'];
- $data['module_name'] = $module_name = $m;
- $data['controller_name'] = $controller_name = $c;
- $data['action_name'] = $action_name = $a;
- $data['action_id'] = $v;
- $data['create_time'] = time();
- $data['client_ip'] = request()->ip();
- $data['content'] = $content ?: lang('ACTIONLOG', [$category, $userInfo['realname'], date('Y-m-d H:i:s'), lang($action_name), $v, lang($controller_name)]);
- $data['join_user_ids'] = $join_user_ids ?: ''; //抄送人
- $data['structure_ids'] = $structure_ids ?: ''; //抄送部门
- if ($action_name == 'delete' || $action_name == 'commentdel') {
- $data['action_delete'] = 1;
- }
- if (!db('admin_action_log')->insert($data)) {
- $res_action = false;
- }
-
- # 数据操作日志
- db('admin_operation_log')->insert([
- 'user_id' => $userInfo['id'],
- 'client_ip' => request()->ip(),
- 'module' => $m . '_' . $c,
- 'action_id' => $v,
- 'content' => $content,
- 'create_time' => time()
- ]);
- }
-
- if ($res_action) {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * 判断操作权限
- * @param
- * @return
- * @author Michael_xu
- */
- function checkPerByAction($m, $c, $a)
- {
- /*获取头部信息*/
- $header = Request::instance()->header();
- $authKey = $header['authkey'];
- $cache = cache('Auth_' . $authKey);
- if (!$cache) {
- return false;
- }
- $userInfo = $cache['userInfo'];
- $adminTypes = adminGroupTypes($userInfo['id']);
- if (in_array(1, $adminTypes)) {
- return true;
- }
- if (empty($m) && empty($c) && empty($a)) {
- $request = Request::instance();
- $m = strtolower($request->module());
- $c = strtolower($request->controller());
- $a = strtolower($request->action());
- }
- $authAdapter = new AuthAdapter($authKey);
- $ruleName = $m . '-' . $c . '-' . $a;
- if (!$authAdapter->checkIntime($ruleName, $userInfo['id'])) {
- return false;
- }
- return true;
- }
-
- /**
- * 给树状菜单添加level并去掉没有子菜单的菜单项
- * @param array $data [description]
- * @param integer $root [description]
- * @param string $child [description]
- * @param string $level [description]
- */
- function memuLevelClear($data, $root = 1, $child = 'children', $level = 'level')
- {
- if (is_array($data)) {
- foreach ($data as $key => $val) {
- // $data[$key]['selected'] = false;
- $data[$key]['level'] = $root;
- if (!empty($val[$child]) && is_array($val[$child])) {
- $data[$key][$child] = memuLevelClear($val[$child], $root + 1);
- } else if ($root < 3 && $data[$key]['menu_type'] == 1) {
- unset($data[$key]);
- }
- if (empty($data[$key][$child]) && ($data[$key]['level'] == 1) && ($data[$key]['menu_type'] == 1)) {
- unset($data[$key]);
- }
- }
- return array_values($data);
- }
- return array();
- }
-
- /**
- * [rulesDeal 给树状规则表处理成 module-controller-action ]
- * @AuthorHTL
- * @DateTime
- * @param [array] $data [树状规则数组]
- * @return [array] [返回数组]
- */
- function rulesDeal($data)
- {
- if (is_array($data)) {
- $ret = [];
- foreach ($data as $k1 => $v1) {
- $str1 = $v1['name'];
- if (is_array($v1['children'])) {
- foreach ($v1['children'] as $k2 => $v2) {
- $str2 = $str1 . '-' . $v2['name'];
- if (is_array($v2['children'])) {
- foreach ($v2['children'] as $k3 => $v3) {
- $str3 = $str2 . '-' . $v3['name'];
- $ret[] = $str3;
- }
- } else {
- $ret[] = $str2;
- }
- }
- } else {
- $ret[] = $str1;
- }
- }
- return $ret;
- }
- return [];
- }
-
- /**
- * 获取下属userId
- * @param $self == true 包含自己
- * @param $type == 0 下属userid
- * @param $type == 1 全部userid
- * @param $user_id 需要查询的user_id
- * @author Michael_xu
- */
- function getSubUserId($self = true, $type = 0, $user_id = '')
- {
- $request = Request::instance();
- $header = $request->header();
- $authKey = $header['authkey'];
- $cache = cache('Auth_' . $authKey);
- if (!$user_id) {
- if (!$cache) {
- return false;
- }
- $userInfo = $cache['userInfo'];
- $user_id = $userInfo['id'];
- $adminTypes = adminGroupTypes($user_id);
-
- if (in_array(1, $adminTypes)) {
- $type = 1;
- }
- }
- $belowIds = [];
- if (empty($type)) {
-
- if ($user_id) {
- $belowIds = getSubUser($user_id);
- }
- } else {
- $belowIds = getSubUser(0);
- }
- if ($self == true) {
- $belowIds[] = $user_id;
- } else {
- $belowIds = $belowIds ? array_diff($belowIds, array($user_id)) : [];
- }
- return array_unique($belowIds);
- }
-
- /**
- * 获取下属userId
- * @author Michael_xu
- */
- function getSubUser($userId, $queried = [], $allUserList = [])
- {
- if (empty($allUserList)) {
- $allUserList = db('admin_user')->field('id,parent_id')->select();
- }
- foreach ($allUserList as $k => $v) {
- if ($v['parent_id'] == $userId) {
- $sub_user[] = $v['id'];
- }
- }
- if ($sub_user) {
- foreach ($sub_user as $v) {
- if (in_array($v, $queried)) {
- continue;
- }
- $queried[] = $v;
- $son_user = [];
- $son_user = getSubUser($v, $queried, $allUserList);
- if (!empty($son_user)) {
- $sub_user = array_merge($sub_user, $son_user);
- }
- }
- }
- return $sub_user;
- }
-
- /**
- * 阿里大于短信发送
- * @param unknown $appkey
- * @param unknown $secret
- * @param unknown $signName 短信签名
- * @param unknown $smsParam
- * @param unknown $templateCode 短信模板
- * @param unknown $send_mobile 接收手机号
- * @param unknown $code 短信验证码
- * @param unknown $template_code 模板参数
- */
- function aliSmsSend($send_mobile, $code, $signName, $templateCode)
- {
- $appkey = '';
- $secret = '';
- import('alimsg.api.Sms', EXTEND_PATH);
- header('Content-Type: text/plain; charset=utf-8');
- $sms = new Sms($appkey, $secret);
- $template_code = array("code" => $code);
- $response = $sms->sendSms($signName, $templateCode, $send_mobile, $template_code);
- $data = object_to_array($response);
- if ($data['Message'] == 'OK' && $data['Code'] == "OK") {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * 发送邮件
- * @param unknown $toemail
- * @param unknown $title
- * @param unknown $content
- * @return boolean
- */
- function emailSend($email_host, $email_id, $email_pass, $email_addr, $toemail, $title, $content)
- {
- $result = false;
- try {
- $mail = new Email();
- $mail->setServer($email_host, $email_id, $email_pass);
- $mail->setFrom($email_addr);
- $mail->setReceiver($toemail);
- $mail->setMailInfo($title, $content);
- $result = $mail->sendMail();
- } catch (\Exception $e) {
- $result = false;
- }
- return $result;
- }
-
- /**
- * 发送站内信
- * @param $user_id 接收人user_id
- * @param $action_id 操作id
- * @param $sysMessage 1为系统消息
- * @param $content 消息内容
- * @return
- * @author Michael_xu
- */
- function sendMessage($user_id, $content, $action_id, $sysMessage = 0)
- {
- $content = trim($content);
- if (!$user_id) return false;
- if (!$content) return false;
- if (!is_array($user_id)) {
- $user_ids[] = $user_id;
- } else {
- $user_ids = $user_id;
- }
- $user_ids = array_unique(array_filter($user_ids));
- $request = request();
- $m = strtolower($request->module());
- $c = strtolower($request->controller());
- $a = strtolower($request->action());
-
- $userInfo = [];
- if ($sysMessage == 0) {
- $header = $request->header();
- $authkey = $header['authkey'];
- $cache = cache('Auth_' . $authkey);
- if (!$cache) {
- return false;
- }
- $userInfo = $cache['userInfo'];
- }
- foreach ($user_ids as $v) {
- $data = [];
- $data['content'] = $content;
- $data['from_user_id'] = $userInfo['id'] ?: 0;
- $data['to_user_id'] = $v;
- $data['read_time'] = 0;
- $data['send_time'] = time();
- $data['module_name'] = $m;
- $data['controller_name'] = $c;
- $data['action_name'] = $a;
- $data['action_id'] = $action_id;
- db('admin_message')->insert($data);
- }
- return true;
- }
-
- /**
- * 格式化字节大小
- * @param number $size 字节数
- * @param string $delimiter 数字和单位分隔符
- * @return string 格式化后的带单位的大小
- * @author
- */
- function format_bytes($size, $delimiter = '')
- {
- $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
- for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
- return round($size, 2) . $delimiter . $units[$i];
- }
-
- /**
- * 数据修改日志
- * @param $types 类型
- * @param $action_id 操作ID
- * @param $newData 新数据
- * @param $newData 新数据
- * @return
- * @author Michael_xu
- */
- function updateActionLog($user_id, $types, $action_id, $oldData = [], $newData = [], $content = '')
- {
- # 转格式
- if (!empty($oldData['next_time']) && $oldData['next_time'] != strtotime($oldData['next_time'])) {
- $oldData['next_time'] = strtotime($oldData['next_time']);
- }
-
- if (is_array($oldData) && is_array($newData) && $user_id) {
- $differentData = array_diff_assoc($newData, $oldData);
- $fieldModel = new FieldModel();
- $userModel = new UserModel();
- $structureModel = new \app\admin\model\Structure();
- $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
- $newFieldArr = array();
- foreach ($field_arr as $k => $v) {
- $newFieldArr[$v['field']] = $v;
- }
- $unField = ['update_time', 'create_time']; //定义过滤字段
- $message = [];
- $un_form_type = ['file', 'form'];
- foreach ($differentData as $k => $v) {
- if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
- $field_name = '';
- $field_name = $newFieldArr[$k]['name'];
- $new_value = $v ?: '空';
- $old_value = $oldData[$k] ?: '空';
- if ($newFieldArr[$k]['form_type'] == 'datetime') {
- $new_value = $v ? date('Y-m-d', $v) : '空';
- $old_value = !empty($oldData[$k]) ? date('Y-m-d', $oldData[$k]) : '空';
- if (empty($v) && empty($oldData[$k])) continue;
- } elseif ($newFieldArr[$k]['form_type'] == 'user') {
- $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
- $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'structure') {
- $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
- $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'business_status') {
- $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'business_type') {
- $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'customer') {
- $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'category') {
- $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'business') {
- $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
- } elseif ($newFieldArr[$k]['field'] == 'check_status') {
- $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
- $new_value = $statusArr[$v];
- $old_value = $statusArr[$oldData[$k]];
- } elseif ($newFieldArr[$k]['form_type'] == 'visit') {
- $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
- $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'single_user') {
- $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
- $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
- } elseif ($newFieldArr[$k]['form_type'] == 'floatnumber') {
- $new_value = $v ? number_format($v, 2) : '';
- }
- if ($old_value != $new_value) {
- $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
- }
- }
- }
- if ($message) {
- $data = [];
- $data['user_id'] = $user_id;
- $data['create_time'] = time();
- $data['types'] = $types;
- $data['action_id'] = $action_id;
- $data['content'] = implode('.|.', $message);
- db('admin_action_record')->insert($data);
- }
- } elseif ($content) {
- $data = [];
- $data['user_id'] = $user_id;
- $data['create_time'] = time();
- $data['types'] = $types;
- $data['action_id'] = $action_id;
- $data['content'] = $content;
- db('admin_action_record')->insert($data);
- }
- }
-
- /**
- * 截取字符串
- * @param $start 开始截取位置
- * @param $length 截取长度
- * @return
- * @author Michael_xu
- */
- function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
- {
- if (function_exists("mb_substr")) {
- $slice = mb_substr($str, $start, $length, $charset);
- } elseif (function_exists('iconv_substr')) {
- $slice = iconv_substr($str, $start, $length, $charset);
- if (false === $slice) {
- $slice = '';
- }
- } else {
- $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
- $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
- $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
- $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
- preg_match_all($re[$charset], $str, $match);
- $slice = join("", array_slice($match[0], $start, $length));
- }
- if (utf8_strlen($str) < $length) $suffix = false;
- return $suffix ? $slice . '...' : $slice;
- }
-
- function utf8_strlen($string = null)
- {
- preg_match_all("/./us", $string, $match);
- return count($match[0]);
- }
-
- /**
- * 合法性验证
- * @param client_sign 签名参数值,使用相同规则对提交参数进行加密验证
- * @return
- * @author Michael_xu
- */
- function checkVerify($saftCode = '5kcrm@')
- {
- $parmList = Request::instance()->post();
- $header = $request->header();
- $parmList['sessionId'] = $header['sessionId'];
- $authkey = $header['authKey'];
- $clientSign = $parmList['client_sign'];
-
- if ($clientSign) {
- unset($parmList['client_sign']);
- if (count($parmList) > 0) {
- // 对要签名参数按照签名格式组合
- foreach ($parmList as $key => $value) {
- if (isset($_POST[$key])) {
- $parame[$key] = $key . '=' . trim($_POST[$key]);
- } else {
- return false;
- }
- }
- ksort($parame); //参数排序
- $returnValue = implode("&", $parame); //拼接字符串
- if ($returnValue) {
- //base64加密
- $signCalc = base64_encode(hash_hmac("sha1", $returnValue, $saftCode . $authkey, $raw_output = false));
- // 检查参数签名是否一致
- if (trim($clientSign) != trim($signCalc)) {
- return false;
- } else {
- return true;
- }
- } else {
- return false;
- }
- } else {
- return false;
- }
- } else {
- //签名认证错误
- return false;
- }
- }
-
- /**
- * 数组转换字符串(以逗号隔开)
- * @param
- * @return
- * @author Michael_xu
- */
- function arrayToString($array)
- {
- if (!is_array($array)) {
- $data_arr[] = $array;
- } else {
- $data_arr = $array;
- }
- $data_arr = array_filter($data_arr); //数组去空
- $data_arr = array_unique($data_arr); //数组去重
- $data_arr = array_merge($data_arr);
- $string = $data_arr ? ',' . implode(',', $data_arr) . ',' : '';
- return $string ?: '';
- }
-
- /**
- * 字符串转换数组(以逗号隔开)
- * @param
- * @return
- * @author Michael_xu
- */
- function stringToArray($string)
- {
- if (is_array($string)) {
- $data_arr = array_unique(array_filter($string));
- } else {
- $data_arr = $string ? array_unique(array_filter(explode(',', $string))) : [];
- }
- $data_arr = $data_arr ? array_merge($data_arr) : [];
- return $data_arr ?: [];
- }
-
- /**
- * 根据时间戳获取星期几
- * @param $time 要转换的时间戳
- */
- function getTimeWeek($time, $i = 0)
- {
- $weekarray = array("日", "一", "二", "三", "四", "五", "六");
- $oneD = 24 * 60 * 60;
- return "星期" . $weekarray[date("w", $time + $oneD * $i)];
- }
-
- /**
- * 二维数组排序(选择)
- * @param $select 要进行排序的select结果集
- * @param $field 排序的字段
- * @param $order 排序方式1降序2升序
- */
- function sort_select($select = array(), $field, $order = 1)
- {
- $count = count($select);
- if ($order == 1) {
- for ($i = 0; $i < $count; $i++) {
- $k = $i;
- for ($j = $i; $j < $count; $j++) {
- if ($select[$k][$field] < $select[$j][$field]) {
- $k = $j;
- }
- }
- $temp = $select[$i];
- $select[$i] = $select[$k];
- $select[$k] = $temp;
- }
- return $select;
- } else {
- for ($i = 0; $i < $count; $i++) {
- $k = $i;
- for ($j = $i; $j < $count; $j++) {
- if ($select[$k][$field] > $select[$j][$field]) {
- $k = $j;
- }
- }
- $temp = $select[$i];
- $select[$i] = $select[$k];
- $select[$k] = $temp;
- }
- return $select;
- }
- }
-
- /**
- * 将秒数转换为时间 (年、天、小时、分、秒)
- * @param
- */
- function getTimeBySec($time)
- {
- if (is_numeric($time)) {
- $value = array(
- "years" => 0, "days" => 0, "hours" => 0,
- "minutes" => 0, "seconds" => 0,
- );
- if ($time >= 31556926) {
- $value["years"] = floor($time / 31556926);
- $time = ($time % 31556926);
- $t .= $value["years"] . "年";
- }
- if ($time >= 86400) {
- $value["days"] = floor($time / 86400);
- $time = ($time % 86400);
- $t .= $value["days"] . "天";
- }
- if ($time >= 3600) {
- $value["hours"] = floor($time / 3600);
- $time = ($time % 3600);
- $t .= $value["hours"] . "小时";
- }
- if ($time >= 60) {
- $value["minutes"] = floor($time / 60);
- $time = ($time % 60);
- $t .= $value["minutes"] . "分钟";
- }
- if ($time < 60) {
- $value["seconds"] = floor($time);
- $t .= $value["seconds"] . "秒";
- }
- return $t;
- } else {
- return (bool)FALSE;
- }
- }
-
- /*
- *根据年月计算有几天
- */
- function getmonthByYM($param)
- {
- $month = $param['month'] ? $param['month'] : date('m', time());
- $year = $param['year'] ? $param['year'] : date('Y', time());
- if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
- $days = '31';
- } elseif ($month == 2) {
- if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
- //判断是否是闰年
- $days = '29';
- } else {
- $days = '28';
- }
- } else {
- $days = '30';
- }
- return $days;
- }
-
- /**
- * 根据时间戳计算当月天数
- * @param
- */
- function getmonthdays($time)
- {
- $month = date('m', $time);
- $year = date('Y', $time);
- if (in_array($month, array('1', '3', '5', '7', '8', '01', '03', '05', '07', '08', '10', '12'))) {
- $days = '31';
- } elseif ($month == 2) {
- if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0)) {
- //判断是否是闰年
- $days = '29';
- } else {
- $days = '28';
- }
- } else {
- $days = '30';
- }
- return $days;
- }
-
- /**
- * 生成从开始时间到结束时间的日期数组
- * @param type,默认时间戳格式
- * @param type = 1 时,date格式
- * @param type = 2 时,获取每日开始、结束时间
- */
- function dateList($start, $end, $type = 0)
- {
- if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
- $i = 0;
- //从开始日期到结束日期的每日时间戳数组
- $d = array();
- if ($type == 1) {
- while ($start <= $end) {
- $d[$i] = date('Y-m-d', $start);
- $start = $start + 86400;
- $i++;
- }
- } else {
- while ($start <= $end) {
- $d[$i] = $start;
- $start = $start + 86400;
- $i++;
- }
- }
- if ($type == 2) {
- $list = array();
- foreach ($d as $k => $v) {
- $list[$k] = getDateRange($v);
- }
- return $list;
- } else {
- return $d;
- }
- }
-
- /**
- * 获取指定日期开始时间与结束时间
- */
- function getDateRange($timestamp)
- {
- $ret = array();
- $ret['sdate'] = strtotime(date('Y-m-d', $timestamp));
- $ret['edate'] = strtotime(date('Y-m-d', $timestamp)) + 86400;
- return $ret;
- }
-
- /**
- * 生成从开始月份到结束月份的月份数组
- * @param int $start 开始时间戳
- * @param int $end 结束时间戳
- */
- function monthList($start, $end)
- {
- if (!is_numeric($start) || !is_numeric($end) || ($end <= $start)) return '';
- $start = date('Y-m', $start);
- $end = date('Y-m', $end);
- //转为时间戳
- $start = strtotime($start . '-01');
- $end = strtotime($end . '-01');
- $i = 0;
- $d = array();
- while ($start <= $end) {
- //这里累加每个月的的总秒数 计算公式:上一月1号的时间戳秒数减去当前月的时间戳秒数
- $d[$i] = $start;
- $start += strtotime('+1 month', $start) - $start;
- $i++;
- }
- return $d;
- }
-
- /**
- * 人民币转大写
- * @param
- */
- function cny($ns)
- {
- static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
- $cnyunits = array("圆", "角", "分"),
- $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");
- list($ns1, $ns2) = explode(".", $ns, 2);
- $ns2 = array_filter(array($ns2[1], $ns2[0]));
- $ret = array_merge($ns2, array(implode("", _cny_map_unit(str_split($ns1), $grees)), ""));
- $ret = implode("", array_reverse(_cny_map_unit($ret, $cnyunits)));
- return str_replace(array_keys($cnums), $cnums, $ret);
- }
-
- function _cny_map_unit($list, $units)
- {
- $ul = count($units);
- $xs = array();
- foreach (array_reverse($list) as $x) {
- $l = count($xs);
- if ($x != "0" || !($l % 4)) {
- $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
- } else {
- $n = is_numeric($xs[0][0]) ? $x : '';
- }
- array_unshift($xs, $n);
- }
- return $xs;
- }
-
- /**
- * 根据类型获取上一类型时间戳数组
- */
- function getLstTimeByType($type = 'today')
- {
- switch ($type) {
- case 'yesterday' :
- $timeArr = Time::yesterday();
- break;
- case 'week' :
- $timeArr = Time::week();
- break;
- case 'lastWeek' :
- $timeArr = Time::lastWeek();
- break;
- case 'month' :
- $timeArr = Time::month();
- break;
- case 'lastMonth' :
- $timeArr = Time::lastMonth();
- break;
- case 'quarter' :
- //本季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- break;
- case 'lastQuarter' :
- //上季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $year = date('Y') - 1;
- $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
- $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- break;
- case 'year' :
- $timeArr = Time::year();
- break;
- case 'lastYear' :
- $timeArr = Time::lastYear();
- break;
- default :
- $timeArr = Time::today();
- break;
- }
- return $timeArr;
- }
-
-
- /**
- * 根据类型获取开始结束时间戳数组
- * @param
- */
- function getTimeByType($type = 'today', $is_last = false)
- {
- $lastArr = [];
- switch ($type) {
- case 'yesterday' :
- $timeArr = Time::yesterday();
- break;
- case 'week' :
- $timeArr = Time::week();
- break;
- case 'lastWeek' :
- $timeArr = Time::lastWeek();
- break;
- case 'month' :
- $timeArr = Time::month();
- break;
- case 'lastMonth' :
- $timeArr = Time::lastMonth();
- break;
- case 'quarter' :
- //本季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- break;
- case 'lastQuarter' :
- //上季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $year = date('Y') - 1;
- $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
- $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- break;
- case 'year' :
- $timeArr = Time::year();
- break;
- case 'lastYear' :
- $timeArr = Time::lastYear();
- break;
- default :
- $timeArr = Time::today();
- break;
- }
- if ($is_last) {
- return $lastArr;
- } else {
- return $timeArr;
- }
- }
-
- /**
- * 服务器附件完整路径处理
- * @param
- */
- function getFullPath($path)
- {
- if ($path) {
- $protocol = strpos(strtolower($_SERVER['HTTP_REFERER']), 'https') === false ? 'http' : 'https';
- return $protocol . '://' . $_SERVER['HTTP_HOST'] . substr($_SERVER["SCRIPT_NAME"], 0, -10) . substr(str_replace(DS, '/', $path), 1);
- } else {
- return '';
- }
- }
-
- /*取得文件后缀*/
- function getExtension($filename)
- {
- $mytext = substr($filename, strrpos($filename, '.') + 1);
- return $mytext;
- }
-
- /**
- * 生成编号
- * @param prefix 前缀
- * @return
- * @author Michael_xu
- */
- function prefixNumber($prefix, $number_id = 0, $str = 5)
- {
- return $prefixNumber = $prefix . str_pad($number_id, $str, 0, STR_PAD_LEFT); //填充字符串的左侧(将字符串填充为新的长度)
- }
-
- /**
- * curl 模拟GET请求
- * @author lee
- ***/
- function curl_get($url)
- {
- //初始化
- $ch = curl_init();
- //设置抓取的url
- curl_setopt($ch, CURLOPT_URL, $url);
- //设置获取的信息以文件流的形式返回,而不是直接输出。
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // https请求 不验证hosts
- //执行命令
- $output = curl_exec($ch);
- curl_close($ch); //释放curl句柄
- return $output;
- }
-
- /**
- * 地址坐标转换
- * @param prefix 前缀
- * @return
- * @author Michael_xu
- */
- function get_lng_lat($address)
- {
- $map_ak = config('map_ak');
- $url = "http://api.map.baidu.com/geocoder/v2/?address=$address&output=json&ak=$map_ak&callback=showLocation";
- $ret_script = curl_get($url);
- preg_match_all("/\{.*?\}}/is", $ret_script, $matches);
- $ret_arr = json_decode($matches[0][0], true);
- if ($ret_arr['status'] == 0) { //成功
- $location['lng'] = $ret_arr['result']['location']['lng'];
- $location['lat'] = $ret_arr['result']['location']['lat'];
- return $location;
- } else {
- return false;
- }
- }
-
- /**
- * 导出数据为excel表格
- * @param $data 一个二维数组,结构如同从数据库查出来的数组
- * @param $title excel的第一行标题,一个数组,如果为空则没有标题
- * @param $filename 下载的文件名
- * @param exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
- */
- function exportexcel($data = array(), $title = array(), $filename = 'report')
- {
- header("Content-type:application/octet-stream");
- header("Accept-Ranges:bytes");
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:attachment;filename=" . $filename . ".xls");
- header("Pragma: no-cache");
- header("Expires: 0");
- //导出xls 开始
- if (!empty($title)) {
- foreach ($title as $k => $v) {
- $title[$k] = iconv("UTF-8", "GB2312", $v);
- }
- $title = implode("\t", $title);
- echo "$title\n";
- }
- if (!empty($data)) {
- foreach ($data as $key => $val) {
- foreach ($val as $ck => $cv) {
- $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
- }
- $data[$key] = implode("\t", $data[$key]);
- }
- echo implode("\n", $data);
- }
- }
-
- //根据数据库查询出来数组获取某个字段拼接字符串
- function getFieldArray($array = array(), $field = '')
- {
- if (is_array($array) && $field) {
- $ary = array();
- foreach ($array as $value) {
- $ary[] = $value[$field];
- }
- $str = implode(',', $ary);
- return $str;
- } else {
- return false;
- }
- }
-
- /**
- * 检查该字段若必填,加上"*"
- * @param is_null 是否为空 0否 1是
- * @param name 字段名称
- **/
- function sign_required($is_null, $name)
- {
- if ($is_null == 1) {
- return '*' . $name;
- } else {
- return $name;
- }
- }
-
- /**
- * [获取是否有管理员角色 adminGroupTypes]
- * @param user_id 当前人ID
- * @return
- */
- function adminGroupTypes($user_id)
- {
- $userModel = new UserModel();
- $groupsArr = $userModel->get($user_id)->groups;
- $groupids = [];
- if ($groupsArr) {
- foreach ($groupsArr as $key => $val) {
- $groupids[] = $val['id'];
- }
- }
- $types = db('admin_group')->where(['id' => ['in', $groupids]])->group('types')->column('types');
- if ($user_id == 1) {
- $types[] = 1;
- }
- return $types ?: [];
- }
-
- /**
- * [权限数组]
- * @param ruleIds 当前人权限id
- * @return
- */
- function rulesListToArray($rulesList, $ruleIds = [])
- {
- $newList = [];
- if (!is_array($rulesList)) {
- return array();
- } else {
- foreach ($rulesList as $k => $v) {
- if (!is_array($v['children'])) continue;
- foreach ($v['children'] as $k1 => $v1) {
- if (!is_array($v1['children'])) continue;
- foreach ($v1['children'] as $k2 => $v2) {
- $check = false;
- if (in_array($v2['id'], $ruleIds)) {
- $check = true;
- }
- $newList[$v['name']][$v1['name']][$v2['name']] = $check;
- }
- }
- }
- }
- return $newList ?: [];
- }
-
- /**
- * [获取下一审批信息 nextCheckData]
- * @param user_id 审批申请人ID
- * @param flow_id 审批流ID
- * @param types 关联对象
- * @param types_id 联对象ID
- * @param order_id 审批排序ID
- * @return
- */
- function nextCheckData($user_id, $flow_id, $types, $types_id, $order_id, $check_user_id)
- {
- $new_order_id = $order_id;
- $max_order_id = db('admin_examine_step')->where(['flow_id' => $flow_id])->max('order_id'); //审批流最大排序ID
- $examineStepModel = new \app\admin\model\ExamineStep();
-
- $stepInfo = $examineStepModel->getStepByOrder($flow_id, $new_order_id); //审批步骤
- $next_user_ids = [];
- $is_end = 0; //审批结束
- //固定流程(status 1负责人主管,2指定用户(任意一人),3指定用户(多人会签),4上一级审批人主管)
-
- //当前步骤审批人user_id
- $step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
- if ($step_user_ids) {
- if (!$order_id) {
- //创建时使用
- $sub_user_ids = stringToArray($step_user_ids);
- } else {
- if ($stepInfo['status'] == 3) {
- //会签(并关系)
- //当前步骤已审批user_id
- $check_user_ids = $examineStepModel->getUserByCheck($types, $types_id, $new_order_id);
- $user_ids[] = $check_user_id;
- $check_user_ids = $check_user_ids ? array_merge($check_user_ids, $user_ids) : $user_ids;
- //剩余审批人user_id
- $sub_user_ids = $check_user_ids ? array_diff(explode(',', $step_user_ids), $check_user_ids) : $step_user_ids;
- $sub_user_ids = array_unique(array_filter($sub_user_ids));
- if (!$sub_user_ids) {
- $is_end = 1;
- }
- } else {
- $is_end = 1;
- }
- }
- } else {
- $is_end = 1;
- }
- if ($is_end == 1) {
- $next_order_id = $new_order_id + 1;
- } else {
- $next_order_id = $new_order_id;
- }
- //当前审批步骤已结束
- if ($is_end == 1) {
- //当前审批流程是否结束
- $stepInfo = $examineStepModel->getStepByOrder($flow_id, $next_order_id); //审批步骤
- $next_step_user_ids = $examineStepModel->getUserByStep($stepInfo['step_id'], $user_id);
- $next_user_ids = stringToArray($next_step_user_ids);
- } else {
- $next_user_ids = array_unique(array_filter($sub_user_ids));
- }
- if (!$next_user_ids && $next_order_id <= $max_order_id) {
- $newRes = [];
- $newRes = nextCheckData($user_id, $flow_id, $types, $types_id, $next_order_id, $check_user_id);
- $next_user_ids = $newRes['next_user_ids'];
- }
- $data = [];
- $data['order_id'] = ($next_order_id <= $max_order_id) ? $next_order_id : $max_order_id;
- $data['next_user_ids'] = $next_user_ids ?: '';
- return $data;
- }
-
- /**
- * 解析获取php.ini 的upload_max_filesize(单位:byte)
- * @param $dec int 小数位数
- * @return float (单位:byte)
- * */
- function get_upload_max_filesize_byte($dec = 2)
- {
- $max_size = ini_get('upload_max_filesize');
- preg_match('/(^[0-9\.]+)(\w+)/', $max_size, $info);
- $size = $info[1];
- $suffix = strtoupper($info[2]);
- $a = array_flip(array("B", "KB", "MB", "GB", "TB", "PB"));
- $b = array_flip(array("B", "K", "M", "G", "T", "P"));
- $pos = $a[$suffix] && $a[$suffix] !== 0 ? $a[$suffix] : $b[$suffix];
- return round($size * pow(1024, $pos), $dec);
- }
-
- /**
- * 模拟post进行url请求
- * @param string $url
- * @param string $param
- */
- function curl_post($url = '', $post = array())
- {
- $curl = curl_init(); // 启动一个CURL会话
- curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
- curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
- curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
- curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
- curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
- curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
- curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
- curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
- $res = curl_exec($curl); // 执行操作
- if (curl_errno($curl)) {
- echo 'Errno' . curl_error($curl);//捕抓异常
- }
- curl_close($curl); // 关闭CURL会话
- return $res; // 返回数据,json格式
- }
-
- /**
- * 输出json字符串,用于接口调试
- *
- * @return void
- * @author ymob
- */
- function vdd()
- {
- header('Content-Type: text/json; charset=utf-8');
- $args = func_get_args();
- foreach ($args as &$val) {
- if ($val instanceof think\Model) {
- $val = $val->getLastSql();
- }
- }
- if (count($args) < 2) {
- $args = array_shift($args);
- }
- die(json_encode($args));
- }
-
-
- /**
- * 根据时间查询参数返回时间条件 (用于统计分析模块)
- *
- * @param array $where
- * @param string $field
- * @return void
- * @author ymob
- */
- function getWhereTimeByParam(&$where, $field = 'create_time')
- {
- $param = request()->param();
- if (empty($param['type']) && empty($param['start_time'])) {
- $param['type'] = 'month';
- }
- if (!empty($param['start_time'])) {
- $where[$field] = ['between', [$param['start_time'], $param['end_time']]];
- } else {
- $timeRange = getTimeByType($param['type']);
- if ($timeRange) {
- $where[$field] = ['between', [$timeRange[0], $timeRange[1]]];
- }
- }
- }
-
- /**
- * 根据员工、部门查询参数返回员工、部门条件 (用于统计分析模块)
- *
- * @param array $where
- * @param string $field
- * @param string $m
- * @param string $c
- * @param string $a
- * @return void
- * @author ymob
- */
- function getWhereUserByParam(&$where, $field = 'owner_user_id', $m = '', $c = '', $a = '')
- {
- $param = request()->param();
- $userModel = new UserModel();
-
- $map_user_ids = [];
- if ($param['user_id']) {
- $map_user_ids = array($param['user_id']);
- } elseif ($param['structure_id']) {
- $map_user_ids = $userModel->getSubUserByStr($param['structure_id'], 2);
- } else {
- $map_user_ids = $userModel->getUserByPer($m, $c, $a);
- $where[$field] = array('in', $map_user_ids);
- return;
- }
-
- $perUserIds = $userModel->getUserByPer($m, $c, $a); //权限范围内userIds
- $userIds = array_intersect($map_user_ids, $perUserIds); //数组交集
- $where[$field] = array('in', $userIds);
- }
-
- /**
- * 获取客户浏览器类型
- */
- function getBrowser()
- {
- $Browser = $_SERVER['HTTP_USER_AGENT'];
- if (preg_match('/MSIE/i', $Browser)) {
- $Browser = 'MSIE';
- } elseif (preg_match('/Firefox/i', $Browser)) {
- $Browser = 'Firefox';
- } elseif (preg_match('/Chrome/i', $Browser)) {
- $Browser = 'Chrome';
- } elseif (preg_match('/Safari/i', $Browser)) {
- $Browser = 'Safari';
- } elseif (preg_match('/Opera/i', $Browser)) {
- $Browser = 'Opera';
- } else {
- $Browser = 'Other';
- }
- return $Browser;
- }
-
- /**
- * 获取客户端系统
- */
- function getOS()
- {
- $agent = $_SERVER['HTTP_USER_AGENT'];
- if (preg_match('/win/i', $agent)) {
- if (preg_match('/nt 6.1/i', $agent)) {
- $OS = 'Windows 7';
- } else if (preg_match('/nt 6.2/i', $agent)) {
- $OS = 'Windows 8';
- } else if (preg_match('/nt 10.0/i', $agent)) {
- $OS = 'Windows 10';
- } else {
- $OS = 'Windows';
- }
- } elseif (preg_match('/mac/i', $agent)) {
- $OS = 'MAC';
- } elseif (preg_match('/linux/i', $agent)) {
- $OS = 'Linux';
- } elseif (preg_match('/unix/i', $agent)) {
- $OS = 'Unix';
- } elseif (preg_match('/bsd/i', $agent)) {
- $OS = 'BSD';
- } else {
- $OS = 'Other';
- }
- return $OS;
- }
-
- /**
- * 根据IP获取地址
- */
- function getAddress($ip)
- {
- $res = file_get_contents("http://ip.360.cn/IPQuery/ipquery?ip=" . $ip);
- $res = json_decode($res, 1);
- if ($res && $res['errno'] == 0) {
- return explode("\t", $res['data'])[0];
- } else {
- return '';
- }
- }
-
- /**
- * 下载服务器文件
- *
- * @param string $file 文件路径
- * @param string $name 下载名称
- * @param boolean $del 下载后删除
- * @return void
- * @author Ymob
- */
- function download($file, $name = '', $del = false)
- {
- if (!file_exists($file)) {
- return resultArray([
- 'error' => '文件不存在',
- ]);
- }
- // 仅允许下载 public 目录下文件
- $res = strpos(realpath($file), realpath('./public'));
- if ($res !== 0) {
- return resultArray([
- 'error' => '文件路径错误',
- ]);
- }
-
- $fp = fopen($file, 'r');
- $size = filesize($file);
-
- //下载文件需要的头
- header("Content-type: application/octet-stream");
- header("Accept-Ranges: bytes");
- header('ResponseType: blob');
- header("Accept-Length: $size");
- $file_name = $name != '' ? $name : pathinfo($file, PATHINFO_BASENAME);
- // urlencode 处理中文乱码
- header("Content-Disposition:attachment; filename=" . urlencode($file_name));
-
- // 导出数据时 csv office Excel 需要添加bom头
- if (pathinfo($file, PATHINFO_EXTENSION) == 'csv') {
- echo "\xEF\xBB\xBF"; // UTF-8 BOM
- }
-
- $fileCount = 0;
- $fileUnit = 1024;
- while (!feof($fp) && $size - $fileCount > 0) {
- $fileContent = fread($fp, $fileUnit);
- echo $fileContent;
- $fileCount += $fileUnit;
- }
- fclose($fp);
-
- // 删除
- if ($del) @unlink($file);
- die();
- }
-
- /**
- * 临时目录生成文件名,并返回绝对路径
- *
- * @param string $ext 文件类型后缀
- * @param string $path 临时文件目录 默认 ./public/temp/
- * @return string $file_path 文件名称绝对路径
- * @author ymob
- */
- function tempFileName($ext = '')
- {
- // 临时目录
- $path = TEMP_DIR . date('Ymd') . DS;
- if (!file_exists($path)) {
- mkdir($path, 0777, true);
- }
-
- $ext = trim($ext, '.');
- do {
- $temp_file = md5(time() . rand(1000, 9999));
- $file_path = $path . $temp_file . '.' . $ext;
- } while (file_exists($file_path));
- return $file_path;
- }
-
- /**
- * 递归删除目录
- *
- * @param string $dir
- * @return void
- * @author Ymob
- */
- function delDir($dir)
- {
- $dh = opendir($dir);
- while ($file = readdir($dh)) {
- if ($file != "." && $file != "..") {
- $fullpath = $dir . "/" . $file;
- if (!is_dir($fullpath)) {
- @unlink($fullpath);
- } else {
- deldir($fullpath);
- }
- }
- }
-
- closedir($dh);
- //删除当前文件夹:
- @rmdir($dir);
- }
-
- /**
- * 商业智能 查询缓存
- *
- * @param string $sql Sql语句
- * @param int $bi_slow_query_time 慢查询时间(毫秒),默认读取Config(bi_slow_query_time)
- * @return mixed
- * @author Ymob
- * @datetime 2019-11-21 17:36:50
- */
- function queryCache($sql = '', $bi_slow_query_time = null)
- {
- $key = 'BI_queryCache' . md5($sql);
- $val = cache($key);
- if (!$val) {
- $start_time = microtime(true) * 1000;
- $val = Db::query($sql);
- $end_time = microtime(true) * 1000;
- $slow_query = true;
- // 是否使用系统默认设置-慢查询时间
- if ($bi_slow_query_time === null) {
- $bi_slow_query_time = config('bi_slow_query_time');
- }
- if ($bi_slow_query_time > 0) {
- $slow_query = ($end_time - $start_time) > $bi_slow_query_time;
- }
- if ($slow_query && $val) {
- cache($key, $val, config('bi_cache_time'));
- }
- }
- return $val;
- }
-
- /**
- * 图表时间范围处理,按月/天返回时间段数组
- *
- * @param int $start 开始时间(时间戳)
- * @param int $end 结束时间(时间戳)
- * @return array
- * @author Ymob
- * @datetime 2019-11-18 09:25:09
- */
- function getTimeArray($start = null, $end = null)
- {
- if ($start == null || $end == null) {
- $param = request()->param();
- switch ($param['type']) {
- // 本年
- case 'year':
- $start = strtotime(date('Y-01-01'));
- $end = strtotime('+1 year', $start) - 1;
- break;
- // 去年
- case 'lastYear':
- $start = strtotime(date(date('Y') - 1 . '-01-01'));
- $end = strtotime('+1 year', $start) - 1;
- break;
- // 本季度、上季度
- case 'quarter':
- case 'lastQuarter':
- $t = intval((date('m') - 1) / 3);
- $start_y = ($t * 3) + 1;
- $start = strtotime(date("Y-{$start_y}-01"));
- if ($param['type'] == 'lastQuarter') { // 上季度
- $start = strtotime('-3 month', $start);
- }
- $end = strtotime('+3 month', $start) - 1;
- break;
- // 本月、上月
- case 'month':
- case 'lastMonth':
- $start = strtotime(date('Y-m-01'));
- if ($param['type'] == 'lastMonth') {
- $start = strtotime('-1 month', $start);
- }
- $end = strtotime('+1 month', $start) - 1;
- break;
- // 本周、上周
- case 'week':
- case 'lastWeek':
- $start = strtotime('-' . (date('w') - 1) . 'day', strtotime(date('Y-m-d')));
- if ($param['type'] == 'lastWeek') {
- $start = strtotime('-7 day', $start);
- }
- $end = strtotime('+7 day', $start) - 1;
- break;
- // 今天、昨天
- case 'today':
- case 'yesterday':
- $start = strtotime(date('Y-m-d'));
- if ($param['type'] == 'yesterday') {
- $start = strtotime('-1 day', $start);
- }
- $end = strtotime('+1 day', $start) - 1;
- break;
- default:
- if ($param['start_time'] && $param['end_time']) {
- $start = $param['start_time'];
- $end = $param['end_time'];
- } else {
- // 本年
- $start = strtotime(date('Y-01-01'));
- $end = strtotime('+1 year', $start) - 1;
- }
- break;
- }
- }
-
- $between = [$start, $end];
- $list = [];
- $len = ($end - $start) / 86400;
- // 大于30天 按月统计、小于按天统计
- if ($len > 31) {
- $time_format = '%Y-%m';
- while (true) {
- $start = strtotime(date('Y-m-01', $start));
- $item = [];
- $item['type'] = date('Y-m', $start);
- $item['start_time'] = $start;
- $item['end_time'] = strtotime('+1 month', $start) - 1;
- $list[] = $item;
- if ($item['end_time'] >= $end) break;
- $start = $item['end_time'] + 1;
- }
- } else {
- $time_format = '%Y-%m-%d';
- while (true) {
- $item = [];
- $item['type'] = date('Y-m-d', $start);
- $item['start_time'] = $start;
- $item['end_time'] = strtotime('+1 day', $start) - 1;
- $list[] = $item;
- if ($item['end_time'] >= $end) break;
- $start = $item['end_time'] + 1;
- }
- }
-
- return [
- 'list' => $list, // 时间段列表
- 'time_format' => $time_format, // 时间格式 mysql 格式化时间戳
- 'between' => $between // 开始结束时间
- ];
- }
-
- /**
- * 打印程序执行时间
- *
- * @param integer $s
- * @return void
- * @author Ymob
- * @datetime 2019-11-28 09:31:45
- */
- function tt($s = 0)
- {
- die((string)round(microtime(1) - ($s ?: THINK_START_TIME), 3));
- }
-
- /**
- * 数据库备份
- */
- function DBBackup($file = '', $path = '')
- {
- $type = config('database.type');
- $host = config('database.hostname');
- $port = config('database.hostport');
- $dbname = config('database.database');
- $username = config('database.username');
- $password = config('database.password');
- $dsn = "{$type}:host={$host};dbname={$dbname};port={$port}";
-
-
- if ($file == '') {
- $save_path = dirname(APP_PATH) . DS . 'data' . DS . date('Ym') . DS;
- if (!file_exists($save_path) && !mkdir($save_path, '0777', true)) {
- return 'data目录无写入权限';
- }
- $file = $save_path . date('d_H_i') . '_db_backup' . '.sql';
- }
-
- if (file_exists($file)) {
- return '数据库备份文件已存在(自动备份时间间隔需大于1分钟)。';
- }
-
- try {
- $backup = new \com\Mysqldump($dsn, $username, $password);
- $backup->start($file);
- return true;
- } catch (\Exception $e) {
- return '备份失败,请手动备份。错误原因:' . $e->getMessage();
- }
-
- }
-
- /**
- * 根据ip获取地址
- */
- function getAddressById($data)
- {
- $ip = new IpLocation();
- $ip_address = $ip->getlocation($data);
- return $ip_address;
- }
-
- if (!function_exists('isSuperAdministrators')) {
- /**
- * 判断是否是超级管理员
- *
- * @param $userId
- * @return bool
- */
- function isSuperAdministrators($userId)
- {
- $status = false;
-
- $apiCommon = new \app\admin\controller\ApiCommon();
-
- $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
-
- $data = db('admin_access')->where('user_id', $userId)->column('group_id');
-
- if ($userId == 1 || in_array(1, $data)) {
- $status = true;
- }
-
- return $status;
- }
- }
-
- if (!function_exists('getFieldGrantData')) {
- /**
- * 获取自动授权数据
- *
- * @return array
- */
- function getFieldGrantData($userId)
- {
- $result = [];
-
- $apiCommon = new \app\admin\controller\ApiCommon();
-
- $userId = !empty($userId) ? $userId : $apiCommon->userInfo['id'];
-
- $grantData = Db::query("
- SELECT
- `grant`.`module`, `grant`.`column`, `grant`.`content`
- FROM
- `5kcrm_admin_access` AS `access`
- LEFT JOIN
- `5kcrm_admin_group` AS `group` ON `access`.`group_id` = `group`.`id`
- LEFT JOIN
- `5kcrm_admin_field_grant` AS `grant` ON `group`.`id` = `grant`.`role_id`
- WHERE
- `access`.`user_id` =
- " . $userId);
-
- # 存在多角色多授权的情况
- foreach ($grantData as $key => $value) {
- if (empty($value['module']) || empty($value['column'])) continue;
-
- $result[$value['module'] . '_' . $value['column']][] = !empty($value['content']) ? unserialize($value['content']) : [];
- }
-
- return $result;
- }
- }
-
- if (!function_exists('getFieldGrantStatus')) {
- /**
- * 获取字段授权状态
- *
- * @param $field
- * @param $grantData
- * @return int[]
- */
- function getFieldGrantStatus($field, $grantData)
- {
- # 默认状态都是不能查看、不能编辑,通过配置来取最大权限。
- $result = ['read' => 0, 'write' => 0];
-
- foreach ($grantData as $key => $value) {
- $fieldBool = false;
-
- foreach ($value as $ke => $va) {
- # 多个字段授权,只取最高的读权限
- if ($va['field'] == $field && $result['read'] == 0) {
- $result['read'] = $va['read'] > $result['read'] ? $va['read'] : $result['read'];
- }
-
- # 多个字段授权,只取最高的写权限
- if ($va['field'] == $field && $result['write'] == 0) {
- $result['write'] = $va['write'] > $result['write'] ? $va['write'] : $result['write'];
- }
-
- if ($va['field'] == $field) $fieldBool = true;
- }
-
- # 对于不在权限控制之内的字段,将状态都改为1。
- if (!$fieldBool) {
- $result['read'] = 1;
- $result['write'] = 1;
- }
- }
-
- return $result;
- }
- }
-
- /**
- * 仪表盘日志使用
- * 根据类型获取开始结束时间戳数组
- * @param
- */
- function ByDateTime($type = 'today')
- {
- switch ($type) {
- case 'yesterday' :
- $timeArr = DataTime::yesterday();
- $timeArr['last_time'] = DataTime::yesterday(1);
- break;
- case 'week' :
- $timeArr = DataTime::week();
- $timeArr['last_time'] = DataTime::lastWeek();
- break;
- case 'lastWeek' :
- $timeArr = DataTime::lastWeek();
- $timeArr['last_time'] = DataTime::lastWeek(1);
- break;
- case 'month' :
- $timeArr = DataTime::month();
- $timeArr['last_time'] = DataTime::lastMonth();
- break;
- case 'lastMonth' :
- $timeArr = DataTime::lastMonth();
- $timeArr['last_time'] = DataTime::lastMonth(1);
- break;
- case 'quarter' :
- //本季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-10-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-12-31 23:59:59"));
- }
-
- //上季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $year = date('Y') - 1;
- $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
- } else {
- $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
- break;
- case 'lastQuarter' :
- //上季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $year = date('Y') - 1;
- $daterange_start_time = strtotime(date($year . '-10-01 00:00:00'));
- $daterange_end_time = strtotime(date($year . '-12-31 23:59:59'));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-06-30 23:59:59"));
- } else {
- $daterange_start_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time = strtotime(date("Y-09-30 23:59:59"));
- }
- //上季度
- $month = date('m');
- if ($month == 1 || $month == 2 || $month == 3) {
- $year = date('Y') - 2;
- $daterange_start_time_last_time = strtotime(date($year . '-10-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date($year . '-12-31 23:59:59'));
- } elseif ($month == 4 || $month == 5 || $month == 6) {
- $daterange_start_time_last_time = strtotime(date('Y-01-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-03-31 23:59:59"));
- } elseif ($month == 7 || $month == 8 || $month == 9) {
- $daterange_start_time_last_time = strtotime(date('Y-04-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-06-30 23:59:59"));
- } else {
- $daterange_start_time_last_time = strtotime(date('Y-07-01 00:00:00'));
- $daterange_end_time_last_time = strtotime(date("Y-09-30 23:59:59"));
- }
- $timeArr = array($daterange_start_time, $daterange_end_time);
- $timeArr['last_time'] = array($daterange_start_time_last_time, $daterange_end_time_last_time);
- break;
- case 'year' :
- $timeArr = DataTime::year();
- $timeArr['last_time'] = DataTime::lastYear();
- break;
- case 'lastYear' :
- $timeArr = DataTime::lastYear();
- $timeArr['last_time'] = DataTime::lastYear(1);
- break;
- case 'recent60' :
- $timeArr = DataTime::recent60();
- break;
- case 'recent30' :
- $timeArr = DataTime::recent30();
- break;
- default :
- $timeArr = DataTime::today();
- $timeArr['last_time'] = DataTime::yesterday();
- break;
- }
- return $timeArr;
- }
-
- /**
- * 系统操作日志
- * @param int $user_id 用户
- * @param string $types 方法所属模块
- * @param int $action_id 操作
- * @param string $module_name 模块
- * @param string $action_name 修改添加删除新建
- * @param array $oldData 旧数据
- * @param array $newData 新数据
- * @param string $target_name 被操作对象
- * @param string $content 添加时创建使用
- * @author alvin guogaobo
- * @version 1.0 版本号
- * @since 2021/3/26 0026 15:10
- */
- function SystemActionLog($user_id, $types, $module_name, $action_id, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
- {
- //action_name 修改添加删除新建 action_id 操作id client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module_name 模块 系统管理 固定 user_id 用户
- $data = [];
- $data['user_id'] = $user_id;
- $data['create_time'] = time();
- $data['client_ip'] = request()->ip();
- $data['action_id'] = $action_id;
- $data['action_name'] = $action_name;
- $data['target_name'] = $target_name;
- $data['module_name'] = $module_name;
- $data['controller_name'] = $types;
- $data['content'] = $content;
- db('admin_system_log')->insert($data);
- }
-
- /**
- * 系统操作日志
- * @param int $user_id 用户
- * @param string $types 方法所属模块
- * @param string $action_name 修改添加删除新建
- * @param string $target_name 被操作对象
- * @param array $oldData 旧数据
- * @param array $newData 新数据
- * @param string $content 添加时创建使用
- * @author alvin guogaobo
- * @version 1.0 版本号
- * @since 2021/4/2 0026 15:10
- */
- function RecordActionLog($user_id, $types, $action_name, $target_name, $oldData = [], $newData = [], $content = '')
- {
- //action_name 修改 添加 删除 client_ip ip create_time时间 content 操作记录 target_name 被操作对象 module 模块 user_id 用户
- if (is_array($oldData) && is_array($newData) && $user_id) {
- $differentData = array_diff_assoc($newData, $oldData);
- $fieldModel = new FieldModel();
- $userModel = new UserModel();
- $structureModel = new \app\admin\model\Structure();
- $field_arr = $fieldModel->getField(['types' => $types, 'unFormType' => ['file', 'form']]); //获取字段属性
- $newFieldArr = array();
- foreach ($field_arr as $k => $v) {
- $newFieldArr[$v['field']] = $v;
- }
- $unField = ['update_time', 'create_time']; //定义过滤字段
- $message = [];
- $un_form_type = ['file', 'form'];
- foreach ($differentData as $k => $v) {
- if ($newFieldArr[$k] && !in_array($newFieldArr[$k]['form_type'], $un_form_type)) {
- $field_name = '';
- $field_name = $newFieldArr[$k]['name'];
- $new_value = $v ?: '空';
- $old_value = $oldData[$k] ?: '空';
- switch ($newFieldArr[$k]['form_type']) {
- case 'datetime' :
- $new_value = $v ? date('Y-m-d', $v) : '';
- $old_value = date('Y-m-d', $oldData[$k]);
- if (!empty($v) && !empty($oldData[$k]))
- break;
- case 'user' :
- $new_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($v))) : '';
- $old_value = $v ? implode(',', $userModel->getUserNameByArr(stringToArray($oldData[$k]))) : '';
- break;
- case 'structure' :
- $new_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($v))) : '';
- $old_value = $v ? implode(',', $structureModel->getStructureNameByArr(stringToArray($oldData[$k]))) : '';
- break;
- case 'business_status' :
- $new_value = $v ? db('crm_business_status')->where(['status_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business_status')->where(['status_id' => $oldData[$k]])->value('name') : '';
- break;
- case 'business_type' :
- $new_value = $v ? db('crm_business_type')->where(['type_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business_type')->where(['type_id' => $oldData[$k]])->value('name') : '';
- break;
- case 'customer' :
- $new_value = $v ? db('crm_customer')->where(['customer_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_customer')->where(['customer_id' => $oldData[$k]])->value('name') : '';
- break;
- case 'category' :
- $new_value = $v ? db('crm_product_category')->where(['category_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_product_category')->where(['category_id' => $oldData[$k]])->value('name') : '';
- break;
- case 'business' :
- $new_value = $v ? db('crm_business')->where(['business_id' => $v])->value('name') : '';
- $old_value = $v ? db('crm_business')->where(['business_id' => $oldData[$k]])->value('name') : '';
- break;
- case 'visit' :
- $new_value = $v ? db('crm_visit')->where(['visit_id' => $v])->value('number') : '';
- $old_value = $v ? db('crm_visit')->where(['visit_id' => $oldData[$k]])->value('number') : '';
- break;
- case 'single_user' :
- $new_value = $v ? db('admin_user')->where(['id' => $v])->value('realname') : '';
- $old_value = $v ? db('admin_user')->where(['id' => $oldData['owner_user_id']])->value('realname') : '';
- break;
- case 'floatnumber' :
- $new_value = $v ? number_format($v, 2) : '';
- break;
- }
- if ($newFieldArr[$k]['field'] == 'check_status') {
- $statusArr = ['0' => '待审核', '1' => '审核中', '2' => '审核通过', '3' => '已拒绝', '4' => '已撤回', '5' => '未提交'];
- $new_value = $statusArr[$v];
- $old_value = $statusArr[$oldData[$k]];
- }
- if ($old_value != $new_value) {
- $message[] = '将 ' . "'" . $field_name . "'" . ' 由 ' . $old_value . ' 修改为 ' . $new_value;
- }
- }
- }
- if ($message) {
- $data = [];
- $data['user_id'] = $user_id;
- $data['create_time'] = time();
- $data['client_ip'] = request()->ip();
- $data['action_name'] = $action_name;
- $data['action_id'] = 1;
- $data['target_name'] = $target_name;
- $data['module'] = $types; //子模块 客户线索
- $data['content'] = implode(',', $message);
- db('admin_operation_log')->insert($data);
- }
- } elseif ($content) {
- $data = [];
- $data['user_id'] = $user_id;
- $data['create_time'] = time();
- $data['client_ip'] = request()->ip();
- $data['action_name'] = $action_name;
- $data['target_name'] = $target_name;
- $data['action_id'] = 1;
- $data['module'] = $types; //子模块 客户线索
- $data['content'] = $content;
- db('admin_operation_log')->insert($data);
- }
- }
-
- if (!function_exists('getFieldGroupOrderData')) {
- /**
- * 对自定义字段进行分组排序
- *
- * @param array $data 自定义字段数据
- * @return array
- * @since 2021-04-27
- * @author fanqi
- */
- function getFieldGroupOrderData($data)
- {
- $formPositionEmpty = [];
- $formPositionExist = [];
- $result = [];
-
- // 处理数据,将有位置信息和无位置信息的数据分开存放。
- foreach ($data as $key => $value) {
- if (empty($value['form_position'])) {
- $formPositionEmpty[] = $value;
- continue;
- }
-
- $formPositionArray = explode(',', $value['form_position']);
- $x = (int)$formPositionArray[0];
- $y = (int)$formPositionArray[1];
-
- if (!isset($value['xaxis'])) $value['xaxis'] = $x;
- if (!isset($value['yaxis'])) $value['yaxis'] = $y;
-
- $formPositionExist[$x][$y] = $value;
- }
-
- // 排序
- ksort($formPositionExist);
-
- // 处理有位置信息的数据
- foreach ($formPositionExist as $key => $value) {
- foreach ($value as $k => $v) {
- if (!empty($formPositionExist[$key][$k])) $result[$key][$k] = $v;
- }
-
- $result[$key] = array_values($result[$key]);
- }
-
- // 将无位置信息的数据放置尾端
- foreach ($formPositionEmpty as $key => $value) {
- $result[] = [$value];
- }
-
- return array_values($result);
- }
- }
-
- if (!function_exists('getPrimaryKeyName')) {
- /**
- * 获取主键
- *
- * @param string $types 栏目类型
- * @return string
- * @since 2021-05-18
- * @author fanqi
- */
- function getPrimaryKeyName($types)
- {
- $primaryKey = '';
-
- if ($types == 'crm_leads') $primaryKey = 'leads_id';
- if ($types == 'crm_customer') $primaryKey = 'customer_id';
- if ($types == 'crm_contacts') $primaryKey = 'contacts_id';
- if ($types == 'crm_business') $primaryKey = 'business_id';
- if ($types == 'crm_contract') $primaryKey = 'contract_id';
- if ($types == 'crm_receivables') $primaryKey = 'receivables_id';
- if ($types == 'crm_receivables_plan') $primaryKey = 'plan_id';
- if ($types == 'crm_visit') $primaryKey = 'visit_id';
- if ($types == 'crm_product') $primaryKey = 'product_id';
- if ($types == 'crm_invoice') $primaryKey = 'invoice_id';
- if ($types == 'oa_examine') $primaryKey = 'examine_id';
-
- return $primaryKey;
- }
-
- }
- function advancedQueryFormatForTeam($requestMap,$db,$db_id)
- {
- // 处理查询条件
- foreach ($requestMap['team_id']['value'] as $v) {
- if ($requestMap['team_id']['condition'] == 'contains') {
- $date = function ($query) use ($v) {
- $query->where('FIND_IN_SET("'.$v.'", ro_user_id)')
- ->whereOr('FIND_IN_SET("'.$v.'", rw_user_id)');
- };
- } elseif ($requestMap['team_id']['condition'] == 'notContains') {
- $date = function ($query) use ($v) {
- $query->where('FIND_IN_SET("'.$v.'", ro_user_id)')
- ->where('FIND_IN_SET("'.$v.'", rw_user_id)');
- };
- } elseif ($requestMap['team_id']['condition'] == 'isNull') {
- $date = function ($query) {
- $query->where('ro_user_id', ['eq', ''])
- ->whereOr('rw_user_id', 'null');
- };
- } elseif ($requestMap['team_id']['condition'] == 'isNotNull') {
- $date = function ($query) {
- $query->where('ro_user_id', ['neq', ''])
- ->where('rw_user_id', ['not null']);
- };
-
- }
- $part[] = db($db)->where($date)->column($db_id);
- }
- $result = [];
- array_walk_recursive($part, function($value) use (&$result) {
- array_push($result, $value);
- });
- $result=array_unique($result);
- $partMap['customer.customer_id'] = ['in', trim(arrayToString($result), ',')];
- return $partMap ?: [];
- }
|