12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371 |
- <?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;
- }
- }
|