Community.php 375 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184
  1. <?php
  2. namespace app\empcrm\controller;
  3. use app\BaseController;
  4. use app\model\CommunityBusiness;
  5. use app\model\FishData;
  6. use app\model\User;
  7. use app\model\Admin;
  8. use think\facade\View;
  9. use think\facade\Session;
  10. use think\facade\Log;
  11. use app\model\Employee;
  12. use app\model\Company;
  13. use app\model\CustomerVisitLog;
  14. use app\model\Customer;
  15. use app\logics\OrgLogic;
  16. use app\model\CustomerSource;
  17. use app\model\Org;
  18. use app\model\CustomerPortraitField;
  19. use app\model\CustomerPortraitFieldSelect;
  20. use app\model\Setting;
  21. use app\logics\CustomerLogic;
  22. use app\model\Decostyle;
  23. use app\model\CustomerPackage;
  24. use app\model\CustomerRecycle;
  25. use app\model\CustomersSubscribe;
  26. use think\facade\Db;
  27. use app\model\Activity;
  28. use app\model\WeworksingleCompanySetting;
  29. use app\model\WeworksingleCustomer;
  30. use think\facade\Console;
  31. use app\model\PreformanceTasksOrg;
  32. use app\event\Msg;
  33. use app\model\CreditsSetting;
  34. use app\model\AgentIntegral;
  35. use app\model\AgentUser;
  36. use app\model\AgentCustomerLog;
  37. use app\model\CustomerImport;
  38. use app\model\EmployeeMsg;
  39. use app\model\Miniprogram;
  40. use app\model\PreformanceTasks as PreformanceTasksModel;
  41. use app\model\CustomerSharing;
  42. use app\model\OutCallLog;
  43. use app\model\OutCallMbLog;
  44. use app\model\ShareLog;
  45. use app\model\StatisticsSetting;
  46. use app\model\TrainCourseView;
  47. use app\model\TrainDoneLog;
  48. use app\model\OutCallSetting;
  49. use call\Yhuatong;
  50. use app\model\CustomerInvalidLog;
  51. use app\model\CustomerPortrait;
  52. use app\model\WechatActivityIntegral;
  53. use toolkits\Aec;
  54. use PhpOffice\PhpSpreadsheet\IOFactory;
  55. use wx\offiaccount\client\TmpMsg;
  56. use clue\Fish;
  57. use app\model\Community as CommunityModel;
  58. use app\model\Building;
  59. class Community extends BaseController
  60. {
  61. /**
  62. * 首页
  63. */
  64. public function index()
  65. {
  66. $request = request();
  67. $root_id = $request->empcrm->root_id;
  68. $today = date('Y-m-d H:i:s',time());
  69. $firstday = $today;
  70. $lastday = date('Y-m-d 00:00:00', strtotime("$firstday -2 day"));
  71. $org_employee = Employee::where([['root_id','=',$root_id],['org_id','=',$request->empcrm->org_id],['community_disable','=',0]])->column('id');
  72. $where[] = ['customer_employee_id','in',$org_employee];
  73. $where[] = ['addtime', 'between', [$lastday,$firstday]];
  74. $where[] = ['state', 'in', array_merge(CustomerVisitLog::changeState('已交定','chaos'),CustomerVisitLog::changeState('已签单','chaos'))];
  75. $list = CustomerVisitLog::with(['employee'=>function($query){
  76. $query->field('id,name');
  77. }])->where($where)->order('addtime desc')->select()->toArray();
  78. foreach($list as $key=>$val){
  79. $list[$key]['package_name'] = !empty($val['package_id']) ? CustomerPackage::where('id',$val['package_id'])->value('name') :'';
  80. $cusdata = Customer::with(['designer'])->where('id',$val['customer_id'])->field('name,community_name,deposit_money,signed_money,addtime,designer_id')->find();
  81. $cusdata['deposit_moneys'] = number_format($cusdata->getData('deposit_money'), 2, '.', ',');
  82. $cusdata['signed_moneys'] = number_format($cusdata->getData('signed_money'), 2, '.', ',');
  83. $list[$key]['cusdata'] = $cusdata;
  84. }
  85. $company_name = Company::where('root_id',$root_id)->value('company_name');
  86. View::assign('company_name',$company_name);
  87. View::assign('list',$list);
  88. return View::fetch();
  89. }
  90. /**
  91. * 登录记录
  92. */
  93. public function login_record(){
  94. $subOrg = orgSubIds(request()->empcrm->org_id);
  95. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职'], ['uid', '>', 0]])->column('id,name,community_login_time');
  96. $today = date('Y-m-d');
  97. foreach ($emp_list as $k => $v) {
  98. $days = 0;
  99. if ($v['community_login_time']) {
  100. $login = date('Y-m-d', strtotime($v['community_login_time']));
  101. if ($login == $today) {
  102. $days = '今';
  103. } else {
  104. $str_days = strtotime($today) - strtotime($login);
  105. $days = $str_days / 86400;
  106. }
  107. } else {
  108. $days = '-';
  109. }
  110. $emp_list[$k]['days'] = $days;
  111. }
  112. View::assign('emp_list', $emp_list);
  113. return View::fetch();
  114. }
  115. /**
  116. * 运营报表
  117. */
  118. public function operate_report(){
  119. $root_id = request()->empcrm->root_id;
  120. if (!request()->isAjax()) {
  121. $list = CommunityModel::where('root_id', '=', $root_id)->column('id,name');
  122. View::assign('community', $list);
  123. return View::fetch();
  124. } else {
  125. $community_id = input('community_id', '', 'intval');
  126. $page = input('page', 1, 'intval');
  127. $limit = input('limit', 10, 'intval');
  128. $date = input('date', '', 'trim');
  129. if ($date) {
  130. $dates = explode(' - ', $date);
  131. $start_date = date('Y-m-d 00:00:00', strtotime($dates[1]));
  132. $end_date = date('Y-m-d 23:59:59', strtotime($dates[0]));
  133. } else {
  134. // 默认近一个月
  135. $start_date = date('Y-m-d 00:00:00');
  136. $end_date = date('Y-m-d 23:59:59', time()- 30*86400);
  137. }
  138. $community = CommunityModel::where([['root_id', '=', $root_id], ['id', '=', $community_id]])->findOrEmpty();
  139. if ($community->isEmpty()) {
  140. return json(['code'=> 0, 'data'=> [], 'msg'=> 'success']);
  141. }
  142. $days = [];
  143. $days_start = strtotime($start_date);
  144. $days_end = strtotime(date('Y-m-d', strtotime($end_date)));
  145. $i = 0;
  146. while (($days_start - $i * 86400) > $days_end){
  147. $days[] = date('Y-m-d', $days_start - $i * 86400);
  148. $i++;
  149. }
  150. $count = count($days);
  151. $new_days = $page_days = array_slice($days, ($page - 1) * $limit, $limit);
  152. $page_start_date = array_pop($new_days) . '00:00:00';
  153. $page_end_date = array_shift($new_days) . '23:59:59';
  154. $subOrg = orgSubIds(request()->empcrm->org_id);
  155. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职']])->column('id');
  156. $where[] = ['community_name', '=', $community['name']];
  157. $where[] = ['employee_id', 'in', $emp_list];
  158. $where[] = ['add_wechat_time|into_owner_group|reputation_gather|last_contact_date', '>=', $page_start_date];
  159. $where[] = ['add_wechat_time|into_owner_group|reputation_gather|last_contact_date', '<=', $page_end_date];
  160. $list = Customer::where($where)->field('id,add_wechat_time,into_owner_group,reputation_gather,last_contact_date')->select()->toArray();
  161. $add_wechat_time = []; // 加微的
  162. $into_owner_group = []; //加群的
  163. $reputation_gather = []; //口碑采集时间
  164. $last_contact_date = []; // 跟进的
  165. $str_start_time = strtotime($page_start_date);
  166. $str_end_time = strtotime($page_end_date);
  167. foreach ($list as $k => $v) {
  168. // 加微处理
  169. $v_time = !empty($v['add_wechat_time']) ? strtotime($v['add_wechat_time']) : 0;
  170. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  171. $add_wechat_time[date('Y-m-d', $v_time)][] = $v['id'];
  172. }
  173. // 加群处理
  174. $v_time = !empty($v['into_owner_group']) ? strtotime($v['into_owner_group']) : 0;
  175. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  176. $into_owner_group[date('Y-m-d', $v_time)][] = $v['id'];
  177. }
  178. // 口碑采集处理
  179. $v_time = !empty($v['reputation_gather']) ? strtotime($v['reputation_gather']) : 0;
  180. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  181. $reputation_gather[date('Y-m-d', $v_time)][] = $v['id'];
  182. }
  183. // 跟进的处理
  184. $v_time = !empty($v['last_contact_date']) ? strtotime($v['last_contact_date']) : 0;
  185. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  186. $last_contact_date[date('Y-m-d', $v_time)][] = $v['id'];
  187. }
  188. }
  189. // 运营纪录查询
  190. $b_where[] = ['root_id', '=', $root_id];
  191. $b_where[] = ['community_id', '=', $community_id];
  192. $b_where[] = ['record_date', '>=', $str_start_time];
  193. $b_where[] = ['record_date', '<=', $str_end_time];
  194. $b_list = CommunityBusiness::where($b_where)->select()->toArray();
  195. $b_employee_ids = array_column($b_list, 'employee_id');
  196. $b_employee_list = Employee::where('id', 'in', $b_employee_ids)->column('name', 'id');
  197. $business_list = [];
  198. foreach ($b_list as $k => $v) {
  199. $v['employee_name'] = $b_employee_list[$v['employee_id']] ?? '';
  200. $business_list[$v['record_date']] = $v;
  201. }
  202. $data = [];
  203. $emp_data = [
  204. 'chat_group'=> 0,
  205. 'work_log'=> 0,
  206. 'group_script'=> 0,
  207. 'customer_worship'=> 0,
  208. 'building_output'=> 0,
  209. 'talk_drill'=> 0,
  210. 'material_production'=> 0,
  211. 'wei_opinions'=> 0,
  212. 'community_broadcast'=> 0,
  213. 'housetype_broadcast'=> 0,
  214. 'house_inspection_broadcast'=> 0,
  215. 'start_work_broadcast'=> 0,
  216. 'sample_room_broadcast'=> 0,
  217. 'anchoring_traffic'=> 0,
  218. 'sample_room_collect'=> 0,
  219. 'owner_buy'=> 0,
  220. 'owner_meeting'=> 0,
  221. 'construction_direct'=> 0,
  222. 'house_inspection'=> 0,
  223. 'home_dinner'=> 0,
  224. 'customer_thanks'=> 0,
  225. 'housetype_share'=> 0,
  226. 'decoration_saves_money'=> 0,
  227. 'decoration_closed_pit'=> 0,
  228. 'top_ten_spatial_planning'=> 0,
  229. 'decoration_acceptance_standards'=> 0,
  230. 'weekly_meeting'=> 0,
  231. 'month_meeting'=> 0,
  232. 'single_meeting'=> 0,
  233. 'train_meeting'=> 0,
  234. ];
  235. foreach ($page_days as $k => $v) {
  236. $one['date'] = $v;
  237. $one['jiav'] = isset($add_wechat_time[$v]) ? count($add_wechat_time[$v]) : 0;
  238. $one['into_owner_group'] = isset($into_owner_group[$v]) ? count($into_owner_group[$v]) : 0;
  239. $one['reputation_gather'] = isset($reputation_gather[$v]) ? count($reputation_gather[$v]) : 0;
  240. $one['last_contact_date'] = isset($last_contact_date[$v]) ? count($last_contact_date[$v]) : 0;
  241. if (isset($business_list[$v])) {
  242. $one = array_merge($one, $business_list[$v]);
  243. } else {
  244. $one = array_merge($one, $emp_data);
  245. }
  246. $data[] = $one;
  247. }
  248. return json(['code'=> 0, 'data'=> $data, 'msg'=> 'success', 'count'=> $count]);
  249. }
  250. }
  251. /**
  252. * 运营纪录列表
  253. */
  254. public function operate_list() {
  255. $root_id = request()->empcrm->root_id;
  256. if (!request()->isAjax()) {
  257. $list = CommunityModel::where('root_id', '=', $root_id)->column('id,name');
  258. View::assign('community', $list);
  259. return View::fetch();
  260. } else {
  261. $community_id = input('community_id', '', 'intval');
  262. $date = input('date', '', 'trim');
  263. $page = input('page', 1, 'intval');
  264. $limit = input('limit', 10, 'intval');
  265. if ($community_id) {
  266. $where[] = ['community_id', '=', $community_id];
  267. }
  268. if ($date) {
  269. $w_date = strtotime(date('Y-m-d', strtotime($date)));
  270. $where[] = ['record_date', '=', $w_date];
  271. }
  272. $where[] = ['root_id', '=', $root_id];
  273. $list = CommunityBusiness::with('communityName')->where($where)->page($page, $limit)->select()->toArray();
  274. $count = CommunityBusiness::where($where)->count();
  275. return json(['code'=> 0, 'data'=> $list, 'msg'=> 'success', 'count'=> $count]);
  276. }
  277. }
  278. /**
  279. * 添加运营纪录
  280. */
  281. public function operate_add() {
  282. $root_id = request()->empcrm->root_id;
  283. if (!request()->isAjax()) {
  284. $list = CommunityModel::where('root_id', '=', $root_id)->column('id,name');
  285. View::assign('community', $list);
  286. return View::fetch();
  287. } else {
  288. $param = $this->request->only(['community_id', 'record_date', 'chat_group', 'work_log', 'group_script', 'customer_worship', 'building_output', 'talk_drill', 'material_production', 'wei_opinions', 'community_broadcast', 'housetype_broadcast', 'house_inspection_broadcast', 'start_work_broadcast', 'sample_room_broadcast', 'anchoring_traffic', 'sample_room_collect', 'owner_buy', 'owner_meeting', 'construction_direct', 'house_inspection', 'home_dinner', 'customer_thanks', 'housetype_share', 'decoration_saves_money', 'decoration_closed_pit', 'top_ten_spatial_planning', 'decoration_acceptance_standards', 'weekly_meeting', 'month_meeting', 'single_meeting', 'train_meeting']);
  289. $param['employee_id'] = $this->request->empcrm->id;
  290. $param['root_id'] = $root_id;
  291. // 判断当天的记录是否存在
  292. $f_where[] = ['root_id', '=', $root_id];
  293. $f_where[] = ['record_date', '=', strtotime($param['record_date'])];
  294. $f_where[] = ['community_id', '=', $param['community_id']];
  295. $find = CommunityBusiness::where($f_where)->findOrEmpty();
  296. if (!$find->isEmpty()) {
  297. return json(['code'=> 1, 'msg'=> '当天记录已存在', 'data'=> []]);
  298. }
  299. $result = CommunityBusiness::create($param);
  300. if ($result !== false) {
  301. return json(['code'=> 0, 'data'=> [], 'msg'=> '添加成功']);
  302. } else {
  303. return json(['code'=> 1, 'data'=> [], 'msg'=> '添加失败']);
  304. }
  305. }
  306. }
  307. /**
  308. * 修改运营纪录
  309. */
  310. public function operate_edit() {
  311. $root_id = request()->empcrm->root_id;
  312. if (!request()->isAjax()) {
  313. $list = CommunityModel::where('root_id', '=', $root_id)->column('id,name');
  314. View::assign('community', $list);
  315. $id = input('id', '', 'intval');
  316. $business = CommunityBusiness::where([['id', '=', $id], ['root_id', '=', $root_id]])->findOrEmpty();
  317. View::assign('data', $business);
  318. return View::fetch();
  319. } else {
  320. $param = $this->request->only(['id', 'community_id', 'record_date', 'chat_group', 'work_log', 'group_script', 'customer_worship', 'building_output', 'talk_drill', 'material_production', 'wei_opinions', 'community_broadcast', 'housetype_broadcast', 'house_inspection_broadcast', 'start_work_broadcast', 'sample_room_broadcast', 'anchoring_traffic', 'sample_room_collect', 'owner_buy', 'owner_meeting', 'construction_direct', 'house_inspection', 'home_dinner', 'customer_thanks', 'housetype_share', 'decoration_saves_money', 'decoration_closed_pit', 'top_ten_spatial_planning', 'decoration_acceptance_standards', 'weekly_meeting', 'month_meeting', 'single_meeting', 'train_meeting']);
  321. $find = CommunityBusiness::where([['id', '=', $param['id']], ['root_id', '=', request()->empcrm->root_id]])->findOrEmpty();
  322. if ($find->isEmpty()) {
  323. return json(['code'=> 1, 'msg'=> '数据不存在', 'data'=> []]);
  324. }
  325. // 判断当天的记录是否存在
  326. $f_where[] = ['root_id', '=', $root_id];
  327. $f_where[] = ['record_date', '=', strtotime($param['record_date'])];
  328. $f_where[] = ['community_id', '=', $param['community_id']];
  329. $f_where[] = ['id', '<>', $param['id']];
  330. $have_find = CommunityBusiness::where($f_where)->findOrEmpty();
  331. if (!$have_find->isEmpty()) {
  332. return json(['code'=> 1, 'msg'=> '当天记录已存在', 'data'=> []]);
  333. }
  334. $result = $find->save($param);
  335. if ($result !== false) {
  336. return json(['code'=> 0, 'data'=> [], 'msg'=> '编辑成功']);
  337. } else {
  338. return json(['code'=> 1, 'data'=> [], 'msg'=> '编辑失败']);
  339. }
  340. }
  341. }
  342. /**
  343. * 汇总报表
  344. */
  345. public function summary_report(){
  346. if (!request()->isAjax()) {
  347. return View::fetch();
  348. } else {
  349. $invalid = input('invalid', '', 'intval');
  350. $page = input('page', 1, 'intval');
  351. $limit = input('limit', 10, 'intval');
  352. $root_id = $this->request->empcrm->root_id;
  353. $community_ids = Building::where([['root_id', '=', $root_id], ['del', '=', 0]])->group('community_id')->column('community_id');
  354. $community_list = CommunityModel::where([['root_id', '=', $root_id], ['id', 'in', $community_ids]])->page($page, $limit)->column('id,name,households');
  355. $count = CommunityModel::where([['root_id', '=', $root_id], ['id', 'in', $community_ids]])->count();
  356. // 社群员工
  357. $subOrg = orgSubIds(request()->empcrm->org_id);
  358. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职'], ['uid', '>', 0]])->column('id');
  359. // 所有小区名称
  360. $community_names = array_column($community_list, 'name');
  361. // 见面状态
  362. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  363. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  364. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  365. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  366. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  367. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  368. $where[] = ['Customer.employee_id', 'in', $emp_list];
  369. $where[] = ['Customer.community_name', 'in', $community_names];
  370. $where[] = ['Customer.died', '<>', 2];
  371. $where[] = ['Customer.state', 'not in', Customer::changeState('无效', 'chaos')];
  372. // $where[] = ['CustomerVisitLog.state', 'in', array_merge($state1, $state2, $state3, $state4, $state5)];
  373. $customer = Db::view('Customer')
  374. ->view('CustomerVisitLog', 'id', 'Customer.id=CustomerVisitLog.customer_id')
  375. ->where($where)
  376. ->where(function($query){
  377. $not_sure = Customer::changeState('待确认', 'chaos');
  378. $or1[] = ['Customer.crm_res_id', 'null', null];
  379. $or2[] = ['Customer.state', 'not in', $not_sure];
  380. $or2[] = ['Customer.crm_res_id', 'not null', null];
  381. $or3[] = ['Customer.valid_time', 'not null', null];
  382. $query->whereOr([$or1, $or2, $or3]);
  383. })
  384. ->column('Customer.id,Customer.community_name,Customer.add_wechat_time,Customer.into_owner_group,Customer.deposit_money,Customer.signed_money,CustomerVisitLog.state');
  385. $customer_data = []; // 数据
  386. $customer_count = []; // 小区客户数组
  387. $customer_state4 = []; // 收定客户数组
  388. $customer_state5 = []; // 签单客户数组
  389. $customer_wechat = []; // 加微客户数组
  390. $customer_visit = []; // 见面客户数组
  391. $customer_group = []; // 进群客户数组
  392. foreach ($customer as $k => $v) {
  393. if (empty($customer_data[$v['community_name']])) {
  394. $customer_data[$v['community_name']] = [];
  395. $customer_data[$v['community_name']]['count'] = 0;
  396. $customer_data[$v['community_name']]['deposit'] = 0;
  397. $customer_data[$v['community_name']]['signed'] = 0;
  398. $customer_data[$v['community_name']]['visit'] = 0;
  399. $customer_data[$v['community_name']]['wechat'] = 0;
  400. $customer_data[$v['community_name']]['into_group'] = 0;
  401. $customer_data[$v['community_name']]['signed_money'] = 0;
  402. }
  403. // 小区客户
  404. if (!in_array($v['id'], $customer_count)) {
  405. $customer_count[] = $v['id'];
  406. $customer_data[$v['community_name']]['count'] ++;
  407. }
  408. // 见面
  409. if (!in_array($v['id'], $customer_visit) && in_array($v['state'], $visit_state)) {
  410. $customer_visit[] = $v['id'];
  411. $customer_data[$v['community_name']]['visit'] ++;
  412. }
  413. // 定金
  414. if (in_array($v['state'], $state4, true) && !in_array($v['id'], $customer_state4)) {
  415. $customer_state4[] = $v['id'];
  416. $customer_data[$v['community_name']]['deposit'] ++;
  417. }
  418. // 签单
  419. if (in_array($v['state'], $state5, true) && !in_array($v['id'], $customer_state5)) {
  420. $customer_state5[] = $v['id'];
  421. $customer_data[$v['community_name']]['signed'] ++;
  422. $customer_data[$v['community_name']]['signed_money'] += $v['signed_money'];
  423. }
  424. // 加微
  425. if (!empty($v['add_wechat_time']) && !in_array($v['id'], $customer_wechat)) {
  426. $customer_wechat[] = $v['id'];
  427. $customer_data[$v['community_name']]['wechat'] ++;
  428. }
  429. // 进群
  430. if (!empty($v['into_owner_group']) && !in_array($v['id'], $customer_group)) {
  431. $customer_group[] = $v['id'];
  432. $customer_data[$v['community_name']]['into_group'] ++;
  433. }
  434. }
  435. // 包含无效
  436. $subOrg = orgSubIds(request()->empcrm->org_id);
  437. $i_where[] = ['Customer.org_id', 'in', $subOrg];
  438. $i_where[] = ['Customer.community_name', 'in', $community_names];
  439. $i_where[] = ['Customer.state', 'in', Customer::changeState('无效', 'chaos')];
  440. $i_where[] = ['CustomerVisitLog.state', 'in', array_merge($state1, $state2, $state3, $state4, $state5)];
  441. $i_customer = Db::view('Customer')
  442. ->view('CustomerVisitLog', 'id', 'Customer.id=CustomerVisitLog.customer_id')
  443. ->where($i_where)
  444. ->column('Customer.id,Customer.community_name,Customer.add_wechat_time,Customer.into_owner_group,Customer.deposit_money,Customer.signed_money,CustomerVisitLog.state');
  445. $customer_invalid_data = []; // 无效数据
  446. $customer_invalid_count = []; // 无效的客户数量
  447. $customer_invalid_visit = []; // 无效的客户见面
  448. $customer_invalid_deposit = []; // 无效的客户交定
  449. foreach ($i_customer as $k => $v) {
  450. if (empty($customer_invalid_data[$v['community_name']])) {
  451. $customer_invalid_data[$v['community_name']] = [];
  452. $customer_invalid_data[$v['community_name']]['invalid_count'] = 0;
  453. $customer_invalid_data[$v['community_name']]['invalid_visit'] = 0;
  454. $customer_invalid_data[$v['community_name']]['invalid_deposit'] = 0;
  455. }
  456. // 无效的客户数量
  457. if (!in_array($v['id'], $customer_invalid_count)) {
  458. $customer_invalid_count[] = $v['id'];
  459. $customer_invalid_data[$v['community_name']]['invalid_count'] ++;
  460. }
  461. // 无效的客户见面
  462. if (!in_array($v['id'], $customer_invalid_visit)) {
  463. $customer_invalid_visit[] = $v['id'];
  464. $customer_invalid_data[$v['community_name']]['invalid_visit'] ++;
  465. }
  466. // 无效的客户交定
  467. if (in_array($v['state'], $state4, true) && !in_array($v['id'], $customer_invalid_deposit)) {
  468. $customer_invalid_deposit[] = $v['id'];
  469. $customer_invalid_data[$v['community_name']]['invalid_deposit'] ++;
  470. }
  471. }
  472. $empty_data = [
  473. 'count'=> 0,
  474. 'deposit' => 0,
  475. 'signed' => 0,
  476. 'visit' => 0,
  477. 'wechat' => 0,
  478. 'into_group' => 0,
  479. 'signed_money' => 0
  480. ];
  481. $empty_invalid_data = [
  482. 'invalid_count'=> 0,
  483. 'invalid_visit'=> 0,
  484. 'invalid_deposit'=> 0
  485. ];
  486. foreach ($community_list as $k => $v) {
  487. if (isset($customer_data[$v['name']])) {
  488. $v = array_merge($v, $customer_data[$v['name']]);
  489. } else {
  490. $v = array_merge($v, $empty_data);
  491. }
  492. if (isset($customer_invalid_data[$v['name']])) {
  493. $v = array_merge($v, $customer_invalid_data[$v['name']]);
  494. } else {
  495. $v = array_merge($v, $empty_invalid_data);
  496. }
  497. $community_list[$k] = $v;
  498. $community_list[$k]['wechat_lv'] = $v['count'] > 0 ? round($v['wechat'] / $v['count'] * 100, 2) : $v['wechat'] * 100;
  499. $community_list[$k]['into_group_lv'] = $v['wechat'] > 0 ? round($v['into_group'] / $v['wechat'] * 100, 2) : $v['into_group'] * 100;
  500. $community_list[$k]['visit_lv'] = $v['wechat'] > 0 ? round($v['visit'] / $v['wechat'] * 100, 2) : $v['visit'] * 100;
  501. $community_list[$k]['deposit_lv'] = $v['visit'] > 0 ? round($v['deposit'] / $v['visit'] * 100, 2) : $v['deposit'] * 100;
  502. }
  503. return json(['code'=> 0, 'data'=> $community_list, 'msg'=> 'success', 'count'=> $count]);
  504. }
  505. }
  506. /**
  507. * 业务报表
  508. */
  509. public function employee_report(){
  510. $root_id = request()->empcrm->root_id;
  511. if (!request()->isAjax()) {
  512. $list = CommunityModel::where('root_id', '=', $root_id)->column('id,name');
  513. View::assign('community', $list);
  514. $theorg = Org::find(request()->empcrm->org_id);
  515. $org = Org::where([['path', 'like', $theorg->path . '%']])->column('id,name');
  516. View::assign('org', $org);
  517. return View::fetch();
  518. } else {
  519. $community_id = input('community_id', '', 'intval');
  520. $search_date = input('date', '', 'trim');
  521. $invalid = input('invalid', '', 'trim');
  522. $org_id = input('org_id', request()->empcrm->org_id, 'intval');
  523. // 小区
  524. if ($community_id) {
  525. $community = CommunityModel::where([['id', '=', $community_id], ['root_id', '=', $root_id]])->findOrEmpty();
  526. // 小区不存在直接返回
  527. if ($community->isEmpty()) {
  528. return json(['code'=> 0, 'data'=> [], 'msg'=> 'success', 'count'=> 0]);
  529. }
  530. }
  531. if ($search_date) {
  532. $date = explode(' - ', $search_date);
  533. $start_date = date('Y-m-d 00:00:00', strtotime($date[0]));
  534. $end_date = date('Y-m-d 23:59:59', strtotime($date[1]));
  535. } else {
  536. // 默认本月
  537. $start_date = date('Y-m-01 00:00:00');
  538. $end_date = date('Y-m-d 23:59:59');
  539. }
  540. $subOrg = orgSubIds($org_id);
  541. // 社群员工
  542. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职'], ['uid', '>', 0]])->column('id,name');
  543. // 有效客户总量
  544. $valid_where[] = ['Employee.org_id', 'in', $subOrg];
  545. $valid_where[] = ['Employee.community_disable', '=', 0];
  546. $valid_where[] = ['Employee.state', '=', '在职'];
  547. $valid_where[] = ['Employee.uid', '>', 0];
  548. $valid_where[] = ['Customer.sign_time', 'between', [$start_date, $end_date]];
  549. if ($community_id) {
  550. $valid_where[] = ['Customer.community_name', '=', $community['name']];
  551. }
  552. $customer_valid = Db::view('Employee')
  553. ->view('Customer', 'id cid', 'Customer.employee_id=Employee.id')
  554. ->where($valid_where)
  555. ->column('Customer.id,Customer.employee_id');
  556. $customer_count = [];
  557. foreach ($customer_valid as $k => $v){
  558. $customer_count[$v['employee_id']][] = $v['id'];
  559. }
  560. // 加微、进群
  561. $m_where[] = ['Employee.org_id', 'in', $subOrg];
  562. $m_where[] = ['Employee.community_disable', '=', 0];
  563. $m_where[] = ['Employee.state', '=', '在职'];
  564. $m_where[] = ['Employee.uid', '>', 0];
  565. $m_where[] = ['Customer.add_wechat_time|Customer.into_owner_group', '>=', $start_date];
  566. $m_where[] = ['Customer.add_wechat_time|Customer.into_owner_group', '<=', $end_date];
  567. if ($community_id) {
  568. $m_where[] = ['Customer.community_name', '=', $community['name']];
  569. }
  570. $emp_customer = Db::view('Employee')
  571. ->view('Customer', 'id cid', 'Customer.employee_id=Employee.id')
  572. ->where($m_where)
  573. ->column('Customer.id,Customer.employee_id,Customer.add_wechat_time,Customer.into_owner_group,Customer.reputation_gather');
  574. $add_wechat_time = []; // 加微的
  575. $into_owner_group = []; //加群的
  576. $str_start_time = strtotime($start_date);
  577. $str_end_time = strtotime($end_date);
  578. foreach ($emp_customer as $k => $v) {
  579. // 加微处理
  580. $v_time = !empty($v['add_wechat_time']) ? strtotime($v['add_wechat_time']) : 0;
  581. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  582. $add_wechat_time[$v['employee_id']][] = $v['id'];
  583. }
  584. // 加群处理
  585. $v_time = !empty($v['into_owner_group']) ? strtotime($v['into_owner_group']) : 0;
  586. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  587. $into_owner_group[$v['employee_id']][] = $v['id'];
  588. }
  589. }
  590. // 见面状态
  591. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  592. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  593. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  594. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  595. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  596. $db_where[] = ['Employee.org_id', 'in', $subOrg];
  597. $db_where[] = ['Employee.community_disable', '=', 0];
  598. $db_where[] = ['Employee.state', '=', '在职'];
  599. $db_where[] = ['Employee.uid', '>', 0];
  600. $db_where[] = ['CustomerVisitLog.confirm_date', 'between', [$start_date, $end_date]];
  601. $db_where[] = ['CustomerVisitLog.state', 'in', array_merge($state1, $state2, $state3, $state4, $state5)];
  602. if ($community_id) {
  603. $db_where[] = ['Customer.community_name', '=', $community['name']];
  604. }
  605. $customer = Db::view('Customer')
  606. ->view('CustomerVisitLog', 'id', 'Customer.id=CustomerVisitLog.customer_id')
  607. ->view('Employee', 'id', 'CustomerVisitLog.customer_employee_id=Employee.id')
  608. ->where($db_where)
  609. ->column('Customer.id,CustomerVisitLog.customer_employee_id employee_id,CustomerVisitLog.state,Customer.deposit_money,Customer.signed_money');
  610. $customer_data = []; // 数据 未做去重
  611. foreach ($customer as $k => $v){
  612. if (empty($customer_data[$v['employee_id']])) {
  613. $customer_data[$v['employee_id']] = [];
  614. $customer_data[$v['employee_id']]['deposit'] = [];
  615. $customer_data[$v['employee_id']]['signed'] = [];
  616. $customer_data[$v['employee_id']]['visit'] = [];
  617. $customer_data[$v['employee_id']]['signed_money'] = 0;
  618. }
  619. // 见面
  620. $customer_data[$v['employee_id']]['visit'][] = $v['id'];
  621. // 定金
  622. if (in_array($v['state'], $state4, true)) {
  623. $customer_data[$v['employee_id']]['deposit'][] = $v['id'];
  624. }
  625. // 签单
  626. if (in_array($v['state'], $state5, true)) {
  627. $customer_data[$v['employee_id']]['signed'][] = $v['id'];
  628. }
  629. }
  630. // 处理业绩 交定+签单 签单的客户不计算交定金额
  631. $customer_deposit = [];
  632. foreach ($customer as $k => $v){
  633. // 用于判断这个客户是否记录过数据
  634. if (empty($customer_deposit[$v['employee_id']])) {
  635. $customer_deposit[$v['employee_id']] = [];
  636. $customer_deposit[$v['employee_id']]['deposit'] = []; //收定客户数组
  637. $customer_deposit[$v['employee_id']]['signed'] = []; //签单客户数组
  638. }
  639. // 定金
  640. if (in_array($v['state'], $state4, true) && !in_array($v['id'], $customer_deposit[$v['employee_id']]['deposit'])) {
  641. $customer_deposit[$v['employee_id']]['deposit'][] = $v['id'];
  642. // 不是转单过的,才加定金
  643. if (!in_array($v['id'], $customer_data[$v['employee_id']]['signed'])) {
  644. $customer_data[$v['employee_id']]['signed_money'] += $v['deposit_money'];
  645. }
  646. }
  647. // 签单
  648. if (in_array($v['state'], $state5, true) && !in_array($v['id'], $customer_deposit[$v['employee_id']]['signed'])) {
  649. $customer_deposit[$v['employee_id']]['signed'][] = $v['id'];
  650. $customer_data[$v['employee_id']]['signed_money'] += $v['signed_money'];
  651. }
  652. }
  653. // 包含无效
  654. $i_where[] = ['Employee.org_id', 'in', $subOrg];
  655. $i_where[] = ['Employee.community_disable', '=', 0];
  656. $i_where[] = ['Employee.state', '=', '在职'];
  657. $i_where[] = ['Employee.uid', '>', 0];
  658. $i_where[] = ['CustomerInvalidLog.cus_addtime|CustomerVisitLog.confirm_date', 'between', [$start_date, $end_date]];
  659. if ($community_id) {
  660. $i_where[] = ['Customer.community_name', '=', $community['name']];
  661. }
  662. $i_customer = Db::view('CustomerInvalidLog')
  663. ->view('Employee', 'id eid', 'Employee.id=CustomerInvalidLog.employee_id')
  664. ->view('Customer', 'id cid', 'Customer.id=CustomerInvalidLog.customer_id')
  665. ->view('CustomerVisitLog', 'id log_id', 'Customer.id=CustomerVisitLog.customer_id')
  666. ->where($i_where)
  667. ->column('CustomerInvalidLog.id,CustomerInvalidLog.status,CustomerInvalidLog.cus_addtime,Customer.id customer_id,Customer.add_wechat_time,Customer.into_owner_group,CustomerVisitLog.id log_id,CustomerVisitLog.customer_employee_id employee_id,CustomerVisitLog.state,CustomerVisitLog.confirm_date');
  668. $customer_invalid_data = []; // 无效数据 数据没有去重
  669. foreach ($i_customer as $k => $v) {
  670. if (empty($customer_invalid_data[$v['employee_id']])) {
  671. $customer_invalid_data[$v['employee_id']] = [];
  672. $customer_invalid_data[$v['employee_id']]['count'] = []; // 某个员工下的置为无效的
  673. $customer_invalid_data[$v['employee_id']]['valid'] = []; // 某个员工下置为无效的时候是有效的
  674. $customer_invalid_data[$v['employee_id']]['visit'] = []; // 某个员工下置为无效的时候有见面
  675. $customer_invalid_data[$v['employee_id']]['deposit'] = []; // 某个员工下置为无效的时候有交定
  676. $customer_invalid_data[$v['employee_id']]['wechat'] = []; // 某个员工下置为无效的时候有加微
  677. $customer_invalid_data[$v['employee_id']]['into_group'] = []; // 某个员工下置为无效的时候有进群
  678. }
  679. // 无效的客户
  680. if ($str_start_time <= strtotime($v['cus_addtime']) && strtotime($v['cus_addtime']) <= $str_end_time) {
  681. $customer_invalid_data[$v['employee_id']]['count'][] = $v['customer_id'];
  682. // 无效的客户曾经有效
  683. if ($v['status'] == 1) {
  684. $customer_invalid_data[$v['employee_id']]['valid'][] = $v['customer_id'];
  685. }
  686. }
  687. if ($str_start_time <= strtotime($v['confirm_date']) && strtotime($v['confirm_date']) <= $str_end_time) {
  688. // 无效的客户见面
  689. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  690. if (in_array($v['state'], $visit_state, true)) {
  691. $customer_invalid_data[$v['employee_id']]['visit'][] = $v['customer_id'];
  692. }
  693. // 无效的客户交定
  694. if (in_array($v['state'], $state4, true)) {
  695. $customer_invalid_data[$v['employee_id']]['deposit'][] = $v['customer_id'];
  696. }
  697. }
  698. // 加微处理
  699. $v_time = !empty($v['add_wechat_time']) ? strtotime($v['add_wechat_time']) : 0;
  700. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  701. $customer_invalid_data[$v['employee_id']]['wechat'][] = $v['customer_id'];
  702. }
  703. // 加群处理
  704. $v_time = !empty($v['into_owner_group']) ? strtotime($v['into_owner_group']) : 0;
  705. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  706. $customer_invalid_data[$v['employee_id']]['into_group'][] = $v['customer_id'];
  707. }
  708. }
  709. $empty_invalid_data = [
  710. 'invalid_valid'=> 0,
  711. 'invalid_visit'=> 0,
  712. 'invalid_deposit'=> 0
  713. ];
  714. // 每个员工下的信息量
  715. foreach ($emp_list as $k => $v) {
  716. // 客户量
  717. $v_count = $customer_count[$v['id']] ?? []; // 现有客户id数组
  718. $v_count_valid = $customer_invalid_data[$v['id']]['count'] ?? []; // 无效客户id数组
  719. $v_count_merge = count(array_unique(array_merge($v_count, $v_count_valid)));
  720. $emp_list[$k]['count'] = $v_count_merge;
  721. // 加微量 加微率
  722. $v_wechat = $add_wechat_time[$v['id']] ?? [];
  723. $v_wechat_valid = $customer_invalid_data[$v['id']]['wechat'] ?? [];
  724. $v_wechat_merge = count(array_unique(array_merge($v_wechat, $v_wechat_valid)));
  725. $emp_list[$k]['wechat'] = $v_wechat_merge;
  726. $emp_list[$k]['wechat_lv'] = ($v_count_merge > 0 ? round($v_wechat_merge / $v_count_merge * 100, 2) : $v_wechat_merge * 100) . '%';
  727. // 进群量 进群率
  728. $into_group = $into_owner_group[$v['id']] ?? [];
  729. $into_group_valid = $customer_invalid_data[$v['id']]['into_group'] ?? [];
  730. $v_into_group_merge = count(array_unique(array_merge($into_group, $into_group_valid)));
  731. $emp_list[$k]['into_group'] = $v_into_group_merge;
  732. $emp_list[$k]['into_group_lv'] = ($v_wechat_merge > 0 ? round($v_into_group_merge / $v_wechat_merge * 100, 2) : $v_into_group_merge * 100) . '%';
  733. // 见面 见面率
  734. $v_visit = $customer_data[$v['id']]['visit'] ?? [];
  735. $v_visit_valid = $customer_invalid_data[$v['id']]['visit'] ?? [];
  736. $v_visit_merge = count(array_unique(array_merge($v_visit, $v_visit_valid)));
  737. $emp_list[$k]['visit'] = $v_visit_merge;
  738. $emp_list[$k]['visit_lv'] = ($v_wechat_merge > 0 ? round($v_visit_merge / $v_wechat_merge * 100, 2) : $v_visit_merge * 100) . '%';
  739. // 定金 成单率
  740. $v_deposit = $customer_data[$v['id']]['deposit'] ?? [];
  741. $v_deposit_valid = $customer_invalid_data[$v['id']]['deposit'] ?? [];
  742. $v_deposit_merge = count(array_unique(array_merge($v_deposit, $v_deposit_valid)));
  743. $emp_list[$k]['deposit'] = $v_deposit_merge;
  744. $emp_list[$k]['deposit_lv'] = ($v_visit_merge > 0 ? round($v_deposit_merge / $v_visit_merge * 100, 2) : $v_deposit_merge * 100) . '%';
  745. // 签单
  746. $v_signed = $customer_data[$v['id']]['signed'] ?? [];
  747. $v_signed_merge = count(array_unique($v_signed));
  748. $emp_list[$k]['signed'] = $v_signed_merge;
  749. // 总业绩
  750. $emp_list[$k]['signed_money'] = $customer_data[$v['id']]['signed_money'] ?? 0;
  751. if (isset($customer_invalid_data[$v['id']])) {
  752. $invalid_data = [
  753. 'invalid_valid'=> count($customer_invalid_data[$v['id']]['valid']),
  754. 'invalid_visit'=> count($customer_invalid_data[$v['id']]['visit']),
  755. 'invalid_deposit'=> count($customer_invalid_data[$v['id']]['deposit'])
  756. ];
  757. $emp_list[$k] = array_merge($emp_list[$k], $invalid_data);
  758. } else {
  759. $emp_list[$k] = array_merge($emp_list[$k], $empty_invalid_data);
  760. }
  761. }
  762. // 求和
  763. $total['name'] = '求和';
  764. $total['count'] = array_sum(array_column($emp_list, 'count'));
  765. $total['wechat'] = array_sum(array_column($emp_list, 'wechat'));
  766. $total['wechat_lv'] = ($total['count'] > 0 ? round($total['wechat'] / $total['count'] * 100, 2) : $total['wechat'] * 100) . '%';
  767. $total['into_group'] = array_sum(array_column($emp_list, 'into_group'));
  768. $total['into_group_lv'] = ($total['wechat'] > 0 ? round($total['into_group'] / $total['wechat'] * 100, 2) : $total['into_group'] * 100) . '%';
  769. $total['visit'] = array_sum(array_column($emp_list, 'visit'));
  770. $total['visit_lv'] = ($total['wechat'] > 0 ? round($total['visit'] / $total['wechat'] * 100, 2) : $total['visit'] * 100) . '%';
  771. $total['deposit'] = array_sum(array_column($emp_list, 'deposit'));
  772. $total['deposit_lv'] = ($total['visit'] > 0 ? round($total['deposit'] / $total['visit'] * 100, 2) : $total['deposit'] * 100) . '%';
  773. $total['signed'] = array_sum(array_column($emp_list, 'signed'));
  774. $total['signed_money'] = array_sum(array_column($emp_list, 'signed_money'));
  775. $total['invalid_valid'] = array_sum(array_column($emp_list, 'invalid_valid'));
  776. $total['invalid_visit'] = array_sum(array_column($emp_list, 'invalid_visit'));
  777. $total['invalid_deposit'] = array_sum(array_column($emp_list, 'invalid_deposit'));
  778. $emp_list[] = $total;
  779. return json(['code'=> 0, 'data'=> $emp_list, 'msg'=> 'success']);
  780. }
  781. }
  782. /**
  783. * 小区报表
  784. */
  785. public function community_report(){
  786. if (!request()->isAjax()) {
  787. // 社群员工
  788. $subOrg = orgSubIds(request()->empcrm->org_id);
  789. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职'], ['uid', '>', 0]])->column('id,name');
  790. View::assign('employee', $emp_list);
  791. return View::fetch();
  792. } else {
  793. $invalid = input('invalid', '', 'intval');
  794. $employee_id = input('employee_id', '', 'intval');
  795. $search_date = input('date', '', 'trim');
  796. if ($search_date) {
  797. $date = explode(' - ', $search_date);
  798. $start_date = date('Y-m-d 00:00:00', strtotime($date[0]));
  799. $end_date = date('Y-m-d 23:59:59', strtotime($date[1]));
  800. } else {
  801. // 默认本月
  802. $start_date = date('Y-m-01 00:00:00');
  803. $end_date = date('Y-m-d 23:59:59');
  804. }
  805. $root_id = request()->empcrm->root_id;
  806. $community_ids = Building::where([['root_id', '=', $root_id], ['del', '=', 0]])->group('community_id')->column('community_id');
  807. $community_list = CommunityModel::where([['id', 'in', $community_ids]])->column('id,name,households');
  808. // 社群员工
  809. $subOrg = orgSubIds(request()->empcrm->org_id);
  810. $emp_list = Employee::where([['org_id', 'in', $subOrg], ['community_disable', '=', 0], ['state', '=', '在职'], ['uid', '>', 0]])->column('id');
  811. // 所有小区名称
  812. $community_names = array_column($community_list, 'name');
  813. if ($employee_id) {
  814. $valid_where[] = ['Employee.id', '=', $employee_id];
  815. } else {
  816. $valid_where[] = ['Employee.org_id', 'in', $subOrg];
  817. $valid_where[] = ['Employee.community_disable', '=', 0];
  818. $valid_where[] = ['Employee.state', '=', '在职'];
  819. $valid_where[] = ['Employee.uid', '>', 0];
  820. }
  821. $valid_where[] = ['Customer.sign_time', 'between', [$start_date, $end_date]];
  822. $valid_where[] = ['Customer.community_name', 'in', $community_names];
  823. // 客户数量
  824. $customer_valid = Db::view('Employee')
  825. ->view('Customer', 'id cid', 'Customer.employee_id=Employee.id')
  826. ->where($valid_where)
  827. ->column('Customer.id,Customer.community_name');
  828. $customer_count = [];
  829. foreach ($customer_valid as $k => $v){
  830. $customer_count[$v['community_name']][] = $v['id'];
  831. }
  832. // 加微、进群
  833. $m_where[] = ['Employee.org_id', 'in', $subOrg];
  834. $m_where[] = ['Employee.community_disable', '=', 0];
  835. $m_where[] = ['Employee.state', '=', '在职'];
  836. $m_where[] = ['Employee.uid', '>', 0];
  837. $m_where[] = ['Customer.add_wechat_time|Customer.into_owner_group', '>=', $start_date];
  838. $m_where[] = ['Customer.add_wechat_time|Customer.into_owner_group', '<=', $end_date];
  839. $m_where[] = ['Customer.community_name', 'in', $community_names];
  840. $emp_customer = Db::view('Employee')
  841. ->view('Customer', 'id cid', 'Customer.employee_id=Employee.id')
  842. ->where($m_where)
  843. ->column('Customer.id,Customer.community_name,Customer.add_wechat_time,Customer.into_owner_group,Customer.reputation_gather');
  844. $add_wechat_time = []; // 加微的
  845. $into_owner_group = []; //加群的
  846. $str_start_time = strtotime($start_date);
  847. $str_end_time = strtotime($end_date);
  848. foreach ($emp_customer as $k => $v) {
  849. // 加微处理
  850. $v_time = !empty($v['add_wechat_time']) ? strtotime($v['add_wechat_time']) : 0;
  851. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  852. $add_wechat_time[$v['community_name']][] = $v['id'];
  853. }
  854. // 加群处理
  855. $v_time = !empty($v['into_owner_group']) ? strtotime($v['into_owner_group']) : 0;
  856. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  857. $into_owner_group[$v['community_name']][] = $v['id'];
  858. }
  859. }
  860. // 见面状态
  861. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  862. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  863. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  864. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  865. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  866. $db_where[] = ['Employee.org_id', 'in', $subOrg];
  867. $db_where[] = ['Employee.community_disable', '=', 0];
  868. $db_where[] = ['Employee.state', '=', '在职'];
  869. $db_where[] = ['Employee.uid', '>', 0];
  870. $db_where[] = ['CustomerVisitLog.confirm_date', 'between', [$start_date, $end_date]];
  871. $db_where[] = ['Customer.community_name', 'in', $community_names];
  872. $db_where[] = ['CustomerVisitLog.state', 'in', array_merge($state1, $state2, $state3, $state4, $state5)];
  873. $customer = Db::view('Customer')
  874. ->view('CustomerVisitLog', 'id', 'Customer.id=CustomerVisitLog.customer_id')
  875. ->view('Employee', 'id', 'CustomerVisitLog.customer_employee_id=Employee.id')
  876. ->where($db_where)
  877. ->column('Customer.id,Customer.community_name,CustomerVisitLog.customer_employee_id employee_id,CustomerVisitLog.state,Customer.deposit_money,Customer.signed_money');
  878. $customer_data = []; // 数据 未做去重
  879. foreach ($customer as $k => $v){
  880. if (empty($customer_data[$v['community_name']])) {
  881. $customer_data[$v['community_name']] = [];
  882. $customer_data[$v['community_name']]['deposit'] = [];
  883. $customer_data[$v['community_name']]['signed'] = [];
  884. $customer_data[$v['community_name']]['visit'] = [];
  885. $customer_data[$v['community_name']]['signed_money'] = 0;
  886. }
  887. // 见面
  888. $customer_data[$v['community_name']]['visit'][] = $v['id'];
  889. // 定金
  890. if (in_array($v['state'], $state4, true)) {
  891. $customer_data[$v['community_name']]['deposit'][] = $v['id'];
  892. }
  893. // 签单
  894. if (in_array($v['state'], $state5, true)) {
  895. $customer_data[$v['community_name']]['signed'][] = $v['id'];
  896. }
  897. }
  898. // 处理业绩 交定+签单 签单的客户不计算交定金额
  899. $customer_deposit = [];
  900. foreach ($customer as $k => $v){
  901. // 用于判断这个客户是否记录过数据
  902. if (empty($customer_deposit[$v['community_name']])) {
  903. $customer_deposit[$v['community_name']] = [];
  904. $customer_deposit[$v['community_name']]['deposit'] = []; //收定客户数组
  905. $customer_deposit[$v['community_name']]['signed'] = []; //签单客户数组
  906. }
  907. // 定金
  908. if (in_array($v['state'], $state4, true) && !in_array($v['id'], $customer_deposit[$v['community_name']]['deposit'])) {
  909. $customer_deposit[$v['community_name']]['deposit'][] = $v['id'];
  910. // 不是转单过的,才加定金
  911. if (!in_array($v['id'], $customer_data[$v['community_name']]['signed'])) {
  912. $customer_data[$v['community_name']]['signed_money'] += $v['deposit_money'];
  913. }
  914. }
  915. // 签单
  916. if (in_array($v['state'], $state5, true) && !in_array($v['id'], $customer_deposit[$v['community_name']]['signed'])) {
  917. $customer_deposit[$v['community_name']]['signed'][] = $v['id'];
  918. $customer_data[$v['community_name']]['signed_money'] += $v['signed_money'];
  919. }
  920. }
  921. // 包含无效
  922. $i_where[] = ['Employee.org_id', 'in', $subOrg];
  923. $i_where[] = ['Employee.community_disable', '=', 0];
  924. $i_where[] = ['Employee.state', '=', '在职'];
  925. $i_where[] = ['Employee.uid', '>', 0];
  926. $i_where[] = ['Customer.community_name', 'in', $community_names];
  927. $i_where[] = ['CustomerVisitLog.confirm_date|CustomerInvalidLog.cus_addtime', 'between', [$start_date, $end_date]];
  928. $i_customer = Db::view('CustomerInvalidLog')
  929. ->view('Employee', 'id eid', 'Employee.id=CustomerInvalidLog.employee_id')
  930. ->view('Customer', 'id cid', 'Customer.id=CustomerInvalidLog.customer_id')
  931. ->view('CustomerVisitLog', 'id log_id', 'Customer.id=CustomerVisitLog.customer_id')
  932. ->where($i_where)
  933. ->column('CustomerInvalidLog.id,CustomerInvalidLog.status,CustomerInvalidLog.cus_addtime,Customer.id customer_id,Customer.community_name,Customer.add_wechat_time,Customer.into_owner_group,CustomerVisitLog.id log_id,CustomerVisitLog.customer_employee_id employee_id,CustomerVisitLog.state,CustomerVisitLog.confirm_date');
  934. $customer_invalid_data = []; // 无效数据 数据没有去重
  935. foreach ($i_customer as $k => $v) {
  936. if (empty($v['community_name'])) {
  937. continue;
  938. }
  939. if (empty($customer_invalid_data[$v['community_name']])) {
  940. $customer_invalid_data[$v['community_name']] = [];
  941. $customer_invalid_data[$v['community_name']]['count'] = []; // 某个员工下的置为无效的
  942. $customer_invalid_data[$v['community_name']]['valid'] = []; // 某个员工下置为无效的时候是有效的
  943. $customer_invalid_data[$v['community_name']]['visit'] = []; // 某个员工下置为无效的时候有见面
  944. $customer_invalid_data[$v['community_name']]['deposit'] = []; // 某个员工下置为无效的时候有交定
  945. $customer_invalid_data[$v['community_name']]['wechat'] = []; // 某个员工下置为无效的时候有加微
  946. $customer_invalid_data[$v['community_name']]['into_group'] = []; // 某个员工下置为无效的时候有进群
  947. }
  948. // 无效的客户
  949. if ($str_start_time <= strtotime($v['cus_addtime']) && strtotime($v['cus_addtime']) <= $str_end_time) {
  950. $customer_invalid_data[$v['community_name']]['count'][] = $v['customer_id'];
  951. // 无效的客户曾经有效
  952. if ($v['status'] == 1) {
  953. $customer_invalid_data[$v['community_name']]['valid'][] = $v['customer_id'];
  954. }
  955. }
  956. // 无效的客户
  957. if ($str_start_time <= $v['confirm_date'] && $v['confirm_date'] <= $str_end_time) {
  958. // 无效的客户见面
  959. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  960. if (in_array($v['state'], $visit_state, true)) {
  961. $customer_invalid_data[$v['community_name']]['visit'][] = $v['customer_id'];
  962. }
  963. // 无效的客户交定
  964. if (in_array($v['state'], $state4, true)) {
  965. $customer_invalid_data[$v['community_name']]['deposit'][] = $v['customer_id'];
  966. }
  967. }
  968. // 加微处理
  969. $v_time = !empty($v['add_wechat_time']) ? strtotime($v['add_wechat_time']) : 0;
  970. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  971. $customer_invalid_data[$v['community_name']]['wechat'][] = $v['customer_id'];
  972. }
  973. // 加群处理
  974. $v_time = !empty($v['into_owner_group']) ? strtotime($v['into_owner_group']) : 0;
  975. if ($v_time && $str_start_time <= $v_time && $v_time <= $str_end_time) {
  976. $customer_invalid_data[$v['community_name']]['into_group'][] = $v['customer_id'];
  977. }
  978. }
  979. $empty_invalid_data = [
  980. 'invalid_valid'=> 0,
  981. 'invalid_visit'=> 0,
  982. 'invalid_deposit'=> 0
  983. ];
  984. // 每个小区下的信息量
  985. foreach ($community_list as $k => $v) {
  986. // 客户量
  987. $v_count = $customer_count[$v['name']] ?? []; // 现有客户id数组
  988. $v_count_valid = $customer_invalid_data[$v['name']]['count'] ?? []; // 无效客户id数组
  989. $v_count_merge = count(array_unique(array_merge($v_count, $v_count_valid)));
  990. $community_list[$k]['count'] = $v_count_merge;
  991. // 加微量 加微率
  992. $v_wechat = $add_wechat_time[$v['name']] ?? [];
  993. $v_wechat_valid = $customer_invalid_data[$v['name']]['wechat'] ?? [];
  994. $v_wechat_merge = count(array_unique(array_merge($v_wechat, $v_wechat_valid)));
  995. $community_list[$k]['wechat'] = $v_wechat_merge;
  996. $community_list[$k]['wechat_lv'] = ($v_count_merge > 0 ? round($v_wechat_merge / $v_count_merge * 100, 2) : $v_wechat_merge * 100) . '%';
  997. // 进群量 进群率
  998. $into_group = $into_owner_group[$v['name']] ?? [];
  999. $into_group_valid = $customer_invalid_data[$v['name']]['into_group'] ?? [];
  1000. $v_into_group_merge = count(array_unique(array_merge($into_group, $into_group_valid)));
  1001. $community_list[$k]['into_group'] = $v_into_group_merge;
  1002. $community_list[$k]['into_group_lv'] = ($v_wechat_merge > 0 ? round($v_into_group_merge / $v_wechat_merge * 100, 2) : $v_into_group_merge * 100) . '%';
  1003. // 见面 见面率
  1004. $v_visit = $customer_data[$v['name']]['visit'] ?? [];
  1005. $v_visit_valid = $customer_invalid_data[$v['name']]['visit'] ?? [];
  1006. $v_visit_merge = count(array_unique(array_merge($v_visit, $v_visit_valid)));
  1007. $community_list[$k]['visit'] = $v_visit_merge;
  1008. $community_list[$k]['visit_lv'] = ($v_wechat_merge > 0 ? round($v_visit_merge / $v_wechat_merge * 100, 2) : $v_visit_merge * 100) . '%';
  1009. // 定金 成单率
  1010. $v_deposit = $customer_data[$v['name']]['deposit'] ?? [];
  1011. //$v_deposit_valid = $customer_invalid_data[$v['name']]['deposit'] ?? [];
  1012. $v_deposit_valid = []; // 置为无效的不加交定
  1013. $v_deposit_merge = count(array_unique(array_merge($v_deposit, $v_deposit_valid)));
  1014. $community_list[$k]['deposit'] = $v_deposit_merge;
  1015. $community_list[$k]['deposit_lv'] = ($v_visit_merge > 0 ? round($v_deposit_merge / $v_visit_merge * 100, 2) : $v_deposit_merge * 100) . '%';
  1016. // 签单
  1017. $v_signed = $customer_data[$v['name']]['signed'] ?? [];
  1018. $v_signed_merge = count(array_unique($v_signed));
  1019. $community_list[$k]['signed'] = $v_signed_merge;
  1020. // 总业绩
  1021. $community_list[$k]['signed_money'] = $customer_data[$v['name']]['signed_money'] ?? 0;
  1022. if (isset($customer_invalid_data[$v['name']])) {
  1023. $invalid_data = [
  1024. 'invalid_valid'=> count($customer_invalid_data[$v['name']]['valid']),
  1025. 'invalid_visit'=> count($customer_invalid_data[$v['name']]['visit']),
  1026. 'invalid_deposit'=> count($customer_invalid_data[$v['name']]['deposit'])
  1027. ];
  1028. $community_list[$k] = array_merge($community_list[$k], $invalid_data);
  1029. } else {
  1030. $community_list[$k] = array_merge($community_list[$k], $empty_invalid_data);
  1031. }
  1032. }
  1033. // 求和
  1034. $total['name'] = '求和';
  1035. $total['households'] = array_sum(array_column($community_list, 'households'));
  1036. $total['count'] = array_sum(array_column($community_list, 'count'));
  1037. $total['wechat'] = array_sum(array_column($community_list, 'wechat'));
  1038. $total['wechat_lv'] = ($total['count'] > 0 ? round($total['wechat'] / $total['count'] * 100, 2) : $total['wechat'] * 100) . '%';
  1039. $total['into_group'] = array_sum(array_column($community_list, 'into_group'));
  1040. $total['into_group_lv'] = ($total['wechat'] > 0 ? round($total['into_group'] / $total['wechat'] * 100, 2) : $total['into_group'] * 100) . '%';
  1041. $total['visit'] = array_sum(array_column($community_list, 'visit'));
  1042. $total['visit_lv'] = ($total['wechat'] > 0 ? round($total['visit'] / $total['wechat'] * 100, 2) : $total['visit'] * 100) . '%';
  1043. $total['deposit'] = array_sum(array_column($community_list, 'deposit'));
  1044. $total['deposit_lv'] = ($total['visit'] > 0 ? round($total['deposit'] / $total['visit'] * 100, 2) : $total['deposit'] * 100) . '%';
  1045. $total['signed'] = array_sum(array_column($community_list, 'signed'));
  1046. $total['signed_money'] = array_sum(array_column($community_list, 'signed_money'));
  1047. $total['invalid_valid'] = array_sum(array_column($community_list, 'invalid_valid'));
  1048. $total['invalid_visit'] = array_sum(array_column($community_list, 'invalid_visit'));
  1049. $total['invalid_deposit'] = array_sum(array_column($community_list, 'invalid_deposit'));
  1050. $community_list[] = $total;
  1051. return json(['code'=> 0, 'data'=> $community_list, 'msg'=> 'success']);
  1052. }
  1053. }
  1054. /**
  1055. * 弹框页面
  1056. */
  1057. public function open()
  1058. {
  1059. $employee_id = input('employee_id', '', 'intval'); //员工id
  1060. $community_id = input('community_id', '', 'intval'); // 小区id
  1061. $type = input('type', ''); // 数据类型
  1062. $module = input('module', '', 'trim'); //数据模块
  1063. $date = input('date', '');
  1064. $field = [
  1065. ['field' => 'name', 'title' => '客户姓名'],
  1066. ['field' => 'community_name', 'title' => '小区名称'],
  1067. ['field' => 'square', 'title' => '面积'],
  1068. ['field' => 'employee_name', 'title' => '客服专员'],
  1069. ['field' => 'designer_name', 'title' => '设计师'],
  1070. ['field' => 'first_visit_time', 'title' => '首次会面'],
  1071. ['field' => 'deposit_time', 'title' => '定金时间'],
  1072. ['field' => 'sign_time', 'title' => '报名时间'],
  1073. ['field' => 'state', 'title' => '状态']
  1074. ];
  1075. $url = url("community/openData", ['employee_id' => $employee_id, 'community_id' => $community_id, 'type' => $type, 'date' => $date, 'module'=> $module]);
  1076. View::assign('fields', json_encode($field));
  1077. View::assign('url', $url);
  1078. return View::fetch();
  1079. }
  1080. /**
  1081. * 弹框列表
  1082. */
  1083. public function openData()
  1084. {
  1085. $request = request();
  1086. $param = $request->only(['page' => 1, 'limit' => 10, 'employee_id' => 0, 'community_id' => 0, 'type' => '', 'date' => '', 'module'=> '']);
  1087. if($param['date']){
  1088. $search_date = explode(' - ', $param['date']);
  1089. $start_date = date('Y-m-d H:i:s', strtotime($search_date[0]));
  1090. $end_date = date('Y-m-d 23:59:59', strtotime($search_date[1]));
  1091. } else {
  1092. $search_date = [];
  1093. }
  1094. $where = [];
  1095. $root_id = request()->empcrm->root_id;
  1096. $org_id = request()->empcrm->org_id;
  1097. if ($param['module'] == 'community') { // 以小区为主线
  1098. $community = CommunityModel::where([['root_id', '=', $root_id], ['id', '=', $param['community_id']]])->findOrEmpty();
  1099. if ($community->isEmpty()) {
  1100. return json(['code'=> 0, 'data'=> [], 'msg'=> 'success']);
  1101. }
  1102. if ($param['type'] == 'customer') { // 信息量
  1103. // 有效客户总量
  1104. $subOrg = orgSubIds($org_id);
  1105. $valid_where[] = ['Employee.org_id', 'in', $subOrg];
  1106. $valid_where[] = ['Employee.community_disable', '=', 0];
  1107. $valid_where[] = ['Employee.state', '=', '在职'];
  1108. $valid_where[] = ['Employee.uid', '>', 0];
  1109. $valid_where[] = ['Customer.community_name', '=', $community['name']];
  1110. if ($search_date) {
  1111. $valid_where[] = ['Customer.sign_time', 'between', [$start_date, $end_date]];
  1112. }
  1113. if ($param['employee_id']) {
  1114. $valid_where[] = ['Customer.employee_id', '=', $param['employee_id']];
  1115. }
  1116. // 有效客户id
  1117. $customer_ids = Db::view('Employee')
  1118. ->view('Customer', 'id', 'Customer.employee_id=Employee.id')
  1119. ->where($valid_where)
  1120. ->order('Customer.sign_time desc')
  1121. ->column('Customer.id');
  1122. // 无效的客户id
  1123. $invalid_where[] = ['Employee.org_id', 'in', $subOrg];
  1124. $invalid_where[] = ['Employee.community_disable', '=', 0];
  1125. $invalid_where[] = ['Employee.state', '=', '在职'];
  1126. $invalid_where[] = ['Employee.uid', '>', 0];
  1127. $invalid_where[] = ['Customer.community_name', '=', $community['name']];
  1128. if ($search_date) {
  1129. $invalid_where[] = ['CustomerInvalidLog.cus_addtime', 'between', [$start_date, $end_date]];
  1130. }
  1131. if ($param['employee_id']) {
  1132. $invalid_where[] = ['CustomerInvalidLog.employee_id', '=', $param['employee_id']];
  1133. }
  1134. $i_customer_ids = Db::view('Employee')
  1135. ->view('CustomerInvalidLog', 'id iid', 'CustomerInvalidLog.employee_id=Employee.id')
  1136. ->view('Customer', 'id', 'Customer.id=CustomerInvalidLog.customer_id')
  1137. ->where($invalid_where)
  1138. ->order('Customer.sign_time desc')
  1139. ->column('Customer.id');
  1140. $all_ids = array_values(array_unique(array_merge($customer_ids, $i_customer_ids)));
  1141. $count = count($all_ids);
  1142. $page_customer_id = array_slice($all_ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  1143. // 见面状态
  1144. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  1145. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  1146. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  1147. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  1148. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  1149. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1150. $list = Customer::with(['employee', 'designer', 'visitLog'=> function($query) use ($visit_state) {
  1151. $query->where([['state', 'in', $visit_state]])->order('confirm_date asc')->field('id,customer_id,confirm_date,state');
  1152. }])->where('id', 'in', $page_customer_id)->select()->toArray();
  1153. $new_list = [];
  1154. foreach ($list as $k => $v) {
  1155. $one = [
  1156. 'id'=> $v['id'],
  1157. 'name'=> $v['name'],
  1158. 'community_name'=> $v['community_name'],
  1159. 'area'=> $v['square'],
  1160. 'employee_name'=> !empty($v['employee']) ? $v['employee']['name'] : '',
  1161. 'designer_name'=> !empty($v['designer']) ? $v['designer']['name'] : '',
  1162. 'sign_time'=> $v['sign_time'],
  1163. 'state'=> $v['state'],
  1164. 'first_visit_time'=> '',
  1165. 'deposit_time'=> ''
  1166. ];
  1167. if (!empty($v['visitLog'])) {
  1168. $first_visit_time = '';
  1169. $deposit_time = '';
  1170. foreach ($v['visitLog'] as $kk =>$vv) {
  1171. if (empty($first_visit_time)) {
  1172. $first_visit_time = $vv['confirm_date'];
  1173. }
  1174. if (empty($deposit_time) && in_array($vv['state'], $state4)) {
  1175. $deposit_time = $vv['confirm_date'];
  1176. }
  1177. }
  1178. $one['first_visit_time'] = $first_visit_time;
  1179. $one['deposit_time'] = $deposit_time;
  1180. }
  1181. $new_list[] = $one;
  1182. }
  1183. return json(['code'=> 0, 'data'=> $new_list, 'msg'=> 'success', 'count'=> $count]);
  1184. } elseif (in_array($param['type'], ['visit', 'deposit', 'signed'])) { //见面
  1185. // 搜索状态
  1186. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  1187. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  1188. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  1189. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  1190. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  1191. switch ($param['type']) {
  1192. case 'visit':
  1193. $search_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1194. break;
  1195. case 'deposit':
  1196. $search_state = $state4;
  1197. break;
  1198. case 'signed':
  1199. $search_state = $state5;
  1200. break;
  1201. default:
  1202. $search_state = '';
  1203. break;
  1204. }
  1205. $subOrg = orgSubIds($org_id);
  1206. $s_where[] = ['Customer.community_name', '=', $community['name']];
  1207. if ($search_date) {
  1208. $s_where[] = ['CustomerVisitLog.confirm_date', 'between', [$start_date, $end_date]];
  1209. }
  1210. if ($param['employee_id']) {
  1211. $s_where[] = ['CustomerVisitLog.customer_employee_id', '=', $community['employee_id']];
  1212. }
  1213. $s_where[] = ['CustomerVisitLog.org_id', 'in', $subOrg];
  1214. $s_where[] = ['CustomerVisitLog.state', 'in', $search_state];
  1215. $ids = Db::view('Customer')
  1216. ->view('CustomerVisitLog', 'id lid', 'CustomerVisitLog.customer_id=Customer.id')
  1217. ->where($s_where)
  1218. ->order('Customer.sign_time desc')
  1219. ->column('Customer.id');
  1220. $count = count($ids);
  1221. $page_customer_id = array_slice($ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  1222. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1223. $list = Customer::with(['employee', 'designer', 'visitLog'=> function($query) use ($visit_state) {
  1224. $query->where([['state', 'in', $visit_state]])->order('confirm_date asc')->field('id,customer_id,confirm_date,state');
  1225. }])->where('id', 'in', $page_customer_id)->select()->toArray();
  1226. $new_list = [];
  1227. foreach ($list as $k => $v) {
  1228. $one = [
  1229. 'id'=> $v['id'],
  1230. 'name'=> $v['name'],
  1231. 'community_name'=> $v['community_name'],
  1232. 'area'=> $v['square'],
  1233. 'employee_name'=> !empty($v['employee']) ? $v['employee']['name'] : '',
  1234. 'designer_name'=> !empty($v['designer']) ? $v['designer']['name'] : '',
  1235. 'sign_time'=> $v['sign_time'],
  1236. 'state'=> $v['state'],
  1237. 'first_visit_time'=> '',
  1238. 'deposit_time'=> ''
  1239. ];
  1240. if (!empty($v['visitLog'])) {
  1241. $first_visit_time = '';
  1242. $deposit_time = '';
  1243. foreach ($v['visitLog'] as $kk =>$vv) {
  1244. if (empty($first_visit_time)) {
  1245. $first_visit_time = $vv['confirm_date'];
  1246. }
  1247. if (empty($deposit_time) && in_array($vv['state'], $state4)) {
  1248. $deposit_time = $vv['confirm_date'];
  1249. }
  1250. }
  1251. $one['first_visit_time'] = $first_visit_time;
  1252. $one['deposit_time'] = $deposit_time;
  1253. }
  1254. $new_list[] = $one;
  1255. }
  1256. return json(['code'=> 0, 'data'=> $new_list, 'msg'=> 'success', 'count'=> $count]);
  1257. }
  1258. } elseif ($param['module'] == 'employee') {
  1259. // 以员工为主线
  1260. $subOrg = orgSubIds($org_id);
  1261. $employee = Employee::where([['org_id', 'in', $subOrg], ['id', '=', $param['employee_id']]])->findOrEmpty();
  1262. if ($employee->isEmpty()) {
  1263. return json(['code'=> 0, 'data'=> [], 'msg'=> 'success', 'count'=> 0]);
  1264. }
  1265. if ($param['community_id']) {
  1266. $community = CommunityModel::where([['root_id', '=', $root_id], ['id', '=', $param['community_id']]])->findOrEmpty();
  1267. if ($community->isEmpty()) {
  1268. return json(['code'=> 0, 'data'=> [], 'msg'=> 'success', 'count'=> 0]);
  1269. }
  1270. }
  1271. if ($param['type'] == 'customer') { // 信息量
  1272. // 有效客户总量
  1273. $valid_where[] = ['employee_id', '=', $param['employee_id']];
  1274. if ($search_date) {
  1275. $valid_where[] = ['sign_time', 'between', [$start_date, $end_date]];
  1276. }
  1277. if ($param['community_id']) {
  1278. $valid_where[] = ['community_name', '=', $community['name']];
  1279. }
  1280. // 有效客户id
  1281. $customer_ids = Customer::where($valid_where)->column('id');
  1282. // 无效的客户id
  1283. $invalid_where[] = ['CustomerInvalidLog.employee_id', '=', $param['employee_id']];
  1284. if ($search_date) {
  1285. $invalid_where[] = ['CustomerInvalidLog.cus_addtime', 'between', [$start_date, $end_date]];
  1286. }
  1287. if ($param['community_id']) {
  1288. $invalid_where[] = ['Customer.community_name', '=', $community['name']];
  1289. }
  1290. $i_customer_ids = Db::view('Customer')
  1291. ->view('CustomerInvalidLog', 'id iid', 'CustomerInvalidLog.customer_id=Customer.id')
  1292. ->where($invalid_where)
  1293. ->order('Customer.sign_time desc')
  1294. ->column('Customer.id');
  1295. $all_ids = array_values(array_unique(array_merge($customer_ids, $i_customer_ids)));
  1296. $count = count($all_ids);
  1297. $page_customer_id = array_slice($all_ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  1298. // 见面状态
  1299. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  1300. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  1301. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  1302. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  1303. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  1304. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1305. $list = Customer::with(['employee', 'designer', 'visitLog'=> function($query) use ($visit_state) {
  1306. $query->where([['state', 'in', $visit_state]])->order('confirm_date asc')->field('id,customer_id,confirm_date,state');
  1307. }])->where('id', 'in', $page_customer_id)->select()->toArray();
  1308. $new_list = [];
  1309. foreach ($list as $k => $v) {
  1310. $one = [
  1311. 'id'=> $v['id'],
  1312. 'name'=> $v['name'],
  1313. 'community_name'=> $v['community_name'],
  1314. 'area'=> $v['square'],
  1315. 'employee_name'=> !empty($v['employee']) ? $v['employee']['name'] : '',
  1316. 'designer_name'=> !empty($v['designer']) ? $v['designer']['name'] : '',
  1317. 'sign_time'=> $v['sign_time'],
  1318. 'state'=> $v['state'],
  1319. 'first_visit_time'=> '',
  1320. 'deposit_time'=> ''
  1321. ];
  1322. if (!empty($v['visitLog'])) {
  1323. $first_visit_time = '';
  1324. $deposit_time = '';
  1325. foreach ($v['visitLog'] as $kk =>$vv) {
  1326. if (empty($first_visit_time)) {
  1327. $first_visit_time = $vv['confirm_date'];
  1328. }
  1329. if (empty($deposit_time) && in_array($vv['state'], $state4)) {
  1330. $deposit_time = $vv['confirm_date'];
  1331. }
  1332. }
  1333. $one['first_visit_time'] = $first_visit_time;
  1334. $one['deposit_time'] = $deposit_time;
  1335. }
  1336. $new_list[] = $one;
  1337. }
  1338. return json(['code'=> 0, 'data'=> $new_list, 'msg'=> 'success', 'count'=> $count]);
  1339. } elseif (in_array($param['type'], ['visit', 'deposit', 'signed'])) { //见面
  1340. // 搜索状态
  1341. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  1342. $state2 = CustomerVisitLog::changeState('已量房', 'chaos');
  1343. $state3 = CustomerVisitLog::changeState('已到场', 'chaos');
  1344. $state4 = CustomerVisitLog::changeState('已交定', 'chaos');
  1345. $state5 = CustomerVisitLog::changeState('已签单', 'chaos');
  1346. switch ($param['type']) {
  1347. case 'visit':
  1348. $search_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1349. break;
  1350. case 'deposit':
  1351. $search_state = $state4;
  1352. break;
  1353. case 'signed':
  1354. $search_state = $state5;
  1355. break;
  1356. default:
  1357. $search_state = '';
  1358. break;
  1359. }
  1360. $s_where[] = ['CustomerVisitLog.customer_employee_id', '=', $param['employee_id']];
  1361. if ($search_date) {
  1362. $s_where[] = ['CustomerVisitLog.confirm_date', 'between', [$start_date, $end_date]];
  1363. }
  1364. if ($param['community_id']) {
  1365. $s_where[] = ['Customer.community_name', '=', $community['name']];
  1366. }
  1367. $s_where[] = ['CustomerVisitLog.state', 'in', $search_state];
  1368. $ids = Db::view('Customer')
  1369. ->view('CustomerVisitLog', 'id lid', 'CustomerVisitLog.customer_id=Customer.id')
  1370. ->where($s_where)
  1371. ->group('Customer.id')
  1372. ->order('Customer.sign_time desc')
  1373. ->column('Customer.id');
  1374. $count = count($ids);
  1375. $page_customer_id = array_slice($ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  1376. $visit_state = array_merge($state1, $state2, $state3, $state4, $state5);
  1377. $list = Customer::with(['employee', 'designer', 'visitLog'=> function($query) use ($visit_state) {
  1378. $query->where([['state', 'in', $visit_state]])->order('confirm_date asc')->field('id,customer_id,confirm_date,state');
  1379. }])->where('id', 'in', $page_customer_id)->select()->toArray();
  1380. $new_list = [];
  1381. foreach ($list as $k => $v) {
  1382. $one = [
  1383. 'id'=> $v['id'],
  1384. 'name'=> $v['name'],
  1385. 'community_name'=> $v['community_name'],
  1386. 'area'=> $v['square'],
  1387. 'employee_name'=> !empty($v['employee']) ? $v['employee']['name'] : '',
  1388. 'designer_name'=> !empty($v['designer']) ? $v['designer']['name'] : '',
  1389. 'sign_time'=> $v['sign_time'],
  1390. 'state'=> $v['state'],
  1391. 'first_visit_time'=> '',
  1392. 'deposit_time'=> ''
  1393. ];
  1394. if (!empty($v['visitLog'])) {
  1395. $first_visit_time = '';
  1396. $deposit_time = '';
  1397. foreach ($v['visitLog'] as $kk =>$vv) {
  1398. if (empty($first_visit_time)) {
  1399. $first_visit_time = $vv['confirm_date'];
  1400. }
  1401. if (empty($deposit_time) && in_array($vv['state'], $state4)) {
  1402. $deposit_time = $vv['confirm_date'];
  1403. }
  1404. }
  1405. $one['first_visit_time'] = $first_visit_time;
  1406. $one['deposit_time'] = $deposit_time;
  1407. }
  1408. $new_list[] = $one;
  1409. }
  1410. return json(['code'=> 0, 'data'=> $new_list, 'msg'=> 'success', 'count'=> $count]);
  1411. }
  1412. } else {
  1413. return json(['code'=> 0, 'data'=> [], 'count'=> 0, 'msg'=> 'success']);
  1414. }
  1415. }
  1416. //获取设计师列表
  1417. private function get_designer()
  1418. {
  1419. //设计师获取
  1420. $w[] = ['path', 'like', request()->empcrm->root_id . '-%'];
  1421. $w[] = ['org_type', '=', 2];
  1422. $orgs = Org::where($w)->column('id');
  1423. $list = Employee::where([['org_id', 'in', $orgs], ['state', '=', '在职'], ['show', '=', 0]])->field('id,name,initials s')->order('s asc')->select()->toArray();
  1424. return $list;
  1425. }
  1426. //公用列表筛选
  1427. public function screen()
  1428. {
  1429. $request = request();
  1430. $root_id = $request->empcrm->root_id;
  1431. $empid = $request->empcrm->id;
  1432. $is_manager = $request->empcrm->is_manager;
  1433. $team_orgs = [$request->empcrm->org_id];
  1434. if($is_manager ==1){
  1435. $team_orgs = orgSubIds($request->empcrm->org_id);
  1436. //$org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0]])->column('id');
  1437. }
  1438. $soudata = CustomerSource::field('id,source as name')->where('root_id', $root_id)->select()->toArray();
  1439. View::assign('soudata', $soudata);
  1440. $list = $this->get_designer();
  1441. if (!empty($list)) {
  1442. // $list = hanziInitsort($list, 'name');
  1443. $sort = array_column($list, 's');
  1444. sort($sort);
  1445. array_multisort($sort, SORT_ASC, $list);
  1446. $sort = array_unique($sort);
  1447. $list = ['sort' => $sort, 'arr' => $list];
  1448. }else{
  1449. $list = ['sort' =>[], 'arr' =>[]];
  1450. }
  1451. View::assign('designers', $list);
  1452. //客户等级
  1453. $level=CustomerPortraitField::with(['select'])->where([['root_id','=',$root_id],['keyname','=','level']])->find()->toArray();
  1454. View::assign('level', $level['select']);
  1455. //部门所有员工
  1456. $employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->field('id,name')->select()->toArray();
  1457. View::assign('employee_list', $employee);
  1458. View::assign('empid', $empid);
  1459. $customer_type = [['id'=>1,'name'=>'资源库'],['id'=>2,'name'=>'自建'],['id'=>3,'name'=>'活动'],['id'=>4,'name'=>'装修推荐官']];
  1460. View::assign('customer_type',$customer_type);
  1461. }
  1462. //已交定列表
  1463. public function jiaoding_list()
  1464. {
  1465. $request = request();
  1466. $root_id = $request->empcrm->root_id;
  1467. $empid = $request->empcrm->id;
  1468. $is_manager = $request->empcrm->is_manager;
  1469. $org_employee = [$empid];
  1470. if($is_manager ==1){
  1471. $team_orgs = orgSubIds($request->empcrm->org_id);
  1472. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  1473. }
  1474. if (!$request->isAjax()) {
  1475. $this->screen();
  1476. return View::fetch();
  1477. }
  1478. $param = $request->only(['page'=>1, 'limit'=>10, 'employee_id', 'level','source_id','designer_id','keyname','date','times'=> 0,'customer_type']);
  1479. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $org_employee = [$param['employee_id']];
  1480. $condition[] = ['employee_id', 'in', $org_employee];
  1481. $condition[] = ['state', 'not in',Customer::changeState('无效', 'chaos')];
  1482. if(!empty($param['level'])) $condition[] = ['level','=',$param['level']];
  1483. if(!empty($param['source_id'])) $condition[] = ['source_id','=',$param['source_id']];
  1484. if(!empty($param['designer_id'])) $condition[] = ['designer_id','=',$param['designer_id']];
  1485. if(!empty($param['keyname'])) $condition[] = ['name|community_name','like','%'.$param['keyname'].'%'];
  1486. $order = isset($param['order']) ? $param['order'] : 'id desc';
  1487. if($param['times'] == 1) $order = 'sign_time asc';
  1488. if($param['times'] == 2) $order = 'sign_time desc';
  1489. $page = intval($param['page']);
  1490. $limit = intval($param['limit']);
  1491. $vslogid = CustomerVisitLog::where([['customer_employee_id','in',$org_employee],['state','in',CustomerVisitLog::changeState('已交定','chaos')]])->column('customer_id');
  1492. if(!empty($param['date'])){
  1493. $time = explode(' - ',$param['date']);
  1494. $vslogid = CustomerVisitLog::where([['customer_employee_id','in',$org_employee],['state','in',CustomerVisitLog::changeState('已交定','chaos')],['confirm_date','between',[$time[0].' 00:00:00',$time[1].' 23:59:59']]])->column('customer_id');
  1495. }
  1496. $condition[] = ['id', 'in', $vslogid];
  1497. //客户种类 资源库,活动,经纪人,自建
  1498. if (!empty($param['customer_type'])) {
  1499. $gather = [
  1500. 1=>[['crm_res_id','not null',null]],//'资源库'
  1501. 2=>[['crm_res_id','null',null],['remark','not like','%活动报名建档%'],['agents_id','null',null]],//'自建'
  1502. 3=>[['remark','like','%活动报名建档%']],//'活动'
  1503. 4=>[['agents_id','>',0]]//'经纪人'
  1504. ];
  1505. $arr = explode(',',$param['customer_type']);
  1506. $whereOr = [];
  1507. foreach ($arr as $val) {
  1508. if (isset($gather[$val])) {
  1509. //$whereOr[] = array_merge($condition,$gather[$val]);
  1510. $whereOr[] = $gather[$val];
  1511. }
  1512. }
  1513. if (!empty($whereOr)) {
  1514. $new_cids = Customer::where($condition)->where(function($query) use ($whereOr){
  1515. $query->whereOr($whereOr);
  1516. })->column('id');
  1517. unset($condition);
  1518. $condition[] = ['id','in',$new_cids];
  1519. }else{
  1520. //无效条件
  1521. return json(['code' => 0, 'data' => [], 'count' => 0]);
  1522. }
  1523. }
  1524. $data = $this->selCustomer($condition,$page,$limit,$order,$root_id);
  1525. $no_visit_state = ['未到访', '待确认'];
  1526. $visit_state = ['已到店', '已量房', '已到场', '已签单', '已转单', '已卖卡'];
  1527. foreach($data as $key=>$val){
  1528. $data[$key]['customer_type'] = $val['crm_res_id'] ? '资源库' : ($val['remark'] == '活动报名建档' ? '活动' : ($val['agents_id'] ? '装修推荐官' : '自建'));
  1529. $data[$key]['jiaoding_day'] = !empty($val['fisttime']) && strtotime($val['jiaoding_time']) > strtotime($val['fisttime']) ? ceil((strtotime($val['jiaoding_time']) - strtotime($val['fisttime']))/86400) : ceil((strtotime($val['jiaoding_time']) - strtotime($val['addtime']))/86400);
  1530. $data[$key]['xinjushang'] = $request->empcrm['xinjushang'];
  1531. // 有'已到店', '已量房', '已到场'状态的话不显示未到访
  1532. $state = explode(',', $val['state']);
  1533. $jiaoji = array_intersect($visit_state, $state);
  1534. $no_jiaoji = array_intersect($no_visit_state, $state);
  1535. if (count($no_jiaoji) == 2) { // 有未到访、待确认两个状态
  1536. $state = ['未到访'];
  1537. }
  1538. if (count($state) > 1 && count($jiaoji) > 0) {
  1539. $state = array_diff($state, $no_visit_state);
  1540. }
  1541. $data[$key]['state'] = implode(',', $state);
  1542. }
  1543. $count = Customer::where($condition)->count();
  1544. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  1545. }
  1546. //业绩页面(已签单)
  1547. public function achment_list()
  1548. {
  1549. $request = request();
  1550. $root_id = $request->empcrm->root_id;
  1551. $empid = $request->empcrm->id;
  1552. $is_manager = $request->empcrm->is_manager;
  1553. $org_employee = [$empid];
  1554. if($is_manager ==1){
  1555. $team_orgs = orgSubIds($request->empcrm->org_id);
  1556. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  1557. }
  1558. if (!$request->isAjax()) {
  1559. $this->screen();
  1560. return View::fetch();
  1561. }
  1562. $param = $request->only(['page'=>1, 'limit'=>10, 'employee_id', 'level','source_id','designer_id','keyname','date','customer_type']);
  1563. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $org_employee = [$param['employee_id']];
  1564. $condition[] = ['employee_id', 'in', $org_employee];
  1565. $condition[] = ['signed_money', '<>', 0];
  1566. $condition[] = ['state', 'not in',Customer::changeState('无效', 'chaos')];
  1567. if(!empty($param['level'])) $condition[] = ['level','=',$param['level']];
  1568. if(!empty($param['source_id'])) $condition[] = ['source_id','=',$param['source_id']];
  1569. if(!empty($param['designer_id'])) $condition[] = ['designer_id','=',$param['designer_id']];
  1570. if(!empty($param['keyname'])) $condition[] = ['name|community_name','like','%'.$param['keyname'].'%'];
  1571. $order = isset($param['order']) ? $param['order'] : 'id desc';
  1572. $page = intval($param['page']);
  1573. $limit = intval($param['limit']);
  1574. $vslogid = CustomerVisitLog::where([['customer_employee_id','in',$org_employee],['state','in',CustomerVisitLog::changeState('已签单','chaos')]])->column('customer_id');
  1575. if(!empty($param['date'])){
  1576. $time = explode(' - ',$param['date']);
  1577. $vslogid = CustomerVisitLog::where([['customer_employee_id','in',$org_employee],['state','in',CustomerVisitLog::changeState('已签单','chaos')],['confirm_date','between',[$time[0].' 00:00:00',$time[1].' 23:59:59']]])->column('customer_id');
  1578. }
  1579. $condition[] = ['id', 'in', $vslogid];
  1580. //客户种类 资源库,活动,经纪人,自建
  1581. if (!empty($param['customer_type'])) {
  1582. $gather = [
  1583. 1=>[['crm_res_id','not null',null]],//'资源库'
  1584. 2=>[['crm_res_id','null',null],['remark','not like','%活动报名建档%'],['agents_id','null',null]],//'自建'
  1585. 3=>[['remark','like','%活动报名建档%']],//'活动'
  1586. 4=>[['agents_id','>',0]]//'经纪人'
  1587. ];
  1588. $arr = explode(',',$param['customer_type']);
  1589. $whereOr = [];
  1590. foreach ($arr as $val) {
  1591. if (isset($gather[$val])) {
  1592. //$whereOr[] = array_merge($condition,$gather[$val]);
  1593. $whereOr[] = $gather[$val];
  1594. }
  1595. }
  1596. if (!empty($whereOr)) {
  1597. $new_cids = Customer::where($condition)->where(function($query) use ($whereOr){
  1598. $query->whereOr($whereOr);
  1599. })->column('id');
  1600. unset($condition);
  1601. $condition[] = ['id','in',$new_cids];
  1602. }else{
  1603. //无效条件
  1604. return json(['code' => 0, 'data' => [], 'count' => 0]);
  1605. }
  1606. }
  1607. $data = $this->selCustomer($condition,$page,$limit,$order,$root_id);
  1608. foreach($data as $key=>$val){
  1609. $sign=[];
  1610. if(!empty($val['sign'])) $sign = $val['sign'];
  1611. $data[$key]['dingqian_day'] = !empty($sign) && !empty($val['jiaoding_time']) ? round((strtotime($sign['confirm_date']) - strtotime($val['jiaoding_time']))/86400) : 0;
  1612. $data[$key]['daoqian_day'] = !empty($sign) && !empty($val['fisttime'])? round((strtotime($sign['confirm_date']) - strtotime($val['fisttime']))/86400) : 0;
  1613. $data[$key]['all_money'] = !empty($sign) ? $sign['money'] : 0;
  1614. $data[$key]['pf_money'] = !empty($val['square']) && !empty($sign) ? round(($sign['money'])/$val['square'],2) : 0;
  1615. $data[$key]['customer_type'] = $val['crm_res_id'] ? '资源库' : ($val['remark'] == '活动报名建档' ? '活动' : ($val['agents_id'] ? '装修推荐官' : '自建'));
  1616. }
  1617. $count = Customer::where($condition)->count();
  1618. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  1619. }
  1620. //搜索
  1621. public function search_list()
  1622. {
  1623. $request = request();
  1624. $root_id = $request->empcrm->root_id;
  1625. $empid = $request->empcrm->id;
  1626. $is_manager = $request->empcrm->is_manager;
  1627. $org_employee = [$empid];
  1628. if (!$request->isAjax()) {
  1629. //$this->screen();
  1630. return View::fetch();
  1631. }
  1632. $param = $request->only(['page'=>1, 'limit'=>10, 'keyname']);
  1633. if($is_manager == 1){
  1634. $team_orgs = orgSubIds($request->empcrm->org_id);
  1635. $empids = Employee::where([['root_id','=',$root_id],['org_id','in',$team_orgs],['community_disable','=',0]])->column('id');
  1636. $condition[] = ['employee_id', 'in', $empids];
  1637. }else{
  1638. $condition[] = ['employee_id', '=', $empid];
  1639. $condition[] = ['community_disable', '=', 0];
  1640. }
  1641. $order = isset($param['order']) ? $param['order'] : 'id desc';
  1642. $list = Customer::where($condition)->field('id,name,community_name,phone,employee_id,designer_id')->select()->toArray();
  1643. $customersIdList = [];
  1644. if(!empty($param['keyname'])){
  1645. foreach($list as $key=>$val){
  1646. $str = $val['name'] . $val['community_name'] . $val['phone'];
  1647. if (strpos($str, trim($param['keyname'])) !== false) $customersIdList[] = $val['id'];
  1648. }
  1649. }
  1650. $new = array_slice($customersIdList, ($param['page'] - 1) * $param['limit'], $param['limit']);
  1651. $cond[] = ['id','in',$new];
  1652. $data = $this->search_selone($cond,$order);
  1653. $count = count($customersIdList);
  1654. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  1655. }
  1656. //已签单或已交定客户详情
  1657. public function deposit_sign_detail()
  1658. {
  1659. $request = request();
  1660. $root_id = $request->empcrm->root_id;
  1661. $empid = $request->empcrm->id;
  1662. $param = $this->request->only(['cid']);
  1663. $ms = $this->seLemp($param['cid'],$empid);
  1664. $data = $ms->toArray();
  1665. $visitlog = $data['visitLog'];
  1666. if(!empty($visitlog)){
  1667. foreach($visitlog as $key=>$val){
  1668. $visitlog[$key]['empname'] = Employee::where('id',$val['employee_id'])->value('name');
  1669. $parr[] = $val['addtime'];
  1670. }
  1671. array_multisort($parr, SORT_ASC, $visitlog);
  1672. foreach($visitlog as $key=>$val){
  1673. if((count($visitlog)-1) > $key){
  1674. $visitlog[$key]['xt'] = round((strtotime($visitlog[$key+1]['addtime']) - strtotime($val['addtime']))/86400);
  1675. }
  1676. if((count($visitlog)-1) == $key){
  1677. $visitlog[$key]['xt'] = 0;
  1678. }
  1679. }
  1680. }
  1681. $data['visitLog'] = $visitlog;
  1682. View::assign('data', $data);
  1683. return View::fetch();
  1684. }
  1685. //搜索的单独查询
  1686. public function search_selone($condition,$order)
  1687. {
  1688. $request = request();
  1689. $root_id = $request->empcrm->root_id;
  1690. $empid = $request->empcrm->id;
  1691. $data = Customer::with(['employee', 'org', 'designer','source'])
  1692. ->withCount(['visitLog' => function ($query) {
  1693. $query->where([[CustomerVisitLog::changeState(['state', '=', '未到访'])]]);
  1694. }])
  1695. ->where($condition)
  1696. ->order($order)->select();
  1697. $data = $data->visible(['id', 'employee_id', 'name','designer_id', 'community_name', 'phone', 'level', 'state', 'square', 'revisit_time', 'addtime', 'last_contact_date', 'org_id', 'protected_to', 'is_resource', 'employee.name', 'org_name', 'designer.name', 'visit_log_count', 'activity_frequency_count','source_id','source.source', 'phone1', 'phone2','remark','crm_res_id','agents_id','house_delivery_time','first_visit_date','ext','transfer_info'])->toArray();
  1698. $setting = Setting::where([['name', '=', 'pubpool'], ['root_id', '=', $root_id]])->find();
  1699. if (!empty($setting)){
  1700. $setting_content = json_decode($setting['content'], true);
  1701. } else {
  1702. $setting_content = [];
  1703. }
  1704. foreach ($data as &$item) {
  1705. $item['un_protected'] = false;
  1706. if (!empty($item['protected_to']) && time() > strtotime($item['protected_to'])) {
  1707. $state_n = Customer::changeState($item['state'], 'n');
  1708. if (isset($setting_content[$state_n]['state']) && $setting_content[$state_n]['state'] == 1) {
  1709. $item['un_protected'] = true;
  1710. }
  1711. }
  1712. $item['square'] = floatval($item['square']);
  1713. $item['phone'] = substr_replace($item['phone'], '******', 3, 6);
  1714. $item['phone1'] = $item['phone1'] ? substr_replace($item['phone1'], '******', 3, 6) : '';
  1715. $item['phone2'] = $item['phone2'] ? substr_replace($item['phone2'], '******', 3, 6) : '';
  1716. $item['jiaofang'] = !empty($item['house_delivery_time'])?($item['house_delivery_time'] <= date('Y/m/d',time())?'现房':$item['house_delivery_time']):'';
  1717. $vlotime = CustomerVisitLog::where('customer_id',$item['id'])->order('addtime desc')->value('addtime');
  1718. $fisttime = CustomerVisitLog::where([['customer_id','=',$item['id']],['customer_employee_id','=',$item['employee_id']],[CustomerVisitLog::changeState(['state', '=', '确认到店'])]])->order('addtime asc')->value('addtime');
  1719. $jiaoding_time = CustomerVisitLog::where([['customer_id','=',$item['id']],['customer_employee_id','=',$item['employee_id']],[CustomerVisitLog::changeState(['state', '=', '已交定'])]])->order('addtime asc')->value('addtime');
  1720. $signorder_time = CustomerVisitLog::where([['customer_id','=',$item['id']],['customer_employee_id','=',$item['employee_id']],[CustomerVisitLog::changeState(['state', '=', '已签单'])]])->order('addtime asc')->value('addtime');
  1721. $item['jiaoding_time'] = $jiaoding_time ? $jiaoding_time :'';
  1722. $item['signorder_time'] = $signorder_time ? $signorder_time :'';
  1723. $item['fisttime'] = $fisttime ? $fisttime :'';
  1724. $item['time_status'] = $vlotime ? $this->uc_time_ago(date('Y-m-d',strtotime($vlotime))) :'';
  1725. $item['add_wechat'] = '否';
  1726. $item['sign_time'] = null;
  1727. if(!empty($item['ext'])){
  1728. $extdata=json_decode($item['ext'],true);
  1729. foreach($extdata as $key=>$val){
  1730. if(isset($val['keyname']) && $val['keyname']=='wechat' && !empty($val['value'])){
  1731. $add_wechat = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  1732. if($add_wechat == '有'){
  1733. $add_wechat = '是';
  1734. }
  1735. $item['add_wechat'] = $add_wechat;
  1736. }
  1737. if(isset($val['keyname']) && $val['keyname']=='sign_time' && !empty($val['value'])){
  1738. $item['sign_time'] = $val['value'];
  1739. }
  1740. }
  1741. }
  1742. }
  1743. return $data;
  1744. }
  1745. //公用查询列表
  1746. public function selCustomer($condition,$page,$limit,$order,$root_id)
  1747. {
  1748. $request = request();
  1749. $root_id = $request->empcrm->root_id;
  1750. $empid = $request->empcrm->id;
  1751. $is_manager = $request->empcrm->is_manager;
  1752. $path = Org::where([['pid','=',$request->empcrm->org_id]])->count();
  1753. if($page && $limit){
  1754. $data = Customer::with(['employee', 'org', 'designer','source','visitLog'=>function($query){
  1755. $query->field('id,customer_id,state,addtime,confirm_date,money')->order('addtime asc');
  1756. }])->withCount(['visitLog' => function ($query) {
  1757. $query->where([[CustomerVisitLog::changeState(['state', '=', '未到访'])]]);
  1758. }])->where($condition)->page($page, $limit)->order($order)->select();
  1759. }else{
  1760. $data = Customer::with(['employee', 'org', 'designer','source','visitLog'=>function($query){
  1761. $query->field('id,customer_id,state,addtime,confirm_date,money')->order('addtime asc');
  1762. }])->withCount(['visitLog' => function ($query) {
  1763. $query->where([[CustomerVisitLog::changeState(['state', '=', '未到访'])]]);
  1764. }])->where($condition)->order($order)->select();
  1765. }
  1766. $data = $data->visible(['designer_id','id', 'employee_id', 'name', 'introduce','community_name', 'phone', 'level', 'state', 'square', 'revisit_time', 'addtime', 'last_contact_date', 'org_id', 'protected_to', 'is_resource', 'employee.name', 'org_name', 'designer.name', 'visit_log_count', 'activity_frequency_count','source_id','source.source', 'phone1', 'phone2','remark','crm_res_id','agents_id','sign_time','house_delivery_time','first_visit_date','ext','transfer_info','deposit_money','signed_money','package_id','fresh','house_type','remark','employee_time', 'add_wechat_time','assigned_personnel','sign_time','reputation_gather','into_owner_group'])->toArray();
  1767. $setting = Setting::where([['name', '=', 'pubpool'], ['root_id', '=', $root_id]])->find();
  1768. if (!empty($setting)){
  1769. $setting_content = json_decode($setting['content'], true);
  1770. } else {
  1771. $setting_content = [];
  1772. }
  1773. $empids = !empty($data) ? array_column($data,'employee_id') : [];
  1774. $emporg = Employee::with(['org'=>function($query){
  1775. $query->field('id,name');
  1776. }])->where([['root_id','=',$root_id],['id','in',$empids]])->field('id,org_id')->select()->toArray();
  1777. $state1 = CustomerVisitLog::changeState('已到店','chaos');
  1778. $state2 = CustomerVisitLog::changeState('已交定','chaos');
  1779. $state3 = CustomerVisitLog::changeState('已签单','chaos');
  1780. $state4 = CustomerVisitLog::changeState('已量房','chaos');
  1781. $state5 = CustomerVisitLog::changeState('无效','chaos');
  1782. foreach ($data as &$item) {
  1783. $item['emporg'] = $item['source_name'] = $item['designer_name'] = $item['employee_name'] = '';
  1784. if (!empty($item['source'])){
  1785. $item['source_name'] = $item['source']['source'];
  1786. }
  1787. if (!empty($item['designer'])){
  1788. $item['designer_name'] = $item['designer']['name'];
  1789. }
  1790. if (!empty($item['employee'])){
  1791. $item['employee_name'] = $item['employee']['name'];
  1792. foreach($emporg as $p){
  1793. if($p['id'] == $item['employee_id']) $item['emporg'] = $p['org']['name'];
  1794. }
  1795. }
  1796. $item['un_protected'] = false;
  1797. if (!empty($item['protected_to']) && time() > strtotime($item['protected_to'])) {
  1798. $state_n = Customer::changeState($item['state'], 'n');
  1799. if (isset($setting_content[$state_n]['state']) && $setting_content[$state_n]['state'] == 1) {
  1800. $item['un_protected'] = true;
  1801. }
  1802. }
  1803. $item['last_invalid_time'] = $item['first_liangfang'] = $item['jiaoding_time'] = $item['sign'] = $item['fisttime'] = '';
  1804. if(!empty($item['visitLog'])){
  1805. //取最新的一条为客户的跟进时间
  1806. $item['last_contact_date'] = $item['visitLog'][count($item['visitLog'])-1]['addtime'];
  1807. $state = [];
  1808. foreach($item['visitLog'] as $k=>$v){
  1809. $state[$v['state']][] = $v;
  1810. }
  1811. foreach($state as $k=>$v){
  1812. if(in_array($k,$state1)) $item['fisttime'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  1813. if(in_array($k,$state4)) $item['first_liangfang'] = date('Y-m-d',strtotime($v[0]['addtime']));
  1814. if(in_array($k,$state2)){
  1815. $item['jiaoding_time'] = $v[0]['addtime'];
  1816. $item['jiaoding_money'] = $v[0]['money'];
  1817. }
  1818. if(in_array($k,$state3)){
  1819. $item['qiandan_time'] = $v[0]['addtime'];
  1820. $item['qiandan_money'] = $v[0]['money'];
  1821. $item['sign'] = $v[0];
  1822. }
  1823. if(in_array($k,$state5)) $item['last_invalid_time'] = $v[0]['addtime'];
  1824. }
  1825. }
  1826. $item['square'] = floatval($item['square']);
  1827. //$item['visitLog'] = CustomerVisitLog::where([['customer_employee_id','=',$item['employee_id']],['customer_id','=',$item['id']],['state','in',array_merge(CustomerVisitLog::changeState('待确认','chaos'),CustomerVisitLog::changeState('已到店','chaos'),CustomerVisitLog::changeState('已到场','chaos'),CustomerVisitLog::changeState('已交定','chaos'),CustomerVisitLog::changeState('已签单','chaos'))]])->group('state,customer_id')->field('state,id,customer_id')->order('addtime asc')->select()->toArray();
  1828. $item['phone'] = substr_replace($item['phone'], '******', 3, 6);
  1829. $item['phone1'] = $item['phone1'] ? substr_replace($item['phone1'], '******', 3, 6) : '';
  1830. $item['phone2'] = $item['phone2'] ? substr_replace($item['phone2'], '******', 3, 6) : '';
  1831. $houses = $item['house_type'];
  1832. if(!empty($item['house_type']) && $item['house_type'] == '期房') $houses = !empty($item['house_delivery_time'])?(str_replace('/','-',$item['house_delivery_time']) <= date('Y-m-d',time())?'现房':$item['house_delivery_time']):'期房';
  1833. $item['jiaofang'] = $houses;
  1834. $item['time_status'] = $item['last_contact_date'] ? $this->uc_time_ago($item['last_contact_date']) :'';
  1835. $item['allstate'] = null;
  1836. $item['package_name'] = !empty($item['package_id']) ? CustomerPackage::where('id',$item['package_id'])->value('name') :'';
  1837. $item['is_followup'] = 0;
  1838. $item['lognum'] = count($item['visitLog']);
  1839. if($is_manager==1 && empty($path)){
  1840. $item['is_followup'] = 1;
  1841. }
  1842. if($empid == $item['employee_id']){
  1843. $item['is_followup'] = 1;
  1844. }
  1845. $now_status = $item['state'];
  1846. if($now_status == '已签单' && $request->empcrm['xinjushang'] == 0) $now_status = '已转单';
  1847. if($now_status == '已交定' && $request->empcrm['xinjushang'] == 0) $now_status = '已签单';
  1848. $item['now_status'] = $now_status;
  1849. $item['state'] = '';
  1850. $allstate='';
  1851. if(!empty($item['visitLog'])){
  1852. $stain=[$now_status];
  1853. foreach($item['visitLog'] as $k=>$v){
  1854. if(!in_array($v['state'],['已交定','已签单','已到店','已量房','已到场','未到访','回访'])) continue;
  1855. if($v['state']=='回访') $v['state'] = '待确认';
  1856. if($v['state']=='已签单' && $request->empcrm['xinjushang'] == 0) $v['state'] = '已转单';
  1857. if($v['state']=='已交定' && $request->empcrm['xinjushang'] == 0) $v['state'] = '已签单';
  1858. if(!in_array($v['state'],$stain)){
  1859. $stain[] = $v['state'];
  1860. //$allstate.= $v['state'].',';
  1861. }
  1862. }
  1863. if(count($stain) > 1 && in_array('待确认',$stain)) $stain = array_diff($stain,['待确认']);
  1864. //$item['state'] = trim($allstate,',');
  1865. $item['state'] = implode(',',$stain);
  1866. if($now_status == '待确认') $item['state'] = '待确认';
  1867. }
  1868. $item['unit_number'] = '';
  1869. if(!empty($item['ext'])){
  1870. foreach(json_decode($item['ext'],true) as $k=>$v){
  1871. if(!empty($v['keyname']) && $v['keyname'] == 'unit_number' && !empty($v['value'])) $item['unit_number'] = $v['value'];
  1872. }
  1873. }
  1874. // 未跟进时间
  1875. $latest_visit_log = $item['last_contact_date'];
  1876. if (empty($latest_visit_log)) {
  1877. $no_visit_long = time() - strtotime($item['addtime']);
  1878. } else {
  1879. $no_visit_long = time() - strtotime($latest_visit_log);
  1880. }
  1881. $no_visit_day = ceil($no_visit_long / 24 / 3600);
  1882. $item['no_visit_day'] = $no_visit_day;
  1883. // 预计见面时间
  1884. $subscribe = CustomersSubscribe::where([['customer_id', '=', $item['id']], ['employee_id', '=', $item['employee_id']], ['state', '=', 0]])->order('subscribe_date desc')->find();
  1885. if (!empty($subscribe)) {
  1886. $item['subscribe_date'] = $subscribe['subscribe_date'];
  1887. } else {
  1888. $item['subscribe_date'] = '';
  1889. }
  1890. $assignIdList = !empty($item['assigned_personnel']) ? explode(',',$item['assigned_personnel']) : [];
  1891. if(!empty($item['designer_id']) && !empty($assignIdList)) $assignIdList = array_diff($assignIdList,[$item['designer_id']]);
  1892. $assign_list = Employee::where('id', 'in', $assignIdList)->column('name');
  1893. $item['assign_list'] = !empty($assign_list) ? implode(',',$assign_list) : '';
  1894. }
  1895. return $data;
  1896. }
  1897. public function uc_time_ago($ptime)
  1898. {
  1899. $ptime = strtotime($ptime);
  1900. $etime = strtotime(date('Y-m-d')) - $ptime;
  1901. switch ($etime) {
  1902. case $etime > 60 * 60 && $etime <= 24 * 60 * 60:
  1903. $msg = date('Ymd', $ptime) == date('Ymd', time()) ? '今天 ' : '昨天 ';
  1904. break;
  1905. case $etime > 24 * 60 * 60 && $etime <= 2 * 24 * 60 * 60:
  1906. $msg = date('Ymd', $ptime) + 1 == date('Ymd', time()) ? '昨天 ' : '前天 ';
  1907. break;
  1908. case $etime > 2 * 24 * 60 * 60 :
  1909. $msg = floor($etime / 86400).'天+';
  1910. break;
  1911. default:
  1912. $msg = date('Y-m-d H:i', $ptime);
  1913. }
  1914. return $msg;
  1915. }
  1916. /**
  1917. * 客户迁移
  1918. */
  1919. public function customerTransfer()
  1920. {
  1921. $request = request();
  1922. $root_id = $request->empcrm->root_id;
  1923. $empid = $request->empcrm->id;
  1924. $orgids = orgSubIds($root_id);
  1925. $param = $this->request->only(['customer_ids' => '', 'employeeid']);
  1926. $arr = explode(',', $param['customer_ids']);
  1927. //查询手机号
  1928. $phone = Customer::where([['employee_id','=', $param['employeeid']],['org_id','in',$orgids]])->column('phone,phone1,phone2');
  1929. $phones = [];
  1930. foreach ($phone as $v) {
  1931. $phones = array_merge($phones, array_values($v));
  1932. }
  1933. $phones = array_filter($phones);
  1934. $customers = Customer::where([['id', 'in', $arr],['org_id','in',$orgids]])->column('id,name,phone,phone1,phone2');
  1935. $repeat = $no_repeat = [];
  1936. foreach ($customers as $v2) {
  1937. $l_phone = array_filter([$v2['phone'], $v2['phone1'], $v2['phone2']]);
  1938. empty(array_intersect($l_phone, $phones)) ? $no_repeat[] = $v2['id'] : $repeat[] = $v2['name'];
  1939. }
  1940. if ($no_repeat) {
  1941. $org_id = Employee::where('id', $param['employeeid'])->value('org_id');
  1942. Customer::where([['id', 'in', $no_repeat]])->update(['employee_id' => $param['employeeid'], 'org_id' => $org_id]);
  1943. Customer::where([['id', 'in', $no_repeat]])->update(['transfer_info' => json_encode(['transfer_empid'=>$empid,'transfer_time'=>date('Y-m-d H:i:s'),'transfer_empname'=>$request->empcrm->name])]);
  1944. //修改转移的客户的跟进记录的customer_employee_id为新员工的id
  1945. CustomerVisitLog::where([['customer_id','in',$no_repeat],['org_id','in',$orgids]])->update(['customer_employee_id'=>$param['employeeid'],'customer_org_id'=>$org_id]);
  1946. }
  1947. if ($repeat) return json(['code' => 1, 'msg' => '分派失败:员工名下已存在客户[' . implode(',', $repeat) . ']的联系方式']);
  1948. return json(['code' => 0, 'msg' => '分派完成']);
  1949. }
  1950. //分派
  1951. public function assignment_list()
  1952. {
  1953. $request = request();
  1954. $root_id = $request->empcrm->root_id;
  1955. $empid = $request->empcrm->id;
  1956. $is_manager = $request->empcrm->is_manager;
  1957. $org_employee = [$empid];
  1958. if($is_manager ==1){
  1959. $team_orgs = orgSubIds($request->empcrm->org_id);
  1960. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  1961. }
  1962. if (!$request->isAjax()) {
  1963. $this->screen();
  1964. $newteam_orgs = orgSubIds($request->empcrm->org_id);
  1965. $assignemp_list = Employee::where([['org_id', 'in', $newteam_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->field('id,name')->select()->toArray();
  1966. View::assign('assignemp_list',$assignemp_list);
  1967. View::assign('is_manager',$is_manager);
  1968. return View::fetch();
  1969. }
  1970. $param = $request->only(['page'=>1, 'limit'=>10, 'employee_id', 'level','source_id','designer_id','keyname']);
  1971. if(!empty($param['employee_id']) && $is_manager ==1) $org_employee = [$param['employee_id']];
  1972. $condition[] = ['employee_id', 'in', $org_employee];
  1973. $condition[] = ['transfer_info', '<>',''];
  1974. $order = isset($param['order']) ? $param['order'] : 'updatetime desc';
  1975. $page = intval($param['page']);
  1976. $limit = intval($param['limit']);
  1977. if(!empty($param['level'])) $condition[] = ['level','=',$param['level']];
  1978. if(!empty($param['source_id'])) $condition[] = ['source_id','=',$param['source_id']];
  1979. if(!empty($param['designer_id'])) $condition[] = ['designer_id','=',$param['designer_id']];
  1980. if(!empty($param['keyname'])) $condition[] = ['name|community_name','like','%'.$param['keyname'].'%'];
  1981. $data = $this->selCustomer($condition,$page,$limit,$order,$root_id);
  1982. foreach($data as $key=>$val){
  1983. $transfer = json_decode($val['transfer_info'],true);
  1984. $data[$key]['transfer_time'] = $transfer['transfer_time'];
  1985. $data[$key]['transfer_name'] = $transfer['transfer_empname'];
  1986. }
  1987. $count = Customer::where($condition)->count();
  1988. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  1989. }
  1990. /**
  1991. * 公海获取客户
  1992. * customer_id来源:业务员获取(int)、报备录入时查询公海存在自动获取(逗号分隔字符串)
  1993. */
  1994. public function fetchpoolitem()
  1995. {
  1996. $request = request();
  1997. $root_id = $request->empcrm->root_id;
  1998. $employee_id = $request->empcrm->id;
  1999. $orgids = orgSubIds($root_id);
  2000. $param = $this->request->only(['cid','designer_id']);
  2001. if (!$request->isAjax()) {
  2002. $this->screen();
  2003. $data = $this->cusdet_noemp($param['cid']);
  2004. View::assign('data',$data);
  2005. return View::fetch();
  2006. }
  2007. // 设计师能否报备、获取客户
  2008. $de_where[] = ['root_id', '=', $root_id];
  2009. $de_where[] = ['name', '=', 'designer_get_customer'];
  2010. $info_de_where = Setting::where($de_where)->findOrEmpty();
  2011. if (!$info_de_where->isEmpty() && request()->empcrm->org_type == 2) {
  2012. if ((int)$info_de_where['content'] != 1) {
  2013. return json(['code' => 1, 'msg' => '您的身份为设计师,无法获取客户']);
  2014. }
  2015. }
  2016. //$customer_id = explode(',', $param['customer_id']);
  2017. $customer_id = $param['cid'];
  2018. $otheremp = Customer::where([['org_id','in',$orgids],['id', 'in', $customer_id], ['employee_id', '=', NULL]])->field('employee_id,phone,phone1,phone2')->select();
  2019. if (empty($otheremp)) {
  2020. return json(['code' => 1, 'msg' => '客户已被人抢先获取。记得下次抓住机会。']);
  2021. }
  2022. //判断名下是否存在该客户手机号,存在则不可获取
  2023. foreach ($otheremp as $item) {
  2024. $phone_arr = [];
  2025. !empty($item['phone']) ? $phone_arr[] = cypherphone($item['phone']) : '';
  2026. !empty($item['phone1']) ? $phone_arr[] = cypherphone($item['phone1']) : '';
  2027. !empty($item['phone2']) ? $phone_arr[] = cypherphone($item['phone2']) : '';
  2028. $phone_arr = array_filter($phone_arr);
  2029. $haveCrm = Customer::where([['employee_id', '=', $employee_id], ['phone|phone1|phone2', 'in', $phone_arr]])->count();
  2030. if ($haveCrm) {
  2031. return json(['code' => 1, 'msg' => '您名下已存在该客户信息。']);
  2032. }
  2033. }
  2034. if (Customer::where([['id', 'in', $customer_id]])->update(['employee_id' => $employee_id, 'org_id' => $this->request->empcrm->org_id, 'state' => 0, 'remark' => '公海获取', 'fresh' => 1, 'designer_id' => null,'employee_time'=>date('Y-m-d H:i:s')])) {
  2035. $saveAll = [];
  2036. $saveAll[] = [
  2037. 'customer_id' => $customer_id,
  2038. 'type' => 1,
  2039. 'remark' => '公海获取',
  2040. 'employee_id' => $employee_id,
  2041. 'user_id' => $this->request->empcrm->uid,
  2042. 'state' => 1
  2043. ];
  2044. if (CustomerVisitLog::insertAll($saveAll)) {
  2045. return json(['code' => 0, 'msg' => '获取成功']);
  2046. } else {
  2047. return json(['code' => 1, 'msg' => '获取失败']);
  2048. }
  2049. } else {
  2050. return json(['code' => 1, 'msg' => '获取失败']);
  2051. }
  2052. }
  2053. //更新已签单客户页面
  2054. public function signcus_detail()
  2055. {
  2056. $request = request();
  2057. $root_id = $request->empcrm->root_id;
  2058. $empid = $request->empcrm->id;
  2059. $org_employee = [$empid];
  2060. $param = $request->only(['id']);
  2061. $this->screen();
  2062. //客户等级 隶属计划
  2063. $fields=CustomerPortraitField::with(['select'])->where([['root_id','=',$root_id],['keyname','in',['level','subjection_plan','housetype_arrow']]])->select()->toArray();
  2064. View::assign('fields', $fields);
  2065. //意向风格
  2066. $decostyle_list = Decostyle::field('id,name,root_id as pid')->where(['root_id' =>$root_id])->where([['type', '=', 0]])->order('id desc')->select()->toArray();
  2067. View::assign('decostyle_list', $decostyle_list);
  2068. //意向产品
  2069. $product = CustomerPackage::field('id, name, total_price')->where(['root_id' =>$root_id])->select();
  2070. View::assign('product', $product);
  2071. $data = $this->seLemp($param['id'],$empid);
  2072. View::assign('data',$data);
  2073. return View::fetch();
  2074. }
  2075. //已签单客户修改客户信息
  2076. public function sign_savecust()
  2077. {
  2078. $request = request();
  2079. $param = $request->only(['id','designer_id','name'=>'','community_name'=>'','square'=>0,'housetype_arrow'=>'','package_id'=>'','deco_style'=>'']);
  2080. $root_id = $request->empcrm->root_id;
  2081. $empid = $request->empcrm->id;
  2082. $org_employee = [$empid];
  2083. $orgids = orgSubIds($root_id);
  2084. $data['name'] = $param['name'];
  2085. $data['community_name'] = $param['community_name'];
  2086. $data['square'] = $param['square'];
  2087. $data['package_id'] = $param['package_id'];
  2088. $data['deco_style'] = $param['deco_style'];
  2089. //$data['designer_id'] = $param['designer_id'];
  2090. //处理客户的扩展字段
  2091. $et=[];
  2092. $kz = CustomerPortraitField::where([['root_id','=',$root_id],['keyname','in',['housetype_arrow']]])->select();
  2093. foreach($kz as $key=>$val){
  2094. $et[]=['id'=>$val['id'],'keyname'=>$val['keyname'],'value'=>$param[$val['keyname']]];
  2095. }
  2096. $data['ext'] = !empty($et)?json_encode($et):NULL;
  2097. $ms = Customer::where([['id','=',$param['id']],['org_id','in',$orgids]])->update($data);
  2098. return json(['code' => 0, 'data' => $ms, 'msg' => '修改成功']);
  2099. }
  2100. //公海点击展示客户详情
  2101. public function pollcus_detail()
  2102. {
  2103. $request = request();
  2104. $root_id = $request->empcrm->root_id;
  2105. $empid = $request->empcrm->id;
  2106. $param = $this->request->only(['cid']);
  2107. $data = $this->cusdet_noemp($param['cid']);
  2108. View::assign('data',$data);
  2109. return View::fetch();
  2110. }
  2111. //公共查询客户详情(没有所属员工id时)
  2112. public function cusdet_noemp($id)
  2113. {
  2114. $request = request();
  2115. $root_id = $request->empcrm->root_id;
  2116. $orgids = orgSubIds($root_id);
  2117. $data = Customer::with(['visitLog'])->where([['id','=',$id],['org_id','in',$orgids]])->find();
  2118. $data = $data->toArray();
  2119. // echo json_encode($data['visitLog']);
  2120. // exit;
  2121. $data['package_name'] = $data['package_id'] ? CustomerPackage::where('id',$data['package_id'])->value('name') :'';
  2122. $data['deco_style_name'] = $data['deco_style'] ? Decostyle::where('id',$data['deco_style'])->value('name') : '';
  2123. $data['company_name'] = Company::where('root_id',$root_id)->value('company_name');
  2124. $data['add_wechat'] = '否';
  2125. $data['housetype'] = $data['unit_number'] = $data['subjection_plan'] = null;
  2126. $data['jiaofang'] = !empty($data['house_delivery_time'])?($data['house_delivery_time'] <= date('Y/m/d',time())?'现房':'期房'):'';
  2127. $data['company_name'] = Company::where('root_id',$root_id)->value('company_name');
  2128. //$vslog = CustomerVisitLog::where('customer_id',$id)->order('addtime desc')->find();
  2129. $data['lrname'] = NULL;
  2130. if(!empty($data['visitLog']) && !empty($data['visitLog'][0]['customer_employee_id'])){
  2131. $data['lrname'] = Employee::where('id',$data['visitLog'][0]['customer_employee_id'])->value('name');
  2132. }
  2133. if(!empty($data['ext'])){
  2134. $field = $this->get_portrait_field($data);
  2135. foreach($field as $key=>$val){
  2136. if($val['keyname'] == 'wechat' && !empty($val['value'])){
  2137. $data['add_wechat'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  2138. }
  2139. if($val['keyname']=='housetype_arrow' && !empty($val['value'])){
  2140. $data['housetype'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  2141. }
  2142. if($val['keyname']=='subjection_plan' && !empty($val['value'])){
  2143. $data['subjection_plan'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  2144. }
  2145. if($val['keyname']=='unit_number' && !empty($val['value'])){
  2146. $data['unit_number'] = $val['value'];
  2147. }
  2148. if($val['keyname']=='sign_name' && !empty($val['value'])){
  2149. $data['sign_time'] = $val['value'];
  2150. }
  2151. }
  2152. }
  2153. if(!empty($data['visitLog'])){
  2154. foreach($data['visitLog'] as $key=>$val){
  2155. if($val['state'] == '已签单' && $request->empcrm['xinjushang'] == 0) $val['state'] = '已转单';
  2156. if($val['state'] == '已交定' && $request->empcrm['xinjushang'] == 0) $val['state'] = '已签单';
  2157. if($val['state'] == '已转单' && $request->empcrm['xinjushang'] == 0) $data['visitLog'][$key]['remark'] = str_replace('已签单','已转单',$val['remark']);
  2158. if($val['state'] == '已签单' && $request->empcrm['xinjushang'] == 0) $data['visitLog'][$key]['remark'] = str_replace('已交定','已签单',$val['remark']);
  2159. $data['visitLog'][$key]['state'] = $val['state'];
  2160. $data['visitLog'][$key]['empname'] = Employee::where('id',$val['employee_id'])->value('name');
  2161. if(!empty($val['save_portrait_field'])){
  2162. $save_portrait_field = json_decode($val['save_portrait_field'],true);
  2163. foreach($save_portrait_field as $k=>$v){
  2164. if($v['type'] == 6){
  2165. $save_portrait_field[$k]['valname'] = explode(',',$v['value']);
  2166. }
  2167. }
  2168. }else{
  2169. $save_portrait_field = '';
  2170. }
  2171. $data['visitLog'][$key]['save_portrait_field'] = $save_portrait_field;
  2172. $parr[] = $val['addtime'];
  2173. if($val['next_contact_date'] > date('Y-m-d H:i:s')){
  2174. $data['visitLog'][$key]['isyes'] = 1;
  2175. }else{
  2176. $data['visitLog'][$key]['isyes'] = 0;
  2177. }
  2178. $data['visitLog'][$key]['wisdom_url'] = '';
  2179. $data['visitLog'][$key]['is_wisdom'] = 0;
  2180. if ($val['remark'] && strpos($val['remark'],'讲解智慧屏##')!==false) {
  2181. //remark = 接待了客户:张三,讲解时长21分钟@讲解智慧屏## url;
  2182. $data['visitLog'][$key]['is_wisdom'] = 1;
  2183. $arr = explode('##',$val['remark']);
  2184. if(count($arr)==2){
  2185. $ali_oss_bindurl = config('app.ali_oss_bindurl');
  2186. $data['visitLog'][$key]['wisdom_url'] = 'https://' . $ali_oss_bindurl . '/' . $arr[1];
  2187. $title = explode('@',$arr[0]);
  2188. $data['visitLog'][$key]['remark'] = $title[0];
  2189. }
  2190. }
  2191. // 检测是否有录音
  2192. if($val['data_type'] == 'out_call'){
  2193. $data['visitLog'][$key]['is_wisdom'] = 2;
  2194. $data['visitLog'][$key]['wisdom_url'] = OutCallLog::where(['id'=>$val['data_id']])->value('url');
  2195. }
  2196. }
  2197. array_multisort($parr, SORT_DESC, $data['visitLog']);
  2198. }
  2199. return $data;
  2200. }
  2201. //新增客户后跟进页面
  2202. public function followup()
  2203. {
  2204. $request = request();
  2205. $root_id = $request->empcrm->root_id;
  2206. $empid = $request->empcrm->id;
  2207. $param = $this->request->only(['cid']);
  2208. $data = $this->seLemp($param['cid'],$empid);
  2209. View::assign('data',$data);
  2210. return View::fetch();
  2211. }
  2212. //单独确认客户有效
  2213. public function validation()
  2214. {
  2215. $request = request();
  2216. $root_id = $request->empcrm->root_id;
  2217. $empid = $request->empcrm->id;
  2218. $orgids = orgSubIds($root_id);
  2219. $param = $this->request->only(['customer_id']);
  2220. $ms = Customer::where([['org_id','in',$orgids],['id','=',$param['customer_id']],['state','in',Customer::changeState('待确认', 'chaos')]])->update(['state'=>1,'valid_time'=>date('Y-m-d H:i:s')]);
  2221. if($ms){
  2222. return json(['code' => 0, 'msg' => '确认完成']);
  2223. }else{
  2224. return json(['code' => 1, 'msg' => '确认失败']);
  2225. }
  2226. }
  2227. //待回访
  2228. public function repay_list()
  2229. {
  2230. $request = request();
  2231. $root_id = $request->empcrm->root_id;
  2232. $empid = $request->empcrm->id;
  2233. $is_manager = $request->empcrm->is_manager;
  2234. $org_employee = [$empid];
  2235. if($is_manager ==1){
  2236. $team_orgs = orgSubIds($request->empcrm->org_id);
  2237. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  2238. }
  2239. if (!$request->isAjax()) {
  2240. $this->screen();
  2241. return View::fetch();
  2242. }
  2243. $param = $request->only(['page'=>1, 'limit'=>10, 'jiange_day','employee_name', 'level','source_name','designer_name','name','date','last_contact_date','community_name','phone']);
  2244. // 客户表revisit_time字段存在无法识别日期格式,查询需指定开始日期
  2245. $condition[] = empty($param['date']) ? ['revisit_time', '=', date('Y-m-d') . ' 00:00:00'] : ['revisit_time', '=', $param['date'] . ' 00:00:00'];
  2246. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $org_employee = [$param['employee_id']];
  2247. $condition[] = ['employee_id', 'in', $org_employee];
  2248. //$condition[] = ['state', 'not in',Customer::changeState('已签单', 'chaos')];
  2249. //客户姓名
  2250. if (!empty($param['name'])) $condition[] = ['name', 'like', '%' . $param['name'] . '%'];
  2251. //小区名称
  2252. if (!empty($param['community_name'])) $condition[] = ['community_name', 'like', '%' . $param['community_name'] . '%'];
  2253. //等级
  2254. if (!empty($param['level'])) $condition[] = ['level', 'in', explode(',',$param['level'])];
  2255. //来源
  2256. if (!empty($param['source_name'])) $condition[] = ['source_id', 'in', explode(',',$param['source_name'])];
  2257. //所属员工
  2258. if (!empty($param['employee_name'])) $condition[] = ['employee_id','in',explode(',',$param['employee_name'])];
  2259. //所属设计师
  2260. if (!empty($param['designer_name'])) $condition[] = ['designer_id', 'in', explode(',',$param['designer_name'])];
  2261. $order = isset($param['order']) ? $param['order'] : 'id desc';
  2262. $page = intval($param['page']);
  2263. $limit = intval($param['limit']);
  2264. if (!empty($param['phone'])) {
  2265. $list = Customer::where($condition)->column('id','phone');
  2266. $keyCustomersId = [];
  2267. foreach ($list as $k => $v) {
  2268. if(cypherphone($param['phone']) == $k) $keyCustomersId[] = $v;
  2269. // if (strpos($k, trim($new_params['phone'])) !== false) $keyCustomersId[] = $v;
  2270. }
  2271. unset($condition);
  2272. $condition[] = ['id', 'in', $keyCustomersId];
  2273. }
  2274. //客户的跟进时间
  2275. if(!empty($param['last_contact_date'])){
  2276. $last_contact = explode(' - ', $param['last_contact_date']);
  2277. $start = str_replace('/','-',$last_contact[0]);
  2278. $end = str_replace('/','-',$last_contact[1]);
  2279. $condition[] = ['last_contact_date','>=',$start];
  2280. $condition[] = ['last_contact_date','<=',$end];
  2281. }
  2282. //未跟进天数
  2283. if (!empty($param['jiange_day'])) {
  2284. $no_visit_day = explode(',',$param['jiange_day']);
  2285. $all_no_visit = [
  2286. 1=>[3,7],
  2287. 2=>[8,14],
  2288. 3=>[15,30],
  2289. 4=>[31,10000]
  2290. ];
  2291. $customersList = Customer::where($condition)->order('addtime desc')->column('id,addtime');
  2292. $wg_where[] = ['customer_id', 'in', array_column($customersList,'id')];
  2293. $latest_visit_log = CustomerVisitLog::where($wg_where)->group('customer_id')->column('max(addtime) as addtime','customer_id');//->select()->toArray();
  2294. $no_visit_ids = [];
  2295. foreach($customersList as $k=>$v){
  2296. if (empty($latest_visit_log[$v['id']])) {
  2297. $no_visit_long = ceil((time() - strtotime($v['addtime']))/86400);
  2298. } else {
  2299. $no_visit_long = ceil((time() - strtotime($latest_visit_log[$v['id']]))/86400);
  2300. }
  2301. foreach($no_visit_day as $m=>$p){
  2302. if(empty($all_no_visit[$p])) continue;
  2303. if($no_visit_long >= $all_no_visit[$p][0] && $no_visit_long <= $all_no_visit[$p][1]) $no_visit_ids[] = $v['id'];
  2304. }
  2305. }
  2306. unset($condition);
  2307. $condition[] = ['id','in',$no_visit_ids];
  2308. }
  2309. $data = $this->selCustomer($condition,$page,$limit,$order,$root_id);
  2310. foreach($data as $key=>$val){
  2311. $data[$key]['jiange_day'] = ceil((strtotime(date('Y-m-d')) - strtotime($val['last_contact_date']))/86400);
  2312. }
  2313. $count = Customer::where($condition)->count();
  2314. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  2315. }
  2316. /**
  2317. * 设置客户池展示字段
  2318. */
  2319. public function poolFieldsSet(){
  2320. $type = input('type', '', 'intval');
  2321. $content = input('content', '', 'trim');
  2322. $content = json_decode($content, true);
  2323. $root_id = request()->empcrm->root_id;
  2324. $employee_id = request()->empcrm->id;
  2325. $find = StatisticsSetting::where([['type', '=', 'sq_'.$type], ['employee_id', '=', $employee_id], ['root_id', '=', $root_id]])->findOrEmpty();
  2326. $default_field = $this->poolFields($type);
  2327. foreach ($content as $k => $v){
  2328. if(isset($v['name']) && isset($v['show']) && isset($v['sort']) && isset($default_field[$v['name']])){
  2329. $default_field[$v['name']]['show'] = $v['show'];
  2330. $default_field[$v['name']]['sort'] = $v['sort'];
  2331. }
  2332. }
  2333. if ($find->isEmpty()) {
  2334. $save['employee_id'] = $employee_id;
  2335. $save['root_id'] = $root_id;
  2336. $save['content'] = json_encode($default_field);
  2337. $save['type'] = 'sq_'.$type;
  2338. $result = StatisticsSetting::insert($save);
  2339. } else {
  2340. $find->content = json_encode($default_field);
  2341. $find->save();
  2342. }
  2343. return json(['code'=> 0, 'msg'=> 'success']);
  2344. }
  2345. /**
  2346. * 客户池展示字段
  2347. */
  2348. public function poolFields($type = 6){
  2349. // 客户池字段
  2350. $field1 = [
  2351. 'name'=> ['name'=> '客户姓名', 'show'=> 1, 'width'=> 120,'sort'=>1],
  2352. 'phone'=> ['name'=> '手机号', 'show'=> 1, 'width'=> 100,'sort'=>2],
  2353. 'employee_name'=> ['name'=> '所属员工', 'show'=> 1, 'width'=> 120,'sort'=>3],
  2354. 'designer_name'=> ['name'=> '设计师', 'show'=> 1, 'width'=> 120,'sort'=>4],
  2355. 'source_name'=> ['name'=> '来源渠道', 'show'=> 1, 'width'=> 120,'sort'=>5],
  2356. 'add_wechat_time'=> ['name'=> '加微时间', 'show'=> 1, 'width'=> 120, 'sort'=> 6],
  2357. 'customer_type'=> ['name'=> '客户种类', 'show'=> 1, 'width'=> 120,'sort'=> 7],
  2358. 'community_name'=> ['name'=> '小区名称', 'show'=> 1, 'width'=> 160,'sort'=> 8],
  2359. 'level'=> ['name'=> '重要', 'show'=> 1, 'width'=> 160,'sort'=> 9],
  2360. 'sign_time'=> ['name'=> '报名时间', 'show'=> 1, 'width'=> 160,'sort'=> 10],
  2361. 'house_delivery_time'=> ['name'=> '交房时间', 'show'=> 1, 'width'=> 120,'sort'=> 11],
  2362. 'state'=> ['name'=> '状态', 'show'=> 1, 'width'=> 120,'sort'=> 12],
  2363. 'square'=> ['name'=> '面积', 'show'=> 1, 'width'=> 100,'sort'=> 13],
  2364. 'last_contact_date'=> ['name'=> '跟进时间', 'show'=> 1, 'width'=> 160,'sort'=> 14],
  2365. 'revisit_time'=> ['name'=> '下次回访时间', 'show'=> 1, 'width'=> 160,'sort'=> 15],
  2366. 'addtime'=> ['name'=> '添加时间', 'show'=> 1, 'width'=> 160,'sort'=> 16],
  2367. 'protected_to'=> ['name'=> '保护至', 'show'=> 1, 'width'=> 160,'sort'=> 17],
  2368. 'visit_log_count'=> ['name'=> '预约次数', 'show'=> 1, 'width'=> 160,'sort'=> 18],
  2369. 'activity_frequency_count'=> ['name'=> '参加活动次数', 'show'=> 1, 'width'=> 160,'sort'=> 19],
  2370. 'lognum'=> ['name'=> '跟进次数', 'show'=> 1, 'width'=> 150,'sort'=> 20],
  2371. 'no_visit_day'=> ['name'=> '未跟进天数', 'show'=> 1, 'width'=> 150,'sort'=> 21],
  2372. 'subscribe_date'=> ['name'=> '预计见面时间', 'show'=> 1, 'width'=> 150,'sort'=> 22],
  2373. 'first_liangfang'=> ['name'=> '首次量房时间', 'show'=> 1, 'width'=> 150,'sort'=> 23],
  2374. 'fisttime'=> ['name'=> '首次到店时间', 'show'=> 1, 'width'=> 150,'sort'=> 24],
  2375. 'jiaoding_time'=> ['name'=> '签单时间', 'show'=> 1, 'width'=> 120, 'sort'=> 25],
  2376. 'jiaoding_money'=> ['name'=> '签单金额', 'show'=> 1, 'width'=> 120, 'sort'=> 26],
  2377. 'qiandan_time'=> ['name'=> '转单时间', 'show'=> 1, 'width'=> 120, 'sort'=> 27],
  2378. 'qiandan_money'=> ['name'=> '转单金额', 'show'=> 1, 'width'=> 120, 'sort'=> 28],
  2379. 'assign_list' => ['name'=>'指派客户经理','show'=>1,'width'=>160,'sort'=>29],
  2380. 'emporg' => ['name'=>'业务员部门','show'=>1,'width'=>160,'sort'=>30],
  2381. 'unit_number' => ['name'=>'楼栋','show'=>1,'width'=>160,'sort'=>31]
  2382. //'editbox'=> ['name'=>'编辑','show'=>1,'width'=>150,'sort'=>24]
  2383. ];
  2384. // 到店客户字段
  2385. $field2 = [
  2386. 'name'=> ['name'=> '客户姓名', 'show'=> 1, 'width'=> 120,'sort'=>1],
  2387. 'phone'=> ['name'=> '手机号', 'show'=> 1, 'width'=> 100,'sort'=>2],
  2388. 'employee_name'=> ['name'=> '所属员工', 'show'=> 1, 'width'=> 120,'sort'=>3],
  2389. 'designer_name'=> ['name'=> '设计师', 'show'=> 1, 'width'=> 120,'sort'=>4],
  2390. 'source_name'=> ['name'=> '来源渠道', 'show'=> 1, 'width'=> 120,'sort'=>5],
  2391. 'community_name'=> ['name'=> '小区名称', 'show'=> 1, 'width'=> 160,'sort'=> 6],
  2392. 'level'=> ['name'=> '重要', 'show'=> 1, 'width'=> 160,'sort'=> 7],
  2393. 'square'=> ['name'=> '面积', 'show'=> 1, 'width'=> 100,'sort'=> 8],
  2394. 'state'=> ['name'=> '状态', 'show'=> 1, 'width'=> 120,'sort'=> 9],
  2395. 'assign_list' => ['name'=>'指派客户经理','show'=>1,'width'=>160,'sort'=>10],
  2396. 'assign_time' => ['name'=>'指派时间','show'=>1,'width'=>160,'sort'=>11],
  2397. 'assign_org' => ['name'=>'指派部门','show'=>1,'width'=>160,'sort'=>12],
  2398. 'assign_type_name' => ['name'=>'指派类型','show'=>1,'width'=>160,'sort'=>13],
  2399. 'last_contact_date'=> ['name'=> '跟进时间', 'show'=> 1, 'width'=> 160,'sort'=> 14],
  2400. 'no_visit_day'=> ['name'=> '未跟进天数', 'show'=> 1, 'width'=> 150,'sort'=> 15],
  2401. 'liangfang_time'=> ['name'=> '量房时间', 'show'=> 1, 'width'=> 150,'sort'=> 16],
  2402. 'daodian_time'=> ['name'=> '到店时间', 'show'=> 1, 'width'=> 150,'sort'=> 17],
  2403. 'jiaoding_time'=> ['name'=> '签单时间', 'show'=> 1, 'width'=> 120, 'sort'=> 18],
  2404. 'jiaoding_money'=> ['name'=> '签单金额', 'show'=> 1, 'width'=> 120, 'sort'=> 19],
  2405. 'qiandan_time'=> ['name'=> '转单时间', 'show'=> 1, 'width'=> 120, 'sort'=> 20],
  2406. 'qiandan_money'=> ['name'=> '转单金额', 'show'=> 1, 'width'=> 120, 'sort'=> 21],
  2407. 'customer_type'=> ['name'=> '客户种类', 'show'=> 1, 'width'=> 120,'sort'=> 22],
  2408. 'unit_number' => ['name'=>'楼栋','show'=>1,'width'=>160,'sort'=>23]
  2409. ];
  2410. // 待回访客户字段
  2411. $field3 = [
  2412. 'name'=> ['name'=> '客户姓名', 'show'=> 1, 'width'=> 120,'sort'=>1],
  2413. 'phone'=> ['name'=> '手机号', 'show'=> 1, 'width'=> 100,'sort'=>2],
  2414. 'employee_name'=> ['name'=> '所属员工', 'show'=> 1, 'width'=> 120,'sort'=>3],
  2415. 'designer_name'=> ['name'=> '设计师', 'show'=> 1, 'width'=> 120,'sort'=>4],
  2416. 'source_name'=> ['name'=> '来源渠道', 'show'=> 1, 'width'=> 120,'sort'=>5],
  2417. 'community_name'=> ['name'=> '小区名称', 'show'=> 1, 'width'=> 160,'sort'=> 6],
  2418. 'level'=> ['name'=> '重要', 'show'=> 1, 'width'=> 160,'sort'=> 7],
  2419. 'square'=> ['name'=> '面积', 'show'=> 1, 'width'=> 100,'sort'=> 8],
  2420. 'last_contact_date'=> ['name'=> '上次回访', 'show'=> 1, 'width'=> 100,'sort'=> 9],
  2421. 'jiange_day'=> ['name'=> '间隔', 'show'=> 1, 'width'=> 100,'sort'=> 10]
  2422. ];
  2423. $root_id = request()->empcrm->root_id;
  2424. switch ($type) {
  2425. case 1: // 客户池
  2426. return $field1;
  2427. break;
  2428. case 2: // 到店
  2429. return $field2;
  2430. break;
  2431. case 3: //待回访
  2432. return $field3;
  2433. break;
  2434. default:
  2435. break;
  2436. }
  2437. }
  2438. /**
  2439. * 客户池展示字段
  2440. */
  2441. public function poolFieldsList(){
  2442. $type = input('type', '', 'intval');
  2443. $is_org = input('is_org', '', 'intval'); // 是否是部门统计 目前只有总统计
  2444. $root_id = request()->empcrm->root_id;
  2445. $employee_id = request()->empcrm->id;
  2446. $find = StatisticsSetting::where([['type', '=', 'sq_'.$type], ['employee_id', '=', $employee_id], ['root_id', '=', $root_id]])->findOrEmpty();
  2447. $default_fields = $this->poolFields($type);
  2448. if (!$find->isEmpty()) {
  2449. $set = json_decode($find['content'], true);
  2450. if (!empty($set)) {
  2451. foreach ($set as $k => $v){
  2452. if (isset($default_fields[$k])){
  2453. $default_fields[$k]['show'] = $v['show'];
  2454. $default_fields[$k]['sort'] = $v['sort'];
  2455. }
  2456. }
  2457. array_multisort(array_column($default_fields, 'sort'), SORT_ASC, $default_fields);
  2458. }
  2459. }
  2460. if ($type == 6) {
  2461. $field_6 = [];
  2462. foreach ($default_fields as $k => $v) {
  2463. if ($k == 'name') {
  2464. unset($default_fields[$k]);
  2465. $field_6[$k] = $v;
  2466. }
  2467. }
  2468. $field_6 = array_merge($field_6, $default_fields);
  2469. $default_fields = $field_6;
  2470. }
  2471. //处理馨居尚交定签单显示文字
  2472. if(request()->empcrm['xinjushang'] == 1){
  2473. foreach($default_fields as $key=>$val){
  2474. if(strpos($val['name'], '签单') !== false) $default_fields[$key]['name'] = str_replace('签单','交定',$val['name']);
  2475. if(strpos($val['name'], '转单') !== false) $default_fields[$key]['name'] = str_replace('转单','签单',$val['name']);
  2476. }
  2477. }
  2478. return json(['code'=> 0, 'msg'=> 'success', 'data'=> $default_fields]);
  2479. }
  2480. //到访(确认到场)列表 包含 到店、量房、到场、签单、转单
  2481. public function confirm_visit_list()
  2482. {
  2483. $request = request();
  2484. $root_id = $request->empcrm->root_id;
  2485. $empid = $request->empcrm->id;
  2486. $is_manager = $request->empcrm->is_manager;
  2487. $org_employee = [$empid];
  2488. if($is_manager ==1){
  2489. $team_orgs = orgSubIds($request->empcrm->org_id);
  2490. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  2491. }
  2492. if (!$request->isAjax()) {
  2493. $this->screen();
  2494. //指派经理
  2495. $assignemp_list = Employee::where([['org_id','in',orgSubIds($root_id)], ['state', '=', '在职'], ['uid', '>', 0]])->column('id,name');
  2496. View::assign('assignemp_list', $assignemp_list);
  2497. //指派部门
  2498. $assignorg_list = Org::where([['path','like',$root_id.'-%']])->column('id,name');
  2499. View::assign('assignorg_list', $assignorg_list);
  2500. $assign_type = [['id'=>1,'name'=>'意向指派'],['id'=>2,'name'=>'量房指派'],['id'=>3,'name'=>'到店指派']];
  2501. View::assign('assign_type',$assign_type);
  2502. return View::fetch();
  2503. }
  2504. $param = $request->only(['page'=>1, 'limit'=>10, 'last_contact_date','assign_org','assign_list','community_name','no_visit_day','liangfang_time','jiaoding_time','qiandan_time','jiaoding_money','qiandan_money','daodian_time'=>'','square','level','source_name','name'=>'','state','assign_time','phone','employee_name','assign_type_name','designer_name','times'=>0,'customer_type']);
  2505. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $org_employee = [$param['employee_id']];
  2506. $condition[] = ['employee_id', 'in', $org_employee];
  2507. $condition[] = ['state', 'not in',Customer::changeState('无效','chaos')];
  2508. $tmp_condition = "";
  2509. //客户姓名
  2510. if (!empty($param['name'])) $condition[] = ['name', 'like', '%' . $param['name'] . '%'];
  2511. //小区名称
  2512. if (!empty($param['community_name'])) $condition[] = ['community_name', 'like', '%' . $param['community_name'] . '%'];
  2513. //等级
  2514. if (!empty($param['level'])) $condition[] = ['level', 'in', explode(',',$param['level'])];
  2515. //来源
  2516. if (!empty($param['source_name'])) $condition[] = ['source_id', 'in', explode(',',$param['source_name'])];
  2517. //所属员工
  2518. if (!empty($param['employee_name'])) $condition[] = ['employee_id','in',explode(',',$param['employee_name'])];
  2519. //所属设计师
  2520. if (!empty($param['designer_name'])) $condition[] = ['designer_id', 'in', explode(',',$param['designer_name'])];
  2521. $order = isset($param['order']) ? $param['order'] : 'id desc';
  2522. if($param['times'] == 1) $order = 'assign_time asc';
  2523. if($param['times'] == 2) $order = 'assign_time desc';
  2524. if($param['times'] == 3) $order = 'last_contact_date asc';
  2525. if($param['times'] == 4) $order = 'last_contact_date desc';
  2526. $page = intval($param['page']);
  2527. $limit = intval($param['limit']);
  2528. //客户的跟进时间
  2529. if(!empty($param['last_contact_date'])){
  2530. $last_contact = explode(' - ', $param['last_contact_date']);
  2531. $start = str_replace('/','-',$last_contact[0]);
  2532. $end = str_replace('/','-',$last_contact[1]);
  2533. $condition[] = ['last_contact_date','>=',$start.' 00:00:00'];
  2534. $condition[] = ['last_contact_date','<=',$end.' 23:59:59'];
  2535. }
  2536. //客户种类 资源库,活动,经纪人,自建
  2537. if (!empty($param['customer_type'])) {
  2538. $gather = [
  2539. 1=>[['crm_res_id','not null',null]],//'资源库'
  2540. 2=>[['crm_res_id','null',null],['remark','not like','%活动报名建档%'],['agents_id','null',null]],//'自建'
  2541. 3=>[['remark','like','%活动报名建档%']],//'活动'
  2542. 4=>[['agents_id','>',0]]//'经纪人'
  2543. ];
  2544. $arr = explode(',',$param['customer_type']);
  2545. $whereOr = [];
  2546. foreach ($arr as $val) {
  2547. if (isset($gather[$val])) {
  2548. $whereOr[] = $gather[$val];
  2549. }
  2550. }
  2551. if (!empty($whereOr)) {
  2552. $new_cids = Customer::where($condition)->where(function($query) use ($whereOr){
  2553. $query->whereOr($whereOr);
  2554. })->column('id');
  2555. unset($condition);
  2556. $condition[] = ['id','in',$new_cids];
  2557. }else{
  2558. //无效条件
  2559. return json(['code' => 0, 'data' => [], 'count' => 0]);
  2560. }
  2561. }
  2562. //指派时间查询
  2563. if(!empty($param['assign_time'])){
  2564. $assign_time = explode('-',$param['assign_time']);
  2565. $start = $assign_time[0].' 00:00:00';
  2566. $end = $assign_time[1].' 23:59:59';
  2567. $condition[] = ['assign_time','>',$start];
  2568. $condition[] = ['assign_time','<',$end];
  2569. }
  2570. //$cusids = Customer::where($condition)->column('id');
  2571. //$vs_where[] = ['customer_id','in',$cusids];
  2572. $vs_where[] = ['customer_employee_id','in',$org_employee];
  2573. $vs_where[] = ['state', 'in', array_merge(CustomerVisitLog::changeState('确认到店','chaos'), CustomerVisitLog::changeState('已量房','chaos'),CustomerVisitLog::changeState('已到场','chaos'), CustomerVisitLog::changeState('已交定','chaos'), CustomerVisitLog::changeState('已签单','chaos'))];
  2574. if(!empty($param['date'])) $vs_where[] = ['confirm_date','between',[$param['date'].' 00:00:00',$param['date'].' 23:59:59']];
  2575. $vslogid = CustomerVisitLog::where($vs_where)->group('customer_id')->column('customer_id');
  2576. $condition[] = ['id', 'in', $vslogid];
  2577. //手机号
  2578. if (!empty($param['phone'])) {
  2579. $list = Customer::where($condition)->order('addtime desc')->field('id,name,community_name,phone')->select()->toArray();
  2580. $customerIdList = [];
  2581. foreach ($list as $v) {
  2582. if (strpos($v['phone'], trim($param['phone'])) !== false) $customerIdList[] = $v['id'];
  2583. }
  2584. unset($condition);
  2585. $condition[] = ['id','in',$customerIdList];
  2586. }
  2587. //客户经理
  2588. if(!empty($param['assign_list'])){
  2589. $assign_employee = explode(',', $param['assign_list']);
  2590. $customerIdList = Customer::where($condition)->where(function($query) use ($assign_employee){
  2591. foreach ($assign_employee as $v) {
  2592. $query->whereOr([['assigned_personnel', 'find in set', $v]]);
  2593. }
  2594. })->column('id');
  2595. unset($condition);
  2596. $condition[] = ['id','in',$customerIdList];
  2597. }
  2598. //指派部门
  2599. if(!empty($param['assign_org'])){
  2600. $assign_org = explode(',', $param['assign_org']);
  2601. $all_assigids = [];
  2602. $assigned_personnelList = Customer::where($condition)->column('assigned_personnel,id,designer_id');
  2603. foreach($assigned_personnelList as $k=>$v){
  2604. $assigned_personal = !empty($v['assigned_personnel']) ? explode(',',$v['assigned_personnel']) : [];
  2605. if(!empty($v['designer_id'])) $assigned_personal[] = $v['designer_id'];
  2606. $assign_orgid = Employee::where([['id','in',$assigned_personal],['org_id','in',$assign_org],['root_id','=',$root_id]])->column('org_id');
  2607. if(!empty($assign_orgid)) $all_assigids[] = $v['id'];
  2608. }
  2609. unset($condition);
  2610. $condition[] = ['id','in',$all_assigids];
  2611. }
  2612. //到店时间
  2613. if(!empty($param['daodian_time'])){
  2614. $daodian_time = explode(' - ', $param['daodian_time']);
  2615. if(empty($daodian_time)) return json(['code'=>1,'msg'=>'时间参数错误']);
  2616. $start = str_replace('/','-',$daodian_time[0]);
  2617. $end = str_replace('/','-',$daodian_time[1]);
  2618. $customerIdList = Customer::where($condition)->column('id');
  2619. $logwhere[] = ['confirm_date','>=',$start.' 00:00:00'];
  2620. $logwhere[] = ['confirm_date','<=',$end.' 23:59:59'];
  2621. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已到店','chaos')];
  2622. $logwhere[] = ['customer_id','in',$customerIdList];
  2623. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2624. unset($condition);
  2625. $condition[] = ['id','in',$customerIdList];
  2626. }
  2627. //量房时间
  2628. if(!empty($param['liangfang_time'])){
  2629. $liangfang_time = explode(' - ', $param['liangfang_time']);
  2630. if(empty($liangfang_time)) return json(['code'=>1,'msg'=>'时间参数错误']);
  2631. $start = str_replace('/','-',$liangfang_time[0]);
  2632. $end = str_replace('/','-',$liangfang_time[1]);
  2633. $customerIdList = Customer::where($condition)->column('id');
  2634. $logwhere[] = ['confirm_date','>=',$start.' 00:00:00'];
  2635. $logwhere[] = ['confirm_date','<=',$end.' 23:59:59'];
  2636. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已量房','chaos')];
  2637. $logwhere[] = ['customer_id','in',$customerIdList];
  2638. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2639. unset($condition);
  2640. $condition[] = ['id','in',$customerIdList];
  2641. }
  2642. //交定时间
  2643. if(!empty($param['jiaoding_time'])){
  2644. $jiaoding_time = explode(' - ', $param['jiaoding_time']);
  2645. if(empty($jiaoding_time)) return json(['code'=>1,'msg'=>'时间参数错误']);
  2646. $start = str_replace('/','-',$jiaoding_time[0]);
  2647. $end = str_replace('/','-',$jiaoding_time[1]);
  2648. $customerIdList = Customer::where($condition)->column('id');
  2649. $logwhere[] = ['confirm_date','>=',$start.' 00:00:00'];
  2650. $logwhere[] = ['confirm_date','<=',$end.' 23:59:59'];
  2651. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已交定','chaos')];
  2652. $logwhere[] = ['customer_id','in',$customerIdList];
  2653. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2654. unset($condition);
  2655. $condition[] = ['id','in',$customerIdList];
  2656. }
  2657. //签单时间
  2658. if(!empty($param['qiandan_time'])){
  2659. $qiandan_time = explode(' - ', $param['qiandan_time']);
  2660. if(empty($qiandan_time)) return json(['code'=>1,'msg'=>'时间参数错误']);
  2661. $start = str_replace('/','-',$qiandan_time[0]);
  2662. $end = str_replace('/','-',$qiandan_time[1]);
  2663. $customerIdList = Customer::where($condition)->column('id');
  2664. $logwhere[] = ['confirm_date','>=',$start.' 00:00:00'];
  2665. $logwhere[] = ['confirm_date','<=',$end.' 23:59:59'];
  2666. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已签单','chaos')];
  2667. $logwhere[] = ['customer_id','in',$customerIdList];
  2668. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2669. unset($condition);
  2670. $condition[] = ['id','in',$customerIdList];
  2671. }
  2672. //交定金额
  2673. if(!empty($param['jiaoding_money'])){
  2674. $jiaoding_money = explode('-', $param['jiaoding_money']);
  2675. if(empty($jiaoding_money)) return json(['code'=>1,'msg'=>'参数错误']);
  2676. $customerIdList = Customer::where($condition)->column('id');
  2677. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已交定','chaos')];
  2678. $logwhere[] = ['money','between',$jiaoding_money];
  2679. $logwhere[] = ['customer_id','in',$customerIdList];
  2680. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2681. unset($condition);
  2682. $condition[] = ['id','in',$customerIdList];
  2683. }
  2684. //签单金额
  2685. if(!empty($param['qiandan_money'])){
  2686. $sign_money = explode('-', $param['qiandan_money']);
  2687. if(empty($sign_money)) return json(['code'=>1,'msg'=>'参数错误']);
  2688. $customerIdList = Customer::where($condition)->column('id');
  2689. $logwhere[] = ['state','in',CustomerVisitLog::changeState('已签单','chaos')];
  2690. $logwhere[] = ['money','between',$sign_money];
  2691. $logwhere[] = ['customer_id','in',$customerIdList];
  2692. $customerIdList = CustomerVisitLog::where($logwhere)->group('customer_id')->column('customer_id');
  2693. unset($condition);
  2694. $condition[] = ['id','in',$customerIdList];
  2695. }
  2696. // 房屋面积
  2697. if (!empty($param['square'])){
  2698. $square = explode(',',$param['square']);
  2699. $square_arr = [
  2700. 1=>'(square > 1 and square <= 80)',
  2701. 2=>'(square > 81 and square <= 100)',
  2702. 3=>'(square > 101 and square <= 120)',
  2703. 4=>'(square > 121 and square <= 200)',
  2704. 5=>'(square > 201 and square <= 500)',
  2705. 6=>'(square > 501 and square <= 10000)'
  2706. ];
  2707. $squ_whereOr=null;
  2708. foreach($square as $k=>$v){
  2709. if(!empty($square_arr[$v])) $squ_whereOr.= $square_arr[$v]. ' OR';
  2710. }
  2711. $customersList = Customer::where($condition)->where(function($query) use ($squ_whereOr){
  2712. $query->whereRaw(trim($squ_whereOr,' OR'));
  2713. })->order('addtime desc')->column('id');
  2714. unset($condition);
  2715. $condition[] = ['id','in',$customersList];
  2716. }
  2717. //未跟进天数
  2718. if (!empty($param['no_visit_day'])) {
  2719. $no_visit_day = explode(',', $param['no_visit_day']);
  2720. $all_no_visit = [
  2721. 1 => [3, 7],
  2722. 2 => [8, 14],
  2723. 3 => [15, 30],
  2724. 4 => [31, 10000]
  2725. ];
  2726. $customersList = Customer::where($condition)->order('addtime desc')->column('id,addtime');
  2727. $wg_where[] = ['customer_id', 'in', array_column($customersList, 'id')];
  2728. $latest_visit_log = CustomerVisitLog::where($wg_where)->group('customer_id')->column('max(addtime) as addtime', 'customer_id'); //->select()->toArray();
  2729. $no_visit_ids = [];
  2730. foreach ($customersList as $k => $v) {
  2731. if (empty($latest_visit_log[$v['id']])) {
  2732. $no_visit_long = ceil((time() - strtotime($v['addtime'])) / 86400);
  2733. } else {
  2734. $no_visit_long = ceil((time() - strtotime($latest_visit_log[$v['id']])) / 86400);
  2735. }
  2736. foreach ($no_visit_day as $m => $p) {
  2737. if (empty($all_no_visit[$p])) continue;
  2738. if ($no_visit_long >= $all_no_visit[$p][0] && $no_visit_long <= $all_no_visit[$p][1]) $no_visit_ids[] = $v['id'];
  2739. }
  2740. }
  2741. unset($condition);
  2742. $condition[] = ['id', 'in', $no_visit_ids];
  2743. }
  2744. if (!empty($param['state'])) {
  2745. $customerIdList = Customer::where($condition)->column('id');
  2746. $stateall = explode(',',$param['state']);
  2747. $allsta = [];
  2748. foreach($stateall as $k=>$v){
  2749. if($v == '已签单') $v = '已交定';
  2750. if($v == '已转单') $v = '已签单';
  2751. if(in_array($v,['待确认','有效'])) continue;
  2752. $onestate = CustomerVisitLog::changeState($v,'chaos');
  2753. $allsta = array_merge($onestate,$allsta);
  2754. }
  2755. $visit_where[] = ['customer_id', 'in', $customerIdList];
  2756. $visit_where[] = ['state', 'in',$allsta];
  2757. // $visit_where[] = ['addtime', '>', date('Y-m-d H:i:s', $startTime)];
  2758. // $visit_where[] = ['addtime', '<', date('Y-m-d H:i:s', $endTime)];
  2759. $logCustomersIdList = CustomerVisitLog::where($visit_where)->group('customer_id')->column('customer_id');
  2760. $c_ids = $logCustomersIdList;
  2761. foreach($stateall as $k=>$v){
  2762. if($v == '待确认'){
  2763. $confirmedids = Customer::where($condition)->where([['state','in',Customer::changeState('待确认','chaos')],['crm_res_id','NULL',null]])->column('id');
  2764. }
  2765. if($v=='有效'){
  2766. $validids = Customer::where($condition)->where('state','not in',Customer::changeState('待确认','chaos'))->column('id');
  2767. }
  2768. }
  2769. unset($condition);
  2770. if(!empty($confirmedids)) $c_ids = array_merge($confirmedids,$c_ids);
  2771. if(!empty($validids)) $c_ids = array_merge($validids,$c_ids);
  2772. unset($condition);
  2773. $condition[] = ['id','in',$c_ids];
  2774. }
  2775. $vis_where = "if(CustomerVisitLog.state in (7,'已到店'), 1, 0) desc,confirm_date asc";
  2776. $tmp_vis_where = 'confirm_date asc';
  2777. if($param['times'] > 4){
  2778. if($param['times'] == 6) {
  2779. $vis_where = "if(CustomerVisitLog.state in (7,'已到店'), 1, 0) desc,confirm_date desc";
  2780. $tmp_vis_where = 'confirm_date desc';
  2781. }
  2782. $page = ($page - 1) * 17;
  2783. $tmp_sql = CustomerVisitLog::hasWhere('customer', $condition)->field("if(CustomerVisitLog.state in (7,'已到店'),1,0) as tmp_state")->group('CustomerVisitLog.state,CustomerVisitLog.customer_id')->orderRaw($vis_where)->buildSql();
  2784. $sql = "select customer_id from " . $tmp_sql . " a group by a.customer_id ORDER BY a.tmp_state desc," . $tmp_vis_where . " LIMIT " . $page . "," . $limit;
  2785. $customer_id = Db::query($sql);
  2786. $data = [];
  2787. foreach($customer_id as $k => $v){
  2788. $one = Customer::with(['employee', 'org', 'designer','source','visitLog' => function ($query) {$query->field('id,customer_id,addtime,state,confirm_date,money');}])->where($condition)->where(['id'=>$v['customer_id']])->find();
  2789. $data[$k] = $one->visible(['designer_id','assigned_personnel','assign_type','assign_time','id', 'employee_id', 'name', 'introduce','community_name', 'phone', 'level', 'state', 'square', 'revisit_time', 'addtime', 'last_contact_date', 'org_id', 'protected_to', 'is_resource', 'employee.name', 'org_name', 'designer.name', 'visit_log_count', 'activity_frequency_count','source_id','source.source', 'phone1', 'phone2','remark','crm_res_id','agents_id','house_delivery_time','first_visit_date','ext','transfer_info','deposit_money','signed_money','package_id','add_wechat_time','reputation_gather','into_owner_group'])->toArray();
  2790. }
  2791. }else{
  2792. $data = Customer::with(['employee', 'org', 'designer','source','visitLog' => function ($query) {
  2793. $query->field('id,customer_id,addtime,state,confirm_date,money');
  2794. }])
  2795. ->where($condition)
  2796. ->page($page, $limit)->order($order)->select();
  2797. $data = $data->visible(['designer_id','assigned_personnel','assign_type','assign_time','id', 'employee_id', 'name', 'introduce','community_name', 'phone', 'level', 'state', 'square', 'revisit_time', 'addtime', 'last_contact_date', 'org_id', 'protected_to', 'is_resource', 'employee.name', 'org_name', 'designer.name', 'visit_log_count', 'activity_frequency_count','source_id','source.source', 'phone1', 'phone2','remark','crm_res_id','agents_id','house_delivery_time','first_visit_date','ext','transfer_info','deposit_money','signed_money','package_id','add_wechat_time','reputation_gather','into_owner_group'])->toArray();
  2798. }
  2799. $setting = Setting::where([['name', '=', 'pubpool'], ['root_id', '=', $root_id]])->find();
  2800. if (!empty($setting)){
  2801. $setting_content = json_decode($setting['content'], true);
  2802. } else {
  2803. $setting_content = [];
  2804. }
  2805. // 指派类型
  2806. $assign_type_default = ['yixiang' => '意向客戶指派','liangfang'=>'量房客戶指派','daodian'=>'到店客戶指派'];
  2807. foreach ($data as &$item) {
  2808. $item['un_protected'] = false;
  2809. if (!empty($item['protected_to']) && time() > strtotime($item['protected_to'])) {
  2810. $state_n = Customer::changeState($item['state'], 'n');
  2811. if (isset($setting_content[$state_n]['state']) && $setting_content[$state_n]['state'] == 1) {
  2812. $item['un_protected'] = true;
  2813. }
  2814. }
  2815. $item['customer_type'] = $item['crm_res_id'] ? '资源库' : ($item['remark'] == '活动报名建档' ? '活动' : ($item['agents_id'] ? '装修推荐官' : '自建'));
  2816. $item['square'] = floatval($item['square']);
  2817. $item['phone'] = substr_replace($item['phone'], '******', 3, 6);
  2818. $item['phone1'] = $item['phone1'] ? substr_replace($item['phone1'], '******', 3, 6) : '';
  2819. $item['phone2'] = $item['phone2'] ? substr_replace($item['phone2'], '******', 3, 6) : '';
  2820. $item['jiaofang'] = !empty($item['house_delivery_time'])?(str_replace('/','-',$item['house_delivery_time']) <= date('Y-m-d',time())?'现房':$item['house_delivery_time']):'';
  2821. $item['time_status'] = $item['last_contact_date'] ? $this->uc_time_ago($item['last_contact_date']) :'';
  2822. $item['add_wechat'] = '否';
  2823. $item['package_name'] = !empty($item['package_id']) ? CustomerPackage::where('id',$item['package_id'])->value('name') :'';
  2824. $item['employee_name'] = !empty($item['employee']) ? $item['employee']['name'] : '';
  2825. $item['designer_name'] = !empty($item['designer']) ? $item['designer']['name'] : '';
  2826. $item['source_name'] = !empty($item['source']) ? $item['source']['source'] : '';
  2827. $item['unit_number'] = '';
  2828. if(!empty($item['ext'])){
  2829. $extdata=json_decode($item['ext'],true);
  2830. foreach($extdata as $key=>$val){
  2831. if(isset($val['keyname']) && $val['keyname']=='unit_number' && !empty($val['value'])){
  2832. $item['unit_number'] = $val['value'];
  2833. }
  2834. }
  2835. }
  2836. $now_status = $item['state'];
  2837. if($now_status == '已签单') $now_status = '已转单';
  2838. if($now_status == '已交定') $now_status = '已签单';
  2839. $assignIdList = !empty($item['assigned_personnel']) ? explode(',',$item['assigned_personnel']) : [];
  2840. //$assignIdList[] = $item['employee_id']; // 所属销售
  2841. if(!empty($item['designer_id'])) $assignIdList[] = $item['designer_id']; // 指派的设计师
  2842. $assign_data = Employee::where([['id', 'in', $assignIdList],['root_id','=',$root_id]])->column('name,org_id');
  2843. $item['assign_list'] = !empty($assign_data) ? implode(',',array_column($assign_data,'name')) : '';
  2844. $assign_org = Org::where([['id', 'in', array_column($assign_data, 'org_id')]])->group('id')->column('name');
  2845. $item['assign_org'] = !empty($assign_org) ? implode(',',$assign_org) : '';
  2846. $item['assign_type_name'] = $item['state'] = $item['daodian_time'] = $item['liangfang_time'] = $item['jiaoding_time'] = $item['qiandan_time'] = '';
  2847. if(!empty($item['assign_type'])){
  2848. if(isset($assign_type_default[$item['assign_type']])){
  2849. $item['assign_type_name'] = $assign_type_default[$item['assign_type']];
  2850. }
  2851. }
  2852. if(!empty($item['visitLog'])){
  2853. //取最新的一条为客户的跟进时间
  2854. $item['last_contact_date'] = $item['visitLog'][count($item['visitLog'])-1]['addtime'];
  2855. //处理合并多个状态
  2856. $stain=[$now_status];
  2857. foreach($item['visitLog'] as $k=>$v){
  2858. if(!in_array($v['state'],['已交定','已签单','已到店','已量房','已到场','未到访','回访'])) continue;
  2859. if($v['state']=='回访') $v['state'] = '待确认';
  2860. if($v['state']=='已签单') $v['state'] = '已转单';
  2861. if($v['state']=='已交定') $v['state'] = '已签单';
  2862. if(!in_array($v['state'],$stain)){
  2863. $stain[] = $v['state'];
  2864. }
  2865. }
  2866. if(count($stain) > 1 && in_array('待确认',$stain)) $stain = array_diff($stain,['待确认']);
  2867. $visit_state = ['已到店', '已量房', '已到场', '已签单', '已转单', '已卖卡'];
  2868. $no_visit_state = ['未到访', '待确认'];
  2869. $jiaoji = array_intersect($visit_state, $stain);
  2870. $no_jiaoji = array_intersect($no_visit_state, $stain);
  2871. if (count($no_jiaoji) == 2) { // 有未到访、待确认两个状态
  2872. $stain = ['未到访'];
  2873. }
  2874. if (count($stain) > 1 && count($jiaoji) > 0) {
  2875. $stain = array_diff($stain, $no_visit_state);
  2876. }
  2877. $item['state'] = implode(',', $stain);
  2878. if($now_status == '待确认') $item['state'] = '待确认';
  2879. //处理时间
  2880. $state = [];
  2881. foreach($item['visitLog'] as $k=>$v){
  2882. $state[$v['state']][] = $v;
  2883. }
  2884. foreach($state as $k=>$v){
  2885. if($k=='已到店') $item['daodian_time'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  2886. if($k=='已量房') $item['liangfang_time'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  2887. if($k=='已交定'){
  2888. $item['jiaoding_time'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  2889. $item['jiaoding_money'] = $v[0]['money'];
  2890. }
  2891. if($k=='已签单'){
  2892. $item['qiandan_time'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  2893. $item['qiandan_money'] = $v[0]['money'];
  2894. //$item['sign'] = $v[0];
  2895. }
  2896. }
  2897. }
  2898. $item['now_state'] = $now_status;
  2899. $item['no_visit_day'] = ceil((strtotime(date('Y-m-d')) - strtotime($item['last_contact_date']))/86400) > 0 ? ceil((strtotime(date('Y-m-d')) - strtotime($item['last_contact_date']))/86400) : 0;
  2900. }
  2901. $count = Customer::where($condition)->count();
  2902. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  2903. }
  2904. /**
  2905. * 客户池
  2906. */
  2907. public function list()
  2908. {
  2909. $request = request();
  2910. $root_id = $request->empcrm->root_id;
  2911. $empid = $request->empcrm->id;
  2912. $is_manager = $request->empcrm->is_manager;
  2913. $sub_orgs = orgSubIds($request->empcrm->org_id);
  2914. $org_id = input('org_id', $request->empcrm->org_id, 'intval');
  2915. if(!in_array($org_id, $sub_orgs)){
  2916. $org_id = $request->empcrm->org_id;
  2917. }
  2918. if ($is_manager) {
  2919. $team_orgs = orgSubIds($org_id);
  2920. } else {
  2921. $team_orgs = [$org_id];
  2922. }
  2923. if (!$request->isAjax()) {
  2924. //来源
  2925. $soudata = CustomerSource::field('id,source as name')->where('root_id', $root_id)->select()->toArray();
  2926. View::assign('soudata', $soudata);
  2927. //设计师
  2928. $list = $this->get_designer();
  2929. if (!empty($list)) {
  2930. $sort = array_column($list, 's');
  2931. sort($sort);
  2932. array_multisort($sort, SORT_ASC, $list);
  2933. $sort = array_unique($sort);
  2934. $list = ['sort' => $sort, 'arr' => $list];
  2935. } else {
  2936. $list = ['sort' => [], 'arr' => []];
  2937. }
  2938. View::assign('designers', $list);
  2939. //客户等级
  2940. $level = CustomerPortraitField::with(['select'])->where([['root_id', '=', $root_id], ['keyname', '=', 'level']])->find()->toArray();
  2941. View::assign('level', $level['select']);
  2942. //部门所有员工
  2943. $employee_list = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->field('id,name')->select()->toArray();
  2944. View::assign('employee_list', $employee_list);
  2945. View::assign('empid', $empid);
  2946. View::assign('is_manager',$is_manager);
  2947. //指派经理
  2948. $assignemp_list = Employee::where([['org_id','in',orgSubIds($root_id)],['id','not in',array_column($list['arr'],'id')],['state', '=', '在职'], ['uid', '>', 0]])->column('id,name');
  2949. View::assign('assignemp_list', $assignemp_list);
  2950. // 馨居上
  2951. //View::assign('xinjushang', $request->empcrm['xinjushang']);
  2952. //员工所属部门
  2953. $emporg_list = Org::where([['id','in',$team_orgs]])->column('id,name');
  2954. View::assign('emporg_list',$emporg_list);
  2955. // 统计模块的控制
  2956. $statistics_setting = Setting::where([['name', '=', 'empcrm_pool_statistics'], ['root_id', '=', $root_id]])->findOrEmpty();
  2957. $statistics_setting_content = !$statistics_setting->isEmpty() ? $statistics_setting['content'] : 1;
  2958. View::assign('statistics_setting', $statistics_setting_content);
  2959. //统计字段展示控制权限
  2960. $type_arr = ['customer_num' => 1, 'visit_num' => 1, 'valid_count' => 1, 'deposit_num' => 1, 'signed_num' => 1, 'yylf_num' => 1, 'lf_num' => 1, 'yydd_num' => 1, 'ydd_num' => 1, 'yyhd_num' => 1, 'ydc_num' => 1];
  2961. $setting = Setting::where([['name', '=', 'teamStatisticsJurisdiction'], ['root_id', '=', $root_id]])->value('content');
  2962. $setting = $setting ? explode(',', $setting) : [];
  2963. foreach ($type_arr as $k => $v) {
  2964. $type_arr[$k] = in_array($k, $setting) ? 1 : 0;
  2965. }
  2966. $sum = array_sum(array_values($type_arr));
  2967. if ($sum < 5) $type_arr = ['customer_num' => 1, 'visit_num' => 1, 'valid_count' => 1, 'deposit_num' => 1, 'signed_num' => 1, 'yylf_num' => 1, 'lf_num' => 1, 'yydd_num' => 1, 'ydd_num' => 1, 'yyhd_num' => 1, 'ydc_num' => 1];
  2968. View::assign('setting', $type_arr);
  2969. return View::fetch();
  2970. }
  2971. $param = $request->only(['page' => 1, 'limit' => 10, 'addtime'=> '', 'level'=> '', 'source_name'=> '', 'designer_name'=> '', 'keyname'=> '', 'followtime'=> '','state'=> '','employee_name'=> '', 'type'=> '','is_assign']);
  2972. $search_type = input('search_type', 1, 'intval'); //数据查询方式 1,以客户为主导 2,以满足的搜索状态为主导,合并出所有客户
  2973. $startTime = strtotime('2015-01-01');
  2974. $endTime = strtotime(date('Y-m-d')) + 86400;
  2975. $array_intersect = false;
  2976. $array_intersect_ids = [];
  2977. if ($search_type == 1) {
  2978. $org_type = Org::where('id', '=', $org_id)->value('org_type');
  2979. // 设计师部门管理员,需要查询指派给下属设计师的客户信息
  2980. if ($org_type == 2) {
  2981. if($is_manager == 1){
  2982. $designer_employee = Employee::where([['org_id', 'in', $team_orgs], ['uid', '<>', 0], ['state', '=', '在职'],['community_disable','=',0]])->column('id');
  2983. $condition[] = ['designer_id', 'in', $designer_employee];
  2984. // 是哪个员工
  2985. if($param['employee_name']) $condition[] = ['employee_id','in',explode(',',$param['employee_name'])];
  2986. } else {
  2987. $condition[] = ['designer_id', '=', $empid];
  2988. }
  2989. } else {
  2990. if($is_manager == 1){
  2991. $empids = Employee::where([['root_id','=',$root_id],['org_id', 'in', $team_orgs], ['uid', '<>', 0], ['state', '=', '在职'],['community_disable','=',0]])->column('id');
  2992. $condition[] = ['employee_id', 'in', $empids];
  2993. // 是哪个员工
  2994. if($param['employee_name']) $condition[] = ['employee_id','in',explode(',',$param['employee_name'])];
  2995. } else {
  2996. $condition[] = ['employee_id', '=', $empid];
  2997. }
  2998. }
  2999. $condition[] = ['state', 'not in', Customer::changeState('无效', 'chaos')];
  3000. $condition[] = ['died', '<>', 2];
  3001. if (!empty($param['addtime'])) {
  3002. //录入时间
  3003. $addtimeArr = explode(' - ', $param['addtime']);
  3004. $start = $addtimeArr[0];
  3005. $end = date('Y-m-d', strtotime($addtimeArr[1]) + 86400);
  3006. $startTime = strtotime($start) - 1;
  3007. $endTime = strtotime($end);
  3008. }
  3009. $condition[] = ['addtime', '>', date('Y-m-d H:i:s', $startTime)];
  3010. $condition[] = ['addtime', '<', date('Y-m-d H:i:s', $endTime)];
  3011. } else {
  3012. $array_intersect_ids = $this->logCondition();
  3013. $array_intersect = true;
  3014. $org_type = Org::where('id', '=', $org_id)->value('org_type');
  3015. // 设计师部门管理员,需要查询指派给下属设计师的客户信息
  3016. if ($org_type == 2) {
  3017. if($is_manager == 1){
  3018. $designer_employee = Employee::where([['org_id', 'in', $team_orgs], ['uid', '<>', 0], ['state', '=', '在职']])->column('id');
  3019. $condition[] = ['designer_id', 'in', $designer_employee];
  3020. // 是哪个员工
  3021. setCondition($param['employee_name'], 'designer_id', '=', $condition);
  3022. } else {
  3023. $condition[] = ['designer_id', '=', $empid];
  3024. }
  3025. } else {
  3026. if($is_manager == 1){
  3027. $condition[] = ['org_id', 'in', $team_orgs];
  3028. $condition[] = ['employee_id', '>', 0];
  3029. // 是哪个员工
  3030. setCondition($param['employee_name'], 'employee_id', '=', $condition);
  3031. } else {
  3032. $condition[] = ['employee_id', '=', $empid];
  3033. }
  3034. }
  3035. $condition[] = ['state', 'not in', Customer::changeState('无效', 'chaos')];
  3036. $condition[] = ['died', '<>', 2];
  3037. }
  3038. if (!empty($param['level'])) $condition[] = ['level', 'in', explode(',',$param['level'])];
  3039. if (!empty($param['source_name'])) $condition[] = ['source_id', 'in', explode(',',$param['source_name'])];
  3040. if (!empty($param['designer_name'])) $condition[] = ['designer_id', 'in', explode(',',$param['designer_name'])];
  3041. if(!empty($param['is_assign']) && $param['is_assign'] == 1) $condition[] = ['assigned_personnel','NOTNULL',null];
  3042. if(!empty($param['is_assign']) && $param['is_assign'] == 2) $condition[] = ['assigned_personnel','NULL',null];
  3043. //2023-02-22 搜索条件修改
  3044. $new_params = $request->only(['emporg','assign_list','revisit_time'=>'','phone'=>'','name'=>'','community_name'=>'','customer_type'=>'','first_liangfang'=>'','last_contact_date'=>'','fisttime'=>'','house_delivery_time'=>'','subscribe_date'=>'','square'=>'','no_visit_day'=>'','sign_time'=>'', 'add_wechat_time'=> '','jiaoding_time'=>'','qiandan_time'=>'']);
  3045. if (!empty($new_params['phone'])) {
  3046. $list = Customer::where($condition)->column('id,phone');
  3047. $keyCustomersId = [];
  3048. $cypherphone = cypherphone($new_params['phone']);
  3049. foreach ($list as $k => $v) {
  3050. if($cypherphone == $v['phone']) $keyCustomersId[] = $v['id'];
  3051. }
  3052. unset($condition);
  3053. $condition[] = ['id', 'in', $keyCustomersId];
  3054. }
  3055. //客户姓名
  3056. if ($new_params['name']) $condition[] = ['name', 'like', '%' . $new_params['name'] . '%'];
  3057. //小区名称
  3058. if ($new_params['community_name']) $condition[] = ['community_name', 'like', '%' . $new_params['community_name'] . '%'];
  3059. //客户种类 资源库,活动,经纪人,自建
  3060. if ($new_params['customer_type']) {
  3061. $gather = [
  3062. 1=>[['crm_res_id','not null',null]],//'资源库'
  3063. 2=>[['crm_res_id','null',null],['remark','not like','%活动报名建档%'],['agents_id','null',null]],//'自建'
  3064. 3=>[['remark','like','%活动报名建档%']],//'活动'
  3065. 4=>[['agents_id','>',0]]//'经纪人'
  3066. ];
  3067. $arr = explode(',',$new_params['customer_type']);
  3068. $whereOr = [];
  3069. foreach ($arr as $val) {
  3070. if (isset($gather[$val])) {
  3071. $whereOr[] = $gather[$val];
  3072. }
  3073. }
  3074. if (!empty($whereOr)) {
  3075. $new_cids = Customer::where($condition)->where(function($query) use ($whereOr){
  3076. $query->whereOr($whereOr);
  3077. })->column('id');
  3078. unset($condition);
  3079. $condition[] = ['id','in',$new_cids];
  3080. }else{
  3081. //无效条件
  3082. return json(['code' => 0, 'data' => [], 'count' => 0]);
  3083. }
  3084. }
  3085. //加微时间
  3086. if (!empty($new_params['add_wechat_time'])) {
  3087. $add_wechat_time = explode(' - ', $new_params['add_wechat_time']);
  3088. $start = str_replace('/','-',$add_wechat_time[0]);
  3089. $end = str_replace('/','-',$add_wechat_time[1] . ' 23:59:59');
  3090. $condition[] = ['add_wechat_time', '>=', $start];
  3091. $condition[] = ['add_wechat_time', '<', $end];
  3092. }
  3093. //下次回访时间
  3094. if (!empty($new_params['revisit_time'])) {
  3095. $revisit_time = explode(' - ', $new_params['revisit_time']);
  3096. $start = str_replace('/','-',$revisit_time[0]. ' 00:00:00');
  3097. $end = str_replace('/','-',$revisit_time[1] . ' 23:59:59');
  3098. $condition[] = ['revisit_time', '>', $start];
  3099. $condition[] = ['revisit_time', '<', $end];
  3100. }
  3101. //交房时间
  3102. if (!empty($new_params['house_delivery_time'])) {
  3103. $house_delivery_time = explode(' - ', $new_params['house_delivery_time']);
  3104. $start = $house_delivery_time[0];
  3105. $end = $house_delivery_time[1] . ' 23:59:59';
  3106. $condition[] = ['house_delivery_time', '>=', $start];
  3107. $condition[] = ['house_delivery_time', '<=', $end];
  3108. }
  3109. //报名时间
  3110. if (!empty($new_params['sign_time'])) {
  3111. $sign_time = explode(' - ', $new_params['sign_time']);
  3112. $start = str_replace('/','-',$sign_time[0]. ' 00:00:00');
  3113. $end = str_replace('/','-',$sign_time[1]. ' 23:59:59');
  3114. $condition[] = ['sign_time', '>=', $start];
  3115. $condition[] = ['sign_time', '<=', $end];
  3116. }
  3117. //客户的跟进时间
  3118. if(!empty($new_params['last_contact_date'])){
  3119. $last_contact = explode(' - ', $new_params['last_contact_date']);
  3120. $start = str_replace('/','-',$last_contact[0]);
  3121. $end = str_replace('/','-',$last_contact[1]);
  3122. $condition[] = ['last_contact_date','>=',$start];
  3123. $condition[] = ['last_contact_date','<=',$end];
  3124. }
  3125. //首次量房时间
  3126. if(!empty($new_params['first_liangfang'])){
  3127. $first_liangfang = explode(' - ', $new_params['first_liangfang']);
  3128. $start = str_replace('/','-',$first_liangfang[0]);
  3129. $end = date('Y-m-d', strtotime($first_liangfang[1]) + 86400);
  3130. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  3131. $lf_where[] = ['customer_id', 'in', $customersIdList];
  3132. $lf_where[] = ['state', 'in', CustomerVisitLog::changeState('已量房', 'chaos')];
  3133. $lf_where[] = ['addtime','>=',$start];
  3134. $lf_where[] = ['addtime','<=',$end];
  3135. $lflog = CustomerVisitLog::where($lf_where)->group('customer_id')->order('addtime asc')->column('customer_id');
  3136. unset($condition);
  3137. $condition[] = ['id','in',$lflog];
  3138. }
  3139. //首次到店时间
  3140. if(!empty($new_params['fisttime'])){
  3141. $fisttime = explode(' - ', $new_params['fisttime']);
  3142. $start = str_replace('/','-',$fisttime[0]);
  3143. $end = date('Y-m-d', strtotime($fisttime[1]) + 86400);
  3144. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  3145. $dd_where[] = ['customer_id', 'in', $customersIdList];
  3146. $dd_where[] = ['state', 'in', CustomerVisitLog::changeState('已到店', 'chaos')];
  3147. $dd_where[] = ['confirm_date','>=',$start];
  3148. $dd_where[] = ['confirm_date','<=',$end];
  3149. $ddlog = CustomerVisitLog::where($dd_where)->group('customer_id')->order('addtime asc')->column('customer_id');
  3150. unset($condition);
  3151. $condition[] = ['id','in',$ddlog];
  3152. }
  3153. //预计见面时间
  3154. if (!empty($new_params['subscribe_date'])) {
  3155. $subscribe_date = explode(' - ', $new_params['subscribe_date']);
  3156. $start = $subscribe_date[0];
  3157. $end = date('Y-m-d', strtotime($subscribe_date[1]) + 86400);
  3158. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  3159. $yj_where[] = ['customer_id', 'in', $customersIdList];
  3160. $yj_where[] = ['state', '=', 0];
  3161. $yj_where[] = ['subscribe_date', '>=', $start];
  3162. $yj_where[] = ['subscribe_date', '<=', $end];
  3163. $sublog = CustomersSubscribe::where($yj_where)->group('customer_id')->order('subscribe_date desc')->column('customer_id');
  3164. unset($condition);
  3165. $condition[] = ['id','in',$sublog];
  3166. }
  3167. //签单时间
  3168. if(!empty($new_params['jiaoding_time'])){
  3169. $fisttime = explode(' - ', $new_params['jiaoding_time']);
  3170. $start = str_replace('/','-',$fisttime[0]. ' 00:00:00');
  3171. $end = str_replace('/','-',$fisttime[1] . ' 23:59:59');
  3172. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  3173. $dd_where[] = ['customer_id', 'in', $customersIdList];
  3174. $dd_where[] = ['state', 'in', CustomerVisitLog::changeState('已交定', 'chaos')];
  3175. $ddlog = CustomerVisitLog::where($dd_where)->whereBetween('addtime',[$start,$end])->group('customer_id')->order('addtime asc')->column('customer_id');
  3176. unset($condition);
  3177. $condition[] = ['id','in',$ddlog];
  3178. }
  3179. //签单时间
  3180. if(!empty($new_params['qiandan_time'])){
  3181. $fisttime = explode(' - ', $new_params['qiandan_time']);
  3182. $start = str_replace('/','-',$fisttime[0]. ' 00:00:00');
  3183. $end = str_replace('/','-',$fisttime[1] . ' 23:59:59');
  3184. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  3185. $dd_where[] = ['customer_id', 'in', $customersIdList];
  3186. $dd_where[] = ['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')];
  3187. $ddlog = CustomerVisitLog::where($dd_where)->whereBetween('addtime',[$start,$end])->group('customer_id')->order('addtime asc')->column('customer_id');
  3188. unset($condition);
  3189. $condition[] = ['id','in',$ddlog];
  3190. }
  3191. //客户经理
  3192. if(!empty($new_params['assign_list'])){
  3193. $assign_employee = explode(',', $new_params['assign_list']);
  3194. $customerIdList = Customer::where($condition)->where(function($query) use ($assign_employee){
  3195. foreach ($assign_employee as $v) {
  3196. $query->whereOr([['assigned_personnel', 'find in set', $v]]);
  3197. }
  3198. })->column('id');
  3199. unset($condition);
  3200. $condition[] = ['id','in',$customerIdList];
  3201. }
  3202. //未跟进天数
  3203. if (!empty($new_params['no_visit_day'])) {
  3204. $no_visit_day = explode(',',$new_params['no_visit_day']);
  3205. $all_no_visit = [
  3206. 1=>[3,7],
  3207. 2=>[8,14],
  3208. 3=>[15,30],
  3209. 4=>[31,10000]
  3210. ];
  3211. $customersList = Customer::where($condition)->order('addtime desc')->column('id,addtime');
  3212. $wg_where[] = ['customer_id', 'in', array_column($customersList,'id')];
  3213. $latest_visit_log = CustomerVisitLog::where($wg_where)->group('customer_id')->column('max(addtime) as addtime','customer_id');//->select()->toArray();
  3214. $no_visit_ids = [];
  3215. foreach($customersList as $k=>$v){
  3216. if (empty($latest_visit_log[$v['id']])) {
  3217. $no_visit_long = ceil((time() - strtotime($v['addtime']))/86400);
  3218. } else {
  3219. $no_visit_long = ceil((time() - strtotime($latest_visit_log[$v['id']]))/86400);
  3220. }
  3221. foreach($no_visit_day as $m=>$p){
  3222. if(empty($all_no_visit[$p])) continue;
  3223. if($no_visit_long >= $all_no_visit[$p][0] && $no_visit_long <= $all_no_visit[$p][1]) $no_visit_ids[] = $v['id'];
  3224. }
  3225. }
  3226. unset($condition);
  3227. $condition[] = ['id','in',$no_visit_ids];
  3228. }
  3229. // 房屋面积
  3230. if (!empty($new_params['square'])){
  3231. $square = explode(',',$new_params['square']);
  3232. $square_arr = [
  3233. 1=>'(square > 1 and square <= 80)',
  3234. 2=>'(square > 81 and square <= 100)',
  3235. 3=>'(square > 101 and square <= 120)',
  3236. 4=>'(square > 121 and square <= 200)',
  3237. 5=>'(square > 201 and square <= 500)',
  3238. 6=>'(square > 501 and square <= 10000)'
  3239. ];
  3240. $squ_whereOr=null;
  3241. foreach($square as $k=>$v){
  3242. if(!empty($square_arr[$v])) $squ_whereOr.= $square_arr[$v]. ' OR';
  3243. }
  3244. $customersList = Customer::where($condition)->where(function($query) use ($squ_whereOr){
  3245. $query->whereRaw(trim($squ_whereOr,' OR'));
  3246. })->order('addtime desc')->column('id');
  3247. unset($condition);
  3248. $condition[] = ['id','in',$customersList];
  3249. }
  3250. //业务员所属部门
  3251. if(!empty($new_params['emporg'])){
  3252. $orgids = explode(',',$new_params['emporg']);
  3253. $empids = Employee::where([['root_id','=',$root_id],['org_id','in',$orgids]])->column('id');
  3254. $customersList = Customer::where($condition)->where('employee_id','in',$empids)->column('id');
  3255. unset($condition);
  3256. $condition[] = ['id','in',$customersList];
  3257. }
  3258. if ($search_type == 1) {
  3259. if (!empty($param['addtime'])) {
  3260. //录入时间
  3261. $addtimeArr = explode(' - ', $param['addtime']);
  3262. $start = $addtimeArr[0];
  3263. $end = date('Y-m-d', strtotime($addtimeArr[1]) + 86400);
  3264. $startTime = strtotime($start) - 1;
  3265. $endTime = strtotime($end);
  3266. }
  3267. } else {
  3268. if (!empty($param['followtime'])) {
  3269. //录入时间
  3270. $addtimeArr = explode(' - ', $param['followtime']);
  3271. $start = $addtimeArr[0];
  3272. $end = date('Y-m-d', strtotime($addtimeArr[1]) + 86400);
  3273. $startTime = strtotime($start) - 1;
  3274. $endTime = strtotime($end);
  3275. }
  3276. }
  3277. // 状态筛选
  3278. $c_ids = [];
  3279. if (!empty($param['state'])) {
  3280. $condition1[] = ['state','in',Customer::changeState('待确认','chaos')];
  3281. $condition1[] = ['crm_res_id','NULL',null];
  3282. $condition2[] = ['state','not in',Customer::changeState('待确认','chaos')];
  3283. //从公海获取的客户是资源库的要显示在客户池
  3284. $condition3[] = ['state','in',Customer::changeState('待确认','chaos')];
  3285. $condition3[] = ['crm_res_id','NOTNULL',null];
  3286. $condition3[] = ['valid_time','NOTNULL',null];
  3287. $customersIdList = Customer::where($condition)->where(function($query) use ($condition1,$condition2,$condition3){
  3288. $query->whereOr([$condition1,$condition2,$condition3]);
  3289. })->order('addtime desc')->column('id');
  3290. $stateall = explode(',',$param['state']);
  3291. $allsta = [];
  3292. foreach($stateall as $k=>$v){
  3293. if($v == '已签单') $v = '已交定';
  3294. if($v == '已转单') $v = '已签单';
  3295. if(in_array($v,['待确认','有效','未到访'])) continue;
  3296. $onestate = CustomerVisitLog::changeState($v,'chaos');
  3297. $allsta = array_merge($onestate,$allsta);
  3298. }
  3299. $visit_where[] = ['customer_id', 'in', $customersIdList];
  3300. $visit_where[] = ['state', 'in',$allsta];
  3301. $visit_where[] = ['addtime', '>', date('Y-m-d H:i:s', $startTime)];
  3302. $visit_where[] = ['addtime', '<', date('Y-m-d H:i:s', $endTime)];
  3303. $logCustomersIdList = CustomerVisitLog::where($visit_where)->group('customer_id')->column('customer_id');
  3304. $c_ids = $logCustomersIdList;
  3305. foreach($stateall as $k=>$v){
  3306. if($v == '待确认'){
  3307. $confirmedids = Customer::where($condition)->where(function($query) use ($condition1,$condition3){
  3308. $query->whereOr([$condition1,$condition3]);
  3309. })->column('id');
  3310. }
  3311. if($v=='有效'){
  3312. $validids = Customer::where($condition)->where('state','not in',Customer::changeState('待确认','chaos'))->column('id');
  3313. }
  3314. if($v=='未到访'){
  3315. $novisitids = Customer::where($condition)->where('state','in',Customer::changeState('未到访','chaos'))->column('id');
  3316. }
  3317. }
  3318. unset($condition,$condition1,$condition2,$condition3);
  3319. if(!empty($confirmedids)) $c_ids = array_merge($confirmedids,$c_ids);
  3320. if(!empty($validids)) $c_ids = array_merge($validids,$c_ids);
  3321. if(!empty($novisitids)) $c_ids = array_merge($novisitids,$c_ids);
  3322. }else{
  3323. //2023-02-10 客户有效状态 为排除待确认和无效, 或者 待确认并且不是资源库过来的
  3324. $state1 = Customer::changeState('待确认', 'chaos');
  3325. $state2 = Customer::changeState('无效', 'chaos');
  3326. $query1 = array_merge($condition,[['state', 'not in', array_merge($state1,$state2)]]);
  3327. $query2 = array_merge($condition,[['state', 'in',$state1],['crm_res_id','NULL',NULL]]);
  3328. $query3 = array_merge($condition,[['state', 'in',$state1],['crm_res_id','NOTNULL',NULL],['valid_time','NOTNULL',null]]);
  3329. $ids = Customer::whereOr([$query1,$query2,$query3])->order('id desc')->column('id');
  3330. unset($condition);
  3331. $c_ids = $ids;
  3332. }
  3333. if ($array_intersect) {
  3334. $c_ids = array_intersect($c_ids, $array_intersect_ids);
  3335. $count = count($c_ids);
  3336. $c_ids = array_slice($c_ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  3337. $condition[] = ['id', 'in', $c_ids];
  3338. } else {
  3339. $count = count($c_ids);
  3340. $c_ids = array_slice($c_ids, ($param['page'] - 1) * $param['limit'], $param['limit']);
  3341. $condition[] = ['id', 'in', $c_ids];
  3342. }
  3343. $order = isset($param['order']) ? $param['order'] : 'id desc';
  3344. $page = intval($param['page']);
  3345. $limit = intval($param['limit']);
  3346. //$data = $this->selCustomer($condition, $page, $limit, $order, $root_id);
  3347. $data = $this->selCustomer($condition, 0, 0, $order, $root_id);
  3348. $no_visit_state = ['未到访', '待确认'];
  3349. if(!empty($stateall) && in_array('未到访',$stateall)) $no_visit_state = ['待确认'];
  3350. $visit_state = ['已到店', '已量房', '已到场', '已签单', '已转单', '已卖卡'];
  3351. foreach($data as &$item) {
  3352. //客户种类
  3353. $item['customer_type'] = $item['crm_res_id'] ? '资源库' : ($item['remark'] == '活动报名建档' ? '活动' : ($item['agents_id'] ? '经纪人' : '自建'));
  3354. // 有'已到店', '已量房', '已到场', '已签单', '已转单'状态的话不显示未到访、待确认
  3355. // 有未到访状态不显示待确认
  3356. $state = explode(',', $item['state']);
  3357. $jiaoji = array_intersect($visit_state, $state);
  3358. $no_jiaoji = array_intersect($no_visit_state, $state);
  3359. if (count($no_jiaoji) == 2) { // 有未到访、待确认两个状态
  3360. $state = ['未到访'];
  3361. }
  3362. if (count($state) > 1 && count($jiaoji) > 0) {
  3363. $state = array_diff($state, $no_visit_state);
  3364. }
  3365. $item['state'] = implode(',', $state);
  3366. }
  3367. //$count = Customer::where($condition)->count();
  3368. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  3369. }
  3370. /**
  3371. * 以客户跟进为主的查询条件
  3372. *
  3373. */
  3374. public function logCondition(){
  3375. $param = $this->request->only(['followtime' => '', 'source' => '', 'employee_id' => '', 'org_id' => '', 'type' => '']);
  3376. $is_manager = request()->empcrm->is_manager;
  3377. $employee_id = request()->empcrm->id;
  3378. $org_id = request()->empcrm->org_id;
  3379. $startTime = strtotime('2015-01-01');
  3380. $endTime = strtotime(date('Y-m-d')) + 86400;
  3381. if (!empty($param['followtime'])) {
  3382. //录入时间
  3383. $addtimeArr = explode(' - ', $param['followtime']);
  3384. $start = $addtimeArr[0];
  3385. $end = date('Y-m-d', strtotime($addtimeArr[1]) + 86400);
  3386. $startTime = strtotime($start) - 1;
  3387. $endTime = strtotime($end);
  3388. }
  3389. // 查询条件
  3390. // 设计师部门管理员,需要查询指派给下属设计师的客户信息
  3391. $org_type = Org::where('id', '=', $org_id)->value('org_type');
  3392. if ($param['org_id']) {
  3393. $param_sub_org = orgSubIds($param['org_id']);
  3394. } else {
  3395. $param_sub_org = orgSubIds($org_id);
  3396. }
  3397. if ($org_type == 2) {
  3398. if($is_manager == 1){
  3399. $designer_employee = Employee::where([['org_id', 'in', $param_sub_org], ['uid', '<>', 0], ['state', '=', '在职']])->column('id');
  3400. $condition[] = ['designer_id', 'in', $designer_employee];
  3401. $condition_log[] = ['Customer.designer_id', 'in', $designer_employee];
  3402. $s_where[] = ['employee_id', 'in', $designer_employee];
  3403. // 是哪个员工
  3404. setCondition($param['employee_id'], 'designer_id', '=', $condition);
  3405. setCondition($param['employee_id'], 'Customer.designer_id', '=', $condition_log);
  3406. setCondition($param['employee_id'], 'employee_id', '=', $s_where);
  3407. } else {
  3408. $condition[] = ['designer_id', '=', $employee_id];
  3409. $condition_log[] = ['Customer.designer_id', '=', $employee_id];
  3410. $s_where[] = ['employee_id', '=', $employee_id];
  3411. }
  3412. } else {
  3413. if($is_manager == 1){
  3414. $condition[] = ['org_id', 'in', $param_sub_org];
  3415. $condition[] = ['employee_id', '>', 0];
  3416. $condition_log[] = ['Customer.org_id', 'in', $param_sub_org];
  3417. $condition_log[] = ['Customer.employee_id', '>', 0];
  3418. $s_where[] = ['org_id', 'in', $param_sub_org];
  3419. $s_where[] = ['employee_id', '>', 0];
  3420. // 是哪个员工
  3421. setCondition($param['employee_id'], 'employee_id', '=', $condition);
  3422. setCondition($param['employee_id'], 'Customer.employee_id', '=', $condition_log);
  3423. setCondition($param['employee_id'], 'employee_id', '=', $s_where);
  3424. } else {
  3425. $condition[] = ['employee_id', '=', $employee_id];
  3426. $condition_log[] = ['Customer.employee_id', '=', $employee_id];
  3427. $s_where[] = ['employee_id', '=', $employee_id];
  3428. }
  3429. }
  3430. $condition[] = ['died', '<>', 2];
  3431. $condition[] = ['state', 'not in', Customer::changeState('无效', 'chaos')];
  3432. $condition_log[] = ['Customer.died', '<>', 2];
  3433. $condition_log[] = ['Customer.state', 'not in', Customer::changeState('无效', 'chaos')];
  3434. $state_n = Customer::changeState('待确认', 'chaos');
  3435. $state_w = Customer::changeState('无效', 'chaos');
  3436. $query1 = array_merge($condition,[['state', 'not in', array_merge($state_n,$state_w)]]);
  3437. $query2 = array_merge($condition,[['state', 'in',$state_n],['crm_res_id','NULL',NULL]]);
  3438. $ids = Customer::whereOr([$query1,$query2])->column('id');
  3439. // 模块
  3440. // 加v
  3441. $condition_jiav = $condition;
  3442. $condition_jiav[] = ['add_wechat_time', '>', date('Y-m-d H:i:s', $startTime)];
  3443. $condition_jiav[] = ['add_wechat_time', '<', date('Y-m-d H:i:s', $endTime)];
  3444. $jiav_ids_find = Customer::where($condition_jiav)->column('id');
  3445. $jiav_ids = array_intersect($jiav_ids_find, $ids);
  3446. // 交房
  3447. $condition_jiaofang = $condition;
  3448. $condition_jiaofang[] = ['house_delivery_time', '>', date('Y/m/d H:i:s', $startTime)];
  3449. $condition_jiaofang[] = ['house_delivery_time', '<', date('Y/m/d H:i:s', $endTime)];
  3450. $jiaofang_ids_find = Customer::where($condition_jiaofang)->column('id');
  3451. $jiaofang_ids = array_intersect($jiaofang_ids_find, $ids);
  3452. //预计量房 预计到店
  3453. if ($is_manager) {
  3454. $s_where[] = ['org_id', 'in', $param_sub_org];
  3455. } else {
  3456. $s_where[] = ['employee_id', '=', $employee_id];
  3457. }
  3458. $s_where[] = ['state', '=', 0];
  3459. $s_where[] = ['addtime', '>', date('Y-m-d H:i:s', $startTime)];
  3460. $s_where[] = ['addtime', '<', date('Y-m-d H:i:s', $endTime)];
  3461. $s_where[] = ['type', 'in', [1,3]];
  3462. $yuji_ids_find = CustomersSubscribe::where($s_where)->group('customer_id')->column('customer_id');
  3463. $yuji_ids = array_intersect($yuji_ids_find, $ids);
  3464. $customer_ids_1 = array_values(array_unique(array_merge($jiav_ids, $jiaofang_ids, $yuji_ids)));
  3465. // 时间段内有跟踪
  3466. $condition_log[] = ['CustomerVisitLog.addtime', '>', date('Y-m-d H:i:s', $startTime)];
  3467. $condition_log[] = ['CustomerVisitLog.addtime', '<', date('Y-m-d H:i:s', $endTime)];
  3468. $customer_ids_2_find = Db::view('Customer')
  3469. ->view('Org', '', 'Org.id=Customer.org_id')
  3470. ->view('CustomerVisitLog', '', 'Customer.id=CustomerVisitLog.customer_id')
  3471. ->where($condition_log)
  3472. ->group('Customer.id')
  3473. ->column('Customer.id');
  3474. $customer_ids_2 = array_intersect($customer_ids_2_find, $ids);
  3475. $customer_ids = array_values(array_unique(array_merge($customer_ids_1, $customer_ids_2)));
  3476. return $customer_ids;
  3477. }
  3478. /**
  3479. * 判断能否查看客户详情
  3480. */
  3481. public function checkCustomer() {
  3482. $id = input('id', '', 'intval');
  3483. $request = request();
  3484. $empid = $request->empcrm->id;
  3485. $is_manager = $request->empcrm->is_manager;
  3486. $where = [
  3487. ['id', '=', $id],
  3488. ['state', '<>', '无效']
  3489. ];
  3490. $data = Customer::where($where)->find();
  3491. if (empty($data)){
  3492. return json(['code'=> 1, 'msg'=> '无法查看此客户,请刷新后重试']);
  3493. }
  3494. $empIdList = explode(',', $data->employee_id . ',' . $data->employee_id . ',' . $data->assigned_personnel);
  3495. $empIdList = array_unique(array_filter($empIdList));
  3496. if(!empty($data) && !in_array($empid, $empIdList)){
  3497. if ($is_manager == 1) {
  3498. $team_orgs = orgSubIds($request->empcrm->org_id);
  3499. $yuangong = Employee::where([['org_id', 'in', $team_orgs], ['uid', '>', 0], ['id', 'in', $empIdList]])->count();
  3500. if ($yuangong == 0) $data = null;
  3501. } else {
  3502. $data = null;
  3503. }
  3504. }
  3505. if (empty($data)){
  3506. return json(['code'=> 1, 'msg'=> '无法查看此客户,请刷新后重试']);
  3507. }
  3508. return json(['code'=> 0, 'msg'=> 'success']);
  3509. }
  3510. //添加回访记录
  3511. public function addlog()
  3512. {
  3513. $request = request();
  3514. $root_id = $request->empcrm->root_id;
  3515. $empid = $request->empcrm->id;
  3516. $is_manager = $request->empcrm->is_manager;
  3517. $team_orgs = orgSubIds($request->empcrm->org_id);
  3518. $param = $this->request->only(['cid','org_id'=>'']);
  3519. $orgids = orgSubIds($root_id);
  3520. //if(!empty($param['org_id']) && !in_array($param['org_id'],$team_orgs)){
  3521. //管理层跟员工校验时
  3522. if(!empty($param['org_id']) && in_array($param['org_id'],$orgids)){
  3523. $ms = $this->other_seLemp($param['cid'],$param['org_id']);
  3524. $is_sharecus = 1;
  3525. }else{
  3526. $ms = $this->seLemp($param['cid'],$empid);
  3527. }
  3528. $data = $ms->toArray();
  3529. $stain = [];
  3530. if(!empty($data['visitLog'])){
  3531. $state1 = CustomerVisitLog::changeState('已到店', 'chaos');
  3532. $state2 = CustomerVisitLog::changeState('已到场', 'chaos');
  3533. foreach($data['visitLog'] as $key=>$val){
  3534. if($val['state'] == '已签单' && $request->empcrm['xinjushang'] == 0) $val['state'] = '已转单';
  3535. if($val['state'] == '已交定' && $request->empcrm['xinjushang'] == 0) $val['state'] = '已签单';
  3536. if($val['state'] == '已转单' && $request->empcrm['xinjushang'] == 0) $data['visitLog'][$key]['remark'] = str_replace('已签单','已转单',$val['remark']);
  3537. if($val['state'] == '已签单' && $request->empcrm['xinjushang'] == 0) $data['visitLog'][$key]['remark'] = str_replace('已交定','已签单',$val['remark']);
  3538. $data['visitLog'][$key]['state'] = $val['state'];
  3539. $data['visitLog'][$key]['empname'] = Employee::where('id',$val['employee_id'])->value('name');
  3540. if(!in_array($val['state'],$stain)){
  3541. $stain[] = $val['state'];
  3542. }
  3543. if(!empty($val['save_portrait_field'])){
  3544. $save_portrait_field = json_decode($val['save_portrait_field'],true);
  3545. foreach($save_portrait_field as $k=>$v){
  3546. if($v['type'] == 6){
  3547. $save_portrait_field[$k]['valname'] = explode(',',$v['value']);
  3548. }
  3549. }
  3550. }else{
  3551. $save_portrait_field = '';
  3552. }
  3553. $data['visitLog'][$key]['save_portrait_field'] = $save_portrait_field;
  3554. $parr[] = $val['addtime'];
  3555. if($val['next_contact_date'] > date('Y-m-d H:i:s')){
  3556. $data['visitLog'][$key]['isyes'] = 1;
  3557. }else{
  3558. $data['visitLog'][$key]['isyes'] = 0;
  3559. }
  3560. $data['visitLog'][$key]['wisdom_url'] = '';
  3561. $data['visitLog'][$key]['is_wisdom'] = 0;
  3562. if ($val['remark'] && strpos($val['remark'],'讲解智慧屏##')!==false) {
  3563. //remark = 接待了客户:张三,讲解时长21分钟@讲解智慧屏## url;
  3564. $data['visitLog'][$key]['is_wisdom'] = 1;
  3565. $arr = explode('##',$val['remark']);
  3566. if(count($arr)==2){
  3567. $ali_oss_bindurl = config('app.ali_oss_bindurl');
  3568. $data['visitLog'][$key]['wisdom_url'] = 'https://' . $ali_oss_bindurl . '/' . $arr[1];
  3569. $title = explode('@',$arr[0]);
  3570. $data['visitLog'][$key]['remark'] = $title[0];
  3571. }
  3572. }
  3573. // 检测是否有录音
  3574. if($val['data_type'] == 'out_call'){
  3575. $data['visitLog'][$key]['is_wisdom'] = 2;
  3576. $data['visitLog'][$key]['wisdom_url'] = OutCallLog::where(['id'=>$val['data_id']])->value('url');
  3577. }
  3578. if ($val['number_of_visitors'] > 0 && in_array($val['state'], $state1)) {
  3579. $val['remark'] = $val['remark'] . ' 到店人数:' . $val['number_of_visitors'] . '人;';
  3580. $data['visitLog'][$key]['remark'] = $val['remark'];
  3581. }
  3582. if ($val['talking_order_time'] && in_array($val['state'], $state1)) {
  3583. $val['remark'] = $val['remark'] . ' 谈单时长:' . $val['talking_order_time'] . '分钟;';
  3584. $data['visitLog'][$key]['remark'] = $val['remark'];
  3585. }
  3586. if ($val['number_of_visitors'] > 0 && in_array($val['state'], $state2)) {
  3587. $val['remark'] = $val['remark'] . ' 到场人数:' . $val['number_of_visitors'] . '人;';
  3588. $data['visitLog'][$key]['remark'] = $val['remark'];
  3589. }
  3590. if ($val['stay_length'] && in_array($val['state'], $state2)) {
  3591. $val['remark'] = $val['remark'] . ' 停留时间:' . $val['stay_length'] . '分钟;';
  3592. $data['visitLog'][$key]['remark'] = $val['remark'];
  3593. }
  3594. //检测是否有下载文件
  3595. if(!empty($val['document_field']) && !empty($val['document_name'])){
  3596. $str = $root_id.'#'.$empid.'#'.$val['id'];
  3597. $aec = new Aec(config('app.aec_key'), config('app.aec_iv'));
  3598. $value = $aec->encrypt($str);
  3599. $data['visitLog'][$key]['document_field'] = $request->domain().'/downdocument/index.html?token='.$value;
  3600. }
  3601. }
  3602. array_multisort($parr, SORT_DESC, $data['visitLog']);
  3603. }
  3604. $data['allstate'] = $stain;
  3605. //房屋状态
  3606. $house_status=CustomerPortraitField::with(['select'])->where([['root_id','=',$root_id],['keyname','=','house_status']])->find()->toArray();
  3607. View::assign('house_status', $house_status['select']);
  3608. View::assign('empname', $request->empcrm->name);
  3609. //指派类型
  3610. $assign_count = Setting::where([['root_id','=',$root_id],['name','=','assign_type']])->findOrEmpty();
  3611. $assign_name = !$assign_count->isEmpty() ? json_decode($assign_count->content,true) : [];
  3612. $assign_list = [];
  3613. foreach($assign_name as $k=>$v){
  3614. if($v=='yixiang') $assign_list[] =['keyname'=>$v,'value'=>'意向客户指派'];
  3615. if($v=='liangfang') $assign_list[] =['keyname'=>$v,'value'=>'量房客户指派'];
  3616. if($v=='daodian') $assign_list[] =['keyname'=>$v,'value'=>'到店客户指派'];
  3617. }
  3618. View::assign('assign_list', $assign_list);
  3619. $isadd_log = 0;
  3620. $path = Org::where([['pid','=',$request->empcrm->org_id]])->count();
  3621. if(empty($path) && $is_manager && in_array($data['org_id'],$team_orgs)){
  3622. $isadd_log = 1;
  3623. }
  3624. if($data['employee_id'] == $empid){
  3625. $isadd_log = 1;
  3626. }
  3627. if(!empty($is_sharecus) && $is_manager) $isadd_log = 1;
  3628. View::assign('data', $data);
  3629. View::assign('isadd_log', $isadd_log);
  3630. View::assign('is_manager', $is_manager);
  3631. // 判断是否有外呼系统
  3632. $outcallSetting = OutCallSetting::where(['root_id' => $root_id, 'type' => 'yhuatong'])->find();
  3633. if ($outcallSetting !== null) {
  3634. // 如果有外呼系统则获取登陆人拨打的电话列表
  3635. View::assign('outcall', 1);
  3636. $phones = empty($request->empcrm['out_call_phone']) ? [] : explode(',', $request->empcrm['out_call_phone']);
  3637. array_unshift($phones, $request->empcrm['phone']);
  3638. View::assign('outcall_phone', $phones);
  3639. } else {
  3640. View::assign('outcall', 0);
  3641. }
  3642. //判断下次回访时间是否必传
  3643. $next_where[] = ['root_id', '=', $root_id];
  3644. $next_where[] = ['name', '=', 'nextVisitTimeIsOk'];
  3645. $nextVisitTimeIsOk = Setting::where($next_where)->value('content');
  3646. View::assign('nextVisitTimeIsOk', $nextVisitTimeIsOk);
  3647. return View::fetch();
  3648. }
  3649. //公用查询客户详情
  3650. public function other_seLemp($id,$org_id)
  3651. {
  3652. $request = request();
  3653. $root_id = $request->empcrm->root_id;
  3654. $orgids = orgSubIds($root_id);
  3655. if(!in_array($org_id,$orgids)) echo json(['code'=>1,'msg'=>'数据不存在']);
  3656. $condition = [
  3657. ['org_id', '=', $org_id],
  3658. ['id', '=', $id]
  3659. ];
  3660. $data = Customer::with(['source', 'designer' => function ($query) {
  3661. $query->field('id,name,headimgurl,org_id,uid');
  3662. }, 'employee' => function ($query) {
  3663. $query->withField(['id','name']);
  3664. },'visitLog' => function ($query){
  3665. $query->field('id,customer_id,type,next_contact_date,remark,addtime,employee_id,state,customer_employee_id,img,img1,sign_img,delivery_img,save_portrait_field,data_type,data_id,number_of_visitors,talking_order_time,stay_length,document_field,document_name');
  3666. }])->where($condition)->find();
  3667. if (empty($data)) echo json(['code' => 1, 'msg' => '数据不存在']);
  3668. //if (empty($data)) return false;
  3669. $data['daochang'] = CustomerVisitLog::where([['customer_id', '=', $id],['employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已到访'])])->order('addtime desc')->find();
  3670. $data['deposit'] = CustomerVisitLog::where([['customer_id', '=', $id],['employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '交定'])])->order('addtime desc')->field("id,money,DATE_FORMAT(confirm_date, '%Y-%m-%d') as confirm_date")->find();
  3671. $data['sign'] = CustomerVisitLog::where([['customer_id', '=', $id],['employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '签单'])])->order('addtime desc')->field("id,money,DATE_FORMAT(confirm_date, '%Y-%m-%d') as confirm_date")->find();
  3672. $data['dd'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已到店'])])->order('addtime desc')->value("DATE_FORMAT(confirm_date, '%Y-%m-%d')");
  3673. $data['lf'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已量房'])])->order('addtime desc')->value("DATE_FORMAT(confirm_date, '%Y-%m-%d')");
  3674. $data['package_name'] = $data['package_id'] ? CustomerPackage::where('id',$data['package_id'])->value('name') :'';
  3675. $data['deco_style_name'] = $data['deco_style'] ? Decostyle::where('id',$data['deco_style'])->value('name') : '';
  3676. //$data['company_name'] = Company::where('root_id',$root_id)->value('company_name');
  3677. $data['add_wechat'] = '否';
  3678. $data['housetype'] = $data['unit_number'] = $data['subjection_plan'] = null;
  3679. if(!empty($data['ext'])){
  3680. $field = $this->get_portrait_field($data);
  3681. foreach($field as $key=>$val){
  3682. if($val['keyname'] == 'wechat' && !empty($val['value'])){
  3683. $data['add_wechat'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3684. }
  3685. if($val['keyname']=='housetype_arrow' && !empty($val['value'])){
  3686. $data['housetype'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3687. }
  3688. if($val['keyname']=='subjection_plan' && !empty($val['value'])){
  3689. $data['subjection_plan'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3690. }
  3691. if($val['keyname']=='unit_number' && !empty($val['value'])){
  3692. $data['unit_number'] = $val['value'];
  3693. }
  3694. }
  3695. }
  3696. $data['daochang'] = !empty($data['daochang']) ? json_decode($data['daochang'],true) : null;
  3697. $data['deposit'] = !empty($data['deposit']) ? json_decode($data['deposit'],true) : null;
  3698. $data['sign'] = !empty($data['sign']) ? json_decode($data['sign'],true) : null;
  3699. return $data;
  3700. }
  3701. //公用查询客户详情
  3702. public function seLemp($id,$empid)
  3703. {
  3704. $request = request();
  3705. $root_id = $request->empcrm->root_id;
  3706. $empid = $request->empcrm->id;
  3707. $orgids = orgSubIds($root_id);
  3708. $is_manager = $request->empcrm->is_manager;
  3709. $where = [
  3710. ['id', '=', $id],
  3711. ['state', '<>', '无效']
  3712. ];
  3713. //增加查询是否要显示修改客户扩展字段信息功能
  3714. $showEmpVistlog = Setting::where([['root_id', '=', $root_id], ['name', '=', 'showEmpVistlog']])->findOrEmpty();
  3715. $visit = !$showEmpVistlog->isEmpty() ? (int)$showEmpVistlog->content : 0;
  3716. $vlg_where[] = $visit ? ['save_portrait_field','NULL',null] : ['id','>',0];
  3717. $data = Customer::with(['source', 'designer' => function ($query) {
  3718. $query->field('id,name,headimgurl,org_id,uid');
  3719. }, 'employee' => function ($query) {
  3720. $query->withField(['id','name']);
  3721. },'visitLog' => function ($query) use ($vlg_where){
  3722. $query->where($vlg_where)->field('id,customer_id,type,next_contact_date,remark,addtime,employee_id,state,customer_employee_id,img,img1,sign_img,delivery_img,save_portrait_field,data_type,data_id,number_of_visitors,talking_order_time,stay_length,document_field,document_name');
  3723. }])->where($where)->find();
  3724. $empIdList = explode(',', $data->employee_id . ',' . $data->employee_id . ',' . $data->assigned_personnel);
  3725. $empIdList = array_unique(array_filter($empIdList));
  3726. if(!empty($data) && !in_array($empid, $empIdList)){
  3727. if ($is_manager == 1) {
  3728. $team_orgs = orgSubIds($request->empcrm->org_id);
  3729. $yuangong = Employee::where([['org_id', 'in', $team_orgs], ['uid', '>', 0], ['id', 'in', $empIdList]])->count();
  3730. if ($yuangong == 0) $data = null;
  3731. } else {
  3732. $data = null;
  3733. }
  3734. }
  3735. if (empty($data)){
  3736. echo json_encode(['code' => 1, 'msg' => '数据不存在']);
  3737. exit;
  3738. }
  3739. $data['daochang'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已到访'])])->order('addtime desc')->find();
  3740. $data['deposit'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '交定'])])->order('addtime desc')->field("id,money,DATE_FORMAT(confirm_date, '%Y-%m-%d') as confirm_date,addtime")->find();
  3741. $data['sign'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '签单'])])->order('addtime desc')->field("id,money,DATE_FORMAT(confirm_date, '%Y-%m-%d') as confirm_date,addtime")->find();
  3742. $data['dd'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已到店'])])->order('addtime desc')->value("DATE_FORMAT(confirm_date, '%Y-%m-%d')");
  3743. $data['lf'] = CustomerVisitLog::where([['customer_id', '=', $id],['customer_employee_id','=',$data['employee_id']], CustomerVisitLog::changeState(['state', '=', '已量房'])])->order('addtime desc')->value("DATE_FORMAT(confirm_date, '%Y-%m-%d')");
  3744. $data['package_name'] = $data['package_id'] ? CustomerPackage::where('id',$data['package_id'])->value('name') :'';
  3745. $data['deco_style_name'] = $data['deco_style'] ? Decostyle::where('id',$data['deco_style'])->value('name') : '';
  3746. $data['company_name'] = Company::where('root_id',$root_id)->value('company_name');
  3747. $data['add_wechat'] = '否';
  3748. $data['housetype'] = $data['unit_number'] = $data['subjection_plan'] = null;
  3749. $data['sign_time'] = '';
  3750. if(!empty($data['ext'])){
  3751. $field = $this->get_portrait_field($data);
  3752. // var_dump($field);
  3753. // exit;
  3754. foreach($field as $key=>$val){
  3755. if($val['keyname'] == 'wechat' && !empty($val['value'])){
  3756. $data['add_wechat'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3757. }
  3758. if($val['keyname']=='housetype_arrow' && !empty($val['value'])){
  3759. $data['housetype'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3760. }
  3761. if($val['keyname']=='subjection_plan' && !empty($val['value'])){
  3762. $data['subjection_plan'] = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  3763. }
  3764. if($val['keyname']=='unit_number' && !empty($val['value'])){
  3765. $data['unit_number'] = $val['value'];
  3766. }
  3767. if($val['keyname']=='sign_name' && !empty($val['value'])){
  3768. $data['sign_time'] = $val['value'];
  3769. }
  3770. }
  3771. }
  3772. $data['daochang'] = !empty($data['daochang']) ? json_decode($data['daochang'],true) : null;
  3773. $data['deposit'] = !empty($data['deposit']) ? json_decode($data['deposit'],true) : null;
  3774. $data['sign'] = !empty($data['sign']) ? json_decode($data['sign'],true) : null;
  3775. $data['assigned_personnel'] = !empty($data['designer_id']) ? $data['assigned_personnel'].','.$data['designer_id'] : $data['assigned_personnel'];
  3776. return $data;
  3777. }
  3778. //新获取客户扩展字段
  3779. public function get_portrait_field($cusdata)
  3780. {
  3781. $request = request();
  3782. $root_id = $request->empcrm->root_id;
  3783. $empid = $request->empcrm->id;
  3784. $w[] = ['root_id', '=', $root_id];
  3785. $list=CustomerPortraitField::with(['select'])->where([['root_id','=',$root_id],['pid','<>',0]])->select()->toArray();
  3786. $cuslog=new CustomerLogic;
  3787. $new = $list;
  3788. if(!empty($cusdata['ext']) && $cusdata['ext'] != 'null'){
  3789. $extdata=json_decode($cusdata['ext'],true);
  3790. if(isset($extdata['ext1'])){
  3791. $new=$cuslog->old_data_saves($cusdata,$list);
  3792. }else{
  3793. $new=$cuslog->new_data_saves($cusdata,$extdata,$list);
  3794. }
  3795. }
  3796. return $new;
  3797. //return json(['code' => 0, 'data' => $new]);
  3798. }
  3799. //添加客户的回访记录
  3800. public function addVisitlog()
  3801. {
  3802. //$token = $this->request->token;
  3803. $request = request();
  3804. $root_id = $request->empcrm->root_id;
  3805. $empid = $request->empcrm->id;
  3806. $is_manager = $request->empcrm->is_manager;
  3807. //防止后台切换部门
  3808. $token['org_id'] = Employee::where('id', $empid)->value('org_id');
  3809. $param = request()->only(['customer_id', 'name'=>'','type'=>'', 'next_contact_date', 'remark'=>'', 'img' => '', 'state', 'money' => 0, 'aid' => 0, 'addtime' => date('Y-m-d H:i:s'), 'confirm_date' => '', 'weixin_media' => '', 'media_id' => '', 'starts' => 0, 'weixin_media1' => '', 'media_id1' => '', 'img1' => '', 'number_of_visitors' => 0, 'measure_room_img_type' => '', 'package' => '', 'deposit_mode' => 0,'house_status'=>'','other_money'=>0,'house_delivery_time'=>'','deco_style'=>'','designer_id'=>'','vlogid'=>'','document_field' =>'','document_name' => '']);
  3810. $param['confirm_date'] = $param['confirm_date'] ? $param['confirm_date'] . ' ' . date('H:i:s') : date('Y-m-d H:i:s');
  3811. $employeeTypeName = $this->request->empcrm['org_type'] == 2 ? '设计师' : '销售';
  3812. $employeeType = $this->request->empcrm['org_type'] == 2 ? 'designer_id' : 'employee_id';
  3813. if($is_manager ==1) $employeeTypeName = '部门领导';
  3814. //2022-10-04 逻辑修改,无效时无效原因必传remark
  3815. //if ($param['state'] == '无效' && empty($param['remark'])) return json(['code' => 1, 'msg' => '请填写无效原因']);
  3816. //2022-10-27 逻辑修改,跟进保护优化 如果后台设置了重复客户跟进保护规则 跟进到保护状态后其他业务员的此重复客户就不能在跟进了,但是可以置为无效
  3817. $forbiddenState = $this->forbiddenState($param['customer_id'],$param['state']);
  3818. if($forbiddenState != false) return json(['code' => 1, 'msg' =>$forbiddenState]);
  3819. if($is_manager ==1){
  3820. $team_orgs = orgSubIds($request->empcrm->org_id);
  3821. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0]])->column('id');
  3822. }else{
  3823. $org_employee = [$empid];
  3824. }
  3825. $where = [
  3826. ['id', '=', $param['customer_id']],
  3827. ['state', '<>', '无效']
  3828. ];
  3829. $had = Customer::where($where)->where(function($query) use ($org_employee){
  3830. foreach($org_employee as $k=>$v){
  3831. $query->whereOr([['employee_id|designer_id|assigned_personnel', 'find in set', $v]]);
  3832. }
  3833. })->find();
  3834. if (!$had) return json(['code' => 1, 'msg' => '添加失败,数据不存在']);
  3835. //签单之后不能置为无效
  3836. if ($param['state'] == '无效') {
  3837. $is_orders = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')], ['customer_id', '=', $had->id]])->count();
  3838. if ($is_orders) return json(['code' => 1, 'msg' => '该客户已签单,不能置为无效']);
  3839. }
  3840. //改为有效之后不能再改为待确认
  3841. if ($param['state'] == '待确认') {
  3842. if ($had->state != '待确认') return json(['code' => 1, 'msg' => '该客户已标记为有效,不能修改为待确认']);
  3843. }
  3844. // 撞单机制
  3845. if ($param['state'] == '未到访') {
  3846. // 同部门能否重复录入开关设置
  3847. $empcrm_repeat[] = ['root_id', '=', $root_id];
  3848. $empcrm_repeat[] = ['name', '=', 'empcrm_customer_repeat'];
  3849. $repeat_setting = Setting::where($empcrm_repeat)->findOrEmpty();
  3850. //判断同部门
  3851. if (!$repeat_setting->isEmpty()) {
  3852. $repeat_org = explode(',', $repeat_setting['content']);
  3853. if (in_array($this->request->empcrm['org_id'], $repeat_org)) {
  3854. // 需要验证
  3855. $not_sure = Customer::changeState('待确认', 'chaos');
  3856. $wuxiao = Customer::changeState('无效', 'chaos');
  3857. $phones_arr = array_filter([$had['phone'], $had['phone1'], $had['phone2']]);
  3858. $repeat_where[] = ['phone|phone1|phone2', 'in', $phones_arr];
  3859. $repeat_where[] = ['org_id', 'in', $repeat_org];
  3860. $repeat_where[] = ['state', 'not in', array_merge($not_sure, $wuxiao)];
  3861. $customerExist = Customer::where($repeat_where)->field('id,employee_id');
  3862. if (!empty($customerExist)) {
  3863. foreach ($customerExist as $ex) {
  3864. if ($ex['employee_id'] != $empid && $ex['id'] != $param['customer_id']) {
  3865. $have_emp = Employee::where('id', '=', $ex['employee_id'])->value('name');
  3866. return json(['code' => 2, 'msg' => '该客户与员工' . $have_emp . '撞单,无法标记有效']);
  3867. }
  3868. }
  3869. }
  3870. }
  3871. }
  3872. }
  3873. // 如果是预约添加预约记录
  3874. $stateType = [
  3875. 1 => '到店',
  3876. 2 => '到场',
  3877. 3 => '量房'
  3878. ];
  3879. $yylf_state = CustomerVisitLog::changeState('预约量房', 'chaos');
  3880. $lf_state = CustomerVisitLog::changeState('已量房', 'chaos');
  3881. $yydc_state = CustomerVisitLog::changeState('预约活动', 'chaos');
  3882. $dc_state = CustomerVisitLog::changeState('已到场', 'chaos');
  3883. $yydd_state = CustomerVisitLog::changeState('预约到店', 'chaos');
  3884. $dd_state = CustomerVisitLog::changeState('已到店', 'chaos');
  3885. $check_state = array_merge($yylf_state, $lf_state, $yydc_state, $dc_state, $yydd_state, $dd_state);
  3886. if (in_array($param['state'], $check_state)) {
  3887. // 保护设置
  3888. $sub_setting = Setting::where([['root_id', '=', $root_id], ['name', '=', 'subscribe_protected']])->findOrEmpty();
  3889. if (!$sub_setting->isEmpty()) { // 有设置
  3890. $setting_content = json_decode($sub_setting['content'], true);
  3891. $org_ids = orgSubIds($root_id);
  3892. foreach ($setting_content as $k_s => $v_s){
  3893. if (!empty($v_s['state']) && !empty($v_s['day']) && $v_s['state'] == 1){
  3894. $continue = false;
  3895. $sub_state = 0;
  3896. $errmsg = '该客户在保护期内,无法提交';
  3897. $check_log = false;
  3898. $check_where = [];
  3899. switch ($k_s){
  3900. case 'liangfang':
  3901. $sub_state = 3;
  3902. $visit_state = 1;
  3903. $check_log = true;
  3904. $check_where[] = ['org_id', 'in', $org_ids];
  3905. $check_where[] = ['addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$v_s['day'])];
  3906. $check_where[] = ['employee_id', '<>', $empid];
  3907. $check_where[] = ['state', 'in', $lf_state];
  3908. break;
  3909. case 'yliangfang': //预约量房
  3910. $sub_state = 3;
  3911. $visit_state = 0;
  3912. break;
  3913. case 'daodian':
  3914. $sub_state = 1;
  3915. $visit_state = 1;
  3916. $check_log = true;
  3917. $check_where[] = ['org_id', 'in', $org_ids];
  3918. $check_where[] = ['addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$v_s['day'])];
  3919. $check_where[] = ['employee_id', '<>', $empid];
  3920. $check_where[] = ['state', 'in', $dd_state];
  3921. break;
  3922. case 'ydaodian':
  3923. $sub_state = 1;
  3924. $visit_state = 0;
  3925. break;
  3926. case 'daochang':
  3927. $sub_state = 2;
  3928. $visit_state = 1;
  3929. $check_log = true;
  3930. $check_where[] = ['org_id', 'in', $org_ids];
  3931. $check_where[] = ['addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$v_s['day'])];
  3932. $check_where[] = ['employee_id', '<>', $empid];
  3933. $check_where[] = ['state', 'in', $dc_state];
  3934. break;
  3935. case 'ydaochang':
  3936. $sub_state = 2;
  3937. $visit_state = 0;
  3938. break;
  3939. default:
  3940. $continue = true;
  3941. break;
  3942. }
  3943. if ($continue) continue;
  3944. // “确认” 不受预约的限制
  3945. if (in_array($k_s, ['yliangfang', 'ydaodian', 'ydaochang']) && in_array($param['state'], array_merge($lf_state, $dd_state, $dc_state))) {
  3946. continue;
  3947. }
  3948. if (in_array($param['state'], array_merge($lf_state, $dd_state, $dc_state))){
  3949. $errmsg = '该客户在保护期内,无法提交确认';
  3950. } elseif (in_array($param['state'], array_merge($yylf_state, $yydd_state, $yydc_state))){
  3951. $errmsg = '该客户在保护期内,无法预约';
  3952. }
  3953. // 查询保护时间段内添加的预约量房记录
  3954. unset($v_where);
  3955. $v_where[] = ['org_id', 'in', $org_ids];
  3956. $v_where[] = ['addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$v_s['day'])];
  3957. $v_where[] = ['employee_id', '<>', $empid];
  3958. $v_where[] = ['type', '=', $sub_state];
  3959. $v_where[] = ['state', '=', $visit_state];
  3960. $sub_list = CustomersSubscribe::where($v_where)->select()->toArray();
  3961. if (!empty($sub_list)){
  3962. $sub_list_ids = array_column($sub_list,'customer_id');
  3963. $sub_employee_ids = array_column($sub_list, 'employee_id');
  3964. $sub_customers = Customer::where([['id', 'in', $sub_list_ids], ['employee_id', 'in', $sub_employee_ids]])->select()->toArray();
  3965. foreach ($sub_customers as $v){
  3966. if (in_array($had->phone, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3967. return json(['code' => 1, 'msg' => $errmsg]);
  3968. }
  3969. if (!empty($had->phone1) && in_array($had->phone1, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3970. return json(['code' => 1, 'msg' => $errmsg]);
  3971. }
  3972. if (!empty($had->phone2) && in_array($had->phone2, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3973. return json(['code' => 1, 'msg' => $errmsg]);
  3974. }
  3975. }
  3976. }
  3977. if ($check_log) {
  3978. $log_list = CustomerVisitLog::where($check_where)->select()->toArray();
  3979. $log_list_ids = array_column($log_list,'customer_id');
  3980. $log_employee_ids = array_column($log_list, 'employee_id');
  3981. $log_customers = Customer::where([['id', 'in', $log_list_ids], ['employee_id', 'in', $log_employee_ids]])->select()->toArray();
  3982. foreach ($log_customers as $v){
  3983. if (in_array($had->phone, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3984. return json(['code' => 1, 'msg' => $errmsg]);
  3985. }
  3986. if (!empty($had->phone1) && in_array($had->phone1, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3987. return json(['code' => 1, 'msg' => $errmsg]);
  3988. }
  3989. if (!empty($had->phone2) && in_array($had->phone2, [$v['phone'], $v['phone1'], $v['phone2']]) && $v['id'] != $had['id']){
  3990. return json(['code' => 1, 'msg' => $errmsg]);
  3991. }
  3992. }
  3993. }
  3994. }
  3995. }
  3996. }
  3997. }
  3998. // 更改客户信息
  3999. $state = Customer::changeState($param['state']);
  4000. $orders = false;
  4001. //签单之后不能签单交定,可以跟进
  4002. if ($state == '已签单') {
  4003. $is = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')], ['customer_id', '=', $had->id]])->count();
  4004. if ($is) {
  4005. return $this->updateMoney($param);
  4006. // Db::rollback();
  4007. // return json(['code' => 1, 'msg' => '该客户' . $state]);
  4008. }
  4009. $orders = true;
  4010. } elseif ($state == '已交定') {
  4011. $is = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')], ['customer_id', '=', $had->id]])->count();
  4012. if ($is) {
  4013. Db::rollback();
  4014. return json(['code' => 1, 'msg' => '该客户已签单']);
  4015. }
  4016. $orders = true;
  4017. }
  4018. Db::startTrans();
  4019. //处理房屋状态
  4020. if(!empty($param['house_status'])){
  4021. $had->house_status = $param['house_status'];
  4022. }
  4023. //如果是分派的客户第一次跟进直接修改分派信息为空
  4024. if(!empty($had->transfer_info)){
  4025. $had->transfer_info = NULL;
  4026. }
  4027. //如果是第一次有效修改有效时间
  4028. if($state == '未到访' && $had->state == '待确认'){
  4029. $had->valid_time = !empty($param['confirm_date']) ? $param['confirm_date'] : null;
  4030. }
  4031. if (!empty($state)) {
  4032. //if(!in_array($had->state,Customer::changeState('待确认','chaos'),true)){
  4033. $had->state = $state;
  4034. //}
  4035. }
  4036. //客户名称
  4037. if (!empty($param['name'])) {
  4038. $had->name = $param['name'];
  4039. }
  4040. //是否设置客户转介绍新客户
  4041. // if($param['introduce']){
  4042. // $had->introduce = 1;
  4043. // }
  4044. //设计师
  4045. if(!empty($param['designer_id']) && empty($had->designer_id)){
  4046. $limitNum = Setting::where(['root_id' => $root_id, 'name' => 'designerNum'])->value('content');
  4047. if ($limitNum != 0) {
  4048. //获取当月时间跨度
  4049. $start_time = date('Y-m').'-01 00:00:00';
  4050. $end_time = date('Y-m-d',strtotime("$start_time +1 month -1 day")).' 23:59:59';
  4051. $whered[] = ['addtime', 'between', [strtotime($start_time),strtotime($end_time)]];
  4052. $whered[] = ['employee_id', '=', $param['designer_id']];
  4053. $hads = CustomerSharing::field('employee_id,count(customer_id) as num')->group('employee_id')->where($whered)->having("num >= $limitNum")->select();
  4054. if (!$hads->isEmpty()){
  4055. Db::rollback();
  4056. return json(['code' => 1, 'msg' => '指派的设计师已无指派名额,请刷新后再试']);
  4057. }
  4058. }
  4059. $had->designer_id = $param['designer_id'];
  4060. }
  4061. $had->revisit_time = !empty($param['next_contact_date']) ? $param['next_contact_date'] . ' 00:00:00' : date('Y-m-d').' 00:00:00';
  4062. $had->last_contact_date = date('Y-m-d', time());
  4063. $had->updatetime = date('Y-m-d H:i:s', time());
  4064. if ($param['aid'] && $param['state'] == '预约活动') $had->aid = $param['aid'];
  4065. $had->fresh = 0;
  4066. // 交定产品
  4067. $dingMsg = '';
  4068. if ($had->state == '已交定') {
  4069. empty($param['money']) ?: $had->deposit_money = $param['money'];
  4070. if (!empty($param['package'])) {
  4071. $package = CustomerPackage::where([['root_id', '=', $root_id], ['id', 'in', $param['package']]])->column('name', 'id');
  4072. if (!$package) return json(['code' => 1, 'msg' => '客户产品不存在']);
  4073. $had->package_id = implode(',', array_keys($package));
  4074. $dingMsg = '交定金额:' . $param['money'] . '元,选择产品:' . implode(',', $package);
  4075. }
  4076. }
  4077. if ($had->state == '已签单' && !empty($param['money'])) $had->signed_money = $param['money'];
  4078. $had->save();
  4079. // 更新客户保护期
  4080. if ($param['state'] !== '无效' && !empty($state)) {
  4081. $log_state = CustomerVisitLog::changeState($state, 'chaos');
  4082. $v_where[] = ['employee_id', '=', $empid];
  4083. $v_where[] = ['state', 'in', $log_state];
  4084. $v_where[] = ['customer_id', '=', $param['customer_id']];
  4085. if (!empty($had['employee_time'])) {
  4086. $v_where[] = ['addtime', '>', $had['employee_time']];
  4087. }
  4088. $v_count = CustomerVisitLog::where($v_where)->count();
  4089. //查看此状态的跟踪记录,如果有数据,说明此客户在此员工这里已经经历过此状态,不再更新保护期
  4090. if (!$v_count) {
  4091. Customer::changeProtectedTo($had->id, $root_id);
  4092. }
  4093. }
  4094. // 添加确定消息内容
  4095. $confirmMsg = '';
  4096. if (!empty($param['confirm_date'])) {
  4097. $confirmMsg = ', 时间:' . $param['confirm_date'];
  4098. }
  4099. // 备注
  4100. $employeeName = Employee::where(['id' => $empid])->value('name');
  4101. $remark = $param['remark'];
  4102. if (empty($remark)) {
  4103. if (empty($state))
  4104. $remark = $employeeTypeName . $employeeName . '对客户进行了回访';
  4105. else
  4106. $remark = $employeeTypeName . $employeeName . '更新客户状态为' . $state . $confirmMsg . ',' . $dingMsg;
  4107. }
  4108. $valid_status = NULL;
  4109. //2022-10-04 逻辑修改,无效时增加无效原因
  4110. if ($param['state'] == '无效' && !empty($param['remark'])) {
  4111. // $remark = $employeeTypeName . $employeeName . '更新客户状态为' . $state . $confirmMsg . ',原因是:' . $param['remark'] . $dingMsg;
  4112. $valid_status = !empty($had->valid_time) ? 2 : 1;
  4113. }
  4114. //如果置为无效时,查询客户的有效状态
  4115. // 添加追踪记录
  4116. $visitLog = [
  4117. 'customer_id' => $had->id,
  4118. 'type' => $param['type'],
  4119. 'next_contact_date' => !empty($param['next_contact_date']) ? $param['next_contact_date'] : null,
  4120. 'employee_id' => $empid,
  4121. 'user_id' => $this->request->empcrm['uid'],
  4122. 'remark' => $remark,
  4123. 'state' => $param['state'],
  4124. 'weixin_media' => $param['weixin_media'],
  4125. 'media_id' => $param['media_id'],
  4126. 'starts' => $param['starts'],
  4127. 'money' => $param['money'],
  4128. 'confirm_date' => $param['confirm_date'],
  4129. 'org_id' => $this->request->empcrm['org_id'],
  4130. 'aid' => $param['aid'] ?: $had->aid,
  4131. 'weixin_media1' => $param['weixin_media1'],
  4132. 'media_id1' => $param['media_id1'],
  4133. 'customer_employee_id' => $had->employee_id,
  4134. 'customer_org_id' => Employee::where('id', $had->employee_id)->value('org_id'),
  4135. 'img' => $param['img'],
  4136. 'img1' => $param['img1'],
  4137. 'number_of_visitors' => $param['number_of_visitors'],
  4138. 'measure_room_img_type' => $param['measure_room_img_type'],
  4139. 'deposit_mode' => $param['deposit_mode'],
  4140. 'document_field' => $param['document_field'],
  4141. 'document_name' => $param['document_name']
  4142. //'other_money' => $param['other_money'],
  4143. //'valid_status' => $valid_status
  4144. ];
  4145. $returnvisit = ['customer_org_id'=>$visitLog['customer_org_id']];
  4146. //2022-10-28 增加交定和签单凭证 凭证为图片
  4147. $deliverySignVoucher = request()->only(['delivery_media_id'=>'','delivery_weixin_media'=>'','sign_media_id'=>'','sign_weixin_media'=>'','delivery_img'=>'','sign_img'=>'']);
  4148. $visitLog = $visitLog + $deliverySignVoucher;
  4149. empty($param['img']) ?: $visitLog['img'] = $param['img'];
  4150. if (!empty($param['aid'])) {
  4151. // 检测活动是否存在
  4152. $existActivity = Activity::where([['id', '=', $param['aid']], ['root_id', '=', $root_id]])->count();
  4153. if ($existActivity == 0) {
  4154. Db::rollback();
  4155. return json(['code' => 1, 'msg' => '活动不存在']);
  4156. }
  4157. $visitLog['aid'] = $param['aid'];
  4158. }
  4159. $visitLog = CustomerVisitLog::create($visitLog);
  4160. if ($orders) $this->preformance_tasks($state, $param['customer_id'], $param['money'], $visitLog->id); //计算业绩
  4161. if (strpos($visitLog->state, '预约') !== false) {
  4162. $state = str_replace('预约', '', $visitLog->state);
  4163. // 查找是否已经预约
  4164. if($is_manager ==1){
  4165. $hadSubscribe = CustomersSubscribe::where([
  4166. ['customer_id', '=', $had['id']],
  4167. //['employee_id|designer_id', '=', $empid],
  4168. ['subscribe_date', '=', date('Y-m-d', strtotime($param['confirm_date']))],
  4169. ['state', '=', 0]
  4170. ])->count();
  4171. $typeSubscribe = CustomersSubscribe::where([
  4172. ['customer_id', '=', $had['id']],
  4173. //['employee_id|designer_id', '=', $empid],
  4174. ['type', '=', array_search($state, $stateType)],
  4175. ['state', '=', 0]
  4176. ])->find();
  4177. }else{
  4178. $hadSubscribe = CustomersSubscribe::where([
  4179. ['customer_id', '=', $had['id']],
  4180. ['employee_id|designer_id', '=', $empid],
  4181. ['subscribe_date', '=', date('Y-m-d', strtotime($param['confirm_date']))],
  4182. ['state', '=', 0]
  4183. ])->count();
  4184. $typeSubscribe = CustomersSubscribe::where([
  4185. ['customer_id', '=', $had['id']],
  4186. ['employee_id|designer_id', '=', $empid],
  4187. ['type', '=', array_search($state, $stateType)],
  4188. ['state', '=', 0]
  4189. ])->find();
  4190. }
  4191. $typeSubscribe = false; // 不是同一天的预约,同类型还可以预约
  4192. if ($hadSubscribe) {
  4193. Db::rollback();
  4194. return json(['code' => 1, 'msg' => '该客户在当前日期已有预约']);
  4195. } elseif ($typeSubscribe) {
  4196. Db::rollback();
  4197. return json(['code' => 1, 'msg' => '该客户已有' . $state . '预约, 预约日期' . $typeSubscribe->subscribe_date]);
  4198. } else {
  4199. $subscribe = [
  4200. 'customer_id' => $had['id'],
  4201. 'subscribe_date' => $param['confirm_date'],
  4202. 'employee_id' => $had->employee_id,
  4203. 'designer_id' => $had->designer_id,
  4204. 'type' => $state,
  4205. 'aid' => $param['aid'] ?: $had->aid,
  4206. 'org_id' => $had->org_id
  4207. ];
  4208. CustomersSubscribe::create($subscribe);
  4209. }
  4210. }
  4211. //当设为无效时,记录当前操作人跟进的最后一次状态,此处在公海列表处展示
  4212. if ($param['state'] == '无效') {
  4213. $last_cvl = CustomerVisitLog::where('customer_id', $param['customer_id'])->with('employee')->order('addtime desc')->find();
  4214. //获取"无效"并进入公海之前的那次跟进记录的信息
  4215. if ($last_cvl) {
  4216. $before_pool = [
  4217. 'name' => $last_cvl->employee->name,
  4218. 'state' => $last_cvl->state,
  4219. 'addtime' => $last_cvl->addtime
  4220. ];
  4221. } else {
  4222. $before_pool = [
  4223. 'name' => Employee::find($had['employee_id'])->value('name'),
  4224. 'state' => '待确认',
  4225. 'addtime' => $had->addtime
  4226. ];
  4227. }
  4228. // 该客户预约中的状态置为无效
  4229. CustomersSubscribe::where([['customer_id', '=', $param['customer_id']], ['state', '=', 0]])->save(['state'=> -1]);
  4230. //公海内是否存在该客户信息,存在则合并客户信息(phone、phone1、phone2)
  4231. $orgids = orgSubIds($root_id);
  4232. $phone_arr = [];
  4233. !empty(trim($had['phone'])) ? $phone_arr[] = cypherphone(trim($had['phone'])) : '' ;
  4234. !empty(trim($had['phone1'])) ? $phone_arr[] = cypherphone(trim($had['phone1'])) : '' ;
  4235. !empty(trim($had['phone2'])) ? $phone_arr[] = cypherphone(trim($had['phone2'])) : '' ;
  4236. $phone_arr = array_filter($phone_arr);
  4237. $pool_condition = [
  4238. ['employee_id', '=', NULL],
  4239. ['is_resource', '=', 0],
  4240. ['org_id', 'in', $orgids],
  4241. ['phone|phone1|phone2','in',$phone_arr]
  4242. ];
  4243. $pool_crm = Customer::where($pool_condition)->column('id');
  4244. if(!empty($pool_crm)){
  4245. //公海存在则删除
  4246. Customer::where([['id', 'in', $pool_crm]])->update(['delete_time'=>time()]);
  4247. //关联回访记录修改
  4248. CustomerVisitLog::where([['customer_id', 'in', $pool_crm]])->update(['is_merge'=>1, 'customer_id'=>$had['id']]);
  4249. CustomersSubscribe::where([['customer_id', 'in', $pool_crm]])->update(['is_merge'=>1, 'customer_id'=>$had['id']]);
  4250. }
  4251. //增加无效记录
  4252. $vlglist = CustomerVisitLog::where([['customer_id','=',$param['customer_id']],['customer_employee_id','=',$empid],['state','not in',array_merge(CustomerVisitLog::changeState('待确认','chaos'),CustomerVisitLog::changeState('无效','chaos'))],['save_portrait_field','NULL',null]])->count();
  4253. $invalidlog = [
  4254. 'customer_id'=>$param['customer_id'],
  4255. 'employee_id'=>$had->employee_id,
  4256. 'designer_id'=>$had->designer_id ? $had->designer_id : 0,
  4257. 'org_id' => $had->org_id,
  4258. 'root_id' => $request->empcrm->root_id,
  4259. 'cus_addtime' =>$had->addtime,
  4260. 'visitlog_id' =>$visitLog->id,
  4261. 'assigned_personnel' => $had->assigned_personnel ? $had->assigned_personnel : '',
  4262. 'source_id' => $had->source_id ? $had->source_id : 0,
  4263. 'status' => !empty($vlglist) ? 1 : 2,
  4264. 'cus_employee_time'=> $had->employee_time,
  4265. 'is_resource'=> $had->is_resource
  4266. ];
  4267. CustomerInvalidLog::create($invalidlog);
  4268. Customer::where('id', $param['customer_id'])->update(['state' => 7, 'employee_id' => NULL, 'org_id' => $request->empcrm->org_id, 'is_resource' => 0, 'before_pool' => json_encode($before_pool), 'designer_id' => NULL, 'employee_time' => NULL]);
  4269. // -------------------- 企业微信逻辑相关 start -----------------
  4270. // 判断是否绑定有企业微信外部联系人关系,并做解绑操作
  4271. $company_id = Company::where('root_id', '=', $root_id)->value('id');
  4272. $company_setting = WeworksingleCompanySetting::where('company_id', '=', $company_id)->find();
  4273. if (!empty($company_setting)) {
  4274. $w_where['company_id'] = $company_id;
  4275. $w_where['employee_id'] = $empid;
  4276. $w_where['customer_id'] = $param['customer_id'];
  4277. WeworksingleCustomer::where($w_where)->save(['customer_id' => 0]);
  4278. }
  4279. // -------------------- 企业微信逻辑相关 end -----------------
  4280. }
  4281. // //如果签单,默认交定
  4282. if (strpos($param['state'], "签单") !== false) {
  4283. trace(strpos($param['state'], "签单"));
  4284. $lw[] = CustomerVisitLog::changeState(['state', '=', '交定']);
  4285. $lw[] = ['customer_id', '=', $param['customer_id']];
  4286. $check = CustomerVisitLog::where($lw)->find();
  4287. if (!$check) {
  4288. $l_visitlog = $visitLog->toArray();
  4289. unset($l_visitlog['id']);
  4290. $l_visitlog['state'] = '交定';
  4291. $l_visitlog['remark'] = !empty($param['remark']) ? $param['remark'] : $employeeTypeName . $employeeName . '变更客户状态为交定';
  4292. $new_visitlog = array_merge($param, $l_visitlog);
  4293. $new_visitlog['money'] = 0; //直接签单默认交定金额为0
  4294. $mr = CustomerVisitLog::create($new_visitlog);
  4295. $this->preformance_tasks('已交定', $param['customer_id'], $param['money'], $mr->id); //计算业绩
  4296. }
  4297. }
  4298. if (in_array($param['state'], ['已到店', '已量房', '已到场'])) {
  4299. $state = str_replace('已', '', $param['state']);
  4300. $subscribe = CustomersSubscribe::where([['customer_id', '=', $had['id']], ['type', '=', array_search($state, $stateType)], ['state', '=', 0]])->find();
  4301. if (!empty($subscribe)) {
  4302. $subscribe->state = 1;
  4303. $subscribe->save();
  4304. } elseif ($param['aid'] && in_array($param['state'], ['已到场'])) { //没有预约可以直接确认到场
  4305. $this->activityState($param, $had);
  4306. }
  4307. }
  4308. if (in_array($param['state'], ['未到店', '未量房', '未到场'])) {
  4309. $state = str_replace('未', '', $param['state']);
  4310. $subscribe = CustomersSubscribe::where([['customer_id', '=', $had['id']], ['type', '=', array_search($state, $stateType)], ['state', '=', 0]])->find();
  4311. if (!empty($subscribe)) {
  4312. $subscribe->state = -1;
  4313. $subscribe->save();
  4314. }
  4315. $data = [
  4316. 'eid' => $had->employee_id,
  4317. 'org_id' => $returnvisit['customer_org_id'],
  4318. 'designer_id' => $had->designer_id,
  4319. 'confirm_date' => $param['confirm_date'],
  4320. 'customer_id' => $had->id,
  4321. 'return_visit' => $had->return_visit,
  4322. 'name' => $had->name,
  4323. 'state' => $param['state']
  4324. ];
  4325. $this->cancelReservation($data);
  4326. //取消预约后,待回访状态也要取消
  4327. $had->return_visit = 0;
  4328. $had->save();
  4329. }
  4330. //增加经纪人送积分功能
  4331. if ($had->agents_id && in_array($param['state'], ['已到店', '已交定', '已签单'])) {
  4332. $this->agents_integral($had->agents_id, $param['state'], $had->id);
  4333. }
  4334. // 微爆活动
  4335. if (in_array($param['state'], ['已到店', '已量房', '已到场', '已交定', '已签单'])) {
  4336. $activity_data['customer_id'] = $param['customer_id'];
  4337. $activity_data['employee_id'] = $had->employee_id;
  4338. $activity_data['org_id'] = $had->org_id;
  4339. switch ($param['state']) {
  4340. case '已到店':
  4341. $activity_data['type'] = 2;
  4342. break;
  4343. case '已量房':
  4344. $activity_data['type'] = 3;
  4345. break;
  4346. case '已交定':
  4347. $activity_data['type'] = 4;
  4348. break;
  4349. case '已签单':
  4350. $activity_data['type'] = 5;
  4351. break;
  4352. case '已到场':
  4353. $activity_data['type'] = 7;
  4354. break;
  4355. default:
  4356. break;
  4357. }
  4358. WechatActivityIntegral::addIntegral($activity_data, $request->empcrm->root_id);
  4359. }
  4360. Db::commit();
  4361. $from_wework = input('from_wework', '', 'trim');
  4362. if ($from_wework) {
  4363. Console::call('download', ['customer', 'wework', (string)$root_id]);
  4364. Console::call('download', ['customer1', 'wework', (string)$root_id]);
  4365. } else {
  4366. Console::call('download', ['customer']);
  4367. Console::call('download', ['customer1']);
  4368. }
  4369. //2022-10-28 更新交定/签单凭证
  4370. if(in_array($param['state'],['已交定','已签单'])){
  4371. $deliveryType = $param['state']=='已交定' ? 'delivery' : 'sign';
  4372. Console::call('download', [$deliveryType]);
  4373. }
  4374. Console::call('medal', ['visit_log', (string)$empid, (string)$root_id]); //勋章
  4375. if($is_manager == 1){
  4376. //经理回访后修改客户的待回访的状态
  4377. Customer::where('id', $had->id)->update(['return_visit' => 0]);
  4378. }else{
  4379. //给业务经理和设计是发送提醒消息回访
  4380. $data = ['phone' => $had->phone, 'org_id' => $returnvisit['customer_org_id'], 'state' => $param['state'], 'confirm_date' => $param['confirm_date'], 'name' => $had->name, 'designer_id' => $had->designer_id, 'eid' => $had->employee_id, 'customer_id' => $had->id];
  4381. }
  4382. //$this->returnVisit($data);
  4383. $data['name'] = !empty($data['name']) ? $data['name'] : '';
  4384. if (in_array($param['state'], $dd_state)) {
  4385. // 发送管理层模板消息
  4386. $msg = ['first'=>'行为通知', 'keyword1'=>'客户确认到店', 'keyword2'=>"客户".$data['name']."(".$had['phone'].")确认到店", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  4387. //TmpMsg::sendMsgToLeader($msg, $token['org_id']);
  4388. }
  4389. if ($state == '已签单') {
  4390. // 发送管理层模板消息
  4391. $msg = ['first'=>'行为通知', 'keyword1'=>'客户签单', 'keyword2'=>"客户".$data['name']."(".$had['phone'].")签单", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  4392. //TmpMsg::sendMsgToLeader($msg, $token['org_id']);
  4393. }
  4394. return json(['code' => 0, 'msg' => '跟进成功']);
  4395. }
  4396. /**
  4397. * 2022-10-27 逻辑修改,跟进保护优化 如果后台设置了重复客户跟进保护规则 跟进到保护状态后其他客户的此重复客户就不能在跟进了,但是可以置为无效
  4398. */
  4399. private function forbiddenState($id,$status){
  4400. if($status == '无效') return false;
  4401. //$token = $this->request->token;
  4402. $root_id = $this->request->empcrm->root_id;
  4403. //保护规则
  4404. $provite = Setting::where([['name','=','forbiddenState'],['root_id','=',$root_id]])->value('content');
  4405. if(!$provite) return false;
  4406. $info = Customer::where('id',$id)->column('phone,phone1,phone2');
  4407. //查询是否是重复客户
  4408. $orgs = Org::where([['path','like',$root_id.'-%']])->column('id');
  4409. $query[] = ['employee_id','>',0];
  4410. $query[] = ['org_id','in',$orgs];
  4411. $query[] = ['phone|phone1|phone2','in',array_filter($info[0])];
  4412. // $query[] = ['employee_id','<>',$token['employee_id']];
  4413. $check = Customer::where($query)->column('id,employee_id');
  4414. if(count($check) <= 1) return false;
  4415. $provite = explode(',',$provite);
  4416. $state = [];
  4417. foreach ($provite as $v) {
  4418. $state = array_merge($state,CustomerVisitLog::changeState($v, 'chaos'));
  4419. }
  4420. //查询该客户是否存在受保护的状态 只有第一个跟进的业务员可以继续跟进
  4421. $where[] = ['state','in',$state];
  4422. $where[] = ['customer_id','in',array_column($check,'id')];
  4423. $where[] = ['employee_id|customer_employee_id','in',array_column($check,'employee_id')];
  4424. $repeat = CustomerVisitLog::where($where)->order('id asc')->field('customer_id,state')->findOrEmpty();
  4425. if($repeat->isEmpty() || (int)$repeat->customer_id==(int)$id) return false;
  4426. //该客户已被其他员工 确认到店/确认量房/确认到场/交定/签单 无法更近
  4427. $state = str_replace('已','',$repeat->state);
  4428. $state = in_array(trim($state),['交定','签单']) ? trim($state) : '确认'.trim($state);
  4429. return '该客户已被其他员工“'.$state.'”无法跟进';
  4430. }
  4431. /**
  4432. * 经纪人送积分功能
  4433. */
  4434. public function agents_integral($agentid, $state, $customer_id)
  4435. {
  4436. //$token = $this->request->token;
  4437. $root_id = $this->request->empcrm->root_id;
  4438. $agent_data = AgentUser::where('id', $agentid)->field('agent_name,type')->find();
  4439. if ($state == '已到店') {
  4440. $code = 'daodian_integral';
  4441. $sta_type = 1;
  4442. }
  4443. if ($state == '已交定') {
  4444. $code = 'jiaoding_integral';
  4445. $sta_type = 2;
  4446. }
  4447. if ($state == '已签单') {
  4448. $code = 'qiandan_integral';
  4449. $sta_type = 3;
  4450. }
  4451. //添加与经纪人相关记录
  4452. $you = AgentCustomerLog::where([['agent_id', '=', $agentid], ['type', '=', $sta_type], ['customer_id', '=', $customer_id]])->count();
  4453. if (empty($you)) {
  4454. $add = array(
  4455. 'agent_id' => $agentid,
  4456. 'type' => $sta_type,
  4457. 'typename' => $state,
  4458. 'addtime' => time(),
  4459. 'customer_id' => $customer_id,
  4460. 'agent_type' => $agent_data['type'],
  4461. 'status' => 1
  4462. );
  4463. AgentCustomerLog::insert($add);
  4464. }
  4465. if ($agent_data['type'] == 2) return; //如果是网红经纪人直接返回
  4466. $jifen = CreditsSetting::where(['code' => $code, 'root_id' => $root_id])->value('value');
  4467. $ye = AgentIntegral::where(['customer_id' => $customer_id, 'agent_id' => $agentid])->column('state');
  4468. if (!in_array($state, $ye) && $agent_data['type'] == 1) {
  4469. $add = array(
  4470. 'agent_id' => $agentid,
  4471. 'type' => 1,
  4472. 'integral' => $jifen ? $jifen : 1,
  4473. 'addtime' => time(),
  4474. 'state' => $state,
  4475. 'customer_id' => $customer_id
  4476. );
  4477. AgentIntegral::insert($add);
  4478. }
  4479. if ($state == '已交定' && !in_array('已到店', $ye)) {
  4480. $jifen = CreditsSetting::where(['code' => 'daodian_integral', 'root_id' => $root_id])->value('value');
  4481. $add = array(
  4482. 'agent_id' => $agentid,
  4483. 'type' => 1,
  4484. 'integral' => $jifen ? $jifen : 1,
  4485. 'addtime' => time(),
  4486. 'state' => '已到店',
  4487. 'customer_id' => $customer_id
  4488. );
  4489. AgentIntegral::insert($add);
  4490. }
  4491. if ($state == '已签单' && !in_array('已到店', $ye)) {
  4492. $jifen = CreditsSetting::where(['code' => 'daodian_integral', 'root_id' => $root_id])->value('value');
  4493. $add = array(
  4494. 'agent_id' => $agentid,
  4495. 'type' => 1,
  4496. 'integral' => $jifen ? $jifen : 1,
  4497. 'addtime' => time(),
  4498. 'state' => '已到店',
  4499. 'customer_id' => $customer_id
  4500. );
  4501. AgentIntegral::insert($add);
  4502. }
  4503. if ($state == '已签单' && !in_array('已交定', $ye)) {
  4504. $jifen = CreditsSetting::where(['code' => 'jiaoding_integral', 'root_id' => $root_id])->value('value');
  4505. $add = array(
  4506. 'agent_id' => $agentid,
  4507. 'type' => 1,
  4508. 'integral' => $jifen ? $jifen : 1,
  4509. 'addtime' => time(),
  4510. 'state' => '已交定',
  4511. 'customer_id' => $customer_id
  4512. );
  4513. AgentIntegral::insert($add);
  4514. }
  4515. }
  4516. /**
  4517. * 取消预约 给部门管理员和设计师发送消息提醒
  4518. * 张三取消了客户李四2020年8月1日的量房/到店/到场预约
  4519. */
  4520. public function cancelReservation($data)
  4521. {
  4522. $token = $this->get_token();
  4523. if ($data['return_visit'] == 1) {
  4524. $token['name'] = Employee::where([['root_id', '=', $token['root_org']],['id', '=', $data['eid']]])->value('name');
  4525. $eids = Employee::where([['root_id', '=', $token['root_org']], ['org_id', '=', $data['org_id']], ['state', '=', '在职'], ['is_manager', '=', 1], ['uid', '>', 0]])->column('id');
  4526. if ($data['designer_id']) array_push($eids, $data['designer_id']);
  4527. $date = date('Y-m-d', strtotime($data['confirm_date']));
  4528. $date = explode('-', $date);
  4529. $state = str_replace('未', '', $data['state']);
  4530. $msg = $token['name'] . '取消了客户' . $data['name'] . $date[0] . '年' . $date[1] . '月' . $date[2] . '日的' . $state;
  4531. $eids = array_unique($eids);
  4532. foreach ($eids as $key => $val) {
  4533. event(new Msg($val, $msg, 'returnVisit', $data['customer_id']));
  4534. }
  4535. return true;
  4536. }
  4537. return false;
  4538. }
  4539. /**
  4540. * 没有预约活动,跟进时传了aid和state='预约活动'
  4541. * 没有预约可以直接确认到场
  4542. * 补全数据添加预约和的追踪记录
  4543. */
  4544. public function activityState($param, $had)
  4545. {
  4546. $token = $this->get_token();
  4547. $employeeTypeName = $token['org_type'] == 2 ? '设计师' : '销售';
  4548. // 备注
  4549. $employeeName = Employee::where(['id' => $token['employee_id']])->value('name');
  4550. $remark = $param['remark'];
  4551. if (empty($remark)) {
  4552. $remark = $employeeTypeName . $employeeName . '对客户进行了回访';
  4553. }
  4554. //预约记录
  4555. $visitLog = [
  4556. 'customer_id' => $had->id,
  4557. 'type' => $param['type'],
  4558. 'next_contact_date' => !empty($param['next_contact_date']) ? $param['next_contact_date'] : date('Y-m-d'),
  4559. 'employee_id' => $token['employee_id'],
  4560. 'user_id' => $token['uid'],
  4561. 'remark' => $remark,
  4562. 'state' => 6,
  4563. 'weixin_media' => '',
  4564. 'media_id' => '',
  4565. 'starts' => $param['starts'],
  4566. 'money' => $param['money'],
  4567. 'confirm_date' => $param['confirm_date'],
  4568. 'org_id' => $token['org_id'],
  4569. 'aid' => $param['aid'],
  4570. 'weixin_media1' => '',
  4571. 'media_id1' => '',
  4572. 'customer_employee_id' => $had->employee_id,
  4573. 'customer_org_id' => Employee::where('id', $had->employee_id)->value('org_id')
  4574. ];
  4575. CustomerVisitLog::create($visitLog);
  4576. //
  4577. $subscribe = [
  4578. 'customer_id' => $had['id'],
  4579. 'subscribe_date' => $param['confirm_date'],
  4580. 'employee_id' => $had->employee_id,
  4581. 'designer_id' => $had->designer_id,
  4582. 'type' => 2,
  4583. 'aid' => $param['aid'],
  4584. 'org_id' => $visitLog['customer_org_id'],
  4585. 'state' => 1
  4586. ];
  4587. CustomersSubscribe::create($subscribe);
  4588. return 1;
  4589. }
  4590. //转换token
  4591. public function get_token()
  4592. {
  4593. $token = [
  4594. 'uid'=>$this->request->empcrm->uid,
  4595. 'employee_id'=>$this->request->empcrm->id,
  4596. 'org_id'=>$this->request->empcrm->org_id,
  4597. 'root_org'=>$this->request->empcrm->root_id,
  4598. 'name'=>$this->request->empcrm->name,
  4599. ];
  4600. return $token;
  4601. }
  4602. /**
  4603. * 计算业绩任务
  4604. */
  4605. public function preformance_tasks($state, $customer_id, $money = 0, $vislog_id)
  4606. {
  4607. $token = $this->get_token();
  4608. //防止后台切换部门
  4609. $token['org_id'] = Employee::where('id', $token['employee_id'])->value('org_id');
  4610. if ($state == '已交定') {
  4611. $w2[] = ['customer_id', '=', $customer_id];
  4612. $w2[] = ['state', 'in', CustomerVisitLog::changeState('已交定', 'chaos')];
  4613. $w2[] = ['customer_employee_id', '=', $token['employee_id']];
  4614. $w2[] = ['customer_org_id', '=', $token['org_id']];
  4615. //切换部门重复交定仍然算业绩
  4616. $check = CustomerVisitLog::where($w2)->count(); //没有交定过计算业绩
  4617. if ($check == 1) {
  4618. $time = date('Y-m-d H:i:s');
  4619. //查询进行中的指派到所属部门的所有进度
  4620. // $w[] = ['org_id','=',$token['org_id']];
  4621. $w[] = ['root_id', '=', $token['root_org']];
  4622. $w[] = ['start_date', '<=', $time];
  4623. $w[] = ['end_date', '>=', $time];
  4624. $w[] = ['is_deposit', '=', 1];
  4625. $preformance_tasks = PreformanceTasksModel::where($w)->column('id');
  4626. $w1[] = ['root_id', '=', $token['root_org']];
  4627. $w1[] = ['org_id', '=', $token['org_id']];
  4628. $w1[] = ['performance_tasks_id', 'in', $preformance_tasks];
  4629. $w1[] = ['is_deposit', '=', 1];
  4630. //指派到自己部门
  4631. $pid = PreformanceTasksOrg::where($w1)->group('performance_tasks_id')->column('*');
  4632. $w4[] = ['id', 'in', array_column($pid, 'performance_tasks_id')];
  4633. $model = PreformanceTasksModel::where($w4)->column('*');
  4634. foreach ($model as $k => $v) {
  4635. $u = [];
  4636. $u['ok_deposit'] = $v['ok_deposit'] + 1;
  4637. $u['customer_visit_log_id'] = $v['customer_visit_log_id'] ? $v['customer_visit_log_id'] . ',' . $vislog_id : $vislog_id;
  4638. PreformanceTasksModel::where('id', $v['id'])->update($u);
  4639. unset($u);
  4640. }
  4641. PreformanceTasksOrg::where($w1)->inc('ok_deposit')->update();
  4642. }
  4643. } elseif ($state == '已签单') {
  4644. $w2[] = ['customer_id', '=', $customer_id];
  4645. $w2[] = ['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')];
  4646. $w2[] = ['customer_employee_id', '=', $token['employee_id']];
  4647. $check = CustomerVisitLog::where($w2)->count(); //没有交定过计算业绩
  4648. if ($check == 1) {
  4649. $time = date('Y-m-d H:i:s');
  4650. //查询进行中的指派到所属部门的所有进度
  4651. // $w[] = ['org_id','=',$token['org_id']];
  4652. $w[] = ['root_id', '=', $token['root_org']];
  4653. $w[] = ['start_date', '<=', $time];
  4654. $w[] = ['end_date', '>=', $time];
  4655. $w[] = ['is_money', '=', 1];
  4656. $preformance_tasks = PreformanceTasksModel::where($w)->column('id');
  4657. $w1[] = ['root_id', '=', $token['root_org']];
  4658. $w1[] = ['org_id', '=', $token['org_id']];
  4659. $w1[] = ['performance_tasks_id', 'in', $preformance_tasks];
  4660. $w1[] = ['is_money', '=', 1];
  4661. //指派到自己部门
  4662. $pid = PreformanceTasksOrg::where($w1)->group('performance_tasks_id')->column('*');
  4663. $w4[] = ['id', 'in', array_column($pid, 'performance_tasks_id')];
  4664. $model = PreformanceTasksModel::where($w4)->column('*');
  4665. foreach ($model as $k => $v) {
  4666. $u = [];
  4667. $u['ok_money'] = $v['ok_money'] + $money;
  4668. $u['customer_visit_log_id'] = $v['customer_visit_log_id'] ? $v['customer_visit_log_id'] . ',' . $vislog_id : $vislog_id;
  4669. PreformanceTasksModel::where('id', $v['id'])->update($u);
  4670. unset($u);
  4671. }
  4672. PreformanceTasksOrg::where($w1)->inc('ok_money', (int)$money)->update();
  4673. }
  4674. }
  4675. return 1;
  4676. }
  4677. /**
  4678. * 2022-11-11 业务修改 签单之后可以编辑签单金额,跟进记录增加 业务员修改签单金额为3000元
  4679. */
  4680. private function updateMoney($param)
  4681. {
  4682. $request = request();
  4683. $token = $this->get_token();
  4684. $money = $param['money'] ?: 0;
  4685. $orgids = orgSubIds($token['root_org']);
  4686. $where[] = ['id', '=', $param['customer_id']];
  4687. $where[] = ['org_id','in',$orgids];
  4688. $cusdata = Customer::where($where)->find();
  4689. $cusdata->signed_money = $money;
  4690. $cusdata->save();
  4691. //Customer::where($where)->update(['signed_money' => $money]);
  4692. if(isset($param['vlogid'])&&$param['vlogid'])CustomerVisitLog::where('id',$param['vlogid'])->update(['money'=>$money]);
  4693. $token['name'] = Employee::where([['id', '=', $token['employee_id']]])->value('name');
  4694. $time = date('Y-m-d H:i:s');
  4695. //增加跟进记录
  4696. $save = [
  4697. 'customer_id' => $param['customer_id'],
  4698. 'type' => '',
  4699. 'next_contact_date' => date('Y-m-d'),
  4700. 'remark' => '业务员' . $token['name'] . '修改已签单金额为' . $money . '元',
  4701. 'addtime' => $time,
  4702. 'employee_id' => $token['employee_id'],
  4703. 'user_id' => $token['uid'],
  4704. // 'state' => 3,
  4705. 'state' => 1,
  4706. 'org_id' => $token['org_id'],
  4707. 'customer_employee_id' => $cusdata['employee_id'],
  4708. 'customer_org_id' => $token['org_id'],
  4709. 'money' => $money
  4710. ];
  4711. //2022-10-28 增加交定和签单凭证 凭证为图片
  4712. //$deliverySignVoucher = request()->only(['sign_media_id' => '', 'sign_weixin_media' => '', 'sign_img' => '']);
  4713. //$save = $save + $deliverySignVoucher;
  4714. CustomerVisitLog::insertGetId($save);
  4715. //if ($deliverySignVoucher['sign_media_id']) Console::call('download', ['sign']);
  4716. $msg = '转单金额修改成功.';
  4717. if($request->empcrm['xinjushang'] == 1) $msg = '签单金额修改成功.';
  4718. return json(['code' => 0, 'msg' => $msg, 'data' => $msg]);
  4719. }
  4720. /**
  4721. * 快速状态跟进
  4722. */
  4723. public function kb(){
  4724. $request = request();
  4725. $empcrm = $request->empcrm;
  4726. $employeeTypeName = $empcrm->is_manager ==1 ? '部门领导' : ($empcrm->org_type == 2 ? '设计师' : '销售');
  4727. // 请求参数设置
  4728. $stateParam = [
  4729. 3 => ['money', 'confirm_date'],
  4730. 2 => ['money', 'confirm_date'],
  4731. 7 => ['confirm_date'],
  4732. 8 => ['confirm_date']
  4733. ];
  4734. $param = $request->only(['customer_id', 'state', 'money','add_wechat_time','vlogid']);
  4735. //2022-10-27 逻辑修改,跟进保护优化 如果后台设置了重复客户跟进保护规则 跟进到保护状态后其他业务员的此重复客户就不能在跟进了,但是可以置为无效
  4736. $forbiddenState = $this->forbiddenState($param['customer_id'],null);
  4737. if($forbiddenState != false) return json(['code' => 1, 'msg' =>$forbiddenState]);
  4738. // 数据查找
  4739. $where = [
  4740. ['id', '=', $param['customer_id']],
  4741. ['state', '<>', '无效']
  4742. ];
  4743. if($empcrm->is_manager ==1){
  4744. $team_orgs = orgSubIds($request->empcrm->org_id);
  4745. $where[] = ['org_id', 'in', $team_orgs];
  4746. }else{
  4747. $where[] = ['employee_id|designer_id|assigned_personnel', 'find in set', $empcrm->id];
  4748. }
  4749. $had = Customer::where($where)->find();
  4750. if ($had === null) return json(['code' => 1, 'msg' => '添加失败,数据不存在']);
  4751. if(!empty($param['add_wechat_time'])) {
  4752. $ext = $had->ext;
  4753. $ext = json_decode($ext,true);
  4754. $ei = false;
  4755. foreach($ext as &$e){
  4756. if($e['keyname'] == 'add_wechat_time') {
  4757. $e['value'] = date('Y-m-d', strtotime($param['add_wechat_time']));
  4758. $ei = true;
  4759. }
  4760. }
  4761. if ($ei === false) {
  4762. $fid = CustomerPortraitField::where(['root_id' => $empcrm->root_id, 'keyname' => 'add_wechat_time'])->value('id');
  4763. if($fid) $ext[] = ['id' => $fid, 'keyname' => 'add_wechat_time', 'value' => date('Y-m-d', strtotime($param['add_wechat_time']))];
  4764. }
  4765. $had->ext = json_encode($ext);
  4766. }
  4767. if(empty($param['state']) || !in_array($param['state'], [2,3,7,8])) {
  4768. $had->save();
  4769. return json(['code'=>0, 'msg'=>'保存成功']);
  4770. } else {
  4771. $customerVisitLogState = CustomerVisitLog::changeState($param['state'], 'n');
  4772. $stateStr = CustomerVisitLog::changeState($param['state']);
  4773. $customerState = Customer::changeState($stateStr, 'n');
  4774. $stateParamValue = $request->only($stateParam[$customerVisitLogState]);
  4775. }
  4776. // 量房到店保护机制
  4777. $protectedDay = 0;
  4778. if (7 == $customerVisitLogState || 8 == $customerVisitLogState) {
  4779. // 保护设置
  4780. $sub_setting = Setting::where([['root_id', '=', $empcrm->root_id], ['name', '=', 'subscribe_protected']])->findOrEmpty();
  4781. if (!$sub_setting->isEmpty()) { // 有设置
  4782. $setting_content = json_decode($sub_setting['content'], true);
  4783. // 判断保护是否开启
  4784. $bh = [];
  4785. foreach ($setting_content as $k_s => $v_s) {
  4786. if (!empty($v_s['state']) && !empty($v_s['day']) && $v_s['state'] == 1) {
  4787. $bh[$k_s] = $v_s['day'];
  4788. if (($k_s == 'ydaodian' && 7 == $customerVisitLogState) || ($k_s == 'yliangfang' && 8 == $customerVisitLogState)) $protectedDay = $v_s['day'];
  4789. }
  4790. }
  4791. $phones = [$had->phone, $had->phone1, $had->phone2];
  4792. $phones = array_filter($phones);
  4793. // 如果设置了保护
  4794. if (!empty($bh)) {
  4795. foreach($bh as $k=>$d){
  4796. $condition = $this->protectCondition($k, $d);
  4797. if(!empty($condition['log'])){
  4798. $e = CustomerVisitLog::withJoin('customer')->where([['Customer.id', '<>', $param['customer_id']]])->where($condition['log'])
  4799. ->where(function($query) use ($phones){
  4800. foreach($phones as $p){
  4801. $c = [
  4802. [['customer.phone', '=', $p]],
  4803. [['customer.phone1', '=', $p]],
  4804. [['customer.phone2', '=', $p]]
  4805. ];
  4806. $query->whereOr($c);
  4807. }
  4808. })->find();
  4809. if($e) return json(['code'=>1, 'msg'=>'该客户在保护期内,无法提交']);
  4810. }
  4811. if(!empty($condition['subscribe'])){
  4812. $e = CustomersSubscribe::withJoin('customer')->where([['Customer.id', '<>', $param['customer_id']]])->where($condition['subscribe'])
  4813. ->where(function($query) use ($phones){
  4814. foreach($phones as $p){
  4815. $c = [
  4816. [['customer.phone', '=', $p]],
  4817. [['customer.phone1', '=', $p]],
  4818. [['customer.phone2', '=', $p]]
  4819. ];
  4820. $query->whereOr($c);
  4821. }
  4822. })
  4823. ->count();
  4824. if($e>0) return json(['code'=>1, 'msg'=>'该客户在保护期内,无法提交']);
  4825. }
  4826. }
  4827. }
  4828. }
  4829. }
  4830. // 更改客户信息
  4831. $orders = false;
  4832. //签单之后不能签单交定,可以跟进
  4833. if (3 == $customerVisitLogState) {
  4834. $is = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')], ['customer_id', '=', $had->id]])->count();
  4835. if ($is) return $this->updateMoney($param);
  4836. $orders = true;
  4837. $had->signed_money = $stateParamValue['money'];
  4838. }
  4839. if (2 == $customerVisitLogState) {
  4840. $is = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState('已签单', 'chaos')], ['customer_id', '=', $had->id]])->count();
  4841. if ($is) return json(['code' => 1, 'msg' => '该客户已签单']);
  4842. $orders = true;
  4843. $had->deposit_money = $stateParamValue['money'];
  4844. }
  4845. Db::startTrans();
  4846. //如果是分派的客户第一次跟进直接修改分派信息为空
  4847. if (!empty($had->transfer_info)) $had->transfer_info = NULL;
  4848. //如果是第一次有效修改有效时间
  4849. if(in_array($param['state'], [2,3,7,8]) && $had->state == '待确认'){
  4850. $had->valid_time = !empty($stateParamValue['confirm_date']) ? $stateParamValue['confirm_date'] : date('Y-m-d H:i:s');
  4851. }
  4852. $had->state = $customerState;
  4853. $had->last_contact_date = date('Y-m-d', time());
  4854. $had->updatetime = date('Y-m-d H:i:s', time());
  4855. $had->fresh = 0;
  4856. // 更新客户保护期限
  4857. if($protectedDay) $had->protected_to = date('Y-m-d', time()+$protectedDay * 86400);
  4858. $had->save();
  4859. // 添加确定消息内容
  4860. $confirmMsg = '';
  4861. if (!empty($stateParamValue['confirm_date'])) {
  4862. $confirmMsg = ', 时间:' . $stateParamValue['confirm_date'];
  4863. }
  4864. // 备注
  4865. $employeeName = Employee::where(['id' => $empcrm->id])->value('name');
  4866. $remark = '';
  4867. $remark = $employeeTypeName . $employeeName . '更新客户状态为' . $stateStr . $confirmMsg;
  4868. $is_set = Setting::where([['root_id','=',$empcrm->root_id],['name','=','nextVisitTimeIsOk']])->value('content');
  4869. // 添加追踪记录
  4870. $visitLog = [
  4871. 'customer_id' => $had->id,
  4872. 'type' => '',
  4873. 'next_contact_date' => $is_set ? date('Y-m-d') : null,
  4874. 'employee_id' => $empcrm->id,
  4875. 'user_id' => $empcrm->uid,
  4876. 'remark' => $remark,
  4877. 'state' => $customerVisitLogState,
  4878. 'money' => $stateParamValue['money'] ?? 0,
  4879. 'confirm_date' => $stateParamValue['confirm_date'] ?? date('Y-m-d H:i:s'),
  4880. 'org_id' => $empcrm['org_id'],
  4881. 'customer_employee_id' => $had->employee_id,
  4882. 'customer_org_id' => Employee::where('id', $had->employee_id)->value('org_id'),
  4883. ];
  4884. $visitLog = CustomerVisitLog::create($visitLog);
  4885. if ($orders) $this->preformance_tasks($stateStr, $param['customer_id'], $stateParamValue['money'], $visitLog->id); //计算业绩
  4886. // //如果签单,默认交定
  4887. // if ($customerVisitLogState == 3) {
  4888. // $lw[] = CustomerVisitLog::changeState(['state', '=', '交定']);
  4889. // $lw[] = ['customer_id', '=', $param['customer_id']];
  4890. // $check = CustomerVisitLog::where($lw)->find();
  4891. // if (!$check) {
  4892. // $l_visitlog = $visitLog->toArray();
  4893. // unset($l_visitlog['id']);
  4894. // $l_visitlog['state'] = '交定';
  4895. // $l_visitlog['remark'] = $employeeTypeName . $employeeName . '变更客户状态为交定';
  4896. // $new_visitlog = array_merge($param, $l_visitlog);
  4897. // $new_visitlog['money'] = 0; //直接签单默认交定金额为0
  4898. // $mr = CustomerVisitLog::create($new_visitlog);
  4899. // $this->preformance_tasks('已交定', $param['customer_id'], $stateParamValue['money'], $mr->id); //计算业绩
  4900. // }
  4901. // }
  4902. if ($customerVisitLogState == 7 || $customerVisitLogState == 8) {
  4903. $type = $customerVisitLogState == 7 ? 1 : 3;
  4904. $subscribe = CustomersSubscribe::where([['customer_id', '=', $had['id']], ['type', '=', $type], ['state', '=', 0]])->find();
  4905. if (!empty($subscribe)) {
  4906. $subscribe->state = 1;
  4907. $subscribe->save();
  4908. }
  4909. }
  4910. //增加经纪人送积分功能
  4911. if ($had->agents_id && in_array($customerVisitLogState, [2,3,7])) {
  4912. $this->agents_integral($had->agents_id, $customerVisitLogState, $had->id);
  4913. }
  4914. // 微爆活动
  4915. if (in_array($param['state'], [2, 3, 7, 8])) {
  4916. $activity_data['customer_id'] = $param['customer_id'];
  4917. $activity_data['employee_id'] = $had->employee_id;
  4918. $activity_data['org_id'] = $had->org_id;
  4919. switch ($param['state']) {
  4920. case 7: // 已到店
  4921. $activity_data['type'] = 2;
  4922. break;
  4923. case 8: // 已量房
  4924. $activity_data['type'] = 3;
  4925. break;
  4926. case 2: // 已交定
  4927. $activity_data['type'] = 4;
  4928. break;
  4929. case 3: // 已签单
  4930. $activity_data['type'] = 5;
  4931. break;
  4932. case 9: // 已到场
  4933. $activity_data['type'] = 7;
  4934. break;
  4935. default:
  4936. break;
  4937. }
  4938. WechatActivityIntegral::addIntegral($activity_data, $empcrm['root_id']);
  4939. }
  4940. Db::commit();
  4941. Console::call('medal', ['visit_log', (string)$empcrm->id, (string)$empcrm->root_id]); //勋章
  4942. if($empcrm->is_manager == 1){
  4943. // 经理回访后修改客户的待回访的状态
  4944. Customer::where('id', $had->id)->update(['return_visit' => 0]);
  4945. }
  4946. // if ($param['state'] == 2) {
  4947. // // 发送管理层模板消息
  4948. // $msg = ['first'=>'行为通知', 'keyword1'=>'客户确认到店', 'keyword2'=>"客户".$had['name']."(".$had['phone'].")确认到店", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  4949. // TmpMsg::sendMsgToLeader($msg, $empcrm['org_id']);
  4950. // }
  4951. $had['name'] = !empty($had['name']) ? $had['name'] : '';
  4952. if ($param['state'] == 3) {
  4953. // 发送管理层模板消息
  4954. $msg = ['first'=>'行为通知', 'keyword1'=>'客户签单', 'keyword2'=>"客户".$had['name']."(".$had['phone'].")签单", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  4955. //TmpMsg::sendMsgToLeader($msg, $empcrm['org_id']);
  4956. }
  4957. if ($param['state'] == 7) {
  4958. // 发送管理层模板消息
  4959. $msg = ['first'=>'行为通知', 'keyword1'=>'客户确认到店', 'keyword2'=>"客户".$had['name']."(".$had['phone'].")确认到店", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  4960. //TmpMsg::sendMsgToLeader($msg, $empcrm['org_id']);
  4961. }
  4962. return json(['code' => 0, 'msg' => '跟进成功']);
  4963. }
  4964. private function protectCondition($k_s, $day)
  4965. {
  4966. $empcrm = request()->empcrm;
  4967. $org_ids = orgSubIds($empcrm->root_id);
  4968. $check_where = [];
  4969. $v_where = [];
  4970. switch ($k_s){
  4971. case 'liangfang':
  4972. $v_where[] = [
  4973. ['customers_subscribe.org_id', 'in', $org_ids],
  4974. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  4975. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  4976. ['customers_subscribe.type', '=', 3],
  4977. ['customers_subscribe.state', '=', 1]
  4978. ];
  4979. $check_where = [
  4980. ['customer_visit_log.org_id', 'in', $org_ids],
  4981. ['customer_visit_log.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  4982. ['customer_visit_log.employee_id', '<>', $empcrm->id],
  4983. ['customer_visit_log.state', 'in', CustomerVisitLog::changeState('已量房', 'chaos')]
  4984. ];
  4985. break;
  4986. case 'yliangfang': //预约量房
  4987. $v_where[] = [
  4988. ['customers_subscribe.org_id', 'in', $org_ids],
  4989. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  4990. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  4991. ['customers_subscribe.type', '=', 3],
  4992. ['customers_subscribe.state', '=', 0]
  4993. ];
  4994. break;
  4995. case 'daodian':
  4996. $v_where[] = [
  4997. ['customers_subscribe.org_id', 'in', $org_ids],
  4998. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  4999. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  5000. ['customers_subscribe.type', '=', 1],
  5001. ['customers_subscribe.state', '=', 1]
  5002. ];
  5003. $check_where = [
  5004. ['customer_visit_log.org_id', 'in', $org_ids],
  5005. ['customer_visit_log.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  5006. ['customer_visit_log.employee_id', '<>', $empcrm->id],
  5007. ['customer_visit_log.state', 'in', CustomerVisitLog::changeState('已到店', 'chaos')]
  5008. ];
  5009. break;
  5010. case 'ydaodian':
  5011. $v_where[] = [
  5012. ['customers_subscribe.org_id', 'in', $org_ids],
  5013. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  5014. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  5015. ['customers_subscribe.type', '=', 1],
  5016. ['customers_subscribe.state', '=', 0]
  5017. ];
  5018. break;
  5019. case 'daochang':
  5020. $v_where[] = [
  5021. ['customers_subscribe.org_id', 'in', $org_ids],
  5022. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  5023. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  5024. ['customers_subscribe.type', '=', 2],
  5025. ['customers_subscribe.state', '=', 1]
  5026. ];
  5027. $check_where = [
  5028. ['customer_visit_log.org_id', 'in', $org_ids],
  5029. ['customer_visit_log.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  5030. ['customer_visit_log.employee_id', '<>', $empcrm->id],
  5031. ['customer_visit_log.state', 'in', CustomerVisitLog::changeState('已到场', 'chaos')]
  5032. ];
  5033. break;
  5034. case 'ydaochang':
  5035. $v_where[] = [
  5036. ['customers_subscribe.org_id', 'in', $org_ids],
  5037. ['customers_subscribe.addtime', '>', date('Y-m-d H:i:s',time() - 24*3600*$day)],
  5038. ['customers_subscribe.employee_id', '<>', $empcrm->id],
  5039. ['customers_subscribe.type', '=', 2],
  5040. ['customers_subscribe.state', '=', 0]
  5041. ];
  5042. break;
  5043. }
  5044. return ['log' => $check_where, 'subscribe' => $v_where];
  5045. }
  5046. //获取客户所有扩展字段
  5047. public function get_all_portrait_field()
  5048. {
  5049. $root_id = request()->empcrm->root_id;
  5050. $w[] = ['root_id', '=', $root_id];
  5051. $param = $this->request->only(['id']);
  5052. $id = $param['id'];
  5053. $AllOrgId = orgSubIds($root_id);
  5054. $cusdata = Customer::where([['org_id', 'in', $AllOrgId], ['id', '=', $id]])->find();
  5055. if(empty($cusdata)) return json(['code' => 1,'msg'=>'客户不存在']);
  5056. $list = CustomerPortraitField::where([['root_id', '=', $root_id], ['pid', '=', 0], ['status', '=', 0]])->orderRaw('if(isnull(sort),1,0),sort asc')->select()->toArray();
  5057. $city = Company::where('root_id', $root_id)->value('city');
  5058. foreach ($list as $key => $val) {
  5059. $child = CustomerPortraitField::with(['select'])->where([['root_id', '=', $root_id], ['pid', '<>', 0], ['pid', '=', $val['id']], ['status', '=', 0]])->orderRaw('if(isnull(sort),1,0),sort asc')->select()->toArray();
  5060. foreach ($child as $k => $v) {
  5061. if ($v['keyname'] == 'current_region') {
  5062. $child[$k]['select'][] = ['id' => $root_id, 'name' => $city, 'pid' => $v['id']];
  5063. }
  5064. if ($v['keyname'] == 'source_id') {
  5065. $soudata = CustomerSource::field('id,source as name')->where('root_id', $root_id)->select()->toArray();
  5066. $child[$k]['select'] = $soudata;
  5067. }
  5068. if ($v['keyname'] == 'deco_style') {
  5069. $decostyles = Decostyle::field('id,name')->where([['root_id', '=', $root_id], ['type', '=', 0]])->select()->toArray();
  5070. $child[$k]['select'] = $decostyles;
  5071. }
  5072. $child[$k]['value'] = '';
  5073. $child[$k]['valname'] = '';
  5074. }
  5075. $list[$key]['child'] = $child;
  5076. }
  5077. $new = $list;
  5078. $cuslog = new CustomerLogic;
  5079. if (!empty($cusdata['ext']) && $cusdata['ext'] != 'null') {
  5080. $extdata = json_decode($cusdata['ext'], true);
  5081. if (isset($extdata['ext1'])) {
  5082. $new = $cuslog->old_data_save($cusdata, $list);
  5083. } else {
  5084. $new = $cuslog->new_data_save($cusdata, $extdata, $list);
  5085. }
  5086. }
  5087. return json(['code' => 0, 'data' => $new,'msg'=>'获取成功']);
  5088. }
  5089. /**
  5090. * 设计师指定
  5091. * 2022-11-08 业务修改, 指派设计师改为指派人员 并且可以指派多人
  5092. * $id 客户id
  5093. * $designerId 指派的人员 1,2,3,4 //为空取消指派人员
  5094. */
  5095. public function reserveDesigner()
  5096. {
  5097. $request = request();
  5098. $param = $this->request->only(['id','designerId','assign_type']);
  5099. $id = $param['id'];
  5100. $designerId = $param['designerId'];
  5101. $root_id = $request->empcrm->root_id;
  5102. if (isset($request->empcrm->is_manager) && $request->empcrm->is_manager) {
  5103. $customer = Customer::where([['id', '=', $id], ['org_id', 'in', orgSubIds($request->empcrm['root_id'])]])->find();
  5104. } else {
  5105. $customer = Customer::where(['id' => $id, 'employee_id' => $request->empcrm['id']])->find();
  5106. }
  5107. if (empty($customer)) return json(['code' => 1, 'msg' => '客户不存在']);
  5108. if (empty($designerId)) {
  5109. $customer->designer_id = NULL;
  5110. $customer->assigned_personnel = NULL;
  5111. $customer->save();
  5112. return json(['code' => 0, 'msg' => '取消指派成功!']);
  5113. }
  5114. $designerId = explode(',', $designerId);
  5115. $designer = Employee::where([
  5116. ['id', 'in', $designerId], ['root_id', '=', $root_id], ['state', '=', '在职']
  5117. ])->column('org_id', 'id');
  5118. if (empty($designer)) return json(['code' => 1, 'msg' => '指派人员不存在']);
  5119. $orgs = Org::where([['id', 'in', array_values($designer)]])->column('org_type', 'id');
  5120. //第一个选择的设计师
  5121. $selectDesigner = [];
  5122. foreach ($designerId as $k => $v) {
  5123. if (empty($designer[$v]) || $orgs[$designer[$v]] !== 2) continue;
  5124. $selectDesigner[] = $v;
  5125. }
  5126. $designer_id = isset($selectDesigner[0]) ? $selectDesigner[0] : null;
  5127. // 检测是否有设计师已指派满了
  5128. $limitNum = Setting::where(['root_id' => $request->empcrm['root_org'], 'name' => 'designerNum'])->value('content');
  5129. if ($limitNum != 0) {
  5130. //获取当月时间跨度
  5131. $start_time = date('Y-m').'-01 00:00:00';
  5132. $end_time = date('Y-m-d',strtotime("$start_time +1 month -1 day")).' 23:59:59';
  5133. $where[] = ['addtime', 'between', [strtotime($start_time),strtotime($end_time)]];
  5134. $where[] = ['employee_id', 'in', $selectDesigner];
  5135. $had = CustomerSharing::field('employee_id,count(customer_id) as num')->group('employee_id')->where($where)->having("num >= $limitNum")->select();
  5136. // var_dump($had->toArray());
  5137. // exit;
  5138. if (!$had->isEmpty()) return json(['code' => 1, 'msg' => '指派的设计师已无指派名额,请刷新后再试']);
  5139. }
  5140. // 检测部门是否是设计师
  5141. // $orgType = Org::where(['id' => $designer->org_id])->value('org_type');
  5142. // if ($orgType != 2) return json(['code' => 1, 'msg' => '设计师不存在']);
  5143. $customer->designer_id = $designer_id;
  5144. $customer->assigned_personnel = implode(',', array_keys($designer));
  5145. $customer->assign_time = date('Y-m-d H:i:s');
  5146. if(!empty($param['assign_type']) && empty($customer->assign_type)) $customer->assign_type = $param['assign_type'];
  5147. $customer->save();
  5148. // 更新预约未确定的客户所属设计师id
  5149. CustomersSubscribe::where(['customer_id' => $customer->id, 'state' => 0])->update(['designer_id' => $designer_id]);
  5150. $all_assign_type = ['yixiang'=>'意向客户指派','liangfang'=>'量房客户指派','daodian'=>'到店客户指派'];
  5151. if(!empty($all_assign_type[$customer->assign_type])){
  5152. $empname_arr = Employee::where([['id','in',implode(',', array_keys($designer))],['root_id','=',$root_id]])->column('name');
  5153. $remark = $all_assign_type[$customer->assign_type] . '指派至员工' . implode(',', $empname_arr);
  5154. $visit_Log = [
  5155. 'customer_id' => $id,
  5156. 'type' => '',
  5157. 'remark' => $remark,
  5158. 'employee_id' => $request->empcrm->id,
  5159. 'user_id' => $request->empcrm->uid,
  5160. 'state' => 1,
  5161. 'next_contact_date'=>date('Y-m-d'),
  5162. 'customer_employee_id'=>$customer->employee_id,
  5163. 'customer_org_id'=>$customer->org_id,
  5164. 'org_id'=>$customer->org_id
  5165. ];
  5166. CustomerVisitLog::create($visit_Log);
  5167. }
  5168. return json(['code' => 0, 'msg' => '指派成功!']);
  5169. }
  5170. /**
  5171. * 客户报备
  5172. */
  5173. public function add_customer()
  5174. {
  5175. if (!request()->isAjax()) {
  5176. return View::fetch();
  5177. }
  5178. $root_id = request()->empcrm->root_id;
  5179. $employee_id = request()->empcrm->id;
  5180. $is_manager = request()->empcrm->is_manager;
  5181. $org_id = request()->empcrm->org_id;
  5182. $orgids = orgSubIds($root_id);
  5183. //编辑客户id
  5184. $id = $this->request->param('id');
  5185. if (empty($id)) {
  5186. // 设计师能否报备、获取客户
  5187. $de_where[] = ['root_id', '=', $root_id];
  5188. $de_where[] = ['name', '=', 'designer_get_customer'];
  5189. $info_de_where = Setting::where($de_where)->findOrEmpty();
  5190. if (!$info_de_where->isEmpty() && request()->empcrm->org_type == 2) {
  5191. if ((int)$info_de_where['content'] != 1) {
  5192. return json(['code' => 1, 'msg' => '您的身份为设计师,无法报备客户']);
  5193. }
  5194. }
  5195. }
  5196. //管理员进行编辑客户信息
  5197. if($is_manager ==1 && $id){
  5198. $employee_id = Customer::where([['id','=', $id],['org_id','in',$orgids]])->value('employee_id');
  5199. }
  5200. $data = $this->request->only(['name', 'phone', 'sex', 'level', 'state' => '待确认', 'last_contact_date' => date('Y-m-d'), 'phone1', 'phone2', 'agents_id']);
  5201. //扩展字段
  5202. $ext = $this->request->param('ext');
  5203. //去掉添加的备用手机号字段
  5204. foreach($ext as $key=>$val){
  5205. if(in_array($val['keyname'],['phone1','phone2'])){
  5206. unset($ext[$key]);
  5207. }
  5208. }
  5209. $ext = array_values($ext);
  5210. $orgids = orgSubIds($root_id);
  5211. $pharr = [
  5212. $data['phone'],
  5213. !empty($data['phone1']) ? $data['phone1'] : '',
  5214. !empty($data['phone2']) ? $data['phone2'] : ''
  5215. ];
  5216. $repeat=[];
  5217. foreach($pharr as $key=>$val){
  5218. if(empty($val)) continue;
  5219. if(!in_array($val,$repeat)){
  5220. $repeat[] = $val;
  5221. }else{
  5222. return json(['code' => 1, 'msg' => '手机号不能重复']);
  5223. }
  5224. }
  5225. //判断手机号是否在公海,资源库,已建档,回收站
  5226. // 增加同部门能否重复录入判断
  5227. if (!$id) {
  5228. $tips = $this->checkPepeat($pharr, $orgids, $employee_id);
  5229. if (!empty($tips)) return $tips;
  5230. } else {
  5231. $tips = $this->checkPepeat($pharr, $orgids, $employee_id, $id);
  5232. if (!empty($tips)) return $tips;
  5233. }
  5234. //验证接收的自定义字段是否开启必填
  5235. $get_field = [
  5236. isset($data['name']) ? 'name' : '',
  5237. isset($data['phone']) ? 'phone' : '',
  5238. isset($data['sex']) ? 'sex' : '',
  5239. isset($data['level']) ? 'level' : '',
  5240. ];
  5241. $get_field = array_filter($get_field);
  5242. $get_field = array_merge($get_field, array_column($ext, 'keyname'));
  5243. $all_field = CustomerPortraitField::where([['root_id', '=', $root_id], ['status', '=', 0], ['keyname', 'in', $get_field]])->orderRaw('if(isnull(sort),1,0),sort asc')->select()->toArray();
  5244. $validate_data = $data;
  5245. $house_type_value = '';
  5246. $live_broadcast_value = [];
  5247. foreach($ext as $t) {
  5248. $validate_data[$t['keyname']] = !empty($t['value']) ? $t['value'] : '';
  5249. if($t['keyname'] == 'house_type' && !empty($t['value'])){
  5250. $house_type_value = CustomerPortraitFieldSelect::where([['pid', '=', $t['id']], ['id', '=', $t['value']]])->value('name');
  5251. }
  5252. if($t['keyname'] == 'live_broadcast' && !empty($t['value'])){
  5253. $live_broadcast_value = CustomerPortraitFieldSelect::where([['pid', '=', $t['id']], ['id', 'in', explode(',',$t['value'])]])->column('name');
  5254. }
  5255. }
  5256. foreach($all_field as $item) {
  5257. if($house_type_value != '期房' && $item['keyname'] == 'house_delivery_time' && $item['is_must'] == 0 && empty($validate_data[$item['keyname']])) continue;
  5258. if(!in_array('1对1业务直播',$live_broadcast_value) && $item['keyname'] == 'live_broadcast_business' && $item['is_must'] == 0 && empty($validate_data[$item['keyname']])) continue;
  5259. if(!in_array('1对1设计直播',$live_broadcast_value) && $item['keyname'] == 'live_broadcast_design' && $item['is_must'] == 0 && empty($validate_data[$item['keyname']])) continue;
  5260. if(!in_array('一对多直播',$live_broadcast_value) && $item['keyname'] == 'live_broadcast_personnel' && $item['is_must'] == 0 && empty($validate_data[$item['keyname']])) continue;
  5261. if ($item['is_must'] == 0 && empty($validate_data[$item['keyname']])) {
  5262. return json(['code' => 1, 'msg' => $item['name'].'不能为空']);
  5263. }
  5264. }
  5265. //扩展字段保存
  5266. $add_customer_extfield = $this->add_customer_extfield($ext);
  5267. $data = array_merge($data, $add_customer_extfield);
  5268. $data['sex'] = isset($data['sex']) && !empty($data['sex']) ? $data['sex'] : 1;//数据库性别必须有默认值
  5269. $customer = new Customer();
  5270. if ($id) {
  5271. unset($data['state']);
  5272. unset($data['last_contact_date']);
  5273. $customer = Customer::where(['id' => $id, 'employee_id|designer_id' => $employee_id])->find();
  5274. $old_customer = $customer;
  5275. if (empty($customer)) return json(['code' => 1, 'msg' => '数据不存在']);
  5276. //增加检测修改的扩展字段信息
  5277. if (!empty($customer['ext']) && $customer['ext'] != 'null') {
  5278. $extdata = json_decode($customer['ext'], true);
  5279. if (isset($extdata['ext1'])) {
  5280. $new_ext = CustomerPortraitField::where([['root_id', '=', $root_id], ['pid', '<>', 0]])->select()->toArray();
  5281. $this->check_old_updatefield($customer, $ext,$new_ext);
  5282. } else {
  5283. $this->check_new_updatefield($customer, $ext);
  5284. }
  5285. }
  5286. } else {
  5287. $data['employee_id'] = $employee_id;
  5288. $data['org_id'] = $org_id;
  5289. }
  5290. Db::startTrans();
  5291. try {
  5292. $customer->save($data);
  5293. // 更新客户保护期
  5294. if (!$id) {
  5295. $customer->save(['employee_time' => date('Y-m-d H:i:s')]); //保存员工获取客户时间
  5296. Customer::changeProtectedTo($customer->id, $root_id);
  5297. $this->check_not_updatefield($customer,$ext);
  5298. }
  5299. //建档后添加一条跟进记录
  5300. if (empty($id)) $this->addFirstCustoemrVisitLog($customer->id);
  5301. Db::commit();
  5302. } catch (\Exception $e) {
  5303. Db::rollback();
  5304. return json(['code' => 1, 'msg' => $e->getMessage()]);
  5305. }
  5306. // 添加微爆积分
  5307. if ($id) {
  5308. // 老客户新加微
  5309. $new_customer = Customer::find($id);
  5310. if (!empty($new_customer['add_wechat_time']) && empty($old_customer['add_wechat_time'])) {
  5311. $i_data['add_wechat_time'] = $new_customer['add_wechat_time'];
  5312. $i_data['customer_id'] = $id;
  5313. $i_data['employee_id'] = $new_customer['employee_id'];
  5314. $i_data['type'] = 1;
  5315. $i_data['org_id'] = $new_customer['org_id'];
  5316. WechatActivityIntegral::addIntegral($i_data, $root_id);
  5317. }
  5318. } else {
  5319. $new_customer = Customer::find($customer->id);
  5320. if (!empty($new_customer['add_wechat_time'])) {
  5321. $i_data['add_wechat_time'] = $new_customer['add_wechat_time'];
  5322. $i_data['customer_id'] = $customer->id;
  5323. $i_data['employee_id'] = $new_customer['employee_id'];
  5324. $i_data['type'] = 1;
  5325. $i_data['org_id'] = $new_customer['org_id'];
  5326. WechatActivityIntegral::addIntegral($i_data, $root_id);
  5327. }
  5328. }
  5329. $customer['name'] = !empty($customer['name']) ? $customer['name'] : '';
  5330. // 发送管理层模板消息
  5331. $msg = ['first'=>'行为通知', 'keyword1'=>'客户信息编辑', 'keyword2'=>"员工". request()->empcrm->name . "对客户".$customer['name']."(".$customer['phone'].")信息编辑", 'keyword3'=>date('Y/m/d'), 'remark'=>'请悉知'];
  5332. //TmpMsg::sendMsgToLeader($msg, request()->empcrm->org_id);
  5333. return json(['code' => 0, 'data' => $customer->id, 'msg' => '添加成功']);
  5334. }
  5335. /**
  5336. * 新建客户时添加一条跟进记录
  5337. * $id 客户id
  5338. */
  5339. public function addFirstCustoemrVisitLog($id)
  5340. {
  5341. $token = request()->empcrm;
  5342. $name = Employee::where('id',$token['id'])->value('name');
  5343. $cname = Customer::where('id',$id)->value('name');
  5344. // $type = $source ? '建档' : '报备';
  5345. $type = '报备';
  5346. $remark = '业务员'.$name.'对客户'.$cname.'进行'.$type;
  5347. $save = [
  5348. 'customer_id' => $id,
  5349. 'type' => '',
  5350. 'next_contact_date' => date('Y-m-d'),
  5351. 'remark' => $remark,
  5352. 'addtime' => date('Y-m-d H:i:s'),
  5353. 'employee_id' => $token['id'],
  5354. 'user_id' => $token['uid'],
  5355. 'state' => 1,
  5356. 'org_id' => $token['org_id'],
  5357. 'customer_employee_id' => $token['id'],
  5358. 'customer_org_id' => $token['org_id']
  5359. ];
  5360. CustomerVisitLog::insertGetId($save);
  5361. return true;
  5362. }
  5363. //新添加字段时的处理
  5364. public function check_not_updatefield($cusdata,$save_ext)
  5365. {
  5366. $yes_save = [];
  5367. foreach($save_ext as $key=>$val){
  5368. if(!empty($val['value'])){
  5369. $yes_save[] = $val;
  5370. }
  5371. }
  5372. if(!empty($yes_save)) $this->save_field_log($yes_save,$cusdata);
  5373. }
  5374. //处理修改字段的记录
  5375. public function save_field_log($yes_data,$cusdata)
  5376. {
  5377. $token = $this->get_token();
  5378. $save_ids = array_column($yes_data,'id');
  5379. $is_down = 0;
  5380. $new_ext = CustomerPortraitField::with(['select'])->where([['root_id', '=', $token['root_org']], ['pid', '<>', 0],['id','in',$save_ids]])->select()->toArray();
  5381. $city = Company::where('root_id', $token['root_org'])->value('city');
  5382. foreach($new_ext as $key=>$val) {
  5383. if ($val['keyname'] == 'current_region') {
  5384. $new_ext[$key]['select'][] = ['id' => $token['root_org'], 'name' => $city, 'pid' => $val['id']];
  5385. }
  5386. if ($val['keyname'] == 'source_id') {
  5387. $new_ext[$key]['select'] = CustomerSource::field('id,source as name')->where('root_id', $token['root_org'])->select()->toArray();
  5388. }
  5389. if ($val['keyname'] == 'deco_style') {
  5390. $new_ext[$key]['select'] = Decostyle::field('id,name')->where([['root_id', '=', $token['root_org']], ['type', '=', 0]])->select()->toArray();
  5391. }
  5392. }
  5393. foreach($yes_data as $key=>$val){
  5394. $selname1 = null;
  5395. $yes_data[$key]['valname'] = $val['value'];
  5396. foreach($new_ext as $k=>$v){
  5397. if($v['id']==$val['id']){
  5398. if($v['type']==6) $is_down = 1;
  5399. $yes_data[$key]['name'] = $v['name'];
  5400. $yes_data[$key]['type'] = $v['type'];
  5401. if (in_array($v['type'], [3, 4]) && !empty($val['value'])) {
  5402. $sp = explode(',', $val['value']);
  5403. foreach ($v['select'] as $w => $q) {
  5404. if (in_array($q['id'], $sp)) {
  5405. $selname1 .= $q['name'] . ',';
  5406. }
  5407. }
  5408. $yes_data[$key]['valname'] = trim($selname1, ',');
  5409. }
  5410. }
  5411. }
  5412. }
  5413. // 添加追踪记录
  5414. $visitLog = [
  5415. 'customer_id' => $cusdata->id,
  5416. 'type' => '',
  5417. 'next_contact_date' => null,
  5418. 'employee_id' => $token['employee_id'],
  5419. 'user_id' => $token['uid'],
  5420. 'remark' => '修改客户扩展信息',
  5421. 'state' => 1,
  5422. 'org_id' => $token['org_id'],
  5423. 'customer_employee_id' => $cusdata->employee_id,
  5424. 'customer_org_id' => Employee::where('id', $cusdata->employee_id)->value('org_id'),
  5425. 'save_portrait_field' =>json_encode($yes_data),
  5426. 'down_portrait_field_status' => 0
  5427. ];
  5428. // var_dump($visitLog);
  5429. // exit;
  5430. CustomerVisitLog::create($visitLog);
  5431. }
  5432. //查询修改值的字段
  5433. public function check_new_updatefield($cusdata,$save_ext)
  5434. {
  5435. $old_data = json_decode($cusdata['ext'],true);
  5436. $yes_save = [];
  5437. foreach ($old_data as $k => $v) {
  5438. foreach ($save_ext as $kk => $vv) {
  5439. if ($v['id'] == $vv['id']) {
  5440. //判断是否修改了数据
  5441. if ($v['value'] != $vv['value']) {
  5442. $yes_save[] = $vv;
  5443. }
  5444. unset($save_ext[$kk]);
  5445. }
  5446. }
  5447. }
  5448. //去除为空值的新字段
  5449. foreach($save_ext as $key=>$val){
  5450. if(empty($val['value'])){
  5451. unset($save_ext[$key]);
  5452. }
  5453. }
  5454. $save_ext = array_values($save_ext);
  5455. $yes_data = $yes_save;
  5456. if (!empty($save_ext)){
  5457. $yes_data = array_merge($yes_save,$save_ext);
  5458. }
  5459. // var_dump($yes_data);
  5460. // exit;
  5461. if(!empty($yes_data)) $this->save_field_log($yes_data,$cusdata);
  5462. }
  5463. //老数据查询修改值的字段
  5464. public function check_old_updatefield($cusdata,$save_ext,$new_ext)
  5465. {
  5466. $old_ext = $this->get_old_ext();
  5467. $ext = json_decode($cusdata['ext'],true);
  5468. // 数据的旧ext处理
  5469. $xin = [];
  5470. foreach ($ext as $key => $val) {
  5471. foreach ($old_ext as $k => $v) {
  5472. if ($k == $key) {
  5473. $a['name'] = $v;
  5474. $a['value'] = $val;
  5475. }
  5476. }
  5477. $xin[] = $a;
  5478. }
  5479. //旧ext处理成新的ext结构
  5480. $old_data = [];
  5481. foreach ($xin as $k => $v){
  5482. foreach ($new_ext as $kk => $vv){
  5483. if ($v['name'] == $vv['name'] && !empty($v['value'])) {
  5484. $old_data['id'] = $vv['id'];
  5485. $old_data['keyname'] = $vv['keyname'];
  5486. $old_data['value'] = $v['value'];
  5487. }
  5488. }
  5489. }
  5490. //$old_data = json_decode($cusdata['ext'],true);
  5491. $yes_save = [];
  5492. foreach ($old_data as $k => $v) {
  5493. foreach ($save_ext as $kk => $vv) {
  5494. if ($v['id'] == $vv['id']) {
  5495. //判断是否修改了数据
  5496. if ($v['value'] != $vv['value']) {
  5497. $yes_save[] = $vv;
  5498. }
  5499. unset($save_ext[$kk]);
  5500. }
  5501. }
  5502. }
  5503. //去除为空值的新字段
  5504. foreach($save_ext as $key=>$val){
  5505. if(empty($val['value'])){
  5506. unset($save_ext[$key]);
  5507. }
  5508. }
  5509. $save_ext = array_values($save_ext);
  5510. $yes_data = $yes_save;
  5511. if (!empty($save_ext)){
  5512. $yes_data = array_merge($yes_save,$save_ext);
  5513. }
  5514. if(!empty($yes_data)) $this->save_field_log($yes_data,$cusdata);
  5515. }
  5516. /**
  5517. * 客户报备扩展字段
  5518. */
  5519. private function add_customer_extfield($ext)
  5520. {
  5521. $root_id = request()->empcrm->root_id;
  5522. $seldata = CustomerPortraitField::with(['select'])->where([['root_id', '=', $root_id], ['status', '=', 0], ['type', 'in', [3, 4]]])->select()->toArray();
  5523. $allselid = [];
  5524. foreach ($seldata as $key => $val) {
  5525. foreach ($val['select'] as $k => $v) {
  5526. $allselid[] = ['id' => $v['id'], 'name' => $v['name']];
  5527. }
  5528. }
  5529. $customer_data = [];
  5530. //Log::record($ext)->save();
  5531. foreach ($ext as $key => $val) {
  5532. $selval = '';
  5533. if ($val['keyname'] == 'community_name') {
  5534. $customer_data['community_name'] = $val['value'];
  5535. }
  5536. if ($val['keyname'] == 'square') {
  5537. $customer_data['square'] = $val['value'];
  5538. }
  5539. if ($val['keyname'] == 'house_type') {
  5540. foreach ($allselid as $k => $v) {
  5541. if ($val['value'] == $v['id']) {
  5542. $selval = $v['name'];
  5543. }
  5544. }
  5545. $customer_data['house_type'] = $selval;
  5546. }
  5547. if ($val['keyname'] == 'house_status') {
  5548. foreach ($allselid as $k => $v) {
  5549. if ($val['value'] == $v['id']) {
  5550. $selval = $v['name'];
  5551. }
  5552. }
  5553. $customer_data['house_status'] = $selval;
  5554. }
  5555. if ($val['keyname'] == 'level') {
  5556. foreach ($allselid as $k => $v) {
  5557. if ($val['value'] == $v['id']) {
  5558. $selval = $v['name'];
  5559. }
  5560. }
  5561. $customer_data['level'] = $selval;
  5562. }
  5563. if ($val['keyname'] == 'house_delivery_time') {
  5564. $customer_data['house_delivery_time'] = $val['value'];
  5565. }
  5566. if ($val['keyname'] == 'plan_deco_time') {
  5567. $customer_data['plan_deco_time'] = $val['value'];
  5568. }
  5569. if ($val['keyname'] == 'budget') {
  5570. $customer_data['budget'] = $val['value'];
  5571. }
  5572. if ($val['keyname'] == 'deco_style') {
  5573. $customer_data['deco_style'] = $val['value'];
  5574. }
  5575. if ($val['keyname'] == 'follow') {
  5576. if (!empty($val['value'])) {
  5577. $gza = explode(',', $val['value']);
  5578. foreach ($allselid as $k => $v) {
  5579. if (in_array($v['id'], $gza)) {
  5580. $selval .= $v['name'] . ',';
  5581. }
  5582. }
  5583. }
  5584. $customer_data['product'] = trim($selval, ',');
  5585. }
  5586. if ($val['keyname'] == 'source_id') {
  5587. $customer_data['source_id'] = $val['value'];
  5588. }
  5589. }
  5590. $customer_data['ext'] = json_encode($ext);
  5591. return $customer_data;
  5592. }
  5593. public function get_old_ext(){
  5594. $extAttr = [
  5595. 'ext1' => '年龄',
  5596. 'ext2' => '是否首次装修',
  5597. 'ext3' => '消费水平',
  5598. 'ext4' => '预计装修时间',
  5599. 'ext5' => '客户爱好',
  5600. 'ext6' => '是否添加微信',
  5601. 'ext7' => '客户空闲时间段',
  5602. 'ext8' => '家庭结构',
  5603. 'ext9' => '家庭成员意见',
  5604. 'ext10' => '请选择房屋户型',
  5605. 'ext11' => '决策人',
  5606. 'ext12' => '客户喜欢的色调',
  5607. 'ext13' => '房屋结构',
  5608. 'ext14' => '装修方式',
  5609. 'ext15' => '客户其它需求',
  5610. 'ext16' => '客户痛点',
  5611. 'ext17' => '重视环保',
  5612. 'ext18' => '重视设计',
  5613. 'ext19' => '关注的工艺',
  5614. 'ext20' => '关注房屋的空间',
  5615. 'ext21' => '汽车价格',
  5616. 'ext22' => '房屋价格',
  5617. 'ext23' => '买小区的原因',
  5618. 'ext24' => '周边配置',
  5619. 'ext25' => '设计师服务',
  5620. 'ext26' => '方案满意度',
  5621. 'ext27' => '报价满意度',
  5622. 'ext28' => '装修意向',
  5623. 'ext29' => '是否到店',
  5624. 'ext30' => '预计到店时间',
  5625. 'ext31' => '是否交定',
  5626. 'ext32' => '客户其他需求',
  5627. 'ext33' => '当前所在区域',
  5628. 'ext34' => '加微类型',
  5629. 'ext35' => '建群情况',
  5630. 'ext36' => '直播情况',
  5631. 'ext37' => '直播人员',
  5632. 'ext38' => '房屋用途',
  5633. 'ext39' => '房屋位置',
  5634. 'ext40' => '其他房屋信息',
  5635. 'ext41' => '谈单时长',
  5636. 'ext42' => '门牌单元号',
  5637. 'ext43' => '业务直播人员',
  5638. 'ext44' => '设计直播人员'
  5639. ];
  5640. return $extAttr;
  5641. }
  5642. /**
  5643. * 添加客户检测手机号的重复
  5644. * 1.客户录入不和资源库和回收站排重 (创艺)
  5645. * 2.客户录入需查询是否和公海重复,如重复,提示可以获取该客户 (创艺) 工单id6077
  5646. */
  5647. public function checkPepeat($pharr, $org_id, $employee_id, $id = null)
  5648. {
  5649. // 同部门能否重复录入开关设置
  5650. $root_id = request()->empcrm['root_id'];
  5651. $empcrm_repeat[] = ['root_id', '=', $root_id];
  5652. $empcrm_repeat[] = ['name', '=', 'empcrm_customer_repeat'];
  5653. $repeat_setting = Setting::where($empcrm_repeat)->findOrEmpty();
  5654. $emp_org = request()->empcrm['org_id'];
  5655. foreach ($pharr as $val) {
  5656. if (empty($val)) continue;
  5657. // 先判断公海 只有添加时候判断
  5658. if (empty($id)) {
  5659. $poolExist = Customer::where([
  5660. ['phone|phone1|phone2', '=', cypherphone(trim($val))],
  5661. ['org_id', '=', $emp_org],
  5662. ['employee_id', 'null', null],
  5663. ['is_resource', '=', 0]
  5664. ])->column('id');
  5665. if (!empty($poolExist)) {
  5666. $poolCrmIdStr = implode(',', $poolExist);
  5667. return json(['code' => 3, 'data' => $poolCrmIdStr, 'msg' => '录入失败:客户信息已在公海中。']);
  5668. }
  5669. }
  5670. // 新建档,检测手机号是否重复
  5671. $customerExist = Customer::where([
  5672. ['phone|phone1|phone2', '=', cypherphone(trim($val))],
  5673. ['org_id', 'in', $org_id],
  5674. ['employee_id', '>', 0] // 员工客户
  5675. ])->field('id,employee_id,is_resource,org_id')->select()->toArray();
  5676. $id_arr = array_column($customerExist, 'id');
  5677. $employee_id_arr = array_column($customerExist, 'employee_id');
  5678. if (empty($id)) {
  5679. // 对非当前业务员名下重复客户不在判断
  5680. if (in_array($employee_id, $employee_id_arr)) {
  5681. // 是否已存在为自己的客户
  5682. return json(['code' => 2, 'msg' => '录入失败。' . $val . '已经是您的客户。']);
  5683. }
  5684. } else {
  5685. if (!in_array($id, $id_arr) && in_array($employee_id, $employee_id_arr)) {
  5686. // 是否已存在为自己的客户
  5687. return json(['code' => 2, 'msg' => '录入失败。' . $val . '已经是您的客户。']);
  5688. }
  5689. }
  5690. //判断同部门
  5691. if (!$repeat_setting->isEmpty()) {
  5692. $repeat_org = explode(',', $repeat_setting['content']);
  5693. if (in_array($emp_org, $repeat_org)) {
  5694. // 需要验证
  5695. if (!empty($customerExist)) {
  5696. foreach ($customerExist as $ex) {
  5697. if (in_array($ex['org_id'], $repeat_org) && $ex['employee_id'] != $employee_id) {
  5698. // 为了避免开启撞单之前都已经重复的情况,所以要查一下这个id的现数据
  5699. if ($id) {
  5700. $this_customer = Customer::find($id);
  5701. if ($this_customer) {
  5702. $this_customer_phone = array_filter([$this_customer['phone'], $this_customer['phone1'], $this_customer['phone2']]);
  5703. if (!in_array($val, $this_customer_phone)) { // 不是原来的客户手机号,编辑时候判断撞单
  5704. $have_emp = Employee::where('id', '=', $ex['employee_id'])->value('name');
  5705. return json(['code' => 2, 'msg' => '该客户与员工' . $have_emp . '撞单,无法录入']);
  5706. }
  5707. }
  5708. } else {
  5709. $have_emp = Employee::where('id', '=', $ex['employee_id'])->value('name');
  5710. return json(['code' => 2, 'msg' => '该客户与员工' . $have_emp . '撞单,无法录入']);
  5711. }
  5712. }
  5713. }
  5714. }
  5715. }
  5716. }
  5717. }
  5718. }
  5719. //编辑客户
  5720. public function edit_customer()
  5721. {
  5722. $request = request();
  5723. $param = $request->only(['id','empid', 'level','source_id','designer_id','name','phone','sex','source_position','subjection_plan'=>'','community_name','square','house_delivery_time','housetype_arrow'=>'','budget','unit_number'=>'','package_id','deco_style','sign_time','employee_id','phone1'=>'']);
  5724. $root_id = $request->empcrm->root_id;
  5725. $empid = $request->empcrm->id;
  5726. $org_employee = [$empid];
  5727. if (!$request->isAjax()) {
  5728. $soudata = CustomerSource::field('id,source as name')->where('root_id', $root_id)->select()->toArray();
  5729. View::assign('soudata', $soudata);
  5730. $list = $this->get_designer();
  5731. if (!empty($list)) {
  5732. // $list = hanziInitsort($list, 'name');
  5733. $sort = array_column($list, 's');
  5734. sort($sort);
  5735. array_multisort($sort, SORT_ASC, $list);
  5736. $sort = array_unique($sort);
  5737. $list = ['sort' => $sort, 'arr' => $list];
  5738. }else{
  5739. $list = ['sort' => [], 'arr' => []];
  5740. }
  5741. View::assign('designers', $list);
  5742. //客户等级 隶属计划
  5743. $fields=CustomerPortraitField::with(['select'])->where([['root_id','=',$root_id],['keyname','in',['level','subjection_plan','housetype_arrow']]])->select()->toArray();
  5744. View::assign('fields', $fields);
  5745. // var_dump($fields);
  5746. // exit;
  5747. //部门所有员工
  5748. $employee_list = Employee::where([['root_id','=',$root_id],['org_id','=',$request->empcrm->org_id],['state', 'in', ['在职']]])->field('id,name')->select()->toArray();
  5749. View::assign('employee_list', $employee_list);
  5750. //意向风格
  5751. $decostyle_list = Decostyle::field('id,name,root_id as pid')->where(['root_id' =>$root_id])->where([['type', '=', 0]])->order('id desc')->select()->toArray();
  5752. View::assign('decostyle_list', $decostyle_list);
  5753. //意向产品
  5754. $product = CustomerPackage::field('id, name, total_price')->where(['root_id' =>$root_id])->select();
  5755. View::assign('product', $product);
  5756. View::assign('empid', $empid);
  5757. //客户详情
  5758. $customer = $this->seLemp($param['id'],$empid);
  5759. // var_dump($customer->toArray());
  5760. // exit;
  5761. View::assign('customer',$customer);
  5762. return View::fetch();
  5763. }
  5764. }
  5765. //客户状态详情
  5766. public function customer_detail()
  5767. {
  5768. $request = request();
  5769. $root_id = $request->empcrm->root_id;
  5770. $empid = $request->empcrm->id;
  5771. $org_employee = [$empid];
  5772. // if (!$request->isAjax()) {
  5773. // $this->screen();
  5774. // return View::fetch();
  5775. // }
  5776. $this->screen();
  5777. $param = $request->only(['id']);
  5778. $data=$this->seLemp($param['id'],$empid);
  5779. //意向风格
  5780. $decostyle_list = Decostyle::field('id,name,root_id as pid')->where(['root_id' =>$root_id])->where([['type', '=', 0]])->order('id desc')->select()->toArray();
  5781. View::assign('decostyle_list', $decostyle_list);
  5782. //意向产品
  5783. $product = CustomerPackage::field('id, name, total_price')->where(['root_id' =>$root_id])->select();
  5784. View::assign('product', $product);
  5785. View::assign('data', $data);
  5786. View::assign('empname', $request->empcrm->name);
  5787. //View::assign('xinjushang',$request->empcrm['xinjushang']);
  5788. // var_dump($data->toArray());
  5789. // exit;
  5790. return View::fetch();
  5791. }
  5792. //公海列表
  5793. public function pool_list()
  5794. {
  5795. $request = request();
  5796. $root_id = $request->empcrm->root_id;
  5797. $empid = $request->empcrm->id;
  5798. $is_manager = $request->empcrm->is_manager;
  5799. $orgids = orgSubIds($root_id);
  5800. if (!$request->isAjax()) {
  5801. $this->screen();
  5802. $week = date('w');
  5803. View::assign('week',$week);
  5804. View::assign('is_manager',$is_manager);
  5805. return View::fetch();
  5806. }
  5807. $param = $request->only(['page' => 1, 'limit' => 20, 'order', 'org', 'keyname', 'state', 'date' => '', 'level', 'source_id', 'designer_id', 'addtime', 'name', 'phone', 'community_name', 'employee_name', 'fistDate']);
  5808. $condition = [];
  5809. $order = isset($param['order']) ? $param['order'] : 'id desc';
  5810. $condition[] = ['employee_id', '=', NULL];
  5811. $condition[] = ['is_resource', '=', 0];
  5812. $condition[] = ['state','in',Customer::changeState('无效','chaos')];
  5813. $condition[] = ['org_id','in',$orgids];
  5814. if (isset($param['org']) && $param['org']) {
  5815. $condition[] = ['org_id', '=', $param['org']];
  5816. } else {
  5817. $orgids = orgSubIds($request->empcrm->org_id);
  5818. $condition[] = ['org_id', 'in', $orgids];
  5819. }
  5820. // if (isset($param['keyname']) && $param['keyname']) {
  5821. // $condition[] = ['name|community_name', 'like', '%' . trim($param['keyname']) . '%'];
  5822. // }
  5823. if (isset($param['level']) && $param['level']) {
  5824. $condition[] = ['level', 'in', explode(',',$param['level'])];
  5825. }
  5826. if (isset($param['source_id']) && $param['source_id']) {
  5827. $condition[] = ['source_id', 'in', explode(',',$param['source_id'])];
  5828. }
  5829. if (isset($param['designer_id']) && $param['designer_id']) {
  5830. $condition[] = ['designer_id', 'in', explode(',',$param['designer_id'])];
  5831. }
  5832. // 姓名筛选
  5833. if (isset($param['name']) && $param['name']) {
  5834. $condition[] = ['name', 'like', '%' . trim($param['name']) . '%'];
  5835. }
  5836. // 小区筛选
  5837. if (isset($param['community_name']) && $param['community_name']) {
  5838. $condition[] = ['community_name', 'like', '%' . trim($param['community_name']) . '%'];
  5839. }
  5840. // 手机号筛选
  5841. if (!empty($param['phone'])) {
  5842. $list = Customer::where($condition)->column('id', 'phone');
  5843. $keyCustomersId = [];
  5844. $aec = new Aec(config('app.aec_key'), config('app.aec_iv'));
  5845. foreach ($list as $k => $v) {
  5846. $v_phone = $aec->decrypt($k);
  5847. if (strpos($v_phone, $param['phone']) !== false) $keyCustomersId[] = $v;
  5848. }
  5849. unset($condition);
  5850. $condition[] = ['id', 'in', $keyCustomersId];
  5851. }
  5852. // 交房时间筛选
  5853. if (!empty($param['house_delivery_time'])) {
  5854. $house_delivery_time = explode(' - ', $param['house_delivery_time']);
  5855. $start = $house_delivery_time[0];
  5856. $end = $house_delivery_time[1] . ' 23:59:59';
  5857. $condition[] = ['house_delivery_time', '>=', $start];
  5858. $condition[] = ['house_delivery_time', '<=', $end];
  5859. }
  5860. // 面积筛选
  5861. if (!empty($param['square'])) {
  5862. $square = explode(',', $param['square']);
  5863. $square_arr = [
  5864. 1 => '(square > 1 and square <= 80)',
  5865. 2 => '(square > 81 and square <= 100)',
  5866. 3 => '(square > 101 and square <= 120)',
  5867. 4 => '(square > 121 and square <= 200)',
  5868. 5 => '(square > 201 and square <= 500)',
  5869. 6 => '(square > 501 and square <= 10000)'
  5870. ];
  5871. $squ_whereOr = null;
  5872. foreach ($square as $k => $v) {
  5873. if (!empty($square_arr[$v])) $squ_whereOr .= $square_arr[$v] . ' OR';
  5874. }
  5875. $customersList = Customer::where($condition)->where(function ($query) use ($squ_whereOr) {
  5876. $query->whereRaw(trim($squ_whereOr, ' OR'));
  5877. })->order('addtime desc')->column('id');
  5878. unset($condition);
  5879. $condition[] = ['id', 'in', $customersList];
  5880. }
  5881. // 首次到店时间筛选
  5882. if (!empty($param['fistDate'])) {
  5883. $fistDate = explode(' - ', $param['fistDate']);
  5884. $start = str_replace('/', '-', $fistDate[0]);
  5885. $end = date('Y-m-d', strtotime($fistDate[1]) + 86400);
  5886. $customersIdList = Customer::where($condition)->order('addtime desc')->column('id');
  5887. $dd_where[] = ['customer_id', 'in', $customersIdList];
  5888. $dd_where[] = ['state', 'in', CustomerVisitLog::changeState('已到店', 'chaos')];
  5889. $dd_where[] = ['confirm_date', '>=', $start];
  5890. $dd_where[] = ['confirm_date', '<=', $end];
  5891. $ddlog = CustomerVisitLog::where($dd_where)->group('customer_id')->order('addtime asc')->column('customer_id');
  5892. unset($condition);
  5893. $condition[] = ['id', 'in', $ddlog];
  5894. }
  5895. // 最后一次置为公海的业务员筛选
  5896. if (!empty($param['employee_name'])) {
  5897. $customersIdList = Customer::where($condition)->column('id');
  5898. $pool_employee_id = CustomerVisitLog::where([['employee_id', 'in', explode(',', $param['employee_name'])], ['customer_id', 'in', $customersIdList], ['state', 'in', CustomerVisitLog::changeState('无效', 'chaos')]])->group('customer_id')->column('customer_id');
  5899. unset($condition);
  5900. $condition[] = ['id', 'in', $pool_employee_id];
  5901. }
  5902. // 报备时间
  5903. if (!empty($param['addtime'])) {
  5904. //筛选区间范围
  5905. $date_time = explode(' - ', $param['addtime']);
  5906. $start = str_replace('/','-',$date_time[0]);
  5907. $end = str_replace('/','-',$date_time[1]);
  5908. $condition[] = [['addtime', 'between', [$start . ' 00:00:00', $end . ' 23:59:59']]];
  5909. }
  5910. // 查询id列表
  5911. $customerIdList = Customer::where($condition)->column('id');
  5912. if (isset($param['state']) && $param['state']) {
  5913. // 筛查状态
  5914. $customerIdList = CustomerVisitLog::where([['state', 'in', CustomerVisitLog::changeState($param['state'])], ['customer_id', 'in', $customerIdList]])->group('customer_id')->column('customer_id');
  5915. }
  5916. //回收时间
  5917. if ($param['date']) {
  5918. //筛选区间范围
  5919. $date_time = explode(' - ', $param['date']);
  5920. $start = str_replace('/','-',$date_time[0]);
  5921. $end = str_replace('/','-',$date_time[1]);
  5922. //$date = explode(' - ', $param['date']);
  5923. //$date = $param['date'];
  5924. $customerIdList = CustomerVisitLog::where([['addtime', 'between', [$start . ' 00:00:00', $end . ' 23:59:59']], ['customer_id', 'in', $customerIdList], CustomerVisitLog::changeState(['state', '=', '无效'])])->group('customer_id')->column('customer_id');
  5925. }
  5926. //$pageIdList = array_slice($customerIdList, ($param['page'] - 1) * $param['limit'], $param['limit']);
  5927. $pageIdList = $customerIdList;
  5928. $condition[] = ['id', 'in', $pageIdList];
  5929. $customersStateList = CustomerVisitLog::where([['customer_id', 'in', $pageIdList]])->group('state,customer_id')->field('count(state) as num, state, customer_id')->select()->toArray();
  5930. $customersState = [];
  5931. foreach ($customersStateList as $s) {
  5932. if (!isset($customersState[$s['customer_id']]))
  5933. $customersState[$s['customer_id']] = ['count' => 0, 'shop' => 0, 'measure' => 0, 'activity' => 0, 'deposit' => 0, 'signed' => 0];
  5934. $customersState[$s['customer_id']]['count'] += $s['num'];
  5935. // 到店,量房,活动,定金,签单
  5936. if ($s['state'] == '已到店') $customersState[$s['customer_id']]['shop'] += $s['num'];
  5937. elseif ($s['state'] == '已量房') $customersState[$s['customer_id']]['measure'] += $s['num'];
  5938. elseif ($s['state'] == '已到场') $customersState[$s['customer_id']]['activity'] += $s['num'];
  5939. elseif ($s['state'] == '已交定') $customersState[$s['customer_id']]['deposit'] += $s['num'];
  5940. elseif ($s['state'] == '已签单') $customersState[$s['customer_id']]['signed'] += $s['num'];
  5941. }
  5942. // 上方id已分页,此处分页参数传固定1
  5943. $data = $this->poollist($condition, 1, $param['limit'], $order);
  5944. $customer_id = array_column($data, 'id');
  5945. $visitLogNum = CustomerVisitLog::where([['customer_id', 'in', $customer_id], CustomerVisitLog::changeState(['state', '=', '无效'])])->group('customer_id')->column('count(customer_id) as num', 'customer_id');
  5946. $visitLogDate = CustomerVisitLog::where([['customer_id', 'in', $customer_id], CustomerVisitLog::changeState(['state', '=', '无效'])])->order('addtime')->column('addtime', 'customer_id');
  5947. $visitLogMeet = CustomerVisitLog::where([['customer_id', 'in', $customer_id], CustomerVisitLog::changeState(['state', '=', '确认到店'])])->order('addtime')->column('addtime', 'customer_id');
  5948. foreach ($data as &$value) {
  5949. //回收次数
  5950. $value['recoverNum'] = isset($visitLogNum[$value['id']]) ? $visitLogNum[$value['id']] : 0;
  5951. //最近的回收时间
  5952. $value['recoverLatelyDate'] = isset($visitLogDate[$value['id']]) ? $visitLogDate[$value['id']] : null;
  5953. //最近的确认到店时间
  5954. $value['fistDate'] = isset($visitLogMeet[$value['id']]) ? $visitLogMeet[$value['id']] : null;
  5955. //上次跟进人信息
  5956. $value['before_pool'] = !empty($value['before_pool']) ? json_decode($value['before_pool'], true) : null;
  5957. $value[$value['id']]['stateNum'] = $customersState[$value['id']] ?? ['count' => 0, 'shop' => 0, 'measure' => 0, 'activity' => 0, 'deposit' => 0, 'signed' => 0];
  5958. // 客户最后一次置为公海的关联员工
  5959. $last_pool_employee = CustomerVisitLog::where([['customer_id', '=', $value['id']], ['state','in',CustomerVisitLog::changeState('无效','chaos')]])->with('employee')->order('addtime desc')->find();
  5960. $value['employee'] = $last_pool_employee ? $last_pool_employee->employee->name : '';
  5961. }
  5962. $sort = array_column($data,'recoverLatelyDate');
  5963. array_multisort($sort, SORT_DESC, $data);
  5964. foreach ($condition as $k => $v) {
  5965. if ($v[0] == 'id') {
  5966. if (isset($v[2])) {
  5967. $condition[$k][2] = $customerIdList;
  5968. }
  5969. }
  5970. }
  5971. $data = array_slice($data, ($param['page'] - 1) * $param['limit'], $param['limit']);
  5972. $count = CustomerLogic::count($condition);
  5973. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  5974. }
  5975. //查询公海
  5976. public function poollist($condition = [], $page, $limit, $order)
  5977. {
  5978. $page = intval($page);
  5979. $limit = intval($limit);
  5980. $data = Customer::with(['source'=>function($query){
  5981. $query->field('id,source');
  5982. }])->field('source_id,id, name, community_name, phone, level, designer_id,state, square, addtime, org_id, employee_id, is_resource, before_pool,first_visit_date,house_delivery_time')
  5983. ->where($condition)
  5984. ->select()->toArray();
  5985. foreach ($data as &$item) {
  5986. $item['pool_name'] = Org::where('id', $item['org_id'])->column('name');
  5987. if (!$item['employee_id']) {
  5988. $item['phone'] = substr_replace($item['phone'], '******', 3, 6);
  5989. }
  5990. }
  5991. return $data;
  5992. }
  5993. /**
  5994. * 快速修改客户的扩展信息
  5995. */
  5996. public function fast_up_portrait()
  5997. {
  5998. $request = request();
  5999. $root_id = $request->empcrm->root_id;
  6000. $orgids = orgSubIds($root_id);
  6001. $param = $request->only(['type','cid','value']);
  6002. //var_dump($param);exit;
  6003. $cusdata = Customer::where([['org_id','in',$orgids],['id','=',$param['cid']]])->find();
  6004. if(empty($cusdata)) return json(['code'=>'1','msg'=>'客户不存在']);
  6005. if($param['type'] == 'level'){
  6006. if(!in_array($param['value'],['A','B','C','D'])) return json(['code'=>'1','msg'=>'客户等级不存在']);
  6007. $cusdata->level = $param['value'];
  6008. $cusdata->save();
  6009. return json(['code'=>'0','msg'=>'修改成功']);
  6010. }
  6011. if($param['type'] == 'field'){
  6012. if(!in_array($param['value'],['reputation_gather','into_owner_group','add_wechat_time'])) return json(['code'=>'1','msg'=>'修改字段不存在']);
  6013. $fieldid = CustomerPortraitField::where([['root_id','=',$root_id],['keyname','=',$param['value']]])->value('id');
  6014. $isin = false;
  6015. if(!empty($cusdata['ext'])){
  6016. foreach(json_decode($cusdata['ext'],true) as $key=>$val){
  6017. if($val['keyname'] == $param['value'] && empty($val['value'])){
  6018. $val['value'] = date('Y-m-d');
  6019. $isin = true;
  6020. }
  6021. $all[] = ['id'=>$val['id'],'value'=>$val['value'],'keyname'=>$val['keyname']];
  6022. }
  6023. if(!$isin) $all[] = ['id'=>$fieldid,'value'=>date('Y-m-d'),'keyname'=>$param['value']];
  6024. $cusdata->ext = json_encode($all);
  6025. $cusdata->save();
  6026. return json(['code'=>'0','msg'=>'修改成功']);
  6027. }
  6028. }
  6029. }
  6030. /*
  6031. * 审核人员
  6032. */
  6033. public function get_person()
  6034. {
  6035. $ids = input('id', '');
  6036. $root_id = request()->empcrm->root_id;
  6037. $type = input('type', 0);
  6038. //树形
  6039. if ($type == 1) {
  6040. //所有员工
  6041. $w1[] = ['root_id', '=', $root_id];
  6042. $w1[] = ['state', '=', '在职'];
  6043. $w1[] = ['uid', '<>', 0];
  6044. $w1[] = ['org_id', '>', 0];
  6045. $w1[] = ['org_id', '<>', $root_id];
  6046. $w1[] = ['id','<>',request()->empcrm->id];
  6047. $employee_list = Employee::where($w1)->with(['org'=>function($query){
  6048. $query->field('id,org_type');
  6049. }])->select()->toArray();
  6050. $employee = [];
  6051. foreach ($employee_list as $k => $v) {
  6052. $employee[] = [
  6053. 'value'=> $v['id'],
  6054. 'name'=> $v['name'],
  6055. 'org_id'=> $v['org_id'],
  6056. 'org_type'=> $v['org']['org_type']
  6057. ];
  6058. }
  6059. if ($ids) {
  6060. $ids = explode(',', $ids);
  6061. foreach ($employee as $k => &$v) {
  6062. $v['selected'] = in_array($v['value'], $ids);
  6063. }
  6064. } else {
  6065. foreach ($employee as $k => &$v) {
  6066. $v['selected'] = false;
  6067. }
  6068. }
  6069. $persons = [];
  6070. foreach ($employee as $k => $v1) {
  6071. $persons[$v1['org_id']][] = $v1;
  6072. }
  6073. $where = [
  6074. ['path', 'like', $root_id . '-%'],
  6075. ['status', '=', 1]
  6076. ];
  6077. $allnodes = Org::where($where)->field('id value,id,pid,name')->order('level asc, id asc')->select()->toArray();
  6078. $tree = $this->tree($allnodes, 0, $persons);
  6079. return json($tree);
  6080. }
  6081. $w[] = ['root_id', '=', $root_id];
  6082. $w[] = ['state', '=', '在职'];
  6083. $w[] = ['role', '=', '领导'];
  6084. $w[] = ['uid', '<>', 0];
  6085. $employee = Employee::where($w)->field('id value,name')->select()->toArray();
  6086. if ($ids) {
  6087. $ids = explode(',', $ids);
  6088. foreach ($employee as $k => &$v) {
  6089. $v['selected'] = in_array($v['value'], $ids);
  6090. }
  6091. } else {
  6092. foreach ($employee as $k => &$v) {
  6093. $v['selected'] = false;
  6094. }
  6095. }
  6096. return json($employee);
  6097. }
  6098. public function tree($data, $pid = 0, $persons)
  6099. {
  6100. $new_arr = [];
  6101. foreach ($data as $k => $v) {
  6102. if ($v['pid'] == $pid) {
  6103. $persions = isset($persons[$v['id']]) ? $persons[$v['id']] : [];
  6104. $children = $this->tree($data, $v['id'], $persons);
  6105. $v['children'] = array_merge_recursive($children, $persions);
  6106. //if (empty($v['children'])) $v['disabled'] = true;
  6107. if (empty($v['children'])) continue;
  6108. $new_arr[] = $v;
  6109. }
  6110. }
  6111. return $new_arr;
  6112. }
  6113. /**
  6114. * 日报
  6115. */
  6116. public function daily()
  6117. {
  6118. $request = request();
  6119. $root_id = $request->empcrm->root_id;
  6120. $empid = $request->empcrm->id;
  6121. $is_manager = $request->empcrm->is_manager;
  6122. $org_employee = [$empid];
  6123. $team_orgs = [$request->empcrm->org_id];
  6124. if($is_manager ==1){
  6125. $team_orgs = orgSubIds($request->empcrm->org_id);
  6126. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  6127. }
  6128. $param = $request->only(['date','employee_id','org_id']);
  6129. if (!$request->isAjax()) {
  6130. $data['company_name'] = Company::where('root_id',$root_id)->value('company_name');
  6131. $data['empname'] = $request->empcrm->name;
  6132. $data['date'] = !empty($param['date']) ? $param['date'] : date('Y-m');
  6133. $data['org_id'] = !empty($param['org_id']) ? $param['org_id'] :'';
  6134. $data['org_name'] = !empty($param['org_id']) ? Org::where([['id','=',$param['org_id']],['root_id','=',$root_id]])->value('name') : '';
  6135. View::assign('data',$data);
  6136. View::assign('is_manager',$is_manager);
  6137. //部门所有员工
  6138. $employee_list = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->field('id,name')->select()->toArray();
  6139. View::assign('employee_list', $employee_list);
  6140. //下级所有部门
  6141. $org_list = Org::where([['id','in',$team_orgs],['id','<>',$request->empcrm->org_id]])->select()->toArray();
  6142. View::assign('org_list',$org_list);
  6143. return View::fetch();
  6144. }
  6145. $today = date('Y-m',time()).'-01 00:00:00';
  6146. $todaynum = date('d',time());
  6147. $firstday = $param['date'].'-'.'01 00:00:00';
  6148. $lastday = date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
  6149. $lastnum = date('d', strtotime("$firstday +1 month -1 day"));
  6150. $nowempid = $empid;
  6151. $noworgid = $request->empcrm->org_id;
  6152. if($is_manager ==1) $nowempid = $noworgid = '';
  6153. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $nowempid = $param['employee_id'];
  6154. $where[] = ['addtime', 'between', [$firstday,$lastday]];
  6155. if(!empty($param['employee_id']) && $is_manager ==1 && in_array($param['employee_id'],$org_employee)) $org_employee = [$param['employee_id']];
  6156. if(!empty($param['org_id']) && $is_manager ==1){
  6157. $noworgid = $param['org_id'];
  6158. $org_employee = Employee::where([['org_id','in',$param['org_id']],['root_id','=',$root_id],['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  6159. }
  6160. $where[] = ['customer_employee_id','in',$org_employee];
  6161. //$list = Customer::where($where)->field('id,name,addtime,state,valid_time')->select()->toArray();
  6162. //电话记录
  6163. $hu_where = [];
  6164. $hu_where[] = ['employee_id','in',$org_employee];
  6165. $hu_where[] = ['root_id','=',$root_id];
  6166. $hu_where[] = ['addtime','>=',$firstday];
  6167. $hu_where[] = ['addtime','<=',$lastday];
  6168. //新增加客户数
  6169. $new_cuslist = Customer::where([['sign_time','>=',$firstday],['sign_time','<=',$lastday],['employee_id','in',$org_employee],['state','not in',Customer::changeState('无效','chaos')]])->column('id,sign_time,state');//->select()->toArray();
  6170. //加微客户数
  6171. $addwechat_cuslist = Customer::where([['add_wechat_time','>=',$firstday],['add_wechat_time','<=',$lastday],['employee_id','in',$org_employee]])->column('id,add_wechat_time');
  6172. //进群客户数
  6173. $into_group_cuslist = Customer::where([['into_owner_group','>=',$firstday],['into_owner_group','<=',$lastday],['employee_id','in',$org_employee]])->column('id,into_owner_group');
  6174. //待确认的客户
  6175. //$treat_cuslist = Customer::where([['state','in',[0,'待确认']],['sign_time','>=',$firstday],['sign_time','<=',$lastday],['employee_id','in',$org_employee]])->column('sign_time','id');
  6176. //置为无效的客户
  6177. $invalidcus = CustomerInvalidLog::where([['root_id','=',$root_id],['employee_id', 'in', $org_employee],['cus_addtime','between', [$firstday,$lastday]]])->column('cus_addtime,employee_id,customer_id,status');
  6178. $state1 = Customer::changeState('待确认','chaos');
  6179. $state2 = Customer::changeState('无效','chaos');
  6180. $state3 = CustomerVisitLog::changeState('已交定','chaos');
  6181. $state4 = CustomerVisitLog::changeState('已签单','chaos');
  6182. $state5 = CustomerVisitLog::changeState('确认到店','chaos');
  6183. $state6 = CustomerVisitLog::changeState('无效','chaos');
  6184. $state7 = CustomerVisitLog::changeState('未到访','chaos');
  6185. $state8 = CustomerVisitLog::changeState('已到场','chaos');
  6186. $state9 = CustomerVisitLog::changeState('已量房','chaos');
  6187. //记录
  6188. $visitlog_list = CustomerVisitLog::where($where)
  6189. ->where([['state','in',array_merge($state3,$state4,$state5,$state6,$state7,$state8,$state9)]])
  6190. //->group('state,customer_id')
  6191. ->order('addtime asc')
  6192. ->column('customer_id,state,money,confirm_date');
  6193. $metids = [];
  6194. foreach($visitlog_list as $key=>$val){
  6195. if(in_array($val['state'],array_merge($state5,$state8,$state9))) $metids[] = $val['customer_id'];
  6196. }
  6197. $yesids = !empty($metids) ? $this->selBeforelog(array_unique($metids),$firstday) : [];
  6198. $xin=[];
  6199. $weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
  6200. if($today == $firstday){
  6201. for($i=0;$i<$todaynum;$i++){
  6202. $day = date('Y-m-d', strtotime("$firstday +$i days"));
  6203. $a['day'] = $day;
  6204. $a['week'] = $weekarray[date("w",strtotime("$firstday +$i days"))];
  6205. $a['logdata'] = [];
  6206. foreach($visitlog_list as $key=>$val){
  6207. if($val['confirm_date'] >= $day.' 00:00:00' && $val['confirm_date'] <= $day.' 23:59:59'){
  6208. $a['logdata'][] = $val;
  6209. }
  6210. }
  6211. $xin[] = $a;
  6212. }
  6213. }elseif($today > $firstday){
  6214. for($i=0;$i<$lastnum;$i++){
  6215. $day = date('Y-m-d', strtotime("$firstday +$i days"));
  6216. $a['day'] = $day;
  6217. $a['week'] = $weekarray[date("w",strtotime("$firstday +$i days"))];
  6218. $a['logdata'] = [];
  6219. foreach($visitlog_list as $key=>$val){
  6220. if($val['confirm_date'] >= $day.' 00:00:00' && $val['confirm_date'] <= $day.' 23:59:59'){
  6221. $a['logdata'][] = $val;
  6222. }
  6223. }
  6224. $xin[] = $a;
  6225. }
  6226. }
  6227. unset($visitlog_list);
  6228. $meetids = [];
  6229. $t=['day'=>'求和','week'=>'','data'=>[],'new_cus'=>0,'jv'=>0,'jv_percen'=>0,'jq'=>0,'jq_percen'=>0,'meet_cont'=>0,'meet_percen'=>0,'deposit_cont'=>0,'sign_cont'=>0,'basic_money'=>0,'other_money'=>0,'all_money'=>0,'invalid_no'=>0,'invalid_yes'=>0,'invalid_meet'=>0];
  6230. foreach($xin as $key=>$val){
  6231. //$xin[$key]['clue_cont'] = count($new_cuslist);
  6232. $xin[$key]['nowempid'] = $nowempid;
  6233. $xin[$key]['noworgid'] = $noworgid;
  6234. $jq = $jv = $new_cus = $meet = $deposit = $sign = $basic_money = $invalid_no = $invalid_yes = $invalid_meet = 0;
  6235. $deposids = $invalids = $daystate = $cusids = $validids = [];
  6236. // 外呼系统统计
  6237. $start = $val['day'].' 00:00:00';
  6238. $end = $val['day'].' 23:59:59';
  6239. //线索量
  6240. foreach($new_cuslist as $k=>$v){
  6241. if($v['sign_time'] >= $start && $v['sign_time'] <= $end){
  6242. $new_cus++;
  6243. $cusids[] = $v['id'];
  6244. }
  6245. }
  6246. //加微客户数
  6247. foreach($addwechat_cuslist as $k=>$v){
  6248. if($v['add_wechat_time'] >= $val['day'] && $v['add_wechat_time'] <= $val['day']){
  6249. $jv++;
  6250. }
  6251. }
  6252. //进群客户数
  6253. foreach($into_group_cuslist as $k=>$v){
  6254. if($v['into_owner_group'] >= $val['day'] && $v['into_owner_group'] <= $val['day']){
  6255. $jq++;
  6256. }
  6257. }
  6258. //无效客户数增加
  6259. foreach($invalidcus as $v){
  6260. if($v['cus_addtime'] >= $start && $v['cus_addtime'] <= $end && !in_array($v['customer_id'],$cusids)){
  6261. $new_cus++;
  6262. $cusids[] = $v['customer_id'];
  6263. }
  6264. }
  6265. unset($cusids);
  6266. foreach($val['logdata'] as $ky=>$v){
  6267. if(in_array($v['state'],$state3,true) && !in_array($v['customer_id'],$deposids)){
  6268. $deposit++;
  6269. $deposids[] = $v['customer_id'];
  6270. }
  6271. if(in_array($v['state'],$state4,true)){
  6272. $sign++;
  6273. $basic_money+= $v['money'];
  6274. }
  6275. if(in_array($v['state'],array_merge($state5,$state8,$state9)) && !in_array($v['customer_id'],$meetids) && in_array($v['customer_id'],$yesids)){
  6276. $meet++;
  6277. $meetids[] = $v['customer_id'];
  6278. }
  6279. if(in_array($v['state'],$state6)){
  6280. $invalid_yes++;
  6281. $invalids[] = $v['customer_id'];
  6282. }
  6283. }
  6284. foreach($invalids as $k=>$v){
  6285. if(in_array($v,$meetids)) $invalid_meet++;
  6286. }
  6287. $xin[$key]['meet_cont'] = $meet;
  6288. $xin[$key]['deposit_cont'] = $deposit;
  6289. $xin[$key]['sign_cont'] = $sign;
  6290. $xin[$key]['basic_money'] = $basic_money;
  6291. $xin[$key]['invalid_no'] = $invalid_no;
  6292. $xin[$key]['invalid_yes'] = $invalid_yes;
  6293. $xin[$key]['invalid_meet'] = $invalid_meet;
  6294. $xin[$key]['new_cus'] = $new_cus;
  6295. $xin[$key]['jv'] = $jv;
  6296. $xin[$key]['jv_percen'] = !empty($jv) && !empty($new_cus) ? round($jv/$new_cus*100,2) : 0;
  6297. $xin[$key]['jq'] = $jq;
  6298. $xin[$key]['jq_percen'] = !empty($jq) && !empty($jv) ? round($jq/$jv*100,2) : 0;
  6299. //总数
  6300. $t['meet_cont'] += $meet;
  6301. $t['deposit_cont'] += $deposit;
  6302. $t['sign_cont'] += $sign;
  6303. $t['basic_money'] += $basic_money;
  6304. $t['invalid_no'] += $invalid_no;
  6305. $t['invalid_yes'] += $invalid_yes;
  6306. $t['invalid_meet'] += $invalid_meet;
  6307. $t['new_cus'] += $new_cus;
  6308. $t['jv'] += $jv;
  6309. $t['jq'] += $jq;
  6310. }
  6311. $t['jv_percen'] = !empty($t['jv']) && !empty($t['new_cus']) ? round($t['jv']/$t['new_cus']*100,2) : 0;
  6312. $t['jq_percen'] = !empty($t['jq']) && !empty($t['jv']) ? round($t['jq']/$t['jv']*100,2) : 0;
  6313. $xin = array_reverse($xin);
  6314. array_push($xin,$t);
  6315. return json(['code' => 0, 'data' => $xin, 'count' =>0,'msg'=>'获取成功']);
  6316. }
  6317. //处理查询客户之前的见面记录
  6318. public function selBeforelog($metids,$firstday)
  6319. {
  6320. $statday = '2021-12-01 00:00:00';
  6321. $state1 = CustomerVisitLog::changeState('确认到店','chaos');
  6322. $state2 = CustomerVisitLog::changeState('已到场','chaos');
  6323. $state3 = CustomerVisitLog::changeState('已量房','chaos');
  6324. $q_where[] = ['customer_id','in',$metids];
  6325. $q_where[] = ['state','in',array_merge($state1,$state2,$state3)];
  6326. $q_where[] = ['addtime', 'between', [$statday,$firstday]];
  6327. $qianvslog = CustomerVisitLog::where($q_where)->group('customer_id')->column('customer_id');
  6328. $yesids = array_diff($metids,$qianvslog);
  6329. return $yesids;
  6330. }
  6331. //日报点击弹出详情页面
  6332. public function new_daily_detail()
  6333. {
  6334. $request = request();
  6335. $root_id = $request->empcrm->root_id;
  6336. $empid = $request->empcrm->id;
  6337. $is_manager = $request->empcrm->is_manager;
  6338. $org_employee = [$empid];
  6339. if($is_manager ==1){
  6340. $team_orgs = orgSubIds($request->empcrm->org_id);
  6341. $org_employee = Employee::where([['org_id', 'in', $team_orgs], ['state', '=', '在职'], ['uid', '>', 0],['community_disable','=',0]])->column('id');
  6342. }
  6343. $param = $this->request->only(['date','state','empid'=>'','page'=>1,'limit'=>17,'orgid'=>'']);
  6344. if (!$request->isAjax()) {
  6345. //$this->screen();
  6346. View::assign('date',$param['date']);
  6347. View::assign('state',$param['state']);
  6348. View::assign('empid',$param['empid']);
  6349. View::assign('orgid',$param['orgid']);
  6350. return View::fetch();
  6351. }
  6352. $order = isset($param['order']) ? $param['order'] : 'id desc';
  6353. $page = intval($param['page']);
  6354. $limit = intval($param['limit']);
  6355. if($is_manager ==1 && !empty($param['empid']) && $param['empid'] != 'undefined' && in_array($param['empid'],$org_employee)) $org_employee = [$param['empid']];
  6356. if($is_manager ==1 && !empty($param['orgid']) && $param['orgid'] != 'undefined'){
  6357. $org_employee = Employee::where([['org_id','=',$param['orgid']],['root_id','=',$root_id],['community_disable','=',0]])->column('id');
  6358. }
  6359. if(empty($param['date'])) return json(['code' => 1, 'msg'=>'参数错误']);
  6360. if (!empty($param['date'])){
  6361. $newtime=explode('到', $param['date']);
  6362. }
  6363. $condition[] = ['employee_id', 'in', $org_employee];
  6364. if($param['state'] != 'addnew') $condition[] = ['died', '<>', 2];
  6365. $condition[] = ['state','not in',Customer::changeState('无效','chaos')];
  6366. $vlst = '确认到店';
  6367. if($param['state']=='到访'){
  6368. $vlst = '确认到店';
  6369. }elseif($param['state']=='交定'){
  6370. $vlst = '交定';
  6371. }elseif($param['state']=='签单'){
  6372. $vlst = '签单';
  6373. }elseif($param['state']=='clue' || $param['state']=='addnew'){
  6374. $condition[] = ['sign_time', 'between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']];
  6375. $addnewids = Customer::where($condition)->column('id');
  6376. //置为无效的客户
  6377. $wuxiaoids = CustomerInvalidLog::where([['employee_id', 'in', $org_employee],['root_id','=',$root_id],['cus_addtime','between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']]])->column('customer_id');
  6378. if(!empty($wuxiaoids)) $addnewids = array_merge($addnewids,$wuxiaoids);
  6379. unset($condition);
  6380. //$condition[] = ['id','in',$addnewids];
  6381. $condition = implode(',',$addnewids);
  6382. $page = ($page - 1) * 17;
  6383. $data = $this->cus_recycle($condition,$page,$limit,$order,$root_id);
  6384. return json(['code' => 0, 'data' => $data['data'], 'count' => $data['count']]);
  6385. }elseif($param['state']=='valid'){
  6386. $condition[] = ['sign_time', 'between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']];
  6387. $condition[] = ['state', 'not in', Customer::changeState('待确认','chaos')];
  6388. $validids = Customer::where($condition)->column('id');
  6389. //置为无效的客户
  6390. $wuxiaoids = CustomerInvalidLog::where([['employee_id', 'in', $org_employee],['status','=',1],['root_id','=',$root_id],['cus_addtime','between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']]])->column('customer_id');
  6391. if(!empty($wuxiaoids)) $validids = array_merge($validids,$wuxiaoids);
  6392. unset($condition);
  6393. //$condition[] = ['id','in',$validids];
  6394. $condition = implode(',',$validids);
  6395. $page = ($page - 1) * 17;
  6396. $data = $this->cus_recycle($condition,$page,$limit,$order,$root_id);
  6397. return json(['code' => 0, 'data' => $data['data'], 'count' => $data['count']]);
  6398. }
  6399. $where[] = ['customer_employee_id', 'in', $org_employee];
  6400. if($vlst == '确认到店'){
  6401. $where[] =['state','in',array_merge(CustomerVisitLog::changeState($vlst,'chaos'),CustomerVisitLog::changeState('已到场','chaos'),CustomerVisitLog::changeState('已量房','chaos'))];
  6402. }else{
  6403. $where[] =['state','in',CustomerVisitLog::changeState($vlst,'chaos')];
  6404. }
  6405. if (!empty($param['date'])){
  6406. $where[] = ['confirm_date', 'between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']];
  6407. }
  6408. //$where[] =['customer_id','in',$customer_list];
  6409. $vslogid = CustomerVisitLog::where($where)->group('customer_id')->column('customer_id');
  6410. if($vlst == '确认到店'){
  6411. $vslogid = !empty(array_unique($vslogid)) ? $this->selBeforelog($vslogid,$newtime[0].' 00:00:00') : [];
  6412. }
  6413. if(!in_array($param['state'],['clue','addnew','yixiang','liangfang','daodian','valid'])){
  6414. unset($condition);
  6415. $condition[] = ['id', 'in', $vslogid];
  6416. }
  6417. $data = $this->selCustomer($condition,$page,$limit,$order,$root_id);
  6418. $count = Customer::where($condition)->count();
  6419. return json(['code' => 0, 'data' => $data, 'count' => $count]);
  6420. }
  6421. /**
  6422. * 客户表加回收站查询
  6423. */
  6424. public function cus_recycle($condition,$page,$limit,$order,$root_id)
  6425. {
  6426. $request = request();
  6427. $root_id = $request->empcrm->root_id;
  6428. $empid = $request->empcrm->id;
  6429. $is_manager = $request->empcrm->is_manager;
  6430. $path = Org::where([['pid','=',$request->empcrm->org_id]])->count();
  6431. $sql = "( SELECT id,name,community_name,square,phone,addtime,employee_id,designer_id,source_id,package_id,assigned_personnel,house_delivery_time,state,ext,last_contact_date FROM `fl_customer` WHERE `id` in (".$condition.")) UNION
  6432. ( SELECT customer_id as id,name,community_name,phone,square,addtime,employee_id,designer_id,source_id,package_id,assigned_personnel,house_delivery_time,state,ext,last_contact_date FROM `fl_customer_recycle` WHERE `customer_id` in (".$condition."))
  6433. LIMIT ".$page.",".$limit;
  6434. $data = Db::query($sql);
  6435. $sqlcont = "( SELECT id FROM `fl_customer` WHERE `id` in (".$condition.")) UNION
  6436. ( SELECT customer_id as id FROM `fl_customer_recycle` WHERE `customer_id` in (".$condition."))";
  6437. $count = count(Db::query($sqlcont));
  6438. $state1 = CustomerVisitLog::changeState('已到店','chaos');
  6439. $state2 = CustomerVisitLog::changeState('已交定','chaos');
  6440. $state3 = CustomerVisitLog::changeState('已签单','chaos');
  6441. $state4 = CustomerVisitLog::changeState('已量房','chaos');
  6442. $state5 = CustomerVisitLog::changeState('无效','chaos');
  6443. foreach ($data as &$item) {
  6444. $item['visitLog'] = $item['source_name'] = $item['designer_name'] = $item['employee_name'] = '';
  6445. $item['source'] = !empty($item['source_id']) ? CustomerSource::where([['root_id','=',$root_id],['id','=',$item['source_id']]])->field('id,source')->find() : '';
  6446. $item['designer'] = !empty($item['designer_id']) ? Employee::where([['root_id','=',$root_id],['id','=',$item['designer_id']]])->field('id,name')->find() : '';
  6447. $item['employee'] = !empty($item['employee_id']) ? Employee::where([['root_id','=',$root_id],['id','=',$item['employee_id']]])->field('id,name')->find() : '';
  6448. $item['last_invalid_time'] = $item['first_liangfang'] = $item['jiaoding_time'] = $item['sign'] = $item['fisttime'] = '';
  6449. $visitLog = CustomerVisitLog::where([['customer_id','=',$item['id']],['org_id','in',orgSubIds($root_id)]])->field('id,customer_id,state,addtime,confirm_date,money')->select()->toArray();
  6450. $item['visitLog'] = !empty($visitLog) ? $visitLog : '';
  6451. if(!empty($item['visitLog'])){
  6452. //取最新的一条为客户的跟进时间
  6453. $item['last_contact_date'] = $item['visitLog'][count($item['visitLog'])-1]['addtime'];
  6454. $state = [];
  6455. foreach($item['visitLog'] as $k=>$v){
  6456. $state[$v['state']][] = $v;
  6457. }
  6458. foreach($state as $k=>$v){
  6459. if(in_array($k,$state1)) $item['fisttime'] = date('Y-m-d',strtotime($v[0]['confirm_date']));
  6460. if(in_array($k,$state4)) $item['first_liangfang'] = date('Y-m-d',strtotime($v[0]['addtime']));
  6461. if(in_array($k,$state2)){
  6462. $item['jiaoding_time'] = $v[0]['addtime'];
  6463. $item['jiaoding_money'] = $v[0]['money'];
  6464. }
  6465. if(in_array($k,$state3)){
  6466. $item['qiandan_time'] = $v[0]['addtime'];
  6467. $item['qiandan_money'] = $v[0]['money'];
  6468. $item['sign'] = $v[0];
  6469. }
  6470. if(in_array($k,$state5)) $item['last_invalid_time'] = $v[0]['addtime'];
  6471. }
  6472. }
  6473. $item['square'] = floatval($item['square']);
  6474. //$item['visitLog'] = CustomerVisitLog::where([['customer_employee_id','=',$item['employee_id']],['customer_id','=',$item['id']],['state','in',array_merge(CustomerVisitLog::changeState('待确认','chaos'),CustomerVisitLog::changeState('已到店','chaos'),CustomerVisitLog::changeState('已到场','chaos'),CustomerVisitLog::changeState('已交定','chaos'),CustomerVisitLog::changeState('已签单','chaos'))]])->group('state,customer_id')->field('state,id,customer_id')->order('addtime asc')->select()->toArray();
  6475. $item['phone'] = substr_replace($this->getPhone($item['phone']), '******', 3, 6);
  6476. $item['time_status'] = $item['last_contact_date'] ? $this->uc_time_ago($item['last_contact_date']) :'';
  6477. $item['add_wechat'] = '否';
  6478. $item['sign_time'] = $item['addtime'];
  6479. $item['allstate'] = null;
  6480. $item['package_name'] = !empty($item['package_id']) ? CustomerPackage::where('id',$item['package_id'])->value('name') :'';
  6481. if(!empty($item['ext'])){
  6482. $extdata=json_decode($item['ext'],true);
  6483. foreach($extdata as $key=>$val){
  6484. if(isset($val['keyname']) && $val['keyname']=='wechat' && !empty($val['value'])){
  6485. $add_wechat = CustomerPortraitFieldSelect::where('id',$val['value'])->value('name');
  6486. if($add_wechat == '有'){
  6487. $add_wechat = '是';
  6488. }
  6489. $item['add_wechat'] = $add_wechat;
  6490. }
  6491. if(isset($val['keyname']) && $val['keyname']=='sign_time' && !empty($val['value'])){
  6492. $item['sign_time'] = str_replace('/','-',$val['value']);
  6493. }
  6494. }
  6495. }
  6496. $item['is_followup'] = 0;
  6497. if($is_manager==1 && empty($path)){
  6498. $item['is_followup'] = 1;
  6499. }
  6500. if($empid == $item['employee_id']){
  6501. $item['is_followup'] = 1;
  6502. }
  6503. $now_status = $this->getState($item['state']);
  6504. if($now_status == '已签单' && $request->empcrm['xinjushang'] == 0) $now_status = '已转单';
  6505. if($now_status == '已交定' && $request->empcrm['xinjushang'] == 0) $now_status = '已签单';
  6506. $item['now_status'] = $now_status;
  6507. $item['state'] = '';
  6508. $allstate='';
  6509. if(!empty($item['visitLog'])){
  6510. $stain=[$now_status];
  6511. foreach($item['visitLog'] as $k=>$v){
  6512. if(!in_array($v['state'],['已交定','已签单','已到店','已量房','已到场','未到访','回访'])) continue;
  6513. if($v['state']=='回访') $v['state'] = '待确认';
  6514. if($v['state']=='已签单' && $request->empcrm['xinjushang'] == 0) $v['state'] = '已转单';
  6515. if($v['state']=='已交定' && $request->empcrm['xinjushang'] == 0) $v['state'] = '已签单';
  6516. if(!in_array($v['state'],$stain)){
  6517. $stain[] = $v['state'];
  6518. //$allstate.= $v['state'].',';
  6519. }
  6520. }
  6521. if(count($stain) > 1 && in_array('待确认',$stain)) $stain = array_diff($stain,['待确认']);
  6522. //$item['state'] = trim($allstate,',');
  6523. $item['state'] = implode(',',$stain);
  6524. }
  6525. if($now_status == '待确认') $item['state'] = '待确认';
  6526. // 未跟进时间
  6527. //$latest_visit_log = CustomerVisitLog::where([['customer_id', '=', $item['id']]])->order('addtime desc')->find();
  6528. $latest_visit_log = $item['last_contact_date'];
  6529. if (empty($latest_visit_log)) {
  6530. $no_visit_long = time() - strtotime($item['addtime']);
  6531. } else {
  6532. $no_visit_long = time() - strtotime($latest_visit_log);
  6533. }
  6534. $no_visit_day = ceil($no_visit_long / 24 / 3600);
  6535. $item['no_visit_day'] = $no_visit_day;
  6536. // 预计见面时间
  6537. $subscribe = CustomersSubscribe::where([['customer_id', '=', $item['id']], ['employee_id', '=', $item['employee_id']], ['state', '=', 0]])->order('subscribe_date desc')->find();
  6538. if (!empty($subscribe)) {
  6539. $item['subscribe_date'] = $subscribe['subscribe_date'];
  6540. } else {
  6541. $item['subscribe_date'] = '';
  6542. }
  6543. $assignIdList = !empty($item['assigned_personnel']) ? explode(',',$item['assigned_personnel']) : [];
  6544. if(!empty($item['designer_id']) && !empty($assignIdList)) $assignIdList = array_diff($assignIdList,[$item['designer_id']]);
  6545. $assign_list = Employee::where('id', 'in', $assignIdList)->column('name');
  6546. $item['assign_list'] = !empty($assign_list) ? implode(',',$assign_list) : '';
  6547. }
  6548. return ['data'=>$data,'count'=>$count];
  6549. }
  6550. /**
  6551. * 手机号解密
  6552. */
  6553. public function getPhone($value)
  6554. {
  6555. if (preg_match('/^1[\d]{10}$/', $value)) return $value;
  6556. $aec = new Aec(config('app.aec_key'), config('app.aec_iv'));
  6557. $value = $aec->decrypt($value);
  6558. return $value;
  6559. }
  6560. public function getState($value)
  6561. {
  6562. $states = [
  6563. ['n' => 0, 'chaos' => [0, '待确认', '0'], 'state' => '待确认'],
  6564. ['n' => 1, 'chaos' => [1, '未到访', '1'], 'state' => '未到访'],
  6565. ['n' => 2, 'chaos' => [2, '已到访', '确认到店', '确定到店', '已到店', '2'], 'state' => '已到店'],
  6566. ['n' => 3, 'chaos' => [3, '确定到场', '确认到场', '已到场', '3'], 'state' => '已到场'],
  6567. ['n' => 4, 'chaos' => [4, '已量房', '确定量房', '确认量房', '4'], 'state' => '已量房'],
  6568. ['n' => 5, 'chaos' => [5, '定金', '交定', '已交定', '5'], 'state' => '已交定'],
  6569. ['n' => 6, 'chaos' => [6, '签单', '已签单', '6'], 'state' => '已签单'],
  6570. ['n' => 7, 'chaos' => [7, '无效', '7'], 'state' => '无效'],
  6571. ['n' => 8, 'chaos' => [8, '已卖卡', '8'], 'state' => '已卖卡'],
  6572. ];
  6573. if (is_numeric($value)) $value = intval($value);
  6574. foreach ($states as $s) {
  6575. if ($value === $s['n'] || in_array($value, $s['chaos'], true)) return $s['state'];
  6576. }
  6577. return '';
  6578. }
  6579. //设计师报表
  6580. public function designer_report()
  6581. {
  6582. $request = request();
  6583. $root_id = $request->empcrm->root_id;
  6584. $empid = $request->empcrm->id;
  6585. $is_manager = $request->empcrm->is_manager;
  6586. $team_orgs = orgSubIds($request->empcrm->org_id);
  6587. $param = $this->request->only(['date', 'source_id', 'org_id']);
  6588. if (!$request->isAjax()) {
  6589. $org_data = Org::where([['id', 'in', $team_orgs]])->field('id,name')->select(); //->toArray();
  6590. View::assign('org_data', $org_data);
  6591. $data['company_name'] = Company::where('root_id', $root_id)->value('company_name');
  6592. $data['empname'] = $request->empcrm->name;
  6593. View::assign('data', $data);
  6594. $soudata = CustomerSource::field('id,source as name')->where('root_id', $root_id)->select()->toArray();
  6595. View::assign('soudata', $soudata);
  6596. View::assign('is_manager', $is_manager);
  6597. return View::fetch();
  6598. }
  6599. // 获取部门列表
  6600. $param_sub_org = $team_orgs;
  6601. if (!empty($param['org_id'])) $param_sub_org = [$param['org_id']];
  6602. if (!empty($param['date'])) {
  6603. $newtime = explode('到', $param['date']);
  6604. } else {
  6605. return json(['code' => 1, 'msg' => '日期为空']);
  6606. }
  6607. //层级以下所有客户指派的设计师
  6608. $designer_where = [
  6609. ['org_id', 'in', $param_sub_org],
  6610. ['designer_id', '>', 0]
  6611. ];
  6612. if (!empty($param['source_id'])) $designer_where[] = ['source_id', '=', $param['source_id']];
  6613. $designer_id = Customer::where($designer_where)->group('designer_id')->column('designer_id');
  6614. //查询无效后的设计师
  6615. $wxdesignerids = CustomerInvalidLog::where([['root_id','=',$root_id],['status','=',1],['org_id', 'in', $param_sub_org],['cus_addtime','between', [$newtime[0] . ' 00:00:00', $newtime[1] . ' 23:59:59']],['designer_id','>',0]])->group('designer_id')->column('designer_id');
  6616. if(!empty($wxdesignerids)) $designer_id = array_unique(array_merge($designer_id,$wxdesignerids));
  6617. $designer_list = Employee::where([['id', 'in', $designer_id], ['root_id', '=', $root_id], ['state', '=', '在职'], ['uid', '>', 0]])->field('id,name')->select()->toArray();
  6618. // 客户
  6619. //$designer_ids = !empty($designer_list) ? array_column($designer_list, 'id') : [];
  6620. $customer_id = Customer::where([['org_id', 'in', $param_sub_org], ['designer_id', '>', 0]])->column('id');
  6621. $where = [
  6622. ['sign_time', 'between', [$newtime[0] . ' 00:00:00', $newtime[1] . ' 23:59:59']],
  6623. ['id', 'in', $customer_id]
  6624. ];
  6625. if (!empty($param['source_id'])) $where[] = ['source_id', '=', $param['source_id']];
  6626. $customer_list = Customer::where($where)->field('id,name,state,source_id,employee_id,designer_id,died')->select()->toArray();
  6627. $invalidcus = CustomerInvalidLog::where([
  6628. ['cus_addtime', 'between', [$newtime[0].' 00:00:00',$newtime[1].' 23:59:59']],
  6629. ['customer_id','in',$customer_id],
  6630. ['root_id','=',$root_id]
  6631. ])->column('customer_id,status');
  6632. $t = ['name' => '求和', 'deposit_percen' => 0, 'dai_confirmed' => 0, 'exten_money' => 0, 'exten_show' => 0, 'exten_click' => 0, 'click_percen' => 0, 'clue_conversion' => 0, 'clue_money' => 0, 'valid_money' => 0, 'meet_money' => 0, 'sign_agv_money' => 0, 'ROI' => 0, 'week' => '', 'data' => [], 'clue_cont' => 0, 'valid_cont' => 0, 'valid_percen' => 0, 'meet_cont' => 0, 'meet_percen' => 0, 'deposit_cont' => 0, 'sign_cont' => 0, 'basic_money' => 0, 'other_money' => 0, 'all_money' => 0, 'invalid_no' => 0, 'invalid_yes' => 0, 'invalid_meet' => 0, 'invalid_deposit' => 0, 'invalid_sign' => 0];
  6633. foreach ($designer_list as $key => $val) {
  6634. $dai_confirmed = $exten_money = $exten_show = $exten_click = $clue_cont = $valid = $meet = $deposit = $sig· = $basic_money = $other_money = $invalid_no = $invalid_yes = $invalid_meet = 0;
  6635. $cusids = [];
  6636. $vs_where = [];
  6637. foreach ($customer_list as $k => $v) {
  6638. if (in_array($val['id'], [$v['designer_id']])) {
  6639. $cusids[] = $v['id'];
  6640. //线索数量增加
  6641. $clue_cont++;
  6642. //有效数量增加
  6643. if ($v['died'] != 2 && !in_array($v['state'], array_merge(Customer::changeState('无效', 'chaos'), Customer::changeState('待确认', 'chaos')), true)) {
  6644. $valid++;
  6645. }
  6646. //待确认数量
  6647. if (in_array($v['state'], Customer::changeState('待确认', 'chaos'))) $dai_confirmed++;
  6648. }
  6649. //处理无效的客户还原到员工身上为有效
  6650. foreach($invalidcus as $item => $vv){
  6651. if($vv['customer_id'] == $v['id']){
  6652. $clue_cont++;
  6653. if($vv['status'] == 1) $valid++;
  6654. }
  6655. }
  6656. }
  6657. // 见面量只统计一次(到场、到店、量房、签单、转单)
  6658. $meet_state = array_merge(CustomerVisitLog::changeState('确认到店','chaos'), CustomerVisitLog::changeState('已到场','chaos'), CustomerVisitLog::changeState('已量房','chaos'), CustomerVisitLog::changeState('已交定','chaos'), CustomerVisitLog::changeState('已签单','chaos'));
  6659. if(empty($param['source_id'])) {
  6660. $visilog = CustomerVisitLog::where([
  6661. ['customer_id', 'in', $cusids],
  6662. ['confirm_date', 'between', [$newtime[0] . ' 00:00:00', $newtime[1] . ' 23:59:59']],
  6663. ['state','in', $meet_state]
  6664. ])->column('customer_id');
  6665. } else {
  6666. $visilog = CustomerVisitLog::hasWhere('customer',['source_id'=>$param['source_id']])
  6667. ->where([
  6668. ['CustomerVisitLog.customer_id', 'in', $cusids],
  6669. ['CustomerVisitLog.confirm_date', 'between', [$newtime[0] . ' 00:00:00', $newtime[1] . ' 23:59:59']],
  6670. ['CustomerVisitLog.state','in', $meet_state]
  6671. ])->column('CustomerVisitLog.customer_id');
  6672. }
  6673. $meet = 0;
  6674. if (!empty(array_unique($visilog))) {
  6675. $new = new Empcrm($this->app);
  6676. $meet = $new->selBeforelog(array_unique($visilog), $newtime[0].' 00:00:00');
  6677. $meet = count($meet);
  6678. }
  6679. $vs_where[] = ['customer_id', 'in', $cusids];
  6680. $vs_where[] = ['confirm_date', 'between', [$newtime[0] . ' 00:00:00', $newtime[1] . ' 23:59:59']];
  6681. //$valid = CustomerVisitLog::where($vs_where)->where('state', 'in', $now_status)->group('customer_id')->count();
  6682. $deposit = CustomerVisitLog::where($vs_where)->where('state', 'in', CustomerVisitLog::changeState('已交定', 'chaos'))->group('customer_id')->count();
  6683. $sign = CustomerVisitLog::where($vs_where)->where('state', 'in', CustomerVisitLog::changeState('已签单', 'chaos'))->group('customer_id')->count();
  6684. //$meet = CustomerVisitLog::where($vs_where)->where('state', 'in', CustomerVisitLog::changeState('确认到店', 'chaos'))->group('customer_id')->count();
  6685. //$basic_money = CustomerVisitLog::where($vs_where)->where('state','in',array_merge(CustomerVisitLog::changeState('已交定','chaos'),CustomerVisitLog::changeState('已签单','chaos')))->sum('money');
  6686. $basic_money = CustomerVisitLog::where($vs_where)->where('state', 'in', CustomerVisitLog::changeState('已签单', 'chaos'))->sum('money');
  6687. $wuxiao = CustomerVisitLog::where($vs_where)->where('state', 'in', CustomerVisitLog::changeState('无效', 'chaos'))->group('customer_id')->column('customer_id');
  6688. $invalid_meet = CustomerVisitLog::where('state', 'in', CustomerVisitLog::changeState('确认到店', 'chaos'))->where([['customer_id', 'in', $wuxiao]])->group('customer_id')->count();
  6689. $invalid_deposit = CustomerVisitLog::where('state', 'in', CustomerVisitLog::changeState('已交定', 'chaos'))->where([['customer_id', 'in', $wuxiao]])->group('customer_id')->count();
  6690. $invalid_sign = CustomerVisitLog::where('state', 'in', CustomerVisitLog::changeState('已签单', 'chaos'))->where([['customer_id', 'in', $wuxiao]])->group('customer_id')->count();
  6691. $designer_list[$key]['clue_cont'] = $clue_cont;
  6692. //有效
  6693. $designer_list[$key]['valid_cont'] = $valid;
  6694. //有效率
  6695. $designer_list[$key]['valid_percen'] = $valid && $clue_cont ? round($valid / $clue_cont * 100, 2) : 0;
  6696. //待确认
  6697. $designer_list[$key]['dai_confirmed'] = $dai_confirmed;
  6698. //见面量
  6699. $designer_list[$key]['meet_cont'] = $meet;
  6700. //见面率
  6701. $designer_list[$key]['meet_percen'] = !empty($meet) && !empty($clue_cont) ? round($meet / $clue_cont * 100, 2) : 0;
  6702. //预订合同
  6703. $designer_list[$key]['deposit_cont'] = $deposit;
  6704. //成单率
  6705. $designer_list[$key]['deposit_percen'] = !empty($deposit) && !empty($meet) ? round($deposit / $meet * 100, 2) : 0;
  6706. //施工合同
  6707. $designer_list[$key]['sign_cont'] = $sign;
  6708. //业绩总额
  6709. $designer_list[$key]['basic_money'] = $basic_money;
  6710. $designer_list[$key]['sign_agv_money'] = !empty($sign_cont) && !empty($basic_money) ? floor($basic_money / $sign_cont) : 0;
  6711. $designer_list[$key]['other_money'] = 0;
  6712. $designer_list[$key]['all_money'] = $basic_money;
  6713. //$xin[$key]['invalid_no'] = $invalid_no;
  6714. //$xin[$key]['invalid_yes'] = $invalid_yes;
  6715. $designer_list[$key]['invalid_meet'] = $invalid_meet;
  6716. $designer_list[$key]['invalid_deposit'] = $invalid_deposit;
  6717. $designer_list[$key]['invalid_sign'] = $invalid_sign;
  6718. //总数
  6719. $t['clue_cont'] += $clue_cont;
  6720. $t['valid_cont'] += $valid;
  6721. // $t['valid_percen'] += !empty($valid) && !empty($clue_cont) ? round($valid/$clue_cont*100,2) : 0;
  6722. //$t['valid_percen'] += $designer_list[$key]['valid_percen'];
  6723. $t['dai_confirmed'] += $dai_confirmed;
  6724. $t['meet_cont'] += $meet;
  6725. // $t['meet_percen'] += !empty($meet) && !empty($clue_cont) ? round($meet/$clue_cont*100,2) : 0;
  6726. $t['deposit_cont'] += $deposit;
  6727. // $t['deposit_percen'] += !empty($deposit) && !empty($meet) ? round($deposit/$meet*100,2) : 0;
  6728. $t['sign_cont'] += $sign;
  6729. $t['basic_money'] += $basic_money;
  6730. $t['sign_agv_money'] += !empty($sign_cont) && !empty($basic_money) ? floor($basic_money / $sign_cont) : 0;
  6731. $t['other_money'] += 0;
  6732. $t['all_money'] += $basic_money;
  6733. // $t['invalid_no'] += $invalid_no;
  6734. // $t['invalid_yes'] += $invalid_yes;
  6735. $t['invalid_meet'] += $invalid_meet;
  6736. $t['invalid_deposit'] += $invalid_deposit;
  6737. $t['invalid_sign'] += $invalid_sign;
  6738. }
  6739. $t['valid_percen'] = $t['clue_cont'] == 0 ? 0 : round($t['valid_cont'] / $t['clue_cont'] * 100, 2);
  6740. $t['meet_percen'] = $t['clue_cont'] == 0 ? 0 : round($t['meet_cont'] / $t['clue_cont'] * 100, 2);
  6741. $t['deposit_percen'] = $t['meet_cont'] == 0 ? 0 : round($t['deposit_cont'] / $t['meet_cont'] * 100, 2);
  6742. array_push($designer_list, $t);
  6743. return json(['code' => 0, 'data' => $designer_list, 'count' => 0, 'msg' => '获取成功']);
  6744. }
  6745. }
  6746. ?>