MCustomer.Class.php 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371
  1. <?php
  2. /**
  3. * 客户管理模块
  4. * Created by PhpStorm.
  5. * User: haoren
  6. * Date: 2020/10/30
  7. * Time: 14:02
  8. */
  9. namespace JinDouYun\Model\Customer;
  10. use Exception;
  11. use JinDouYun\Dao\Customer\DCustomerCommunication;
  12. use JinDouYun\Dao\Enterprise\DEnterprise;
  13. use JinDouYun\Dao\Finance\DReceive;
  14. use JinDouYun\Dao\Finance\DReceived;
  15. use JinDouYun\Dao\Finance\DReceivedIndex;
  16. use JinDouYun\Dao\Finance\DReceiveReceiptIndex;
  17. use JinDouYun\Dao\Shop\DShop;
  18. use Mall\Framework\Core\ErrorCode;
  19. use Mall\Framework\Core\StatusCode;
  20. use Mall\Framework\Core\ResultWrapper;
  21. use JinDouYun\Controller\Common\Logger;
  22. use JinDouYun\Dao\Integral\DIntegralRule;
  23. use JinDouYun\Dao\Customer\DCustomer;
  24. use JinDouYun\Dao\Customer\DCustomerBalanceTurnover;
  25. use JinDouYun\Dao\Customer\DCustomerRechargeRecord;
  26. use JinDouYun\Dao\Customer\DCustomerIntegralDesc;
  27. use JinDouYun\Dao\UserCenter\DUserCenter;
  28. use JinDouYun\Dao\Enterprise\DUserBindEnterprise;
  29. use JinDouYun\Dao\Stock\DReservoirArea;
  30. use JinDouYun\Dao\Department\DStaff;
  31. use JinDouYun\Model\UserCenter\MUserCenterRegister;
  32. use JinDouYun\Model\SysAreaChina\MSysAreaChina;
  33. use JinDouYun\Model\Shop\MShop;
  34. use JinDouYun\Model\Department\MDepartment;
  35. use JinDouYun\Model\Department\MStaff;
  36. use JinDouYun\Model\System\MCustomerSource;
  37. use JinDouYun\Model\System\MBasicSetup;
  38. use JinDouYun\Model\MBaseModel;
  39. use JinDouYun\Model\Enterprise\MEnterprise;
  40. use JinDouYun\Model\Finance\MCustomerBalanceDetail;
  41. use JinDouYun\Model\Goods\MGoodsCollect;
  42. use JinDouYun\Model\Market\MUserCoupon;
  43. use JinDouYun\Model\Market\MVipCard;
  44. use JinDouYun\Model\Order\MOrder;
  45. use JinDouYun\Model\Stock\MReservoirArea;
  46. use JinDouYun\Model\System\MPaymentSetting;
  47. use JinDouYun\Cache\CustomerCache;
  48. use JinDouYun\Cache\OverviewCache;
  49. use JinDouYun\Cache\SystemCache;
  50. use Util\Common\ChineseCharacter;
  51. use Util\WeiXin\Pay;
  52. use const Grpc\STATUS_ABORTED;
  53. class MCustomer extends MBaseModel
  54. {
  55. private $objDCustomer;
  56. private $objMCustomerContact;
  57. private $objDUserCenter;
  58. private $objDCustomerBalanceTurnover;
  59. private $objDCustomerRechargeRecord;
  60. private $objMShop;
  61. private $objMDepartment;
  62. private $objMStaff;
  63. private $objMCustomerSource;
  64. private $objDUserBindEnterprise;
  65. private $objCustomerCache;
  66. private $objOverviewCache;
  67. private $objMShippingAddress;
  68. private $objDCustomerIntegralDesc;
  69. private $cutTable = 1;//客户按照企业id分表
  70. private $enterpriseId;
  71. private $userCenterId;
  72. public function __construct($enterpriseId, $userCenterId)
  73. {
  74. $this->enterpriseId = $enterpriseId;
  75. $this->userCenterId = $userCenterId;
  76. parent::__construct($this->enterpriseId, $this->userCenterId);
  77. $this->objMCustomerContact = new MCustomerContact($enterpriseId, $userCenterId);
  78. $this->objMShop = new MShop($enterpriseId, $userCenterId);
  79. $this->objMDepartment = new MDepartment($enterpriseId);
  80. $this->objMStaff = new MStaff($enterpriseId, $userCenterId);
  81. $this->objDCustomerIntegralDesc = new DCustomerIntegralDesc();
  82. $this->objMCustomerSource = new MCustomerSource($enterpriseId);
  83. $this->objMShippingAddress = new MShippingAddress($enterpriseId);
  84. $this->objCustomerCache = new CustomerCache();
  85. $this->objOverviewCache = new OverviewCache();
  86. $this->objDCustomerBalanceTurnover = new DCustomerBalanceTurnover();
  87. $this->objDCustomerBalanceTurnover->setTable('qianniao_customer_balance_turnover_'.$enterpriseId);
  88. $this->objDCustomerRechargeRecord = new DCustomerRechargeRecord();
  89. $this->objDCustomerRechargeRecord->setTable('qianniao_customer_recharge_record_'.$enterpriseId);
  90. $this->objDCustomerIntegralDesc->setTable('qianniao_customer_integral_desc_'.$enterpriseId);
  91. $this->objDCustomer = new DCustomer('default');
  92. $this->objDUserCenter = new DUserCenter('default');
  93. $tableName = $this->objDCustomer->getTableName($this->objDCustomer->get_Table(), $this->enterpriseId, $this->cutTable);
  94. $this->objDCustomer->setTable($tableName);
  95. $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
  96. $this->objDCustomer->setSearchIndex('customer_search')->setType('customer');
  97. }
  98. /**
  99. * 添加客户
  100. * @param $params
  101. * @return ResultWrapper
  102. * @throws Exception
  103. */
  104. public function addCustomer($params)
  105. {
  106. $beginStatus = $this->objDCustomer->beginTransaction();
  107. $contact = $params['contact'];
  108. unset($params['contact']);
  109. if(!isMobile($params['mobile'])){
  110. return ResultWrapper::fail('该手机号格式有问题', ErrorCode::$mobileishaved);
  111. }
  112. //判断账号密码是否在该企业下被注册过
  113. $objMUserCenterRegister = new MUserCenterRegister();
  114. $isRegister = $objMUserCenterRegister->mobileIsRegister($params['mobile'], $this->enterpriseId);
  115. if ($isRegister) {
  116. $this->objDCustomer->rollBack();
  117. return ResultWrapper::fail('该手机号已经被注册', ErrorCode::$mobileishaved);
  118. }
  119. //添加userCenter表
  120. $dbResult = $this->objDUserCenter->get(['mobile' => $params['mobile']]);
  121. if($dbResult === false){
  122. $this->objDCustomer->rollBack();
  123. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  124. }
  125. if(empty($dbResult)){
  126. $userCenterData = [
  127. 'mobile' => $params['mobile'],
  128. 'source' => StatusCode::$source['manage'],
  129. 'isCustomer' => StatusCode::$customerType['customer'],
  130. 'createTime' => time(),
  131. 'updateTime' => time(),
  132. ];
  133. $userCenterId = $this->objDUserCenter->insert($userCenterData);
  134. if ($userCenterId === false) {
  135. $this->objDCustomer->rollBack();
  136. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  137. }
  138. }else{
  139. $userCenterId = $dbResult['id'];
  140. }
  141. $params['enterpriseId'] = $this->enterpriseId;
  142. $params['userCenterId'] = $userCenterId;
  143. //添加负责人电话
  144. $params['managerMobile'] = $params['mobile'];
  145. unset($params['mobile']);
  146. unset($params['password']);
  147. //后台添加客户 状态为已审核
  148. $params['status'] = StatusCode::$auditStatus['auditPass'];
  149. $objChineseCharacter = new ChineseCharacter();
  150. $condition = $objChineseCharacter->getInitials(trim($params['name']));
  151. $params['condition'] = $condition;
  152. $customerId = $this->objDCustomer->insert($params);
  153. if ($customerId === false) {
  154. $this->objDCustomer->rollBack();
  155. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  156. }
  157. //增加客户公司关系表
  158. $UserBindEnterpriseData = [
  159. 'userCenterId' => $userCenterId,
  160. 'roleType' => StatusCode::$roleType['customer'],
  161. 'enterpriseId' => $this->enterpriseId,
  162. 'updateTime' => time(),
  163. 'createTime' => time(),
  164. ];
  165. $dbResult = $this->objDUserBindEnterprise->insert($UserBindEnterpriseData);
  166. if ($dbResult === false) {
  167. return ResultWrapper::fail($this->objDUserBindEnterprise->error(), ErrorCode::$dberror);
  168. }
  169. if(!empty($contact)){
  170. //保存联系人信息
  171. $customerContactData = [
  172. 'customerId' => $customerId,
  173. 'name' => isset($contact['name']) ? $contact['name'] : '',
  174. 'mobile' => isset($contact['mobile']) ? $contact['mobile'] : '',
  175. 'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
  176. 'cityCode' => isset($contact['cityCode']) ? $contact['cityCode'] : '',
  177. 'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
  178. 'address' => isset($contact['address']) ? $contact['address'] : '',
  179. 'deleteStatus' => StatusCode::$standard,
  180. 'createTime' => time(),
  181. 'updateTime' => time()
  182. ];
  183. $result = $this->objMCustomerContact->addCustomerContact($customerContactData);
  184. if ($result->isSuccess() === false) {
  185. $this->objDCustomer->rollBack();
  186. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  187. }
  188. //把联系人信息保存为收货地址
  189. $ShippingAddressData = [
  190. 'name' => $customerContactData['name'],
  191. 'mobile' => $customerContactData['mobile'],//客户收货手机号
  192. 'provinceCode' => $customerContactData['provinceCode'],//客户收货地址省份编码
  193. 'cityCode' => $customerContactData['cityCode'],//客户收货地址城市编码
  194. 'districtCode' => $customerContactData['districtCode'],//客户收货地址区县编码
  195. 'address' => $customerContactData['address'],//详细收货地址
  196. 'deleteStatus' => StatusCode::$standard,
  197. 'defaultStatus' => StatusCode::$standard,
  198. 'customerId' => $customerId,
  199. 'extend' => json_encode(['createType' => StatusCode::$roleType['admin']]),
  200. 'updateTime' => time()
  201. ];
  202. $result = $this->objMShippingAddress->addShippingAddress($ShippingAddressData);
  203. if ($result->isSuccess() === false) {
  204. $this->objDCustomer->rollBack();
  205. return ResultWrapper::fail($result->getData(), $result->getErrorCode());
  206. }
  207. }
  208. $beginStatus && $this->objDCustomer->commit();
  209. //self::updateEsData($customerId);
  210. return ResultWrapper::success($customerId);
  211. }
  212. /**
  213. * 获取指定客户信息,获取联系人信息
  214. * @param $CustomerIds
  215. * @return ResultWrapper
  216. * @throws Exception
  217. */
  218. public function getCustomerInfo($CustomerIds)
  219. {
  220. $dbResult = $this->objDCustomer->get_by('id', $CustomerIds);
  221. if ($dbResult === false) {
  222. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  223. } else {
  224. $dbResult = self::format([$dbResult]);
  225. $dbResult = array_shift($dbResult);
  226. return ResultWrapper::success($dbResult);
  227. }
  228. }
  229. /**
  230. * 获取指定客户信息,获取客戶信息
  231. * @param $CustomerIds
  232. * @return ResultWrapper
  233. * @throws Exception
  234. */
  235. public function getCustomerName($CustomerIds)
  236. {
  237. $dbResult = $this->objDCustomer->get_by('id', $CustomerIds, 'id,name,managerMobile');
  238. if ($dbResult === false) {
  239. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  240. }
  241. return ResultWrapper::success($dbResult);
  242. }
  243. /**
  244. * 获取客户
  245. * @param $where
  246. * @param string $field
  247. * @param bool $isOne
  248. * @param bool $isFormat
  249. * @return ResultWrapper
  250. */
  251. public function getCustomerData($where, $field = '*', $isOne = true, $isFormat = false)
  252. {
  253. if($isOne){
  254. $dbResult = $this->objDCustomer->get($where, $field);
  255. }else{
  256. $dbResult = $this->objDCustomer->select($where, $field);
  257. }
  258. if($dbResult === false){
  259. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  260. }
  261. if($isFormat){
  262. $dbResult = self::format($dbResult);
  263. }
  264. return ResultWrapper::success($dbResult);
  265. }
  266. /**
  267. * 获取客户
  268. * @param $sql
  269. * @return ResultWrapper
  270. */
  271. public function getCustomerDataByQuery($sql)
  272. {
  273. $dbResult = $this->objDCustomer->query($sql);
  274. if($dbResult === false){
  275. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  276. }
  277. return ResultWrapper::success($dbResult);
  278. }
  279. /**
  280. * 处理客户联系人信息
  281. * @param $data
  282. * @param bool $flag 二维数组传true
  283. * @return array
  284. * @throws Exception
  285. */
  286. public function format($data)
  287. {
  288. if (!$data) {
  289. return $data;
  290. }
  291. $objMSysAreaChina = new MSysAreaChina();
  292. $customerIds = [];
  293. $userCenterIds = [];
  294. $shopIds = [];
  295. $departmentIds = [];
  296. $recommenderCustomerIds = [];
  297. $staffIds = [];
  298. $customerSourceIds = [];//客户类型
  299. $reservoirAreaIds = []; // 分拣区id
  300. foreach ($data as $key => $customer) {
  301. !empty($customer['id']) && $customerIds[] = $customer['id'];
  302. !empty($customer['userCenterId']) && $userCenterIds[] = $customer['userCenterId'];
  303. !empty($customer['shopId']) && $shopIds[] = $customer['shopId'];
  304. !empty($customer['departmentId']) && $departmentIds[] = $customer['departmentId'];
  305. !empty($customer['salesManId']) && $staffIds[] = $customer['salesManId'];
  306. if (isset($customer['type'])) {
  307. $customerSourceIds[] = $customer['type'];
  308. }
  309. if(isset($customer['sortingId'])){
  310. $reservoirAreaIds = $customer['sortingId'];
  311. }
  312. if( empty($customer['recommenderId']) ) continue;
  313. if($customer['recommenderType'] == StatusCode::$roleType['customer']){
  314. !empty($customer['recommenderId']) && $recommenderCustomerIds[] = $customer['recommenderId'];
  315. }else{
  316. !empty($customer['recommenderId']) && $staffIds[] = $customer['recommenderId'];
  317. }
  318. }
  319. //获取用户账号信息
  320. $userCenters = [];
  321. if ($userCenterIds) {
  322. $userCenterDatas = $this->objDUserCenter->select(array_unique(array_filter($userCenterIds)), 'id,mobile,source,createTime');
  323. foreach ($userCenterDatas as $userCenterData){
  324. $userCenters[$userCenterData['id']] = $userCenterData;
  325. }
  326. }
  327. //获取联系人信息
  328. $customerContacts = [];
  329. if ($customerIds) {
  330. $contacts = $this->objMCustomerContact->getContactInfoById($customerIds);
  331. foreach ($contacts as $contact)
  332. $customerContacts[$contact['customerId']][] = $contact;
  333. }
  334. //获取店铺
  335. $shops = [];
  336. if ($shopIds) {
  337. $shopData = $this->objMShop->getShopName(array_unique(array_filter($shopIds)));
  338. foreach ($shopData as $shop)
  339. $shops[$shop['id']] = $shop['name'];
  340. }
  341. //获取部门
  342. $departments = [];
  343. if ($departmentIds) {
  344. $departmentData = $this->objMDepartment->departmentDataByDepartmentIds(array_unique(array_filter($departmentIds)));
  345. foreach ($departmentData as $department)
  346. $departments[$department['id']] = $department['departmentName'];
  347. }
  348. //获取业务员
  349. $staffs = [];
  350. if ($staffIds) {
  351. $staffData = $this->objMStaff->getStaffDataByStaffIds(array_unique(array_filter($staffIds)));
  352. foreach ($staffData as $staff)
  353. $staffs[$staff['id']] = $staff['staffName'];
  354. }
  355. // 根据客户ids批量获取客户名称
  356. $customerIdBindName = [];
  357. if( !empty($recommenderCustomerIds) ){
  358. $dbResult = $this->objDCustomer->select($recommenderCustomerIds, 'id,name');
  359. if($dbResult !== false){
  360. foreach ($dbResult as $key => $value){
  361. $customerIdBindName[$value['id']] = $value['name'];
  362. }
  363. }
  364. }
  365. //查询客户类型
  366. $customerSourceArr = [];
  367. if ($customerSourceIds) {
  368. $customerSourceData = $this->objMCustomerSource->getCustomerSourceNameByIds($customerSourceIds);
  369. if ($customerSourceData->isSuccess()) {
  370. $customerSourceArray = $customerSourceData->getData();
  371. foreach ($customerSourceArray as $customerSource)
  372. $customerSourceArr[$customerSource['id']] = $customerSource['name'];
  373. }
  374. }
  375. foreach ($data as &$customer) {
  376. $customer['customerDays'] = intval((time() - $customer['createTime']) / 86400);//注册天数
  377. $customer['code'] = createCode(StatusCode::$code['customer']['prefix'], $customer['id'], StatusCode::$code['customer']['length']);
  378. $customer['taglib'] = isset($customer['taglib']) ? json_decode($customer['taglib'], true) : [];
  379. $customer['extend'] = isset($customer['extend']) ? json_decode($customer['extend'], true) : [];
  380. //处理客户地址
  381. if (isset($customer['provinceCode']) && isset($customer['cityCode']) && isset($customer['districtCode'])) {
  382. $areaName = $objMSysAreaChina->getNameByCode([
  383. $customer['provinceCode'],
  384. $customer['cityCode'],
  385. $customer['districtCode']
  386. ]);
  387. $customer['area']['provinceName'] = isset($areaName[$customer['provinceCode']]) ? $areaName[$customer['provinceCode']] : '';
  388. $customer['area']['cityName'] = isset($areaName[$customer['cityCode']]) ? $areaName[$customer['cityCode']] : '';
  389. $customer['area']['districtName'] = isset($areaName[$customer['districtCode']]) ? $areaName[$customer['districtCode']] : '';
  390. $customer['area']['address'] = getArrayItem($customer, 'address');
  391. }
  392. //处理店铺
  393. $customer['shopName'] = isset($shops[$customer['shopId']]) ? $shops[$customer['shopId']] : '';
  394. //处理销售部门
  395. $customer['departmentName'] = isset($departments[$customer['departmentId']]) ? $departments[$customer['departmentId']] : '';
  396. //处理业务员
  397. $customer['salesManName'] = isset($staffs[$customer['salesManId']]) ? $staffs[$customer['salesManId']] : '';
  398. //处理客户类型
  399. $customer['customerType'] = isset($customerSourceArr[$customer['type']]) ? $customerSourceArr[$customer['type']] : '';
  400. $customer['mobile'] = '';
  401. $customer['password'] = '';
  402. $customer['registerTime'] = '';
  403. $customer['source'] = '';
  404. //处理注册手机号/时间/来源
  405. if (isset($userCenters[$customer['userCenterId']]) && $userCenters[$customer['userCenterId']]) {
  406. $userCenter = $userCenters[$customer['userCenterId']];
  407. $customer['mobile'] = ($this->enterpriseId == 4) ? substr_replace($userCenter['mobile'],'****',3,4) : $userCenter['mobile'];
  408. $customer['registerTime'] = date('Y-m-d H:i:s', $userCenter['createTime']);
  409. $customer['source'] = array_search($userCenter['source'], StatusCode::$source);
  410. }
  411. $defaultContact[] = [
  412. 'name' => '',
  413. 'mobile' => ''
  414. ];
  415. $customer['contact'] = isset($customerContacts[$customer['id']]) ? $customerContacts[$customer['id']] : $defaultContact;
  416. // 处理推荐人
  417. if(isset($customer['recommenderType'])){
  418. if($customer['recommenderType'] == StatusCode::$roleType['customer']){
  419. $customer['recommenderName'] = isset($customerIdBindName[$customer['recommenderId']]) ? $customerIdBindName[$customer['recommenderId']] : '';
  420. }else{
  421. $customer['recommenderName'] = isset($staffs[$customer['recommenderId']]) ? $staffs[$customer['recommenderId']] : '';
  422. }
  423. }
  424. }
  425. return $data;
  426. }
  427. /**
  428. * 处理时间戳
  429. * @param $timestamp
  430. * @param string $type
  431. * @return false|string
  432. */
  433. function time_format($timestamp, $type = 'Y-m-d')
  434. {
  435. $time = explode('-', $timestamp);
  436. if (count($time) > 1) {
  437. return $timestamp;
  438. }
  439. return date($type, $timestamp);
  440. }
  441. /**
  442. * 编辑客户
  443. * 事务修改联系人信息
  444. * @param int|array $params 修改客户的数据
  445. *
  446. * @return ResultWrapper
  447. * @throws Exception
  448. */
  449. public function editCustomer($params)
  450. {
  451. if (empty($params['id'])) {
  452. return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
  453. }
  454. $updateCustomerId = $params['id'];
  455. unset($params['id']);
  456. $contact = $params['contact'];
  457. unset($params['contact']);
  458. $beginStatus = $this->objDCustomer->beginTransaction();
  459. //修改客户账号密码
  460. $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $updateCustomerId);
  461. $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');
  462. if ($userCenterInfo === false) {
  463. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  464. }
  465. //手机号不应该随意修改
  466. /* if (isset($userCenterInfo['mobile']) && isset($userCenterInfo['password'])) {
  467. //比对手机号和密码有没有发生变化
  468. $updateUserCenterData = [];
  469. if ($params['mobile'] != $userCenterInfo['mobile']) {
  470. $updateUserCenterData['mobile'] = $params['mobile'];
  471. }
  472. //如果输入了密码,则判断密码与原来的密码是否一致
  473. if ($params['password'] && password_verify($params['password'], $userCenterInfo['password']) === false) {
  474. $updateUserCenterData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
  475. }
  476. if (!empty($updateUserCenterData)) {
  477. $userCenterResult = $this->objDUserCenter->update($updateUserCenterData, $userCenterId);
  478. if ($userCenterResult === false) {
  479. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  480. }
  481. }
  482. }*/
  483. unset($params['mobile']);
  484. unset($params['password']);
  485. if(isset($params['name'])){
  486. $objChineseCharacter = new ChineseCharacter();
  487. $condition = $objChineseCharacter->getInitials(trim($params['name']));
  488. $params['condition'] = $condition;
  489. }
  490. // 修改手机号
  491. // $params['managerMobile'] = $params['mobile'];
  492. //修改客户基本信息
  493. $dbResult = $this->objDCustomer->update($params, $updateCustomerId);
  494. if ($dbResult === false) {
  495. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  496. }
  497. $customerContactData = [
  498. 'name' => isset($contact['name']) ? $contact['name'] : '',
  499. 'mobile' => isset($contact['mobile']) ? $contact['mobile'] : '',
  500. 'provinceCode' => isset($contact['provinceCode']) ? $contact['provinceCode'] : '',
  501. 'cityCode' => isset($contact['cityCode']) ? $contact['cityCode'] : '',
  502. 'districtCode' => isset($contact['districtCode']) ? $contact['districtCode'] : '',
  503. 'address' => isset($contact['address']) ? $contact['address'] : '',
  504. 'updateTime' => time()
  505. ];
  506. //修改联系人信息
  507. if (isset($contact['id']) && !empty($contact['id'])) {
  508. $customerContactData['id'] = $contact['id'];
  509. $dbResult1 = $this->objMCustomerContact->editCustomerContact($customerContactData);
  510. } else {
  511. $customerContactData['customerId'] = $updateCustomerId;
  512. $customerContactData['createTime'] = time();
  513. $customerContactData['deleteStatus'] = StatusCode::$standard;
  514. $dbResult1 = $this->objMCustomerContact->addCustomerContact($customerContactData);
  515. }
  516. if ($dbResult1->isSuccess() === false) {
  517. $this->objDCustomer->rollBack();
  518. return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
  519. }
  520. $objCustomerCache = new CustomerCache();
  521. $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
  522. $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);
  523. $beginStatus && $this->objDCustomer->commit();
  524. //self::updateEsData($updateCustomerId);
  525. return ResultWrapper::success($dbResult);
  526. }
  527. /**
  528. * 后台批量分配部门及业务员
  529. * @param array $params
  530. * @return ResultWrapper
  531. */
  532. public function batchEditCustomer(array $params)
  533. {
  534. $dbResult = $this->objDCustomer->update(
  535. [
  536. 'departmentId' => $params['departmentId'],
  537. 'salesManId' => $params['salesManId'],
  538. 'updateTime' => time()
  539. ],
  540. ['id' => $params['ids']]
  541. );
  542. if ($dbResult === false){
  543. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  544. }
  545. return ResultWrapper::success("操作成功");
  546. }
  547. //前台修改客户信息
  548. public function editCustomerInfo($params)
  549. {
  550. $userCenterId = $params['userCenterId'];
  551. unset($params['userCenterId']);
  552. $updateCustomerId = self::getCustomerIdByUserCenterId($userCenterId);
  553. if (empty($updateCustomerId)) {
  554. return ResultWrapper::fail('没有指定要修改的客户id', ErrorCode::$paramError);
  555. }
  556. $contact = $params['contact'];
  557. unset($params['contact']);
  558. //状态 为已审核
  559. $params['status'] = StatusCode::$auditStatus['auditPass'];
  560. $params['auditFailReason'] = '';
  561. //查询系统设置
  562. $objMBasicSetup = new MBasicSetup($this->enterpriseId);
  563. $modelResult = $objMBasicSetup->getBasicSetup();
  564. if (!$modelResult->isSuccess()) {
  565. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  566. }
  567. $system = $modelResult->getData();
  568. //判断完善资料内容
  569. if (isset($system['basicData']) && isset($system['basicData']['finishData']) && $system['basicData']['finishData'] == StatusCode::$standard) {
  570. //如果完善资料 限制资料提交内容
  571. if(!isset($params['name']) || empty($params['name'])){
  572. return ResultWrapper::fail('请输入真实名称', ErrorCode::$paramError);
  573. }
  574. }
  575. //判断系统设置审核
  576. if (isset($system['basicData']) && isset($system['basicData']['personnelReview']) && $system['basicData']['personnelReview'] == StatusCode::$standard) {
  577. //如果开启客户审核 把状态改为待审核
  578. $params['status'] = StatusCode::$auditStatus['auditing'];
  579. }
  580. //修改客户基本信息
  581. $dbResult = $this->objDCustomer->update($params, $updateCustomerId);
  582. if ($dbResult === false) {
  583. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  584. }
  585. $objCustomerCache = new CustomerCache();
  586. $objCustomerCache->delCustomerUserData($this->enterpriseId, $userCenterId);
  587. $objCustomerCache->delCustomerData($this->enterpriseId, $updateCustomerId);
  588. //修改联系人信息
  589. if (isset($contact['id'])) {
  590. $contact['updateTime'] = time();
  591. $dbResult1 = $this->objMCustomerContact->editCustomerContact($contact);
  592. } else {
  593. $dbResult1 = true;
  594. if (
  595. (isset($contact['provinceCode']) && !empty($contact['provinceCode'])) ||
  596. (isset($contact['cityCode']) && !empty($contact['cityCode'])) ||
  597. (isset($contact['districtCode']) && !empty($contact['districtCode'])) ||
  598. (isset($contact['address']) && !empty($contact['address'])) ||
  599. (isset($contact['name']) && !empty($contact['name'])) ||
  600. (isset($contact['mobile']) && !empty($contact['mobile']))
  601. ) {
  602. $contact['customerId'] = $updateCustomerId;
  603. $contact['createTime'] = time();
  604. $contact['updateTime'] = time();
  605. $dbResult1 = $this->objMCustomerContact->addCustomerContact($contact);
  606. }
  607. }
  608. //获取客户所属的商铺
  609. /*$shopId = $this->objMShop->getShopIdByArea($params);
  610. if ($shopId) {
  611. $this->objDCustomer->update(['shopId' => $shopId], $updateCustomerId);
  612. }*/
  613. if (!$dbResult1->isSuccess()) {
  614. $this->objDCustomer->rollBack();
  615. return ResultWrapper::fail($dbResult1->getData(), $dbResult1->getErrorCode());
  616. } else {
  617. $this->objDCustomer->commit();
  618. // $_id = self::createEsDocumentId($updateCustomerId);
  619. // $result = $this->objDCustomer->esupdateTypeFieldVaule($params, $_id);
  620. return ResultWrapper::success($params['status']);
  621. }
  622. }
  623. private function createEsDocumentId($customerId)
  624. {
  625. return 'EnterpriseId_' . $this->enterpriseId . '_CustomerId_' . $customerId;
  626. }
  627. /**
  628. * 更新ES
  629. * @param $customerId
  630. * @throws Exception
  631. */
  632. public function updateEsData($customerId)
  633. {
  634. //每次查询一遍,避免客户在数据库存在,在ES中不存在的情况
  635. $userCenterId = $this->objDCustomer->get_field('userCenterId', 'id = ' . $customerId);
  636. $userCenterInfo = $this->objDUserCenter->get_by('id', $userCenterId, '*');
  637. $customerInfo = $this->objDCustomer->get_by('id', $customerId);
  638. if ($customerInfo !== false) {
  639. $customerInfo['shopName'] = $this->objMShop->getShopNameById($customerInfo['shopId']);
  640. $customerInfo['departmentName'] = $this->objMDepartment->getNameById($customerInfo['departmentId']);
  641. $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
  642. $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName']:'';
  643. $objMSysAreaChina = new MSysAreaChina();
  644. if (isset($customerInfo['provinceCode']) && isset($customerInfo['cityCode']) && isset($customerInfo['districtCode'])) {
  645. $areaName = $objMSysAreaChina->getNameByCode([
  646. $customerInfo['provinceCode'],
  647. $customerInfo['cityCode'],
  648. $customerInfo['districtCode']
  649. ]);
  650. $customerInfo['provinceName'] = isset($areaName[$customerInfo['provinceCode']]) ? $areaName[$customerInfo['provinceCode']] : '';
  651. $customerInfo['cityName'] = isset($areaName[$customerInfo['cityCode']]) ? $areaName[$customerInfo['cityCode']] : '';
  652. $customerInfo['districtName'] = isset($areaName[$customerInfo['districtCode']]) ? $areaName[$customerInfo['districtCode']] : '';
  653. }
  654. $customerInfo['tag'] = $customerInfo['tag'] ? json_decode($customerInfo['tag'], true) : [];
  655. $customerInfo['mobile'] = $userCenterInfo['mobile'];
  656. $customerInfo['source'] = $userCenterInfo['source'];
  657. $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerId);
  658. if (!empty($customerInfo['latitude']) && !empty($customerInfo['longitude'])) {
  659. $customerInfo['location'] = [
  660. 'lat' => $customerInfo['latitude'],
  661. 'lon' => $customerInfo['longitude']
  662. ];
  663. }
  664. unset($customerInfo['latitude']);
  665. unset($customerInfo['longitude']);
  666. $_id = self::createEsDocumentId($customerId);
  667. $result = $this->objDCustomer->addUpSearchIndexDocument($customerInfo, $_id);
  668. if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
  669. // echo "es操作成功";die;
  670. }
  671. //echo "es操作失败";
  672. }
  673. }
  674. /**
  675. * 删除客户
  676. *
  677. * @param array $userCenterIds 要删除的客户id
  678. * @return ResultWrapper
  679. * @throws Exception
  680. */
  681. public function delCustomer($userCenterIds)
  682. {
  683. if (empty($userCenterIds)) {
  684. return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
  685. }
  686. $deleteDate =[
  687. 'userCenterId'=> $userCenterIds,
  688. ];
  689. $dbResult = $this->objDCustomer->update(['deleteStatus' => StatusCode::$delete], $deleteDate);
  690. if ($dbResult === false) {
  691. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  692. }
  693. unset($deleteDate);
  694. $objDUserBindEnterprise = new DUserBindEnterprise();
  695. $deleteDate =[
  696. 'userCenterId'=> $userCenterIds,
  697. 'enterpriseId'=> $this->enterpriseId,
  698. // 'roleType' => StatusCode::$roleType['customer']//文档建议这样修改
  699. ];
  700. $dbResult = $objDUserBindEnterprise->delete($deleteDate);
  701. if ($dbResult === false) {
  702. return ResultWrapper::fail($objDUserBindEnterprise->error(), ErrorCode::$dberror);
  703. }
  704. //在ES删除
  705. // $_id = self::createEsDocumentId($delCustomerIds);
  706. // $this->objDCustomer->esdeleteTypeDocument($_id);
  707. return ResultWrapper::success($dbResult);
  708. }
  709. /**
  710. * 客户启用和禁用
  711. * @param array $params
  712. * @return ResultWrapper
  713. * @throws Exception
  714. */
  715. public function updateCustomerStatus($params)
  716. {
  717. $dbResult = $this->objDCustomer->get($params['id']);
  718. if ($dbResult === false) {
  719. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  720. }
  721. $customerData = $dbResult;
  722. unset($dbResult);
  723. if(empty($customerData)){
  724. return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
  725. }
  726. $dbResult = $this->objDCustomer->update(['enableStatus' => $params['enableStatus']], $params['id']);
  727. if ($dbResult === false) {
  728. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  729. }
  730. //self::updateEsData($params['id']);
  731. $objCustomerCache = new CustomerCache();
  732. $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
  733. $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
  734. return ResultWrapper::success($dbResult);
  735. }
  736. /**
  737. * 修改客户
  738. * @param $update
  739. * @param $where
  740. * @return ResultWrapper
  741. * @throws Exception
  742. */
  743. public function updateCustomer($update, $where)
  744. {
  745. if(empty($where)){
  746. return ResultWrapper::fail('修改客户参数错误', ErrorCode::$paramError);
  747. }
  748. $where['deleteStatus'] = StatusCode::$standard;
  749. $dbResult = $this->objDCustomer->get($where);
  750. if ($dbResult === false) {
  751. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  752. }
  753. $customerData = $dbResult;
  754. unset($dbResult);
  755. if(empty($customerData)){
  756. return ResultWrapper::fail('修改客户不存在', ErrorCode::$paramError);
  757. }
  758. $dbResult = $this->objDCustomer->update($update, $where);
  759. if ($dbResult === false) {
  760. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  761. }
  762. // self::updateEsData($customerData['id']);
  763. return ResultWrapper::success($dbResult);
  764. }
  765. /**
  766. * 客户审核和未审核
  767. * @param array $params
  768. * @return ResultWrapper
  769. * @throws Exception
  770. */
  771. public function updateCustomerCheckStatus($params)
  772. {
  773. $data = [
  774. 'status' => $params['status'],
  775. 'auditFailReason' => ''
  776. ];
  777. if ($params['status'] == StatusCode::$auditStatus['auditNotPass']) {
  778. $data['auditFailReason'] = $params['reason'];
  779. }
  780. $dbResult = $this->objDCustomer->update($data, $params['id']);
  781. if ($dbResult === false) {
  782. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  783. } else {
  784. /*//redis添加客户总数
  785. $this->objCustomerCache->incrCustomerNum($this->enterpriseId);
  786. //近一个月注册的用户
  787. $this->objCustomerCache->incrCustomer($params['id'], $this->enterpriseId);
  788. //添加今日新增客户数
  789. $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1);
  790. $shopId = $this->objDCustomer->get_field('shopId', $params['id']);
  791. if ($shopId) {
  792. $this->objOverviewCache->saveBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', 1, $shopId);
  793. }*/
  794. $customerData = $this->objDCustomer->get($params['id']);
  795. self::setCustomerCache($customerData['shopId']);//缓存用户数据
  796. // self::updateEsData($params['id']);
  797. $objCustomerCache = new CustomerCache();
  798. $objCustomerCache->delCustomerData($this->enterpriseId, $params['id']);
  799. $objCustomerCache->delCustomerUserData($this->enterpriseId, $customerData['userCenterId']);
  800. return ResultWrapper::success($dbResult);
  801. }
  802. }
  803. /**
  804. *
  805. * 缓存用户数据
  806. * @param int $shopId
  807. * @return ResultWrapper
  808. */
  809. public function setCustomerCache($shopId = false)
  810. {
  811. $result = self::querySelectCondition(['status'=>StatusCode::$auditStatus['auditPass']]);
  812. if (!$result->isSuccess()){
  813. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  814. }
  815. $total =(int) $result->getData();
  816. //缓存客户总数
  817. $this->objCustomerCache->setCustomerNum($this->enterpriseId,$total);
  818. //今日新增客户数
  819. $todayStart = date('Y-m-d 00:00:00', time());
  820. $todayEnd = date('Y-m-d 23:59:59', time());
  821. $todayResult = self::querySelectCondition(
  822. [
  823. //'status'=>StatusCode::$auditStatus['auditPass'],
  824. 'createTime'=>[
  825. 'lt'=> strtotime($todayStart),
  826. 'gt'=> strtotime($todayEnd)
  827. ]
  828. ]
  829. );
  830. if (!$result->isSuccess()){
  831. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  832. }
  833. $todayCustomerNum =(int) $todayResult->getData();
  834. $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum);
  835. //对应店铺
  836. if ($shopId) {
  837. $this->objOverviewCache->setBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $todayCustomerNum, $shopId);
  838. }
  839. }
  840. /**
  841. * @param $condition
  842. * @param bool $total
  843. * @return ResultWrapper
  844. */
  845. public function querySelectCondition($condition,$total = true)
  846. {
  847. $field = 'id,status';
  848. $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.'
  849. where deleteStatus = '.StatusCode::$standard;
  850. if (isset($condition['status']) && !empty($condition['status'])){
  851. $sql .= ' and status = '.StatusCode::$auditStatus['auditPass'];
  852. }
  853. if (isset($condition['createTime']) && !empty($condition['createTime'])){
  854. $sql .= ' and createTime BETWEEN '.$condition['createTime']['lt'] .' and '.$condition['createTime']['gt'];
  855. }
  856. $dbResult = $this->objDCustomer->query($sql);
  857. if ($dbResult === false){
  858. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  859. }
  860. return ResultWrapper::success(count((array)$dbResult));
  861. }
  862. /**
  863. * 不同状态下用户的数量
  864. * @return ResultWrapper
  865. * @throws Exception
  866. */
  867. public function getNumberUser()
  868. {
  869. $field = 'COUNT(id) AS totalCount, SUM(CASE WHEN enableStatus='.StatusCode::$standard.
  870. ' 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';
  871. $sql = 'select '.$field.' from qianniao_customer_'.$this->enterpriseId.'
  872. where deleteStatus = '.StatusCode::$standard;
  873. $dbResult = $this->objDCustomer->query($sql);
  874. if ($dbResult === false){
  875. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  876. }
  877. return ResultWrapper::success(reset($dbResult));
  878. }
  879. /**
  880. * 客户列表
  881. * @param array $params 过滤条件
  882. * @return ResultWrapper
  883. * @throws Exception
  884. */
  885. public function getAllCustomer($params)
  886. {
  887. $limit = $params['limit'];
  888. unset($params['limit']);
  889. $offset = $params['offset'];
  890. unset($params['offset']);
  891. $selectParams = 'deleteStatus = ' . StatusCode::$standard . ' AND enterpriseId = ' . $this->enterpriseId;
  892. if (!empty($params['keyword'])) {
  893. $selectParams .= ' AND (name LIKE "%' . $params['keyword'] . '%" or managerMobile LIKE "%' . $params['keyword'] . '%")';
  894. }
  895. if (!empty($params['type'])) {
  896. $selectParams .= ' AND type =' . $params['type'];
  897. }
  898. if (!empty($params['provinceCode'])) {
  899. $selectParams .= ' AND provinceCode =' . $params['provinceCode'];
  900. }
  901. if (!empty($params['cityCode'])) {
  902. $selectParams .= ' AND cityCode =' . $params['cityCode'];
  903. }
  904. if (!empty($params['districtCode'])) {
  905. $selectParams .= ' AND districtCode =' . $params['districtCode'];
  906. }
  907. if (isset($params['status'])) {
  908. if ($params['status'] == StatusCode::$auditStatus['completion']) {
  909. $selectParams .= ' AND status in (' . StatusCode::$auditStatus['completion'] . ',' . StatusCode::$auditStatus['auditNotPass'] . ')';
  910. } else {
  911. $selectParams .= ' AND status =' . $params['status'];
  912. }
  913. }
  914. if (!empty($params['enableStatus'])) {
  915. $selectParams .= ' AND enableStatus =' . $params['enableStatus'];
  916. }
  917. if (!empty($params['shopId'])) {
  918. $selectParams .= ' AND shopId =' . $params['shopId'];
  919. }
  920. if (!empty($params['departmentId'])) {
  921. $selectParams .= ' AND departmentId =' . $params['departmentId'];
  922. }
  923. if (!empty($params['salesManId'])) {
  924. $selectParams .= ' AND salesManId =' . $params['salesManId'];
  925. }
  926. if (!empty($params['start'])) {
  927. $selectParams .= ' AND createTime >=' . $params['start'];
  928. }
  929. if (!empty($params['end'])) {
  930. $selectParams .= ' AND createTime <=' . $params['end'];
  931. }
  932. $selectParams = parent::getSalesManQueryParams($selectParams);
  933. $dbResult = $this->objDCustomer->select($selectParams, '*', 'createTime desc', $limit, $offset);
  934. if ($dbResult === false) {
  935. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  936. }
  937. $total = $this->objDCustomer->count($selectParams);
  938. $return = [
  939. 'data' => self::format($dbResult),
  940. 'total' => ($total) ? intval($total) : 0,
  941. ];
  942. return ResultWrapper::success($return);
  943. }
  944. /**
  945. * 获取企业下的所有客户余额
  946. *
  947. * @param array $selectParams 过滤条件
  948. *
  949. * @return ResultWrapper
  950. * @throws Exception
  951. */
  952. public function getCustomerMoney($selectParams)
  953. {
  954. $limit = $selectParams['limit'];
  955. unset($selectParams['limit']);
  956. $offset = $selectParams['offset'];
  957. unset($selectParams['offset']);
  958. $where = 'deleteStatus=' . StatusCode::$standard . ' AND enterpriseId=' . $this->enterpriseId;
  959. if (isset($selectParams['id'])) {
  960. $where .= ' AND id=' . $selectParams['id'];
  961. }
  962. if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$standard) {
  963. //有财务纠纷
  964. $where .= ' AND (money != 0)';
  965. }
  966. if (isset($selectParams['tag']) && $selectParams['tag'] == StatusCode::$delete) {
  967. //无财务纠纷
  968. $where .= ' AND (money=0)';
  969. }
  970. $selectParams = parent::getSalesManQueryParams($where);
  971. $dbResult = $this->objDCustomer->select($selectParams, 'id AS customerId,name,money,memberBalance', 'createTime desc', $limit, $offset);
  972. if ($dbResult === false) {
  973. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  974. }
  975. foreach ($dbResult as $key => $value) {
  976. //获取销售金额,收款金额
  977. $saleMoney = 0;// 销售金额
  978. $collectionMoney = 0;// 收款金额
  979. $objReceiveTable = new DReceive('finance');
  980. $objReceivedTable = new DReceived('finance');
  981. $objReceiveIndexTable = new DReceiveReceiptIndex('finance');
  982. $objReceiveIndexTable->setTable('qianniao_receive_receipt_index_'.$this->enterpriseId);
  983. $objReceivedIndexTable = new DReceivedIndex('finance');
  984. $objReceivedIndexTable->setTable('qianniao_received_index_'.$this->enterpriseId);
  985. $receiveIndexSql = 'select * from '.$objReceiveIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
  986. $receiveIndexDate = $objReceiveIndexTable->query($receiveIndexSql);
  987. if($receiveIndexDate === false){
  988. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  989. }
  990. if(!empty($receiveIndexDate)){
  991. foreach ($receiveIndexDate as $receiveKey => $receiveValue){
  992. $suffix = date('Y', $receiveValue['createTime']) . '_' . ceil(date('m', $receiveValue['createTime']) / 3);
  993. $objReceiveTable->setTable('qianniao_receive_receipt_' . $this->enterpriseId . '_' . $suffix);
  994. $receiveDate = $objReceiveTable->get($receiveValue['id']);
  995. $saleMoney = bcadd($saleMoney,$receiveDate['receiveMoney'],2);
  996. }
  997. }
  998. $receivedIndexSql = 'select * from '.$objReceivedIndexTable->get_Table().' WHERE customerId='.$value['customerId'] .' AND offsetStatus='.StatusCode::$standard;
  999. $receivedIndexDate = $objReceivedIndexTable->query($receivedIndexSql);
  1000. if($receiveIndexDate === false){
  1001. return ResultWrapper::fail($objReceiveIndexTable->error(), ErrorCode::$dberror);
  1002. }
  1003. if(!empty($receivedIndexDate)){
  1004. foreach ($receivedIndexDate as $receivedKey => $receivedValue){
  1005. $objReceivedTable->setTable('qianniao_received_' . $this->enterpriseId . '_' . date('Y', $receivedValue['createTime']) . '_' . ceil(date('m', $receivedValue['createTime']) / 3));
  1006. $receivedDate = $objReceivedTable->get($receivedValue['id']);
  1007. $collectionMoney = bcadd($collectionMoney,isset($receivedDate['totalFinalMoney']) ? $receivedDate['totalFinalMoney'] :0,2);
  1008. }
  1009. }
  1010. $dbResult[$key]['openingBalance'] = $value['money'];
  1011. // $dbResult[$key]['interimBalance'] = 0;
  1012. $dbResult[$key]['saleMoney'] = $saleMoney;
  1013. $dbResult[$key]['collectionMoney'] = $collectionMoney;
  1014. $dbResult[$key]['endingBalance'] = $value['money'];
  1015. $dbResult[$key]['memberBalance'] = $value['memberBalance'];
  1016. unset($dbResult[$key]['money']);
  1017. }
  1018. $total = $this->objDCustomer->count($selectParams);
  1019. $return = [
  1020. 'data' => $dbResult,
  1021. 'total' => ($total) ? intval($total) : 0,
  1022. ];
  1023. return ResultWrapper::success($return);
  1024. }
  1025. /**
  1026. * 查询客户标签
  1027. * @param $id
  1028. * @return array
  1029. */
  1030. public function getCustomerTag($id)
  1031. {
  1032. $dbResult = $this->objDCustomer->get($id, 'tag');
  1033. return $dbResult;
  1034. }
  1035. /**
  1036. * 添加客户标签
  1037. * @param $params
  1038. * @return ResultWrapper
  1039. * @throws Exception
  1040. */
  1041. public function addCustomerTag($params)
  1042. {
  1043. $tagResult = $this->getCustomerTag($params['id']);
  1044. //判断标签是否已经存在
  1045. $tags = isset($tagResult['tag']) ? json_decode($tagResult['tag'], true) : [];
  1046. if ($tags && in_array($params['tag'], $tags)) {
  1047. return ResultWrapper::fail("客户标签已存在", ErrorCode::$resubmit);
  1048. }
  1049. $tags[] = $params['tag'];
  1050. $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
  1051. if ($dbResult === false) {
  1052. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1053. } else {
  1054. // self::updateEsData($params['id']);
  1055. return ResultWrapper::success($dbResult);
  1056. }
  1057. }
  1058. /**
  1059. * 删除客户标签
  1060. * @param $params
  1061. * @return ResultWrapper
  1062. * @throws Exception
  1063. */
  1064. public function delCustomerTag($params)
  1065. {
  1066. $tagResult = $this->getCustomerTag($params['id']);
  1067. //判断标签是否已经存在
  1068. $tags = json_decode($tagResult['tag'], true);
  1069. if (!$tags || !in_array($params['tag'], $tags)) {
  1070. return ResultWrapper::fail("客户标签不存在", ErrorCode::$resubmit);
  1071. }
  1072. //标签存在,进行删除
  1073. foreach ($tags as $key => $tag) {
  1074. if ($tag == $params['tag']) {
  1075. unset($tags[$key]);
  1076. }
  1077. }
  1078. $dbResult = $this->objDCustomer->update(['tag' => json_encode($tags)], $params['id']);
  1079. if ($dbResult === false) {
  1080. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1081. } else {
  1082. // self::updateEsData($params['id']);
  1083. return ResultWrapper::success($dbResult);
  1084. }
  1085. }
  1086. /**
  1087. * 搜索
  1088. *
  1089. * @param array $selectParams 过滤条件
  1090. *
  1091. * @return ResultWrapper
  1092. * @throws Exception
  1093. */
  1094. public function search($selectParams)
  1095. {
  1096. $defaultDSL = [
  1097. 'from' => $selectParams['offset'],
  1098. 'size' => $selectParams['limit'],
  1099. 'sort' => [
  1100. 'createTime' => [
  1101. 'order' => 'desc'
  1102. ],
  1103. ],
  1104. ];
  1105. $dsl = [];
  1106. $dsl['query']['bool']['must'][] = [
  1107. 'term' => ['deleteStatus' => StatusCode::$standard],
  1108. //'term' => ['enterpriseId' => $this->enterpriseId],
  1109. ];
  1110. $dsl['query']['bool']['must'][] = [
  1111. //'term' => ['deleteStatus' => StatusCode::$standard],
  1112. 'term' => ['enterpriseId' => $this->enterpriseId],
  1113. ];
  1114. //客户名称/手机号
  1115. if (!empty($selectParams['keyword'])) {
  1116. $dsl['query']['bool']['must'][] = [
  1117. 'multi_match' => [
  1118. 'fields' => ['name^1.5', 'mobile', 'tag', 'managerMobile'],
  1119. 'query' => $selectParams['keyword'],
  1120. //'fuzziness' => 'AUTO',
  1121. "type" => "best_fields",
  1122. "tie_breaker" => 0.3,
  1123. "minimum_should_match" => "100%"
  1124. ],
  1125. ];
  1126. }
  1127. //客户类型
  1128. if (!empty($selectParams['type'])) {
  1129. $dsl['query']['bool']['filter'][] =
  1130. ['term' => ['type' => $selectParams['type']]];
  1131. }
  1132. //省code
  1133. if (!empty($selectParams['provinceCode'])) {
  1134. $dsl['query']['bool']['filter'][] =
  1135. ['term' => ['provinceCode' => $selectParams['provinceCode']]];
  1136. }
  1137. //市code
  1138. if (!empty($selectParams['cityCode'])) {
  1139. $dsl['query']['bool']['filter'][] =
  1140. ['term' => ['cityCode' => $selectParams['cityCode']]];
  1141. }
  1142. //区code
  1143. if (!empty($selectParams['districtCode'])) {
  1144. $dsl['query']['bool']['filter'][] =
  1145. ['term' => ['districtCode' => $selectParams['districtCode']]];
  1146. }
  1147. //客户审核状态
  1148. if (!empty($selectParams['status'])) {
  1149. $dsl['query']['bool']['filter'][] =
  1150. ['term' => ['status' => $selectParams['status']]];
  1151. }
  1152. //客户启用状态
  1153. if (!empty($selectParams['enableStatus'])) {
  1154. $dsl['query']['bool']['filter'][] =
  1155. ['term' => ['enableStatus' => $selectParams['enableStatus']]];
  1156. }
  1157. //商铺id
  1158. if (!empty($selectParams['shopId'])) {
  1159. $dsl['query']['bool']['filter'][] =
  1160. ['term' => ['shopId' => $selectParams['shopId']]];
  1161. }
  1162. //部门id
  1163. if (!empty($selectParams['departmentId'])) {
  1164. $dsl['query']['bool']['filter'][] =
  1165. ['term' => ['departmentId' => $selectParams['departmentId']]];
  1166. }
  1167. parent::getAccessSalesManIds();
  1168. if (parent::$salesManIds) {
  1169. $dsl['query']['bool']['filter'][] = [
  1170. 'terms' => ['salesManId' => parent::$salesManIds]
  1171. ];
  1172. }
  1173. //业务员id
  1174. if (!empty($selectParams['salesManId'])) {
  1175. $dsl['query']['bool']['filter'][] =
  1176. ['term' => ['salesManId' => $selectParams['salesManId']]];
  1177. }
  1178. if (!empty($selectParams['start']) && !empty($selectParams['end'])) {
  1179. $dsl['query']['bool']['must'][] = [
  1180. 'range' => [
  1181. 'createTime' => [
  1182. 'gte' => $selectParams['start'],
  1183. 'lte' => $selectParams['end'],
  1184. ]
  1185. ]
  1186. ];
  1187. } else {
  1188. if (!empty($selectParams['start'])) {
  1189. $dsl['query']['bool']['must'][] = [
  1190. 'range' => [
  1191. 'createTime' => [
  1192. 'gte' => $selectParams['start'],
  1193. ]
  1194. ]
  1195. ];
  1196. }
  1197. if (!empty($selectParams['end'])) {
  1198. $dsl['query']['bool']['must'][] = [
  1199. 'range' => [
  1200. 'createTime' => [
  1201. 'lte' => $selectParams['end'],
  1202. ]
  1203. ]
  1204. ];
  1205. }
  1206. }
  1207. $dsl = array_merge($defaultDSL, $dsl);
  1208. $result = $this->objDCustomer->getSearchQueryDsl($dsl);
  1209. if (isset($result['status']) && $result['status'] == 400) {
  1210. if ($result['error']['reason'] == 'all shards failed') {
  1211. return ResultWrapper::success([
  1212. 'data' => [],
  1213. 'total' => 0
  1214. ]);
  1215. }
  1216. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1217. }
  1218. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1219. return ResultWrapper::success([
  1220. 'data' => [],
  1221. 'total' => 0
  1222. ]);
  1223. }
  1224. $total = $result['hits']['total'];
  1225. $dbResult = $result['hits']['hits'];
  1226. $list = [];
  1227. foreach ($dbResult as $key => &$value) {
  1228. $data = [];
  1229. $data = $value['_source'];
  1230. //$data['id'] = $value['_id'];
  1231. $list[] = $data;
  1232. }
  1233. $return = [
  1234. 'data' => self::format($list),
  1235. 'total' => ($total) ? intval($total) : 0,
  1236. ];
  1237. return ResultWrapper::success($return);
  1238. }
  1239. /**
  1240. * 搜索 客户查询
  1241. *
  1242. * @param array $selectParams 过滤条件
  1243. *
  1244. * @return ResultWrapper
  1245. * @throws Exception
  1246. */
  1247. public function query($selectParams)
  1248. {
  1249. $defaultDSL = [
  1250. 'from' => $selectParams['offset'],
  1251. 'size' => $selectParams['limit'],
  1252. 'sort' => [
  1253. 'createTime' => [
  1254. 'order' => 'desc'
  1255. ],
  1256. ],
  1257. ];
  1258. $dsl = [];
  1259. $dsl['query']['bool']['must'][] = [
  1260. 'term' => ['deleteStatus' => StatusCode::$standard],
  1261. //'term' => ['enterpriseId' => $this->enterpriseId],
  1262. ];
  1263. $dsl['query']['bool']['must'][] = [
  1264. //'term' => ['deleteStatus' => StatusCode::$standard],
  1265. 'term' => ['enterpriseId' => $this->enterpriseId],
  1266. ];
  1267. //客户名称/手机号
  1268. if (!empty($selectParams['keyword'])) {
  1269. $dsl['query']['bool']['must'][] = [
  1270. 'multi_match' => [
  1271. 'fields' => ['name', 'mobile', 'managerMobile'],
  1272. 'query' => $selectParams['keyword'],
  1273. //'fuzziness' => 'AUTO',
  1274. "type" => "best_fields",
  1275. "tie_breaker" => 0.3,
  1276. "minimum_should_match" => "100%"
  1277. ],
  1278. ];
  1279. }
  1280. //标签
  1281. if (!empty($selectParams['tag'])) {
  1282. $dsl['query']['bool']['must'][] = [
  1283. 'match' => [
  1284. 'tag' => $selectParams['tag'],
  1285. ],
  1286. ];
  1287. }
  1288. //省code
  1289. if (!empty($selectParams['provinceCode'])) {
  1290. $dsl['query']['bool']['filter'][] =
  1291. ['term' => ['provinceCode' => $selectParams['provinceCode']]];
  1292. }
  1293. //市code
  1294. if (!empty($selectParams['cityCode'])) {
  1295. $dsl['query']['bool']['filter'][] =
  1296. ['term' => ['cityCode' => $selectParams['cityCode']]];
  1297. }
  1298. //区code
  1299. if (!empty($selectParams['districtCode'])) {
  1300. $dsl['query']['bool']['filter'][] =
  1301. ['term' => ['districtCode' => $selectParams['districtCode']]];
  1302. }
  1303. //客户启用状态
  1304. if (!empty($selectParams['enableStatus'])) {
  1305. $dsl['query']['bool']['filter'][] =
  1306. ['term' => ['enableStatus' => $selectParams['enableStatus']]];
  1307. }
  1308. //商铺id
  1309. if (!empty($selectParams['shopId'])) {
  1310. $dsl['query']['bool']['filter'][] =
  1311. ['term' => ['shopId' => $selectParams['shopId']]];
  1312. }
  1313. //来源
  1314. if (!empty($selectParams['source'])) {
  1315. $dsl['query']['bool']['filter'][] =
  1316. ['term' => ['source' => $selectParams['source']]];
  1317. }
  1318. parent::getAccessSalesManIds();
  1319. if (parent::$salesManIds) {
  1320. $dsl['query']['bool']['filter'][] = [
  1321. 'terms' => ['salesManId' => parent::$salesManIds]
  1322. ];
  1323. }
  1324. //业务员id
  1325. if (!empty($selectParams['salesManId'])) {
  1326. $dsl['query']['bool']['filter'][] =
  1327. ['term' => ['salesManId' => $selectParams['salesManId']]];
  1328. }
  1329. if (!empty($selectParams['birthday_start']) && !empty($selectParams['birthday_end'])) {
  1330. $dsl['query']['bool']['must'][] = [
  1331. 'range' => [
  1332. 'createTime' => [
  1333. 'gte' => $selectParams['birthday_start'],
  1334. 'lte' => $selectParams['birthday_end'],
  1335. ]
  1336. ]
  1337. ];
  1338. } else {
  1339. if (!empty($selectParams['birthday_start'])) {
  1340. $dsl['query']['bool']['must'][] = [
  1341. 'range' => [
  1342. 'createTime' => [
  1343. 'gte' => $selectParams['birthday_start'],
  1344. ]
  1345. ]
  1346. ];
  1347. }
  1348. if (!empty($selectParams['birthday_end'])) {
  1349. $dsl['query']['bool']['must'][] = [
  1350. 'range' => [
  1351. 'createTime' => [
  1352. 'lte' => $selectParams['birthday_end'],
  1353. ]
  1354. ]
  1355. ];
  1356. }
  1357. }
  1358. $dsl = array_merge($defaultDSL, $dsl);
  1359. $result = $this->objDCustomer->getSearchQueryDsl($dsl);
  1360. if (isset($result['status']) && $result['status'] == 400) {
  1361. if ($result['error']['reason'] == 'all shards failed') {
  1362. return ResultWrapper::success([
  1363. 'data' => [],
  1364. 'total' => 0
  1365. ]);
  1366. }
  1367. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1368. }
  1369. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1370. return ResultWrapper::success([
  1371. 'data' => [],
  1372. 'total' => 0
  1373. ]);
  1374. }
  1375. $total = $result['hits']['total'];
  1376. $dbResult = $result['hits']['hits'];
  1377. $list = [];
  1378. foreach ($dbResult as $key => &$value) {
  1379. $data = [];
  1380. $data = $value['_source'];
  1381. //$data['id'] = $value['_id'];
  1382. $list[] = $data;
  1383. }
  1384. $return = [
  1385. 'data' => self::format($list),
  1386. 'total' => ($total) ? intval($total) : 0,
  1387. ];
  1388. return ResultWrapper::success($return);
  1389. }
  1390. /**
  1391. * 根据code获取今日下单客户的经纬度信息
  1392. * @param string $code 省市区编码
  1393. * @return ResultWrapper
  1394. */
  1395. public function getTodayOrderCustomerLocation($code = '')
  1396. {
  1397. $result = [];
  1398. $objCustomerCache = new CustomerCache();
  1399. $customerIds = $objCustomerCache->getTodayCustomerOrderInfo($this->enterpriseId, $code);
  1400. $dsl = [];
  1401. $dsl['query']['terms'] = [
  1402. '_id' => $customerIds,
  1403. ];
  1404. $result = $this->objDCustomer->getSearchQueryDsl($dsl);
  1405. if (isset($result['status']) && $result['status'] == 400) {
  1406. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1407. }
  1408. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1409. return ResultWrapper::success([]);
  1410. }
  1411. $dbResult = $result['hits']['hits'];
  1412. $list = [];
  1413. foreach ($dbResult as $key => &$value) {
  1414. $location = $value['_source']['location'];
  1415. $list[] = [
  1416. 'lng' => $location['lon'],
  1417. 'lat' => $location['lat']
  1418. ];
  1419. }
  1420. return ResultWrapper::success($list);
  1421. }
  1422. /**
  1423. * 根据code获取客户分布图
  1424. * @param string $code 省市区编码
  1425. * @return ResultWrapper
  1426. */
  1427. public function getCustomerLocation($code = '')
  1428. {
  1429. $dsl = [];
  1430. parent::getAccessSalesManIds();
  1431. if (parent::$salesManIds) {
  1432. $dsl['query']['bool']['filter'][] = [
  1433. 'terms' => ['salesManId' => parent::$salesManIds]
  1434. ];
  1435. }
  1436. if (!empty($code)) {
  1437. $dsl['query']['bool']['must'][] = [
  1438. 'term' => ['districtCode' => $code],
  1439. ];
  1440. }
  1441. $result = $this->objDCustomer->getSearchQueryDsl($dsl);
  1442. if (isset($result['status']) && $result['status'] == 400) {
  1443. if ($result['error']['reason'] == 'all shards failed') {
  1444. return ResultWrapper::success([]);
  1445. }
  1446. return ResultWrapper::fail('获取数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
  1447. }
  1448. if (!isset($result['hits']) || $result['hits']['total'] == 0) {
  1449. return ResultWrapper::success([]);
  1450. }
  1451. $dbResult = $result['hits']['hits'];
  1452. $list = [];
  1453. foreach ($dbResult as $key => &$value) {
  1454. if (isset($value['_source']['location'])) {
  1455. $location = $value['_source']['location'];
  1456. $list[] = [
  1457. 'lng' => $location['lon'],
  1458. 'lat' => $location['lat']
  1459. ];
  1460. }
  1461. }
  1462. return ResultWrapper::success($list);
  1463. }
  1464. /**
  1465. * 根据userCenterId获取customerId
  1466. * @param $userCenterId
  1467. * @return mixed
  1468. */
  1469. public function getCustomerIdByUserCenterId($userCenterId)
  1470. {
  1471. $customerId = $this->objDCustomer->get_field('id', ['userCenterId' => $userCenterId]);
  1472. return $customerId ? $customerId : 0;
  1473. }
  1474. /**
  1475. * 根据customerId获取userCenterId
  1476. * @param $customerId
  1477. * @return mixed
  1478. */
  1479. public function getUserCenterIdByCustomerId($customerId)
  1480. {
  1481. $userCenterId = $this->objDCustomer->get_field('userCenterId', ['id' => $customerId]);
  1482. return $userCenterId ? $userCenterId : 0;
  1483. }
  1484. /**
  1485. * 根据openId获取userCenterId
  1486. * @param $openId
  1487. * @return mixed
  1488. */
  1489. public function getUserCenterIdByOpenId($openId)
  1490. {
  1491. $userCenterId = $this->objDCustomer->get_field('userCenterId', ['openId' => $openId]);
  1492. return $userCenterId ? $userCenterId : 0;
  1493. }
  1494. /**
  1495. * 通过openId或者uniondId获取userCenterId
  1496. * @param $params
  1497. * @param $source
  1498. * @return ResultWrapper
  1499. * @throws Exception
  1500. */
  1501. public function getUserCenterIdByOpenIdOrUnionId($params, $source)
  1502. {
  1503. $whereSql = '';
  1504. if( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['android'],StatusCode::$source['ios'],StatusCode::$source['weiXinBrowser']]) ) {
  1505. //微信
  1506. $whereSql = ' where openId = "' . $params['openId'] . '"';
  1507. !empty($params['unionId']) && $whereSql .= ' or unionId = "' . $params['unionId'] . '"';
  1508. // !empty($params['unionId']) && $whereSql .= ' and unionId = "' . $params['unionId'] . '"';//文档建议这样修改
  1509. }
  1510. if ($source == StatusCode::$source['ByteProgram']) {
  1511. //抖音
  1512. $whereSql = ' where byteOpenId = "' . $params['openId'] . '"';
  1513. }
  1514. if (empty($whereSql)) {
  1515. return ResultWrapper::fail('查询客户source参数错误', ErrorCode::$paramError);
  1516. }
  1517. $this->objDCustomer->setTable('qianniao_customer_' . $this->enterpriseId);
  1518. $sql = 'select * from ' . $this->objDCustomer->get_Table() . $whereSql;
  1519. $dbResult = $this->objDCustomer->query($sql);
  1520. if ($dbResult === false) {
  1521. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1522. }
  1523. //是空仍然返回
  1524. return ResultWrapper::success($dbResult);
  1525. }
  1526. /**
  1527. * 指定字段修改用户数据
  1528. * @param $where
  1529. * @param $update
  1530. * @return ResultWrapper
  1531. */
  1532. public function setCustomerData($where, $update)
  1533. {
  1534. $dbResult = $this->objDCustomer->update($update, $where);
  1535. if ($dbResult === false) {
  1536. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1537. }
  1538. return ResultWrapper::success($dbResult);
  1539. }
  1540. /**
  1541. * 绑定覆盖unionId (微信, 抖音)
  1542. * @param $source
  1543. * @param $userCenterId
  1544. * @param $openId
  1545. * @param $unionId
  1546. * @param string $avatar
  1547. * @param string $name
  1548. * @return ResultWrapper
  1549. */
  1550. public function bindOpenIdAndMobile($source, $userCenterId, $openId, $unionId, $avatar = '', $name = '')
  1551. {
  1552. //判断是微信还是抖音
  1553. if ( in_array($source, [StatusCode::$source['miniProgram'],StatusCode::$source['ios'],StatusCode::$source['android'],StatusCode::$source['weiXinBrowser']])) {
  1554. !empty($openId) && $param['openId'] = $openId;
  1555. $param['unionId'] = $unionId;
  1556. } elseif ($source == StatusCode::$source['ByteProgram']) {
  1557. $param['byteOpenId'] = $openId;
  1558. } else {
  1559. return ResultWrapper::fail('覆盖客户绑定数据source参数错误', ErrorCode::$paramError);
  1560. }
  1561. if (empty($param)) {
  1562. return ResultWrapper::fail('覆盖客户绑定修改数据为空', ErrorCode::$paramError);
  1563. }
  1564. $dbResult = $this->objDCustomer->update($param, ['userCenterId' => $userCenterId]);
  1565. if ($dbResult === false) {
  1566. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1567. } else {
  1568. return ResultWrapper::success($dbResult);
  1569. }
  1570. }
  1571. /**
  1572. * 根据userCenterId和企业id查询客户数据
  1573. * @param $userCenterId
  1574. * @param $enterpriseId
  1575. * @return ResultWrapper
  1576. * @throws Exception
  1577. */
  1578. public function getCustomerDataByUserCenterIdAndEnterpriseId($userCenterId, $enterpriseId = false)
  1579. {
  1580. !$enterpriseId && $enterpriseId = $this->enterpriseId;
  1581. $this->objDCustomer->setTable('qianniao_customer_' . $enterpriseId);
  1582. $dbResult = $this->objDCustomer->get(['userCenterId' => $userCenterId, 'enterpriseId' => $enterpriseId, 'deleteStatus' => StatusCode::$standard]);
  1583. if ($dbResult === false) {
  1584. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1585. }
  1586. return ResultWrapper::success($dbResult);
  1587. }
  1588. /**
  1589. * 获取客户基本信息
  1590. */
  1591. public function getCustomerBasicInfoByUserCenterIds($userCenterIds = [])
  1592. {
  1593. if(empty($userCenterIds)){
  1594. return ResultWrapper::success('未指定查询的userCenterIds', ErrorCode::$paramError);
  1595. }
  1596. $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) .')';
  1597. $dbResult = $this->objDCustomer->query($sql);
  1598. if ($dbResult === false) {
  1599. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1600. }
  1601. return ResultWrapper::success($dbResult);
  1602. }
  1603. /**
  1604. * 根据userCenterId获取客户完整信息 看不懂?????
  1605. * @param $userCenterId
  1606. * @param $fields
  1607. * @return ResultWrapper
  1608. * @throws Exception
  1609. */
  1610. public function getCustomerInfoByUserCenterId($userCenterId,$isMini = false)
  1611. {
  1612. $customerInfo = $this->objCustomerCache->getCustomerUserData($this->enterpriseId,$userCenterId);
  1613. // if (empty($customerInfo)) {
  1614. $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';
  1615. $dbResult = $this->objDCustomer->query($sql);
  1616. if ($dbResult === false) {
  1617. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1618. }
  1619. if (empty($dbResult)) {
  1620. return ResultWrapper::fail('要查询的客户不存在', ErrorCode::$contentNotExists);
  1621. }
  1622. //查业务员名称
  1623. $customerInfo = array_shift($dbResult);
  1624. $sourceType = isset($customerInfo['type']) ? $customerInfo['type'] : null;
  1625. $dbResult['customerSourceTypeName'] = '';
  1626. $dbResult['modelType'] = '';
  1627. if (!empty($sourceType)) {
  1628. //映射客户类型名称
  1629. $fields = 'id,name,modelType';
  1630. $customerSource = $this->objDCustomer->query('select ' . $fields . ' from qianniao_customer_source where id = ' . $sourceType);
  1631. if ($customerSource === false) {
  1632. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1633. }
  1634. $customerSourceInfo = array_shift($customerSource);
  1635. $dbResult['customerSourceTypeName'] = isset($customerSourceInfo['name']) ? $customerSourceInfo['name'] : '';
  1636. $dbResult['modelType'] = isset($customerSourceInfo['modelType']) ? $customerSourceInfo['modelType'] : '';
  1637. }
  1638. $customerInfo['extend'] = json_decode($customerInfo['extend'], true);
  1639. $salesManDate = $this->objMStaff->getNameById($customerInfo['salesManId']);
  1640. $customerInfo['salesManName'] = isset($salesManDate['staffName']) ? $salesManDate['staffName'] : '';
  1641. $customerInfo['salesManMobile'] = isset($salesManDate['userMobile']) ? $salesManDate['userMobile'] : '';
  1642. $customerInfo['modelType'] = $dbResult['modelType'];
  1643. $customerInfo['customerSourceTypeName'] = $dbResult['customerSourceTypeName'];
  1644. //联系人
  1645. $customerInfo['contact'] = $this->objMCustomerContact->getContactInfoById($customerInfo['id']);
  1646. $this->objCustomerCache->cacheCustomerUserData($this->enterpriseId,$userCenterId,$customerInfo);
  1647. // }
  1648. if ($isMini === true){
  1649. $objMUserCoupon = new MUserCoupon($this->userCenterId,$this->enterpriseId);
  1650. $couponNumResult = $objMUserCoupon->getCouponNum($userCenterId);
  1651. if (!$couponNumResult->isSuccess()){
  1652. return ResultWrapper::fail($couponNumResult->getData(),$couponNumResult->getErrorCode());
  1653. }
  1654. $objMVipCard = new MVipCard($this->enterpriseId,$this->userCenterId);
  1655. $vipNumResult = $objMVipCard->getVipCardNum($userCenterId);
  1656. if (!$vipNumResult->isSuccess()){
  1657. return ResultWrapper::fail($vipNumResult->getData(),$vipNumResult->getErrorCode());
  1658. }
  1659. $customerInfo['vipNum'] = (int)$vipNumResult->getData();
  1660. $customerInfo['couponNum'] = $couponNumResult->getData();
  1661. $objMGoodsCollect = new MGoodsCollect($this->enterpriseId,$this->userCenterId);
  1662. $collNumResult = $objMGoodsCollect->getCollNum($userCenterId);
  1663. if (!$collNumResult->isSuccess()){
  1664. return ResultWrapper::fail($collNumResult->getData(),$collNumResult->getErrorCode());
  1665. }
  1666. $customerInfo['collNum'] = (int)$collNumResult->getData();
  1667. }
  1668. //查询店铺信息
  1669. $customerInfo['shopDate'] = [];
  1670. $objDShop = new DShop();
  1671. $objDShop->setTable('qianniao_shop_1');
  1672. $shopResult = $objDShop->get(['enterpriseId'=>$this->enterpriseId]);
  1673. if ($shopResult === false) {
  1674. return ResultWrapper::fail($objDShop->error(), ErrorCode::$dberror);
  1675. }
  1676. $customerInfo['shopDate'] = $shopResult;
  1677. $customerInfo['enterpriseMobile'] = isset($customerInfo["enterpriseMobile"])? $customerInfo["enterpriseMobile"]:"";//文档建议这样修改,返回一个企业联系电话
  1678. return ResultWrapper::success($customerInfo);
  1679. }
  1680. /**
  1681. * @param $selectParams
  1682. * @param string $field
  1683. * @return ResultWrapper
  1684. */
  1685. public function getCustomer($selectParams, $field = 'name,id')
  1686. {
  1687. $dbResult = $this->objDCustomer->select($selectParams, $field);
  1688. if ($dbResult === false) {
  1689. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1690. }
  1691. $customerData = [];
  1692. if (!empty($dbResult)) {
  1693. foreach ($dbResult as $info) {
  1694. $customerData[$info['id']] = $info;
  1695. }
  1696. }
  1697. return ResultWrapper::success($customerData);
  1698. }
  1699. /**
  1700. * 获取客户总数
  1701. */
  1702. public function getCustomerTotalNum()
  1703. {
  1704. $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
  1705. if ($result === false){
  1706. //缓存客户数据
  1707. self::setCustomerCache();
  1708. $result = $this->objCustomerCache->getAllCustomerNum($this->enterpriseId);
  1709. }
  1710. return $result ? $result : 0;
  1711. }
  1712. /**
  1713. * 今日新增客户数
  1714. * @param null $shopId
  1715. * @return bool|int
  1716. */
  1717. public function getTodayCustomerTotalNum($shopId = null)
  1718. {
  1719. /*$result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
  1720. if ($result === false){
  1721. self::setCustomerCache();
  1722. $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
  1723. }*/
  1724. self::setCustomerCache($shopId);
  1725. $result = $this->objOverviewCache->getBusinessOverview($this->enterpriseId, 'todayNewCustomerNum', $shopId);
  1726. return $result ? $result : 0;
  1727. }
  1728. /**
  1729. * 获取总的应收款
  1730. */
  1731. public function getTotalShouldReceive()
  1732. {
  1733. $result = $this->objOverviewCache->getAggregateStatistics($this->enterpriseId, 'totalShouldReceive');
  1734. return $result ? $result : 0;
  1735. }
  1736. /**
  1737. *获取新增客户数(近30天注册但未交易)
  1738. */
  1739. public function getNewCustomerNum()
  1740. {
  1741. $result = $this->objCustomerCache->getNewCustomerNum($this->enterpriseId);
  1742. return $result ? $result : 0;
  1743. }
  1744. /**
  1745. *获取兴趣人群数
  1746. */
  1747. public function getInterestCustomerNum()
  1748. {
  1749. $result = $this->objCustomerCache->getInterestCustomerNum($this->enterpriseId);
  1750. return $result ? $result : 0;
  1751. }
  1752. /**
  1753. * 今日客户排行
  1754. * @param int $ranking 1销量排行 2销额排行
  1755. * @return array
  1756. */
  1757. public function todayCustomerRanking($ranking = 1)
  1758. {
  1759. if ($ranking == 1) {
  1760. $result = $this->objOverviewCache->getRanking($this->enterpriseId, 'customerRanking');
  1761. } else {
  1762. $result = $this->objOverviewCache->getSalesMoneyRanking($this->enterpriseId, 'customerRanking');
  1763. }
  1764. if (empty($result)) {
  1765. return [];
  1766. }
  1767. //拼接customerId
  1768. $customerIds = [];
  1769. foreach ($result as $customerId => $v) {
  1770. $i = 1;
  1771. $customerIds[] = $customerId;
  1772. $i++;
  1773. if ($i >= 8) {
  1774. break;
  1775. }
  1776. }
  1777. //查找客户名称
  1778. $customerResult = self::getCustomer($customerIds);
  1779. $customerNameData = [];
  1780. if ($customerResult->isSuccess()) {
  1781. $customerNameData = $customerResult->getData();
  1782. }
  1783. //拼接返回数据
  1784. $return = [];
  1785. foreach ($result as $customerId => $v) {
  1786. $i = 1;
  1787. $rank = [];
  1788. $rank['id'] = $i;
  1789. $rank['customerName'] = isset($customerNameData[$customerId]['name']) ? $customerNameData[$customerId]['name'] : '';
  1790. $rank['numberOrMoney'] = $v;
  1791. $return[] = $rank;
  1792. $i++;
  1793. if ($i >= 8) {
  1794. break;
  1795. }
  1796. }
  1797. return $return;
  1798. }
  1799. /**
  1800. * 格式化客户
  1801. */
  1802. public function formatCustomer()
  1803. {
  1804. //查询所有企业
  1805. $sql = 'select id from qianniao_enterprise_1 where deleteStatus = 5';
  1806. $dbResult = $this->objDCustomer->query($sql);
  1807. if($dbResult === false){
  1808. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1809. }
  1810. $ii = 0;
  1811. $enterprise = $dbResult;
  1812. unset($dbResult);
  1813. foreach($enterprise as $enterpriseValue){
  1814. //查询客户
  1815. $this->objDCustomer->setTable('qianniao_customer_'.$enterpriseValue['id']);
  1816. $dbResult = $this->objDCustomer->select();
  1817. if($dbResult === false){
  1818. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1819. }
  1820. if(empty($dbResult)){
  1821. continue;
  1822. }
  1823. //循环客户
  1824. foreach($dbResult as $value){
  1825. //修改营业执照
  1826. $extend = json_decode($value['extend'], true);
  1827. if(isset($extend['license']) && !empty($extend['license']) && strpos($extend['license'],'?imageView2') !== false){
  1828. $extend['license'] = substr($extend['license'], 0, strrpos($extend['license'],'?imageView2'));
  1829. $update['extend'] = json_encode($extend);
  1830. //保存客户
  1831. $result = $this->objDCustomer->update($update, ['id' => $value['id']]);
  1832. if($result === false){
  1833. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1834. }
  1835. $ii++;
  1836. }
  1837. }
  1838. }
  1839. return ResultWrapper::success('修改成功, 共修改'.$ii.'条数据');
  1840. }
  1841. /**
  1842. * 充值余额
  1843. * @param $params
  1844. * @return ResultWrapper
  1845. * @throws Exception
  1846. */
  1847. public function rechargeBalance($params)
  1848. {
  1849. $where['userCenterId'] = $params['userCenterId'];
  1850. //查询客户信息
  1851. $dbResult = $this->objDCustomer->get($where);
  1852. if($dbResult === false){
  1853. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1854. }
  1855. $customerData = $dbResult;
  1856. unset($dbResult);
  1857. //记录充值记录
  1858. $recordInsert = [
  1859. 'no' => createOrderSn(StatusCode::$source['miniProgram'], 0, $customerData['userCenterId']),
  1860. 'customerId' => $customerData['id'],
  1861. 'money' => $params['money'],
  1862. 'userCenterId' => $customerData['userCenterId'],
  1863. 'shopId' => $customerData['shopId'],
  1864. 'payStatus' => StatusCode::$delete,
  1865. 'desc' => '充值余额'.$params['money'].'元',
  1866. 'createTime' => time(),
  1867. 'updateTime' => time(),
  1868. ];
  1869. $dbResult = $this->objDCustomerRechargeRecord->insert($recordInsert);
  1870. if($dbResult === false){
  1871. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  1872. }
  1873. $recordId = $dbResult;
  1874. unset($dbResult);
  1875. //获取支付配置
  1876. $objMPaymentSetting = new MPaymentSetting($this->enterpriseId, $this->userCenterId);
  1877. $result = $objMPaymentSetting->getPayData($params['payType']);
  1878. if (!$result->isSuccess() || empty($result->getData())) {
  1879. return ResultWrapper::fail('获取微信配置错误', ErrorCode::$configEroor);
  1880. }
  1881. $payment = $result->getData();
  1882. // 获取当前登录企业的小程序配置
  1883. $objSystemCache = new SystemCache();
  1884. $miniprogramSetting = $objSystemCache->getAppIdByEnterpriseId($this->enterpriseId);
  1885. if (empty($miniprogramSetting)) {
  1886. return ResultWrapper::fail('后台小程序配置项为空', ErrorCode::$configEroor);
  1887. }
  1888. $miniprogramSetting = json_decode($miniprogramSetting, true);//获取小程序appid
  1889. $appid = $miniprogramSetting['appid'];
  1890. $paySource = 'miniProgram';
  1891. $weixinConfigData = [
  1892. 'mch_id' => $payment['mchId'],
  1893. 'apiPartnerKey' => $payment['apiPartnerKey'],
  1894. 'appid' => $appid
  1895. ];
  1896. $attach = $this->enterpriseId . '|' . $this->userCenterId . '|' . $recordId;
  1897. $objPay = new Pay($appid, $weixinConfigData['mch_id'], $weixinConfigData['apiPartnerKey']);
  1898. $modelResult = $objPay->unifiedorder($recordInsert['no'], $params['money'], $params['ip'], $paySource, '千鸟云商', $customerData['openId'], $attach);
  1899. if (!$modelResult->isSuccess()) {
  1900. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1901. }
  1902. return ResultWrapper::success($modelResult->getData());
  1903. }
  1904. /**
  1905. * 支付完成调用方法
  1906. * @param $params
  1907. * @return ResultWrapper
  1908. * @throws Exception
  1909. */
  1910. public function payTrue($params)
  1911. {
  1912. //查询充值记录
  1913. $dbResult = $this->objDCustomerRechargeRecord->get(['id' => $params['id']]);
  1914. if($dbResult === false){
  1915. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  1916. }
  1917. $record = $dbResult;
  1918. unset($dbResult);
  1919. //查询客户
  1920. $dbResult = $this->objDCustomer->get(['id' => $record['customerId']]);
  1921. if($dbResult === false){
  1922. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1923. }
  1924. $customerData = $dbResult;
  1925. unset($dbResult);
  1926. //客户修改数据
  1927. $update = [
  1928. 'money' => bcadd($customerData['money'], $record['money'], 4),
  1929. 'updateTime' => time(),
  1930. ];
  1931. //修改充值记录状态
  1932. $updateRecord = [
  1933. 'balance' => $update['money'],
  1934. 'payStatus' => StatusCode::$standard,
  1935. 'updateTime' => time(),
  1936. ];
  1937. //开启事务
  1938. $this->objDCustomerRechargeRecord->beginTransaction();
  1939. $dbResult = $this->objDCustomerRechargeRecord->update($updateRecord, ['id' => $params['id']]);
  1940. if($dbResult === false){
  1941. $this->objDCustomerRechargeRecord->rollBack();
  1942. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  1943. }
  1944. //记录余额流水
  1945. $turnoverInsert = [
  1946. 'sourceId' => $record['id'],
  1947. 'sourceNo' => $record['no'],
  1948. 'source' => 1,//来源 1:充值余额
  1949. 'customerId' => $customerData['id'],
  1950. 'userCenterId' => $customerData['userCenterId'],
  1951. 'shopId' => $customerData['shopId'],
  1952. 'money' => $record['money'],
  1953. 'balance' => $update['money'],
  1954. 'type' => StatusCode::$standard,
  1955. 'desc' => '充值余额'.$record['money'].'元',
  1956. 'createTime' => time(),
  1957. 'updateTime' => time(),
  1958. ];
  1959. $dbResult = $this->objDCustomerBalanceTurnover->insert($turnoverInsert);
  1960. if($dbResult === false){
  1961. $this->objDCustomerRechargeRecord->rollBack();
  1962. return ResultWrapper::fail($this->objDCustomerBalanceTurnover->error(), ErrorCode::$dberror);
  1963. }
  1964. //增加财务客户余额流水
  1965. $objMCustomerBalanceDetail = new MCustomerBalanceDetail($this->enterpriseId, $this->userCenterId);
  1966. $detailInsert = [
  1967. 'customerId' => $customerData['id'],//'客户id',
  1968. 'receiptTime' => time(),//'单据日期',
  1969. 'sourceId' => $customerData['id'],
  1970. 'sourceNo' => createOrderSn(StatusCode::$source['miniProgram'], 8, $customerData['userCenterId']),//'单据编号',
  1971. 'financeType' => '会员余额充值收款',//'财务类型名称',
  1972. 'financeTypeId' => 8,//'财务类型id',
  1973. 'sourceId' => $record['id'],
  1974. 'sourceNo' => $record['no'],//'源订单销货号',
  1975. 'salesAmount' => $record['money'],//总金额
  1976. 'discountMoney' => 0,// '优惠金额',
  1977. 'customerAmount' => $record['money'],// '客户承担金额',
  1978. 'receivableAmount' => $record['money'],// '应收金额',
  1979. 'actualReceivableAmount' => $record['money'],//'实际收款金额',
  1980. 'receivableBalance' => $update['money'],//'应收后余额',
  1981. 'remark' => '客户充值余额 本次实收' . $record['money'] . '元',//'备注',
  1982. 'createTime' => time(),//'创建日期',
  1983. 'updateTime' => time(),//'修改日期',
  1984. ];
  1985. $modelResult = $objMCustomerBalanceDetail->addCustomerBalanceDetail($detailInsert);
  1986. if(!$modelResult->isSuccess()){
  1987. $this->objDCustomerRechargeRecord->rollBack();
  1988. return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
  1989. }
  1990. //修改客户余额
  1991. $dbResult = $this->objDCustomer->update($update, ['id' => $customerData['id']]);
  1992. if($dbResult === false){
  1993. $this->objDCustomerRechargeRecord->rollBack();
  1994. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  1995. }
  1996. //提交事务
  1997. $this->objDCustomerRechargeRecord->commit();
  1998. return ResultWrapper::success('支付成功');
  1999. }
  2000. /**
  2001. * 充值记录列表
  2002. * @param $params
  2003. * @return ResultWrapper
  2004. */
  2005. public function getAllRechargeBalance($params)
  2006. {
  2007. $limit = $params['limit'];
  2008. $offset = $params['offset'];
  2009. $where = [];
  2010. if(isset($params['customerId'])){
  2011. $where['customerId'] = $params['customerId'];
  2012. }
  2013. if(isset($params['userCenterId'])){
  2014. $where['userCenterId'] = $params['userCenterId'];
  2015. }
  2016. $dbResult = $this->objDCustomerRechargeRecord->select($where, '*', 'createTime desc', $limit, $offset);
  2017. if($dbResult === false){
  2018. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  2019. }
  2020. $data = $dbResult;
  2021. unset($dbResult);
  2022. $count = $this->objDCustomerRechargeRecord->count($where);
  2023. $return = [
  2024. 'data' => $data,
  2025. 'total' => $count ? $count : 0
  2026. ];
  2027. return ResultWrapper::success($return);
  2028. }
  2029. /**
  2030. * Doc: (des="")
  2031. * User: XMing
  2032. * Date: 2021/1/15
  2033. * Time: 5:35 下午
  2034. * @param $ids
  2035. * @return ResultWrapper
  2036. * @throws Exception
  2037. */
  2038. public function getCustomerByIds($ids): ResultWrapper
  2039. {
  2040. if (empty($ids)){
  2041. return ResultWrapper::success([]);
  2042. }
  2043. $lists = $this->objDCustomer->select(['id' => $ids]);
  2044. if ($lists === false){
  2045. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  2046. }
  2047. $formatLists = self::format($lists);
  2048. return ResultWrapper::success($formatLists);
  2049. }
  2050. /**
  2051. * Doc: (des="")
  2052. * User: XMing
  2053. * Date: 2020/11/14
  2054. * Time: 10:40 上午
  2055. * @param $customerId
  2056. * @return ResultWrapper
  2057. */
  2058. public function getCustomerByCustomerId($customerId): ResultWrapper
  2059. {
  2060. if (empty($customerId)){
  2061. return ResultWrapper::success([]);
  2062. }
  2063. $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 ';
  2064. $sql = 'SELECT '.$fields.' FROM ' . $this->objDUserCenter->get_Table() . '
  2065. AS u JOIN ' . $this->objDCustomer->get_Table() . '
  2066. AS c ON u.id=c.userCenterId AND c.id=' . $customerId . ' LIMIT 1';
  2067. $dbResult = $this->objDCustomer->query($sql);
  2068. if ($dbResult === false) {
  2069. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2070. }
  2071. $dbResult = (array)$dbResult;
  2072. $dbResult = array_shift($dbResult);
  2073. return ResultWrapper::success($dbResult);
  2074. }
  2075. /**
  2076. * 首字母搜索客户
  2077. * @param $data
  2078. * @return ResultWrapper
  2079. */
  2080. public function initialsSearch($data)
  2081. {
  2082. $condition = isset($data['condition']) && !empty($data['condition']) ? $data['condition'] : '';
  2083. if (empty($condition)) return ResultWrapper::success([]);
  2084. $objChineseCharacter = new ChineseCharacter();
  2085. $condition = $objChineseCharacter->getInitials($condition);
  2086. $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';
  2087. $dbResult = $this->objDCustomer->query($sql);
  2088. if($dbResult === false){
  2089. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2090. }
  2091. return ResultWrapper::success($dbResult);
  2092. }
  2093. /**
  2094. * 初始化客户首字母
  2095. */
  2096. public function initialsCustomer()
  2097. {
  2098. $objChineseCharacter = new ChineseCharacter();
  2099. $dbResult = $this->objDCustomer->select();
  2100. if($dbResult === false){
  2101. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2102. }
  2103. foreach($dbResult as $value){
  2104. $condition = $objChineseCharacter->getInitials(trim($value['name']));
  2105. $result = $this->objDCustomer->update(['condition' => $condition], ['id' => $value['id']]);
  2106. if($result === false){
  2107. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2108. }
  2109. }
  2110. return ResultWrapper::success('执行成功');
  2111. }
  2112. /**
  2113. * Doc: (des="根据客户id获取客户实时的分拣区")
  2114. * User: XMing
  2115. * Date: 2020/12/25
  2116. * Time: 4:57 下午
  2117. * @param $ids
  2118. * @return ResultWrapper
  2119. */
  2120. public function getReservoirByCustomerIds($ids): ResultWrapper
  2121. {
  2122. if (empty($ids)){
  2123. return ResultWrapper::success([]);
  2124. }
  2125. $customer = $this->objDCustomer->select($ids);
  2126. if ($customer === false){
  2127. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  2128. }
  2129. $reservoirIds = [];
  2130. foreach ($customer as $value){
  2131. if (empty($value['reservoirId'])){
  2132. continue;
  2133. }
  2134. $reservoirIds[] = $value['reservoirId'];
  2135. }
  2136. $objMReservoirArea = new MReservoirArea($this->enterpriseId,$this->userCenterId);
  2137. $reservoir = [];
  2138. if(!empty($reservoirIds)){
  2139. $reservoirResult = $objMReservoirArea->getReservoirMapByIds(['id' => $reservoirIds]);
  2140. if (!$reservoirResult->isSuccess()){
  2141. return ResultWrapper::fail($reservoirResult->getData(),$reservoirResult->getErrorCode());
  2142. }
  2143. $reservoir = $reservoirResult->getData();
  2144. }
  2145. $reservoirMap = [];
  2146. foreach ($customer as $value){
  2147. $reservoirId = $value['reservoirId'];
  2148. $row = getArrayItem($reservoir,$reservoirId,[]);
  2149. $reservoirMap[$value['id']] = [
  2150. 'name' => getArrayItem($row, 'name', ''),
  2151. 'warehouseId' => getArrayItem($row, 'warehouseId', 0),
  2152. 'code' => getArrayItem($row, 'code', ''),
  2153. 'type' => getArrayItem($row, 'type', 0)
  2154. ];
  2155. }
  2156. return ResultWrapper::success($reservoirMap);
  2157. }
  2158. /**
  2159. * Doc: (des="查询客户商品购买记录")
  2160. * User: XMing
  2161. * Date: 2021/3/10
  2162. * Time: 10:59 上午
  2163. * @param array $params
  2164. * @return ResultWrapper
  2165. * @throws Exception
  2166. */
  2167. public function searchCustomerBuyLog(array $params ,$export = 0): ResultWrapper
  2168. {
  2169. $objMOrder = new MOrder($this->userCenterId,$this->enterpriseId);
  2170. if($export){
  2171. $params['limit'] = null;
  2172. $params['offset'] = null;
  2173. }
  2174. $dbResult = $objMOrder->getGoodsListsByUserCenterId($params);
  2175. if (!$dbResult->isSuccess()){
  2176. return ResultWrapper::fail($dbResult->getData(),$dbResult->getErrorCode());
  2177. }
  2178. //客户购买记录导出
  2179. if($export){
  2180. self::exportCustomerBuyLog($dbResult->getData()['data']);
  2181. exit;
  2182. }
  2183. return ResultWrapper::success($dbResult->getData());
  2184. }
  2185. /**
  2186. * Doc: (des="获取客户的余额")
  2187. * User: XMing
  2188. * Date: 2021/3/18
  2189. * Time: 10:55 上午
  2190. * @param int $customerId
  2191. * @return ResultWrapper
  2192. */
  2193. public function getCustomerBalance(int $customerId): ResultWrapper
  2194. {
  2195. $result = $this->objDCustomer->get($customerId);
  2196. if ($result === false){
  2197. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$dberror);
  2198. }
  2199. if (empty($result)){
  2200. return ResultWrapper::fail('为获取到客户的余额信息',ErrorCode::$paramError);
  2201. }
  2202. $money = getArrayItem($result,'money',0);
  2203. return ResultWrapper::success($money);
  2204. }
  2205. /**
  2206. * Doc: (des="修改客户的余额并增加流水记录")
  2207. * User: XMing
  2208. * Date: 2021/3/18
  2209. * Time: 11:41 上午
  2210. * @param int $customerId
  2211. * @param float $changeMoney
  2212. * @return ResultWrapper
  2213. */
  2214. public function decCustomerBalance(int $customerId,float $changeMoney,$tmpOuterTradeNo): ResultWrapper
  2215. {
  2216. if (empty($changeMoney)){
  2217. return ResultWrapper::fail('支付金额异常',ErrorCode::$paramError);
  2218. }
  2219. $customerResult = self::getCustomerBalance($customerId);
  2220. if (!$customerResult->isSuccess()){
  2221. return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
  2222. }
  2223. $customerMoney = $customerResult->getData();
  2224. if($customerMoney >= 0){
  2225. return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
  2226. }
  2227. if ($customerMoney <0 && (bccomp($changeMoney,abs($customerMoney),2) > 0)){
  2228. return ResultWrapper::fail('余额不足,至少需要'.$changeMoney,ErrorCode::$paramError);
  2229. }
  2230. //扣除余额,
  2231. $update = [
  2232. 'money' => bcsub($customerMoney,$changeMoney,2),
  2233. 'updateTime' => time()
  2234. ];
  2235. $updateResult = $this->objDCustomer->update($update,$customerId);
  2236. if ($updateResult === false){
  2237. return ResultWrapper::fail($this->objDCustomer->error(),ErrorCode::$paramError);
  2238. }
  2239. //TODO(增加流水)
  2240. $trans = [
  2241. 'tmpOuterTradeNo' => $tmpOuterTradeNo,
  2242. 'oldMoney' => $customerMoney,
  2243. 'payMoney' => $changeMoney,
  2244. 'createTime' => time(),
  2245. 'money' => $update['money']
  2246. ];
  2247. $update['tmpOuterTradeNo'] = $tmpOuterTradeNo;
  2248. Logger::logs(E_USER_ERROR,'订单余额支付记录'.$tmpOuterTradeNo,__CLASS__,__LINE__,$trans);
  2249. return ResultWrapper::success(true);
  2250. }
  2251. /**
  2252. * 添加余额支付密码
  2253. * User: kang
  2254. * Date: 2021/3/25
  2255. * Time: 17:00 下午
  2256. * @param $params
  2257. * @return ResultWrapper
  2258. * @throws Exception
  2259. */
  2260. public function addpayPassword($payPasswordData)
  2261. {
  2262. $ifPayPassword = $this->objDCustomer->get(['id'=>$payPasswordData['id']]);
  2263. if(!empty($ifPayPassword['payPassword'])){
  2264. return ResultWrapper::fail('该用户密码已添加', ErrorCode::$accountfail);
  2265. }
  2266. $payPasswordId= $payPasswordData['id'];
  2267. unset($payPasswordData['id']);
  2268. $dbResult = $this->objDCustomer->update($payPasswordData,$payPasswordId);
  2269. if($dbResult === false){
  2270. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2271. }
  2272. return ResultWrapper::success($dbResult);
  2273. }
  2274. /**
  2275. * 修改余额支付密码
  2276. * User: kang
  2277. * Date: 2021/3/25
  2278. * Time: 17:25 下午
  2279. * @param $params
  2280. * @return ResultWrapper
  2281. * @throws Exception
  2282. */
  2283. public function updatePayPassword($updatePayPasswordData)
  2284. {
  2285. $customerid = $updatePayPasswordData['id'];
  2286. unset($updatePayPasswordData['id']);
  2287. $dbResult = $this->objDCustomer->update($updatePayPasswordData,$customerid);
  2288. if($dbResult === false){
  2289. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2290. }else{
  2291. return ResultWrapper::success($dbResult);
  2292. }
  2293. }
  2294. /**
  2295. * 校验余额支付密码
  2296. * User: kang
  2297. * Date: 2021/3/25
  2298. * Time: 17:25 下午
  2299. * @param $params
  2300. * @return ResultWrapper
  2301. * @throws Exception
  2302. */
  2303. public function checkPayPassword($checkPayPasswordData)
  2304. {
  2305. $oldPayPassword = $this->objDCustomer->get(['id'=>$checkPayPasswordData['id']]);
  2306. if($oldPayPassword === false){
  2307. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2308. }
  2309. if(password_verify($checkPayPasswordData['payPassword'], $oldPayPassword['payPassword'] ) !== true){
  2310. return ResultWrapper::fail('密码错误', ErrorCode::$accountfail);
  2311. }
  2312. return ResultWrapper::success();
  2313. }
  2314. /**
  2315. * 客户积分流水
  2316. * @param $selectParams
  2317. * @return ResultWrapper
  2318. */
  2319. public function getAllCustomerIntegralDesc($selectParams)
  2320. {
  2321. $limit = $selectParams['limit'];
  2322. unset($selectParams['limit']);
  2323. $offset = $selectParams['offset'];
  2324. unset($selectParams['offset']);
  2325. $dbResult = $this->objDCustomer->get(['id' => $selectParams['customerId']]);
  2326. if($dbResult === false){
  2327. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2328. }
  2329. $customerData = $dbResult;
  2330. unset($dbResult);
  2331. isset($selectParams['search']) && $selectParams['search'] = ['title' => $selectParams['search']];
  2332. $selectParams = self::formatSqlWhere($selectParams);
  2333. $dbResult = $this->objDCustomerIntegralDesc->select($selectParams,'*', 'createTime desc', $limit, $offset);
  2334. if($dbResult === false){
  2335. return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
  2336. }
  2337. $data = $dbResult;
  2338. unset($dbResult);
  2339. $countResult = $this->objDCustomerIntegralDesc->count($selectParams);
  2340. if ($countResult === false) {
  2341. return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
  2342. }
  2343. $return = [
  2344. 'data' => [
  2345. 'lists' => $data,
  2346. 'customer' => $customerData,
  2347. ],
  2348. 'total' => ($countResult) ? intval($countResult) : 0,
  2349. ];
  2350. return ResultWrapper::success($return);
  2351. }
  2352. /**
  2353. * 修改积分
  2354. * @param $params
  2355. * @return ResultWrapper
  2356. */
  2357. public function updateCustomerIntegral($params)
  2358. {
  2359. if (empty($params['integral'])) {
  2360. return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
  2361. }
  2362. if ($params['integral'] < 0) {
  2363. return ResultWrapper::fail('修改积分不能为空', ErrorCode::$paramError);
  2364. }
  2365. $dbResult = $this->objDCustomer->get(['id' => $params['customerId']]);
  2366. if ($dbResult === false) {
  2367. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2368. }
  2369. $customer = $dbResult;
  2370. unset($dbResult);
  2371. if (empty($customer)) {
  2372. return ResultWrapper::fail('用户不存在', ErrorCode::$dberror);
  2373. }
  2374. if ($params['type'] == 5) {
  2375. $money = bcadd($customer['integral'], $params['integral'], 2);
  2376. } else {
  2377. $money = bcsub($customer['integral'], $params['integral'], 2);
  2378. }
  2379. if($money < 0){
  2380. return ResultWrapper::fail('修改后积分不能为负数', ErrorCode::$paramError);
  2381. }
  2382. $update = [
  2383. 'integral' => $money,
  2384. 'updateTime' => time()
  2385. ];
  2386. $dbResult = $this->objDCustomer->update($update, ['id' => $params['customerId']]);
  2387. if ($dbResult === false) {
  2388. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2389. }
  2390. if(isset($params['desc']) && !empty($params['desc'])){
  2391. //增加记录
  2392. $insertDesc = [
  2393. 'userCenterId' => $customer['userCenterId'],
  2394. 'customerId' => $customer['id'],
  2395. 'shopId' => isset($params['shopId']) ? $params['shopId'] : 0,
  2396. 'title' => $params['desc'],
  2397. 'amount' => $params['integral'],
  2398. 'changeAmount' => $money,
  2399. 'type' => $params['type'],
  2400. 'source' => 3,
  2401. 'createTime' => time(),
  2402. 'updateTime' => time()
  2403. ];
  2404. $result = $this->objDCustomerIntegralDesc->insert($insertDesc);
  2405. if ($result === false) {
  2406. return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
  2407. }
  2408. }
  2409. return ResultWrapper::success(true);
  2410. }
  2411. /**
  2412. * 根据订单增加客户积分
  2413. * @param int $shopId
  2414. * @param array $customer
  2415. * @param array $order
  2416. * @param array $orderGoods
  2417. * @return ResultWrapper
  2418. */
  2419. public function addCustomerIntegralByOrder($shopId = 0, $customer = [], $order = [], $orderGoods = [])
  2420. {
  2421. //查询规则
  2422. $objDIntegralRule = new DIntegralRule();
  2423. $objDIntegralRule->setTable('qianniao_integral_rule_'.$this->enterpriseId);
  2424. $dbResult = $objDIntegralRule->get(['shopId' => $shopId, 'enableStatus' => StatusCode::$standard, 'deleteStatus' => StatusCode::$standard], '*', 'createTime DESC');
  2425. if($dbResult === false){
  2426. return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
  2427. }
  2428. $rule = $dbResult;
  2429. unset($dbResult);
  2430. if(empty($rule)){
  2431. return ResultWrapper::success(false);
  2432. }
  2433. $ruleGoods = json_decode($rule['goods'], true);
  2434. if(empty($rule['startMoney']) || $rule['startMoney'] < 0){
  2435. $rule['startMoney'] = 0;
  2436. }
  2437. //匹配商品
  2438. $goodsIntegral = 0;
  2439. $orderAmount = 0;
  2440. foreach($orderGoods as $value){
  2441. if(isset($ruleGoods[$value['skuId']])){
  2442. //计算商品积分
  2443. if($ruleGoods[$value['skuId']]['integral'] > 0){
  2444. $goodsIntegral = bcadd($goodsIntegral, bcmul($ruleGoods[$value['skuId']]['integral'], $value['buyNum']),2);
  2445. }
  2446. }else{
  2447. if($order['totalMoney'] >= $rule['startMoney']){
  2448. $orderAmount = bcadd($orderAmount, $value['totalMoney'], 2);
  2449. }
  2450. }
  2451. }
  2452. $insertIntegralDesc = [];
  2453. if($goodsIntegral > 0){
  2454. //增加记录
  2455. $insertIntegralDesc[] = [
  2456. 'userCenterId' => $customer['userCenterId'],
  2457. 'customerId' => $customer['id'],
  2458. 'shopId' => $shopId,
  2459. 'originId' => $order['id'],
  2460. 'originNo' => $order['no'],
  2461. 'ruleId' => $rule['id'],
  2462. 'title' => '购买指定商品奖励积分',
  2463. 'amount' => $goodsIntegral,
  2464. 'changeAmount' => bcadd($customer['integral'], $goodsIntegral, 2),
  2465. 'type' => StatusCode::$standard,
  2466. 'source' => 2,
  2467. 'createTime' => time() - 1,
  2468. 'updateTime' => time() - 1,
  2469. ];
  2470. }
  2471. //计算订单积分
  2472. $orderIntegral = 0;
  2473. if($orderAmount > 0 && $rule['amount'] > 0 && $rule['integral'] > 0){
  2474. $orderIntegral = bcmul(intval($orderAmount / $rule['amount']), $rule['integral'], 2);
  2475. //增加记录
  2476. $insertIntegralDesc[] = [
  2477. 'userCenterId' => $customer['userCenterId'],
  2478. 'customerId' => $customer['id'],
  2479. 'shopId' => $shopId,
  2480. 'originId' => $order['id'],
  2481. 'originNo' => $order['no'],
  2482. 'ruleId' => $rule['id'],
  2483. 'title' => '订单满足'.bcmul(intval($orderAmount / $rule['amount']), $rule['amount'], 2).',奖励积分',
  2484. 'amount' => $orderIntegral,
  2485. 'changeAmount' => bcadd($customer['integral'], bcadd($orderIntegral, $goodsIntegral,2), 2),
  2486. 'type' => StatusCode::$standard,
  2487. 'source' => 1,
  2488. 'createTime' => time(),
  2489. 'updateTime' => time(),
  2490. ];
  2491. }
  2492. //累加积分
  2493. $addIntegral = bcadd($orderIntegral, $goodsIntegral, 2);
  2494. //增加客户积分
  2495. if($addIntegral > 0){
  2496. $updateCustomer = [
  2497. 'integral' => bcadd($customer['integral'], $addIntegral, 2),
  2498. 'updateTime' => time(),
  2499. ];
  2500. $dbResult = $this->objDCustomer->update($updateCustomer, ['id' => $customer['id']]);
  2501. if($dbResult === false){
  2502. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2503. }
  2504. }
  2505. //累加规则赠送积分
  2506. $updateRule = [
  2507. 'integralTotal' => bcadd($rule['integralTotal'], $addIntegral, 2),
  2508. 'updateTime' => time(),
  2509. ];
  2510. $dbResult = $objDIntegralRule->update($updateRule, ['id' => $rule['id']]);
  2511. if($dbResult === false){
  2512. return ResultWrapper::fail($objDIntegralRule->error(), ErrorCode::$dberror);
  2513. }
  2514. //保存记录
  2515. if(!empty($insertIntegralDesc)){
  2516. $dbResult = $this->objDCustomerIntegralDesc->insert($insertIntegralDesc, true);
  2517. if($dbResult === false){
  2518. return ResultWrapper::fail($this->objDCustomerIntegralDesc->error(), ErrorCode::$dberror);
  2519. }
  2520. }
  2521. return ResultWrapper::success('执行成功');
  2522. }
  2523. /**
  2524. * 新注册未下单统计
  2525. */
  2526. public function noOrderCustomer($params)
  2527. {
  2528. // 间隔天数转时间戳
  2529. $endTime = time() - (86400 * $params['intervalDay']);
  2530. $where = '';
  2531. if( isset($params['customerName']) && !empty($params['customerName']) ){
  2532. $where .= ' and c.name like "%'.$params['customerName'].'%" ';
  2533. }
  2534. if( isset($params['salesManId']) && !empty($params['salesManId']) ){
  2535. $where .= ' and c.salesManId = '.$params['salesManId'];
  2536. }
  2537. if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
  2538. $where .= ' and c.provinceCode = '.$params['provinceCode'];
  2539. }
  2540. if( isset($params['cityCode']) && !empty($params['cityCode']) ){
  2541. $where .= ' and c.cityCode = '.$params['cityCode'];
  2542. }
  2543. if( isset($params['districtCode']) && !empty($params['districtCode']) ){
  2544. $where .= ' and c.districtCode = '.$params['districtCode'];
  2545. }
  2546. $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';
  2547. $listSql = $sql.' ORDER BY tmp.createTime desc limit '.$params['offset'].','.$params['limit'];
  2548. $fields = 'select tmp.name,tmp.id,tmp.createTime,tmp.provinceCode,tmp.cityCode,tmp.districtCode,tmp.type,tmp.salesManId,tmp.userCenterId,tmp.shopId,tmp.departmentId';
  2549. $dbResult = $this->objDCustomerRechargeRecord->query($fields.$listSql);
  2550. if($dbResult === false){
  2551. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  2552. }
  2553. //拿到范围内的客户
  2554. $customerIds = [];
  2555. foreach ($dbResult as $value){
  2556. $customerIds[] = $value['id'];
  2557. }
  2558. $customerIds = implode(',',$customerIds);
  2559. $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
  2560. //根据客户id查询客户本年拜访次数
  2561. $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
  2562. if(!$dbYearNum->isSuccess()){
  2563. return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
  2564. }
  2565. $yearNumDbResult = $dbYearNum->getData();
  2566. $yearNum = [];
  2567. foreach ($yearNumDbResult as $v){
  2568. $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
  2569. }
  2570. //根据客户id查询客户距离上次拜访相差多少天
  2571. $dbDayNum = $objMCustomerCommunication->getCustomerlastTimeDay($customerIds);
  2572. if(!$dbDayNum->isSuccess()){
  2573. return ResultWrapper::fail($dbDayNum->getData(),$dbDayNum->getErrorCode());
  2574. }
  2575. $dayNumDbResult = $dbDayNum->getData();
  2576. $dayNum = [];
  2577. foreach ($dayNumDbResult as $v){
  2578. $dayNum[$v['customerId']]= $v['time'];//所查出客户距离上次拜访相差多少天
  2579. }
  2580. //根据查出天数范围内的客户查出所对应的日期并归组
  2581. $result = $objMCustomerCommunication->getCustomerDate($customerIds);
  2582. if(!$result->isSuccess()){
  2583. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  2584. }
  2585. $dbResultDate = $result->getData();
  2586. //按照查出的年 本月 上月进行分组
  2587. $data = [];
  2588. $year = strtotime(date('Y-1-1'));
  2589. $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
  2590. $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
  2591. foreach ( $dbResultDate as $value ){
  2592. //年
  2593. $time = strtotime($value['time']);
  2594. if( $time>$year ){
  2595. if( isset($data[$value['customerId']]['year']) ){
  2596. $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
  2597. $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
  2598. } else {
  2599. $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
  2600. $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
  2601. }
  2602. }
  2603. //月
  2604. if( $time>$thisMonth ){
  2605. if( isset($data[$value['customerId']]['thisMonth']) ){
  2606. $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
  2607. $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
  2608. } else {
  2609. $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
  2610. $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
  2611. }
  2612. }
  2613. //上月
  2614. if( $time>$lastMonth && $time < $thisMonth ){
  2615. if( isset($data[$value['customerId']]['lastMonth']) ){
  2616. $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
  2617. $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
  2618. } else {
  2619. $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
  2620. $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
  2621. }
  2622. }
  2623. }
  2624. foreach($dbResult as &$value) {
  2625. //年
  2626. if ( isset($data[$value['id']]['year']) ) {
  2627. $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
  2628. $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
  2629. } else {
  2630. $value['year']['orderNum'] = 0;
  2631. $value['year']['orderMoney'] = 0;
  2632. }
  2633. //月
  2634. if ( isset($data[$value['id']]['thisMonth']) ) {
  2635. $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
  2636. $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
  2637. } else {
  2638. $value['thisMonth']['orderNum'] = 0;
  2639. $value['thisMonth']['orderMoney'] = 0;
  2640. }
  2641. //上月
  2642. if ( isset($data[$value['id']]['lastMonth']) ) {
  2643. $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
  2644. $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
  2645. } else {
  2646. $value['lastMonth']['orderNum'] = 0;
  2647. $value['lastMonth']['orderMoney'] = 0;
  2648. }
  2649. //客户本年拜访次数
  2650. if(isset($yearNum[$value['id']])){
  2651. $value['yearNum'] = isset( $yearNum[$value['id']]) ? $yearNum[$value['id']] : 0;
  2652. } else {
  2653. $value['yearNum'] = 0;
  2654. }
  2655. //客户距离上次多少天
  2656. if(isset($dayNum[$value['id']])){
  2657. $value['dayNum'] = isset( $dayNum[$value['id']]) ? $dayNum[$value['id']] : 0;
  2658. } else {
  2659. $value['dayNum'] = 0;
  2660. }
  2661. }
  2662. if(empty($dbResult)){
  2663. return ResultWrapper::success([
  2664. 'data' => [],
  2665. 'total' => 0,
  2666. ]);
  2667. }
  2668. $fields = 'select count(*) as total ';
  2669. $count = $this->objDCustomerRechargeRecord->query($fields.$sql);
  2670. $return = [
  2671. 'data' => self::format($dbResult),
  2672. 'total' => $count ? $count[0]['total'] : 0
  2673. ];
  2674. return ResultWrapper::success($return);
  2675. }
  2676. /**
  2677. * 距离最近一次未下单统计
  2678. */
  2679. public function intervalNoOrderCustomer($params)
  2680. {
  2681. $where = '';
  2682. if( isset($params['customerName']) && !empty($params['customerName']) ){
  2683. $where .= ' and c.name like "%'.$params['customerName'].'%" ';
  2684. }
  2685. if( isset($params['salesManId']) && !empty($params['salesManId']) ){
  2686. $where .= ' and c.salesManId = '.$params['salesManId'];
  2687. }
  2688. if( isset($params['provinceCode']) && !empty($params['provinceCode']) ){
  2689. $where .= ' and c.provinceCode = '.$params['provinceCode'];
  2690. }
  2691. if( isset($params['cityCode']) && !empty($params['cityCode']) ){
  2692. $where .= ' and c.cityCode = '.$params['cityCode'];
  2693. }
  2694. if( isset($params['districtCode']) && !empty($params['districtCode']) ){
  2695. $where .= ' and c.districtCode = '.$params['districtCode'];
  2696. }
  2697. $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 (
  2698. 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'];
  2699. $dbResult = $this->objDCustomer->query($sql);
  2700. if($dbResult === false){
  2701. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2702. }
  2703. //拿到范围内的客户
  2704. $customerIds = [];
  2705. foreach ($dbResult as $value){
  2706. $customerIds[] = $value['id'];
  2707. }
  2708. $customerIds = implode(',',$customerIds);
  2709. $objMCustomerCommunication = new MCustomerCommunication($this->enterpriseId);
  2710. //根据客户id查询客户本年拜访次数
  2711. $dbYearNum = $objMCustomerCommunication->getCustomerYearVisitNumber($customerIds);
  2712. if(!$dbYearNum->isSuccess()){
  2713. return ResultWrapper::fail($dbYearNum->getData(),$dbYearNum->getErrorCode());
  2714. }
  2715. $yearNumDbResult = $dbYearNum->getData();
  2716. $yearNum = [];
  2717. foreach ($yearNumDbResult as $v){
  2718. $yearNum[$v['customerId']]= $v['yearNum'];//所查出客户本年拜访次数
  2719. }
  2720. //根据查出天数范围内的客户查出所对应的日期并归组
  2721. $result = $objMCustomerCommunication->getCustomerDate($customerIds);
  2722. if(!$result->isSuccess()){
  2723. return ResultWrapper::fail($result->getData(),$result->getErrorCode());
  2724. }
  2725. $dbResultDate = $result->getData();
  2726. //按照查出的年 本月 上月进行分组
  2727. $data = [];
  2728. $year = strtotime(date('Y-1-1'));
  2729. $thisMonth = mktime(0,0,0,date('m'),1,date('Y'));
  2730. $lastMonth = strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')));
  2731. foreach ( $dbResultDate as $value ){
  2732. //年
  2733. $time = strtotime($value['time']);
  2734. if( $time>$year ){
  2735. if( isset($data[$value['customerId']]['year']) ){
  2736. $data[$value['customerId']]['year']['orderNum'] += $value['orderNum'];
  2737. $data[$value['customerId']]['year']['orderMoney'] += $value['orderMoney'];
  2738. } else {
  2739. $data[$value['customerId']]['year']['orderNum'] = $value['orderNum'];
  2740. $data[$value['customerId']]['year']['orderMoney'] = $value['orderMoney'];
  2741. }
  2742. }
  2743. //月
  2744. if( $time>$thisMonth ){
  2745. if( isset($data[$value['customerId']]['thisMonth']) ){
  2746. $data[$value['customerId']]['thisMonth']['orderNum'] += $value['orderNum'];
  2747. $data[$value['customerId']]['thisMonth']['orderMoney'] += $value['orderMoney'];
  2748. } else {
  2749. $data[$value['customerId']]['thisMonth']['orderNum'] = $value['orderNum'];
  2750. $data[$value['customerId']]['thisMonth']['orderMoney'] = $value['orderMoney'];
  2751. }
  2752. }
  2753. //上月
  2754. if( $time>$lastMonth && $time < $thisMonth ){
  2755. if( isset($data[$value['customerId']]['lastMonth']) ){
  2756. $data[$value['customerId']]['lastMonth']['orderNum'] += $value['orderNum'];
  2757. $data[$value['customerId']]['lastMonth']['orderMoney'] += $value['orderMoney'];
  2758. } else {
  2759. $data[$value['customerId']]['lastMonth']['orderNum'] = $value['orderNum'];
  2760. $data[$value['customerId']]['lastMonth']['orderMoney'] = $value['orderMoney'];
  2761. }
  2762. }
  2763. }
  2764. foreach($dbResult as &$value) {
  2765. //年
  2766. if ( isset($data[$value['id']]['year']) ) {
  2767. $value['year']['orderNum'] = $data[$value['id']]['year']['orderNum'];
  2768. $value['year']['orderMoney'] = $data[$value['id']]['year']['orderMoney'];
  2769. } else {
  2770. $value['year']['orderNum'] = 0;
  2771. $value['year']['orderMoney'] = 0;
  2772. }
  2773. //月
  2774. if ( isset($data[$value['id']]['thisMonth']) ) {
  2775. $value['thisMonth']['orderNum'] = $data[$value['id']]['thisMonth']['orderNum'];
  2776. $value['thisMonth']['orderMoney'] = $data[$value['id']]['thisMonth']['orderMoney'];
  2777. } else {
  2778. $value['thisMonth']['orderNum'] = 0;
  2779. $value['thisMonth']['orderMoney'] = 0;
  2780. }
  2781. //上月
  2782. if ( isset($data[$value['id']]['lastMonth']) ) {
  2783. $value['lastMonth']['orderNum'] = $data[$value['id']]['lastMonth']['orderNum'];
  2784. $value['lastMonth']['orderMoney'] = $data[$value['id']]['lastMonth']['orderMoney'];
  2785. } else {
  2786. $value['lastMonth']['orderNum'] = 0;
  2787. $value['lastMonth']['orderMoney'] = 0;
  2788. }
  2789. //客户本年拜访次数
  2790. if(isset($yearNum[$value['id']])){
  2791. $value['yearNum'] = isset( $yearNum[$value['id']]) ? $yearNum[$value['id']] : 0;
  2792. } else {
  2793. $value['yearNum'] = 0;
  2794. }
  2795. }
  2796. if(empty($dbResult)){
  2797. return ResultWrapper::success([
  2798. 'data' => [],
  2799. 'total' => 0,
  2800. ]);
  2801. }
  2802. $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 (
  2803. 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";
  2804. $count = $this->objDCustomer->query($sql);
  2805. if($count === false){
  2806. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2807. }
  2808. $return = [
  2809. 'data' => self::format($dbResult),
  2810. 'total' => $count ? $count[0]['total'] : 0
  2811. ];
  2812. return ResultWrapper::success($return);
  2813. }
  2814. /**
  2815. * 拉新统计
  2816. */
  2817. public function recommenderStatic($params)
  2818. {
  2819. $where = '';
  2820. // 时间筛选
  2821. if (isset($params['startTime']) && !empty($params['startTime'])){
  2822. $where .= ' AND c.createTime BETWEEN '.$params['startTime'].' AND '.$params['endTime'];
  2823. }
  2824. if( isset($params['customerId']) && !empty($params['customerId']) ){
  2825. $where .= ' and c.id = '.$params['customerId'];
  2826. }
  2827. if( isset($params['staffId']) && !empty($params['staffId']) ){
  2828. $where .= ' and c.salesManId = '.$params['staffId'];
  2829. }
  2830. $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';
  2831. $limit = ' limit '.$params['offset'].','.$params['limit'];
  2832. $listSql = $sql.' ORDER BY recommenderTotal desc';
  2833. $fields = 'SELECT c.recommenderId,c.recommenderType,count(*) as recommenderTotal,b.*';
  2834. $this->objDCustomerRechargeRecord->setTable('qianniao_customer_'.$this->enterpriseId);
  2835. $this->objDCustomerRechargeRecord->setTable('qianniao_order_goods_'.$this->enterpriseId);
  2836. $this->objDCustomerRechargeRecord->setTable('qianniao_order_'.$this->enterpriseId);
  2837. $returnData = $this->objDCustomerRechargeRecord->query($fields.$listSql.$limit);
  2838. if($returnData === false){
  2839. return ResultWrapper::fail($this->objDCustomerRechargeRecord->error(), ErrorCode::$dberror);
  2840. }
  2841. if(empty($returnData)){
  2842. return ResultWrapper::success([
  2843. 'data' => [],
  2844. 'total' => 0,
  2845. ]);
  2846. }
  2847. $sql = 'select count(*) as total from ('.$fields.$sql.') t';
  2848. $count = $this->objDCustomerRechargeRecord->query($sql);
  2849. $customerIds = [];
  2850. $staffIds = [];
  2851. foreach ($returnData as $key => $value){
  2852. if( empty($value['recommenderId']) ) continue;
  2853. if($value['recommenderType'] == StatusCode::$roleType['customer']){
  2854. $customerIds[] = $value['recommenderId'];
  2855. }else{
  2856. $staffIds[] = $value['recommenderId'];
  2857. }
  2858. }
  2859. // 根据客户ids批量获取客户名称
  2860. $customerIdBindName = [];
  2861. if( !empty($customerIds) ){
  2862. $dbResult = $this->objDCustomer->select($customerIds, 'id,name');
  2863. if($dbResult === false){
  2864. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2865. }
  2866. foreach ($dbResult as $key => $value){
  2867. $customerIdBindName[$value['id']] = $value['name'];
  2868. }
  2869. }
  2870. // 根据员工ids批量获取员工名称
  2871. $staffIdBindName = [];
  2872. if( !empty($staffIds) ){
  2873. $objDStaff = new DStaff();
  2874. $objDStaff->setTable('qianniao_staff_'.$this->enterpriseId);
  2875. $dbResult = $objDStaff->select($staffIds, 'id,staffName');
  2876. if($dbResult === false){
  2877. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2878. }
  2879. foreach ($dbResult as $key => $value){
  2880. $staffIdBindName[$value['id']] = $value['staffName'];
  2881. }
  2882. }
  2883. // 映射上名称
  2884. foreach ($returnData as $key => $value){
  2885. if($value['recommenderType'] == StatusCode::$roleType['customer']){
  2886. $returnData[$key]['recommenderName'] = isset($customerIdBindName[$value['recommenderId']]) ? $customerIdBindName[$value['recommenderId']] : '';
  2887. }else{
  2888. $returnData[$key]['recommenderName'] = isset($staffIdBindName[$value['recommenderId']]) ? $staffIdBindName[$value['recommenderId']] : '';
  2889. }
  2890. }
  2891. $return = [
  2892. 'data' => $returnData,
  2893. 'total' => $count ? $count[0]['total'] : 0
  2894. ];
  2895. return ResultWrapper::success($return);
  2896. }
  2897. /**
  2898. * 客户购买记录导出方法
  2899. * @param $result
  2900. * @return void
  2901. * @throws Exception
  2902. */
  2903. public function exportCustomerBuyLog($result)
  2904. {
  2905. //导出到本地
  2906. header("Content-type:application/vnd.ms-excel");
  2907. header("Content-Disposition:filename=客户购买记录表.csv");
  2908. header('Cache-Control: max-age=0');
  2909. $fp = fopen('php://output', 'a');
  2910. $head = ['客户','商品','单位','属性','单价','购买数量','其他单位','商品总价','发货数量','商品条码']; //定义标题
  2911. foreach ($head as $i => $v) {
  2912. $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8'); //将中文标题转换编码,否则乱码
  2913. }
  2914. fputcsv($fp, $head);
  2915. $limit = 10000;
  2916. $num = 0; //计数器
  2917. foreach ($result as $v) { //循环数据
  2918. $specGroupA = '';
  2919. if(!empty($v['specGroup'])){
  2920. foreach ($v['specGroup'] as $kk =>$vv){
  2921. $specGroupA .=$vv['specName'].','.$vv['specValueName'].',';
  2922. }
  2923. $specGroup = rtrim($specGroupA, ",") ;//剔除追后的字符串
  2924. }
  2925. $num++;
  2926. if ($num == $limit) {
  2927. ob_flush(); //释放内存
  2928. flush();
  2929. }
  2930. $rows['customerName'] = isset($v['customerName']) ? $v['customerName'] : '';//客户
  2931. $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : '';//商品
  2932. $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : '';//单位
  2933. $rows['specGroup'] = $specGroup;//属性
  2934. $rows['price'] = isset($v['price']) ? $v['price'] : '';//单价
  2935. $rows['buyNum'] = isset($v['buyNum']) ? $v['buyNum'] : '';//购买数量
  2936. $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : '';//其他单位
  2937. $rows['totalMoney'] = isset($v['totalMoney']) ? $v['totalMoney'] : '';//商品总价
  2938. $rows['outNum'] = isset($v['outNum']) ? $v['outNum'] : '';//发货数量
  2939. $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : '';//商品条码
  2940. foreach ($rows as $kk => $vv) {
  2941. $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8'); //转译编码
  2942. }
  2943. fputcsv($fp, $rs);
  2944. $rows = [];
  2945. }
  2946. }
  2947. /**
  2948. * 客户分布
  2949. * @return ResultWrapper
  2950. */
  2951. public function getCustomerDistributed()
  2952. {
  2953. $sql = 'select provinceCode,count(provinceCode) as total from qianniao_customer_'.$this->enterpriseId.' where deleteStatus = '.StatusCode::$standard.' group by provinceCode';
  2954. $dbResult = $this->objDUserCenter->query($sql);
  2955. if($dbResult === false){
  2956. return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
  2957. }
  2958. $objMSysAreaChina = new MSysAreaChina();
  2959. $areaData = [];
  2960. $noTotal = 0;
  2961. foreach($dbResult as $value){
  2962. if(empty($value['provinceCode'])){
  2963. $noTotal += $value['total'];
  2964. }else{
  2965. $areaName = $objMSysAreaChina->getNameByCode([
  2966. $value['provinceCode'],
  2967. ]);
  2968. if(empty($areaName[$value['provinceCode']])){
  2969. $noTotal += $value['total'];
  2970. }else{
  2971. $areaData[] = [
  2972. 'name' => str_replace('省', '',$areaName[$value['provinceCode']]),
  2973. 'value' => $value['total']
  2974. ];
  2975. }
  2976. }
  2977. }
  2978. if(!empty($noTotal)){
  2979. $areaData[] = [
  2980. 'name' => '未知',
  2981. 'value' => $noTotal
  2982. ];
  2983. }
  2984. return ResultWrapper::success($areaData);
  2985. }
  2986. /**
  2987. * 批量设置客户类型
  2988. */
  2989. public function setCustomerType($params)
  2990. {
  2991. if(empty($params['customerIds'])){
  2992. return ResultWrapper::fail('客户数据不能为空',ErrorCode::$notAllowAccess);
  2993. }
  2994. //更新数据
  2995. $dbResult = $this->objDCustomer->update(['type'=>$params['type']],['id'=>$params['customerIds']]);
  2996. if($dbResult === false){
  2997. return ResultWrapper::fail($this->objDCustomer->error(), ErrorCode::$dberror);
  2998. }
  2999. $objCustomerCache = new CustomerCache();
  3000. //删除缓存
  3001. foreach ($params['customerIds'] as $value){
  3002. $objCustomerCache->delCustomerData($this->enterpriseId,$value);
  3003. }
  3004. return ResultWrapper::success($dbResult);
  3005. }
  3006. public function get($where)
  3007. {
  3008. $data = $this->objDCustomer->get($where);
  3009. return $data;
  3010. }
  3011. public function select($where, $limit, $offset)
  3012. {
  3013. $data = $this->objDCustomer->select($where, '*', 'id DESC', $limit, $offset);
  3014. return $data;
  3015. }
  3016. public function count($where)
  3017. {
  3018. $count = $this->objDCustomer->count($where);
  3019. return $count;
  3020. }
  3021. }