1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370 |
- <?php
- /**
- * 客户管理模块
- * Created by PhpStorm.
- * User: haoren
- * Date: 2020/10/30
- * Time: 14:02
- */
- namespace JinDouYun\Model\Customer;
- use Exception;
- use JinDouYun\Dao\Customer\DCustomerCommunication;
- use JinDouYun\Dao\Enterprise\DEnterprise;
- use JinDouYun\Dao\Finance\DReceive;
- use JinDouYun\Dao\Finance\DReceived;
- use JinDouYun\Dao\Finance\DReceivedIndex;
- use JinDouYun\Dao\Finance\DReceiveReceiptIndex;
- use JinDouYun\Dao\Shop\DShop;
- use Mall\Framework\Core\ErrorCode;
- use Mall\Framework\Core\StatusCode;
- use Mall\Framework\Core\ResultWrapper;
- use JinDouYun\Controller\Common\Logger;
- use JinDouYun\Dao\Integral\DIntegralRule;
- use JinDouYun\Dao\Customer\DCustomer;
- use JinDouYun\Dao\Customer\DCustomerBalanceTurnover;
- use JinDouYun\Dao\Customer\DCustomerRechargeRecord;
- use JinDouYun\Dao\Customer\DCustomerIntegralDesc;
- use JinDouYun\Dao\UserCenter\DUserCenter;
- use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
- use JinDouYun\Dao\Stock\DReservoirArea;
- use JinDouYun\Dao\Department\DStaff;
- use JinDouYun\Model\UserCenter\MUserCenterRegister;
- use JinDouYun\Model\SysAreaChina\MSysAreaChina;
- use JinDouYun\Model\Shop\MShop;
- use JinDouYun\Model\Department\MDepartment;
- use JinDouYun\Model\Department\MStaff;
- use JinDouYun\Model\System\MCustomerSource;
- use JinDouYun\Model\System\MBasicSetup;
- use JinDouYun\Model\MBaseModel;
- use JinDouYun\Model\Enterprise\MEnterprise;
- use JinDouYun\Model\Finance\MCustomerBalanceDetail;
- use JinDouYun\Model\Goods\MGoodsCollect;
- use JinDouYun\Model\Market\MUserCoupon;
- use JinDouYun\Model\Market\MVipCard;
- use JinDouYun\Model\Order\MOrder;
- use JinDouYun\Model\Stock\MReservoirArea;
- use JinDouYun\Model\System\MPaymentSetting;
- use JinDouYun\Cache\CustomerCache;
- use JinDouYun\Cache\OverviewCache;
- use JinDouYun\Cache\SystemCache;
- use Util\Common\ChineseCharacter;
- use Util\WeiXin\Pay;
- use const Grpc\STATUS_ABORTED;
- class MCustomer extends MBaseModel
- {
- private $objDCustomer;
- private $objMCustomerContact;
- private $objDUserCenter;
- private $objDCustomerBalanceTurnover;
- private $objDCustomerRechargeRecord;
- private $objMShop;
- private $objMDepartment;
- private $objMStaff;
- private $objMCustomerSource;
- private $objDUserBindEnterprise;
- private $objCustomerCache;
- private $objOverviewCache;
- private $objMShippingAddress;
- private $objDCustomerIntegralDesc;
- private $cutTable = 1;//客户按照企业id分表
- private $enterpriseId;
- private $userCenterId;
- public function __construct($enterpriseId, $userCenterId)
- {
- $this->enterpriseId = $enterpriseId;
- $this->userCenterId = $userCenterId;
- parent::__construct($this->enterpriseId, $this->userCenterId);
- $this->objMCustomerContact = new MCustomerContact($enterpriseId, $userCenterId);
- $this->objMShop = new MShop($enterpriseId, $userCenterId);
- $this->objMDepartment = new MDepartment($enterpriseId);
- $this->objMStaff = new MStaff($enterpriseId, $userCenterId);
- $this->objDCustomerIntegralDesc = new DCustomerIntegralDesc();
- $this->objMCustomerSource = new MCustomerSource($enterpriseId);
- $this->objMShippingAddress = new MShippingAddress($enterpriseId);
- $this->objCustomerCache = new CustomerCache();
- $this->objOverviewCache = new OverviewCache();
- $this->objDCustomerBalanceTurnover = new DCustomerBalanceTurnover();
- $this->objDCustomerBalanceTurnover->setTable('qianniao_customer_balance_turnover_'.$enterpriseId);
- $this->objDCustomerRechargeRecord = new DCustomerRechargeRecord();
- $this->objDCustomerRechargeRecord->setTable('qianniao_customer_recharge_record_'.$enterpriseId);
- $this->objDCustomerIntegralDesc->setTable('qianniao_customer_integral_desc_'.$enterpriseId);
- $this->objDCustomer = new DCustomer('default');
- $this->objDUserCenter = new DUserCenter('default');
- $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, $this->cutTable);
- $this->objDCustomer->setTable($tableName);
- $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
- $this->objDCustomer->setSearchIndex('customer_search')->setType('customer');
- }
- /**
- * 添加客户
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function addCustomer($params)
- {
- $beginStatus = $this->objDCustomer->beginTransaction();
- $contact = $params['contact'];
- unset($params['contact']);
-
- if(!isMobile($params['mobile'])){
- return ResultWrapper::fail('该手机号格式有问题', ErrorCode::$mobileishaved);
- }
- //判断账号密码是否在该企业下被注册过
- $objMUserCenterRegister = new MUserCenterRegister();
- $isRegister = $objMUserCenterRegister->mobileIsRegister($params['mobile'], $this->enterpriseId);
- if ($isRegister) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail('该手机号已经被注册', ErrorCode::$mobileishaved);
- }
- //添加userCenter表
- $dbResult = $this->objDUserCenter->get(['mobile' => $params['mobile']]);
- if($dbResult === false){
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- $userCenterData = [
- 'mobile' => $params['mobile'],
- 'source' => StatusCode::$source['manage'],
- 'isCustomer' => StatusCode::$customerType['customer'],
- 'createTime' => time(),
- 'updateTime' => time(),
- ];
- $userCenterId = $this->objDUserCenter->insert($userCenterData);
- if ($userCenterId === false) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
- }
- }else{
- $userCenterId = $dbResult['id'];
- }
- $params['enterpriseId'] = $this->enterpriseId;
- $params['userCenterId'] = $userCenterId;
- //添加负责人电话
- $params['managerMobile'] = $params['mobile'];
- unset($params['mobile']);
- unset($params['password']);
- //后台添加客户 状态为已审核
- $params['status'] = StatusCode::$auditStatus['auditPass'];
- $objChineseCharacter = new ChineseCharacter();
- $condition = $objChineseCharacter->getInitials(trim($params['name']));
- $params['condition'] = $condition;
- $customerId = $this->objDCustomer->insert($params);
- if ($customerId === false) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- //增加客户公司关系表
- $UserBindEnterpriseData = [
- 'userCenterId' => $userCenterId,
- 'roleType' => StatusCode::$roleType['customer'],
- 'enterpriseId' => $this->enterpriseId,
- 'updateTime' => time(),
- 'createTime' => time(),
- ];
- $dbResult = $this->objDUserBindEnterprise->insert($UserBindEnterpriseData);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
- }
- if(!empty($contact)){
- //保存联系人信息
- $customerContactData = [
- 'customerId' => $customerId,
- 'name' => isset($contact['name']) ? $contact['name'] : '',
- 'mobile' => isset($contact['mobile']) ? $contact['mobile'] : '',
- 'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
- 'cityCode' => isset($contact['cityCode']) ? $contact['cityCode'] : '',
- 'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
- 'address' => isset($contact['address']) ? $contact['address'] : '',
- 'deleteStatus' => StatusCode::$standard,
- 'createTime' => time(),
- 'updateTime' => time()
- ];
- $result = $this->objMCustomerContact->addCustomerContact($customerContactData);
- if ($result->isSuccess() === false) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- //把联系人信息保存为收货地址
- $ShippingAddressData = [
- 'name' => $customerContactData['name'],
- 'mobile' => $customerContactData['mobile'],//客户收货手机号
- 'provinceCode' => $customerContactData['provinceCode'],//客户收货地址省份编码
- 'cityCode' => $customerContactData['cityCode'],//客户收货地址城市编码
- 'districtCode' => $customerContactData['districtCode'],//客户收货地址区县编码
- 'address' => $customerContactData['address'],//详细收货地址
- 'deleteStatus' => StatusCode::$standard,
- 'defaultStatus' => StatusCode::$standard,
- 'customerId' => $customerId,
- 'extend' => json_encode(['createType' => StatusCode::$roleType['admin']]),
- 'updateTime' => time()
- ];
- $result = $this->objMShippingAddress->addShippingAddress($ShippingAddressData);
- if ($result->isSuccess() === false) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($result->getData(), $result->getErrorCode());
- }
- }
- $beginStatus && $this->objDCustomer->commit();
- //self::updateEsData($customerId);
- return ResultWrapper::success($customerId);
- }
- /**
- * 获取指定客户信息,获取联系人信息
- * @param $CustomerIds
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerInfo($CustomerIds)
- {
- $dbResult = $this->objDCustomer->get_by('id', $CustomerIds);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- } else {
- $dbResult = self::format([$dbResult]);
- $dbResult = array_shift($dbResult);
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 获取指定客户信息,获取客戶信息
- * @param $CustomerIds
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerName($CustomerIds)
- {
- $dbResult = $this->objDCustomer->get_by('id', $CustomerIds, 'id,name,managerMobile');
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 获取客户
- * @param $where
- * @param string $field
- * @param bool $isOne
- * @param bool $isFormat
- * @return ResultWrapper
- */
- public function getCustomerData($where, $field = '*', $isOne = true, $isFormat = false)
- {
- if($isOne){
- $dbResult = $this->objDCustomer->get($where, $field);
- }else{
- $dbResult = $this->objDCustomer->select($where, $field);
- }
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if($isFormat){
- $dbResult = self::format($dbResult);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 获取客户
- * @param $sql
- * @return ResultWrapper
- */
- public function getCustomerDataByQuery($sql)
- {
- $dbResult = $this->objDCustomer->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 处理客户联系人信息
- * @param $data
- * @param bool $flag 二维数组传true
- * @return array
- * @throws Exception
- */
- public function format($data)
- {
- if (!$data) {
- return $data;
- }
- $objMSysAreaChina = new MSysAreaChina();
- $customerIds = [];
- $userCenterIds = [];
- $shopIds = [];
- $departmentIds = [];
- $recommenderCustomerIds = [];
- $staffIds = [];
- $customerSourceIds = [];//客户类型
- $reservoirAreaIds = []; // 分拣区id
- foreach ($data as $key => $customer) {
- !empty($customer['id']) && $customerIds[] = $customer['id'];
- !empty($customer['userCenterId']) && $userCenterIds[] = $customer['userCenterId'];
- !empty($customer['shopId']) && $shopIds[] = $customer['shopId'];
- !empty($customer['departmentId']) && $departmentIds[] = $customer['departmentId'];
- !empty($customer['salesManId']) && $staffIds[] = $customer['salesManId'];
- if (isset($customer['type'])) {
- $customerSourceIds[] = $customer['type'];
- }
- if(isset($customer['sortingId'])){
- $reservoirAreaIds = $customer['sortingId'];
- }
- if( empty($customer['recommenderId']) ) continue;
- if($customer['recommenderType'] == StatusCode::$roleType['customer']){
- !empty($customer['recommenderId']) && $recommenderCustomerIds[] = $customer['recommenderId'];
- }else{
- !empty($customer['recommenderId']) && $staffIds[] = $customer['recommenderId'];
- }
- }
- //获取用户账号信息
- $userCenters = [];
- if ($userCenterIds) {
- $userCenterDatas = $this->objDUserCenter->select(array_unique(array_filter($userCenterIds)), 'id,mobile,source,createTime');
- foreach ($userCenterDatas as $userCenterData){
- $userCenters[$userCenterData['id']] = $userCenterData;
- }
- }
-
- //获取联系人信息
- $customerContacts = [];
- if ($customerIds) {
- $contacts = $this->objMCustomerContact->getContactInfoById($customerIds);
- foreach ($contacts as $contact)
- $customerContacts[$contact['customerId']][] = $contact;
- }
- //获取店铺
- $shops = [];
- if ($shopIds) {
- $shopData = $this->objMShop->getShopName(array_unique(array_filter($shopIds)));
- foreach ($shopData as $shop)
- $shops[$shop['id']] = $shop['name'];
- }
- //获取部门
- $departments = [];
- if ($departmentIds) {
- $departmentData = $this->objMDepartment->departmentDataByDepartmentIds(array_unique(array_filter($departmentIds)));
- foreach ($departmentData as $department)
- $departments[$department['id']] = $department['departmentName'];
- }
- //获取业务员
- $staffs = [];
- if ($staffIds) {
- $staffData = $this->objMStaff->getStaffDataByStaffIds(array_unique(array_filter($staffIds)));
- foreach ($staffData as $staff)
- $staffs[$staff['id']] = $staff['staffName'];
- }
- // 根据客户ids批量获取客户名称
- $customerIdBindName = [];
- if( !empty($recommenderCustomerIds) ){
- $dbResult = $this->objDCustomer->select($recommenderCustomerIds, 'id,name');
- if($dbResult !== false){
- foreach ($dbResult as $key => $value){
- $customerIdBindName[$value['id']] = $value['name'];
- }
- }
- }
- //查询客户类型
- $customerSourceArr = [];
- if ($customerSourceIds) {
- $customerSourceData = $this->objMCustomerSource->getCustomerSourceNameByIds($customerSourceIds);
- if ($customerSourceData->isSuccess()) {
- $customerSourceArray = $customerSourceData->getData();
- foreach ($customerSourceArray as $customerSource)
- $customerSourceArr[$customerSource['id']] = $customerSource['name'];
- }
- }
- foreach ($data as &$customer) {
- $customer['customerDays'] = intval((time() - $customer['createTime']) / 86400);//注册天数
- $customer['code'] = createCode(StatusCode::$code['customer']['prefix'], $customer['id'], StatusCode::$code['customer']['length']);
- $customer['taglib'] = isset($customer['taglib']) ? json_decode($customer['taglib'], true) : [];
- $customer['extend'] = isset($customer['extend']) ? json_decode($customer['extend'], true) : [];
- //处理客户地址
- if (isset($customer['provinceCode']) && isset($customer['cityCode']) && isset($customer['districtCode'])) {
- $areaName = $objMSysAreaChina->getNameByCode([
- $customer['provinceCode'],
- $customer['cityCode'],
- $customer['districtCode']
- ]);
- $customer['area']['provinceName'] = isset($areaName[$customer['provinceCode']]) ? $areaName[$customer['provinceCode']] : '';
- $customer['area']['cityName'] = isset($areaName[$customer['cityCode']]) ? $areaName[$customer['cityCode']] : '';
- $customer['area']['districtName'] = isset($areaName[$customer['districtCode']]) ? $areaName[$customer['districtCode']] : '';
- $customer['area']['address'] = getArrayItem($customer, 'address');
- }
- //处理店铺
- $customer['shopName'] = isset($shops[$customer['shopId']]) ? $shops[$customer['shopId']] : '';
- //处理销售部门
- $customer['departmentName'] = isset($departments[$customer['departmentId']]) ? $departments[$customer['departmentId']] : '';
- //处理业务员
- $customer['salesManName'] = isset($staffs[$customer['salesManId']]) ? $staffs[$customer['salesManId']] : '';
- //处理客户类型
- $customer['customerType'] = isset($customerSourceArr[$customer['type']]) ? $customerSourceArr[$customer['type']] : '';
- $customer['mobile'] = '';
- $customer['password'] = '';
- $customer['registerTime'] = '';
- $customer['source'] = '';
- //处理注册手机号/时间/来源
- if (isset($userCenters[$customer['userCenterId']]) && $userCenters[$customer['userCenterId']]) {
- $userCenter = $userCenters[$customer['userCenterId']];
- $customer['mobile'] = ($this->enterpriseId == 4) ? substr_replace($userCenter['mobile'],'****',3,4) : $userCenter['mobile'];
- $customer['registerTime'] = date('Y-m-d H:i:s', $userCenter['createTime']);
- $customer['source'] = array_search($userCenter['source'], StatusCode::$source);
- }
- $defaultContact[] = [
- 'name' => '',
- 'mobile' => ''
- ];
- $customer['contact'] = isset($customerContacts[$customer['id']]) ? $customerContacts[$customer['id']] : $defaultContact;
- // 处理推荐人
- if(isset($customer['recommenderType'])){
- if($customer['recommenderType'] == StatusCode::$roleType['customer']){
- $customer['recommenderName'] = isset($customerIdBindName[$customer['recommenderId']]) ? $customerIdBindName[$customer['recommenderId']] : '';
- }else{
- $customer['recommenderName'] = isset($staffs[$customer['recommenderId']]) ? $staffs[$customer['recommenderId']] : '';
- }
- }
- }
- return $data;
- }
- /**
- * 处理时间戳
- * @param $timestamp
- * @param string $type
- * @return false|string
- */
- function time_format($timestamp, $type = 'Y-m-d')
- {
- $time = explode('-', $timestamp);
- if (count($time) > 1) {
- return $timestamp;
- }
- return date($type, $timestamp);
- }
- /**
- * 编辑客户
- * 事务修改联系人信息
- * @param int|array $params 修改客户的数据
- *
- * @return ResultWrapper
- * @throws Exception
- */
- public function editCustomer($params)
- {
- if (empty($params['id'])) {
- return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
- }
- $updateCustomerId = $params['id'];
- unset($params['id']);
- $contact = $params['contact'];
- unset($params['contact']);
- $beginStatus = $this->objDCustomer->beginTransaction();
- //修改客户账号密码
- $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $updateCustomerId);
- $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');
- if ($userCenterInfo === false) {
- return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
- }
- //手机号不应该随意修改
- /* if (isset($userCenterInfo['mobile']) && isset($userCenterInfo['password'])) {
- //比对手机号和密码有没有发生变化
- $updateUserCenterData = [];
- if ($params['mobile'] != $userCenterInfo['mobile']) {
- $updateUserCenterData['mobile'] = $params['mobile'];
- }
- //如果输入了密码,则判断密码与原来的密码是否一致
- if ($params['password'] && password_verify($params['password'], $userCenterInfo['password']) === false) {
- $updateUserCenterData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
- }
- if (!empty($updateUserCenterData)) {
- $userCenterResult = $this->objDUserCenter->update($updateUserCenterData, $userCenterId);
- if ($userCenterResult === false) {
- return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
- }
- }
- }*/
- unset($params['mobile']);
- unset($params['password']);
- if(isset($params['name'])){
- $objChineseCharacter = new ChineseCharacter();
- $condition = $objChineseCharacter->getInitials(trim($params['name']));
- $params['condition'] = $condition;
- }
- // 修改手机号
- // $params['managerMobile'] = $params['mobile'];
- //修改客户基本信息
- $dbResult = $this->objDCustomer->update($params, $updateCustomerId);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerContactData = [
- 'name' => isset($contact['name']) ? $contact['name'] : '',
- 'mobile' => isset($contact['mobile']) ? $contact['mobile'] : '',
- 'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
- 'cityCode' => isset($contact['cityCode']) ? $contact['cityCode'] : '',
- 'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
- 'address' => isset($contact['address']) ? $contact['address'] : '',
- 'updateTime' => time()
- ];
- //修改联系人信息
- if (isset($contact['id']) && !empty($contact['id'])) {
- $customerContactData['id'] = $contact['id'];
- $dbResult1 = $this->objMCustomerContact->editCustomerContact($customerContactData);
- } else {
- $customerContactData['customerId'] = $updateCustomerId;
- $customerContactData['createTime'] = time();
- $customerContactData['deleteStatus'] = StatusCode::$standard;
- $dbResult1 = $this->objMCustomerContact->addCustomerContact($customerContactData);
- }
- if ($dbResult1->isSuccess() === false) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
- }
- $objCustomerCache = new CustomerCache();
- $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
- $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);
- $beginStatus && $this->objDCustomer->commit();
- //self::updateEsData($updateCustomerId);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 后台批量分配部门及业务员
- * @param array $params
- * @return ResultWrapper
- */
- public function batchEditCustomer(array $params)
- {
- $dbResult = $this->objDCustomer->update(
- [
- 'departmentId' => $params['departmentId'],
- 'salesManId' => $params['salesManId'],
- 'updateTime' => time()
- ],
- ['id' => $params['ids']]
- );
- if ($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- return ResultWrapper::success("操作成功");
- }
- //前台修改客户信息
- public function editCustomerInfo($params)
- {
- $userCenterId = $params['userCenterId'];
- unset($params['userCenterId']);
- $updateCustomerId = self::getCustomerIdByUserCenterId($userCenterId);
- if (empty($updateCustomerId)) {
- return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
- }
- $contact = $params['contact'];
- unset($params['contact']);
- //状态 为已审核
- $params['status'] = StatusCode::$auditStatus['auditPass'];
- $params['auditFailReason'] = '';
- //查询系统设置
- $objMBasicSetup = new MBasicSetup($this->enterpriseId);
- $modelResult = $objMBasicSetup->getBasicSetup();
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- $system = $modelResult->getData();
- //判断完善资料内容
- if (isset($system['basicData']) && isset($system['basicData']['finishData']) && $system['basicData']['finishData'] == StatusCode::$standard) {
- //如果完善资料 限制资料提交内容
- if(!isset($params['name']) || empty($params['name'])){
- return ResultWrapper::fail('请输入真实名称', ErrorCode::$paramError);
- }
- }
- //判断系统设置审核
- if (isset($system['basicData']) && isset($system['basicData']['personnelReview']) && $system['basicData']['personnelReview'] == StatusCode::$standard) {
- //如果开启客户审核 把状态改为待审核
- $params['status'] = StatusCode::$auditStatus['auditing'];
- }
- //修改客户基本信息
- $dbResult = $this->objDCustomer->update($params, $updateCustomerId);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $objCustomerCache = new CustomerCache();
- $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);
- $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
- //修改联系人信息
- if (isset($contact['id'])) {
- $contact['updateTime'] = time();
- $dbResult1 = $this->objMCustomerContact->editCustomerContact($contact);
- } else {
- $dbResult1 = true;
- if (
- (isset($contact['provinceCode']) && !empty($contact['provinceCode'])) ||
- (isset($contact['cityCode']) && !empty($contact['cityCode'])) ||
- (isset($contact['districtCode']) && !empty($contact['districtCode'])) ||
- (isset($contact['address']) && !empty($contact['address'])) ||
- (isset($contact['name']) && !empty($contact['name'])) ||
- (isset($contact['mobile']) && !empty($contact['mobile']))
- ) {
- $contact['customerId'] = $updateCustomerId;
- $contact['createTime'] = time();
- $contact['updateTime'] = time();
- $dbResult1 = $this->objMCustomerContact->addCustomerContact($contact);
- }
- }
- //获取客户所属的商铺
- /*$shopId = $this->objMShop->getShopIdByArea($params);
- if ($shopId) {
- $this->objDCustomer->update(['shopId' => $shopId], $updateCustomerId);
- }*/
- if (!$dbResult1->isSuccess()) {
- $this->objDCustomer->rollBack();
- return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
- } else {
- $this->objDCustomer->commit();
- // $_id = self::createEsDocumentId($updateCustomerId);
- // $result = $this->objDCustomer->esupdateTypeFieldVaule($params, $_id);
- return ResultWrapper::success($params['status']);
- }
- }
- private function createEsDocumentId($customerId)
- {
- return 'EnterpriseId_' . $this->enterpriseId . '_CustomerId_' . $customerId;
- }
- /**
- * 更新ES
- * @param $customerId
- * @throws Exception
- */
- public function updateEsData($customerId)
- {
- //每次查询一遍,避免客户在数据库存在,在ES中不存在的情况
- $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $customerId);
- $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');
- $customerInfo = $this->objDCustomer->get_by('id', $customerId);
- if ($customerInfo !== false) {
- $customerInfo['shopName'] = $this->objMShop->getShopNameById($customerInfo['shopId']);
- $customerInfo['departmentName'] = $this->objMDepartment->getNameById($customerInfo['departmentId']);
- $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
- $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName']:'';
- $objMSysAreaChina = new MSysAreaChina();
- if (isset($customerInfo['provinceCode']) && isset($customerInfo['cityCode']) && isset($customerInfo['districtCode'])) {
- $areaName = $objMSysAreaChina->getNameByCode([
- $customerInfo['provinceCode'],
- $customerInfo['cityCode'],
- $customerInfo['districtCode']
- ]);
- $customerInfo['provinceName'] = isset($areaName[$customerInfo['provinceCode']]) ? $areaName[$customerInfo['provinceCode']] : '';
- $customerInfo['cityName'] = isset($areaName[$customerInfo['cityCode']]) ? $areaName[$customerInfo['cityCode']] : '';
- $customerInfo['districtName'] = isset($areaName[$customerInfo['districtCode']]) ? $areaName[$customerInfo['districtCode']] : '';
- }
- $customerInfo['tag'] = $customerInfo['tag'] ? json_decode($customerInfo['tag'], true) : [];
- $customerInfo['mobile'] = $userCenterInfo['mobile'];
- $customerInfo['source'] = $userCenterInfo['source'];
- $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerId);
- if (!empty($customerInfo['latitude']) && !empty($customerInfo['longitude'])) {
- $customerInfo['location'] = [
- 'lat' => $customerInfo['latitude'],
- 'lon' => $customerInfo['longitude']
- ];
- }
- unset($customerInfo['latitude']);
- unset($customerInfo['longitude']);
- $_id = self::createEsDocumentId($customerId);
- $result = $this->objDCustomer->addUpSearchIndexDocument($customerInfo, $_id);
- if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
- // echo "es操作成功";die;
- }
- //echo "es操作失败";
- }
- }
- /**
- * 删除客户
- *
- * @param array $userCenterIds 要删除的客户id
- * @return ResultWrapper
- * @throws Exception
- */
- public function delCustomer($userCenterIds)
- {
- if (empty($userCenterIds)) {
- return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
- }
- $deleteDate =[
- 'userCenterId'=> $userCenterIds,
- ];
-
- $dbResult = $this->objDCustomer->update(['deleteStatus' => StatusCode::$delete], $deleteDate);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
-
- unset($deleteDate);
- $objDUserBindEnterprise = new DUserBindEnterprise();
- $deleteDate =[
- 'userCenterId'=> $userCenterIds,
- 'enterpriseId'=> $this->enterpriseId,
- // 'roleType' => StatusCode::$roleType['customer']//文档建议这样修改
- ];
- $dbResult = $objDUserBindEnterprise->delete($deleteDate);
- if ($dbResult === false) {
- return ResultWrapper::fail($objDUserBindEnterprise->error(), ErrorCode::$dberror);
- }
- //在ES删除
- // $_id = self::createEsDocumentId($delCustomerIds);
- // $this->objDCustomer->esdeleteTypeDocument($_id);
- return ResultWrapper::success($dbResult);
-
- }
- /**
- * 客户启用和禁用
- * @param array $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function updateCustomerStatus($params)
- {
- $dbResult = $this->objDCustomer->get($params['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = $dbResult;
- unset($dbResult);
- if(empty($customerData)){
- return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
- }
- $dbResult = $this->objDCustomer->update(['enableStatus' => $params['enableStatus']], $params['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- //self::updateEsData($params['id']);
- $objCustomerCache = new CustomerCache();
- $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
- $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 修改客户
- * @param $update
- * @param $where
- * @return ResultWrapper
- * @throws Exception
- */
- public function updateCustomer($update, $where)
- {
- if(empty($where)){
- return ResultWrapper::fail('修改客户参数错误', ErrorCode::$paramError);
- }
- $where['deleteStatus'] = StatusCode::$standard;
- $dbResult = $this->objDCustomer->get($where);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = $dbResult;
- unset($dbResult);
- if(empty($customerData)){
- return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
- }
- $dbResult = $this->objDCustomer->update($update, $where);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- // self::updateEsData($customerData['id']);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 客户审核和未审核
- * @param array $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function updateCustomerCheckStatus($params)
- {
- $data = [
- 'status' => $params['status'],
- 'auditFailReason' => ''
- ];
- if ($params['status'] == StatusCode::$auditStatus['auditNotPass']) {
- $data['auditFailReason'] = $params['reason'];
- }
- $dbResult = $this->objDCustomer->update($data, $params['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- } else {
- /*//redis添加客户总数
- $this->objCustomerCache->incrCustomerNum($this->enterpriseId);
- //近一个月注册的用户
- $this->objCustomerCache->incrCustomer($params['id'], $this->enterpriseId);
- //添加今日新增客户数
- $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1);
- $shopId = $this->objDCustomer->get_field('shopId', $params['id']);
- if ($shopId) {
- $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1, $shopId);
- }*/
- $customerData = $this->objDCustomer->get($params['id']);
- self::setCustomerCache($customerData['shopId']);//缓存用户数据
- // self::updateEsData($params['id']);
- $objCustomerCache = new CustomerCache();
- $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
- $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- *
- * 缓存用户数据
- * @param int $shopId
- * @return ResultWrapper
- */
- public function setCustomerCache($shopId = false)
- {
- $result = self::querySelectCondition(['status'=>StatusCode::$auditStatus['auditPass']]);
- if (!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $total =(int) $result->getData();
- //缓存客户总数
- $this->objCustomerCache->setCustomerNum($this->enterpriseId,$total);
- //今日新增客户数
- $todayStart = date('Y-m-d 00:00:00', time());
- $todayEnd = date('Y-m-d 23:59:59', time());
- $todayResult = self::querySelectCondition(
- [
- //'status'=>StatusCode::$auditStatus['auditPass'],
- 'createTime'=>[
- 'lt'=> strtotime($todayStart),
- 'gt'=> strtotime($todayEnd)
- ]
- ]
- );
- if (!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $todayCustomerNum =(int) $todayResult->getData();
- $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum);
- //对应店铺
- if ($shopId) {
- $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum, $shopId);
- }
- }
- /**
- * @param $condition
- * @param bool $total
- * @return ResultWrapper
- */
- public function querySelectCondition($condition,$total = true)
- {
- $field = 'id,status';
- $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.'
- where deleteStatus = '.StatusCode::$standard;
- if (isset($condition['status']) && !empty($condition['status'])){
- $sql .= ' and status = '.StatusCode::$auditStatus['auditPass'];
- }
- if (isset($condition['createTime']) && !empty($condition['createTime'])){
- $sql .= ' and createTime BETWEEN '.$condition['createTime']['lt'] .' and '.$condition['createTime']['gt'];
- }
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- return ResultWrapper::success(count((array)$dbResult));
- }
- /**
- * 不同状态下用户的数量
- * @return ResultWrapper
- * @throws Exception
- */
- public function getNumberUser()
- {
- $field = 'COUNT(id) AS totalCount, SUM(CASE WHEN enableStatus='.StatusCode::$standard.
- ' and status ='.StatusCode::$auditStatus['auditPass'].' THEN 1 ELSE 0 END) AS valid,SUM(CASE WHEN enableStatus='.StatusCode::$delete.' OR status !='.StatusCode::$auditStatus['auditPass'].' THEN 1 ELSE 0 END) AS void';
- $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.'
- where deleteStatus = '.StatusCode::$standard;
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- return ResultWrapper::success(reset($dbResult));
- }
- /**
- * 客户列表
- * @param array $params 过滤条件
- * @return ResultWrapper
- * @throws Exception
- */
- public function getAllCustomer($params)
- {
- $limit = $params['limit'];
- unset($params['limit']);
- $offset = $params['offset'];
- unset($params['offset']);
- $selectParams = 'deleteStatus = ' . StatusCode::$standard . ' AND enterpriseId = ' . $this->enterpriseId;
- if (!empty($params['keyword'])) {
- $selectParams .= ' AND (name LIKE "%' . $params['keyword'] . '%" or managerMobile LIKE "%' . $params['keyword'] . '%")';
- }
- if (!empty($params['type'])) {
- $selectParams .= ' AND type =' . $params['type'];
- }
- if (!empty($params['provinceCode'])) {
- $selectParams .= ' AND provinceCode =' . $params['provinceCode'];
- }
- if (!empty($params['cityCode'])) {
- $selectParams .= ' AND cityCode =' . $params['cityCode'];
- }
- if (!empty($params['districtCode'])) {
- $selectParams .= ' AND districtCode =' . $params['districtCode'];
- }
- if (isset($params['status'])) {
- if ($params['status'] == StatusCode::$auditStatus['completion']) {
- $selectParams .= ' AND status in (' . StatusCode::$auditStatus['completion'] . ',' . StatusCode::$auditStatus['auditNotPass'] . ')';
- } else {
- $selectParams .= ' AND status =' . $params['status'];
- }
- }
- if (!empty($params['enableStatus'])) {
- $selectParams .= ' AND enableStatus =' . $params['enableStatus'];
- }
- if (!empty($params['shopId'])) {
- $selectParams .= ' AND shopId =' . $params['shopId'];
- }
- if (!empty($params['departmentId'])) {
- $selectParams .= ' AND departmentId =' . $params['departmentId'];
- }
- if (!empty($params['salesManId'])) {
- $selectParams .= ' AND salesManId =' . $params['salesManId'];
- }
- if (!empty($params['start'])) {
- $selectParams .= ' AND createTime >=' . $params['start'];
- }
- if (!empty($params['end'])) {
- $selectParams .= ' AND createTime <=' . $params['end'];
- }
- $selectParams = parent::getSalesManQueryParams($selectParams);
- $dbResult = $this->objDCustomer->select($selectParams, '*', 'createTime desc', $limit, $offset);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
-
- $total = $this->objDCustomer->count($selectParams);
-
- $return = [
- 'data' => self::format($dbResult),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 获取企业下的所有客户余额
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerMoney($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $where = 'deleteStatus=' . StatusCode::$standard . ' AND enterpriseId=' . $this->enterpriseId;
- if (isset($selectParams['id'])) {
- $where .= ' AND id=' . $selectParams['id'];
- }
- if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$standard) {
- //有财务纠纷
- $where .= ' AND (money != 0)';
- }
- if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$delete) {
- //无财务纠纷
- $where .= ' AND (money=0)';
- }
- $selectParams = parent::getSalesManQueryParams($where);
- $dbResult = $this->objDCustomer->select($selectParams, 'id AS customerId,name,money,memberBalance', 'createTime desc', $limit, $offset);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- foreach ($dbResult as $key => $value) {
- //获取销售金额,收款金额
- $saleMoney = 0;// 销售金额
- $collectionMoney = 0;// 收款金额
- $objReceiveTable = new DReceive('finance');
- $objReceivedTable = new DReceived('finance');
- $objReceiveIndexTable = new DReceiveReceiptIndex('finance');
- $objReceiveIndexTable->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
- $objReceivedIndexTable = new DReceivedIndex('finance');
- $objReceivedIndexTable->setTable('qianniao_received_index_'.$this->enterpriseId);
- $receiveIndexSql = 'select * from '.$objReceiveIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
- $receiveIndexDate = $objReceiveIndexTable->query($receiveIndexSql);
- if($receiveIndexDate === false){
- return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
- }
- if(!empty($receiveIndexDate)){
- foreach ($receiveIndexDate as $receiveKey => $receiveValue){
- $suffix = date('Y', $receiveValue['createTime']) . '_' . ceil(date('m', $receiveValue['createTime']) / 3);
- $objReceiveTable->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
- $receiveDate = $objReceiveTable->get($receiveValue['id']);
- $saleMoney = bcadd($saleMoney,$receiveDate['receiveMoney'],2);
- }
- }
- $receivedIndexSql = 'select * from '.$objReceivedIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
- $receivedIndexDate = $objReceivedIndexTable->query($receivedIndexSql);
- if($receiveIndexDate === false){
- return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
- }
- if(!empty($receivedIndexDate)){
- foreach ($receivedIndexDate as $receivedKey => $receivedValue){
- $objReceivedTable->setTable('qianniao_received_' . $this->enterpriseId . '_' . date('Y', $receivedValue['createTime']) . '_' . ceil(date('m', $receivedValue['createTime']) / 3));
- $receivedDate = $objReceivedTable->get($receivedValue['id']);
- $collectionMoney = bcadd($collectionMoney,isset($receivedDate['totalFinalMoney']) ? $receivedDate['totalFinalMoney'] :0,2);
- }
- }
- $dbResult[$key]['openingBalance'] = $value['money'];
- // $dbResult[$key]['interimBalance'] = 0;
- $dbResult[$key]['saleMoney'] = $saleMoney;
- $dbResult[$key]['collectionMoney'] = $collectionMoney;
- $dbResult[$key]['endingBalance'] = $value['money'];
- $dbResult[$key]['memberBalance'] = $value['memberBalance'];
- unset($dbResult[$key]['money']);
- }
- $total = $this->objDCustomer->count($selectParams);
- $return = [
- 'data' => $dbResult,
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 查询客户标签
- * @param $id
- * @return array
- */
- public function getCustomerTag($id)
- {
- $dbResult = $this->objDCustomer->get($id, 'tag');
- return $dbResult;
- }
- /**
- * 添加客户标签
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function addCustomerTag($params)
- {
- $tagResult = $this->getCustomerTag($params['id']);
- //判断标签是否已经存在
- $tags = isset($tagResult['tag']) ? json_decode($tagResult['tag'], true) : [];
- if ($tags && in_array($params['tag'], $tags)) {
- return ResultWrapper::fail("客户标签已存在", ErrorCode::$resubmit);
- }
- $tags[] = $params['tag'];
- $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- } else {
- // self::updateEsData($params['id']);
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 删除客户标签
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function delCustomerTag($params)
- {
- $tagResult = $this->getCustomerTag($params['id']);
- //判断标签是否已经存在
- $tags = json_decode($tagResult['tag'], true);
- if (!$tags || !in_array($params['tag'], $tags)) {
- return ResultWrapper::fail("客户标签不存在", ErrorCode::$resubmit);
- }
- //标签存在,进行删除
- foreach ($tags as $key => $tag) {
- if ($tag == $params['tag']) {
- unset($tags[$key]);
- }
- }
- $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- } else {
- // self::updateEsData($params['id']);
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 搜索
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- * @throws Exception
- */
- public function search($selectParams)
- {
- $defaultDSL = [
- 'from' => $selectParams['offset'],
- 'size' => $selectParams['limit'],
- 'sort' => [
- 'createTime' => [
- 'order' => 'desc'
- ],
- ],
- ];
- $dsl = [];
- $dsl['query']['bool']['must'][] = [
- 'term' => ['deleteStatus' => StatusCode::$standard],
- //'term' => ['enterpriseId' => $this->enterpriseId],
- ];
- $dsl['query']['bool']['must'][] = [
- //'term' => ['deleteStatus' => StatusCode::$standard],
- 'term' => ['enterpriseId' => $this->enterpriseId],
- ];
- //客户名称/手机号
- if (!empty($selectParams['keyword'])) {
- $dsl['query']['bool']['must'][] = [
- 'multi_match' => [
- 'fields' => ['name^1.5', 'mobile', 'tag', 'managerMobile'],
- 'query' => $selectParams['keyword'],
- //'fuzziness' => 'AUTO',
- "type" => "best_fields",
- "tie_breaker" => 0.3,
- "minimum_should_match" => "100%"
- ],
- ];
- }
- //客户类型
- if (!empty($selectParams['type'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['type' => $selectParams['type']]];
- }
- //省code
- if (!empty($selectParams['provinceCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['provinceCode' => $selectParams['provinceCode']]];
- }
- //市code
- if (!empty($selectParams['cityCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['cityCode' => $selectParams['cityCode']]];
- }
- //区code
- if (!empty($selectParams['districtCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['districtCode' => $selectParams['districtCode']]];
- }
- //客户审核状态
- if (!empty($selectParams['status'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['status' => $selectParams['status']]];
- }
- //客户启用状态
- if (!empty($selectParams['enableStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['enableStatus' => $selectParams['enableStatus']]];
- }
- //商铺id
- if (!empty($selectParams['shopId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['shopId' => $selectParams['shopId']]];
- }
- //部门id
- if (!empty($selectParams['departmentId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['departmentId' => $selectParams['departmentId']]];
- }
- parent::getAccessSalesManIds();
- if (parent::$salesManIds) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => ['salesManId' => parent::$salesManIds]
- ];
- }
- //业务员id
- if (!empty($selectParams['salesManId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['salesManId' => $selectParams['salesManId']]];
- }
- if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['start'],
- 'lte' => $selectParams['end'],
- ]
- ]
- ];
- } else {
- if (!empty($selectParams['start'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['start'],
- ]
- ]
- ];
- }
- if (!empty($selectParams['end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'lte' => $selectParams['end'],
- ]
- ]
- ];
- }
- }
- $dsl = array_merge($defaultDSL, $dsl);
- $result = $this->objDCustomer->getSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- if ($result['error']['reason'] == 'all shards failed') {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- if (!isset($result['hits']) || $result['hits']['total'] == 0) {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- $total = $result['hits']['total'];
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- $data = [];
- $data = $value['_source'];
- //$data['id'] = $value['_id'];
- $list[] = $data;
- }
- $return = [
- 'data' => self::format($list),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 搜索 客户查询
- *
- * @param array $selectParams 过滤条件
- *
- * @return ResultWrapper
- * @throws Exception
- */
- public function query($selectParams)
- {
- $defaultDSL = [
- 'from' => $selectParams['offset'],
- 'size' => $selectParams['limit'],
- 'sort' => [
- 'createTime' => [
- 'order' => 'desc'
- ],
- ],
- ];
- $dsl = [];
- $dsl['query']['bool']['must'][] = [
- 'term' => ['deleteStatus' => StatusCode::$standard],
- //'term' => ['enterpriseId' => $this->enterpriseId],
- ];
- $dsl['query']['bool']['must'][] = [
- //'term' => ['deleteStatus' => StatusCode::$standard],
- 'term' => ['enterpriseId' => $this->enterpriseId],
- ];
- //客户名称/手机号
- if (!empty($selectParams['keyword'])) {
- $dsl['query']['bool']['must'][] = [
- 'multi_match' => [
- 'fields' => ['name', 'mobile', 'managerMobile'],
- 'query' => $selectParams['keyword'],
- //'fuzziness' => 'AUTO',
- "type" => "best_fields",
- "tie_breaker" => 0.3,
- "minimum_should_match" => "100%"
- ],
- ];
- }
- //标签
- if (!empty($selectParams['tag'])) {
- $dsl['query']['bool']['must'][] = [
- 'match' => [
- 'tag' => $selectParams['tag'],
- ],
- ];
- }
- //省code
- if (!empty($selectParams['provinceCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['provinceCode' => $selectParams['provinceCode']]];
- }
- //市code
- if (!empty($selectParams['cityCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['cityCode' => $selectParams['cityCode']]];
- }
- //区code
- if (!empty($selectParams['districtCode'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['districtCode' => $selectParams['districtCode']]];
- }
- //客户启用状态
- if (!empty($selectParams['enableStatus'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['enableStatus' => $selectParams['enableStatus']]];
- }
- //商铺id
- if (!empty($selectParams['shopId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['shopId' => $selectParams['shopId']]];
- }
- //来源
- if (!empty($selectParams['source'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['source' => $selectParams['source']]];
- }
- parent::getAccessSalesManIds();
- if (parent::$salesManIds) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => ['salesManId' => parent::$salesManIds]
- ];
- }
- //业务员id
- if (!empty($selectParams['salesManId'])) {
- $dsl['query']['bool']['filter'][] =
- ['term' => ['salesManId' => $selectParams['salesManId']]];
- }
- if (!empty($selectParams['birthday_start']) && !empty($selectParams['birthday_end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['birthday_start'],
- 'lte' => $selectParams['birthday_end'],
- ]
- ]
- ];
- } else {
- if (!empty($selectParams['birthday_start'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'gte' => $selectParams['birthday_start'],
- ]
- ]
- ];
- }
- if (!empty($selectParams['birthday_end'])) {
- $dsl['query']['bool']['must'][] = [
- 'range' => [
- 'createTime' => [
- 'lte' => $selectParams['birthday_end'],
- ]
- ]
- ];
- }
- }
- $dsl = array_merge($defaultDSL, $dsl);
- $result = $this->objDCustomer->getSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- if ($result['error']['reason'] == 'all shards failed') {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- if (!isset($result['hits']) || $result['hits']['total'] == 0) {
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0
- ]);
- }
- $total = $result['hits']['total'];
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- $data = [];
- $data = $value['_source'];
- //$data['id'] = $value['_id'];
- $list[] = $data;
- }
- $return = [
- 'data' => self::format($list),
- 'total' => ($total) ? intval($total) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 根据code获取今日下单客户的经纬度信息
- * @param string $code 省市区编码
- * @return ResultWrapper
- */
- public function getTodayOrderCustomerLocation($code = '')
- {
- $result = [];
- $objCustomerCache = new CustomerCache();
- $customerIds = $objCustomerCache->getTodayCustomerOrderInfo($this->enterpriseId, $code);
- $dsl = [];
- $dsl['query']['terms'] = [
- '_id' => $customerIds,
- ];
- $result = $this->objDCustomer->getSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- if (!isset($result['hits']) || $result['hits']['total'] == 0) {
- return ResultWrapper::success([]);
- }
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- $location = $value['_source']['location'];
- $list[] = [
- 'lng' => $location['lon'],
- 'lat' => $location['lat']
- ];
- }
- return ResultWrapper::success($list);
- }
- /**
- * 根据code获取客户分布图
- * @param string $code 省市区编码
- * @return ResultWrapper
- */
- public function getCustomerLocation($code = '')
- {
- $dsl = [];
- parent::getAccessSalesManIds();
- if (parent::$salesManIds) {
- $dsl['query']['bool']['filter'][] = [
- 'terms' => ['salesManId' => parent::$salesManIds]
- ];
- }
- if (!empty($code)) {
- $dsl['query']['bool']['must'][] = [
- 'term' => ['districtCode' => $code],
- ];
- }
- $result = $this->objDCustomer->getSearchQueryDsl($dsl);
- if (isset($result['status']) && $result['status'] == 400) {
- if ($result['error']['reason'] == 'all shards failed') {
- return ResultWrapper::success([]);
- }
- return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
- }
- if (!isset($result['hits']) || $result['hits']['total'] == 0) {
- return ResultWrapper::success([]);
- }
- $dbResult = $result['hits']['hits'];
- $list = [];
- foreach ($dbResult as $key => &$value) {
- if (isset($value['_source']['location'])) {
- $location = $value['_source']['location'];
- $list[] = [
- 'lng' => $location['lon'],
- 'lat' => $location['lat']
- ];
- }
- }
- return ResultWrapper::success($list);
- }
- /**
- * 根据userCenterId获取customerId
- * @param $userCenterId
- * @return mixed
- */
- public function getCustomerIdByUserCenterId($userCenterId)
- {
- $customerId = $this->objDCustomer->get_field('id', ['userCenterId' => $userCenterId]);
- return $customerId ? $customerId : 0;
- }
- /**
- * 根据customerId获取userCenterId
- * @param $customerId
- * @return mixed
- */
- public function getUserCenterIdByCustomerId($customerId)
- {
- $userCenterId = $this->objDCustomer->get_field('userCenterId', ['id' => $customerId]);
- return $userCenterId ? $userCenterId : 0;
- }
- /**
- * 根据openId获取userCenterId
- * @param $openId
- * @return mixed
- */
- public function getUserCenterIdByOpenId($openId)
- {
- $userCenterId = $this->objDCustomer->get_field('userCenterId', ['openId' => $openId]);
- return $userCenterId ? $userCenterId : 0;
- }
- /**
- * 通过openId或者uniondId获取userCenterId
- * @param $params
- * @param $source
- * @return ResultWrapper
- * @throws Exception
- */
- public function getUserCenterIdByOpenIdOrUnionId($params, $source)
- {
- $whereSql = '';
- if( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['android'],StatusCode::$source['ios'],StatusCode::$source['weiXinBrowser']]) ) {
- //微信
- $whereSql = ' where openId = "' . $params['openId'] . '"';
- !empty($params['unionId']) && $whereSql .= ' or unionId = "' . $params['unionId'] . '"';
- // !empty($params['unionId']) && $whereSql .= ' and unionId = "' . $params['unionId'] . '"';//文档建议这样修改
- }
- if ($source == StatusCode::$source['ByteProgram']) {
- //抖音
- $whereSql = ' where byteOpenId = "' . $params['openId'] . '"';
- }
- if (empty($whereSql)) {
- return ResultWrapper::fail('查询客户source参数错误', ErrorCode::$paramError);
- }
- $this->objDCustomer->setTable('qianniao_customer_' . $this->enterpriseId);
- $sql = 'select * from ' . $this->objDCustomer->get_Table() . $whereSql;
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- //是空仍然返回
- return ResultWrapper::success($dbResult);
- }
- /**
- * 指定字段修改用户数据
- * @param $where
- * @param $update
- * @return ResultWrapper
- */
- public function setCustomerData($where, $update)
- {
- $dbResult = $this->objDCustomer->update($update, $where);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 绑定覆盖unionId (微信, 抖音)
- * @param $source
- * @param $userCenterId
- * @param $openId
- * @param $unionId
- * @param string $avatar
- * @param string $name
- * @return ResultWrapper
- */
- public function bindOpenIdAndMobile($source, $userCenterId, $openId, $unionId, $avatar = '', $name = '')
- {
- //判断是微信还是抖音
- if ( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['ios'],StatusCode::$source['android'],StatusCode::$source['weiXinBrowser']])) {
- !empty($openId) && $param['openId'] = $openId;
- $param['unionId'] = $unionId;
- } elseif ($source == StatusCode::$source['ByteProgram']) {
- $param['byteOpenId'] = $openId;
- } else {
- return ResultWrapper::fail('覆盖客户绑定数据source参数错误', ErrorCode::$paramError);
- }
- if (empty($param)) {
- return ResultWrapper::fail('覆盖客户绑定修改数据为空', ErrorCode::$paramError);
- }
- $dbResult = $this->objDCustomer->update($param, ['userCenterId' => $userCenterId]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- } else {
- return ResultWrapper::success($dbResult);
- }
- }
- /**
- * 根据userCenterId和企业id查询客户数据
- * @param $userCenterId
- * @param $enterpriseId
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerDataByUserCenterIdAndEnterpriseId($userCenterId, $enterpriseId = false)
- {
- !$enterpriseId && $enterpriseId = $this->enterpriseId;
- $this->objDCustomer->setTable('qianniao_customer_' . $enterpriseId);
- $dbResult = $this->objDCustomer->get(['userCenterId' => $userCenterId, 'enterpriseId' => $enterpriseId, 'deleteStatus' => StatusCode::$standard]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 获取客户基本信息
- */
- public function getCustomerBasicInfoByUserCenterIds($userCenterIds = [])
- {
- if(empty($userCenterIds)){
- return ResultWrapper::success('未指定查询的userCenterIds', ErrorCode::$paramError);
- }
- $sql = 'select c.*,u.mobile from qianniao_customer_'.$this->enterpriseId.' as c left join qianniao_user_center as u on u.id = c.userCenterId where c.userCenterId in ('. implode(',', $userCenterIds) .')';
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 根据userCenterId获取客户完整信息 看不懂?????
- * @param $userCenterId
- * @param $fields
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerInfoByUserCenterId($userCenterId,$isMini = false)
- {
- $customerInfo = $this->objCustomerCache->getCustomerUserData($this->enterpriseId,$userCenterId);
- // if (empty($customerInfo)) {
- $sql = 'SELECT u.mobile,c.*,c.money as balance FROM ' . $this->objDUserCenter->get_Table() . ' AS u JOIN ' . $this->objDCustomer->get_Table() . ' AS c ON u.id=c.userCenterId AND u.id = ' . $userCenterId . ' LIMIT 1';
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if (empty($dbResult)) {
- return ResultWrapper::fail('要查询的客户不存在', ErrorCode::$contentNotExists);
- }
- //查业务员名称
- $customerInfo = array_shift($dbResult);
- $sourceType = isset($customerInfo['type']) ? $customerInfo['type'] : null;
- $dbResult['customerSourceTypeName'] = '';
- $dbResult['modelType'] = '';
- if (!empty($sourceType)) {
- //映射客户类型名称
- $fields = 'id,name,modelType';
- $customerSource = $this->objDCustomer->query('select ' . $fields . ' from qianniao_customer_source where id = ' . $sourceType);
- if ($customerSource === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerSourceInfo = array_shift($customerSource);
- $dbResult['customerSourceTypeName'] = isset($customerSourceInfo['name']) ? $customerSourceInfo['name'] : '';
- $dbResult['modelType'] = isset($customerSourceInfo['modelType']) ? $customerSourceInfo['modelType'] : '';
- }
- $customerInfo['extend'] = json_decode($customerInfo['extend'], true);
- $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
- $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName'] : '';
- $customerInfo['salesManMobile'] = isset($salesManDate['userMobile']) ? $salesManDate['userMobile'] : '';
- $customerInfo['modelType'] = $dbResult['modelType'];
- $customerInfo['customerSourceTypeName'] = $dbResult['customerSourceTypeName'];
- //联系人
- $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerInfo['id']);
- $this->objCustomerCache->cacheCustomerUserData($this->enterpriseId,$userCenterId,$customerInfo);
- // }
- if ($isMini === true){
- $objMUserCoupon = new MUserCoupon($this->userCenterId,$this->enterpriseId);
- $couponNumResult = $objMUserCoupon->getCouponNum($userCenterId);
- if (!$couponNumResult->isSuccess()){
- return ResultWrapper::fail($couponNumResult->getData(),$couponNumResult->getErrorCode());
- }
- $objMVipCard = new MVipCard($this->enterpriseId,$this->userCenterId);
- $vipNumResult = $objMVipCard->getVipCardNum($userCenterId);
- if (!$vipNumResult->isSuccess()){
- return ResultWrapper::fail($vipNumResult->getData(),$vipNumResult->getErrorCode());
- }
- $customerInfo['vipNum'] = (int)$vipNumResult->getData();
- $customerInfo['couponNum'] = $couponNumResult->getData();
- $objMGoodsCollect = new MGoodsCollect($this->enterpriseId,$this->userCenterId);
- $collNumResult = $objMGoodsCollect->getCollNum($userCenterId);
- if (!$collNumResult->isSuccess()){
- return ResultWrapper::fail($collNumResult->getData(),$collNumResult->getErrorCode());
- }
- $customerInfo['collNum'] = (int)$collNumResult->getData();
- }
- //查询店铺信息
- $customerInfo['shopDate'] = [];
- $objDShop = new DShop();
- $objDShop->setTable('qianniao_shop_1');
- $shopResult = $objDShop->get(['enterpriseId'=>$this->enterpriseId]);
- if ($shopResult === false) {
- return ResultWrapper::fail($objDShop->error(), ErrorCode::$dberror);
- }
- $customerInfo['shopDate'] = $shopResult;
- $customerInfo['enterpriseMobile'] = isset($customerInfo["enterpriseMobile"])? $customerInfo["enterpriseMobile"]:"";//文档建议这样修改,返回一个企业联系电话
- return ResultWrapper::success($customerInfo);
- }
- /**
- * @param $selectParams
- * @param string $field
- * @return ResultWrapper
- */
- public function getCustomer($selectParams, $field = 'name,id')
- {
- $dbResult = $this->objDCustomer->select($selectParams, $field);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = [];
- if (!empty($dbResult)) {
- foreach ($dbResult as $info) {
- $customerData[$info['id']] = $info;
- }
- }
- return ResultWrapper::success($customerData);
- }
- /**
- * 获取客户总数
- */
- public function getCustomerTotalNum()
- {
- $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
- if ($result === false){
- //缓存客户数据
- self::setCustomerCache();
- $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
- }
- return $result ? $result : 0;
- }
- /**
- * 今日新增客户数
- * @param null $shopId
- * @return bool|int
- */
- public function getTodayCustomerTotalNum($shopId = null)
- {
- /*$result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
- if ($result === false){
- self::setCustomerCache();
- $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
- }*/
- self::setCustomerCache($shopId);
- $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
- return $result ? $result : 0;
- }
- /**
- * 获取总的应收款
- */
- public function getTotalShouldReceive()
- {
- $result = $this->objOverviewCache->getAggregateStatistics($this->enterpriseId, 'totalShouldReceive');
- return $result ? $result : 0;
- }
- /**
- *获取新增客户数(近30天注册但未交易)
- */
- public function getNewCustomerNum()
- {
- $result = $this->objCustomerCache->getNewCustomerNum($this->enterpriseId);
- return $result ? $result : 0;
- }
- /**
- *获取兴趣人群数
- */
- public function getInterestCustomerNum()
- {
- $result = $this->objCustomerCache->getInterestCustomerNum($this->enterpriseId);
- return $result ? $result : 0;
- }
- /**
- * 今日客户排行
- * @param int $ranking 1销量排行 2销额排行
- * @return array
- */
- public function todayCustomerRanking($ranking = 1)
- {
- if ($ranking == 1) {
- $result = $this->objOverviewCache->getRanking($this->enterpriseId, 'customerRanking');
- } else {
- $result = $this->objOverviewCache->getSalesMoneyRanking($this->enterpriseId, 'customerRanking');
- }
- if (empty($result)) {
- return [];
- }
- //拼接customerId
- $customerIds = [];
- foreach ($result as $customerId => $v) {
- $i = 1;
- $customerIds[] = $customerId;
- $i++;
- if ($i >= 8) {
- break;
- }
- }
- //查找客户名称
- $customerResult = self::getCustomer($customerIds);
- $customerNameData = [];
- if ($customerResult->isSuccess()) {
- $customerNameData = $customerResult->getData();
- }
- //拼接返回数据
- $return = [];
- foreach ($result as $customerId => $v) {
- $i = 1;
- $rank = [];
- $rank['id'] = $i;
- $rank['customerName'] = isset($customerNameData[$customerId]['name']) ? $customerNameData[$customerId]['name'] : '';
- $rank['numberOrMoney'] = $v;
- $return[] = $rank;
- $i++;
- if ($i >= 8) {
- break;
- }
- }
- return $return;
- }
- /**
- * 格式化客户
- */
- public function formatCustomer()
- {
- //查询所有企业
- $sql = 'select id from qianniao_enterprise_1 where deleteStatus = 5';
- $dbResult = $this->objDCustomer->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $ii = 0;
- $enterprise = $dbResult;
- unset($dbResult);
- foreach($enterprise as $enterpriseValue){
- //查询客户
- $this->objDCustomer->setTable('qianniao_customer_'.$enterpriseValue['id']);
- $dbResult = $this->objDCustomer->select();
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if(empty($dbResult)){
- continue;
- }
- //循环客户
- foreach($dbResult as $value){
- //修改营业执照
- $extend = json_decode($value['extend'], true);
- if(isset($extend['license']) && !empty($extend['license']) && strpos($extend['license'],'?imageView2') !== false){
- $extend['license'] = substr($extend['license'], 0, strrpos($extend['license'],'?imageView2'));
- $update['extend'] = json_encode($extend);
- //保存客户
- $result = $this->objDCustomer->update($update, ['id' => $value['id']]);
- if($result === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $ii++;
- }
- }
- }
- return ResultWrapper::success('修改成功, 共修改'.$ii.'条数据');
- }
- /**
- * 充值余额
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function rechargeBalance($params)
- {
- $where['userCenterId'] = $params['userCenterId'];
- //查询客户信息
- $dbResult = $this->objDCustomer->get($where);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = $dbResult;
- unset($dbResult);
- //记录充值记录
- $recordInsert = [
- 'no' => createOrderSn(StatusCode::$source['miniProgram'], 0, $customerData['userCenterId']),
- 'customerId' => $customerData['id'],
- 'money' => $params['money'],
- 'userCenterId' => $customerData['userCenterId'],
- 'shopId' => $customerData['shopId'],
- 'payStatus' => StatusCode::$delete,
- 'desc' => '充值余额'.$params['money'].'元',
- 'createTime' => time(),
- 'updateTime' => time(),
- ];
- $dbResult = $this->objDCustomerRechargeRecord->insert($recordInsert);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
- $recordId = $dbResult;
- unset($dbResult);
- //获取支付配置
- $objMPaymentSetting = new MPaymentSetting($this->enterpriseId, $this->userCenterId);
- $result = $objMPaymentSetting->getPayData($params['payType']);
- if (!$result->isSuccess() || empty($result->getData())) {
- return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
- }
- $payment = $result->getData();
- // 获取当前登录企业的小程序配置
- $objSystemCache = new SystemCache();
- $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
- if (empty($miniprogramSetting)) {
- return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
- }
- $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
- $appid = $miniprogramSetting['appid'];
- $paySource = 'miniProgram';
- $weixinConfigData = [
- 'mch_id' => $payment['mchId'],
- 'apiPartnerKey' => $payment['apiPartnerKey'],
- 'appid' => $appid
- ];
- $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . $recordId;
- $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
- $modelResult = $objPay->unifiedorder($recordInsert['no'], $params['money'], $params['ip'], $paySource, '千鸟云商', $customerData['openId'], $attach);
- if (!$modelResult->isSuccess()) {
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- return ResultWrapper::success($modelResult->getData());
- }
- /**
- * 支付完成调用方法
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function payTrue($params)
- {
- //查询充值记录
- $dbResult = $this->objDCustomerRechargeRecord->get(['id' => $params['id']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
- $record = $dbResult;
- unset($dbResult);
- //查询客户
- $dbResult = $this->objDCustomer->get(['id' => $record['customerId']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = $dbResult;
- unset($dbResult);
- //客户修改数据
- $update = [
- 'money' => bcadd($customerData['money'], $record['money'], 4),
- 'updateTime' => time(),
- ];
- //修改充值记录状态
- $updateRecord = [
- 'balance' => $update['money'],
- 'payStatus' => StatusCode::$standard,
- 'updateTime' => time(),
- ];
- //开启事务
- $this->objDCustomerRechargeRecord->beginTransaction();
- $dbResult = $this->objDCustomerRechargeRecord->update($updateRecord, ['id' => $params['id']]);
- if($dbResult === false){
- $this->objDCustomerRechargeRecord->rollBack();
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
- //记录余额流水
- $turnoverInsert = [
- 'sourceId' => $record['id'],
- 'sourceNo' => $record['no'],
- 'source' => 1,//来源 1:充值余额
- 'customerId' => $customerData['id'],
- 'userCenterId' => $customerData['userCenterId'],
- 'shopId' => $customerData['shopId'],
- 'money' => $record['money'],
- 'balance' => $update['money'],
- 'type' => StatusCode::$standard,
- 'desc' => '充值余额'.$record['money'].'元',
- 'createTime' => time(),
- 'updateTime' => time(),
- ];
- $dbResult = $this->objDCustomerBalanceTurnover->insert($turnoverInsert);
- if($dbResult === false){
- $this->objDCustomerRechargeRecord->rollBack();
- return ResultWrapper::fail($this->objDCustomerBalanceTurnover->error(), ErrorCode::$dberror);
- }
- //增加财务客户余额流水
- $objMCustomerBalanceDetail = new MCustomerBalanceDetail($this->enterpriseId, $this->userCenterId);
- $detailInsert = [
- 'customerId' => $customerData['id'],//'客户id',
- 'receiptTime' => time(),//'单据日期',
- 'sourceId' => $customerData['id'],
- 'sourceNo' => createOrderSn(StatusCode::$source['miniProgram'], 8, $customerData['userCenterId']),//'单据编号',
- 'financeType' => '会员余额充值收款',//'财务类型名称',
- 'financeTypeId' => 8,//'财务类型id',
- 'sourceId' => $record['id'],
- 'sourceNo' => $record['no'],//'源订单销货号',
- 'salesAmount' => $record['money'],//总金额
- 'discountMoney' => 0,// '优惠金额',
- 'customerAmount' => $record['money'],// '客户承担金额',
- 'receivableAmount' => $record['money'],// '应收金额',
- 'actualReceivableAmount' => $record['money'],//'实际收款金额',
- 'receivableBalance' => $update['money'],//'应收后余额',
- 'remark' => '客户充值余额 本次实收' . $record['money'] . '元',//'备注',
- 'createTime' => time(),//'创建日期',
- 'updateTime' => time(),//'修改日期',
- ];
- $modelResult = $objMCustomerBalanceDetail->addCustomerBalanceDetail($detailInsert);
- if(!$modelResult->isSuccess()){
- $this->objDCustomerRechargeRecord->rollBack();
- return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
- }
- //修改客户余额
- $dbResult = $this->objDCustomer->update($update, ['id' => $customerData['id']]);
- if($dbResult === false){
- $this->objDCustomerRechargeRecord->rollBack();
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- //提交事务
- $this->objDCustomerRechargeRecord->commit();
- return ResultWrapper::success('支付成功');
- }
- /**
- * 充值记录列表
- * @param $params
- * @return ResultWrapper
- */
- public function getAllRechargeBalance($params)
- {
- $limit = $params['limit'];
- $offset = $params['offset'];
- $where = [];
- if(isset($params['customerId'])){
- $where['customerId'] = $params['customerId'];
- }
- if(isset($params['userCenterId'])){
- $where['userCenterId'] = $params['userCenterId'];
- }
- $dbResult = $this->objDCustomerRechargeRecord->select($where, '*', 'createTime desc', $limit, $offset);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
- $data = $dbResult;
- unset($dbResult);
- $count = $this->objDCustomerRechargeRecord->count($where);
- $return = [
- 'data' => $data,
- 'total' => $count ? $count : 0
- ];
- return ResultWrapper::success($return);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2021/1/15
- * Time: 5:35 下午
- * @param $ids
- * @return ResultWrapper
- * @throws Exception
- */
- public function getCustomerByIds($ids): ResultWrapper
- {
- if (empty($ids)){
- return ResultWrapper::success([]);
- }
- $lists = $this->objDCustomer->select(['id' => $ids]);
- if ($lists === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- $formatLists = self::format($lists);
- return ResultWrapper::success($formatLists);
- }
- /**
- * Doc: (des="")
- * User: XMing
- * Date: 2020/11/14
- * Time: 10:40 上午
- * @param $customerId
- * @return ResultWrapper
- */
- public function getCustomerByCustomerId($customerId): ResultWrapper
- {
- if (empty($customerId)){
- return ResultWrapper::success([]);
- }
- $fields = ' u.mobile,c.id,c.salesManId,c.avatar,c.name,c.birthday,c.provinceCode,c.cityCode,c.districtCode,c.status,c.auditFailReason,c.enableStatus,c.openId,c.type,c.remark,c.extend ';
- $sql = 'SELECT '.$fields.' FROM ' . $this->objDUserCenter->get_Table() . '
- AS u JOIN ' . $this->objDCustomer->get_Table() . '
- AS c ON u.id=c.userCenterId AND c.id=' . $customerId . ' LIMIT 1';
- $dbResult = $this->objDCustomer->query($sql);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $dbResult = (array)$dbResult;
- $dbResult = array_shift($dbResult);
- return ResultWrapper::success($dbResult);
- }
- /**
- * 首字母搜索客户
- * @param $data
- * @return ResultWrapper
- */
- public function initialsSearch($data)
- {
- $condition = isset($data['condition']) && !empty($data['condition']) ? $data['condition'] : '';
- if (empty($condition)) return ResultWrapper::success([]);
- $objChineseCharacter = new ChineseCharacter();
- $condition = $objChineseCharacter->getInitials($condition);
- $sql = 'select c.* from '.$this->objDCustomer->get_Table().' c left join qianniao_user_center u on c.userCenterId = u.id where c.deleteStatus = '.StatusCode::$standard.' and c.enableStatus = '.StatusCode::$standard.' and c.condition like "%'.$condition.'%" or u.mobile like "%'.$condition.'%" order by c.createTime desc';
- $dbResult = $this->objDCustomer->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
- /**
- * 初始化客户首字母
- */
- public function initialsCustomer()
- {
- $objChineseCharacter = new ChineseCharacter();
- $dbResult = $this->objDCustomer->select();
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- foreach($dbResult as $value){
- $condition = $objChineseCharacter->getInitials(trim($value['name']));
- $result = $this->objDCustomer->update(['condition' => $condition], ['id' => $value['id']]);
- if($result === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- }
- return ResultWrapper::success('执行成功');
- }
- /**
- * Doc: (des="根据客户id获取客户实时的分拣区")
- * User: XMing
- * Date: 2020/12/25
- * Time: 4:57 下午
- * @param $ids
- * @return ResultWrapper
- */
- public function getReservoirByCustomerIds($ids): ResultWrapper
- {
- if (empty($ids)){
- return ResultWrapper::success([]);
- }
- $customer = $this->objDCustomer->select($ids);
- if ($customer === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- $reservoirIds = [];
- foreach ($customer as $value){
- if (empty($value['reservoirId'])){
- continue;
- }
- $reservoirIds[] = $value['reservoirId'];
- }
- $objMReservoirArea = new MReservoirArea($this->enterpriseId,$this->userCenterId);
- $reservoir = [];
- if(!empty($reservoirIds)){
- $reservoirResult = $objMReservoirArea->getReservoirMapByIds(['id' => $reservoirIds]);
- if (!$reservoirResult->isSuccess()){
- return ResultWrapper::fail($reservoirResult->getData(),$reservoirResult->getErrorCode());
- }
- $reservoir = $reservoirResult->getData();
- }
- $reservoirMap = [];
- foreach ($customer as $value){
- $reservoirId = $value['reservoirId'];
- $row = getArrayItem($reservoir,$reservoirId,[]);
- $reservoirMap[$value['id']] = [
- 'name' => getArrayItem($row, 'name', ''),
- 'warehouseId' => getArrayItem($row, 'warehouseId', 0),
- 'code' => getArrayItem($row, 'code', ''),
- 'type' => getArrayItem($row, 'type', 0)
- ];
- }
- return ResultWrapper::success($reservoirMap);
- }
- /**
- * Doc: (des="查询客户商品购买记录")
- * User: XMing
- * Date: 2021/3/10
- * Time: 10:59 上午
- * @param array $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function searchCustomerBuyLog(array $params ,$export = 0): ResultWrapper
- {
- $objMOrder = new MOrder($this->userCenterId,$this->enterpriseId);
- if($export){
- $params['limit'] = null;
- $params['offset'] = null;
- }
- $dbResult = $objMOrder->getGoodsListsByUserCenterId($params);
- if (!$dbResult->isSuccess()){
- return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
- }
- //客户购买记录导出
- if($export){
- self::exportCustomerBuyLog($dbResult->getData()['data']);
- exit;
- }
- return ResultWrapper::success($dbResult->getData());
- }
- /**
- * Doc: (des="获取客户的余额")
- * User: XMing
- * Date: 2021/3/18
- * Time: 10:55 上午
- * @param int $customerId
- * @return ResultWrapper
- */
- public function getCustomerBalance(int $customerId): ResultWrapper
- {
- $result = $this->objDCustomer->get($customerId);
- if ($result === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
- }
- if (empty($result)){
- return ResultWrapper::fail('为获取到客户的余额信息',ErrorCode::$paramError);
- }
- $money = getArrayItem($result,'money',0);
- return ResultWrapper::success($money);
- }
- /**
- * Doc: (des="修改客户的余额并增加流水记录")
- * User: XMing
- * Date: 2021/3/18
- * Time: 11:41 上午
- * @param int $customerId
- * @param float $changeMoney
- * @return ResultWrapper
- */
- public function decCustomerBalance(int $customerId,float $changeMoney,$tmpOuterTradeNo): ResultWrapper
- {
- if (empty($changeMoney)){
- return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError);
- }
- $customerResult = self::getCustomerBalance($customerId);
- if (!$customerResult->isSuccess()){
- return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
- }
- $customerMoney = $customerResult->getData();
- if($customerMoney >= 0){
- return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
- }
- if ($customerMoney <0 && (bccomp($changeMoney,abs($customerMoney),2) > 0)){
- return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
- }
- //扣除余额,
- $update = [
- 'money' => bcsub($customerMoney,$changeMoney,2),
- 'updateTime' => time()
- ];
- $updateResult = $this->objDCustomer->update($update,$customerId);
- if ($updateResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$paramError);
- }
- //TODO(增加流水)
- $trans = [
- 'tmpOuterTradeNo' => $tmpOuterTradeNo,
- 'oldMoney' => $customerMoney,
- 'payMoney' => $changeMoney,
- 'createTime' => time(),
- 'money' => $update['money']
- ];
- $update['tmpOuterTradeNo'] = $tmpOuterTradeNo;
- Logger::logs(E_USER_ERROR,'订单余额支付记录'.$tmpOuterTradeNo,__CLASS__,__LINE__,$trans);
- return ResultWrapper::success(true);
- }
-
- /**
- * 添加余额支付密码
- * User: kang
- * Date: 2021/3/25
- * Time: 17:00 下午
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function addpayPassword($payPasswordData)
- {
- $ifPayPassword = $this->objDCustomer->get(['id'=>$payPasswordData['id']]);
- if(!empty($ifPayPassword['payPassword'])){
- return ResultWrapper::fail('该用户密码已添加', ErrorCode::$accountfail);
- }
- $payPasswordId= $payPasswordData['id'];
- unset($payPasswordData['id']);
- $dbResult = $this->objDCustomer->update($payPasswordData,$payPasswordId);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- return ResultWrapper::success($dbResult);
- }
-
- /**
- * 修改余额支付密码
- * User: kang
- * Date: 2021/3/25
- * Time: 17:25 下午
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function updatePayPassword($updatePayPasswordData)
- {
- $customerid = $updatePayPasswordData['id'];
- unset($updatePayPasswordData['id']);
- $dbResult = $this->objDCustomer->update($updatePayPasswordData,$customerid);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }else{
- return ResultWrapper::success($dbResult);
- }
- }
-
- /**
- * 校验余额支付密码
- * User: kang
- * Date: 2021/3/25
- * Time: 17:25 下午
- * @param $params
- * @return ResultWrapper
- * @throws Exception
- */
- public function checkPayPassword($checkPayPasswordData)
- {
- $oldPayPassword = $this->objDCustomer->get(['id'=>$checkPayPasswordData['id']]);
- if($oldPayPassword === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
-
- if(password_verify($checkPayPasswordData['payPassword'], $oldPayPassword['payPassword'] ) !== true){
- return ResultWrapper::fail('密码错误', ErrorCode::$accountfail);
- }
- return ResultWrapper::success();
- }
- /**
- * 客户积分流水
- * @param $selectParams
- * @return ResultWrapper
- */
- public function getAllCustomerIntegralDesc($selectParams)
- {
- $limit = $selectParams['limit'];
- unset($selectParams['limit']);
- $offset = $selectParams['offset'];
- unset($selectParams['offset']);
- $dbResult = $this->objDCustomer->get(['id' => $selectParams['customerId']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customerData = $dbResult;
- unset($dbResult);
- isset($selectParams['search']) && $selectParams['search'] = ['title' => $selectParams['search']];
- $selectParams = self::formatSqlWhere($selectParams);
- $dbResult = $this->objDCustomerIntegralDesc->select($selectParams,'*', 'createTime desc', $limit, $offset);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
- }
- $data = $dbResult;
- unset($dbResult);
- $countResult = $this->objDCustomerIntegralDesc->count($selectParams);
- if ($countResult === false) {
- return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
- }
- $return = [
- 'data' => [
- 'lists' => $data,
- 'customer' => $customerData,
- ],
- 'total' => ($countResult) ? intval($countResult) : 0,
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 修改积分
- * @param $params
- * @return ResultWrapper
- */
- public function updateCustomerIntegral($params)
- {
- if (empty($params['integral'])) {
- return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
- }
- if ($params['integral'] < 0) {
- return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
- }
- $dbResult = $this->objDCustomer->get(['id' => $params['customerId']]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $customer = $dbResult;
- unset($dbResult);
- if (empty($customer)) {
- return ResultWrapper::fail('用户不存在', ErrorCode::$dberror);
- }
- if ($params['type'] == 5) {
- $money = bcadd($customer['integral'], $params['integral'], 2);
- } else {
- $money = bcsub($customer['integral'], $params['integral'], 2);
- }
- if($money < 0){
- return ResultWrapper::fail('修改后积分不能为负数', ErrorCode::$paramError);
- }
- $update = [
- 'integral' => $money,
- 'updateTime' => time()
- ];
- $dbResult = $this->objDCustomer->update($update, ['id' => $params['customerId']]);
- if ($dbResult === false) {
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- if(isset($params['desc']) && !empty($params['desc'])){
- //增加记录
- $insertDesc = [
- 'userCenterId' => $customer['userCenterId'],
- 'customerId' => $customer['id'],
- 'shopId' => isset($params['shopId']) ? $params['shopId'] : 0,
- 'title' => $params['desc'],
- 'amount' => $params['integral'],
- 'changeAmount' => $money,
- 'type' => $params['type'],
- 'source' => 3,
- 'createTime' => time(),
- 'updateTime' => time()
- ];
- $result = $this->objDCustomerIntegralDesc->insert($insertDesc);
- if ($result === false) {
- return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
- }
- }
- return ResultWrapper::success(true);
- }
- /**
- * 根据订单增加客户积分
- * @param int $shopId
- * @param array $customer
- * @param array $order
- * @param array $orderGoods
- * @return ResultWrapper
- */
- public function addCustomerIntegralByOrder($shopId = 0, $customer = [], $order = [], $orderGoods = [])
- {
- //查询规则
- $objDIntegralRule = new DIntegralRule();
- $objDIntegralRule->setTable('qianniao_integral_rule_'.$this->enterpriseId);
- $dbResult = $objDIntegralRule->get(['shopId' => $shopId, 'enableStatus' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard], '*', 'createTime DESC');
- if($dbResult === false){
- return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
- }
- $rule = $dbResult;
- unset($dbResult);
- if(empty($rule)){
- return ResultWrapper::success(false);
- }
- $ruleGoods = json_decode($rule['goods'], true);
- if(empty($rule['startMoney']) || $rule['startMoney'] < 0){
- $rule['startMoney'] = 0;
- }
- //匹配商品
- $goodsIntegral = 0;
- $orderAmount = 0;
- foreach($orderGoods as $value){
- if(isset($ruleGoods[$value['skuId']])){
- //计算商品积分
- if($ruleGoods[$value['skuId']]['integral'] > 0){
- $goodsIntegral = bcadd($goodsIntegral, bcmul($ruleGoods[$value['skuId']]['integral'], $value['buyNum']),2);
- }
- }else{
- if($order['totalMoney'] >= $rule['startMoney']){
- $orderAmount = bcadd($orderAmount, $value['totalMoney'], 2);
- }
- }
- }
- $insertIntegralDesc = [];
- if($goodsIntegral > 0){
- //增加记录
- $insertIntegralDesc[] = [
- 'userCenterId' => $customer['userCenterId'],
- 'customerId' => $customer['id'],
- 'shopId' => $shopId,
- 'originId' => $order['id'],
- 'originNo' => $order['no'],
- 'ruleId' => $rule['id'],
- 'title' => '购买指定商品奖励积分',
- 'amount' => $goodsIntegral,
- 'changeAmount' => bcadd($customer['integral'], $goodsIntegral, 2),
- 'type' => StatusCode::$standard,
- 'source' => 2,
- 'createTime' => time() - 1,
- 'updateTime' => time() - 1,
- ];
- }
- //计算订单积分
- $orderIntegral = 0;
- if($orderAmount > 0 && $rule['amount'] > 0 && $rule['integral'] > 0){
- $orderIntegral = bcmul(intval($orderAmount / $rule['amount']), $rule['integral'], 2);
- //增加记录
- $insertIntegralDesc[] = [
- 'userCenterId' => $customer['userCenterId'],
- 'customerId' => $customer['id'],
- 'shopId' => $shopId,
- 'originId' => $order['id'],
- 'originNo' => $order['no'],
- 'ruleId' => $rule['id'],
- 'title' => '订单满足'.bcmul(intval($orderAmount / $rule['amount']), $rule['amount'], 2).',奖励积分',
- 'amount' => $orderIntegral,
- 'changeAmount' => bcadd($customer['integral'], bcadd($orderIntegral, $goodsIntegral,2), 2),
- 'type' => StatusCode::$standard,
- 'source' => 1,
- 'createTime' => time(),
- 'updateTime' => time(),
- ];
- }
- //累加积分
- $addIntegral = bcadd($orderIntegral, $goodsIntegral, 2);
- //增加客户积分
- if($addIntegral > 0){
- $updateCustomer = [
- 'integral' => bcadd($customer['integral'], $addIntegral, 2),
- 'updateTime' => time(),
- ];
- $dbResult = $this->objDCustomer->update($updateCustomer, ['id' => $customer['id']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- }
- //累加规则赠送积分
- $updateRule = [
- 'integralTotal' => bcadd($rule['integralTotal'], $addIntegral, 2),
- 'updateTime' => time(),
- ];
- $dbResult = $objDIntegralRule->update($updateRule, ['id' => $rule['id']]);
- if($dbResult === false){
- return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
- }
- //保存记录
- if(!empty($insertIntegralDesc)){
- $dbResult = $this->objDCustomerIntegralDesc->insert($insertIntegralDesc, true);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
- }
- }
- return ResultWrapper::success('执行成功');
- }
- /**
- * 新注册未下单统计
- */
- public function noOrderCustomer($params)
- {
- // 间隔天数转时间戳
- $endTime = time() - (86400 * $params['intervalDay']);
- $where = '';
- if( isset($params['customerName']) && !empty($params['customerName']) ){
- $where .= ' and c.name like "%'.$params['customerName'].'%" ';
- }
- if( isset($params['salesManId']) && !empty($params['salesManId']) ){
- $where .= ' and c.salesManId = '.$params['salesManId'];
- }
- if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
- $where .= ' and c.provinceCode = '.$params['provinceCode'];
- }
- if( isset($params['cityCode']) && !empty($params['cityCode']) ){
- $where .= ' and c.cityCode = '.$params['cityCode'];
- }
- if( isset($params['districtCode']) && !empty($params['districtCode']) ){
- $where .= ' and c.districtCode = '.$params['districtCode'];
- }
- $sql = ' from (select c.*,count(o.id) as total from qianniao_customer_'.$this->enterpriseId.' c left join qianniao_order_index_'.$this->enterpriseId.' o on o.customerId = c.id where c.deleteStatus = 5 and c.createTime >= '.$endTime.' '.$where.' GROUP BY c.id) tmp where tmp.total = 0';
- $listSql = $sql.' ORDER BY tmp.createTime desc limit '.$params['offset'].','.$params['limit'];
- $fields = 'select tmp.name,tmp.id,tmp.createTime,tmp.provinceCode,tmp.cityCode,tmp.districtCode,tmp.type,tmp.salesManId,tmp.userCenterId,tmp.shopId,tmp.departmentId';
- $dbResult = $this->objDCustomerRechargeRecord->query($fields.$listSql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
-
- //拿到范围内的客户
- $customerIds = [];
- foreach ($dbResult as $value){
- $customerIds[] = $value['id'];
- }
-
- $customerIds = implode(',',$customerIds);
-
- $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
- //根据客户id查询客户本年拜访次数
- $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
- if(!$dbYearNum->isSuccess()){
- return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
- }
- $yearNumDbResult = $dbYearNum->getData();
-
- $yearNum = [];
- foreach ($yearNumDbResult as $v){
- $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
- }
-
- //根据客户id查询客户距离上次拜访相差多少天
- $dbDayNum = $objMCustomerCommunication->getCustomerlastTimeDay($customerIds);
- if(!$dbDayNum->isSuccess()){
- return ResultWrapper::fail($dbDayNum->getData(),$dbDayNum->getErrorCode());
- }
- $dayNumDbResult = $dbDayNum->getData();
-
- $dayNum = [];
- foreach ($dayNumDbResult as $v){
- $dayNum[$v['customerId']]= $v['time'];//所查出客户距离上次拜访相差多少天
- }
-
- //根据查出天数范围内的客户查出所对应的日期并归组
- $result = $objMCustomerCommunication->getCustomerDate($customerIds);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $dbResultDate = $result->getData();
-
- //按照查出的年 本月 上月进行分组
- $data = [];
- $year = strtotime(date('Y-1-1'));
- $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
- $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
- foreach ( $dbResultDate as $value ){
- //年
- $time = strtotime($value['time']);
- if( $time>$year ){
- if( isset($data[$value['customerId']]['year']) ){
- $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
- }
- }
- //月
- if( $time>$thisMonth ){
- if( isset($data[$value['customerId']]['thisMonth']) ){
- $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
- }
- }
- //上月
- if( $time>$lastMonth && $time < $thisMonth ){
- if( isset($data[$value['customerId']]['lastMonth']) ){
- $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
- }
- }
- }
-
- foreach($dbResult as &$value) {
-
- //年
- if ( isset($data[$value['id']]['year']) ) {
- $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
- $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
- } else {
- $value['year']['orderNum'] = 0;
- $value['year']['orderMoney'] = 0;
- }
-
- //月
- if ( isset($data[$value['id']]['thisMonth']) ) {
- $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
- $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
- } else {
- $value['thisMonth']['orderNum'] = 0;
- $value['thisMonth']['orderMoney'] = 0;
- }
-
- //上月
- if ( isset($data[$value['id']]['lastMonth']) ) {
- $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
- $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
- } else {
- $value['lastMonth']['orderNum'] = 0;
- $value['lastMonth']['orderMoney'] = 0;
- }
-
- //客户本年拜访次数
- if(isset($yearNum[$value['id']])){
- $value['yearNum'] = isset( $yearNum[$value['id']]) ? $yearNum[$value['id']] : 0;
- } else {
- $value['yearNum'] = 0;
- }
- //客户距离上次多少天
- if(isset($dayNum[$value['id']])){
- $value['dayNum'] = isset( $dayNum[$value['id']]) ? $dayNum[$value['id']] : 0;
- } else {
- $value['dayNum'] = 0;
- }
-
- }
-
- if(empty($dbResult)){
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0,
- ]);
- }
- $fields = 'select count(*) as total ';
- $count = $this->objDCustomerRechargeRecord->query($fields.$sql);
- $return = [
- 'data' => self::format($dbResult),
- 'total' => $count ? $count[0]['total'] : 0
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 距离最近一次未下单统计
- */
- public function intervalNoOrderCustomer($params)
- {
- $where = '';
- if( isset($params['customerName']) && !empty($params['customerName']) ){
- $where .= ' and c.name like "%'.$params['customerName'].'%" ';
- }
- if( isset($params['salesManId']) && !empty($params['salesManId']) ){
- $where .= ' and c.salesManId = '.$params['salesManId'];
- }
- if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
- $where .= ' and c.provinceCode = '.$params['provinceCode'];
- }
- if( isset($params['cityCode']) && !empty($params['cityCode']) ){
- $where .= ' and c.cityCode = '.$params['cityCode'];
- }
- if( isset($params['districtCode']) && !empty($params['districtCode']) ){
- $where .= ' and c.districtCode = '.$params['districtCode'];
- }
-
- $sql = "select * from ( select b.*,b.createTime as lastTime,now() as nowtime,TIMESTAMPDIFF(day,FROM_UNIXTIME(b.createTime,'%Y%m%d'),CURRENT_DATE()) as intervalDay from (
- select DISTINCT c.id,o.createTime,c.name,c.provinceCode,c.cityCode,c.districtCode,c.type,c.salesManId,c.userCenterId,c.shopId,c.departmentId from qianniao_customer_".$this->enterpriseId." c LEFT JOIN qianniao_order_index_".$this->enterpriseId." o on c.id = o.customerId where c.deleteStatus = ".StatusCode::$standard." ".$where." order by o.createTime desc)b GROUP BY id)tmp where intervalDay >= ".$params['intervalDay']." order by intervalDay desc limit ".$params['offset'].",".$params['limit'];
- $dbResult = $this->objDCustomer->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
-
- //拿到范围内的客户
- $customerIds = [];
- foreach ($dbResult as $value){
- $customerIds[] = $value['id'];
- }
-
- $customerIds = implode(',',$customerIds);
- $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
- //根据客户id查询客户本年拜访次数
- $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
- if(!$dbYearNum->isSuccess()){
- return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
- }
- $yearNumDbResult = $dbYearNum->getData();
-
- $yearNum = [];
- foreach ($yearNumDbResult as $v){
- $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
- }
-
- //根据查出天数范围内的客户查出所对应的日期并归组
- $result = $objMCustomerCommunication->getCustomerDate($customerIds);
- if(!$result->isSuccess()){
- return ResultWrapper::fail($result->getData(),$result->getErrorCode());
- }
- $dbResultDate = $result->getData();
-
- //按照查出的年 本月 上月进行分组
- $data = [];
- $year = strtotime(date('Y-1-1'));
- $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
- $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
- foreach ( $dbResultDate as $value ){
- //年
- $time = strtotime($value['time']);
- if( $time>$year ){
- if( isset($data[$value['customerId']]['year']) ){
- $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
- }
- }
- //月
- if( $time>$thisMonth ){
- if( isset($data[$value['customerId']]['thisMonth']) ){
- $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
- }
- }
- //上月
- if( $time>$lastMonth && $time < $thisMonth ){
- if( isset($data[$value['customerId']]['lastMonth']) ){
- $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
- $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
- } else {
- $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
- $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
- }
- }
- }
-
- foreach($dbResult as &$value) {
-
- //年
- if ( isset($data[$value['id']]['year']) ) {
- $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
- $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
- } else {
- $value['year']['orderNum'] = 0;
- $value['year']['orderMoney'] = 0;
- }
-
- //月
- if ( isset($data[$value['id']]['thisMonth']) ) {
- $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
- $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
- } else {
- $value['thisMonth']['orderNum'] = 0;
- $value['thisMonth']['orderMoney'] = 0;
- }
-
- //上月
- if ( isset($data[$value['id']]['lastMonth']) ) {
- $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
- $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
- } else {
- $value['lastMonth']['orderNum'] = 0;
- $value['lastMonth']['orderMoney'] = 0;
- }
-
- //客户本年拜访次数
- if(isset($yearNum[$value['id']])){
- $value['yearNum'] = isset( $yearNum[$value['id']]) ? $yearNum[$value['id']] : 0;
- } else {
- $value['yearNum'] = 0;
- }
- }
-
- if(empty($dbResult)){
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0,
- ]);
- }
- $sql = "select count(*) as total from ( select b.*,b.createTime as lastTime,now() as nowtime,TIMESTAMPDIFF(day,FROM_UNIXTIME(b.createTime,'%Y%m%d'),CURRENT_DATE()) as intervalDay from (
- select DISTINCT c.id,o.createTime,c.name,c.provinceCode,c.cityCode,c.districtCode,c.type,c.salesManId,c.userCenterId,c.shopId,c.departmentId from qianniao_customer_".$this->enterpriseId." c LEFT JOIN qianniao_order_index_".$this->enterpriseId." o on c.id = o.customerId where c.deleteStatus = ".StatusCode::$standard." ".$where." order by o.createTime desc)b GROUP BY id)tmp where intervalDay >= ".$params['intervalDay']." order by intervalDay desc";
- $count = $this->objDCustomer->query($sql);
- if($count === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
-
-
- $return = [
- 'data' => self::format($dbResult),
- 'total' => $count ? $count[0]['total'] : 0
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 拉新统计
- */
- public function recommenderStatic($params)
- {
- $where = '';
-
- // 时间筛选
- if (isset($params['startTime']) && !empty($params['startTime'])){
- $where .= ' AND c.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
- }
-
- if( isset($params['customerId']) && !empty($params['customerId']) ){
- $where .= ' and c.id = '.$params['customerId'];
- }
- if( isset($params['staffId']) && !empty($params['staffId']) ){
- $where .= ' and c.salesManId = '.$params['staffId'];
- }
- $sql = ' from qianniao_customer_'.$this->enterpriseId.' c left join ( select i.customerId,sum(i.payAmount) as OrderTotalMoney,count(g.skuId) as goodsNum,count(distinct g.orderId) as orderNum from qianniao_order_goods_'.$this->enterpriseId.'_1 g LEFT JOIN qianniao_order_'.$this->enterpriseId.'_1 i on i.id = g.orderId where i.deleteStatus ='.StatusCode::$standard.' and i.auditStatus ='.StatusCode::$auditStatus['auditPass'].' group by i.customerId)b on c.id = b.customerId where c.recommenderId != 0 and c.deleteStatus = '.StatusCode::$standard.$where.' GROUP BY recommenderId';
- $limit = ' limit '.$params['offset'].','.$params['limit'];
- $listSql = $sql.' ORDER BY recommenderTotal desc';
- $fields = 'SELECT c.recommenderId,c.recommenderType,count(*) as recommenderTotal,b.*';
- $this->objDCustomerRechargeRecord->setTable('qianniao_customer_'.$this->enterpriseId);
- $this->objDCustomerRechargeRecord->setTable('qianniao_order_goods_'.$this->enterpriseId);
- $this->objDCustomerRechargeRecord->setTable('qianniao_order_'.$this->enterpriseId);
- $returnData = $this->objDCustomerRechargeRecord->query($fields.$listSql.$limit);
- if($returnData === false){
- return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
- }
- if(empty($returnData)){
- return ResultWrapper::success([
- 'data' => [],
- 'total' => 0,
- ]);
- }
- $sql = 'select count(*) as total from ('.$fields.$sql.') t';
- $count = $this->objDCustomerRechargeRecord->query($sql);
- $customerIds = [];
- $staffIds = [];
- foreach ($returnData as $key => $value){
- if( empty($value['recommenderId']) ) continue;
- if($value['recommenderType'] == StatusCode::$roleType['customer']){
- $customerIds[] = $value['recommenderId'];
- }else{
- $staffIds[] = $value['recommenderId'];
- }
- }
- // 根据客户ids批量获取客户名称
- $customerIdBindName = [];
- if( !empty($customerIds) ){
- $dbResult = $this->objDCustomer->select($customerIds, 'id,name');
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- foreach ($dbResult as $key => $value){
- $customerIdBindName[$value['id']] = $value['name'];
- }
- }
- // 根据员工ids批量获取员工名称
- $staffIdBindName = [];
- if( !empty($staffIds) ){
- $objDStaff = new DStaff();
- $objDStaff->setTable('qianniao_staff_'.$this->enterpriseId);
- $dbResult = $objDStaff->select($staffIds, 'id,staffName');
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- foreach ($dbResult as $key => $value){
- $staffIdBindName[$value['id']] = $value['staffName'];
- }
- }
- // 映射上名称
- foreach ($returnData as $key => $value){
- if($value['recommenderType'] == StatusCode::$roleType['customer']){
- $returnData[$key]['recommenderName'] = isset($customerIdBindName[$value['recommenderId']]) ? $customerIdBindName[$value['recommenderId']] : '';
- }else{
- $returnData[$key]['recommenderName'] = isset($staffIdBindName[$value['recommenderId']]) ? $staffIdBindName[$value['recommenderId']] : '';
- }
- }
- $return = [
- 'data' => $returnData,
- 'total' => $count ? $count[0]['total'] : 0
- ];
- return ResultWrapper::success($return);
- }
- /**
- * 客户购买记录导出方法
- * @param $result
- * @return void
- * @throws Exception
- */
- public function exportCustomerBuyLog($result)
- {
- //导出到本地
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:filename=客户购买记录表.csv");
- header('Cache-Control: max-age=0');
-
- $fp = fopen('php://output', 'a');
-
- $head = ['客户','商品','单位','属性','单价','购买数量','其他单位','商品总价','发货数量','商品条码']; //定义标题
-
- foreach ($head as $i => $v) {
- $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
- }
-
- fputcsv($fp, $head);
-
- $limit = 10000;
- $num = 0; //计数器
- foreach ($result as $v) { //循环数据
- $specGroupA = '';
- if(!empty($v['specGroup'])){
- foreach ($v['specGroup'] as $kk =>$vv){
- $specGroupA .=$vv['specName'].','.$vv['specValueName'].',';
- }
- $specGroup = rtrim($specGroupA, ",") ;//剔除追后的字符串
- }
- $num++;
- if ($num == $limit) {
- ob_flush(); //释放内存
- flush();
- }
- $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户
- $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品
- $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : '';//单位
- $rows['specGroup'] = $specGroup;//属性
- $rows['price'] = isset($v['price']) ? $v['price'] : '';//单价
- $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//购买数量
- $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : '';//其他单位
- $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//商品总价
- $rows['outNum'] = isset($v['outNum']) ? $v['outNum'] : '';//发货数量
- $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : '';//商品条码
-
- foreach ($rows as $kk => $vv) {
- $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
- }
- fputcsv($fp, $rs);
-
- $rows = [];
- }
- }
- /**
- * 客户分布
- * @return ResultWrapper
- */
- public function getCustomerDistributed()
- {
- $sql = 'select provinceCode,count(provinceCode) as total from qianniao_customer_'.$this->enterpriseId.' where deleteStatus = '.StatusCode::$standard.' group by provinceCode';
- $dbResult = $this->objDUserCenter->query($sql);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
- }
- $objMSysAreaChina = new MSysAreaChina();
- $areaData = [];
- $noTotal = 0;
- foreach($dbResult as $value){
- if(empty($value['provinceCode'])){
- $noTotal += $value['total'];
- }else{
- $areaName = $objMSysAreaChina->getNameByCode([
- $value['provinceCode'],
- ]);
- if(empty($areaName[$value['provinceCode']])){
- $noTotal += $value['total'];
- }else{
- $areaData[] = [
- 'name' => str_replace('省', '',$areaName[$value['provinceCode']]),
- 'value' => $value['total']
- ];
- }
- }
- }
- if(!empty($noTotal)){
- $areaData[] = [
- 'name' => '未知',
- 'value' => $noTotal
- ];
- }
- return ResultWrapper::success($areaData);
- }
- /**
- * 批量设置客户类型
- */
- public function setCustomerType($params)
- {
- if(empty($params['customerIds'])){
- return ResultWrapper::fail('客户数据不能为空',ErrorCode::$notAllowAccess);
- }
-
- //更新数据
- $dbResult = $this->objDCustomer->update(['type'=>$params['type']],['id'=>$params['customerIds']]);
- if($dbResult === false){
- return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
- }
- $objCustomerCache = new CustomerCache();
- //删除缓存
- foreach ($params['customerIds'] as $value){
- $objCustomerCache->delCustomerData($this->enterpriseId,$value);
- }
- return ResultWrapper::success($dbResult);
- }
- public function get($where)
- {
- $data = $this->objDCustomer->get($where);
- return $data;
- }
- public function select($where, $limit, $offset)
- {
- $data = $this->objDCustomer->select($where, '*', 'id DESC', $limit, $offset);
- return $data;
- }
- public function count($where)
- {
- $count = $this->objDCustomer->count($where);
- return $count;
- }
- }
|