statistic_report.go 233 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133
  1. package controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/rdlucklib/rdluck_tools/paging"
  7. "github.com/shopspring/decimal"
  8. "github.com/tealeg/xlsx"
  9. "hongze/hz_crm_api/models"
  10. "hongze/hz_crm_api/models/company"
  11. "hongze/hz_crm_api/models/fms"
  12. "hongze/hz_crm_api/models/response"
  13. "hongze/hz_crm_api/models/roadshow"
  14. statisticModels "hongze/hz_crm_api/models/statistic_report"
  15. "hongze/hz_crm_api/models/system"
  16. "hongze/hz_crm_api/services"
  17. "hongze/hz_crm_api/services/alarm_msg"
  18. contractService "hongze/hz_crm_api/services/contract"
  19. cygxService "hongze/hz_crm_api/services/cygx"
  20. fmsService "hongze/hz_crm_api/services/fms"
  21. "hongze/hz_crm_api/services/statistic_report"
  22. "hongze/hz_crm_api/utils"
  23. "os"
  24. "path/filepath"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "time"
  29. )
  30. // StatisticReportController 统计报告基类
  31. type StatisticReportController struct {
  32. BaseAuthController
  33. }
  34. // StatisticReportCommonController 统计报告
  35. type StatisticReportCommonController struct {
  36. BaseCommonController
  37. }
  38. // getQueryParams 获取基础查询信息
  39. func getQueryParams(condition string, pars []interface{}, sysUser *system.Admin, tableAlias string) (newCondition string, newPars []interface{}) {
  40. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  41. condition += " AND " + tableAlias + "product_id=?"
  42. pars = append(pars, 1)
  43. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  44. condition += " AND " + tableAlias + "product_id=?"
  45. pars = append(pars, 2)
  46. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  47. //超级管理员账户,不做条件限制
  48. } else {
  49. //如果不是研究员,那么去找对应的 部门、小组、销售
  50. if sysUser.Authority == 0 {
  51. //普通用户
  52. condition += " AND " + tableAlias + "seller_id=?"
  53. pars = append(pars, sysUser.AdminId)
  54. } else if sysUser.Authority == 1 {
  55. //部门主管
  56. condition += " AND " + tableAlias + "department_id=?"
  57. pars = append(pars, sysUser.DepartmentId)
  58. } else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
  59. //权益小组负责人
  60. condition += " AND " + tableAlias + "group_id=?"
  61. pars = append(pars, sysUser.GroupId)
  62. } else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
  63. //ficc销售主管
  64. pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
  65. if err != nil {
  66. fmt.Println(err.Error())
  67. return
  68. }
  69. var ids []*string
  70. if pid != nil && *pid != 0 {
  71. ids, err = company.GetGroupIdsByParentId(*pid)
  72. if err != nil {
  73. fmt.Println(err.Error())
  74. }
  75. } else {
  76. ids, err = company.GetGroupIdsByParentId(sysUser.GroupId)
  77. if err != nil {
  78. fmt.Println(err.Error())
  79. }
  80. }
  81. var idSlice []string
  82. var sid string
  83. for _, id := range ids {
  84. idSlice = append(idSlice, *id)
  85. }
  86. //加入父级groupId
  87. if *pid > 0 {
  88. idSlice = append(idSlice, strconv.Itoa(*pid))
  89. } else {
  90. idSlice = append(idSlice, strconv.Itoa(sysUser.GroupId))
  91. }
  92. sid = strings.Join(idSlice, ",")
  93. condition += " AND " + tableAlias + `group_id IN (` + sid + `) `
  94. fmt.Println("condition:", condition)
  95. //pars = append(pars, sysUser.GroupId)
  96. } else if sysUser.Authority == 4 {
  97. //ficc小组负责人
  98. condition += " AND " + tableAlias + "group_id=?"
  99. pars = append(pars, sysUser.GroupId)
  100. } else {
  101. //不知道什么类型的用户(后面新增的位置类型客户)
  102. condition += " AND " + tableAlias + "seller_id=?"
  103. pars = append(pars, sysUser.AdminId)
  104. }
  105. }
  106. newCondition = condition
  107. newPars = pars
  108. return
  109. }
  110. // Home
  111. // @Title 获取首页工作台数据
  112. // @Description 获取首页工作台数据接口
  113. // @Success 200 {object} response.WorktopResp
  114. // @router /home [get]
  115. func (this *StatisticReportController) Home() {
  116. br := new(models.BaseResponse).Init()
  117. defer func() {
  118. this.Data["json"] = br
  119. this.ServeJSON()
  120. }()
  121. sysUser := this.SysUser
  122. if sysUser == nil {
  123. br.Msg = "请登录"
  124. br.ErrMsg = "请登录,SysUser Is Empty"
  125. br.Ret = 408
  126. return
  127. }
  128. todayStr := utils.GetToday("20060102")
  129. //近6个月客户增量数据
  130. var incrementalCompanyChartList response.IncrementalCompanyChartResp
  131. ch := make(chan response.IncrementalCompanyChartResp, 1)
  132. go getIncrementalCompanyList(sysUser, ch)
  133. //未来6个月即将到期
  134. var willExpireList response.WillExpireChartResp
  135. ch2 := make(chan response.WillExpireChartResp, 1)
  136. go getWillExpireList(sysUser, ch2)
  137. //近6个月收入统计
  138. var incomeList response.IncomeChartResp
  139. ch3 := make(chan response.IncomeChartResp, 1)
  140. go getIncomeList(sysUser, ch3)
  141. var formalCompanyCount, trialCompanyTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  142. today := utils.GetToday(utils.FormatDate)
  143. //正式客户数
  144. {
  145. key := "admin:home:formalCompanyCount:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  146. redisCount, redisErr := utils.Rc.RedisInt(key)
  147. if redisErr != nil {
  148. var condition string
  149. var pars []interface{}
  150. //根据当前角色来获取查询条件
  151. condition, pars = getQueryParams(condition, pars, sysUser, "b.")
  152. condition += ` AND b.status = "正式" `
  153. tmpFormalCompanyCount, err := models.GetCurrCompanyCount(condition, pars)
  154. if err != nil && err.Error() != utils.ErrNoRow() {
  155. br.Msg = "获取正式客户总数失败"
  156. br.ErrMsg = "获取正式客户总数失败,Err:" + err.Error()
  157. return
  158. }
  159. redisCount = tmpFormalCompanyCount
  160. _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  161. }
  162. formalCompanyCount = redisCount
  163. }
  164. //试用客户数
  165. {
  166. key := "admin:home:trialCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  167. redisCount, redisErr := utils.Rc.RedisInt(key)
  168. if redisErr != nil {
  169. var condition string
  170. var pars []interface{}
  171. //根据当前角色来获取查询条件
  172. //condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  173. //condition += " AND a.create_time <= ?"
  174. //pars = append(pars, time.Now())
  175. //
  176. //condition += ` AND a.operation in ("add","receive")`
  177. //tmpTrialCompanyTotal, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
  178. condition, pars = getQueryParams(condition, pars, sysUser, "b.")
  179. condition += ` AND b.status = "试用" `
  180. tmpTrialCompanyTotal, err := models.GetCurrCompanyCount(condition, pars)
  181. if err != nil && err.Error() != utils.ErrNoRow() {
  182. br.Msg = "获取试用客户总数失败"
  183. br.ErrMsg = "获取试用客户总数失败,Err:" + err.Error()
  184. return
  185. }
  186. redisCount = tmpTrialCompanyTotal
  187. _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  188. }
  189. trialCompanyTotal = redisCount
  190. }
  191. //新签客户数
  192. {
  193. key := "admin:home:newCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  194. redisCount, redisErr := utils.Rc.RedisInt(key)
  195. if redisErr != nil {
  196. var condition string
  197. var pars []interface{}
  198. //根据当前角色来获取查询条件
  199. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  200. //condition += ` AND c.status ="正式" `
  201. condition += ` AND a.start_date <= ? AND a.end_date >= ? `
  202. pars = append(pars, today, today)
  203. condition += ` AND a.contract_type = ? `
  204. pars = append(pars, "新签合同")
  205. total, err := models.GetIncrementalNewCompanyCount(condition, pars)
  206. if err != nil && err.Error() != utils.ErrNoRow() {
  207. br.Msg = "获取新签客户失败"
  208. br.ErrMsg = "获取新签客户失败,Err:" + err.Error()
  209. return
  210. }
  211. redisCount = total
  212. _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  213. }
  214. newCompanyTotal = redisCount
  215. }
  216. //续约客户数
  217. {
  218. key := "admin:home:renewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  219. redisCount, redisErr := utils.Rc.RedisInt(key)
  220. if redisErr != nil {
  221. var condition string
  222. var pars []interface{}
  223. //根据当前角色来获取查询条件
  224. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  225. //condition += ` AND c.status="正式" `
  226. condition += ` AND a.start_date <= ? AND a.end_date >= ? `
  227. pars = append(pars, today, today)
  228. condition += ` AND a.contract_type = ? `
  229. pars = append(pars, "续约合同")
  230. total, err := models.GetIncrementalNewCompanyCount(condition, pars)
  231. if err != nil && err.Error() != utils.ErrNoRow() {
  232. br.Msg = "获取续约客户失败"
  233. br.ErrMsg = "获取续约客户失败,Err:" + err.Error()
  234. return
  235. }
  236. redisCount = total
  237. _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  238. }
  239. renewalCompanyTotal = redisCount
  240. }
  241. //未续约客户数
  242. //{
  243. // key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  244. // redisCount, redisErr := utils.Rc.RedisInt(key)
  245. // if redisErr != nil {
  246. // var condition string
  247. // var pars []interface{}
  248. //
  249. // //根据当前角色来获取查询条件
  250. // condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  251. // condition += ` AND c.status not in ("永续","正式") `
  252. // total, err := models.GetIncrementalNewCompanyCount(condition, pars)
  253. // if err != nil && err.Error() != utils.ErrNoRow() {
  254. // br.Msg = "获取未续约客户失败"
  255. // br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
  256. // return
  257. // }
  258. // redisCount = total
  259. // _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  260. // }
  261. // notRenewalCompanyTotal = redisCount
  262. //}
  263. //未续约客户数
  264. {
  265. key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  266. redisCount, redisErr := utils.Rc.RedisInt(key)
  267. if redisErr != nil {
  268. var condition string
  269. var pars []interface{}
  270. //根据当前角色来获取查询条件
  271. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  272. condition += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
  273. pars = append(pars, time.Now().Format(utils.FormatDateTime))
  274. condition += ` AND a.operation = 'try_out' `
  275. total, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
  276. if err != nil && err.Error() != utils.ErrNoRow() {
  277. br.Msg = "获取未续约客户失败"
  278. br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
  279. return
  280. }
  281. redisCount = total
  282. _ = utils.Rc.Put(key, redisCount, time.Minute*30)
  283. }
  284. notRenewalCompanyTotal = redisCount
  285. }
  286. //合同数据
  287. contractChartData := response.ContractChartResp{}
  288. {
  289. key := "admin:home:contractChartData:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  290. redisContractChartData, redisErr := utils.Rc.RedisString(key)
  291. if redisErr != nil {
  292. var condition string
  293. var pars []interface{}
  294. //根据当前角色来获取查询条件
  295. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  296. condition += ` AND a.end_date >= ? `
  297. pars = append(pars, today)
  298. //condition += ` AND c.status = "正式" `
  299. tmpContractCompanyCount, tmpContractTotal, tmpMoney, err := models.GetContractStatListCount(condition, pars)
  300. if err != nil && err.Error() != utils.ErrNoRow() {
  301. if err != nil && err.Error() != utils.ErrNoRow() {
  302. br.Msg = "获取未续约客户失败"
  303. br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
  304. return
  305. }
  306. return
  307. }
  308. //数据赋值
  309. contractChartData.Title = "当前有效合同存量"
  310. contractChartData.FormalCompanyCount = tmpContractCompanyCount
  311. contractChartData.ContractTotal = tmpContractTotal
  312. contractChartData.MoneyTotal = tmpMoney
  313. //入缓存
  314. redisJsonData, err := json.Marshal(contractChartData)
  315. if err == nil {
  316. _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
  317. }
  318. } else {
  319. err := json.Unmarshal([]byte(redisContractChartData), &contractChartData)
  320. if err != nil {
  321. fmt.Println("合同数据,json转换失败:", err)
  322. }
  323. }
  324. }
  325. for v := range ch {
  326. incrementalCompanyChartList = v
  327. close(ch)
  328. }
  329. for v := range ch2 {
  330. willExpireList = v
  331. close(ch2)
  332. }
  333. for v := range ch3 {
  334. incomeList = v
  335. close(ch3)
  336. }
  337. resp := response.WorktopResp{
  338. FormalCompanyCount: formalCompanyCount,
  339. TrialCompanyTotal: trialCompanyTotal,
  340. NewCompanyTotal: newCompanyTotal,
  341. RenewalCompanyTotal: renewalCompanyTotal,
  342. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  343. IncrementalCompanyChartList: incrementalCompanyChartList,
  344. WillExpireChartList: willExpireList,
  345. IncomeChartList: incomeList,
  346. ContractData: contractChartData,
  347. }
  348. br.Ret = 200
  349. br.Success = true
  350. br.Msg = "获取成功"
  351. br.Data = resp
  352. }
  353. // 查询从2021/01开始的,每个月的客户增量数据
  354. func getIncrementalCompanyList(sysUser *system.Admin, ch chan response.IncrementalCompanyChartResp) (incrementalCompanyChart response.IncrementalCompanyChartResp, err error) {
  355. defer func() {
  356. if err != nil {
  357. go alarm_msg.SendAlarmMsg("查询近6个月的客户增量数据异常,Err:"+err.Error(), 3)
  358. //go utils.SendEmail(utils.APPNAME+"查询近6个月的客户增量数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
  359. }
  360. ch <- incrementalCompanyChart
  361. }()
  362. todayStr := utils.GetToday("20060102")
  363. key := "admin:home:incrementalCompanyList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  364. redisJsonData, redisErr := utils.Rc.RedisString(key)
  365. if redisErr != nil {
  366. var condition string
  367. var pars []interface{}
  368. //根据当前角色来获取查询条件
  369. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  370. var dateSlice []string
  371. var newCompanySlice, renewalCompanySlice []int
  372. //var notRenewalCompanySlice []int
  373. yearNum := time.Now().Year() - 2021
  374. monthNum := time.Now().Month() - 1
  375. numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月
  376. for i := numMonth; i >= 0; i-- {
  377. timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  378. dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
  379. //开始日期
  380. startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
  381. startDate = fmt.Sprint(startDate, "-01")
  382. //结束日期
  383. endDateTime := timeNow.AddDate(0, -i+1, 0)
  384. endDate := endDateTime.Format("2006-01")
  385. //因为就算是当月的后续事件还没到,也要计入数据统计,所以不做限制到当天处理
  386. //if endDateTime.After(time.Now()) {
  387. // endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
  388. //} else {
  389. // endDate = fmt.Sprint(endDate, "-01")
  390. //}
  391. endDate = fmt.Sprint(endDate, "-01")
  392. //新签客户数
  393. {
  394. condition1 := condition
  395. pars1 := pars
  396. condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
  397. pars1 = append(pars1, startDate, endDate)
  398. condition1 += ` AND a.contract_type = ? `
  399. pars1 = append(pars1, "新签合同")
  400. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  401. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  402. err = countErr
  403. return
  404. }
  405. newCompanySlice = append(newCompanySlice, total)
  406. }
  407. //续约客户数
  408. {
  409. //2022-02-07 13:26:48注释掉,更改成以下的逻辑,续约客户定义修改:续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
  410. //condition1 := condition
  411. //pars1 := pars
  412. //condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
  413. //pars1 = append(pars1, startDate, endDate)
  414. //condition1 += ` AND a.contract_type = ? `
  415. //pars1 = append(pars1, "续约合同")
  416. //total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  417. //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  418. // err = countErr
  419. // return
  420. //}
  421. //renewalCompanySlice = append(renewalCompanySlice, total)
  422. //2022-02-07 13:26:48;更改成以下的逻辑,续约客户定义修改:续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
  423. condition1 := condition
  424. pars1 := pars
  425. condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
  426. pars1 = append(pars1, startDate, endDate)
  427. condition1 += ` AND a.contract_type = ? `
  428. pars1 = append(pars1, "续约合同")
  429. //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
  430. pars1 = append(pars1, endDate)
  431. total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
  432. if err != nil && err.Error() != utils.ErrNoRow() {
  433. err = countErr
  434. return
  435. }
  436. renewalCompanySlice = append(renewalCompanySlice, total)
  437. }
  438. //未续约客户数
  439. //{
  440. // condition1 := condition
  441. // pars1 := pars
  442. //
  443. // condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
  444. // pars1 = append(pars1, fmt.Sprint(startDate, " 00:00:00"), fmt.Sprint(endDate, " 00:00:00"))
  445. // condition1 += ` AND a.operation = ? `
  446. // pars1 = append(pars1, "try_out")
  447. // total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  448. // if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  449. // err = countErr
  450. // return
  451. // }
  452. // notRenewalCompanySlice = append(notRenewalCompanySlice, total)
  453. //}
  454. }
  455. incrementalCompanyChart.Title = "客户增量图"
  456. incrementalCompanyChart.Date = dateSlice
  457. incrementalCompanyChart.NewCompanyTotal = newCompanySlice
  458. incrementalCompanyChart.RenewalCompanyTotal = renewalCompanySlice
  459. //incrementalCompanyChart.NotRenewalCompanyTotal = notRenewalCompanySlice
  460. redisJsonData, err := json.Marshal(incrementalCompanyChart)
  461. if err == nil {
  462. _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
  463. }
  464. } else {
  465. err = json.Unmarshal([]byte(redisJsonData), &incrementalCompanyChart)
  466. if err != nil {
  467. fmt.Println("近6个月客户增量图,json转换失败")
  468. }
  469. }
  470. return
  471. }
  472. // 获取未来近6个月的即将到期客户
  473. func getWillExpireList(sysUser *system.Admin, ch chan response.WillExpireChartResp) (willExpireChart response.WillExpireChartResp, err error) {
  474. defer func() {
  475. if err != nil {
  476. go alarm_msg.SendAlarmMsg("获取未来近6个月的即将到期客户数据异常,Err:"+err.Error(), 3)
  477. //go utils.SendEmail(utils.APPNAME+"获取未来近6个月的即将到期客户数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
  478. }
  479. ch <- willExpireChart
  480. }()
  481. todayStr := utils.GetToday("20060102")
  482. key := "admin:home:willExpireList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  483. redisJsonData, redisErr := utils.Rc.RedisString(key)
  484. if redisErr != nil {
  485. var condition string
  486. var pars []interface{}
  487. //根据当前角色来获取查询条件
  488. condition, pars = getQueryParams(condition, pars, sysUser, "a.")
  489. var dateSlice []string
  490. var companySlice []int
  491. for i := 0; i < 6; i++ {
  492. //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  493. //startDate := timeNow.Format(utils.FormatDate)
  494. startDate := utils.GetToday(utils.FormatDate)
  495. //endDate := timeNow.AddDate(0, i+1, 0).Format(utils.FormatDate)
  496. endDate := time.Now().AddDate(0, i+1, 0).Format(utils.FormatDate)
  497. dateSlice = append(dateSlice, fmt.Sprint("未来", i+1, "个月"))
  498. condition1 := condition
  499. pars1 := pars
  500. condition1 += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
  501. pars1 = append(pars1, startDate, endDate)
  502. total, countErr := models.GetWillExpireCompanyListCountV2(condition1, pars1)
  503. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  504. err = countErr
  505. return
  506. }
  507. companySlice = append(companySlice, total)
  508. }
  509. willExpireChart.Title = "即将到期客户数"
  510. willExpireChart.Date = dateSlice
  511. willExpireChart.CompanyTotal = companySlice
  512. redisJsonData, err := json.Marshal(willExpireChart)
  513. if err == nil {
  514. _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
  515. }
  516. } else {
  517. err = json.Unmarshal([]byte(redisJsonData), &willExpireChart)
  518. if err != nil {
  519. fmt.Println("未来近6个月的即将到期客户,json转换失败")
  520. }
  521. }
  522. return
  523. }
  524. // 获取近12个月的收入统计数据
  525. func getIncomeList(sysUser *system.Admin, ch chan response.IncomeChartResp) (incomeChart response.IncomeChartResp, err error) {
  526. defer func() {
  527. if err != nil {
  528. go alarm_msg.SendAlarmMsg("获取近12个月的收入统计数据异常,Err:"+err.Error(), 3)
  529. //go utils.SendEmail(utils.APPNAME+"获取近12个月的收入统计数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
  530. }
  531. ch <- incomeChart
  532. }()
  533. todayStr := utils.GetToday("20060102")
  534. key := "admin:home:incomeList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
  535. redisJsonData, redisErr := utils.Rc.RedisString(key)
  536. if redisErr != nil {
  537. var condition string
  538. var pars []interface{}
  539. //根据当前角色来获取查询条件
  540. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  541. var dateSlice []string
  542. var contractTotalSlice []int
  543. var moneySlice []float64
  544. yearNum := time.Now().Year() - 2021
  545. monthNum := time.Now().Month() - 1
  546. numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月
  547. for i := numMonth; i >= 0; i-- {
  548. timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
  549. dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
  550. //开始日期
  551. startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
  552. startDate = fmt.Sprint(startDate, "-01")
  553. //结束日期
  554. endDateTime := timeNow.AddDate(0, -i+1, 0)
  555. endDate := endDateTime.Format("2006-01")
  556. //因为就算是当月的后续事件还没到,也要计入数据统计,所以不做限制到当天处理
  557. //if endDateTime.After(time.Now()) {
  558. // endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
  559. //} else {
  560. // endDate = fmt.Sprint(endDate, "-01")
  561. //}
  562. endDate = fmt.Sprint(endDate, "-01")
  563. condition1 := condition
  564. pars1 := pars
  565. condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
  566. pars1 = append(pars1, startDate, endDate)
  567. total, money, countErr := models.GetIncomeListCount(condition1, pars1)
  568. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  569. err = countErr
  570. return
  571. }
  572. contractTotalSlice = append(contractTotalSlice, total)
  573. moneySlice = append(moneySlice, money)
  574. }
  575. incomeChart.Title = "收入统计图"
  576. incomeChart.Date = dateSlice
  577. incomeChart.ContractTotal = contractTotalSlice
  578. incomeChart.MoneyTotal = moneySlice
  579. redisJsonData, err := json.Marshal(incomeChart)
  580. if err == nil {
  581. _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
  582. }
  583. } else {
  584. err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
  585. if err != nil {
  586. fmt.Println("近6个月的收入统计数据,json转换失败")
  587. }
  588. }
  589. return
  590. }
  591. // WillExpireList
  592. // @Title 获取即将过期的客户列表
  593. // @Description 获取即将过期的客户列表接口
  594. // @Param PageSize query int true "每页数据条数"
  595. // @Param CurrentIndex query int true "当前页页码,从1开始"
  596. // @Param Keyword query string true "客户名称"
  597. // @Param StartDate query string true "开始日期"
  598. // @Param EndDate query string true "结束日期"
  599. // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  600. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  601. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  602. // @Param IsExport query bool false "是否导出excel,默认是false"
  603. // @Success 200 {object} response.WillExpireCompanyListResp
  604. // @router /will_expire_list [get]
  605. func (this *StatisticReportController) WillExpireList() {
  606. br := new(models.BaseResponse).Init()
  607. defer func() {
  608. this.Data["json"] = br
  609. this.ServeJSON()
  610. }()
  611. sysUser := this.SysUser
  612. if sysUser == nil {
  613. br.Msg = "请登录"
  614. br.ErrMsg = "请登录,SysUser Is Empty"
  615. br.Ret = 408
  616. return
  617. }
  618. pageSize, _ := this.GetInt("PageSize")
  619. currentIndex, _ := this.GetInt("CurrentIndex")
  620. //是否导出报表
  621. isExport, _ := this.GetBool("IsExport")
  622. if isExport {
  623. pageSize = 10000
  624. currentIndex = 1
  625. }
  626. startDate := this.GetString("StartDate")
  627. endDate := this.GetString("EndDate")
  628. adminId := this.GetString("AdminId")
  629. regionType := this.GetString("RegionType")
  630. companyType := this.GetString("CompanyType")
  631. keyword := this.GetString("Keyword")
  632. if startDate == "" {
  633. startDate = time.Now().Format(utils.FormatDate)
  634. //br.Msg = "获取失败,开始日期未传"
  635. //br.ErrMsg = "获取失败,开始日期未传"
  636. //return
  637. }
  638. if endDate == "" {
  639. endDate = time.Now().AddDate(100, 0, 0).Format(utils.FormatDate)
  640. //br.Msg = "获取失败,结束日期未传"
  641. //br.ErrMsg = "获取失败,结束日期未传"
  642. //return
  643. }
  644. var startSize int
  645. if pageSize <= 0 {
  646. pageSize = utils.PageSize20
  647. }
  648. if currentIndex <= 0 {
  649. currentIndex = 1
  650. }
  651. startSize = utils.StartIndex(currentIndex, pageSize)
  652. var condition string
  653. var pars []interface{}
  654. //today := utils.GetToday(utils.FormatDate)
  655. condition += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
  656. pars = append(pars, startDate, endDate)
  657. if adminId != "" {
  658. condition += ` AND a.seller_id in (` + adminId + `) `
  659. //pars = append(pars, adminId)
  660. } else {
  661. //根据当前角色来获取查询条件
  662. condition, pars = getQueryParams(condition, pars, sysUser, "a.")
  663. }
  664. if regionType != "" {
  665. condition += ` AND b.region_type = ? `
  666. pars = append(pars, regionType)
  667. }
  668. //关键字搜索
  669. if keyword != "" {
  670. condition += ` and b.company_name like "%` + keyword + `%" `
  671. }
  672. switch companyType {
  673. case "ficc":
  674. condition += ` AND a.product_id = ? `
  675. pars = append(pars, 1)
  676. case "权益":
  677. condition += ` AND a.product_id = ? `
  678. pars = append(pars, 2)
  679. case "":
  680. default:
  681. br.Msg = "获取失败,客户类型异常"
  682. br.ErrMsg = "获取失败,客户类型异常"
  683. return
  684. }
  685. totalCompany, err := models.GetWillExpireCompanyListCountV2(condition, pars)
  686. if err != nil && err.Error() != utils.ErrNoRow() {
  687. br.Msg = "获取失败"
  688. br.ErrMsg = "获取失败,Err:" + err.Error()
  689. return
  690. }
  691. totalContract, err := models.GetWillExpireContactListCountV2(condition, pars)
  692. if err != nil && err.Error() != utils.ErrNoRow() {
  693. br.Msg = "获取失败"
  694. br.ErrMsg = "获取失败,Err:" + err.Error()
  695. return
  696. }
  697. list, err := models.GetWillExpireCompanyListV2(condition, pars, startSize, pageSize)
  698. if err != nil {
  699. br.Msg = "获取失败"
  700. br.ErrMsg = "获取失败,Err:" + err.Error()
  701. return
  702. }
  703. listLen := len(list)
  704. permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)
  705. if listLen > 0 {
  706. companyIdSlice := make([]string, 0)
  707. for _, v := range list {
  708. companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  709. }
  710. companyIds := strings.Join(companyIdSlice, ",")
  711. permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
  712. if permissionErr != nil {
  713. br.Msg = "获取权限失败"
  714. br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
  715. return
  716. }
  717. for _, permission := range permissionList {
  718. key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
  719. permissionListMap[key] = append(permissionListMap[key], permission)
  720. }
  721. }
  722. for i := 0; i < listLen; i++ {
  723. item := list[i]
  724. //剩余可用天数
  725. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  726. endDateTime = endDateTime.AddDate(0, 0, 1)
  727. sub := endDateTime.Sub(time.Now())
  728. if sub < 0 {
  729. sub = 0
  730. }
  731. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  732. list[i].ExpireDay = expireDay
  733. key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
  734. if permissionList, ok := permissionListMap[key]; ok {
  735. for _, permission := range permissionList {
  736. if item.ProductId == permission.ProductId {
  737. list[i].PermissionList = append(list[i].PermissionList, permission)
  738. }
  739. }
  740. //list[i].PermissionList = permissionList
  741. }
  742. }
  743. page := paging.GetPaging(currentIndex, pageSize, totalContract)
  744. resp := response.WillExpireCompanyListResp{
  745. Paging: page,
  746. List: list,
  747. TotalCompany: totalCompany,
  748. }
  749. //导出excel
  750. if isExport {
  751. WillExpireListExport(this, resp, br)
  752. return
  753. }
  754. br.Ret = 200
  755. br.Success = true
  756. br.Msg = "获取成功"
  757. br.Data = resp
  758. }
  759. // WillExpireListExport 即将过期的客户报表导出
  760. func WillExpireListExport(this *StatisticReportController, resp response.WillExpireCompanyListResp, br *models.BaseResponse) {
  761. dir, err := os.Executable()
  762. exPath := filepath.Dir(dir)
  763. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  764. xlsxFile := xlsx.NewFile()
  765. if err != nil {
  766. br.Msg = "生成文件失败"
  767. br.ErrMsg = "生成文件失败"
  768. return
  769. }
  770. style := xlsx.NewStyle()
  771. alignment := xlsx.Alignment{
  772. Horizontal: "center",
  773. Vertical: "center",
  774. WrapText: true,
  775. }
  776. style.Alignment = alignment
  777. style.ApplyAlignment = true
  778. sheel, err := xlsxFile.AddSheet("即将到期客户数据")
  779. if err != nil {
  780. br.Msg = "新增Sheet失败"
  781. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  782. return
  783. }
  784. sheel.SetColWidth(0, 0, 30)
  785. sheel.SetColWidth(1, 1, 15)
  786. sheel.SetColWidth(2, 2, 15)
  787. sheel.SetColWidth(3, 3, 18)
  788. //统计数据
  789. statisticRow := sheel.AddRow()
  790. cell1 := statisticRow.AddCell()
  791. cell1.SetStyle(style)
  792. cell1.SetValue(fmt.Sprint("即将到期客户数:", resp.TotalCompany))
  793. //表头
  794. titleRow := sheel.AddRow()
  795. cellName := titleRow.AddCell()
  796. cellName.SetStyle(style)
  797. cellName.SetValue("客户名称")
  798. cellProName := titleRow.AddCell()
  799. cellProName.SetStyle(style)
  800. cellProName.SetValue("客户类型")
  801. cellSellerName := titleRow.AddCell()
  802. cellSellerName.SetStyle(style)
  803. cellSellerName.SetValue("所属销售")
  804. cellTime := titleRow.AddCell()
  805. cellTime.SetStyle(style)
  806. cellTime.SetValue("服务期限")
  807. cellDay := titleRow.AddCell()
  808. cellDay.SetStyle(style)
  809. cellDay.SetValue("剩余天数")
  810. for _, v := range resp.List {
  811. dataRow := sheel.AddRow()
  812. dataRow.SetHeight(20)
  813. cellDataName := dataRow.AddCell()
  814. cellDataName.SetStyle(style)
  815. cellDataName.SetValue(v.CompanyName)
  816. cellDataProName := dataRow.AddCell()
  817. cellDataProName.SetStyle(style)
  818. cellDataProName.SetValue(v.ProductName)
  819. cellDataSellerName := dataRow.AddCell()
  820. cellDataSellerName.SetStyle(style)
  821. cellDataSellerName.SetValue(v.SellerName)
  822. cellDataTime := dataRow.AddCell()
  823. cellDataTime.SetStyle(style)
  824. cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  825. cellDay := dataRow.AddCell()
  826. cellDay.SetStyle(style)
  827. cellDay.SetValue(v.ExpireDay)
  828. }
  829. err = xlsxFile.Save(downLoadnFilePath)
  830. if err != nil {
  831. br.Msg = "保存文件失败"
  832. br.ErrMsg = "保存文件失败"
  833. return
  834. }
  835. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  836. downloadFileName := "即将到期客户数据_" + randStr + ".xlsx"
  837. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  838. defer func() {
  839. os.Remove(downLoadnFilePath)
  840. }()
  841. br.Ret = 200
  842. br.Success = true
  843. br.Msg = "导出成功"
  844. }
  845. func (this *StatisticReportController) WillExpireListOld() {
  846. br := new(models.BaseResponse).Init()
  847. defer func() {
  848. this.Data["json"] = br
  849. this.ServeJSON()
  850. }()
  851. sysUser := this.SysUser
  852. if sysUser == nil {
  853. br.Msg = "请登录"
  854. br.ErrMsg = "请登录,SysUser Is Empty"
  855. br.Ret = 408
  856. return
  857. }
  858. pageSize, _ := this.GetInt("PageSize")
  859. currentIndex, _ := this.GetInt("CurrentIndex")
  860. startDate := this.GetString("StartDate")
  861. endDate := this.GetString("EndDate")
  862. adminId := this.GetString("AdminId")
  863. regionType := this.GetString("RegionType")
  864. companyType := this.GetString("CompanyType")
  865. if startDate == "" {
  866. br.Msg = "获取失败,开始日期未传"
  867. br.ErrMsg = "获取失败,开始日期未传"
  868. return
  869. }
  870. if endDate == "" {
  871. br.Msg = "获取失败,结束日期未传"
  872. br.ErrMsg = "获取失败,结束日期未传"
  873. return
  874. }
  875. var startSize int
  876. if pageSize <= 0 {
  877. pageSize = utils.PageSize20
  878. }
  879. if currentIndex <= 0 {
  880. currentIndex = 1
  881. }
  882. startSize = utils.StartIndex(currentIndex, pageSize)
  883. var condition string
  884. var pars []interface{}
  885. //today := utils.GetToday(utils.FormatDate)
  886. condition += ` AND a.end_date >= ? AND a.end_date <= ? `
  887. pars = append(pars, startDate, endDate)
  888. if adminId != "" {
  889. condition += ` AND c.seller_id in (` + adminId + `) `
  890. //pars = append(pars, adminId)
  891. } else {
  892. //根据当前角色来获取查询条件
  893. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  894. }
  895. if regionType != "" {
  896. condition += ` AND b.region_type = ? `
  897. pars = append(pars, regionType)
  898. }
  899. switch companyType {
  900. case "ficc":
  901. condition += ` AND a.product_id = ? `
  902. pars = append(pars, 1)
  903. case "权益":
  904. condition += ` AND a.product_id = ? `
  905. pars = append(pars, 2)
  906. case "":
  907. default:
  908. br.Msg = "获取失败,客户类型异常"
  909. br.ErrMsg = "获取失败,客户类型异常"
  910. return
  911. }
  912. totalCompany, err := models.GetWillExpireCompanyListCount(condition, pars)
  913. if err != nil && err.Error() != utils.ErrNoRow() {
  914. br.Msg = "获取失败"
  915. br.ErrMsg = "获取失败,Err:" + err.Error()
  916. return
  917. }
  918. totalContract, err := models.GetWillExpireContactListCount(condition, pars)
  919. if err != nil && err.Error() != utils.ErrNoRow() {
  920. br.Msg = "获取失败"
  921. br.ErrMsg = "获取失败,Err:" + err.Error()
  922. return
  923. }
  924. list, err := models.GetWillExpireCompanyList(condition, pars, startSize, pageSize)
  925. if err != nil {
  926. br.Msg = "获取失败"
  927. br.ErrMsg = "获取失败,Err:" + err.Error()
  928. return
  929. }
  930. listLen := len(list)
  931. permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)
  932. if listLen > 0 {
  933. companyIdSlice := make([]string, 0)
  934. for _, v := range list {
  935. companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  936. }
  937. companyIds := strings.Join(companyIdSlice, ",")
  938. permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
  939. if permissionErr != nil {
  940. br.Msg = "获取权限失败"
  941. br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
  942. return
  943. }
  944. for _, permission := range permissionList {
  945. key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
  946. permissionListMap[key] = append(permissionListMap[key], permission)
  947. }
  948. }
  949. for i := 0; i < listLen; i++ {
  950. item := list[i]
  951. //剩余可用天数
  952. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  953. endDateTime = endDateTime.AddDate(0, 0, 1)
  954. sub := endDateTime.Sub(time.Now())
  955. if sub < 0 {
  956. sub = 0
  957. }
  958. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  959. list[i].ExpireDay = expireDay
  960. key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
  961. if permissionList, ok := permissionListMap[key]; ok {
  962. for _, permission := range permissionList {
  963. if item.ProductId == permission.ProductId {
  964. list[i].PermissionList = append(list[i].PermissionList, permission)
  965. }
  966. }
  967. //list[i].PermissionList = permissionList
  968. }
  969. }
  970. page := paging.GetPaging(currentIndex, pageSize, totalContract)
  971. resp := response.WillExpireCompanyListResp{
  972. Paging: page,
  973. List: list,
  974. TotalCompany: totalCompany,
  975. }
  976. br.Ret = 200
  977. br.Success = true
  978. br.Msg = "获取成功"
  979. br.Data = resp
  980. }
  981. // ContractList
  982. // @Title 获取合同数据报表
  983. // @Description 获取合同数据报表接口
  984. // @Param PageSize query int true "每页数据条数"
  985. // @Param CurrentIndex query int true "当前页页码,从1开始"
  986. // @Param Keyword query string true "客户名称"
  987. // @Param EndDate query string true "结束日期"
  988. // @Param CompanyType query string false "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  989. // @Param AdminId query string false "销售id,多个用英文逗号隔开,空字符串为全部"
  990. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  991. // @Param DataType query string false "报表类型,枚举值:`普通数据`,`类型数据`;传空字符串或者不传为:普通数据"
  992. // @Param SourceType query string false "合同类型,枚举值:`系统合同`,`上传附件`;传空字符串或者不传为全部合同"
  993. // @Param IsExport query bool false "是否导出excel,默认是false"
  994. // @Success 200 {object} models.ContractStatListResp
  995. // @router /contract_list [get]
  996. func (this *StatisticReportController) ContractList() {
  997. br := new(models.BaseResponse).Init()
  998. defer func() {
  999. this.Data["json"] = br
  1000. this.ServeJSON()
  1001. }()
  1002. sysUser := this.SysUser
  1003. if sysUser == nil {
  1004. br.Msg = "请登录"
  1005. br.ErrMsg = "请登录,SysUser Is Empty"
  1006. br.Ret = 408
  1007. return
  1008. }
  1009. pageSize, _ := this.GetInt("PageSize")
  1010. currentIndex, _ := this.GetInt("CurrentIndex")
  1011. //是否导出报表
  1012. isExport, _ := this.GetBool("IsExport")
  1013. if isExport {
  1014. pageSize = 10000
  1015. currentIndex = 1
  1016. }
  1017. endDate := this.GetString("EndDate")
  1018. adminId := this.GetString("AdminId")
  1019. regionType := this.GetString("RegionType")
  1020. companyType := this.GetString("CompanyType")
  1021. keyword := this.GetString("Keyword")
  1022. dataType := this.GetString("DataType") //数据报表类型
  1023. sourceType := this.GetString("SourceType") //合同来源
  1024. if endDate == "" {
  1025. br.Msg = "获取失败,结束日期未传"
  1026. br.ErrMsg = "获取失败,结束日期未传"
  1027. return
  1028. }
  1029. var startSize int
  1030. if pageSize <= 0 {
  1031. pageSize = utils.PageSize20
  1032. }
  1033. if currentIndex <= 0 {
  1034. currentIndex = 1
  1035. }
  1036. startSize = utils.StartIndex(currentIndex, pageSize)
  1037. var condition string
  1038. var pars []interface{}
  1039. //上传附件
  1040. var sourceFileCondition string
  1041. var sourceFilePars []interface{}
  1042. //系统合同
  1043. var sourceSystemCondition string
  1044. var sourceSystemPars []interface{}
  1045. condition += ` AND a.start_date <= ? AND a.end_date >= ? `
  1046. pars = append(pars, endDate, endDate)
  1047. sourceFileCondition += ` AND a.create_time <= ? `
  1048. sourceFilePars = append(sourceFilePars, endDate)
  1049. sourceSystemCondition += ` AND a.check_back_file_time <= "` + endDate + ` 23:59:59"`
  1050. //sourceSystemPars = append(sourceSystemPars, endDate)
  1051. //condition += ` AND c.status = "正式" `
  1052. if adminId != "" {
  1053. condition += ` AND c.seller_id in (` + adminId + `) `
  1054. sourceFileCondition += ` AND c.seller_id in (` + adminId + `) `
  1055. sourceSystemCondition += ` AND a.seller_id in (` + adminId + `) `
  1056. //pars = append(pars, adminId)
  1057. } else {
  1058. //根据当前角色来获取查询条件
  1059. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  1060. sourceFileCondition, sourceFilePars = getQueryParams(sourceFileCondition, sourceFilePars, sysUser, "c.")
  1061. //合同
  1062. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  1063. sourceSystemCondition += ` AND a.product_id=? `
  1064. sourceSystemPars = append(sourceSystemPars, 1)
  1065. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  1066. sourceSystemCondition += ` AND a.product_id=? `
  1067. sourceSystemPars = append(sourceSystemPars, 2)
  1068. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
  1069. //超级管理员账户,不做条件限制
  1070. } else {
  1071. //如果不是研究员,那么去找对应的 部门、小组、销售
  1072. if sysUser.Authority == 0 {
  1073. //普通用户
  1074. sourceSystemCondition += ` AND a.seller_id=? `
  1075. sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
  1076. } else if sysUser.Authority == 1 {
  1077. //部门主管
  1078. sourceSystemCondition += ` AND b.department_id=? `
  1079. sourceSystemPars = append(sourceSystemPars, sysUser.DepartmentId)
  1080. } else if sysUser.Authority == 2 {
  1081. //小组负责人
  1082. sourceSystemCondition += ` AND b.group_id=? `
  1083. sourceSystemPars = append(sourceSystemPars, sysUser.GroupId)
  1084. } else {
  1085. //不知道什么类型的用户(后面新增的位置类型客户)
  1086. sourceSystemCondition += ` AND a.seller_id=? `
  1087. sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
  1088. }
  1089. }
  1090. }
  1091. if regionType != "" {
  1092. condition += ` AND b.region_type = ? `
  1093. pars = append(pars, regionType)
  1094. }
  1095. //关键字搜索
  1096. if keyword != "" {
  1097. condition += ` and b.company_name like "%` + keyword + `%" `
  1098. }
  1099. switch companyType {
  1100. case "ficc":
  1101. condition += ` AND a.product_id = ? `
  1102. pars = append(pars, 1)
  1103. case "权益":
  1104. condition += ` AND a.product_id = ? `
  1105. pars = append(pars, 2)
  1106. case "":
  1107. default:
  1108. br.Msg = "获取失败,客户类型异常"
  1109. br.ErrMsg = "获取失败,客户类型异常"
  1110. return
  1111. }
  1112. dataTotal := 0 //页面数据总数
  1113. total, totalContract, money, err := models.GetContractStatListCount(condition, pars)
  1114. if err != nil && err.Error() != utils.ErrNoRow() {
  1115. br.Msg = "获取失败"
  1116. br.ErrMsg = "获取失败,Err:" + err.Error()
  1117. return
  1118. }
  1119. //上传附件
  1120. totalFileContract, err := models.GetContractStatListCountBySource("上传附件", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)
  1121. if err != nil && err.Error() != utils.ErrNoRow() {
  1122. br.Msg = "获取失败"
  1123. br.ErrMsg = "获取失败,Err:" + err.Error()
  1124. return
  1125. }
  1126. //系统合同
  1127. totalSystemContract, err := models.GetContractStatListCountBySource("系统合同", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)
  1128. if err != nil && err.Error() != utils.ErrNoRow() {
  1129. br.Msg = "获取失败"
  1130. br.ErrMsg = "获取失败,Err:" + err.Error()
  1131. return
  1132. }
  1133. list := make([]*models.ContractStatList, 0)
  1134. if dataType == "类型数据" {
  1135. if sourceType != "" {
  1136. condition += ` AND a.source=? `
  1137. pars = append(pars, sourceType)
  1138. }
  1139. //列表数据
  1140. tmpList, err := models.GetContractStatListBySource(sourceType, sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars, startSize, pageSize)
  1141. if err != nil {
  1142. br.Msg = "获取失败"
  1143. br.ErrMsg = "获取失败,Err:" + err.Error()
  1144. return
  1145. }
  1146. for _, v := range tmpList {
  1147. if v.ProductId == 1 {
  1148. v.ProductName = "ficc"
  1149. } else {
  1150. v.ProductName = "权益"
  1151. }
  1152. }
  1153. list = tmpList
  1154. } else {
  1155. //列表数据
  1156. tmpList, err := models.GetContractStatList(condition, pars, startSize, pageSize)
  1157. if err != nil {
  1158. br.Msg = "获取失败"
  1159. br.ErrMsg = "获取失败,Err:" + err.Error()
  1160. return
  1161. }
  1162. list = tmpList
  1163. }
  1164. //listLen := len(list)
  1165. //for i := 0; i < listLen; i++ {
  1166. // item := list[i]
  1167. //}
  1168. if dataType == "类型数据" {
  1169. switch sourceType {
  1170. case "上传附件":
  1171. dataTotal = totalFileContract
  1172. case "系统合同":
  1173. dataTotal = totalSystemContract
  1174. default:
  1175. dataTotal = totalFileContract + totalSystemContract
  1176. }
  1177. } else {
  1178. dataTotal = total
  1179. }
  1180. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  1181. resp := response.ContractStatListResp{
  1182. Paging: page,
  1183. List: list,
  1184. TotalMoney: money,
  1185. TotalCompany: total,
  1186. TotalFileContract: totalFileContract,
  1187. TotalSystemContract: totalSystemContract,
  1188. TotalContract: totalContract,
  1189. }
  1190. //导出excel
  1191. if isExport {
  1192. ContractListExport(this, resp, br)
  1193. return
  1194. }
  1195. br.Ret = 200
  1196. br.Success = true
  1197. br.Msg = "获取成功"
  1198. br.Data = resp
  1199. }
  1200. // ContractListExport 合同数据报表导出
  1201. func ContractListExport(this *StatisticReportController, resp response.ContractStatListResp, br *models.BaseResponse) {
  1202. dataType := this.GetString("DataType") //数据报表类型
  1203. dir, err := os.Executable()
  1204. exPath := filepath.Dir(dir)
  1205. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  1206. xlsxFile := xlsx.NewFile()
  1207. if err != nil {
  1208. br.Msg = "生成文件失败"
  1209. br.ErrMsg = "生成文件失败"
  1210. return
  1211. }
  1212. style := xlsx.NewStyle()
  1213. alignment := xlsx.Alignment{
  1214. Horizontal: "center",
  1215. Vertical: "center",
  1216. WrapText: true,
  1217. }
  1218. style.Alignment = alignment
  1219. style.ApplyAlignment = true
  1220. sheel, err := xlsxFile.AddSheet("合同数据报表")
  1221. if err != nil {
  1222. br.Msg = "新增Sheet失败"
  1223. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  1224. return
  1225. }
  1226. sheel.SetColWidth(0, 0, 30)
  1227. sheel.SetColWidth(1, 1, 15)
  1228. sheel.SetColWidth(2, 2, 15)
  1229. sheel.SetColWidth(3, 5, 18)
  1230. //统计数据
  1231. statisticRow := sheel.AddRow()
  1232. cell1 := statisticRow.AddCell()
  1233. cell1.SetStyle(style)
  1234. cell1.SetValue(fmt.Sprint("有效合同数:", resp.TotalContract))
  1235. cell2 := statisticRow.AddCell()
  1236. cell2.SetStyle(style)
  1237. cell2.SetValue(fmt.Sprint("有效合同总金额:", resp.TotalMoney))
  1238. cell3 := statisticRow.AddCell()
  1239. cell3.SetStyle(style)
  1240. cell3.SetValue(fmt.Sprint("正式客户数:", resp.TotalCompany))
  1241. cell4 := statisticRow.AddCell()
  1242. cell4.SetStyle(style)
  1243. cell4.SetValue(fmt.Sprint("总上传附件合同数:", resp.TotalFileContract))
  1244. cell5 := statisticRow.AddCell()
  1245. cell5.SetStyle(style)
  1246. cell5.SetValue(fmt.Sprint("总系统生成合同数:", resp.TotalSystemContract))
  1247. //表头
  1248. titleRow := sheel.AddRow()
  1249. cellName := titleRow.AddCell()
  1250. cellName.SetStyle(style)
  1251. cellName.SetValue("客户名称")
  1252. cellProName := titleRow.AddCell()
  1253. cellProName.SetStyle(style)
  1254. cellProName.SetValue("客户类型")
  1255. cellSellerName := titleRow.AddCell()
  1256. cellSellerName.SetStyle(style)
  1257. cellSellerName.SetValue("所属销售")
  1258. if dataType == "类型数据" {
  1259. cellContractNum := titleRow.AddCell()
  1260. cellContractNum.SetStyle(style)
  1261. cellContractNum.SetValue("生成方式")
  1262. cellContractPrice := titleRow.AddCell()
  1263. cellContractPrice.SetStyle(style)
  1264. cellContractPrice.SetValue("合同提交时间")
  1265. } else {
  1266. cellContractNum := titleRow.AddCell()
  1267. cellContractNum.SetStyle(style)
  1268. cellContractNum.SetValue("有效合同数")
  1269. cellContractPrice := titleRow.AddCell()
  1270. cellContractPrice.SetStyle(style)
  1271. cellContractPrice.SetValue("有效合同总金额")
  1272. }
  1273. for _, v := range resp.List {
  1274. dataRow := sheel.AddRow()
  1275. dataRow.SetHeight(20)
  1276. cellDataName := dataRow.AddCell()
  1277. cellDataName.SetStyle(style)
  1278. cellDataName.SetValue(v.CompanyName)
  1279. cellDataProName := dataRow.AddCell()
  1280. cellDataProName.SetStyle(style)
  1281. cellDataProName.SetValue(v.ProductName)
  1282. cellDataSellerName := dataRow.AddCell()
  1283. cellDataSellerName.SetStyle(style)
  1284. cellDataSellerName.SetValue(v.SellerName)
  1285. if dataType == "类型数据" {
  1286. cellDataTime := dataRow.AddCell()
  1287. cellDataTime.SetStyle(style)
  1288. cellDataTime.SetValue(v.Source)
  1289. cellDay := dataRow.AddCell()
  1290. cellDay.SetStyle(style)
  1291. cellDay.SetValue(v.CreateTime)
  1292. } else {
  1293. cellDataTime := dataRow.AddCell()
  1294. cellDataTime.SetStyle(style)
  1295. cellDataTime.SetValue(v.Count)
  1296. cellDay := dataRow.AddCell()
  1297. cellDay.SetStyle(style)
  1298. cellDay.SetValue(v.SumMoney)
  1299. }
  1300. }
  1301. err = xlsxFile.Save(downLoadnFilePath)
  1302. if err != nil {
  1303. br.Msg = "保存文件失败"
  1304. br.ErrMsg = "保存文件失败"
  1305. return
  1306. }
  1307. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1308. downloadFileName := "合同数据报表_" + randStr + ".xlsx"
  1309. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  1310. defer func() {
  1311. os.Remove(downLoadnFilePath)
  1312. }()
  1313. br.Ret = 200
  1314. br.Success = true
  1315. br.Msg = "导出成功"
  1316. }
  1317. // CompanyContractList
  1318. // @Title 获取企业客户的合同数据报表
  1319. // @Description 获取企业客户的合同数据报表接口
  1320. // @Param PageSize query int true "每页数据条数"
  1321. // @Param CurrentIndex query int true "当前页页码,从1开始"
  1322. // @Param EndDate query string true "结束日期"
  1323. // @Param CompanyId query int true "企业客户id"
  1324. // @Success 200 {object} response.CompanyContractStatListResp
  1325. // @router /company_contract_list [get]
  1326. func (this *StatisticReportController) CompanyContractList() {
  1327. br := new(models.BaseResponse).Init()
  1328. defer func() {
  1329. this.Data["json"] = br
  1330. this.ServeJSON()
  1331. }()
  1332. endDate := this.GetString("EndDate")
  1333. companyId := this.GetString("CompanyId")
  1334. //companyType := this.GetString("CompanyType")
  1335. if endDate == "" {
  1336. br.Msg = "获取失败,结束日期未传"
  1337. br.ErrMsg = "获取失败,结束日期未传"
  1338. return
  1339. }
  1340. sysUser := this.SysUser
  1341. var condition string
  1342. var pars []interface{}
  1343. condition += ` AND a.start_date <= ? AND a.end_date >= ? `
  1344. pars = append(pars, endDate, endDate)
  1345. if companyId == "" {
  1346. br.Msg = "获取失败,客户id未传"
  1347. br.ErrMsg = "获取失败,客户id未传"
  1348. return
  1349. }
  1350. condition += ` AND a.company_id = ? `
  1351. pars = append(pars, companyId)
  1352. //根据当前角色来获取查询条件
  1353. if strings.Contains(sysUser.RoleTypeCode, "ficc") {
  1354. condition += ` AND a.product_id = ? `
  1355. pars = append(pars, 1)
  1356. } else if strings.Contains(sysUser.RoleTypeCode, "rai") {
  1357. condition += ` AND a.product_id = ? `
  1358. pars = append(pars, 2)
  1359. }
  1360. //switch companyType {
  1361. //case "ficc":
  1362. // condition += ` AND a.product_id = ? `
  1363. // pars = append(pars, 1)
  1364. //case "权益":
  1365. // condition += ` AND a.product_id = ? `
  1366. // pars = append(pars, 2)
  1367. //case "":
  1368. //default:
  1369. // br.Msg = "获取失败,客户类型异常"
  1370. // br.ErrMsg = "获取失败,客户类型异常"
  1371. // return
  1372. //}
  1373. list, err := models.GetCompanyContractStatList(condition, pars)
  1374. if err != nil {
  1375. br.Msg = "获取失败"
  1376. br.ErrMsg = "获取失败,Err:" + err.Error()
  1377. return
  1378. }
  1379. listLen := len(list)
  1380. permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
  1381. if listLen > 0 {
  1382. companyContractIdSlice := make([]string, 0)
  1383. for _, v := range list {
  1384. companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
  1385. }
  1386. companyContractIds := strings.Join(companyContractIdSlice, ",")
  1387. permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
  1388. if permissionErr != nil {
  1389. br.Msg = "获取权限失败"
  1390. br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
  1391. return
  1392. }
  1393. // CRM8.8-权益权限主客观合并
  1394. permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)
  1395. //列表数据处理
  1396. for i := 0; i < listLen; i++ {
  1397. item := list[i]
  1398. //权限拼接
  1399. companyContractPermissionList := make([]models.CompanyContractPermission, 0)
  1400. companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
  1401. for _, permission := range permissionList {
  1402. if permission.IsUpgrade == 1 {
  1403. permission.ChartPermissionName += "(升级)"
  1404. }
  1405. if permission.CompanyContractId == item.CompanyContractId {
  1406. companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
  1407. }
  1408. permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
  1409. }
  1410. for classifyName, permissionList := range companyContractPermissionMap {
  1411. companyContractPermission := models.CompanyContractPermission{
  1412. ClassifyName: classifyName,
  1413. PermissionList: permissionList,
  1414. }
  1415. companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
  1416. }
  1417. list[i].PermissionList = companyContractPermissionList
  1418. }
  1419. }
  1420. resp := response.CompanyContractStatListResp{
  1421. List: list,
  1422. }
  1423. br.Ret = 200
  1424. br.Success = true
  1425. br.Msg = "获取成功"
  1426. br.Data = resp
  1427. }
  1428. // ContractDetailList
  1429. // @Title 获取合同详情
  1430. // @Description 获取企业客户的合同数据报表接口
  1431. // @Param CompanyContractId query int true "客户合同id,进行过客户申请的"
  1432. // @Param ContractId query int true "系统合同id"
  1433. // @Success 200 {object} response.CompanyContractStatListResp
  1434. // @router /contract_detail_list [get]
  1435. func (this *StatisticReportController) ContractDetailList() {
  1436. br := new(models.BaseResponse).Init()
  1437. defer func() {
  1438. this.Data["json"] = br
  1439. this.ServeJSON()
  1440. }()
  1441. list := make([]*models.CompanyContractStatList, 0)
  1442. item := models.CompanyContractStatList{}
  1443. companyContractId, _ := this.GetInt("CompanyContractId")
  1444. contractId, _ := this.GetInt("ContractId")
  1445. companyContractPermissionList := make([]models.CompanyContractPermission, 0)
  1446. if companyContractId > 0 {
  1447. contractInfo, err := company.GetCompanyContractDetailByCompanyContractId(companyContractId)
  1448. if err != nil {
  1449. br.Msg = "获取合同失败"
  1450. br.ErrMsg = "获取合同失败,Err:" + err.Error()
  1451. return
  1452. }
  1453. permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
  1454. permissionList, err := company.GetCompanyContractPermissionListByContractId(contractInfo.CompanyContractId)
  1455. if err != nil {
  1456. br.Msg = "获取权限失败"
  1457. br.ErrMsg = "获取权限失败,Err:" + err.Error()
  1458. return
  1459. }
  1460. companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
  1461. for _, permission := range permissionList {
  1462. //权限拼接
  1463. if permission.IsUpgrade == 1 {
  1464. permission.PermissionName += "(升级)"
  1465. }
  1466. companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
  1467. permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
  1468. }
  1469. for classifyName, permissionList := range companyContractPermissionMap {
  1470. companyContractPermission := models.CompanyContractPermission{
  1471. ClassifyName: classifyName,
  1472. PermissionList: permissionList,
  1473. }
  1474. companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
  1475. }
  1476. item = models.CompanyContractStatList{
  1477. CompanyContractId: contractInfo.CompanyContractId,
  1478. ContractType: contractInfo.ContractType,
  1479. ProductId: contractInfo.ProductId,
  1480. ProductName: contractInfo.ProductName,
  1481. CompanyId: contractInfo.CompanyId,
  1482. ContractCode: contractInfo.ContractCode,
  1483. StartDate: contractInfo.StartDate,
  1484. EndDate: contractInfo.EndDate,
  1485. Money: contractInfo.Money,
  1486. PayMethod: contractInfo.PayMethod,
  1487. PayChannel: contractInfo.PayChannel,
  1488. PermissionList: companyContractPermissionList,
  1489. }
  1490. list = append(list, &item)
  1491. } else if contractId > 0 {
  1492. contractInfo, err := contractService.GetContractDetail(contractId)
  1493. if err != nil {
  1494. br.Msg = "获取权限失败"
  1495. br.ErrMsg = "获取权限失败,Err:" + err.Error()
  1496. return
  1497. }
  1498. productName := "ficc"
  1499. if contractInfo.ProductId == 2 {
  1500. productName = `权益`
  1501. }
  1502. //合同中包含的产品权限
  1503. permissionLookList, _ := contractService.GetPermissionByContractService(contractInfo.ProductId, contractInfo.Service)
  1504. //权限处理
  1505. for _, v := range permissionLookList {
  1506. permissionList := make([]*company.CompanyContractPermissionName, 0)
  1507. checkIdMap := make(map[int]int)
  1508. for _, checkId := range v.CheckList {
  1509. checkIdMap[checkId] = checkId
  1510. }
  1511. for _, permission := range v.Items {
  1512. if _, ok := checkIdMap[permission.ChartPermissionId]; ok {
  1513. tmpCompanyContractPermissionName := &company.CompanyContractPermissionName{
  1514. ChartPermissionId: permission.ChartPermissionId,
  1515. ChartPermissionName: permission.PermissionName,
  1516. ClassifyName: permission.ClassifyName,
  1517. StartDate: permission.StartDate,
  1518. EndDate: permission.EndDate,
  1519. //CreateTime :permission.ChartPermissionId,
  1520. //ModifyTime :permission.ChartPermissionId,
  1521. }
  1522. permissionList = append(permissionList, tmpCompanyContractPermissionName)
  1523. }
  1524. }
  1525. if len(permissionList) > 0 {
  1526. companyContractPermission := models.CompanyContractPermission{
  1527. ClassifyName: v.ClassifyName,
  1528. PermissionList: permissionList,
  1529. }
  1530. companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
  1531. }
  1532. }
  1533. item = models.CompanyContractStatList{
  1534. //CompanyContractId :contractInfo.CompanyContractId,
  1535. ContractType: contractInfo.ContractType,
  1536. ProductId: contractInfo.ProductId,
  1537. ProductName: productName,
  1538. ContractCode: contractInfo.ContractCode,
  1539. StartDate: contractInfo.StartDate.Format(utils.FormatDate),
  1540. EndDate: contractInfo.EndDate.Format(utils.FormatDate),
  1541. Money: contractInfo.Price,
  1542. PayMethod: contractInfo.PayRemark,
  1543. PayChannel: contractInfo.PayChannel,
  1544. PermissionList: companyContractPermissionList,
  1545. }
  1546. list = append(list, &item)
  1547. }
  1548. resp := response.CompanyContractStatListResp{
  1549. List: list,
  1550. }
  1551. br.Ret = 200
  1552. br.Success = true
  1553. br.Msg = "获取成功"
  1554. br.Data = resp
  1555. }
  1556. // IncomeList
  1557. // @Title 获取收入统计列表
  1558. // @Description 获取收入统计列表接口
  1559. // @Param PageSize query int true "每页数据条数"
  1560. // @Param CurrentIndex query int true "当前页页码,从1开始"
  1561. // @Param Keyword query string true "客户名称"
  1562. // @Param StartDate query string true "开始月份"
  1563. // @Param EndDate query string true "结束月份"
  1564. // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  1565. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  1566. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  1567. // @Param IsExport query bool false "是否导出excel,默认是false"
  1568. // @Success 200 {object} response.IncomeListResp
  1569. // @router /income_list [get]
  1570. func (this *StatisticReportController) IncomeList() {
  1571. br := new(models.BaseResponse).Init()
  1572. defer func() {
  1573. this.Data["json"] = br
  1574. this.ServeJSON()
  1575. }()
  1576. sysUser := this.SysUser
  1577. if sysUser == nil {
  1578. br.Msg = "请登录"
  1579. br.ErrMsg = "请登录,SysUser Is Empty"
  1580. br.Ret = 408
  1581. return
  1582. }
  1583. pageSize, _ := this.GetInt("PageSize")
  1584. currentIndex, _ := this.GetInt("CurrentIndex")
  1585. startDate := this.GetString("StartDate")
  1586. endDate := this.GetString("EndDate")
  1587. adminId := this.GetString("AdminId")
  1588. regionType := this.GetString("RegionType")
  1589. companyType := this.GetString("CompanyType")
  1590. keyword := this.GetString("Keyword")
  1591. //if startDate == "" || endDate == "" {
  1592. // br.Msg = "获取失败,开始日期或结束日期未传"
  1593. // br.ErrMsg = "获取失败,开始日期或结束日期未传"
  1594. // return
  1595. //}
  1596. if startDate == "" {
  1597. startDate = "2015-01"
  1598. }
  1599. if endDate == "" {
  1600. endDate = time.Now().AddDate(100, 0, 0).Format("2006-01")
  1601. }
  1602. var startSize int
  1603. if pageSize <= 0 {
  1604. pageSize = utils.PageSize20
  1605. }
  1606. if currentIndex <= 0 {
  1607. currentIndex = 1
  1608. }
  1609. startSize = utils.StartIndex(currentIndex, pageSize)
  1610. //是否导出报表
  1611. isExport, _ := this.GetBool("IsExport")
  1612. if isExport {
  1613. pageSize = 10000
  1614. currentIndex = 1
  1615. }
  1616. var condition string
  1617. var pars []interface{}
  1618. //开始时间
  1619. startDayTimes, startDayErr := time.Parse("2006-01", startDate)
  1620. if startDayErr != nil {
  1621. br.Msg = "获取失败,开始日期格式异常"
  1622. br.ErrMsg = "获取失败,开始日期格式异常" + startDayErr.Error()
  1623. return
  1624. }
  1625. startDay := startDayTimes.Format(utils.FormatDate)
  1626. //结束时间
  1627. endDayTimes, endDayErr := time.Parse("2006-01", endDate)
  1628. if endDayErr != nil {
  1629. br.Msg = "获取失败,结束日期格式异常"
  1630. br.ErrMsg = "获取失败,结束日期格式异常" + endDayErr.Error()
  1631. return
  1632. }
  1633. //本月最后一天
  1634. endDayTimes = endDayTimes.AddDate(0, 1, -1)
  1635. endDay := endDayTimes.Format(utils.FormatDate)
  1636. //条件
  1637. condition += ` AND a.start_date >= ? AND a.start_date <= ?`
  1638. pars = append(pars, startDay, endDay)
  1639. if adminId != "" {
  1640. condition += ` AND c.seller_id in (` + adminId + `) `
  1641. //pars = append(pars, adminId)
  1642. } else {
  1643. //根据当前角色来获取查询条件
  1644. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  1645. }
  1646. if regionType != "" {
  1647. condition += ` AND b.region_type = ? `
  1648. pars = append(pars, regionType)
  1649. }
  1650. //关键字搜索
  1651. if keyword != "" {
  1652. condition += ` and b.company_name like "%` + keyword + `%" `
  1653. }
  1654. switch companyType {
  1655. case "ficc":
  1656. condition += ` AND a.product_id = ? `
  1657. pars = append(pars, 1)
  1658. case "权益":
  1659. condition += ` AND a.product_id = ? `
  1660. pars = append(pars, 2)
  1661. case "":
  1662. default:
  1663. br.Msg = "获取失败,客户类型异常"
  1664. br.ErrMsg = "获取失败,客户类型异常"
  1665. return
  1666. }
  1667. total, money, err := models.GetIncomeListCount(condition, pars)
  1668. if err != nil && err.Error() != utils.ErrNoRow() {
  1669. br.Msg = "获取失败"
  1670. br.ErrMsg = "获取失败,Err:" + err.Error()
  1671. return
  1672. }
  1673. list, err := models.GetIncomeList(condition, pars, startSize, pageSize)
  1674. if err != nil {
  1675. br.Msg = "获取失败"
  1676. br.ErrMsg = "获取失败,Err:" + err.Error()
  1677. return
  1678. }
  1679. listLen := len(list)
  1680. if listLen > 0 {
  1681. permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
  1682. companyContractIdSlice := make([]string, 0)
  1683. for _, v := range list {
  1684. companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
  1685. }
  1686. companyContractIds := strings.Join(companyContractIdSlice, ",")
  1687. //49, 50,28
  1688. permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
  1689. if permissionErr != nil {
  1690. br.Msg = "获取权限失败"
  1691. br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
  1692. return
  1693. }
  1694. // CRM8.8-权益主客观权限合并
  1695. permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)
  1696. for i := 0; i < listLen; i++ {
  1697. item := list[i]
  1698. //剩余可用天数
  1699. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  1700. endDateTime = endDateTime.AddDate(0, 0, 1)
  1701. sub := endDateTime.Sub(time.Now())
  1702. if sub < 0 {
  1703. sub = 0
  1704. }
  1705. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  1706. list[i].ExpireDay = expireDay
  1707. //权限拼接
  1708. companyContractPermissionList := make([]models.CompanyContractPermission, 0)
  1709. companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
  1710. for _, permission := range permissionList {
  1711. if permission.CompanyContractId == item.CompanyContractId {
  1712. if permission.IsUpgrade == 1 {
  1713. permission.ChartPermissionName += "(升级)"
  1714. }
  1715. companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
  1716. }
  1717. permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
  1718. }
  1719. for classifyName, permissionList := range companyContractPermissionMap {
  1720. companyContractPermission := models.CompanyContractPermission{
  1721. ClassifyName: classifyName,
  1722. PermissionList: permissionList,
  1723. }
  1724. companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
  1725. }
  1726. list[i].PermissionList = companyContractPermissionList
  1727. }
  1728. }
  1729. page := paging.GetPaging(currentIndex, pageSize, total)
  1730. resp := response.IncomeListResp{
  1731. Paging: page,
  1732. List: list,
  1733. Total: total,
  1734. Money: money,
  1735. }
  1736. //导出excel
  1737. if isExport {
  1738. IncomeListExport(this, resp, br)
  1739. return
  1740. }
  1741. br.Ret = 200
  1742. br.Success = true
  1743. br.Msg = "获取成功"
  1744. br.Data = resp
  1745. }
  1746. // IncomeListExport 收入统计报表导出
  1747. func IncomeListExport(this *StatisticReportController, resp response.IncomeListResp, br *models.BaseResponse) {
  1748. dir, err := os.Executable()
  1749. exPath := filepath.Dir(dir)
  1750. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  1751. xlsxFile := xlsx.NewFile()
  1752. if err != nil {
  1753. br.Msg = "生成文件失败"
  1754. br.ErrMsg = "生成文件失败"
  1755. return
  1756. }
  1757. style := xlsx.NewStyle()
  1758. alignment := xlsx.Alignment{
  1759. Horizontal: "center",
  1760. Vertical: "center",
  1761. WrapText: true,
  1762. }
  1763. style.Alignment = alignment
  1764. style.ApplyAlignment = true
  1765. sheel, err := xlsxFile.AddSheet("收入统计报表")
  1766. if err != nil {
  1767. br.Msg = "新增Sheet失败"
  1768. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  1769. return
  1770. }
  1771. sheel.SetColWidth(0, 0, 30)
  1772. sheel.SetColWidth(1, 1, 15)
  1773. sheel.SetColWidth(2, 2, 15)
  1774. sheel.SetColWidth(3, 3, 18)
  1775. //统计数据
  1776. statisticRow := sheel.AddRow()
  1777. cell1 := statisticRow.AddCell()
  1778. cell1.SetStyle(style)
  1779. cell1.SetValue(fmt.Sprint("签约合同数:", resp.Total))
  1780. cell2 := statisticRow.AddCell()
  1781. cell2.SetStyle(style)
  1782. cell2.SetValue(fmt.Sprint("签约合同总金额:", resp.Money))
  1783. //表头
  1784. titleRow := sheel.AddRow()
  1785. cellContractNo := titleRow.AddCell()
  1786. cellContractNo.SetStyle(style)
  1787. cellContractNo.SetValue("合同编号")
  1788. cellName := titleRow.AddCell()
  1789. cellName.SetStyle(style)
  1790. cellName.SetValue("客户名称")
  1791. cellProName := titleRow.AddCell()
  1792. cellProName.SetStyle(style)
  1793. cellProName.SetValue("客户类型")
  1794. cellSellerName := titleRow.AddCell()
  1795. cellSellerName.SetStyle(style)
  1796. cellSellerName.SetValue("所属销售")
  1797. cellContractPrice := titleRow.AddCell()
  1798. cellContractPrice.SetStyle(style)
  1799. cellContractPrice.SetValue("合同金额")
  1800. cellContractPayMethod := titleRow.AddCell()
  1801. cellContractPayMethod.SetStyle(style)
  1802. cellContractPayMethod.SetValue("付款方式")
  1803. cellContractPayChannel := titleRow.AddCell()
  1804. cellContractPayChannel.SetStyle(style)
  1805. cellContractPayChannel.SetValue("付款渠道")
  1806. cellContractDate := titleRow.AddCell()
  1807. cellContractDate.SetStyle(style)
  1808. cellContractDate.SetValue("服务期限")
  1809. for _, v := range resp.List {
  1810. dataRow := sheel.AddRow()
  1811. dataRow.SetHeight(20)
  1812. cellDataContractNo := dataRow.AddCell()
  1813. cellDataContractNo.SetStyle(style)
  1814. cellDataContractNo.SetValue(v.ContractCode)
  1815. cellDataName := dataRow.AddCell()
  1816. cellDataName.SetStyle(style)
  1817. cellDataName.SetValue(v.CompanyName)
  1818. cellDataProName := dataRow.AddCell()
  1819. cellDataProName.SetStyle(style)
  1820. cellDataProName.SetValue(v.ProductName)
  1821. cellDataSellerName := dataRow.AddCell()
  1822. cellDataSellerName.SetStyle(style)
  1823. cellDataSellerName.SetValue(v.SellerName)
  1824. cellDataPrice := dataRow.AddCell()
  1825. cellDataPrice.SetStyle(style)
  1826. cellDataPrice.SetValue(v.Money)
  1827. cellDataPayMethod := dataRow.AddCell()
  1828. cellDataPayMethod.SetStyle(style)
  1829. cellDataPayMethod.SetValue(v.PayMethod)
  1830. cellDataPayChannel := dataRow.AddCell()
  1831. cellDataPayChannel.SetStyle(style)
  1832. cellDataPayChannel.SetValue(v.PayChannel)
  1833. cellDay := dataRow.AddCell()
  1834. cellDay.SetStyle(style)
  1835. cellDay.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  1836. }
  1837. err = xlsxFile.Save(downLoadnFilePath)
  1838. if err != nil {
  1839. br.Msg = "保存文件失败"
  1840. br.ErrMsg = "保存文件失败"
  1841. return
  1842. }
  1843. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  1844. downloadFileName := "收入统计报表_" + randStr + ".xlsx"
  1845. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  1846. defer func() {
  1847. os.Remove(downLoadnFilePath)
  1848. }()
  1849. br.Ret = 200
  1850. br.Success = true
  1851. br.Msg = "导出成功"
  1852. }
  1853. // StackCompanyList
  1854. // @Title 获取存量客户数据列表
  1855. // @Description 获取存量客户数据列表接口
  1856. // @Param PageSize query int true "每页数据条数"
  1857. // @Param CurrentIndex query int true "当前页页码,从1开始"
  1858. // @Param Keyword query string true "客户名称"
  1859. // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  1860. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  1861. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  1862. // @Param Date query string false "日期"
  1863. // @Param DataType query string false "报表类型,枚举值:`新签客户`,`续约客户`,`未续约客户`"
  1864. // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
  1865. // @Param IsExport query bool false "是否导出excel,默认是false"
  1866. // @Param IsConfirm query int false "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
  1867. // @Param CompanyAscribeId query int false "归因ID"
  1868. // @Success 200 {object} response.StackCompanyListResp
  1869. // @router /stack_company_list [get]
  1870. func (this *StatisticReportController) StackCompanyList() {
  1871. br := new(models.BaseResponse).Init()
  1872. defer func() {
  1873. this.Data["json"] = br
  1874. this.ServeJSON()
  1875. }()
  1876. sysUser := this.SysUser
  1877. if sysUser == nil {
  1878. br.Msg = "请登录"
  1879. br.ErrMsg = "请登录,SysUser Is Empty"
  1880. br.Ret = 408
  1881. return
  1882. }
  1883. pageSize, _ := this.GetInt("PageSize")
  1884. currentIndex, _ := this.GetInt("CurrentIndex")
  1885. //是否导出报表
  1886. isExport, _ := this.GetBool("IsExport")
  1887. if isExport {
  1888. pageSize = 10000
  1889. currentIndex = 1
  1890. }
  1891. adminId := this.GetString("AdminId")
  1892. regionType := this.GetString("RegionType")
  1893. companyType := this.GetString("CompanyType")
  1894. dataType := this.GetString("DataType")
  1895. tryOutType := this.GetString("TryOutType")
  1896. keyword := this.GetString("Keyword")
  1897. date := this.GetString("Date")
  1898. isConfirm, _ := this.GetInt("IsConfirm", -1) // CRM 13.9
  1899. companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
  1900. if date == "" {
  1901. br.Msg = "获取失败,请选择日期"
  1902. br.ErrMsg = "获取失败,请选择日期"
  1903. return
  1904. }
  1905. //获取筛选时间的时间戳
  1906. formatTime, err := time.Parse(utils.FormatDate, date)
  1907. if err != nil {
  1908. br.Msg = "获取失败,日期格式异常"
  1909. br.ErrMsg = "获取失败,日期格式异常"
  1910. return
  1911. }
  1912. dateTime := formatTime.Unix()
  1913. //获取今天零点的时间戳
  1914. todayStr := time.Now().Format(utils.FormatDate)
  1915. todayTime, _ := time.Parse(utils.FormatDate, todayStr)
  1916. todayTimeNumber := todayTime.Unix()
  1917. var resp response.StackCompanyListResp
  1918. //历史统计数据
  1919. if dateTime < todayTimeNumber {
  1920. tmpResp, err := getHistoryStackCompanyList(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, date, keyword)
  1921. if err != nil {
  1922. br.Msg = "获取失败"
  1923. br.ErrMsg = "获取失败,Err:" + err.Error()
  1924. return
  1925. }
  1926. resp = tmpResp
  1927. } else {
  1928. //获取实时统计数据(今天数据)
  1929. tmpResp, err := getTodayStackCompanyListV2(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
  1930. if err != nil {
  1931. br.Msg = "获取失败"
  1932. br.ErrMsg = "获取失败,Err:" + err.Error()
  1933. return
  1934. }
  1935. resp = tmpResp
  1936. }
  1937. //导出excel
  1938. if isExport {
  1939. StackCompanyListExport(this, dataType, resp, br)
  1940. return
  1941. }
  1942. br.Ret = 200
  1943. br.Success = true
  1944. br.Msg = "获取成功"
  1945. br.Data = resp
  1946. }
  1947. // StackCompanyListExport 获取存量客户数据报表导出
  1948. func StackCompanyListExport(this *StatisticReportController, dataType string, resp response.StackCompanyListResp, br *models.BaseResponse) {
  1949. dir, err := os.Executable()
  1950. exPath := filepath.Dir(dir)
  1951. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  1952. xlsxFile := xlsx.NewFile()
  1953. if err != nil {
  1954. br.Msg = "生成文件失败"
  1955. br.ErrMsg = "生成文件失败"
  1956. return
  1957. }
  1958. style := xlsx.NewStyle()
  1959. alignment := xlsx.Alignment{
  1960. Horizontal: "center",
  1961. Vertical: "center",
  1962. WrapText: true,
  1963. }
  1964. style.Alignment = alignment
  1965. style.ApplyAlignment = true
  1966. sheel, err := xlsxFile.AddSheet("存量客户数据")
  1967. if err != nil {
  1968. br.Msg = "新增Sheet失败"
  1969. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  1970. return
  1971. }
  1972. sheel.SetColWidth(0, 0, 30)
  1973. sheel.SetColWidth(1, 1, 15)
  1974. sheel.SetColWidth(2, 2, 15)
  1975. sheel.SetColWidth(3, 3, 18)
  1976. //统计数据
  1977. statisticRow := sheel.AddRow()
  1978. cell1 := statisticRow.AddCell()
  1979. cell1.SetStyle(style)
  1980. cell1.SetValue(fmt.Sprint("新签客户数:", resp.NewCompanyTotal))
  1981. cell2 := statisticRow.AddCell()
  1982. cell2.SetStyle(style)
  1983. cell2.SetValue(fmt.Sprint("续约客户数:", resp.RenewalCompanyTotal))
  1984. cell3 := statisticRow.AddCell()
  1985. cell3.SetStyle(style)
  1986. cell3.SetValue(fmt.Sprint("未续约客户数:", resp.NotRenewalCompanyTotal))
  1987. //表头
  1988. titleRow := sheel.AddRow()
  1989. cellName := titleRow.AddCell()
  1990. cellName.SetStyle(style)
  1991. cellName.SetValue("客户名称")
  1992. cellProName := titleRow.AddCell()
  1993. cellProName.SetStyle(style)
  1994. cellProName.SetValue("客户类型")
  1995. cellSellerName := titleRow.AddCell()
  1996. cellSellerName.SetStyle(style)
  1997. cellSellerName.SetValue("所属销售")
  1998. switch dataType {
  1999. case "未续约客户":
  2000. cellTime := titleRow.AddCell()
  2001. cellTime.SetStyle(style)
  2002. cellTime.SetValue("最近合同到期时间")
  2003. cellRemark := titleRow.AddCell()
  2004. cellRemark.SetStyle(style)
  2005. cellRemark.SetValue("未续约说明")
  2006. cellDay := titleRow.AddCell()
  2007. cellDay.SetStyle(style)
  2008. cellDay.SetValue("超出过期天数")
  2009. cellAscribeContent := titleRow.AddCell()
  2010. cellAscribeContent.SetStyle(style)
  2011. cellAscribeContent.SetValue("不续约归因")
  2012. cellContent := titleRow.AddCell()
  2013. cellContent.SetStyle(style)
  2014. cellContent.SetValue("详细原因")
  2015. default:
  2016. cellTime := titleRow.AddCell()
  2017. cellTime.SetStyle(style)
  2018. cellTime.SetValue("服务期限")
  2019. cellDay := titleRow.AddCell()
  2020. cellDay.SetStyle(style)
  2021. cellDay.SetValue("剩余天数")
  2022. }
  2023. for _, v := range resp.List {
  2024. dataRow := sheel.AddRow()
  2025. dataRow.SetHeight(20)
  2026. cellDataName := dataRow.AddCell()
  2027. cellDataName.SetStyle(style)
  2028. cellDataName.SetValue(v.CompanyName)
  2029. cellDataProName := dataRow.AddCell()
  2030. cellDataProName.SetStyle(style)
  2031. cellDataProName.SetValue(v.ProductName)
  2032. cellDataSellerName := dataRow.AddCell()
  2033. cellDataSellerName.SetStyle(style)
  2034. cellDataSellerName.SetValue(v.SellerName)
  2035. cellDataTime := dataRow.AddCell()
  2036. cellDataTime.SetStyle(style)
  2037. switch dataType {
  2038. case "新签客户":
  2039. cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  2040. case "续约客户":
  2041. cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  2042. case "未续约客户":
  2043. cellDataTime.SetValue(v.EndDate)
  2044. //未续约说明
  2045. cellDataRemark := dataRow.AddCell()
  2046. cellDataRemark.SetStyle(style)
  2047. cellDataRemark.SetValue(v.RenewalReason)
  2048. }
  2049. cellDay := dataRow.AddCell()
  2050. cellDay.SetStyle(style)
  2051. cellDay.SetValue(v.ExpireDay)
  2052. switch dataType {
  2053. case "未续约客户":
  2054. cellAscribeContent := dataRow.AddCell()
  2055. cellAscribeContent.SetStyle(style)
  2056. cellAscribeContent.SetValue(v.AscribeContent)
  2057. cellContent := dataRow.AddCell()
  2058. cellContent.SetStyle(style)
  2059. cellContent.SetValue(v.Content)
  2060. }
  2061. }
  2062. err = xlsxFile.Save(downLoadnFilePath)
  2063. if err != nil {
  2064. br.Msg = "保存文件失败"
  2065. br.ErrMsg = "保存文件失败"
  2066. return
  2067. }
  2068. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2069. downloadFileName := "存量客户数据_" + randStr + ".xlsx"
  2070. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  2071. defer func() {
  2072. os.Remove(downLoadnFilePath)
  2073. }()
  2074. br.Ret = 200
  2075. br.Success = true
  2076. br.Msg = "导出成功"
  2077. }
  2078. // StackCompanyListExportRai 获取存量客户数据报表导出
  2079. func StackCompanyListExportRai(this *StatisticReportController, dataType string, resp response.StackCompanyListResp, br *models.BaseResponse) {
  2080. dir, err := os.Executable()
  2081. exPath := filepath.Dir(dir)
  2082. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  2083. xlsxFile := xlsx.NewFile()
  2084. if err != nil {
  2085. br.Msg = "生成文件失败"
  2086. br.ErrMsg = "生成文件失败"
  2087. return
  2088. }
  2089. style := xlsx.NewStyle()
  2090. alignment := xlsx.Alignment{
  2091. Horizontal: "center",
  2092. Vertical: "center",
  2093. WrapText: true,
  2094. }
  2095. style.Alignment = alignment
  2096. style.ApplyAlignment = true
  2097. sheel, err := xlsxFile.AddSheet("存量客户数据")
  2098. if err != nil {
  2099. br.Msg = "新增Sheet失败"
  2100. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  2101. return
  2102. }
  2103. sheel.SetColWidth(0, 0, 30)
  2104. sheel.SetColWidth(1, 1, 15)
  2105. sheel.SetColWidth(2, 2, 15)
  2106. sheel.SetColWidth(3, 3, 18)
  2107. //统计数据
  2108. statisticRow := sheel.AddRow()
  2109. cell1 := statisticRow.AddCell()
  2110. cell1.SetStyle(style)
  2111. cell1.SetValue(fmt.Sprint("新签客户数:", resp.NewCompanyTotal))
  2112. cell2 := statisticRow.AddCell()
  2113. cell2.SetStyle(style)
  2114. cell2.SetValue(fmt.Sprint("续约客户数:", resp.RenewalCompanyTotal))
  2115. cell3 := statisticRow.AddCell()
  2116. cell3.SetStyle(style)
  2117. cell3.SetValue(fmt.Sprint("未续约客户数:", resp.NotRenewalCompanyTotal))
  2118. //表头
  2119. titleRow := sheel.AddRow()
  2120. cellName := titleRow.AddCell()
  2121. cellName.SetStyle(style)
  2122. cellName.SetValue("客户名称")
  2123. cellProName := titleRow.AddCell()
  2124. cellProName.SetStyle(style)
  2125. cellProName.SetValue("客户类型")
  2126. cellSellerName := titleRow.AddCell()
  2127. cellSellerName.SetStyle(style)
  2128. cellSellerName.SetValue("所属销售")
  2129. switch dataType {
  2130. case "未续约客户":
  2131. cellTime := titleRow.AddCell()
  2132. cellTime.SetStyle(style)
  2133. cellTime.SetValue("最近合同到期时间")
  2134. cellRemark := titleRow.AddCell()
  2135. cellRemark.SetStyle(style)
  2136. cellRemark.SetValue("未续约说明")
  2137. cellDay := titleRow.AddCell()
  2138. cellDay.SetStyle(style)
  2139. cellDay.SetValue("超出过期天数")
  2140. cellAscribeContent := titleRow.AddCell()
  2141. cellAscribeContent.SetStyle(style)
  2142. cellAscribeContent.SetValue("不续约归因")
  2143. cellContent := titleRow.AddCell()
  2144. cellContent.SetStyle(style)
  2145. cellContent.SetValue("详细原因")
  2146. default:
  2147. cellTime := titleRow.AddCell()
  2148. cellTime.SetStyle(style)
  2149. cellTime.SetValue("服务期限")
  2150. cellDay := titleRow.AddCell()
  2151. cellDay.SetStyle(style)
  2152. cellDay.SetValue("剩余天数")
  2153. }
  2154. for _, v := range resp.List {
  2155. dataRow := sheel.AddRow()
  2156. dataRow.SetHeight(20)
  2157. cellDataName := dataRow.AddCell()
  2158. cellDataName.SetStyle(style)
  2159. cellDataName.SetValue(v.CompanyName)
  2160. cellDataProName := dataRow.AddCell()
  2161. cellDataProName.SetStyle(style)
  2162. cellDataProName.SetValue(v.ProductName)
  2163. cellDataSellerName := dataRow.AddCell()
  2164. cellDataSellerName.SetStyle(style)
  2165. cellDataSellerName.SetValue(v.SellerName)
  2166. cellDataTime := dataRow.AddCell()
  2167. cellDataTime.SetStyle(style)
  2168. switch dataType {
  2169. case "新签客户":
  2170. cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  2171. case "续约客户":
  2172. cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
  2173. case "未续约客户":
  2174. cellDataTime.SetValue(v.EndDate)
  2175. //未续约说明
  2176. cellDataRemark := dataRow.AddCell()
  2177. cellDataRemark.SetStyle(style)
  2178. cellDataRemark.SetValue(v.RenewalReason)
  2179. }
  2180. cellDay := dataRow.AddCell()
  2181. cellDay.SetStyle(style)
  2182. cellDay.SetValue(v.ExpireDay)
  2183. switch dataType {
  2184. case "未续约客户":
  2185. cellAscribeContent := dataRow.AddCell()
  2186. cellAscribeContent.SetStyle(style)
  2187. cellAscribeContent.SetValue(v.AscribeContent)
  2188. cellContent := dataRow.AddCell()
  2189. cellContent.SetStyle(style)
  2190. cellContent.SetValue(v.Content)
  2191. }
  2192. }
  2193. err = xlsxFile.Save(downLoadnFilePath)
  2194. if err != nil {
  2195. br.Msg = "保存文件失败"
  2196. br.ErrMsg = "保存文件失败"
  2197. return
  2198. }
  2199. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  2200. downloadFileName := "存量客户数据_" + randStr + ".xlsx"
  2201. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  2202. defer func() {
  2203. os.Remove(downLoadnFilePath)
  2204. }()
  2205. br.Ret = 200
  2206. br.Success = true
  2207. br.Msg = "导出成功"
  2208. }
  2209. // 获取历史的数据
  2210. func getHistoryStackCompanyList(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, date, keyword string) (returnData response.StackCompanyListResp, err error) {
  2211. if date == "" {
  2212. err = errors.New("请选择日期")
  2213. return
  2214. }
  2215. var startSize int
  2216. if pageSize <= 0 {
  2217. pageSize = utils.PageSize20
  2218. }
  2219. if currentIndex <= 0 {
  2220. currentIndex = 1
  2221. }
  2222. startSize = utils.StartIndex(currentIndex, pageSize)
  2223. var condition string
  2224. var pars []interface{}
  2225. //条件
  2226. condition += ` AND date = ? `
  2227. pars = append(pars, date)
  2228. var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
  2229. var parsAscribeRai []interface{}
  2230. //是否确认续约 CRM 13.9
  2231. if isConfirm != -1 {
  2232. var conditionConfirm string
  2233. var parsConfirm []interface{}
  2234. companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
  2235. if e != nil && e.Error() != utils.ErrNoRow() {
  2236. err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
  2237. return
  2238. }
  2239. var companyIds []int
  2240. if len(companyConfirmList) == 0 {
  2241. companyIds = append(companyIds, 0) // 给一个不存在的ID
  2242. } else {
  2243. for _, v := range companyConfirmList {
  2244. companyIds = append(companyIds, v.CompanyId)
  2245. }
  2246. }
  2247. if isConfirm == 0 {
  2248. conditionAscribRai += ` AND c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 待确认
  2249. } else {
  2250. conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 已确认
  2251. }
  2252. parsAscribeRai = append(parsAscribeRai, companyIds)
  2253. }
  2254. //归因ID CRM 13.9
  2255. if companyAscribeId > 0 {
  2256. var conditionAscribe string
  2257. var parsAscribe []interface{}
  2258. conditionAscribe = " AND company_ascribe_id = ? "
  2259. parsAscribe = append(parsAscribe, companyAscribeId)
  2260. companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
  2261. if e != nil && e.Error() != utils.ErrNoRow() {
  2262. err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
  2263. return
  2264. }
  2265. var companyIds []int
  2266. if len(companyNoRenewedAscribeList) == 0 {
  2267. companyIds = append(companyIds, 0) // 给一个不存在的ID
  2268. } else {
  2269. for _, v := range companyNoRenewedAscribeList {
  2270. companyIds = append(companyIds, v.CompanyId)
  2271. }
  2272. }
  2273. conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
  2274. parsAscribeRai = append(parsAscribeRai, companyIds)
  2275. }
  2276. if adminId != "" {
  2277. condition += ` AND a.seller_id in (` + adminId + `) `
  2278. //pars = append(pars, adminId)
  2279. } else {
  2280. //根据当前角色来获取查询条件
  2281. condition, pars = getQueryParams(condition, pars, sysUser, "a.")
  2282. }
  2283. if regionType != "" {
  2284. condition += ` AND region_type = ? `
  2285. pars = append(pars, regionType)
  2286. }
  2287. switch companyType {
  2288. case "ficc":
  2289. condition += ` AND a.product_id = ? `
  2290. pars = append(pars, 1)
  2291. case "权益":
  2292. condition += ` AND a.product_id = ? `
  2293. pars = append(pars, 2)
  2294. case "":
  2295. default:
  2296. err = errors.New("客户类型异常")
  2297. return
  2298. }
  2299. //关键字搜索
  2300. if keyword != "" {
  2301. condition += ` and c.company_name like "%` + keyword + `%" `
  2302. }
  2303. var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  2304. var notRenewalTryOut, notRenewalNotTryOut int
  2305. //新签客户数
  2306. {
  2307. condition1 := condition
  2308. pars1 := pars
  2309. condition1 += ` AND a.type = ? `
  2310. pars1 = append(pars, "新签客户")
  2311. total, countErr := models.GetStackCompanyCount(condition1, pars1)
  2312. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2313. err = countErr
  2314. return
  2315. }
  2316. newCompanyTotal = total
  2317. if dataType == "新签客户" {
  2318. //列表页数据总和
  2319. total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
  2320. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2321. err = countErr
  2322. return
  2323. }
  2324. dataTotal = total
  2325. }
  2326. }
  2327. //续约客户数
  2328. {
  2329. condition1 := condition
  2330. pars1 := pars
  2331. condition1 += ` AND a.type = ? `
  2332. pars1 = append(pars, "续约客户")
  2333. total, countErr := models.GetStackCompanyCount(condition1, pars1)
  2334. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2335. err = countErr
  2336. return
  2337. }
  2338. renewalCompanyTotal = total
  2339. if dataType == "续约客户" {
  2340. //列表页数据总和
  2341. total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
  2342. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2343. err = countErr
  2344. return
  2345. }
  2346. dataTotal = total
  2347. }
  2348. }
  2349. //未续约客户数
  2350. {
  2351. condition1 := condition
  2352. pars1 := pars
  2353. condition1 += ` AND a.type = ? `
  2354. pars1 = append(pars, "未续约客户")
  2355. total, countErr := models.GetStackCompanyCount(condition1, pars1)
  2356. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2357. err = countErr
  2358. return
  2359. }
  2360. notRenewalCompanyTotal = total
  2361. condition1 += conditionAscribRai
  2362. pars1 = append(pars1, parsAscribeRai)
  2363. if dataType == "未续约客户" {
  2364. //列表页数据总和
  2365. //统计数据
  2366. for _, v := range []string{"试用", "非试用"} {
  2367. totalCondition1 := condition1
  2368. totalPars1 := pars1
  2369. var tmpTotal int
  2370. if v == "试用" {
  2371. totalCondition1 += ` AND b.status = "试用" `
  2372. tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
  2373. if err != nil {
  2374. return
  2375. }
  2376. notRenewalTryOut = tmpTotal
  2377. } else if v == "非试用" {
  2378. totalCondition1 += ` AND b.status IN ("冻结","流失") `
  2379. tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
  2380. if err != nil && err.Error() != utils.ErrNoRow() {
  2381. return
  2382. }
  2383. notRenewalNotTryOut = tmpTotal
  2384. }
  2385. }
  2386. //列表数据数量
  2387. if tryOutType == "试用" {
  2388. condition1 += ` AND b.status = "试用" `
  2389. total = notRenewalTryOut
  2390. } else if tryOutType == "非试用" {
  2391. condition1 += ` AND b.status IN ("冻结","流失") `
  2392. total = notRenewalNotTryOut
  2393. }
  2394. total, countErr := models.GetNotRenewalStackCompanyProductCount(condition1, pars1)
  2395. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2396. err = countErr
  2397. return
  2398. }
  2399. dataTotal = total
  2400. }
  2401. }
  2402. //报表类型,新签客户`,`续约客户`,`未续约客户`
  2403. condition += ` AND a.type = ? `
  2404. pars = append(pars, dataType)
  2405. orderBy := ``
  2406. if dataType == "新签客户" || dataType == "续约客户" {
  2407. orderBy = `start_date desc`
  2408. }
  2409. if tryOutType == "试用" {
  2410. condition += ` AND b.status = "试用" `
  2411. } else if tryOutType == "非试用" {
  2412. condition += ` AND b.status IN ("冻结","流失") `
  2413. }
  2414. list, countErr := models.GetStackCompanyList(condition, orderBy, pars, startSize, pageSize)
  2415. if countErr != nil {
  2416. err = countErr
  2417. return
  2418. }
  2419. listLen := len(list)
  2420. //moreListMap := make(map[int][]*models.StackCompanyStatisticList)
  2421. if dataType == "续约客户" {
  2422. var ids []string
  2423. var ascribecompanyIds []int
  2424. oldCompanyMap := make(map[int]*models.IncrementalList)
  2425. oldMoneyMap := make(map[int]float64)
  2426. countMap := make(map[int]int)
  2427. for _, item := range list {
  2428. ids = append(ids, strconv.Itoa(item.CompanyId))
  2429. ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
  2430. }
  2431. //归因标签
  2432. mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
  2433. mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
  2434. if len(ids) > 0 {
  2435. idStr := strings.Join(ids, ",")
  2436. lists, contractErr := models.GetLastContractMoney(idStr)
  2437. if contractErr != nil {
  2438. err = contractErr
  2439. return
  2440. }
  2441. for _, item := range lists {
  2442. _, countOk := countMap[item.CompanyId]
  2443. _, ok := oldCompanyMap[item.CompanyId]
  2444. if !ok {
  2445. oldCompanyMap[item.CompanyId] = item
  2446. oldMoneyMap[item.CompanyId] = item.Money
  2447. } else if !countOk {
  2448. countMap[item.CompanyId] = 1
  2449. oldCompanyMap[item.CompanyId] = item
  2450. }
  2451. }
  2452. //给list赋值
  2453. for _, item := range list {
  2454. if item.ProductName == "权益" {
  2455. oldMoney, _ := oldMoneyMap[item.CompanyId]
  2456. lastContract, _ := oldCompanyMap[item.CompanyId]
  2457. if oldMoney > lastContract.Money {
  2458. item.PackageDifference = "增加套餐"
  2459. } else if oldMoney < lastContract.Money {
  2460. item.PackageDifference = "减少套餐"
  2461. } else {
  2462. item.PackageDifference = "维持套餐"
  2463. }
  2464. }
  2465. item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  2466. item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  2467. item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  2468. }
  2469. }
  2470. }
  2471. //获取其他产品数据
  2472. //if listLen > 0 {
  2473. // companyIdSlice := make([]string, 0)
  2474. // statisticIdSlice := make([]string, 0)
  2475. // for _, v := range list {
  2476. // if v.Count > 1 {
  2477. // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  2478. // statisticIdSlice = append(statisticIdSlice, strconv.Itoa(v.StatisticId))
  2479. // }
  2480. // }
  2481. // if len(companyIdSlice) > 0 {
  2482. // companyIds := strings.Join(companyIdSlice, ",")
  2483. // statisticIds := strings.Join(statisticIdSlice, ",")
  2484. // stackCompanyList2, list2Err := models.GetStackCompanyListByCompanyIds(companyIds, statisticIds, condition, pars)
  2485. // //companyType
  2486. // if list2Err != nil {
  2487. // err = errors.New("获取其他产品失败,Err:" + list2Err.Error())
  2488. // return
  2489. // }
  2490. //
  2491. // for _, stackCompany := range stackCompanyList2 {
  2492. // moreListMap[stackCompany.CompanyId] = append(moreListMap[stackCompany.CompanyId], stackCompany)
  2493. // }
  2494. // }
  2495. //}
  2496. for i := 0; i < listLen; i++ {
  2497. item := list[i]
  2498. //剩余可用天数
  2499. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  2500. endDateTime = endDateTime.AddDate(0, 0, 1)
  2501. sub := endDateTime.Sub(time.Now())
  2502. //if sub < 0 {
  2503. // sub = 0
  2504. //}
  2505. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  2506. list[i].ExpireDay = expireDay
  2507. //其他产品数据处理
  2508. //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
  2509. // for _, otherCompanyProduct := range otherCompanyProductList {
  2510. // list[i].ProductName += "/" + otherCompanyProduct.ProductName
  2511. // list[i].SellerName += "/" + otherCompanyProduct.SellerName
  2512. // list[i].StartDate += "/" + otherCompanyProduct.StartDate
  2513. // list[i].EndDate += "/" + otherCompanyProduct.EndDate
  2514. //
  2515. // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
  2516. // endDateTime = endDateTime.AddDate(0, 0, 1)
  2517. // sub := endDateTime.Sub(time.Now())
  2518. // //if sub < 0 {
  2519. // // sub = 0
  2520. // //}
  2521. // tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  2522. // list[i].ExpireDay += "/" + tmpExpireDay
  2523. // }
  2524. //}
  2525. }
  2526. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  2527. resp := response.StackCompanyListResp{
  2528. Paging: page,
  2529. List: list,
  2530. NewCompanyTotal: newCompanyTotal,
  2531. RenewalCompanyTotal: renewalCompanyTotal,
  2532. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  2533. NotRenewalTryOut: notRenewalTryOut,
  2534. NotRenewalNotTryOut: notRenewalNotTryOut,
  2535. }
  2536. return resp, err
  2537. }
  2538. // 获取今日的数据
  2539. func getTodayStackCompanyList(sysUser *system.Admin, currentIndex, pageSize int, adminId, regionType, companyType, dataType string) (returnData response.StackCompanyListResp, err error) {
  2540. var startSize int
  2541. if pageSize <= 0 {
  2542. pageSize = utils.PageSize20
  2543. }
  2544. if currentIndex <= 0 {
  2545. currentIndex = 1
  2546. }
  2547. startSize = utils.StartIndex(currentIndex, pageSize)
  2548. var condition, listCondition string
  2549. var pars, listPars []interface{}
  2550. today := utils.GetToday(utils.FormatDate)
  2551. //条件
  2552. if adminId != "" {
  2553. condition += ` AND c.seller_id in (` + adminId + `) `
  2554. //pars = append(pars, adminId)
  2555. } else {
  2556. //根据当前角色来获取查询条件
  2557. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  2558. }
  2559. if regionType != "" {
  2560. condition += ` AND b.region_type = ? `
  2561. pars = append(pars, regionType)
  2562. }
  2563. switch companyType {
  2564. case "ficc":
  2565. condition += ` AND a.product_id = ? `
  2566. pars = append(pars, 1)
  2567. case "权益":
  2568. condition += ` AND a.product_id = ? `
  2569. pars = append(pars, 2)
  2570. case "":
  2571. default:
  2572. err = errors.New("客户类型异常")
  2573. return
  2574. }
  2575. var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  2576. //新签客户数
  2577. {
  2578. condition1 := condition
  2579. pars1 := pars
  2580. condition1 += ` AND c.status = "正式" AND a.start_date <= ? AND a.end_date >= ? `
  2581. pars1 = append(pars1, today, today)
  2582. condition1 += ` AND a.contract_type = ? `
  2583. pars1 = append(pars1, "新签合同")
  2584. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  2585. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2586. err = countErr
  2587. return
  2588. }
  2589. newCompanyTotal = total
  2590. if dataType == "新签客户" {
  2591. //页表页数据总和
  2592. total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
  2593. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2594. err = countErr
  2595. return
  2596. }
  2597. dataTotal = total
  2598. listCondition = condition1
  2599. listPars = pars1
  2600. }
  2601. }
  2602. //续约客户数
  2603. {
  2604. condition1 := condition
  2605. pars1 := pars
  2606. condition1 += ` AND c.status = "正式" `
  2607. condition1 += " AND a.end_date >= ?"
  2608. pars1 = append(pars1, today)
  2609. condition1 += ` AND a.contract_type = ? `
  2610. pars1 = append(pars1, "续约合同")
  2611. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  2612. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2613. err = countErr
  2614. return
  2615. }
  2616. renewalCompanyTotal = total
  2617. if dataType == "续约客户" {
  2618. //页表页数据总和
  2619. total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
  2620. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2621. err = countErr
  2622. return
  2623. }
  2624. dataTotal = total
  2625. listCondition = condition1
  2626. listPars = pars1
  2627. }
  2628. }
  2629. //未续约客户数
  2630. {
  2631. condition1 := condition
  2632. pars1 := pars
  2633. condition1 += ` AND c.status not in ("永续","正式") `
  2634. //condition1 += " AND a.end_date < ?"
  2635. //pars1 = append(pars1, today)
  2636. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  2637. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2638. err = countErr
  2639. return
  2640. }
  2641. notRenewalCompanyTotal = total
  2642. if dataType == "未续约客户" {
  2643. //页表页数据总和
  2644. total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
  2645. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2646. err = countErr
  2647. return
  2648. }
  2649. dataTotal = total
  2650. listCondition = condition1
  2651. listPars = pars1
  2652. }
  2653. }
  2654. list, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
  2655. if countErr != nil {
  2656. err = countErr
  2657. return
  2658. }
  2659. listLen := len(list)
  2660. //moreListMap := make(map[int][]*models.IncrementalList)
  2661. //获取其他产品数据
  2662. //if listLen > 0 {
  2663. // companyIdSlice := make([]string, 0)
  2664. // companyContractIdSlice := make([]string, 0)
  2665. // for _, v := range list {
  2666. // if v.Count > 1 {
  2667. // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  2668. // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
  2669. // }
  2670. // }
  2671. //if len(companyIdSlice) > 0 {
  2672. // companyIds := strings.Join(companyIdSlice, ",")
  2673. // companyContractIds := strings.Join(companyContractIdSlice, ",")
  2674. // incrementalList2, list2Err := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, listCondition, listPars)
  2675. // //companyType
  2676. // if list2Err != nil {
  2677. // err = errors.New("获取其他产品失败,Err:" + list2Err.Error())
  2678. // return
  2679. // }
  2680. //
  2681. // for _, incremental := range incrementalList2 {
  2682. // moreListMap[incremental.CompanyId] = append(moreListMap[incremental.CompanyId], incremental)
  2683. // }
  2684. //}
  2685. //}
  2686. for i := 0; i < listLen; i++ {
  2687. item := list[i]
  2688. //剩余可用天数
  2689. expireDay := "0"
  2690. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  2691. endDateTime = endDateTime.AddDate(0, 0, 1)
  2692. var sub time.Duration
  2693. if dataType != "未续约客户" {
  2694. sub = endDateTime.Sub(time.Now())
  2695. //if sub < 0 {
  2696. // sub = 0
  2697. //}
  2698. } else {
  2699. sub = time.Now().Sub(endDateTime)
  2700. }
  2701. expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
  2702. list[i].ExpireDay = expireDay
  2703. //其他产品数据拼接
  2704. //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
  2705. // for _, otherCompanyProduct := range otherCompanyProductList {
  2706. // list[i].ProductName += "/" + otherCompanyProduct.ProductName
  2707. // list[i].SellerName += "/" + otherCompanyProduct.SellerName
  2708. // list[i].StartDate += "/" + otherCompanyProduct.StartDate
  2709. // list[i].EndDate += "/" + otherCompanyProduct.EndDate
  2710. //
  2711. // tmpExpireDay := "0"
  2712. // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
  2713. // endDateTime = endDateTime.AddDate(0, 0, 1)
  2714. // var sub time.Duration
  2715. // if dataType != "未续约客户" {
  2716. // sub = endDateTime.Sub(time.Now())
  2717. // //if sub < 0 {
  2718. // // sub = 0
  2719. // //}
  2720. // } else {
  2721. // sub = time.Now().Sub(endDateTime)
  2722. // }
  2723. // tmpExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
  2724. //
  2725. // list[i].ExpireDay += "/" + tmpExpireDay
  2726. // }
  2727. //}
  2728. }
  2729. var stackCompanyStatisticList []*models.StackCompanyStatisticList
  2730. for _, v := range list {
  2731. stackCompanyStatistic := models.StackCompanyStatisticList{
  2732. Type: dataType,
  2733. CompanyId: v.CompanyId,
  2734. CompanyName: v.CompanyName,
  2735. ProductId: v.ProductId,
  2736. ProductName: v.ProductName,
  2737. ContractNum: v.Count,
  2738. SellerId: v.SellerId,
  2739. SellerName: v.SellerName,
  2740. Date: today,
  2741. StartDate: v.StartDate,
  2742. EndDate: v.EndDate,
  2743. RegionType: v.RegionType,
  2744. //CreateTime :v.CreateTime,
  2745. CreateTimeStr: v.CreateTime,
  2746. ExpireDay: v.ExpireDay,
  2747. }
  2748. stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
  2749. }
  2750. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  2751. resp := response.StackCompanyListResp{
  2752. Paging: page,
  2753. List: stackCompanyStatisticList,
  2754. NewCompanyTotal: newCompanyTotal,
  2755. RenewalCompanyTotal: renewalCompanyTotal,
  2756. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  2757. }
  2758. return resp, err
  2759. }
  2760. func getTodayStackCompanyListV2(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
  2761. var startSize int
  2762. if pageSize <= 0 {
  2763. pageSize = utils.PageSize20
  2764. }
  2765. if currentIndex <= 0 {
  2766. currentIndex = 1
  2767. }
  2768. startSize = utils.StartIndex(currentIndex, pageSize)
  2769. var condition, listCondition string
  2770. var pars, listPars []interface{}
  2771. today := utils.GetToday(utils.FormatDate)
  2772. //条件
  2773. var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
  2774. var parsAscribeRai []interface{}
  2775. //是否确认续约 CRM 13.9
  2776. if isConfirm != -1 {
  2777. var conditionConfirm string
  2778. var parsConfirm []interface{}
  2779. companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
  2780. if e != nil && e.Error() != utils.ErrNoRow() {
  2781. err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
  2782. return
  2783. }
  2784. var companyIds []int
  2785. if len(companyConfirmList) == 0 {
  2786. companyIds = append(companyIds, 0) // 给一个不存在的ID
  2787. } else {
  2788. for _, v := range companyConfirmList {
  2789. companyIds = append(companyIds, v.CompanyId)
  2790. }
  2791. }
  2792. if isConfirm == 0 {
  2793. conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `) AND c.product_id = 2 ) ` // 待确认
  2794. } else {
  2795. conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `) OR c.product_id = 2 )` // 已确认
  2796. }
  2797. parsAscribeRai = append(parsAscribeRai, companyIds)
  2798. }
  2799. //归因ID CRM 13.9
  2800. if companyAscribeId > 0 {
  2801. var conditionAscribe string
  2802. var parsAscribe []interface{}
  2803. conditionAscribe = " AND company_ascribe_id = ? "
  2804. parsAscribe = append(parsAscribe, companyAscribeId)
  2805. companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
  2806. if e != nil && e.Error() != utils.ErrNoRow() {
  2807. err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
  2808. return
  2809. }
  2810. var companyIds []int
  2811. if len(companyNoRenewedAscribeList) == 0 {
  2812. companyIds = append(companyIds, 0) // 给一个不存在的ID
  2813. } else {
  2814. for _, v := range companyNoRenewedAscribeList {
  2815. companyIds = append(companyIds, v.CompanyId)
  2816. }
  2817. }
  2818. conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
  2819. parsAscribeRai = append(parsAscribeRai, companyIds)
  2820. }
  2821. if adminId != "" {
  2822. condition += ` AND c.seller_id in (` + adminId + `) `
  2823. //pars = append(pars, adminId)
  2824. } else {
  2825. //根据当前角色来获取查询条件
  2826. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  2827. }
  2828. if regionType != "" {
  2829. condition += ` AND b.region_type = ? `
  2830. pars = append(pars, regionType)
  2831. }
  2832. //关键字搜索
  2833. if keyword != "" {
  2834. condition += ` and b.company_name like "%` + keyword + `%" `
  2835. }
  2836. switch companyType {
  2837. case "ficc":
  2838. condition += ` AND a.product_id = ? `
  2839. pars = append(pars, 1)
  2840. case "权益":
  2841. condition += ` AND a.product_id = ? `
  2842. pars = append(pars, 2)
  2843. case "":
  2844. default:
  2845. err = errors.New("客户类型异常")
  2846. return
  2847. }
  2848. var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  2849. var notRenewalTryOut, notRenewalNotTryOut int
  2850. var list []*models.IncrementalList
  2851. //新签客户数
  2852. {
  2853. condition1 := condition
  2854. pars1 := pars
  2855. //condition1 += ` AND c.status = "正式" `
  2856. condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
  2857. pars1 = append(pars1, today, today)
  2858. condition1 += ` AND a.contract_type = ? `
  2859. pars1 = append(pars1, "新签合同")
  2860. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  2861. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2862. err = countErr
  2863. return
  2864. }
  2865. newCompanyTotal = total
  2866. if dataType == "新签客户" {
  2867. //页表页数据总和
  2868. total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
  2869. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2870. err = countErr
  2871. return
  2872. }
  2873. dataTotal = total
  2874. listCondition = condition1
  2875. listPars = pars1
  2876. }
  2877. }
  2878. //续约客户数
  2879. {
  2880. condition1 := condition
  2881. pars1 := pars
  2882. //condition1 += ` AND c.status = "正式" `
  2883. condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
  2884. pars1 = append(pars1, today, today)
  2885. condition1 += ` AND a.contract_type = ? `
  2886. pars1 = append(pars1, "续约合同")
  2887. //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
  2888. pars1 = append(pars1, today)
  2889. total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
  2890. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2891. err = countErr
  2892. return
  2893. }
  2894. renewalCompanyTotal = total
  2895. if dataType == "续约客户" {
  2896. //页表页数据总和
  2897. total, countErr := models.GetTodayStackCompanyProductCountV2(condition1, pars1)
  2898. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2899. err = countErr
  2900. return
  2901. }
  2902. dataTotal = total
  2903. listCondition = condition1
  2904. listPars = pars1
  2905. }
  2906. }
  2907. //未续约客户数
  2908. {
  2909. condition1 := condition
  2910. pars1 := pars
  2911. condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
  2912. pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
  2913. condition1 += ` AND a.operation = 'try_out' `
  2914. total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  2915. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2916. err = countErr
  2917. return
  2918. }
  2919. notRenewalCompanyTotal = total
  2920. condition1 += conditionAscribRai
  2921. pars1 = append(pars1, parsAscribeRai)
  2922. if dataType == "未续约客户" {
  2923. //页表页数据总和
  2924. //统计数据
  2925. for _, v := range []string{"试用", "非试用"} {
  2926. totalCondition1 := condition1
  2927. totalPars1 := pars1
  2928. var tmpTotal int
  2929. if v == "试用" {
  2930. totalCondition1 += ` AND c.status = "试用" `
  2931. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  2932. if err != nil {
  2933. return
  2934. }
  2935. notRenewalTryOut = tmpTotal
  2936. } else if v == "非试用" {
  2937. totalCondition1 += ` AND c.status IN ("冻结","流失") `
  2938. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  2939. if err != nil && err.Error() != utils.ErrNoRow() {
  2940. return
  2941. }
  2942. notRenewalNotTryOut = tmpTotal
  2943. }
  2944. }
  2945. //列表数据数量
  2946. if tryOutType == "试用" {
  2947. condition1 += ` AND c.status = "试用" `
  2948. total = notRenewalTryOut
  2949. } else if tryOutType == "非试用" {
  2950. condition1 += ` AND c.status IN ("冻结","流失") `
  2951. total = notRenewalNotTryOut
  2952. }
  2953. //total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
  2954. //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  2955. // err = countErr
  2956. // return
  2957. //}
  2958. dataTotal = total
  2959. listCondition = condition1
  2960. listPars = pars1
  2961. if tryOutType == "试用" {
  2962. listCondition += ` AND c.status = "试用" `
  2963. } else if tryOutType == "非试用" {
  2964. listCondition += ` AND c.status IN ("冻结","流失") `
  2965. }
  2966. tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
  2967. if countErr != nil {
  2968. err = countErr
  2969. return
  2970. }
  2971. for i := 0; i < len(tmpList); i++ {
  2972. endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
  2973. if parseErr != nil {
  2974. err = parseErr
  2975. return
  2976. }
  2977. tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
  2978. }
  2979. list = tmpList
  2980. }
  2981. }
  2982. switch dataType {
  2983. case "新签客户":
  2984. tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
  2985. if countErr != nil {
  2986. err = countErr
  2987. return
  2988. }
  2989. list = tmpList
  2990. case "续约客户":
  2991. tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
  2992. if countErr != nil {
  2993. err = countErr
  2994. return
  2995. }
  2996. list = tmpList
  2997. }
  2998. if dataType == "续约客户" {
  2999. var ids []string
  3000. oldCompanyMap := make(map[int]*models.IncrementalList)
  3001. oldMoneyMap := make(map[int]float64)
  3002. countMap := make(map[int]int)
  3003. for _, item := range list {
  3004. ids = append(ids, strconv.Itoa(item.CompanyId))
  3005. }
  3006. if len(ids) > 0 {
  3007. idStr := strings.Join(ids, ",")
  3008. lists, contractErr := models.GetLastContractMoney(idStr)
  3009. if contractErr != nil {
  3010. err = contractErr
  3011. return
  3012. }
  3013. for _, item := range lists {
  3014. _, countOk := countMap[item.CompanyId]
  3015. _, ok := oldCompanyMap[item.CompanyId]
  3016. if !ok {
  3017. oldCompanyMap[item.CompanyId] = item
  3018. oldMoneyMap[item.CompanyId] = item.Money
  3019. } else if !countOk {
  3020. countMap[item.CompanyId] = 1
  3021. oldCompanyMap[item.CompanyId] = item
  3022. }
  3023. }
  3024. //给list赋值
  3025. for _, item := range list {
  3026. if item.ProductName == "权益" {
  3027. oldMoney, _ := oldMoneyMap[item.CompanyId]
  3028. lastContract, _ := oldCompanyMap[item.CompanyId]
  3029. if oldMoney > lastContract.Money {
  3030. item.PackageDifference = "增加套餐"
  3031. } else if oldMoney < lastContract.Money {
  3032. item.PackageDifference = "减少套餐"
  3033. } else {
  3034. item.PackageDifference = "维持套餐"
  3035. }
  3036. }
  3037. }
  3038. }
  3039. }
  3040. var ascribecompanyIds []int
  3041. for _, item := range list {
  3042. ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
  3043. }
  3044. //归因标签
  3045. mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
  3046. mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
  3047. for _, item := range list {
  3048. item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3049. item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3050. item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3051. }
  3052. listLen := len(list)
  3053. for i := 0; i < listLen; i++ {
  3054. item := list[i]
  3055. //剩余可用天数
  3056. expireDay := "0"
  3057. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  3058. var sub time.Duration
  3059. if dataType != "未续约客户" {
  3060. endDateTime = endDateTime.AddDate(0, 0, 1)
  3061. sub = endDateTime.Sub(time.Now())
  3062. //if sub < 0 {
  3063. // sub = 0
  3064. //}
  3065. } else {
  3066. sub = time.Now().Sub(endDateTime)
  3067. }
  3068. expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
  3069. list[i].ExpireDay = expireDay
  3070. }
  3071. var stackCompanyStatisticList []*models.StackCompanyStatisticList
  3072. for _, v := range list {
  3073. stackCompanyStatistic := models.StackCompanyStatisticList{
  3074. Type: dataType,
  3075. CompanyId: v.CompanyId,
  3076. CompanyName: v.CompanyName,
  3077. ProductId: v.ProductId,
  3078. ProductName: v.ProductName,
  3079. ContractNum: v.Count,
  3080. SellerId: v.SellerId,
  3081. SellerName: v.SellerName,
  3082. Date: today,
  3083. StartDate: v.StartDate,
  3084. EndDate: v.EndDate,
  3085. RegionType: v.RegionType,
  3086. //CreateTime :v.CreateTime,
  3087. CreateTimeStr: v.CreateTime,
  3088. ExpireDay: v.ExpireDay,
  3089. RenewalReason: v.RenewalReason,
  3090. RenewalTodo: v.RenewalTodo,
  3091. Status: v.Status,
  3092. PackageDifference: v.PackageDifference,
  3093. AscribeContent: v.AscribeContent,
  3094. IsShowNoRenewedNote: v.IsShowNoRenewedNote,
  3095. Content: v.Content,
  3096. }
  3097. stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
  3098. }
  3099. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  3100. resp := response.StackCompanyListResp{
  3101. Paging: page,
  3102. List: stackCompanyStatisticList,
  3103. NewCompanyTotal: newCompanyTotal,
  3104. RenewalCompanyTotal: renewalCompanyTotal,
  3105. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  3106. NotRenewalTryOut: notRenewalTryOut,
  3107. NotRenewalNotTryOut: notRenewalNotTryOut,
  3108. }
  3109. return resp, err
  3110. }
  3111. // IncrementalCompanyList
  3112. // @Title 获取增量客户数据列表
  3113. // @Description 获取增量客户数据列表接口
  3114. // @Param PageSize query int true "每页数据条数"
  3115. // @Param CurrentIndex query int true "当前页页码,从1开始"
  3116. // @Param Keyword query string true "客户名称"
  3117. // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  3118. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  3119. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  3120. // @Param StartDate query string false "开始日期"
  3121. // @Param EndDate query string false "结束日期"
  3122. // @Param DataType query string false "报表类型,枚举值:`新增试用`,`新签客户`,`续约客户`,`未续约客户`"
  3123. // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
  3124. // @Param IsExport query bool false "是否导出excel,默认是false"
  3125. // @Param IsConfirm query int false "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
  3126. // @Param CompanyAscribeId query int false "归因ID"
  3127. // @Success 200 {object} response.IncrementalCompanyListResp
  3128. // @router /incremental_company_list [get]
  3129. func (this *StatisticReportController) IncrementalCompanyList() {
  3130. br := new(models.BaseResponse).Init()
  3131. defer func() {
  3132. this.Data["json"] = br
  3133. this.ServeJSON()
  3134. }()
  3135. sysUser := this.SysUser
  3136. if sysUser == nil {
  3137. br.Msg = "请登录"
  3138. br.ErrMsg = "请登录,SysUser Is Empty"
  3139. br.Ret = 408
  3140. return
  3141. }
  3142. pageSize, _ := this.GetInt("PageSize")
  3143. currentIndex, _ := this.GetInt("CurrentIndex")
  3144. adminId := this.GetString("AdminId")
  3145. regionType := this.GetString("RegionType")
  3146. companyType := this.GetString("CompanyType")
  3147. dataType := this.GetString("DataType")
  3148. tryOutType := this.GetString("TryOutType")
  3149. keyword := this.GetString("Keyword")
  3150. startDate := this.GetString("StartDate")
  3151. endDate := this.GetString("EndDate")
  3152. isConfirm, _ := this.GetInt("IsConfirm", -1) // CRM 13.9
  3153. companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
  3154. //if startDate == "" || endDate == "" {
  3155. // br.Msg = "获取失败,开始日期或结束日期未传"
  3156. // br.ErrMsg = "获取失败,开始日期或结束日期未传"
  3157. // return
  3158. //}
  3159. if startDate == "" {
  3160. startDate = "2015-01-01"
  3161. }
  3162. if endDate == "" {
  3163. endDate = time.Now().Format(utils.FormatDate)
  3164. }
  3165. var startSize int
  3166. if pageSize <= 0 {
  3167. pageSize = utils.PageSize20
  3168. }
  3169. if currentIndex <= 0 {
  3170. currentIndex = 1
  3171. }
  3172. startSize = utils.StartIndex(currentIndex, pageSize)
  3173. //是否导出报表
  3174. isExport, _ := this.GetBool("IsExport")
  3175. if isExport {
  3176. pageSize = 10000
  3177. currentIndex = 1
  3178. }
  3179. var condition string
  3180. var pars []interface{}
  3181. //条件
  3182. if adminId != "" {
  3183. condition += ` AND c.seller_id in (` + adminId + `) `
  3184. //pars = append(pars, adminId)
  3185. } else {
  3186. //根据当前角色来获取查询条件
  3187. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  3188. }
  3189. if regionType != "" {
  3190. condition += ` AND b.region_type = ? `
  3191. pars = append(pars, regionType)
  3192. }
  3193. //关键字搜索
  3194. if keyword != "" {
  3195. condition += ` and b.company_name like "%` + keyword + `%" `
  3196. }
  3197. var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
  3198. var conditionAscribRaiTotal string // 处理权益未续约客户总量查询条件
  3199. var parsAscribeRai []interface{}
  3200. var parsAscribeRaiTotal []interface{} // 处理权益未续约客户总量查询条件
  3201. var conditionConfirm string
  3202. var parsConfirm []interface{}
  3203. companyConfirmList, err := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
  3204. if err != nil && err.Error() != utils.ErrNoRow() {
  3205. br.Msg = "获取失败"
  3206. br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
  3207. return
  3208. }
  3209. var noRenewedcompanyIds []int //已经确定未续约的公司ID
  3210. if len(companyConfirmList) == 0 {
  3211. noRenewedcompanyIds = append(noRenewedcompanyIds, 0) // 给一个不存在的ID
  3212. } else {
  3213. for _, v := range companyConfirmList {
  3214. noRenewedcompanyIds = append(noRenewedcompanyIds, v.CompanyId)
  3215. }
  3216. }
  3217. //是否确认续约 CRM 13.9
  3218. conditionAscribRaiTotal += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) OR c.product_id = 1 OR a.create_time < '2023-01-01' ) ` // 已确认
  3219. parsAscribeRaiTotal = append(parsAscribeRaiTotal, noRenewedcompanyIds)
  3220. if isConfirm != -1 {
  3221. if isConfirm == 0 {
  3222. conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) AND c.product_id = 2 AND a.create_time >= '2023-01-01' ) ` // 待确认
  3223. } else {
  3224. conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) OR c.product_id = 1 OR a.create_time < '2023-01-01' ) ` // 已确认
  3225. }
  3226. parsAscribeRai = append(parsAscribeRai, noRenewedcompanyIds)
  3227. }
  3228. //归因ID CRM 13.9
  3229. if companyAscribeId > 0 {
  3230. var conditionAscribe string
  3231. var parsAscribe []interface{}
  3232. conditionAscribe = " AND company_ascribe_id = ? "
  3233. parsAscribe = append(parsAscribe, companyAscribeId)
  3234. companyNoRenewedAscribeList, err := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
  3235. if err != nil && err.Error() != utils.ErrNoRow() {
  3236. br.Msg = "获取失败"
  3237. br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
  3238. return
  3239. }
  3240. var companyIds []int
  3241. if len(companyNoRenewedAscribeList) == 0 {
  3242. companyIds = append(companyIds, 0) // 给一个不存在的ID
  3243. } else {
  3244. for _, v := range companyNoRenewedAscribeList {
  3245. companyIds = append(companyIds, v.CompanyId)
  3246. }
  3247. }
  3248. conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
  3249. parsAscribeRai = append(parsAscribeRai, companyIds)
  3250. }
  3251. switch companyType {
  3252. case "ficc":
  3253. condition += ` AND c.product_id = ? `
  3254. pars = append(pars, 1)
  3255. case "权益":
  3256. condition += ` AND c.product_id = ? `
  3257. pars = append(pars, 2)
  3258. case "":
  3259. default:
  3260. br.Msg = "获取失败,客户类型异常"
  3261. br.ErrMsg = "获取失败,客户类型异常"
  3262. return
  3263. }
  3264. var list []*models.IncrementalList
  3265. //moreListMap := make(map[int][]*models.IncrementalList)
  3266. var dataTotal, trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  3267. var notRenewalTryOut, notRenewalNotTryOut int
  3268. //试用客户数
  3269. {
  3270. condition1 := condition
  3271. pars1 := pars
  3272. condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
  3273. pars1 = append(pars1, startDate, endDate)
  3274. total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  3275. if err != nil && err.Error() != utils.ErrNoRow() {
  3276. br.Msg = "获取失败"
  3277. br.ErrMsg = "获取失败,Err:" + err.Error()
  3278. return
  3279. }
  3280. trialTotal = total
  3281. if dataType == "新增试用" {
  3282. //列表数据数量
  3283. total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
  3284. if err != nil && err.Error() != utils.ErrNoRow() {
  3285. br.Msg = "获取失败"
  3286. br.ErrMsg = "获取失败,Err:" + err.Error()
  3287. return
  3288. }
  3289. //列表页数据
  3290. tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
  3291. if err != nil {
  3292. br.Msg = "获取失败"
  3293. br.ErrMsg = "获取失败,Err:" + err.Error()
  3294. return
  3295. }
  3296. list = tmpList
  3297. dataTotal = total
  3298. }
  3299. }
  3300. //新签客户数
  3301. {
  3302. condition1 := condition
  3303. pars1 := pars
  3304. condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
  3305. pars1 = append(pars1, startDate, endDate)
  3306. condition1 += ` AND a.contract_type = ? `
  3307. pars1 = append(pars1, "新签合同")
  3308. total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
  3309. if err != nil && err.Error() != utils.ErrNoRow() {
  3310. br.Msg = "获取失败"
  3311. br.ErrMsg = "获取失败,Err:" + err.Error()
  3312. return
  3313. }
  3314. newCompanyTotal = total
  3315. if dataType == "新签客户" {
  3316. //列表数据数量
  3317. total, err := models.GetIncrementalNewCompanyProductCount(condition1, pars1)
  3318. if err != nil && err.Error() != utils.ErrNoRow() {
  3319. br.Msg = "获取失败"
  3320. br.ErrMsg = "获取失败,Err:" + err.Error()
  3321. return
  3322. }
  3323. //列表页数据
  3324. tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
  3325. if err != nil {
  3326. br.Msg = "获取失败"
  3327. br.ErrMsg = "获取失败,Err:" + err.Error()
  3328. return
  3329. }
  3330. list = tmpList
  3331. dataTotal = total
  3332. //获取其他产品
  3333. //if len(list) > 0 {
  3334. // companyIdSlice := make([]string, 0)
  3335. // companyContractIdSlice := make([]string, 0)
  3336. // for _, v := range list {
  3337. // if v.Count > 1 {
  3338. // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  3339. // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
  3340. // }
  3341. // }
  3342. // if len(companyIdSlice) > 0 {
  3343. // companyIds := strings.Join(companyIdSlice, ",")
  3344. // companyContractIds := strings.Join(companyContractIdSlice, ",")
  3345. // otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
  3346. // //companyType
  3347. // if otherListErr != nil {
  3348. // br.Msg = "获取其他产品失败"
  3349. // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
  3350. // return
  3351. // }
  3352. //
  3353. // for _, otherCompanyContract := range otherList {
  3354. // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
  3355. // }
  3356. // }
  3357. //}
  3358. }
  3359. }
  3360. //续约客户数
  3361. {
  3362. condition1 := condition
  3363. pars1 := pars
  3364. condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
  3365. pars1 = append(pars1, startDate, endDate)
  3366. condition1 += ` AND a.contract_type = ? `
  3367. pars1 = append(pars1, "续约合同")
  3368. //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
  3369. pars1 = append(pars1, endDate)
  3370. total, err := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
  3371. if err != nil && err.Error() != utils.ErrNoRow() {
  3372. br.Msg = "获取失败"
  3373. br.ErrMsg = "获取失败,Err:" + err.Error()
  3374. return
  3375. }
  3376. renewalCompanyTotal = total
  3377. if dataType == "续约客户" {
  3378. //列表数据数量
  3379. total, err := models.GetIncrementalNewCompanyProductCountV2(condition1, pars1)
  3380. if err != nil && err.Error() != utils.ErrNoRow() {
  3381. br.Msg = "获取失败"
  3382. br.ErrMsg = "获取失败,Err:" + err.Error()
  3383. return
  3384. }
  3385. //列表页数据
  3386. tmpList, err := models.GetIncrementalNewCompanyListV2(condition1, pars1, startSize, pageSize)
  3387. if err != nil {
  3388. br.Msg = "获取失败"
  3389. br.ErrMsg = "获取失败,Err:" + err.Error()
  3390. return
  3391. }
  3392. list = tmpList
  3393. dataTotal = total
  3394. var ids []string
  3395. companyMap := make(map[int]*models.IncrementalList)
  3396. oldCompanyMap := make(map[int]*models.IncrementalList)
  3397. countMap := make(map[int]int)
  3398. for _, item := range tmpList {
  3399. ids = append(ids, strconv.Itoa(item.CompanyId))
  3400. companyMap[item.CompanyId] = item
  3401. }
  3402. if len(ids) > 0 {
  3403. idStr := strings.Join(ids, ",")
  3404. lists, err := models.GetLastContractMoney(idStr)
  3405. if err != nil {
  3406. br.Msg = "获取失败"
  3407. br.ErrMsg = "获取失败,Err:" + err.Error()
  3408. return
  3409. }
  3410. for _, item := range lists {
  3411. _, countOk := countMap[item.CompanyId]
  3412. _, ok := oldCompanyMap[item.CompanyId]
  3413. if !ok {
  3414. oldCompanyMap[item.CompanyId] = item
  3415. } else if !countOk {
  3416. countMap[item.CompanyId] = 1
  3417. oldCompanyMap[item.CompanyId] = item
  3418. }
  3419. }
  3420. //给list赋值
  3421. for _, item := range list {
  3422. if item.ProductName == "权益" {
  3423. lastContract, _ := oldCompanyMap[item.CompanyId]
  3424. if item.Money > lastContract.Money {
  3425. item.PackageDifference = "增加套餐"
  3426. } else if item.Money < lastContract.Money {
  3427. item.PackageDifference = "减少套餐"
  3428. } else {
  3429. item.PackageDifference = "维持套餐"
  3430. }
  3431. }
  3432. }
  3433. }
  3434. //获取其他产品
  3435. //if len(list) > 0 {
  3436. // companyIdSlice := make([]string, 0)
  3437. // companyContractIdSlice := make([]string, 0)
  3438. // for _, v := range list {
  3439. // if v.Count > 1 {
  3440. // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  3441. // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
  3442. // }
  3443. // }
  3444. // if len(companyIdSlice) > 0 {
  3445. // companyIds := strings.Join(companyIdSlice, ",")
  3446. // companyContractIds := strings.Join(companyContractIdSlice, ",")
  3447. // otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
  3448. // //companyType
  3449. // if otherListErr != nil {
  3450. // br.Msg = "获取其他产品失败"
  3451. // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
  3452. // return
  3453. // }
  3454. //
  3455. // for _, otherCompanyContract := range otherList {
  3456. // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
  3457. // }
  3458. // }
  3459. //}
  3460. }
  3461. }
  3462. //未续约客户数
  3463. {
  3464. condition1 := condition
  3465. pars1 := pars
  3466. endDateTime, err := time.Parse(utils.FormatDate, endDate)
  3467. if err != nil {
  3468. br.Msg = "结束时间异常"
  3469. br.ErrMsg = "获取失败,Err:" + err.Error()
  3470. return
  3471. }
  3472. //选择的日期加一天的原因是因为:筛选条件是截止到时分秒的,如果要把选择的这一天也统计进去,那么需要在选择的结束日期基础上加上一天
  3473. tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
  3474. condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
  3475. pars1 = append(pars1, startDate, tryOutEndDate)
  3476. condition1 += ` AND a.operation = ? `
  3477. pars1 = append(pars1, "try_out")
  3478. condition1 += ` AND c.status not in ("永续","正式","关闭") `
  3479. //未续约这里只统计已经确定的
  3480. notRenewalCondition := condition1
  3481. notRenewalPars := pars1
  3482. notRenewalCondition += conditionAscribRaiTotal
  3483. notRenewalPars = append(notRenewalPars, parsAscribeRaiTotal)
  3484. total, err := models.GetIncrementalCompanyProductCountByOperationRecord(notRenewalCondition, notRenewalPars)
  3485. if err != nil && err.Error() != utils.ErrNoRow() {
  3486. br.Msg = "获取失败"
  3487. br.ErrMsg = "获取失败,Err:" + err.Error()
  3488. return
  3489. }
  3490. notRenewalCompanyTotal = total
  3491. condition1 += conditionAscribRai
  3492. pars1 = append(pars1, parsAscribeRai)
  3493. if dataType == "未续约客户" {
  3494. //统计数据
  3495. for _, v := range []string{"试用", "非试用"} {
  3496. totalCondition1 := condition1
  3497. totalPars1 := pars1
  3498. var tmpTotal int
  3499. if v == "试用" {
  3500. totalCondition1 += ` AND c.status = "试用" `
  3501. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  3502. if err != nil && err.Error() != utils.ErrNoRow() {
  3503. br.Msg = "获取失败"
  3504. br.ErrMsg = "获取失败,Err:" + err.Error()
  3505. return
  3506. }
  3507. notRenewalTryOut = tmpTotal
  3508. } else if v == "非试用" {
  3509. totalCondition1 += ` AND c.status IN ("冻结","流失") `
  3510. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  3511. if err != nil && err.Error() != utils.ErrNoRow() {
  3512. br.Msg = "获取失败"
  3513. br.ErrMsg = "获取失败,Err:" + err.Error()
  3514. return
  3515. }
  3516. notRenewalNotTryOut = tmpTotal
  3517. }
  3518. }
  3519. //列表数据数量
  3520. if tryOutType == "试用" {
  3521. condition1 += ` AND c.status = "试用" `
  3522. total = notRenewalTryOut
  3523. } else if tryOutType == "非试用" {
  3524. condition1 += ` AND c.status IN ("冻结","流失") `
  3525. total = notRenewalNotTryOut
  3526. }
  3527. //total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
  3528. //if err != nil && err.Error() != utils.ErrNoRow() {
  3529. // br.Msg = "获取失败"
  3530. // br.ErrMsg = "获取失败,Err:" + err.Error()
  3531. // return
  3532. //}
  3533. //分页total单独计算
  3534. total, err = models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
  3535. if err != nil && err.Error() != utils.ErrNoRow() {
  3536. br.Msg = "获取失败"
  3537. br.ErrMsg = "获取失败,Err:" + err.Error()
  3538. return
  3539. }
  3540. //列表页数据
  3541. tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
  3542. if err != nil {
  3543. br.Msg = "获取失败"
  3544. br.ErrMsg = "获取失败,Err:" + err.Error()
  3545. return
  3546. }
  3547. var ascribecompanyIds []int
  3548. for _, item := range tmpList {
  3549. endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
  3550. item.EndDate = endDateTime.Format(utils.FormatDate)
  3551. ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
  3552. }
  3553. //归因标签
  3554. mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
  3555. mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
  3556. for _, item := range tmpList {
  3557. item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3558. item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3559. item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  3560. if item.ProductId == utils.COMPANY_PRODUCT_RAI_ID { //权益客户的销售,按照创建时候对应的销售展示
  3561. item.SellerName = item.SellerNameInit
  3562. }
  3563. }
  3564. list = tmpList
  3565. dataTotal = total
  3566. //获取其他产品
  3567. //if len(list) > 0 {
  3568. // companyIdSlice := make([]string, 0)
  3569. // for _, v := range list {
  3570. // if v.Count > 1 {
  3571. // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
  3572. // }
  3573. // }
  3574. // if len(companyIdSlice) > 0 {
  3575. // companyIds := strings.Join(companyIdSlice, ",")
  3576. // otherList, otherListErr := models.GetOtherIncrementalCompanyListByOperationRecord(companyIds, condition1, pars1)
  3577. // //companyType
  3578. // if otherListErr != nil {
  3579. // br.Msg = "获取其他产品失败"
  3580. // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
  3581. // return
  3582. // }
  3583. //
  3584. // for _, otherCompanyContract := range otherList {
  3585. // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
  3586. // }
  3587. // }
  3588. //}
  3589. }
  3590. }
  3591. listLen := len(list)
  3592. if listLen == 0 {
  3593. list = make([]*models.IncrementalList, 0)
  3594. }
  3595. for i := 0; i < listLen; i++ {
  3596. item := list[i]
  3597. //新增试用不需要计算剩余日期
  3598. if dataType != "新增试用" {
  3599. //剩余可用天数
  3600. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  3601. endDateTime = endDateTime.AddDate(0, 0, 1)
  3602. sub := endDateTime.Sub(time.Now())
  3603. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  3604. list[i].ExpireDay = expireDay
  3605. }
  3606. //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
  3607. // for _, otherCompanyProduct := range otherCompanyProductList {
  3608. // //只有改产品不是同一产品,且并没有拼接过,那么才去拼接
  3609. // if item.ProductId != otherCompanyProduct.ProductId && strings.Contains(list[i].ProductName, "/") == false {
  3610. // list[i].ProductName += "/" + otherCompanyProduct.ProductName
  3611. // list[i].SellerName += "/" + otherCompanyProduct.SellerName
  3612. // list[i].StartDate += "/" + otherCompanyProduct.StartDate
  3613. // list[i].EndDate += "/" + otherCompanyProduct.EndDate
  3614. //
  3615. // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
  3616. // endDateTime = endDateTime.AddDate(0, 0, 1)
  3617. // sub := endDateTime.Sub(time.Now())
  3618. // //if sub < 0 {
  3619. // // sub = 0
  3620. // //}
  3621. // tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  3622. // list[i].ExpireDay += "/" + tmpExpireDay
  3623. // }
  3624. // }
  3625. //}
  3626. //if company2
  3627. }
  3628. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  3629. resp := response.IncrementalCompanyListResp{
  3630. Paging: page,
  3631. List: list,
  3632. TrialTotal: trialTotal,
  3633. NewCompanyTotal: newCompanyTotal,
  3634. RenewalCompanyTotal: renewalCompanyTotal,
  3635. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  3636. NotRenewalTryOut: notRenewalTryOut,
  3637. NotRenewalNotTryOut: notRenewalNotTryOut,
  3638. }
  3639. //导出excel
  3640. if isExport {
  3641. IncrementalCompanyListExport(this, dataType, resp, br)
  3642. return
  3643. }
  3644. br.Ret = 200
  3645. br.Success = true
  3646. br.Msg = "获取成功"
  3647. br.Data = resp
  3648. }
  3649. // IncrementalCompanyListExport 导出增量客户数据报表excel
  3650. func IncrementalCompanyListExport(this *StatisticReportController, dataType string, resp response.IncrementalCompanyListResp, br *models.BaseResponse) {
  3651. dir, err := os.Executable()
  3652. exPath := filepath.Dir(dir)
  3653. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  3654. xlsxFile := xlsx.NewFile()
  3655. if err != nil {
  3656. br.Msg = "生成文件失败"
  3657. br.ErrMsg = "生成文件失败"
  3658. return
  3659. }
  3660. style := xlsx.NewStyle()
  3661. alignment := xlsx.Alignment{
  3662. Horizontal: "center",
  3663. Vertical: "center",
  3664. WrapText: true,
  3665. }
  3666. style.Alignment = alignment
  3667. style.ApplyAlignment = true
  3668. sheel, err := xlsxFile.AddSheet("增量客户数据")
  3669. if err != nil {
  3670. br.Msg = "新增Sheet失败"
  3671. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  3672. return
  3673. }
  3674. sheel.SetColWidth(0, 0, 30)
  3675. sheel.SetColWidth(1, 1, 15)
  3676. sheel.SetColWidth(2, 2, 15)
  3677. sheel.SetColWidth(3, 3, 18)
  3678. sheel.SetColWidth(4, 4, 40)
  3679. sheel.SetColWidth(5, 5, 18)
  3680. //统计数据
  3681. statisticRow := sheel.AddRow()
  3682. cell1 := statisticRow.AddCell()
  3683. cell1.SetStyle(style)
  3684. cell1.SetValue(fmt.Sprint("新增试用客户数:", resp.TrialTotal))
  3685. cell2 := statisticRow.AddCell()
  3686. cell2.SetStyle(style)
  3687. cell2.SetValue(fmt.Sprint("新签客户数:", resp.NewCompanyTotal))
  3688. cell3 := statisticRow.AddCell()
  3689. cell3.SetStyle(style)
  3690. cell3.SetValue(fmt.Sprint("续约客户数:", resp.RenewalCompanyTotal))
  3691. cell4 := statisticRow.AddCell()
  3692. cell4.SetStyle(style)
  3693. cell4.SetValue(fmt.Sprint("未续约客户数:", resp.NotRenewalCompanyTotal))
  3694. //表头
  3695. titleRow := sheel.AddRow()
  3696. cellName := titleRow.AddCell()
  3697. cellName.SetStyle(style)
  3698. cellName.SetValue("客户名称")
  3699. cellProName := titleRow.AddCell()
  3700. cellProName.SetStyle(style)
  3701. cellProName.SetValue("客户类型")
  3702. cellSellerName := titleRow.AddCell()
  3703. cellSellerName.SetStyle(style)
  3704. cellSellerName.SetValue("所属销售")
  3705. permissionMap := make(map[int][]string)
  3706. tmpPermissionMap := make(map[int]map[string][]string)
  3707. companyContractIdList := make([]string, 0)
  3708. for _, v := range resp.List {
  3709. companyContractIdList = append(companyContractIdList, fmt.Sprint(v.CompanyContractId))
  3710. }
  3711. if dataType == "新签客户" || dataType == "续约客户" {
  3712. cellMoney := titleRow.AddCell()
  3713. cellMoney.SetStyle(style)
  3714. cellMoney.SetValue("合同金额")
  3715. cellPermission := titleRow.AddCell()
  3716. cellPermission.SetStyle(style)
  3717. cellPermission.SetValue("合同品种")
  3718. //这么大费周章的目的是为了:权益的品种存在主观、客观的区分,如果一个品种既存在主观,又存在客观,那么就展示品种名称,否则就要列出品种名称+主、客观类型
  3719. if len(companyContractIdList) > 0 {
  3720. list, tmpErr := company.GetCompanyContractPermissionListByContractIds(strings.Join(companyContractIdList, ","))
  3721. if tmpErr != nil {
  3722. err = tmpErr
  3723. return
  3724. }
  3725. for _, v := range list {
  3726. tmpPermissionNameMap, ok := tmpPermissionMap[v.CompanyContractId]
  3727. if ok {
  3728. tmpPermissionNameList, ok2 := tmpPermissionNameMap[v.ChartPermissionName]
  3729. if ok2 {
  3730. tmpPermissionNameList = append(tmpPermissionNameList, v.PermissionRemark)
  3731. } else {
  3732. tmpPermissionNameList = []string{v.PermissionRemark}
  3733. }
  3734. tmpPermissionNameMap[v.ChartPermissionName] = tmpPermissionNameList
  3735. } else {
  3736. tmpPermissionNameMap = make(map[string][]string)
  3737. tmpPermissionNameMap[v.ChartPermissionName] = []string{v.PermissionRemark}
  3738. }
  3739. tmpPermissionMap[v.CompanyContractId] = tmpPermissionNameMap
  3740. }
  3741. }
  3742. }
  3743. for companyContractId, tmpPermissionNameMap := range tmpPermissionMap {
  3744. tmpPermissionName := ``
  3745. tmpPermissionList := []string{}
  3746. for tmpChartPermissionName, tmpChartPermissionNameList := range tmpPermissionNameMap {
  3747. if len(tmpChartPermissionNameList) > 1 {
  3748. tmpPermissionName = tmpChartPermissionName
  3749. } else {
  3750. tmpPermissionName = tmpChartPermissionNameList[0]
  3751. }
  3752. tmpPermissionList = append(tmpPermissionList, tmpPermissionName)
  3753. }
  3754. permissionMap[companyContractId] = tmpPermissionList
  3755. }
  3756. cellTime := titleRow.AddCell()
  3757. cellTime.SetStyle(style)
  3758. switch dataType {
  3759. case "新增试用":
  3760. cellTime.SetValue("新增时间")
  3761. case "新签客户":
  3762. cellTime.SetValue("签约时间")
  3763. case "续约客户":
  3764. cellTime.SetValue("续约时间")
  3765. case "未续约客户":
  3766. cellTime.SetValue("最近合同到期时间")
  3767. cellAscribeContent := titleRow.AddCell()
  3768. cellAscribeContent.SetStyle(style)
  3769. cellAscribeContent.SetValue("不续约归因")
  3770. cellContent := titleRow.AddCell()
  3771. cellContent.SetStyle(style)
  3772. cellContent.SetValue("详细原因")
  3773. }
  3774. for _, v := range resp.List {
  3775. dataRow := sheel.AddRow()
  3776. dataRow.SetHeight(20)
  3777. cellDataName := dataRow.AddCell()
  3778. cellDataName.SetStyle(style)
  3779. cellDataName.SetValue(v.CompanyName)
  3780. cellDataProName := dataRow.AddCell()
  3781. cellDataProName.SetStyle(style)
  3782. cellDataProName.SetValue(v.ProductName)
  3783. cellDataSellerName := dataRow.AddCell()
  3784. cellDataSellerName.SetStyle(style)
  3785. cellDataSellerName.SetValue(v.SellerName)
  3786. if dataType == "新签客户" || dataType == "续约客户" {
  3787. cellDataMoney := dataRow.AddCell()
  3788. cellDataMoney.SetStyle(style)
  3789. cellDataMoney.SetValue(v.Money)
  3790. cellDataPermission := dataRow.AddCell()
  3791. cellDataPermission.SetStyle(style)
  3792. if permissionStrList, ok := permissionMap[v.CompanyContractId]; ok {
  3793. cellDataPermission.SetValue(strings.Join(permissionStrList, ","))
  3794. }
  3795. }
  3796. cellDataTime := dataRow.AddCell()
  3797. cellDataTime.SetStyle(style)
  3798. switch dataType {
  3799. case "新增试用":
  3800. cellDataTime.SetValue(v.CreateTime)
  3801. case "新签客户":
  3802. cellDataTime.SetValue(v.StartDate)
  3803. case "续约客户":
  3804. cellDataTime.SetValue(v.StartDate)
  3805. case "未续约客户":
  3806. cellDataTime.SetValue(v.EndDate)
  3807. cellAscribeContent := dataRow.AddCell()
  3808. cellAscribeContent.SetStyle(style)
  3809. cellAscribeContent.SetValue(v.AscribeContent)
  3810. cellContent := dataRow.AddCell()
  3811. cellContent.SetStyle(style)
  3812. cellContent.SetValue(v.Content)
  3813. }
  3814. }
  3815. err = xlsxFile.Save(downLoadnFilePath)
  3816. if err != nil {
  3817. br.Msg = "保存文件失败"
  3818. br.ErrMsg = "保存文件失败"
  3819. return
  3820. }
  3821. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  3822. downloadFileName := "增量客户数据_" + randStr + ".xlsx"
  3823. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  3824. defer func() {
  3825. os.Remove(downLoadnFilePath)
  3826. }()
  3827. br.Ret = 200
  3828. br.Success = true
  3829. br.Msg = "导出成功"
  3830. }
  3831. // IncrementalCompanyListExport
  3832. // @Title 增量客户数据导出
  3833. // @Description 增量客户数据导出接口
  3834. // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
  3835. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  3836. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  3837. // @Param StartDate query string false "开始日期"
  3838. // @Param EndDate query string false "结束日期"
  3839. // @Param DataType query string false "报表类型,枚举值:`新增试用`,`新签客户`,`续约客户`,`未续约客户`"
  3840. // @Success 200 Ret=200 导出成功
  3841. // @router /incremental_company/export [get]
  3842. func (this *StatisticReportController) IncrementalCompanyListExport() {
  3843. br := new(models.BaseResponse).Init()
  3844. defer func() {
  3845. this.Data["json"] = br
  3846. this.ServeJSON()
  3847. }()
  3848. sysUser := this.SysUser
  3849. if sysUser == nil {
  3850. br.Msg = "请登录"
  3851. br.ErrMsg = "请登录,SysUser Is Empty"
  3852. br.Ret = 408
  3853. return
  3854. }
  3855. adminId := this.GetString("AdminId")
  3856. regionType := this.GetString("RegionType")
  3857. companyType := this.GetString("CompanyType")
  3858. dataType := this.GetString("DataType")
  3859. startDate := this.GetString("StartDate")
  3860. endDate := this.GetString("EndDate")
  3861. if startDate == "" || endDate == "" {
  3862. br.Msg = "获取失败,开始日期或结束日期未传"
  3863. br.ErrMsg = "获取失败,开始日期或结束日期未传"
  3864. return
  3865. }
  3866. var startSize int
  3867. currentIndex := 1
  3868. pageSize := 10000
  3869. startSize = utils.StartIndex(currentIndex, pageSize)
  3870. var condition string
  3871. var pars []interface{}
  3872. //条件
  3873. if adminId != "" {
  3874. condition += ` AND c.seller_id in (` + adminId + `) `
  3875. //pars = append(pars, adminId)
  3876. } else {
  3877. //根据当前角色来获取查询条件
  3878. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  3879. }
  3880. if regionType != "" {
  3881. condition += ` AND b.region_type = ? `
  3882. pars = append(pars, regionType)
  3883. }
  3884. switch companyType {
  3885. case "ficc":
  3886. condition += ` AND c.product_id = ? `
  3887. pars = append(pars, 1)
  3888. case "权益":
  3889. condition += ` AND c.product_id = ? `
  3890. pars = append(pars, 2)
  3891. case "":
  3892. default:
  3893. br.Msg = "获取失败,客户类型异常"
  3894. br.ErrMsg = "获取失败,客户类型异常"
  3895. return
  3896. }
  3897. var list []*models.IncrementalList
  3898. //moreListMap := make(map[int][]*models.IncrementalList)
  3899. var trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  3900. //试用客户数
  3901. {
  3902. condition1 := condition
  3903. pars1 := pars
  3904. condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
  3905. pars1 = append(pars1, startDate, endDate)
  3906. total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  3907. if err != nil && err.Error() != utils.ErrNoRow() {
  3908. br.Msg = "获取失败"
  3909. br.ErrMsg = "获取失败,Err:" + err.Error()
  3910. return
  3911. }
  3912. trialTotal = total
  3913. if dataType == "新增试用" {
  3914. //列表页数据
  3915. tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
  3916. if err != nil {
  3917. br.Msg = "获取失败"
  3918. br.ErrMsg = "获取失败,Err:" + err.Error()
  3919. return
  3920. }
  3921. list = tmpList
  3922. }
  3923. }
  3924. //新签客户数
  3925. {
  3926. condition1 := condition
  3927. pars1 := pars
  3928. condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
  3929. pars1 = append(pars1, startDate, endDate)
  3930. condition1 += ` AND a.contract_type = ? `
  3931. pars1 = append(pars1, "新签合同")
  3932. total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
  3933. if err != nil && err.Error() != utils.ErrNoRow() {
  3934. br.Msg = "获取失败"
  3935. br.ErrMsg = "获取失败,Err:" + err.Error()
  3936. return
  3937. }
  3938. newCompanyTotal = total
  3939. if dataType == "新签客户" {
  3940. //列表页数据
  3941. tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
  3942. if err != nil {
  3943. br.Msg = "获取失败"
  3944. br.ErrMsg = "获取失败,Err:" + err.Error()
  3945. return
  3946. }
  3947. list = tmpList
  3948. }
  3949. }
  3950. //续约客户数
  3951. {
  3952. condition1 := condition
  3953. pars1 := pars
  3954. condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
  3955. pars1 = append(pars1, startDate, endDate)
  3956. condition1 += ` AND a.contract_type = ? `
  3957. pars1 = append(pars1, "续约合同")
  3958. total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
  3959. if err != nil && err.Error() != utils.ErrNoRow() {
  3960. br.Msg = "获取失败"
  3961. br.ErrMsg = "获取失败,Err:" + err.Error()
  3962. return
  3963. }
  3964. renewalCompanyTotal = total
  3965. if dataType == "续约客户" {
  3966. //列表页数据
  3967. tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
  3968. if err != nil {
  3969. br.Msg = "获取失败"
  3970. br.ErrMsg = "获取失败,Err:" + err.Error()
  3971. return
  3972. }
  3973. list = tmpList
  3974. }
  3975. }
  3976. //未续约客户数
  3977. {
  3978. condition1 := condition
  3979. pars1 := pars
  3980. endDateTime, err := time.Parse(utils.FormatDate, endDate)
  3981. if err != nil {
  3982. br.Msg = "结束时间异常"
  3983. br.ErrMsg = "获取失败,Err:" + err.Error()
  3984. return
  3985. }
  3986. //选择的日期加一天的原因是因为:筛选条件是截止到时分秒的,如果要把选择的这一天也统计进去,那么需要在选择的结束日期基础上加上一天
  3987. tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
  3988. condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
  3989. pars1 = append(pars1, startDate, tryOutEndDate)
  3990. condition1 += ` AND a.operation = ? `
  3991. pars1 = append(pars1, "try_out")
  3992. condition1 += ` AND c.status not in ("永续","正式") `
  3993. total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  3994. if err != nil && err.Error() != utils.ErrNoRow() {
  3995. br.Msg = "获取失败"
  3996. br.ErrMsg = "获取失败,Err:" + err.Error()
  3997. return
  3998. }
  3999. notRenewalCompanyTotal = total
  4000. if dataType == "未续约客户" {
  4001. //列表页数据
  4002. tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
  4003. if err != nil {
  4004. br.Msg = "获取失败"
  4005. br.ErrMsg = "获取失败,Err:" + err.Error()
  4006. return
  4007. }
  4008. for _, item := range tmpList {
  4009. endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
  4010. item.EndDate = endDateTime.Format(utils.FormatDate)
  4011. }
  4012. list = tmpList
  4013. }
  4014. }
  4015. listLen := len(list)
  4016. for i := 0; i < listLen; i++ {
  4017. item := list[i]
  4018. //新增试用不需要计算剩余日期
  4019. if dataType != "新增试用" {
  4020. //剩余可用天数
  4021. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  4022. endDateTime = endDateTime.AddDate(0, 0, 1)
  4023. sub := endDateTime.Sub(time.Now())
  4024. expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
  4025. list[i].ExpireDay = expireDay
  4026. }
  4027. }
  4028. dir, err := os.Executable()
  4029. exPath := filepath.Dir(dir)
  4030. downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  4031. xlsxFile := xlsx.NewFile()
  4032. if err != nil {
  4033. br.Msg = "生成文件失败"
  4034. br.ErrMsg = "生成文件失败"
  4035. return
  4036. }
  4037. style := xlsx.NewStyle()
  4038. alignment := xlsx.Alignment{
  4039. Horizontal: "center",
  4040. Vertical: "center",
  4041. WrapText: true,
  4042. }
  4043. style.Alignment = alignment
  4044. style.ApplyAlignment = true
  4045. sheel, err := xlsxFile.AddSheet("增量客户数据")
  4046. if err != nil {
  4047. br.Msg = "新增Sheet失败"
  4048. br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
  4049. return
  4050. }
  4051. sheel.SetColWidth(0, 0, 30)
  4052. sheel.SetColWidth(1, 1, 15)
  4053. sheel.SetColWidth(2, 2, 15)
  4054. sheel.SetColWidth(3, 3, 18)
  4055. //统计数据
  4056. statisticRow := sheel.AddRow()
  4057. cell1 := statisticRow.AddCell()
  4058. cell1.SetStyle(style)
  4059. cell1.SetValue(fmt.Sprint("新增试用客户数:", trialTotal))
  4060. cell2 := statisticRow.AddCell()
  4061. cell2.SetStyle(style)
  4062. cell2.SetValue(fmt.Sprint("新签客户数:", newCompanyTotal))
  4063. cell3 := statisticRow.AddCell()
  4064. cell3.SetStyle(style)
  4065. cell3.SetValue(fmt.Sprint("续约客户数:", renewalCompanyTotal))
  4066. cell4 := statisticRow.AddCell()
  4067. cell4.SetStyle(style)
  4068. cell4.SetValue(fmt.Sprint("未续约客户数:", notRenewalCompanyTotal))
  4069. //表头
  4070. titleRow := sheel.AddRow()
  4071. cellName := titleRow.AddCell()
  4072. cellName.SetStyle(style)
  4073. cellName.SetValue("客户名称")
  4074. cellProName := titleRow.AddCell()
  4075. cellProName.SetStyle(style)
  4076. cellProName.SetValue("客户类型")
  4077. cellSellerName := titleRow.AddCell()
  4078. cellSellerName.SetStyle(style)
  4079. cellSellerName.SetValue("所属销售")
  4080. cellTime := titleRow.AddCell()
  4081. cellTime.SetStyle(style)
  4082. switch dataType {
  4083. case "新增试用":
  4084. cellTime.SetValue("新增时间")
  4085. case "新签客户":
  4086. cellTime.SetValue("签约时间")
  4087. case "续约客户":
  4088. cellTime.SetValue("续约时间")
  4089. case "未续约客户":
  4090. cellTime.SetValue("最近合同到期时间")
  4091. }
  4092. for _, v := range list {
  4093. dataRow := sheel.AddRow()
  4094. dataRow.SetHeight(20)
  4095. cellDataName := dataRow.AddCell()
  4096. cellDataName.SetStyle(style)
  4097. cellDataName.SetValue(v.CompanyName)
  4098. cellDataProName := dataRow.AddCell()
  4099. cellDataProName.SetStyle(style)
  4100. cellDataProName.SetValue(v.ProductName)
  4101. cellDataSellerName := dataRow.AddCell()
  4102. cellDataSellerName.SetStyle(style)
  4103. cellDataSellerName.SetValue(v.SellerName)
  4104. cellDataTime := dataRow.AddCell()
  4105. cellDataTime.SetStyle(style)
  4106. switch dataType {
  4107. case "新增试用":
  4108. cellDataTime.SetValue(v.CreateTime)
  4109. case "新签客户":
  4110. cellDataTime.SetValue(v.StartDate)
  4111. case "续约客户":
  4112. cellDataTime.SetValue(v.StartDate)
  4113. case "未续约客户":
  4114. cellDataTime.SetValue(v.EndDate)
  4115. }
  4116. }
  4117. err = xlsxFile.Save(downLoadnFilePath)
  4118. if err != nil {
  4119. br.Msg = "保存文件失败"
  4120. br.ErrMsg = "保存文件失败"
  4121. return
  4122. }
  4123. randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  4124. downloadFileName := "增量客户数据_" + randStr + ".xlsx"
  4125. this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  4126. defer func() {
  4127. os.Remove(downLoadnFilePath)
  4128. }()
  4129. br.Ret = 200
  4130. br.Success = true
  4131. br.Msg = "导出成功"
  4132. }
  4133. // MoreRenewReason 未续约说明列表
  4134. // @Title 未续约说明列表
  4135. // @Description 未续约说明列表
  4136. // @Param CompanyId query string true "客户id"
  4137. // @Param ProductId query string true "产品id"
  4138. // @Success 200 {object} response.MoreRenewReasonResp
  4139. // @router /more_renew_reason [get]
  4140. func (this *StatisticReportController) MoreRenewReason() {
  4141. br := new(models.BaseResponse).Init()
  4142. defer func() {
  4143. this.Data["json"] = br
  4144. this.ServeJSON()
  4145. }()
  4146. sysUser := this.SysUser
  4147. if sysUser == nil {
  4148. br.Msg = "请登录"
  4149. br.ErrMsg = "请登录,SysUser Is Empty"
  4150. br.Ret = 408
  4151. return
  4152. }
  4153. CompanyId := this.GetString("CompanyId")
  4154. ProductId := this.GetString("ProductId")
  4155. renewalReason, err := models.GetMoreRenewalReason(CompanyId, ProductId)
  4156. if err != nil {
  4157. br.Msg = "获取失败"
  4158. br.ErrMsg = "获取失败,Err:" + err.Error()
  4159. return
  4160. }
  4161. resp := make([]response.MoreRenewReasonResp, len(renewalReason))
  4162. for i, reason := range renewalReason {
  4163. createDate := reason.CreateTime.Format("2006.01.02")
  4164. resp[i].RenewalReason = reason.RenewalReason
  4165. resp[i].RenewalTodo = reason.RenewalTodo
  4166. resp[i].CreateTime = createDate
  4167. resp[i].ExpirationTimeExceeded = strconv.Itoa(reason.ExpirationTimeExceeded)
  4168. }
  4169. br.Ret = 200
  4170. br.Success = true
  4171. br.Msg = "获取成功"
  4172. br.Data = resp
  4173. }
  4174. // StackCompanyReport
  4175. // @Title 获取存量客户统计数据
  4176. // @Description 获取存量客户统计数据接口
  4177. // @Param ProductId query string true "产品id"
  4178. // @Param Date query string true "日期,格式:2022-04-06"
  4179. // @Success 200 {object} statistic_report.CompanyReportRecordResp
  4180. // @router /report/stack_company [get]
  4181. func (this *StatisticReportController) StackCompanyReport() {
  4182. br := new(models.BaseResponse).Init()
  4183. defer func() {
  4184. this.Data["json"] = br
  4185. this.ServeJSON()
  4186. }()
  4187. sysUser := this.SysUser
  4188. if sysUser == nil {
  4189. br.Msg = "请登录"
  4190. br.ErrMsg = "请登录,SysUser Is Empty"
  4191. br.Ret = 408
  4192. return
  4193. }
  4194. date := this.GetString("Date")
  4195. productId, _ := this.GetInt("ProductId", 1)
  4196. //获取列表
  4197. companyReportDataMapList, firstDate, err := statistic_report.GetDateData(date, productId)
  4198. if err != nil {
  4199. br.Msg = "数据异常"
  4200. br.ErrMsg = "数据异常,Err:" + err.Error()
  4201. return
  4202. }
  4203. //获取销售人员分组数据
  4204. var group []services.AdminGroup
  4205. var groupIdRelationMap map[int]int
  4206. var groupMap map[int][]*roadshow.Researcher
  4207. if productId == 1 {
  4208. group, groupIdRelationMap, err = services.GetFiccSystemGroup()
  4209. if err != nil {
  4210. br.Msg = "获取信息失败!"
  4211. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4212. return
  4213. }
  4214. researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
  4215. if tmpErr != nil {
  4216. err = tmpErr
  4217. }
  4218. groupMap = make(map[int][]*roadshow.Researcher)
  4219. for _, v := range researcherList {
  4220. if v.RoleTypeCode == "ficc_admin" {
  4221. findItems := groupMap[1]
  4222. findItems = append(findItems, v)
  4223. groupMap[1] = findItems
  4224. } else {
  4225. if findItems, ok := groupMap[v.GroupId]; ok {
  4226. findItems = append(findItems, v)
  4227. groupMap[v.GroupId] = findItems
  4228. } else {
  4229. findItems = append(findItems, v)
  4230. groupMap[v.GroupId] = findItems
  4231. }
  4232. }
  4233. }
  4234. } else {
  4235. group, groupIdRelationMap, err = services.GetRaiSystemGroup()
  4236. if err != nil {
  4237. br.Msg = "获取信息失败!"
  4238. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4239. return
  4240. }
  4241. researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
  4242. if tmpErr != nil {
  4243. err = tmpErr
  4244. }
  4245. groupMap = make(map[int][]*roadshow.Researcher)
  4246. for _, v := range researcherList {
  4247. if v.RoleTypeCode == "rai_admin" {
  4248. findItems := groupMap[1]
  4249. findItems = append(findItems, v)
  4250. groupMap[1] = findItems
  4251. } else {
  4252. if findItems, ok := groupMap[v.GroupId]; ok {
  4253. findItems = append(findItems, v)
  4254. groupMap[v.GroupId] = findItems
  4255. } else {
  4256. findItems = append(findItems, v)
  4257. groupMap[v.GroupId] = findItems
  4258. }
  4259. }
  4260. }
  4261. }
  4262. //数据处理
  4263. groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
  4264. allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
  4265. companyReportRecordResp := statistic_report.CompanyReportRecordResp{
  4266. List: groupReportRecordList,
  4267. CompanyReportRecordNumList: allCompanyReportRecordNum,
  4268. }
  4269. startDateIndexList := make(map[int]string) //开始时间间隔map
  4270. endDateIndexList := make(map[int]string) //结束时间间隔map
  4271. tmpAllTryOutNumMap := make(map[int]int)
  4272. tmpAllFormalNumMap := make(map[int]int)
  4273. tmpAllActiveNumMap := make(map[int]int)
  4274. tmpAllAllActiveNumMap := make(map[int]int)
  4275. tmpAllNoIncrementalActiveNumMap := make(map[int]int)
  4276. tmpAllTryStagePushMap := make(map[int]int)
  4277. tmpAllTryStageFollowMap := make(map[int]int)
  4278. tmpAllTryStageReadyMap := make(map[int]int)
  4279. tmpAllTryStageInitMap := make(map[int]int)
  4280. for _, v := range group {
  4281. v.ResearcherList = groupMap[v.GroupId]
  4282. tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
  4283. tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
  4284. tmpGroupTryOutNumMap := make(map[int]int)
  4285. tmpGroupFormalNumMap := make(map[int]int)
  4286. tmpGroupActiveNumMap := make(map[int]int)
  4287. tmpGroupAllActiveNumMap := make(map[int]int)
  4288. tmpGroupNoIncrementalActiveNumMap := make(map[int]int)
  4289. tmpGroupTryStagePushMap := make(map[int]int)
  4290. tmpGroupTryStageFollowMap := make(map[int]int)
  4291. tmpGroupTryStageReadyMap := make(map[int]int)
  4292. tmpGroupTryStageInitMap := make(map[int]int)
  4293. for _, researcher := range groupMap[v.GroupId] {
  4294. //组内研究员数据
  4295. //每个区间的数据
  4296. tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
  4297. for index, adminData := range companyReportDataMapList {
  4298. startDateIndexList[index] = adminData.StartDate
  4299. endDateIndexList[index] = adminData.EndDate
  4300. var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
  4301. var tmpTryStagePushNum, tmpTryStageFollowNum, tmpTryStageReadyNum, tmpTryStageInitNum int
  4302. if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
  4303. tmpTryOutNum = num
  4304. }
  4305. if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
  4306. tmpFormalNum = num
  4307. }
  4308. if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
  4309. tmpActiveStatus = num
  4310. }
  4311. if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
  4312. tmpAllActiveStatus = num
  4313. }
  4314. if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
  4315. tmpNoIncrementalActiveStatus = num
  4316. }
  4317. // 每个用户的试用标签统计 推进-跟踪-预备-未分类
  4318. if num, ok := adminData.TryStagePushNum[researcher.AdminId]; ok {
  4319. tmpTryStagePushNum = num
  4320. }
  4321. if num, ok := adminData.TryStageFollowNum[researcher.AdminId]; ok {
  4322. tmpTryStageFollowNum = num
  4323. }
  4324. if num, ok := adminData.TryStageReadyNum[researcher.AdminId]; ok {
  4325. tmpTryStageReadyNum = num
  4326. }
  4327. if num, ok := adminData.TryStageInitNum[researcher.AdminId]; ok {
  4328. tmpTryStageInitNum = num
  4329. }
  4330. tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
  4331. TryOutNum: tmpTryOutNum,
  4332. FormalNum: tmpFormalNum,
  4333. ActiveNum: tmpActiveStatus,
  4334. AllActiveNum: tmpAllActiveStatus,
  4335. NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
  4336. StartDate: adminData.StartDate,
  4337. EndDate: adminData.EndDate,
  4338. TryStagePushNum: tmpTryStagePushNum,
  4339. TryStageFollowNum: tmpTryStageFollowNum,
  4340. TryStageReadyNum: tmpTryStageReadyNum,
  4341. TryStageInitNum: tmpTryStageInitNum,
  4342. }
  4343. tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)
  4344. //组内数据汇总
  4345. tmpGroupTryOutNumMap[index] += tmpTryOutNum
  4346. tmpGroupFormalNumMap[index] += tmpFormalNum
  4347. tmpGroupActiveNumMap[index] += tmpActiveStatus
  4348. tmpGroupAllActiveNumMap[index] += tmpActiveStatus
  4349. tmpGroupNoIncrementalActiveNumMap[index] += tmpActiveStatus
  4350. tmpGroupTryStagePushMap[index] += tmpTryStagePushNum
  4351. tmpGroupTryStageFollowMap[index] += tmpTryStageFollowNum
  4352. tmpGroupTryStageReadyMap[index] += tmpTryStageReadyNum
  4353. tmpGroupTryStageInitMap[index] += tmpTryStageInitNum
  4354. //总数据汇总
  4355. tmpAllTryOutNumMap[index] += tmpTryOutNum
  4356. tmpAllFormalNumMap[index] += tmpFormalNum
  4357. tmpAllActiveNumMap[index] += tmpActiveStatus
  4358. tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
  4359. tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
  4360. // 总数据试用标签数据汇总
  4361. tmpAllTryStagePushMap[index] += tmpTryStagePushNum
  4362. tmpAllTryStageFollowMap[index] += tmpTryStageFollowNum
  4363. tmpAllTryStageReadyMap[index] += tmpTryStageReadyNum
  4364. tmpAllTryStageInitMap[index] += tmpTryStageInitNum
  4365. }
  4366. tmpAdminReportRecord := statistic_report.AdminReportRecord{
  4367. Name: researcher.RealName,
  4368. AdminId: researcher.AdminId,
  4369. CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
  4370. }
  4371. tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
  4372. }
  4373. for i := 0; i < len(tmpGroupActiveNumMap); i++ {
  4374. tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
  4375. TryOutNum: tmpGroupTryOutNumMap[i],
  4376. FormalNum: tmpGroupFormalNumMap[i],
  4377. ActiveNum: tmpGroupActiveNumMap[i],
  4378. AllActiveNum: tmpGroupAllActiveNumMap[i],
  4379. NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
  4380. StartDate: startDateIndexList[i],
  4381. EndDate: endDateIndexList[i],
  4382. TryStagePushNum: tmpGroupTryStagePushMap[i],
  4383. TryStageFollowNum: tmpGroupTryStageFollowMap[i],
  4384. TryStageReadyNum: tmpGroupTryStageReadyMap[i],
  4385. TryStageInitNum: tmpGroupTryStageInitMap[i],
  4386. }
  4387. tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
  4388. }
  4389. groupReportRecord := statistic_report.GroupReportRecord{
  4390. Item: tmpGroupAdminReportRecord,
  4391. Name: v.GroupName,
  4392. GroupId: v.GroupId,
  4393. CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
  4394. }
  4395. groupReportRecordList = append(groupReportRecordList, groupReportRecord)
  4396. }
  4397. //总体汇总数据
  4398. for i := 0; i < len(tmpAllFormalNumMap); i++ {
  4399. tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
  4400. TryOutNum: tmpAllTryOutNumMap[i],
  4401. FormalNum: tmpAllFormalNumMap[i],
  4402. ActiveNum: tmpAllActiveNumMap[i],
  4403. AllActiveNum: tmpAllAllActiveNumMap[i],
  4404. NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
  4405. StartDate: startDateIndexList[i],
  4406. EndDate: endDateIndexList[i],
  4407. TryStagePushNum: tmpAllTryStagePushMap[i],
  4408. TryStageFollowNum: tmpAllTryStageFollowMap[i],
  4409. TryStageReadyNum: tmpAllTryStageReadyMap[i],
  4410. TryStageInitNum: tmpAllTryStageInitMap[i],
  4411. }
  4412. allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
  4413. }
  4414. companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
  4415. tmpList := groupReportRecordList
  4416. //因为RoleTypeCode不一样,所以需要重新从数据库取数据
  4417. adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
  4418. adminGroupId := adminInfo.GroupId
  4419. if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
  4420. adminGroupId = tmpGroupId
  4421. }
  4422. switch adminInfo.RoleTypeCode {
  4423. case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
  4424. for index, v := range tmpList {
  4425. //如果不是同一个分组,那么就移除该分组下的人员数据
  4426. if v.GroupId != adminGroupId {
  4427. tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
  4428. } else {
  4429. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  4430. }
  4431. }
  4432. companyReportRecordResp.List = tmpList
  4433. case utils.ROLE_TYPE_CODE_RAI_GROUP:
  4434. for index, v := range tmpList {
  4435. //如果不是同一个分组,那么就移除该分组下的人员数据
  4436. if v.GroupId != adminGroupId {
  4437. tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
  4438. } else {
  4439. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  4440. }
  4441. }
  4442. companyReportRecordResp.List = tmpList
  4443. case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
  4444. //管理员、超管看全部数据
  4445. companyReportRecordResp.List = tmpList
  4446. }
  4447. br.Ret = 200
  4448. br.Success = true
  4449. br.Msg = "获取成功"
  4450. br.Data = companyReportRecordResp
  4451. }
  4452. // IncrementalCompanyReport
  4453. // @Title 获取增量客户统计数据
  4454. // @Description 获取增量客户统计数据接口
  4455. // @Param DataType query string true "枚举值:week、month、time_interval"
  4456. // @Param ProductId query int true "客户类型 ficc:1 权益:2"
  4457. // @Param StartDate query string true "开始日期,格式:2022-04-06"
  4458. // @Param EndDate query string true "结束日期,格式:2022-04-06"
  4459. // @Success 200 {object} statistic_report.CompanyReportRecordResp
  4460. // @router /report/incremental_company [get]
  4461. func (this *StatisticReportController) IncrementalCompanyReport() {
  4462. br := new(models.BaseResponse).Init()
  4463. defer func() {
  4464. this.Data["json"] = br
  4465. this.ServeJSON()
  4466. }()
  4467. sysUser := this.SysUser
  4468. if sysUser == nil {
  4469. br.Msg = "请登录"
  4470. br.ErrMsg = "请登录,SysUser Is Empty"
  4471. br.Ret = 408
  4472. return
  4473. }
  4474. dataType := this.GetString("DataType")
  4475. productId, _ := this.GetInt("ProductId", 1)
  4476. startDate := this.GetString("StartDate")
  4477. endDate := this.GetString("EndDate")
  4478. var companyReportDataMapList []statistic_report.CompanyReportDataMap
  4479. var err error
  4480. var firstDate time.Time
  4481. switch dataType {
  4482. //获取列表
  4483. case "week":
  4484. nowWeekMonday := utils.GetNowWeekMonday() //本周周一
  4485. //companyReportDataMapList, firstDate, err = statistic_report.GetWeekData()
  4486. companyReportDataMapList, firstDate, err = statistic_report.GetWeekDataNum(nowWeekMonday, productId, 6)
  4487. if err != nil {
  4488. br.Msg = "数据异常"
  4489. br.ErrMsg = "数据异常,Err:" + err.Error()
  4490. return
  4491. }
  4492. case "month":
  4493. nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
  4494. //companyReportDataMapList, firstDate, err = statistic_report.GetMonthData()
  4495. companyReportDataMapList, firstDate, err = statistic_report.GetMonthDataNum(nowMonthFirstDay, productId, 6)
  4496. if err != nil {
  4497. br.Msg = "数据异常"
  4498. br.ErrMsg = "数据异常,Err:" + err.Error()
  4499. return
  4500. }
  4501. case "time_interval":
  4502. if startDate == `` || endDate == `` {
  4503. br.Msg = "开始日期或结束日期不能为空"
  4504. br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
  4505. return
  4506. }
  4507. companyReportDataMapList, firstDate, err = statistic_report.GetTimeIntervalData(productId, startDate, endDate)
  4508. if err != nil {
  4509. br.Msg = "数据异常"
  4510. br.ErrMsg = "数据异常,Err:" + err.Error()
  4511. return
  4512. }
  4513. }
  4514. //获取销售人员分组数据
  4515. var group []services.AdminGroup
  4516. var groupIdRelationMap map[int]int
  4517. var groupMap map[int][]*roadshow.Researcher
  4518. if productId == 1 {
  4519. group, groupIdRelationMap, err = services.GetFiccSystemGroup()
  4520. if err != nil {
  4521. br.Msg = "获取信息失败!"
  4522. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4523. return
  4524. }
  4525. researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
  4526. if tmpErr != nil {
  4527. err = tmpErr
  4528. }
  4529. groupMap = make(map[int][]*roadshow.Researcher)
  4530. for _, v := range researcherList {
  4531. if v.RoleTypeCode == "ficc_admin" {
  4532. findItems := groupMap[1]
  4533. findItems = append(findItems, v)
  4534. groupMap[1] = findItems
  4535. } else {
  4536. if findItems, ok := groupMap[v.GroupId]; ok {
  4537. findItems = append(findItems, v)
  4538. groupMap[v.GroupId] = findItems
  4539. } else {
  4540. findItems = append(findItems, v)
  4541. groupMap[v.GroupId] = findItems
  4542. }
  4543. }
  4544. }
  4545. } else {
  4546. group, groupIdRelationMap, err = services.GetRaiSystemGroup()
  4547. if err != nil {
  4548. br.Msg = "获取信息失败!"
  4549. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4550. return
  4551. }
  4552. researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
  4553. if tmpErr != nil {
  4554. err = tmpErr
  4555. }
  4556. groupMap = make(map[int][]*roadshow.Researcher)
  4557. for _, v := range researcherList {
  4558. if v.RoleTypeCode == "rai_admin" {
  4559. findItems := groupMap[1]
  4560. findItems = append(findItems, v)
  4561. groupMap[1] = findItems
  4562. } else {
  4563. if findItems, ok := groupMap[v.GroupId]; ok {
  4564. findItems = append(findItems, v)
  4565. groupMap[v.GroupId] = findItems
  4566. } else {
  4567. findItems = append(findItems, v)
  4568. groupMap[v.GroupId] = findItems
  4569. }
  4570. }
  4571. }
  4572. }
  4573. //数据处理
  4574. groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
  4575. allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
  4576. companyReportRecordResp := statistic_report.CompanyReportRecordResp{
  4577. List: groupReportRecordList,
  4578. CompanyReportRecordNumList: allCompanyReportRecordNum,
  4579. }
  4580. startDateIndexList := make(map[int]string) //开始时间间隔map
  4581. endDateIndexList := make(map[int]string) //结束时间间隔map
  4582. //客户数汇总
  4583. tmpAllTryOutNumMap := make(map[int]int)
  4584. tmpAllFormalNumMap := make(map[int]int)
  4585. tmpAllActiveNumMap := make(map[int]int)
  4586. tmpAllAllActiveNumMap := make(map[int]int)
  4587. tmpAllNoIncrementalActiveNumMap := make(map[int]int)
  4588. //id集合汇总
  4589. tmpAllTryOutIdMap := make(map[int]string)
  4590. tmpAllFormalIdMap := make(map[int]string)
  4591. tmpAllActiveIdMap := make(map[int]string)
  4592. tmpAllAllActiveIdMap := make(map[int]string)
  4593. tmpAllNoIncrementalActiveIdMap := make(map[int]string)
  4594. for _, v := range group {
  4595. v.ResearcherList = groupMap[v.GroupId]
  4596. tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
  4597. tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
  4598. //数量统计
  4599. tmpGroupTryOutNumMap := make(map[int]int)
  4600. tmpGroupFormalNumMap := make(map[int]int)
  4601. tmpGroupActiveNumMap := make(map[int]int)
  4602. tmpGroupAllActiveNumMap := make(map[int]int)
  4603. tmpGroupNoIncrementalActiveNumMap := make(map[int]int)
  4604. //id集合
  4605. tmpGroupTryOutIdSliceMap := make(map[int][]string)
  4606. tmpGroupFormalIdSliceMap := make(map[int][]string)
  4607. tmpGroupActiveIdSliceMap := make(map[int][]string)
  4608. tmpGroupAllActiveIdSliceMap := make(map[int][]string)
  4609. tmpGroupNoIncrementalActiveIdSliceMap := make(map[int][]string)
  4610. //id集合
  4611. tmpGroupTryOutIdMap := make(map[int]string)
  4612. tmpGroupFormalIdMap := make(map[int]string)
  4613. tmpGroupActiveIdMap := make(map[int]string)
  4614. tmpGroupAllActiveIdMap := make(map[int]string)
  4615. tmpGroupNoIncrementalActiveIdMap := make(map[int]string)
  4616. for _, researcher := range groupMap[v.GroupId] {
  4617. //组内研究员数据
  4618. //每个区间的数据
  4619. tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
  4620. for index, adminData := range companyReportDataMapList {
  4621. startDateIndexList[index] = adminData.StartDate
  4622. endDateIndexList[index] = adminData.EndDate
  4623. var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
  4624. //var tmpTryOutIds, tmpFormalIds, tmpActiveIds string
  4625. var tmpTryOutIdSlice, tmpFormalIdSlice, tmpActiveIdSlice, tmpAllActiveIdSlice, tmpNoIncrementalActiveIdSlice []string
  4626. var tmpTryOutId, tmpFormalId, tmpActiveId, tmpAllActiveId, tmpNoIncrementalActiveId string
  4627. if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
  4628. tmpTryOutNum = num
  4629. tmpTryOutIdSlice = append(tmpTryOutIdSlice, adminData.TryOutIdMap[researcher.AdminId])
  4630. tmpTryOutId = strings.Join(tmpTryOutIdSlice, ",")
  4631. }
  4632. if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
  4633. tmpFormalNum = num
  4634. tmpFormalIdSlice = append(tmpFormalIdSlice, adminData.FormalIdMap[researcher.AdminId])
  4635. tmpFormalId = strings.Join(tmpFormalIdSlice, ",")
  4636. }
  4637. if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
  4638. tmpActiveStatus = num
  4639. tmpActiveIdSlice = append(tmpActiveIdSlice, adminData.ActiveIdMap[researcher.AdminId])
  4640. tmpActiveId = strings.Join(tmpActiveIdSlice, ",")
  4641. }
  4642. if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
  4643. tmpAllActiveStatus = num
  4644. tmpAllActiveIdSlice = append(tmpAllActiveIdSlice, adminData.AllActiveIdMap[researcher.AdminId])
  4645. tmpAllActiveId = strings.Join(tmpAllActiveIdSlice, ",")
  4646. }
  4647. if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
  4648. tmpNoIncrementalActiveStatus = num
  4649. tmpNoIncrementalActiveIdSlice = append(tmpNoIncrementalActiveIdSlice, adminData.NoIncrementalActiveIdMap[researcher.AdminId])
  4650. tmpNoIncrementalActiveId = strings.Join(tmpNoIncrementalActiveIdSlice, ",")
  4651. }
  4652. tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
  4653. TryOutNum: tmpTryOutNum,
  4654. TryOutIds: tmpTryOutId,
  4655. FormalNum: tmpFormalNum,
  4656. FormalIds: tmpFormalId,
  4657. ActiveNum: tmpActiveStatus,
  4658. ActiveIds: tmpActiveId,
  4659. AllActiveNum: tmpAllActiveStatus,
  4660. AllActiveIds: tmpAllActiveId,
  4661. NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
  4662. NoIncrementalActiveIds: tmpNoIncrementalActiveId,
  4663. StartDate: adminData.StartDate,
  4664. EndDate: adminData.EndDate,
  4665. }
  4666. tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)
  4667. //组内数据汇总
  4668. if _, ok := tmpGroupTryOutNumMap[index]; !ok {
  4669. tmpGroupTryOutNumMap[index] = 0
  4670. }
  4671. if _, ok := tmpGroupFormalNumMap[index]; !ok {
  4672. tmpGroupFormalNumMap[index] = 0
  4673. }
  4674. if _, ok := tmpGroupActiveNumMap[index]; !ok {
  4675. tmpGroupActiveNumMap[index] = 0
  4676. }
  4677. if _, ok := tmpGroupAllActiveNumMap[index]; !ok {
  4678. tmpGroupAllActiveNumMap[index] = 0
  4679. }
  4680. if _, ok := tmpGroupNoIncrementalActiveNumMap[index]; !ok {
  4681. tmpGroupNoIncrementalActiveNumMap[index] = 0
  4682. }
  4683. tmpGroupTryOutNumMap[index] += tmpTryOutNum
  4684. tmpGroupFormalNumMap[index] += tmpFormalNum
  4685. tmpGroupActiveNumMap[index] += tmpActiveStatus
  4686. tmpGroupAllActiveNumMap[index] += tmpAllActiveStatus
  4687. tmpGroupNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
  4688. //组内数据汇总
  4689. if _, ok := tmpGroupTryOutIdMap[index]; !ok {
  4690. tmpGroupTryOutIdMap[index] = ""
  4691. }
  4692. if _, ok := tmpGroupFormalIdMap[index]; !ok {
  4693. tmpGroupFormalIdMap[index] = ""
  4694. }
  4695. if _, ok := tmpGroupActiveIdMap[index]; !ok {
  4696. tmpGroupActiveIdMap[index] = ""
  4697. }
  4698. if tmpTryOutId != "" {
  4699. tmpGroupTryOutIdSliceMap[index] = append(tmpGroupTryOutIdSliceMap[index], tmpTryOutId)
  4700. }
  4701. if tmpFormalId != "" {
  4702. tmpGroupFormalIdSliceMap[index] = append(tmpGroupFormalIdSliceMap[index], tmpFormalId)
  4703. }
  4704. if tmpActiveId != "" {
  4705. tmpGroupActiveIdSliceMap[index] = append(tmpGroupActiveIdSliceMap[index], tmpActiveId)
  4706. }
  4707. if tmpAllActiveId != "" {
  4708. tmpGroupAllActiveIdSliceMap[index] = append(tmpGroupAllActiveIdSliceMap[index], tmpAllActiveId)
  4709. }
  4710. if tmpNoIncrementalActiveId != "" {
  4711. tmpGroupNoIncrementalActiveIdSliceMap[index] = append(tmpGroupNoIncrementalActiveIdSliceMap[index], tmpNoIncrementalActiveId)
  4712. }
  4713. //总数据汇总
  4714. if _, ok := tmpAllTryOutNumMap[index]; !ok {
  4715. tmpAllTryOutNumMap[index] = 0
  4716. }
  4717. if _, ok := tmpAllFormalNumMap[index]; !ok {
  4718. tmpAllFormalNumMap[index] = 0
  4719. }
  4720. if _, ok := tmpAllActiveNumMap[index]; !ok {
  4721. tmpAllActiveNumMap[index] = 0
  4722. }
  4723. if _, ok := tmpAllAllActiveNumMap[index]; !ok {
  4724. tmpAllAllActiveNumMap[index] = 0
  4725. }
  4726. if _, ok := tmpAllNoIncrementalActiveNumMap[index]; !ok {
  4727. tmpAllNoIncrementalActiveNumMap[index] = 0
  4728. }
  4729. tmpAllTryOutNumMap[index] += tmpTryOutNum
  4730. tmpAllFormalNumMap[index] += tmpFormalNum
  4731. tmpAllActiveNumMap[index] += tmpActiveStatus
  4732. tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
  4733. tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
  4734. ////总数据汇总
  4735. //if _, ok := tmpAllTryOutIdMap[index]; !ok {
  4736. // tmpAllTryOutIdMap[index] = ""
  4737. //}
  4738. //if _, ok := tmpAllFormalIdMap[index]; !ok {
  4739. // tmpAllFormalIdMap[index] = ""
  4740. //}
  4741. //if _, ok := tmpAllActiveIdMap[index]; !ok {
  4742. // tmpAllActiveIdMap[index] = ""
  4743. //}
  4744. //tmpAllTryOutIdMap[index] += tmpTryOutId
  4745. //tmpAllFormalIdMap[index] += tmpFormalId
  4746. //tmpAllActiveIdMap[index] += tmpActiveId
  4747. }
  4748. tmpAdminReportRecord := statistic_report.AdminReportRecord{
  4749. Name: researcher.RealName,
  4750. AdminId: researcher.AdminId,
  4751. CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
  4752. }
  4753. tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
  4754. }
  4755. for i := 0; i < len(tmpGroupActiveNumMap); i++ {
  4756. tmpGroupTryOutIdMap[i] = strings.Join(tmpGroupTryOutIdSliceMap[i], ",")
  4757. tmpGroupFormalIdMap[i] = strings.Join(tmpGroupFormalIdSliceMap[i], ",")
  4758. tmpGroupActiveIdMap[i] = strings.Join(tmpGroupActiveIdSliceMap[i], ",")
  4759. tmpGroupAllActiveIdMap[i] = strings.Join(tmpGroupAllActiveIdSliceMap[i], ",")
  4760. tmpGroupNoIncrementalActiveIdMap[i] = strings.Join(tmpGroupNoIncrementalActiveIdSliceMap[i], ",")
  4761. tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
  4762. TryOutNum: tmpGroupTryOutNumMap[i],
  4763. TryOutIds: tmpGroupTryOutIdMap[i],
  4764. FormalNum: tmpGroupFormalNumMap[i],
  4765. FormalIds: tmpGroupFormalIdMap[i],
  4766. ActiveNum: tmpGroupActiveNumMap[i],
  4767. ActiveIds: tmpGroupActiveIdMap[i],
  4768. AllActiveNum: tmpGroupAllActiveNumMap[i],
  4769. AllActiveIds: tmpGroupAllActiveIdMap[i],
  4770. NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
  4771. NoIncrementalActiveIds: tmpGroupNoIncrementalActiveIdMap[i],
  4772. StartDate: startDateIndexList[i],
  4773. EndDate: endDateIndexList[i],
  4774. }
  4775. tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
  4776. }
  4777. groupReportRecord := statistic_report.GroupReportRecord{
  4778. Item: tmpGroupAdminReportRecord,
  4779. Name: v.GroupName,
  4780. GroupId: v.GroupId,
  4781. CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
  4782. }
  4783. groupReportRecordList = append(groupReportRecordList, groupReportRecord)
  4784. }
  4785. //总体汇总数据
  4786. for i := 0; i < len(tmpAllFormalNumMap); i++ {
  4787. tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
  4788. TryOutNum: tmpAllTryOutNumMap[i],
  4789. TryOutIds: tmpAllTryOutIdMap[i],
  4790. FormalNum: tmpAllFormalNumMap[i],
  4791. FormalIds: tmpAllFormalIdMap[i],
  4792. ActiveNum: tmpAllActiveNumMap[i],
  4793. ActiveIds: tmpAllActiveIdMap[i],
  4794. AllActiveNum: tmpAllAllActiveNumMap[i],
  4795. AllActiveIds: tmpAllAllActiveIdMap[i],
  4796. NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
  4797. NoIncrementalActiveIds: tmpAllNoIncrementalActiveIdMap[i],
  4798. StartDate: startDateIndexList[i],
  4799. EndDate: endDateIndexList[i],
  4800. }
  4801. allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
  4802. }
  4803. companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
  4804. tmpList := groupReportRecordList
  4805. //因为RoleTypeCode不一样,所以需要重新从数据库取数据
  4806. adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
  4807. adminGroupId := adminInfo.GroupId
  4808. if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
  4809. adminGroupId = tmpGroupId
  4810. }
  4811. switch adminInfo.RoleTypeCode {
  4812. case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
  4813. for index, v := range tmpList {
  4814. //如果不是同一个分组,那么就移除该分组下的人员数据
  4815. if v.GroupId != adminGroupId {
  4816. tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
  4817. } else {
  4818. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  4819. }
  4820. }
  4821. companyReportRecordResp.List = tmpList
  4822. case utils.ROLE_TYPE_CODE_RAI_GROUP:
  4823. for index, v := range tmpList {
  4824. //如果不是同一个分组,那么就移除该分组下的人员数据
  4825. if v.GroupId != adminGroupId {
  4826. tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
  4827. } else {
  4828. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  4829. }
  4830. }
  4831. companyReportRecordResp.List = tmpList
  4832. case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
  4833. //管理员、超管看全部数据
  4834. companyReportRecordResp.List = tmpList
  4835. }
  4836. br.Ret = 200
  4837. br.Success = true
  4838. br.Msg = "获取成功"
  4839. br.Data = companyReportRecordResp
  4840. }
  4841. // CompanyList
  4842. // @Title 客户列表
  4843. // @Description 客户列表接口
  4844. // @Param request body statisticModels.IncrementalCompanyListReq true "type json string"
  4845. // @Success 200 {object} statistic_report.CompanyListResp
  4846. // @router /report/company_list [post]
  4847. func (this *StatisticReportController) CompanyList() {
  4848. br := new(models.BaseResponse).Init()
  4849. defer func() {
  4850. this.Data["json"] = br
  4851. this.ServeJSON()
  4852. }()
  4853. sysUser := this.SysUser
  4854. if sysUser == nil {
  4855. br.Msg = "请登录"
  4856. br.ErrMsg = "请登录,SysUser Is Empty"
  4857. br.Ret = 408
  4858. return
  4859. }
  4860. //roleTypeCode := sysUser.RoleTypeCode
  4861. var req statisticModels.IncrementalCompanyListReq
  4862. err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
  4863. if err != nil {
  4864. br.Msg = "参数解析异常!"
  4865. br.ErrMsg = "参数解析失败,Err:" + err.Error()
  4866. return
  4867. }
  4868. resp, err, errMsg := statistic_report.CompanyList(sysUser, req)
  4869. if err != nil {
  4870. br.Msg = err.Error()
  4871. br.ErrMsg = errMsg
  4872. return
  4873. }
  4874. br.Ret = 200
  4875. br.Success = true
  4876. br.Msg = "获取成功"
  4877. br.Data = resp
  4878. }
  4879. // RenewCompanyStatistics
  4880. // @Title 获取续约客户统计数据
  4881. // @Description 获取续约客户统计数据接口
  4882. // @Param DataType query string true "枚举值:week、month、time_interval"
  4883. // @Param ProductId query int true "客户类型 ficc:1 权益:2"
  4884. // @Param StartDate query string true "开始日期,格式:2022-04-06"
  4885. // @Param EndDate query string true "结束日期,格式:2022-04-06"
  4886. // @Success 200 {object} statistic_report.CompanyRenewRecordResp
  4887. // @router /report/renew_company [get]
  4888. func (this *StatisticReportController) RenewCompanyStatistics() {
  4889. br := new(models.BaseResponse).Init()
  4890. defer func() {
  4891. this.Data["json"] = br
  4892. this.ServeJSON()
  4893. }()
  4894. sysUser := this.SysUser
  4895. if sysUser == nil {
  4896. br.Msg = "请登录"
  4897. br.ErrMsg = "请登录,SysUser Is Empty"
  4898. br.Ret = 408
  4899. return
  4900. }
  4901. dataType := this.GetString("DataType")
  4902. productId, _ := this.GetInt("ProductId", 1)
  4903. startDate := this.GetString("StartDate")
  4904. endDate := this.GetString("EndDate")
  4905. var companyRenewDataMapList []statistic_report.CompanyRenewDataMap
  4906. var err error
  4907. var firstDate time.Time
  4908. switch dataType {
  4909. //获取列表
  4910. case "week":
  4911. nowWeekMonday := utils.GetNowWeekMonday() //本周周一
  4912. //companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
  4913. companyRenewDataMapList, firstDate, err = statistic_report.GetRenewWeekDataNum(nowWeekMonday, productId, 6)
  4914. if err != nil {
  4915. br.Msg = "数据异常"
  4916. br.ErrMsg = "数据异常,Err:" + err.Error()
  4917. return
  4918. }
  4919. case "month":
  4920. nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
  4921. //companyRenewDataMapList, firstDate, err = statistic_report.GetMonthData()
  4922. companyRenewDataMapList, firstDate, err = statistic_report.GetRenewMonthDataNum(nowMonthFirstDay, productId, 6)
  4923. if err != nil {
  4924. br.Msg = "数据异常"
  4925. br.ErrMsg = "数据异常,Err:" + err.Error()
  4926. return
  4927. }
  4928. case "time_interval":
  4929. if startDate == `` || endDate == `` {
  4930. br.Msg = "开始日期或结束日期不能为空"
  4931. br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
  4932. return
  4933. }
  4934. companyRenewDataMapList, firstDate, err = statistic_report.GetRenewTimeIntervalData(productId, startDate, endDate)
  4935. if err != nil {
  4936. br.Msg = "数据异常"
  4937. br.ErrMsg = "数据异常,Err:" + err.Error()
  4938. return
  4939. }
  4940. }
  4941. var group []services.AdminGroup
  4942. var groupIdRelationMap map[int]int
  4943. var groupMap map[int][]*roadshow.Researcher
  4944. //获取销售人员分组数据
  4945. if productId == 1 {
  4946. group, groupIdRelationMap, err = services.GetFiccSystemGroup()
  4947. if err != nil {
  4948. br.Msg = "获取信息失败!"
  4949. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4950. return
  4951. }
  4952. researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
  4953. if tmpErr != nil {
  4954. err = tmpErr
  4955. }
  4956. groupMap = make(map[int][]*roadshow.Researcher)
  4957. for _, v := range researcherList {
  4958. if v.RoleTypeCode == "ficc_admin" {
  4959. findItems := groupMap[1]
  4960. findItems = append(findItems, v)
  4961. groupMap[1] = findItems
  4962. } else {
  4963. if findItems, ok := groupMap[v.GroupId]; ok {
  4964. findItems = append(findItems, v)
  4965. groupMap[v.GroupId] = findItems
  4966. } else {
  4967. findItems = append(findItems, v)
  4968. groupMap[v.GroupId] = findItems
  4969. }
  4970. }
  4971. }
  4972. } else {
  4973. group, groupIdRelationMap, err = services.GetRaiSystemGroup()
  4974. if err != nil {
  4975. br.Msg = "获取信息失败!"
  4976. br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
  4977. return
  4978. }
  4979. researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
  4980. if tmpErr != nil {
  4981. err = tmpErr
  4982. }
  4983. groupMap = make(map[int][]*roadshow.Researcher)
  4984. for _, v := range researcherList {
  4985. if v.RoleTypeCode == "rai_admin" {
  4986. findItems := groupMap[1]
  4987. findItems = append(findItems, v)
  4988. groupMap[1] = findItems
  4989. } else {
  4990. if findItems, ok := groupMap[v.GroupId]; ok {
  4991. findItems = append(findItems, v)
  4992. groupMap[v.GroupId] = findItems
  4993. } else {
  4994. findItems = append(findItems, v)
  4995. groupMap[v.GroupId] = findItems
  4996. }
  4997. }
  4998. }
  4999. }
  5000. //数据处理
  5001. groupRenewRecordList := make([]statistic_report.GroupRenewRecord, 0)
  5002. allCompanyRenewRecordNum := make([]statistic_report.CompanyRenewRecordNum, 0)
  5003. companyRenewRecordResp := statistic_report.CompanyRenewRecordResp{
  5004. List: groupRenewRecordList,
  5005. CompanyRenewRecordNumList: allCompanyRenewRecordNum,
  5006. }
  5007. startDateIndexList := make(map[int]string) //开始时间间隔map
  5008. endDateIndexList := make(map[int]string) //结束时间间隔map
  5009. //客户数汇总
  5010. tmpAllNotRenewNumMap := make(map[int]int)
  5011. tmpAllRenewFollowNumMap := make(map[int]int)
  5012. tmpAllExpireNumMap := make(map[int]int)
  5013. tmpAllRenewNumMap := make(map[int]int)
  5014. tmpAllUnusualRenewNumMap := make(map[int]int) // 续约异常客户数量汇总
  5015. tmpAllFormalCompanyNumMap := make(map[int]int) // 当期正式客户数量汇总
  5016. //id集合汇总
  5017. tmpAllNotRenewIdMap := make(map[int]string)
  5018. tmpAllRenewFollowIdMap := make(map[int]string)
  5019. tmpAllExpireIdMap := make(map[int]string)
  5020. tmpAllRenewIdMap := make(map[int]string)
  5021. tmpAllUnusualRenewIdMap := make(map[int]string) // 续约异常客户id汇总
  5022. tmpAllUnusualRenewIdSlice := make(map[int][]string, 0)
  5023. for _, v := range group {
  5024. v.ResearcherList = groupMap[v.GroupId]
  5025. tmpGroupAdminRenewRecord := make([]statistic_report.AdminRenewRecord, 0)
  5026. tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)
  5027. //数量统计
  5028. tmpGroupNotRenewNumMap := make(map[int]int)
  5029. tmpGroupRenewFollowNumMap := make(map[int]int)
  5030. tmpGroupExpireNumMap := make(map[int]int)
  5031. tmpGroupRenewNumMap := make(map[int]int)
  5032. tmpGroupUnusualRenewNumMap := make(map[int]int) //组内续约异常客户数
  5033. //id集合
  5034. tmpGroupNotRenewIdSliceMap := make(map[int][]string)
  5035. tmpGroupRenewFollowIdSliceMap := make(map[int][]string)
  5036. tmpGroupExpireIdSliceMap := make(map[int][]string)
  5037. tmpGroupRenewIdSliceMap := make(map[int][]string)
  5038. tmpGroupUnusualRenewIdSliceMap := make(map[int][]string) // 组内续约异常客户id汇总
  5039. //id集合
  5040. tmpGroupNotRenewIdMap := make(map[int]string)
  5041. tmpGroupRenewFollowIdMap := make(map[int]string)
  5042. tmpGroupExpireIdMap := make(map[int]string)
  5043. tmpGroupRenewIdMap := make(map[int]string)
  5044. tmpGroupUnusualRenewIdMap := make(map[int]string) // 组内续约异常客户id汇总
  5045. for _, researcher := range groupMap[v.GroupId] {
  5046. //组内研究员数据
  5047. //每个区间的数据
  5048. tmpCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)
  5049. for index, adminData := range companyRenewDataMapList {
  5050. startDateIndexList[index] = adminData.StartDate
  5051. endDateIndexList[index] = adminData.EndDate
  5052. var tmpNotRenewNum, tmpRenewFollowNum, tmpExpireStatus, tmpRenewStatus, tmpUnusualRenewStatus int
  5053. //var tmpNotRenewIds, tmpRenewFollowIds, tmpExpireIds string
  5054. var tmpNotRenewIdSlice, tmpRenewFollowIdSlice, tmpExpireIdSlice, tmpRenewIdSlice, tmpUnusualRenewIdSlice []string
  5055. var tmpNotRenewId, tmpRenewFollowId, tmpExpireId, tmpRenewId, tmpUnusualRenewId string
  5056. if num, ok := adminData.NotRenewMap[researcher.AdminId]; ok {
  5057. tmpNotRenewNum = num
  5058. tmpNotRenewIdSlice = append(tmpNotRenewIdSlice, adminData.NotRenewIdMap[researcher.AdminId])
  5059. tmpNotRenewId = strings.Join(tmpNotRenewIdSlice, ",")
  5060. }
  5061. if num, ok := adminData.RenewFollowMap[researcher.AdminId]; ok {
  5062. tmpRenewFollowNum = num
  5063. tmpRenewFollowIdSlice = append(tmpRenewFollowIdSlice, adminData.RenewFollowIdMap[researcher.AdminId])
  5064. tmpRenewFollowId = strings.Join(tmpRenewFollowIdSlice, ",")
  5065. }
  5066. if num, ok := adminData.ExpireMap[researcher.AdminId]; ok {
  5067. tmpExpireStatus = num
  5068. tmpExpireIdSlice = append(tmpExpireIdSlice, adminData.ExpireIdMap[researcher.AdminId])
  5069. tmpExpireId = strings.Join(tmpExpireIdSlice, ",")
  5070. }
  5071. if num, ok := adminData.RenewMap[researcher.AdminId]; ok {
  5072. tmpRenewStatus = num
  5073. tmpRenewIdSlice = append(tmpRenewIdSlice, adminData.RenewIdMap[researcher.AdminId])
  5074. tmpRenewId = strings.Join(tmpRenewIdSlice, ",")
  5075. }
  5076. // 续约异常客户
  5077. if num, ok := adminData.UnusualRenewMap[researcher.AdminId]; ok {
  5078. tmpUnusualRenewStatus = num
  5079. tmpUnusualRenewIdSlice = append(tmpUnusualRenewIdSlice, adminData.UnusualRenewIdMap[researcher.AdminId])
  5080. tmpUnusualRenewId = strings.Join(tmpUnusualRenewIdSlice, ",")
  5081. }
  5082. tmpAdminRsRenewRecordNum := statistic_report.CompanyRenewRecordNum{
  5083. NotRenewNum: tmpNotRenewNum,
  5084. NotRenewIds: tmpNotRenewId,
  5085. RenewFollowNum: tmpRenewFollowNum,
  5086. RenewFollowIds: tmpRenewFollowId,
  5087. ExpireNum: tmpExpireStatus,
  5088. ExpireIds: tmpExpireId,
  5089. RenewNum: tmpRenewStatus,
  5090. RenewIds: tmpRenewId,
  5091. UnusualRenewNum: tmpUnusualRenewStatus,
  5092. UnusualRenewIds: tmpUnusualRenewId,
  5093. StartDate: adminData.StartDate,
  5094. EndDate: adminData.EndDate,
  5095. }
  5096. tmpCompanyRenewRecordNumList = append(tmpCompanyRenewRecordNumList, tmpAdminRsRenewRecordNum)
  5097. //组内数据汇总
  5098. if _, ok := tmpGroupNotRenewNumMap[index]; !ok {
  5099. tmpGroupNotRenewNumMap[index] = 0
  5100. }
  5101. if _, ok := tmpGroupRenewFollowNumMap[index]; !ok {
  5102. tmpGroupRenewFollowNumMap[index] = 0
  5103. }
  5104. if _, ok := tmpGroupExpireNumMap[index]; !ok {
  5105. tmpGroupExpireNumMap[index] = 0
  5106. }
  5107. if _, ok := tmpGroupRenewNumMap[index]; !ok {
  5108. tmpGroupRenewNumMap[index] = 0
  5109. }
  5110. if _, ok := tmpGroupUnusualRenewNumMap[index]; !ok {
  5111. tmpGroupUnusualRenewNumMap[index] = 0
  5112. }
  5113. tmpGroupNotRenewNumMap[index] += tmpNotRenewNum
  5114. tmpGroupRenewFollowNumMap[index] += tmpRenewFollowNum
  5115. tmpGroupExpireNumMap[index] += tmpExpireStatus
  5116. tmpGroupRenewNumMap[index] += tmpRenewStatus
  5117. tmpGroupUnusualRenewNumMap[index] += tmpUnusualRenewStatus
  5118. //组内数据汇总
  5119. if _, ok := tmpGroupNotRenewIdMap[index]; !ok {
  5120. tmpGroupNotRenewIdMap[index] = ""
  5121. }
  5122. if _, ok := tmpGroupRenewFollowIdMap[index]; !ok {
  5123. tmpGroupRenewFollowIdMap[index] = ""
  5124. }
  5125. if _, ok := tmpGroupExpireIdMap[index]; !ok {
  5126. tmpGroupExpireIdMap[index] = ""
  5127. }
  5128. if tmpNotRenewId != "" {
  5129. tmpGroupNotRenewIdSliceMap[index] = append(tmpGroupNotRenewIdSliceMap[index], tmpNotRenewId)
  5130. }
  5131. if tmpRenewFollowId != "" {
  5132. tmpGroupRenewFollowIdSliceMap[index] = append(tmpGroupRenewFollowIdSliceMap[index], tmpRenewFollowId)
  5133. }
  5134. if tmpExpireId != "" {
  5135. tmpGroupExpireIdSliceMap[index] = append(tmpGroupExpireIdSliceMap[index], tmpExpireId)
  5136. }
  5137. if tmpRenewId != "" {
  5138. tmpGroupRenewIdSliceMap[index] = append(tmpGroupRenewIdSliceMap[index], tmpRenewId)
  5139. }
  5140. if tmpUnusualRenewId != "" {
  5141. tmpGroupUnusualRenewIdSliceMap[index] = append(tmpGroupUnusualRenewIdSliceMap[index], tmpUnusualRenewId)
  5142. tmpSlice := strings.Split(tmpUnusualRenewId, ",")
  5143. tmpAllUnusualRenewIdSlice[index] = append(tmpAllUnusualRenewIdSlice[index], tmpSlice...)
  5144. }
  5145. //总数据汇总
  5146. if _, ok := tmpAllNotRenewNumMap[index]; !ok {
  5147. tmpAllNotRenewNumMap[index] = 0
  5148. }
  5149. if _, ok := tmpAllRenewFollowNumMap[index]; !ok {
  5150. tmpAllRenewFollowNumMap[index] = 0
  5151. }
  5152. if _, ok := tmpAllExpireNumMap[index]; !ok {
  5153. tmpAllExpireNumMap[index] = 0
  5154. }
  5155. if _, ok := tmpAllRenewNumMap[index]; !ok {
  5156. tmpAllRenewNumMap[index] = 0
  5157. }
  5158. tmpAllNotRenewNumMap[index] += tmpNotRenewNum
  5159. tmpAllRenewFollowNumMap[index] += tmpRenewFollowNum
  5160. tmpAllExpireNumMap[index] += tmpExpireStatus
  5161. tmpAllRenewNumMap[index] += tmpRenewStatus
  5162. tmpAllUnusualRenewNumMap[index] = adminData.UnusualRenewTotal
  5163. tmpAllFormalCompanyNumMap[index] = adminData.FormalCompanyTotal
  5164. }
  5165. tmpAdminRenewRecord := statistic_report.AdminRenewRecord{
  5166. Name: researcher.RealName,
  5167. AdminId: researcher.AdminId,
  5168. CompanyRenewRecordNumList: tmpCompanyRenewRecordNumList,
  5169. }
  5170. tmpGroupAdminRenewRecord = append(tmpGroupAdminRenewRecord, tmpAdminRenewRecord)
  5171. }
  5172. for i := 0; i < len(tmpGroupExpireNumMap); i++ {
  5173. tmpGroupNotRenewIdMap[i] = strings.Join(tmpGroupNotRenewIdSliceMap[i], ",")
  5174. tmpGroupRenewFollowIdMap[i] = strings.Join(tmpGroupRenewFollowIdSliceMap[i], ",")
  5175. tmpGroupExpireIdMap[i] = strings.Join(tmpGroupExpireIdSliceMap[i], ",")
  5176. tmpGroupRenewIdMap[i] = strings.Join(tmpGroupRenewIdSliceMap[i], ",")
  5177. tmpGroupUnusualRenewIdMap[i] = strings.Join(tmpGroupUnusualRenewIdSliceMap[i], ",")
  5178. tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
  5179. NotRenewNum: tmpGroupNotRenewNumMap[i],
  5180. NotRenewIds: tmpGroupNotRenewIdMap[i],
  5181. RenewFollowNum: tmpGroupRenewFollowNumMap[i],
  5182. RenewFollowIds: tmpGroupRenewFollowIdMap[i],
  5183. ExpireNum: tmpGroupExpireNumMap[i],
  5184. ExpireIds: tmpGroupExpireIdMap[i],
  5185. RenewNum: tmpGroupRenewNumMap[i],
  5186. RenewIds: tmpGroupRenewIdMap[i],
  5187. UnusualRenewNum: tmpGroupUnusualRenewNumMap[i],
  5188. UnusualRenewIds: tmpGroupUnusualRenewIdMap[i],
  5189. StartDate: startDateIndexList[i],
  5190. EndDate: endDateIndexList[i],
  5191. }
  5192. tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, tmpGroupCompanyRenewRecordNum)
  5193. }
  5194. groupRenewRecord := statistic_report.GroupRenewRecord{
  5195. Item: tmpGroupAdminRenewRecord,
  5196. Name: v.GroupName,
  5197. GroupId: v.GroupId,
  5198. CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
  5199. }
  5200. groupRenewRecordList = append(groupRenewRecordList, groupRenewRecord)
  5201. }
  5202. // 总体数据汇总,去掉重复销售的公司个数
  5203. //总体汇总数据
  5204. for i := 0; i < len(tmpAllRenewFollowNumMap); i++ {
  5205. // 未续约统计数据去重
  5206. unusualRenewIdsFinal := make([]string, 0)
  5207. unusualRenewIdsMap := make(map[string]struct{})
  5208. for _, id := range tmpAllUnusualRenewIdSlice[i] {
  5209. if _, ok := unusualRenewIdsMap[id]; !ok {
  5210. unusualRenewIdsFinal = append(unusualRenewIdsFinal, id)
  5211. unusualRenewIdsMap[id] = struct{}{}
  5212. }
  5213. }
  5214. tmpAllUnusualRenewNumMap[i] = len(unusualRenewIdsFinal)
  5215. tmpAllUnusualRenewIdMap[i] = strings.Join(unusualRenewIdsFinal, ",")
  5216. unusualRate := ``
  5217. if tmpAllUnusualRenewNumMap[i] > 0 && tmpAllFormalCompanyNumMap[i] > 0 {
  5218. unusualRate = decimal.NewFromInt(int64(tmpAllUnusualRenewNumMap[i])*100).Div(decimal.NewFromInt(int64(tmpAllFormalCompanyNumMap[i]))).Round(2).String() + "%"
  5219. }
  5220. tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
  5221. NotRenewNum: tmpAllNotRenewNumMap[i],
  5222. NotRenewIds: tmpAllNotRenewIdMap[i],
  5223. RenewFollowNum: tmpAllRenewFollowNumMap[i],
  5224. RenewFollowIds: tmpAllRenewFollowIdMap[i],
  5225. ExpireNum: tmpAllExpireNumMap[i],
  5226. ExpireIds: tmpAllExpireIdMap[i],
  5227. RenewNum: tmpAllRenewNumMap[i],
  5228. RenewIds: tmpAllRenewIdMap[i],
  5229. UnusualRenewNum: tmpAllUnusualRenewNumMap[i],
  5230. UnusualRenewIds: tmpAllUnusualRenewIdMap[i],
  5231. UnusualRate: unusualRate, // 异常率
  5232. StartDate: startDateIndexList[i],
  5233. EndDate: endDateIndexList[i],
  5234. }
  5235. allCompanyRenewRecordNum = append(allCompanyRenewRecordNum, tmpGroupCompanyRenewRecordNum)
  5236. }
  5237. companyRenewRecordResp.CompanyRenewRecordNumList = allCompanyRenewRecordNum
  5238. tmpList := groupRenewRecordList
  5239. //因为RoleTypeCode不一样,所以需要重新从数据库取数据
  5240. adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
  5241. adminGroupId := adminInfo.GroupId
  5242. if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
  5243. adminGroupId = tmpGroupId
  5244. }
  5245. if productId == 2 {
  5246. //对权益组排个序
  5247. tmpList = statistic_report.SortGroupSellers(tmpList)
  5248. }
  5249. switch adminInfo.RoleTypeCode {
  5250. case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
  5251. for index, v := range tmpList {
  5252. //如果不是同一个分组,那么就移除该分组下的人员数据
  5253. if v.GroupId != adminGroupId {
  5254. tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
  5255. } else {
  5256. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  5257. }
  5258. }
  5259. companyRenewRecordResp.List = tmpList
  5260. case utils.ROLE_TYPE_CODE_RAI_GROUP:
  5261. for index, v := range tmpList {
  5262. //如果不是同一个分组,那么就移除该分组下的人员数据
  5263. if v.GroupId != adminGroupId {
  5264. tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
  5265. } else {
  5266. tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
  5267. }
  5268. }
  5269. companyRenewRecordResp.List = tmpList
  5270. case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
  5271. //管理员、超管看全部数据
  5272. companyRenewRecordResp.List = tmpList
  5273. }
  5274. br.Ret = 200
  5275. br.Success = true
  5276. br.Msg = "获取成功"
  5277. br.Data = companyRenewRecordResp
  5278. }
  5279. // List
  5280. // @Title 商品到款统计列表
  5281. // @Description 商品到款统计列表
  5282. // @Param Keyword query string false "关键词"
  5283. // @Param ServiceType query int false "套餐类型"
  5284. // @Param StartDate query string false "合同开始日期"
  5285. // @Param EndDate query string false "合同结束日期"
  5286. // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
  5287. // @Param hasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
  5288. // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
  5289. // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
  5290. // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
  5291. // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
  5292. // @Success 200 {object} fms.ContractRegisterItem
  5293. // @router /census/invoice_payment/list [get]
  5294. func (this *StatisticReportController) InvoicePaymentList() {
  5295. br := new(models.BaseResponse).Init()
  5296. defer func() {
  5297. this.Data["json"] = br
  5298. this.ServeJSON()
  5299. }()
  5300. sysUser := this.SysUser
  5301. if sysUser == nil {
  5302. br.Msg = "请登录"
  5303. br.ErrMsg = "请登录,SysUser Is Empty"
  5304. br.Ret = 408
  5305. return
  5306. }
  5307. keyword := this.GetString("Keyword")
  5308. serviceType := this.GetString("ServiceType")
  5309. timeType, _ := this.GetInt("TimeType")
  5310. startDate := this.GetString("StartDate")
  5311. endDate := this.GetString("EndDate")
  5312. hasInvoice := this.GetString("HasInvoice")
  5313. hasPayment := this.GetString("HasPayment")
  5314. sortParam := this.GetString("SortParam")
  5315. sortType := this.GetString("SortType")
  5316. sellerIdstr := this.GetString("SellerIds")
  5317. cond := `1 = 1`
  5318. pars := make([]interface{}, 0)
  5319. // 客户姓名/销售
  5320. if keyword != "" {
  5321. kw := "%" + keyword + "%"
  5322. cond += ` AND b.company_name LIKE ?`
  5323. pars = append(pars, kw)
  5324. }
  5325. if sellerIdstr != "" {
  5326. //sellerIds := strings.Split(sellerIdstr, ",")
  5327. cond += ` AND (c.seller_id in (` + sellerIdstr + `) OR d.seller_id in (` + sellerIdstr + `))`
  5328. //pars = append(pars, sellerIds, sellerIds)
  5329. }
  5330. // 套餐筛选
  5331. if serviceType != "" {
  5332. serviceTypes := strings.Split(serviceType, ",")
  5333. tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
  5334. if e != nil {
  5335. br.Msg = "获取失败!"
  5336. br.ErrMsg = "获取合同登记IDs失败,Err:" + e.Error()
  5337. return
  5338. }
  5339. if len(tempRegisterIds) > 0 {
  5340. cond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(tempRegisterIds)) + `)`
  5341. pars = append(pars, tempRegisterIds)
  5342. } else {
  5343. cond += ` AND 1 = 2`
  5344. }
  5345. }
  5346. var depId int
  5347. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
  5348. depId = 2
  5349. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  5350. depId = 5
  5351. }
  5352. dshiAdminId := 13
  5353. if utils.RunMode == "debug" {
  5354. dshiAdminId = 233
  5355. }
  5356. if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
  5357. sellerIdsList, err := system.GetSellerIdsByDepId(depId)
  5358. if err != nil {
  5359. br.Msg = "获取失败!"
  5360. br.ErrMsg = "获取商品到款统计列表总数失败,Err:" + err.Error()
  5361. return
  5362. }
  5363. cond += ` AND (c.seller_id IN (` + strings.Join(sellerIdsList, ",") + `) OR d.seller_id IN (` + strings.Join(sellerIdsList, ",") + `))`
  5364. } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP && sysUser.AdminId == dshiAdminId {
  5365. groupTeamSellerList, err := system.GetSysUserByParentIdGroupId(5)
  5366. if err != nil {
  5367. br.Msg = "获取销售失败"
  5368. br.ErrMsg = "获取销售失败,Err:" + err.Error()
  5369. return
  5370. }
  5371. sellerIdsList := ""
  5372. for _, v := range groupTeamSellerList {
  5373. sellerIdsList += strconv.Itoa(v.AdminId) + ","
  5374. }
  5375. sellerIdsList = strings.TrimRight(sellerIdsList, ",")
  5376. cond += ` AND (c.seller_id IN (` + sellerIdsList + `) OR d.seller_id IN (` + sellerIdsList + `))`
  5377. pars = append(pars)
  5378. } else if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
  5379. cond += ` AND (c.seller_id=? OR d.seller_id=?)`
  5380. pars = append(pars, sysUser.AdminId, sysUser.AdminId)
  5381. }
  5382. // 开票到款日期
  5383. if timeType != 0 {
  5384. if timeType == 1 && startDate != "" && endDate != "" {
  5385. st := fmt.Sprint(startDate, " 00:00:00")
  5386. ed := fmt.Sprint(endDate, " 23:59:59")
  5387. cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
  5388. pars = append(pars, st, ed)
  5389. } else if timeType == 2 && startDate != "" && endDate != "" {
  5390. st := fmt.Sprint(startDate, " 00:00:00")
  5391. ed := fmt.Sprint(endDate, " 23:59:59")
  5392. cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
  5393. pars = append(pars, st, ed)
  5394. } else if timeType == 3 && startDate != "" && endDate != "" {
  5395. st := fmt.Sprint(startDate, " 00:00:00")
  5396. ed := fmt.Sprint(endDate, " 23:59:59")
  5397. cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
  5398. pars = append(pars, st, ed, st, ed)
  5399. }
  5400. } else if startDate != "" && endDate != "" {
  5401. st := fmt.Sprint(startDate, " 00:00:00")
  5402. ed := fmt.Sprint(endDate, " 23:59:59")
  5403. cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
  5404. pars = append(pars, st, ed, st, ed)
  5405. }
  5406. if hasInvoice == "1" {
  5407. cond += ` AND a.invoice_id > 0 `
  5408. } else if hasInvoice == "0" {
  5409. cond += ` AND a.invoice_id = 0 `
  5410. }
  5411. if hasPayment == "1" {
  5412. cond += ` AND a.payment_id > 0 `
  5413. } else if hasPayment == "0" {
  5414. cond += ` AND a.payment_id = 0 `
  5415. }
  5416. pageSize, _ := this.GetInt("PageSize")
  5417. currentIndex, _ := this.GetInt("CurrentIndex")
  5418. var startSize int
  5419. if pageSize <= 0 {
  5420. pageSize = utils.PageSize20
  5421. }
  5422. if currentIndex <= 0 {
  5423. currentIndex = 1
  5424. }
  5425. startSize = utils.StartIndex(currentIndex, pageSize)
  5426. //排序
  5427. if sortType == "" {
  5428. sortType = "desc"
  5429. }
  5430. if sortType != "desc" && sortType != "asc" {
  5431. br.Msg = "排序类型不正确!"
  5432. return
  5433. }
  5434. var order string
  5435. if sortParam == "" {
  5436. order = ` ORDER BY sort_invoice_id ,sort_payment_id desc,c.invoice_time desc,c.amount desc,a.create_time desc `
  5437. } else if sortParam == "invoice_time" {
  5438. if sortType == "asc" {
  5439. order = ` ORDER BY sort_invoice_id desc,c.invoice_time ,c.amount ,a.create_time ASC `
  5440. } else {
  5441. order = ` ORDER BY sort_invoice_id ,c.invoice_time desc,c.amount desc,a.create_time desc `
  5442. }
  5443. } else if sortParam == "payment_date" {
  5444. if sortType == "asc" {
  5445. order = ` ORDER BY sort_payment_id desc,d.invoice_time ,d.amount ,a.create_time `
  5446. } else {
  5447. order = ` ORDER BY sort_payment_id ,d.invoice_time desc,d.amount desc,a.create_time desc `
  5448. }
  5449. } else {
  5450. br.Msg = "排序字段不正确!"
  5451. return
  5452. }
  5453. registerList, total, e := fms.GetInvoicePaymentCensusPageList(cond, pars, order, startSize, pageSize)
  5454. if e != nil {
  5455. br.Msg = "获取失败!"
  5456. br.ErrMsg = "获取商品到款统计列表总数失败,Err:" + e.Error()
  5457. return
  5458. }
  5459. queryRegisterIds := make([]int, 0)
  5460. for i := range registerList {
  5461. queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
  5462. }
  5463. //fmt.Println("queryRegisterIds:",queryRegisterIds)
  5464. results := new(fms.InvoicePaymentCensusResp)
  5465. if len(queryRegisterIds) > 0 {
  5466. // 获取汇总数据IDs, 用于查询合计数据
  5467. summaryIdsCond := cond
  5468. summaryIdsPars := pars
  5469. summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
  5470. if e != nil {
  5471. br.Msg = "获取失败!"
  5472. br.ErrMsg = "获取商品到款汇总IDs失败,Err:" + e.Error()
  5473. return
  5474. }
  5475. //fmt.Println("summaryIds:",summaryIds)
  5476. var listErr, totalErr, totalGroupErr error
  5477. wg := sync.WaitGroup{}
  5478. // 响应列表
  5479. respList := make([]*fms.InvoicePaymentCensusItem, 0)
  5480. summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
  5481. wg.Add(1)
  5482. go func() {
  5483. defer wg.Done()
  5484. // 获取汇总数据
  5485. summaryCond := cond
  5486. summaryCond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(queryRegisterIds)) + `)`
  5487. summaryPars := pars
  5488. summaryPars = append(summaryPars, queryRegisterIds)
  5489. summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
  5490. if e != nil {
  5491. br.Msg = "获取失败!"
  5492. br.ErrMsg = "获取商品到款汇总列表失败,Err:" + e.Error()
  5493. return
  5494. }
  5495. summaryList = summaryData
  5496. //summaryIds := make([]int, 0)
  5497. paymentIds := make([]int, 0)
  5498. for i := range summaryList {
  5499. //summaryIds = append(summaryIds, summaryList[i].SummaryId)
  5500. if summaryList[i].PaymentId > 0 {
  5501. paymentIds = append(paymentIds, summaryList[i].PaymentId)
  5502. }
  5503. }
  5504. // 合同套餐
  5505. /*contractServiceCond := `contract_register_id IN ?`
  5506. contractServicePars := make([]interface{}, 0)
  5507. contractServicePars = append(contractServicePars, queryRegisterIds)
  5508. contractServiceOB := new(fms.ContractService)
  5509. contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
  5510. if e != nil {
  5511. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  5512. return
  5513. }
  5514. contractServiceMap := make(map[int][]*fms.ContractService, 0)
  5515. servicesNameMap := make(map[int][]string, 0)
  5516. for i := range contractServiceList {
  5517. if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
  5518. contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
  5519. }
  5520. contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
  5521. servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
  5522. }
  5523. */
  5524. servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
  5525. if e != nil {
  5526. listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
  5527. return
  5528. }
  5529. // 到款套餐分配
  5530. serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
  5531. if len(paymentIds) > 0 {
  5532. serviceAmountCond := ` AND contract_payment_id IN (` + utils.GetOrmInReplace(len(paymentIds)) + `)`
  5533. serviceAmountPars := make([]interface{}, 0)
  5534. serviceAmountPars = append(serviceAmountPars, paymentIds)
  5535. serviceAmountOB := new(fms.ContractPaymentServiceAmount)
  5536. serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
  5537. if e != nil {
  5538. listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
  5539. return
  5540. }
  5541. for i := range serviceAmountList {
  5542. if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
  5543. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
  5544. }
  5545. serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
  5546. }
  5547. }
  5548. // 重组汇总数据
  5549. summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
  5550. amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
  5551. for i := range summaryList {
  5552. v := new(fms.InvoicePaymentCensusInfo)
  5553. v.InvoiceId = summaryList[i].InvoiceId
  5554. v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
  5555. v.InvoiceAmount = summaryList[i].InvoiceAmount
  5556. v.SellerId = summaryList[i].SellerId
  5557. v.SellerName = summaryList[i].SellerName
  5558. v.SellerGroupId = summaryList[i].SellerGroupId
  5559. v.SellerGroupName = summaryList[i].SellerGroupName
  5560. v.SellerType = summaryList[i].ServiceProductId
  5561. v.PaymentId = summaryList[i].PaymentId
  5562. v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
  5563. v.PaymentAmount = summaryList[i].PaymentAmount
  5564. v.PayType = summaryList[i].PayType
  5565. // 套餐到款分配
  5566. svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
  5567. amountList := serviceAmountMap[summaryList[i].PaymentId]
  5568. if amountList != nil {
  5569. for i := range amountList {
  5570. k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
  5571. amountMap[k] = amountList[i]
  5572. }
  5573. }
  5574. // 合同对应的所有套餐
  5575. svList := serviceFormatMap[summaryList[i].RegisterId]
  5576. if svList != nil {
  5577. for ii := range svList {
  5578. vv := new(fms.ContractPaymentServiceAmountItem)
  5579. vv.ServiceTemplateId = svList[ii].ServiceTemplateId
  5580. vv.ServiceTemplateName = svList[ii].FormatTitle
  5581. vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
  5582. vv.ServiceProductId = svList[ii].ServiceProductId
  5583. k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
  5584. a := amountMap[k2]
  5585. if a != nil {
  5586. vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
  5587. vv.ContractPaymentId = a.ContractPaymentId
  5588. vv.Amount = a.Amount
  5589. }
  5590. svaList = append(svaList, vv)
  5591. }
  5592. }
  5593. v.ServiceAmountList = svaList
  5594. summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
  5595. }
  5596. // 响应列表
  5597. for i := range registerList {
  5598. v := new(fms.InvoicePaymentCensusItem)
  5599. v.SummaryId = registerList[i].SummaryId
  5600. v.ContractRegisterId = registerList[i].ContractRegisterId
  5601. v.CompanyName = registerList[i].CompanyName
  5602. v.NewCompany = registerList[i].NewCompany
  5603. v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
  5604. v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
  5605. v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
  5606. v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
  5607. v.ContractType = registerList[i].ContractType
  5608. v.ActualPayCompanies = registerList[i].ActualPayCompanies
  5609. respList = append(respList, v)
  5610. }
  5611. }()
  5612. // 开票到款金额合计(换算后)
  5613. var invoiceTotal, paymentTotal, amountTotal float64
  5614. wg.Add(1)
  5615. go func() {
  5616. defer wg.Done()
  5617. if len(summaryIds) == 0 {
  5618. return
  5619. }
  5620. amountTotalCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
  5621. amountTotalPars := make([]interface{}, 0)
  5622. amountTotalPars = append(amountTotalPars, summaryIds)
  5623. invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
  5624. if e != nil {
  5625. totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
  5626. return
  5627. }
  5628. invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
  5629. paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
  5630. if e != nil {
  5631. totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
  5632. return
  5633. }
  5634. paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
  5635. amountCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `) AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
  5636. amountPars := make([]interface{}, 0)
  5637. amountPars = append(amountPars, summaryIds)
  5638. amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
  5639. if e != nil {
  5640. totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
  5641. return
  5642. }
  5643. amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
  5644. }()
  5645. // 分币种金额统计
  5646. invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  5647. paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
  5648. wg.Add(1)
  5649. go func() {
  5650. defer wg.Done()
  5651. currencyOB := new(fms.CurrencyUnit)
  5652. currencyCond := `enable = 1`
  5653. currencyPars := make([]interface{}, 0)
  5654. currencyList, e := currencyOB.List(currencyCond, currencyPars)
  5655. if e != nil {
  5656. totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
  5657. return
  5658. }
  5659. unitMap := make(map[string]string)
  5660. for i := range currencyList {
  5661. unitMap[currencyList[i].Code] = currencyList[i].UnitName
  5662. invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  5663. Name: currencyList[i].Name,
  5664. UnitName: currencyList[i].UnitName,
  5665. Code: currencyList[i].Code,
  5666. FlagImg: currencyList[i].FlagImg,
  5667. })
  5668. paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
  5669. Name: currencyList[i].Name,
  5670. UnitName: currencyList[i].UnitName,
  5671. Code: currencyList[i].Code,
  5672. FlagImg: currencyList[i].FlagImg,
  5673. })
  5674. }
  5675. if len(summaryIds) == 0 {
  5676. return
  5677. }
  5678. totalGroupCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
  5679. totalGroupPars := make([]interface{}, 0)
  5680. totalGroupPars = append(totalGroupPars, summaryIds)
  5681. invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
  5682. if e != nil {
  5683. totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
  5684. return
  5685. }
  5686. paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
  5687. if e != nil {
  5688. totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
  5689. return
  5690. }
  5691. invoiceSumMap := make(map[string]float64)
  5692. paymentSumMap := make(map[string]float64)
  5693. for i := range invoiceSumGroup {
  5694. invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
  5695. continue
  5696. }
  5697. for i := range paymentSumGroup {
  5698. paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
  5699. continue
  5700. }
  5701. for i := range invoiceCurrencyTotals {
  5702. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
  5703. invoiceCurrencyTotals[i].Amount = a
  5704. }
  5705. for i := range paymentCurrencyTotals {
  5706. a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
  5707. paymentCurrencyTotals[i].Amount = a
  5708. }
  5709. }()
  5710. wg.Wait()
  5711. if listErr != nil {
  5712. br.Msg = "获取失败!"
  5713. br.ErrMsg = "获取商品到款汇总失败,Err:" + listErr.Error()
  5714. return
  5715. }
  5716. if totalErr != nil {
  5717. br.Msg = "获取失败!"
  5718. br.ErrMsg = "获取商品到款汇总失败,Err:" + totalErr.Error()
  5719. return
  5720. }
  5721. if totalGroupErr != nil {
  5722. br.Msg = "获取失败!"
  5723. br.ErrMsg = "获取商品到款汇总失败,Err:" + totalGroupErr.Error()
  5724. return
  5725. }
  5726. results.DataList = respList
  5727. results.InvoiceTotal = invoiceTotal
  5728. results.PaymentTotal = paymentTotal
  5729. results.AmountTotal = amountTotal
  5730. results.InvoiceCurrencyTotal = invoiceCurrencyTotals
  5731. results.PaymentCurrencyTotal = paymentCurrencyTotals
  5732. }
  5733. page := paging.GetPaging(currentIndex, pageSize, int(total))
  5734. results.Paging = page
  5735. br.Ret = 200
  5736. br.Success = true
  5737. br.Msg = "获取成功"
  5738. br.Data = results
  5739. }
  5740. // SimpleList
  5741. // @Title 合同套餐列表
  5742. // @Description 合同套餐列表
  5743. // @Param ProductId query int false "套餐类型: 1-FICC(默认); 2-权益"
  5744. // @Success 200 {object} crm.ContractSearchListResp
  5745. // @router /contract/service/simple [get]
  5746. func (this *StatisticReportController) SimpleList() {
  5747. br := new(models.BaseResponse).Init()
  5748. defer func() {
  5749. this.Data["json"] = br
  5750. this.ServeJSON()
  5751. }()
  5752. sysUser := this.SysUser
  5753. if sysUser == nil {
  5754. br.Msg = "请登录"
  5755. br.ErrMsg = "请登录,SysUser Is Empty"
  5756. br.Ret = 408
  5757. return
  5758. }
  5759. list, err := fms.GetContractServiceTemplateSecond()
  5760. if err != nil {
  5761. br.Msg = "获取失败!"
  5762. br.ErrMsg = "获取产品套餐失败,Err:" + err.Error()
  5763. return
  5764. }
  5765. allList := make([]*fms.ContractServiceTemplateItem, 0)
  5766. allMap := make(map[int][]*fms.ContractServiceTemplateMapItems)
  5767. respList := make([]*fms.ContractServiceTemplateList, 0)
  5768. for i := 0; i < len(list); i++ {
  5769. if list[i].Title == "行业套餐" {
  5770. industryList, e := fms.GetContractServiceTemplateMapByParentId(list[i].ServiceTemplateId)
  5771. if e != nil {
  5772. br.Msg = "获取失败!"
  5773. br.ErrMsg = "获取套餐失败,Err:" + e.Error()
  5774. return
  5775. }
  5776. for _, sv := range industryList {
  5777. allList = append(allList, sv)
  5778. }
  5779. } else {
  5780. allList = append(allList, list[i])
  5781. }
  5782. }
  5783. for i := 0; i < len(allList); i++ {
  5784. item := allList[i]
  5785. v := new(fms.ContractServiceTemplateMapItems)
  5786. v.ContractServiceTemplateItem = *item
  5787. allMap[item.ProductId] = append(allMap[item.ProductId], v)
  5788. }
  5789. allTitleMap := map[int]string{
  5790. 1: "FICC套餐",
  5791. 2: "权益套餐",
  5792. }
  5793. tmp1 := &fms.ContractServiceTemplateList{
  5794. Title: allTitleMap[1],
  5795. Children: allMap[1],
  5796. }
  5797. tmp2 := &fms.ContractServiceTemplateList{
  5798. Title: allTitleMap[2],
  5799. Children: allMap[2],
  5800. }
  5801. respList = append(respList, tmp1)
  5802. respList = append(respList, tmp2)
  5803. br.Ret = 200
  5804. br.Success = true
  5805. br.Msg = "获取成功"
  5806. br.Data = respList
  5807. }
  5808. // UnusualRenewCompanyStatistics
  5809. // @Title 获取续约异常的客户统计数据
  5810. // @Description 获取续约客户统计数据接口
  5811. // @Param DataType query string true "枚举值:week、month、time_interval"
  5812. // @Param Source query int true "类型,枚举值,1:续约异常客户;2:续约正常客户;3:超时续约客户;4:合同到期后一个月未续约客户;5:合同到期未续约客户;6:合同到期前一个月还未续约的客户;7:合同到期前两个月还未续约客户;8:合同到期前3个月还未续约客户;9:合同到期前4个月还未续约客户"
  5813. // @Param StartDate query string true "开始日期,格式:2022-04-06"
  5814. // @Param EndDate query string true "结束日期,格式:2022-04-06"
  5815. // @Success 200 {object} statistic_report.CompanyUnusualRenewRecordResp
  5816. // @router /report/unusual_renew_company [get]
  5817. func (this *StatisticReportController) UnusualRenewCompanyStatistics() {
  5818. br := new(models.BaseResponse).Init()
  5819. defer func() {
  5820. this.Data["json"] = br
  5821. this.ServeJSON()
  5822. }()
  5823. sysUser := this.SysUser
  5824. if sysUser == nil {
  5825. br.Msg = "请登录"
  5826. br.ErrMsg = "请登录,SysUser Is Empty"
  5827. br.Ret = 408
  5828. return
  5829. }
  5830. dataType := this.GetString("DataType")
  5831. productId, _ := this.GetInt("ProductId", 1)
  5832. startDate := this.GetString("StartDate")
  5833. endDate := this.GetString("EndDate")
  5834. source, _ := this.GetInt("Source", 1)
  5835. var companyUnusualRenewDataMapList []statistic_report.UnusualCompanyRenewDataMap
  5836. var err error
  5837. //var firstDate time.Time
  5838. switch dataType {
  5839. //获取列表
  5840. case "week":
  5841. nowWeekMonday := utils.GetNowWeekMonday() //本周周一
  5842. //companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
  5843. companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewWeekDataNum(nowWeekMonday, productId, source, 6)
  5844. if err != nil {
  5845. br.Msg = "数据异常"
  5846. br.ErrMsg = "数据异常,Err:" + err.Error()
  5847. return
  5848. }
  5849. case "month":
  5850. nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
  5851. companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewMonthDataNum(nowMonthFirstDay, productId, source, 6)
  5852. if err != nil {
  5853. br.Msg = "数据异常"
  5854. br.ErrMsg = "数据异常,Err:" + err.Error()
  5855. return
  5856. }
  5857. case "time_interval":
  5858. if startDate == `` || endDate == `` {
  5859. br.Msg = "开始日期或结束日期不能为空"
  5860. br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
  5861. return
  5862. }
  5863. companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewTimeIntervalData(productId, source, startDate, endDate)
  5864. if err != nil {
  5865. br.Msg = "数据异常"
  5866. br.ErrMsg = "数据异常,Err:" + err.Error()
  5867. return
  5868. }
  5869. }
  5870. groupId := 0
  5871. if utils.RunMode == "release" {
  5872. groupId = 37
  5873. } else {
  5874. groupId = 61
  5875. }
  5876. subAdmins, err := system.GetAdminByGroupId(groupId)
  5877. if err != nil && err.Error() != utils.ErrNoRow() {
  5878. br.Msg = "获取销售失败"
  5879. br.ErrMsg = "获取销售失败,Err:" + err.Error()
  5880. return
  5881. }
  5882. //数据处理
  5883. list := make([]statistic_report.GroupUnusualRenewRecord, 0)
  5884. summaryList := make([]statistic_report.SummaryUnusualRenewRecordNum, 0)
  5885. companyRenewRecordResp := statistic_report.CompanyUnusualRenewRecordResp{
  5886. List: list,
  5887. SummaryList: summaryList,
  5888. }
  5889. unusualRenewTotal := make(map[int]int)
  5890. adminDataUnusualRenewTotal := make(map[int]int)
  5891. // 每日期组数据的汇总客户id
  5892. companyIdIndexMap := make(map[int][]string)
  5893. for k, v := range subAdmins {
  5894. tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyUnusualRenewRecordNum, 0)
  5895. for index, adminData := range companyUnusualRenewDataMapList {
  5896. tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, statistic_report.CompanyUnusualRenewRecordNum{
  5897. UnusualRenewNum: adminData.UnusualRenewMap[v.AdminId],
  5898. UnusualRenewIds: adminData.UnusualRenewIdMap[v.AdminId],
  5899. StartDate: adminData.StartDate,
  5900. EndDate: adminData.EndDate,
  5901. })
  5902. unusualRenewTotal[index] = unusualRenewTotal[index] + adminData.UnusualRenewMap[v.AdminId]
  5903. if adminData.UnusualRenewIdMap[v.AdminId] != `` {
  5904. tmpCompanyIdList, ok := companyIdIndexMap[index]
  5905. if !ok {
  5906. tmpCompanyIdList = make([]string, 0)
  5907. }
  5908. companyIdIndexMap[index] = append(tmpCompanyIdList, adminData.UnusualRenewIdMap[v.AdminId])
  5909. adminDataUnusualRenewTotal[index] = adminData.FormalCompanyTotal
  5910. }
  5911. if k == 0 {
  5912. /*unusualRate := ``
  5913. if adminData.UnusualRenewTotal > 0 && adminData.FormalCompanyTotal > 0 {
  5914. unusualRate = decimal.NewFromInt(int64(adminData.UnusualRenewTotal)*100).Div(decimal.NewFromInt(int64(adminData.FormalCompanyTotal))).Round(2).String() + `%`
  5915. }*/
  5916. summaryList = append(summaryList, statistic_report.SummaryUnusualRenewRecordNum{
  5917. UnusualRenewNum: 0,
  5918. UnusualRate: "0",
  5919. })
  5920. }
  5921. }
  5922. list = append(list, statistic_report.GroupUnusualRenewRecord{
  5923. SellerId: v.AdminId,
  5924. SellerName: v.RealName,
  5925. CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
  5926. })
  5927. }
  5928. // 汇总数据
  5929. for index, _ := range summaryList {
  5930. totalSum, ok1 := unusualRenewTotal[index]
  5931. if ok1 {
  5932. summaryList[index].UnusualRenewNum = totalSum
  5933. unusualRate := ``
  5934. formalCompanyTotal, ok2 := adminDataUnusualRenewTotal[index]
  5935. if ok2 {
  5936. if totalSum > 0 && formalCompanyTotal > 0 {
  5937. unusualRate = decimal.NewFromInt(int64(totalSum)*100).Div(decimal.NewFromInt(int64(formalCompanyTotal))).Round(2).String() + `%`
  5938. summaryList[index].UnusualRate = unusualRate
  5939. }
  5940. }
  5941. }
  5942. tmpCompanyIdList, ok := companyIdIndexMap[index]
  5943. if ok {
  5944. summaryList[index].UnusualRenewIds = strings.Join(tmpCompanyIdList, ",")
  5945. }
  5946. }
  5947. companyRenewRecordResp.List = list
  5948. companyRenewRecordResp.SummaryList = summaryList
  5949. br.Ret = 200
  5950. br.Success = true
  5951. br.Msg = "获取成功"
  5952. br.Data = companyRenewRecordResp
  5953. }
  5954. // UnusualRenewCompanyList
  5955. // @Title 获取未续约的公司合同列表
  5956. // @Description 获取未续约的公司合同列表
  5957. // @Param ProductId query int false "套餐类型: 1-FICC(默认); 2-权益"
  5958. // @Param Source query int true "类型,枚举值,1:续约异常客户;2:续约正常客户;3:超时续约客户;4:合同到期后一个月未续约客户;5:合同到期未续约客户;6:合同到期前一个月还未续约的客户;7:合同到期前两个月还未续约客户;8:合同到期前3个月还未续约客户;9:合同到期前4个月还未续约客户"
  5959. // @Param StartDate query string true "开始日期,格式:2022-04"
  5960. // @Param EndDate query string true "结束日期,格式:2022-04"
  5961. // @Success 200 {object} company.GetUnusualRenewListGroupMonthResp
  5962. // @router /report/unusual_renew_company/chart [get]
  5963. func (this *StatisticReportController) UnusualRenewCompanyList() {
  5964. br := new(models.BaseResponse).Init()
  5965. defer func() {
  5966. this.Data["json"] = br
  5967. this.ServeJSON()
  5968. }()
  5969. sysUser := this.SysUser
  5970. if sysUser == nil {
  5971. br.Msg = "请登录"
  5972. br.ErrMsg = "请登录,SysUser Is Empty"
  5973. br.Ret = 408
  5974. return
  5975. }
  5976. // 起始日期
  5977. // 截止日期
  5978. productId, _ := this.GetInt("ProductId", 1)
  5979. startDate := this.GetString("StartDate")
  5980. endDate := this.GetString("EndDate")
  5981. source, _ := this.GetInt("Source", 1)
  5982. if startDate == `` || endDate == `` {
  5983. br.Msg = "开始日期或结束日期不能为空"
  5984. return
  5985. }
  5986. allList := make([]*company.GetUnusualRenewListGroupMonth, 0)
  5987. resp := new(company.GetUnusualRenewListGroupMonthResp)
  5988. resp.List = allList
  5989. newStartDate := startDate + "-01"
  5990. newEndDate := endDate + "-01"
  5991. startDateTimer, _ := time.ParseInLocation(utils.FormatDate, newStartDate, time.Local)
  5992. endDateTimer, _ := time.ParseInLocation(utils.FormatDate, newEndDate, time.Local)
  5993. endDateTimer = endDateTimer.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天
  5994. // 按月分组
  5995. monthMap := make(map[string]int)
  5996. monthCompanyMap := make(map[string]struct{})
  5997. monthList := make([]string, 0)
  5998. tmpDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, startDate, time.Local)
  5999. tmpEndDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, endDate, time.Local)
  6000. for tmpDate.Before(tmpEndDate) || tmpDate == tmpEndDate {
  6001. monthMap[tmpDate.Format(utils.FormatYearMonthDate)] = 0
  6002. monthList = append(monthList, tmpDate.Format(utils.FormatYearMonthDate))
  6003. tmpDate = tmpDate.AddDate(0, 1, 0)
  6004. }
  6005. // 只查询ficc销售下的客户
  6006. roleTypeCode := "('ficc_seller','ficc_group','ficc_team')"
  6007. researcherList, err := roadshow.GetSellerList(roleTypeCode, "")
  6008. if err != nil {
  6009. return
  6010. }
  6011. if err != nil && err.Error() != utils.ErrNoRow() {
  6012. br.Msg = "获取销售失败"
  6013. br.ErrMsg = "获取销售失败,Err:" + err.Error()
  6014. return
  6015. }
  6016. if len(researcherList) == 0 {
  6017. resp = &company.GetUnusualRenewListGroupMonthResp{
  6018. List: allList,
  6019. }
  6020. br.Ret = 200
  6021. br.Success = true
  6022. br.Msg = "获取成功"
  6023. br.Data = resp
  6024. return
  6025. }
  6026. subAdminIds := make([]string, 0)
  6027. for _, v := range researcherList {
  6028. subAdminIds = append(subAdminIds, strconv.Itoa(v.AdminId))
  6029. }
  6030. sellerIds := strings.Join(subAdminIds, ",")
  6031. list, err := company.GetUnusualRenewList(startDateTimer, endDateTimer, productId, source, sellerIds)
  6032. if err != nil {
  6033. br.Msg = "数据异常"
  6034. br.ErrMsg = "数据异常,Err:" + err.Error()
  6035. return
  6036. }
  6037. if len(list) > 0 {
  6038. for _, v := range list {
  6039. t := v.ModifyTime.Format(utils.FormatYearMonthDate)
  6040. name := fmt.Sprintf("%s_%d", t, v.CompanyId)
  6041. if _, ok := monthCompanyMap[name]; !ok {
  6042. if num, ok1 := monthMap[t]; ok1 {
  6043. monthMap[t] = num + 1
  6044. }
  6045. monthCompanyMap[name] = struct{}{}
  6046. }
  6047. }
  6048. }
  6049. for _, v := range monthList {
  6050. n, _ := monthMap[v]
  6051. tmp := &company.GetUnusualRenewListGroupMonth{
  6052. Date: v,
  6053. CompanyNum: n,
  6054. }
  6055. allList = append(allList, tmp)
  6056. }
  6057. resp = &company.GetUnusualRenewListGroupMonthResp{
  6058. List: allList,
  6059. }
  6060. br.Ret = 200
  6061. br.Success = true
  6062. br.Msg = "获取成功"
  6063. br.Data = resp
  6064. }
  6065. // StackCompanyListRai
  6066. // @Title 获取权益存量客户数据列表
  6067. // @Description 获取权益存量客户数据列表接口
  6068. // @Param PageSize query int true "每页数据条数"
  6069. // @Param CurrentIndex query int true "当前页页码,从1开始"
  6070. // @Param Keyword query string true "客户名称"
  6071. // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
  6072. // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
  6073. // @Param DataType query string false "报表类型,枚举值:`新签客户`,`续约客户`,`未续约客户`"
  6074. // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
  6075. // @Param IsExport query bool false "是否导出excel,默认是false"
  6076. // @Param CompanyAscribeId query int false "归因ID"
  6077. // @Success 200 {object} response.StackCompanyListResp
  6078. // @router /stack_company_list_rai [get]
  6079. func (this *StatisticReportController) StackCompanyListRai() {
  6080. br := new(models.BaseResponse).Init()
  6081. defer func() {
  6082. this.Data["json"] = br
  6083. this.ServeJSON()
  6084. }()
  6085. sysUser := this.SysUser
  6086. if sysUser == nil {
  6087. br.Msg = "请登录"
  6088. br.ErrMsg = "请登录,SysUser Is Empty"
  6089. br.Ret = 408
  6090. return
  6091. }
  6092. pageSize, _ := this.GetInt("PageSize")
  6093. currentIndex, _ := this.GetInt("CurrentIndex")
  6094. //是否导出报表
  6095. isExport, _ := this.GetBool("IsExport")
  6096. if isExport {
  6097. pageSize = 10000
  6098. currentIndex = 1
  6099. }
  6100. adminId := this.GetString("AdminId")
  6101. regionType := this.GetString("RegionType")
  6102. companyType := this.GetString("CompanyType")
  6103. dataType := this.GetString("DataType")
  6104. tryOutType := this.GetString("TryOutType")
  6105. keyword := this.GetString("Keyword")
  6106. companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
  6107. var resp response.StackCompanyListResp
  6108. //历史统计数据
  6109. //获取实时统计数据(今天数据)
  6110. tmpResp, err := getTodayStackCompanyListV2Rai(sysUser, currentIndex, pageSize, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
  6111. if err != nil {
  6112. br.Msg = "获取失败"
  6113. br.ErrMsg = "获取失败,Err:" + err.Error()
  6114. return
  6115. }
  6116. resp = tmpResp
  6117. //导出excel
  6118. if isExport {
  6119. StackCompanyListExportRai(this, dataType, resp, br)
  6120. return
  6121. }
  6122. br.Ret = 200
  6123. br.Success = true
  6124. br.Msg = "获取成功"
  6125. br.Data = resp
  6126. }
  6127. func getTodayStackCompanyListV2Rai(sysUser *system.Admin, currentIndex, pageSize, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
  6128. var startSize int
  6129. if pageSize <= 0 {
  6130. pageSize = utils.PageSize20
  6131. }
  6132. if currentIndex <= 0 {
  6133. currentIndex = 1
  6134. }
  6135. startSize = utils.StartIndex(currentIndex, pageSize)
  6136. var condition, listCondition string
  6137. var pars, listPars []interface{}
  6138. today := utils.GetToday(utils.FormatDate)
  6139. //条件
  6140. var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
  6141. var parsAscribeRai []interface{}
  6142. //归因ID CRM 13.9
  6143. if companyAscribeId > 0 {
  6144. var conditionAscribe string
  6145. var parsAscribe []interface{}
  6146. conditionAscribe = " AND company_ascribe_id = ? "
  6147. parsAscribe = append(parsAscribe, companyAscribeId)
  6148. companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
  6149. if e != nil && e.Error() != utils.ErrNoRow() {
  6150. err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
  6151. return
  6152. }
  6153. var companyIds []int
  6154. if len(companyNoRenewedAscribeList) == 0 {
  6155. companyIds = append(companyIds, 0) // 给一个不存在的ID
  6156. } else {
  6157. for _, v := range companyNoRenewedAscribeList {
  6158. companyIds = append(companyIds, v.CompanyId)
  6159. }
  6160. }
  6161. conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
  6162. parsAscribeRai = append(parsAscribeRai, companyIds)
  6163. }
  6164. if adminId != "" {
  6165. //condition += ` AND c.seller_id in (` + adminId + `) `
  6166. //pars = append(pars, adminId)
  6167. } else {
  6168. //根据当前角色来获取查询条件
  6169. condition, pars = getQueryParams(condition, pars, sysUser, "c.")
  6170. }
  6171. if regionType != "" {
  6172. condition += ` AND b.region_type = ? `
  6173. pars = append(pars, regionType)
  6174. }
  6175. //关键字搜索
  6176. if keyword != "" {
  6177. condition += ` and b.company_name like "%` + keyword + `%" `
  6178. }
  6179. condition += ` AND a.product_id = ? `
  6180. pars = append(pars, 2)
  6181. var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
  6182. var notRenewalTryOut, notRenewalNotTryOut int
  6183. var list []*models.IncrementalList
  6184. //新签客户数
  6185. {
  6186. condition1 := condition
  6187. if adminId != "" {
  6188. condition1 += ` AND a.seller_id_init in (` + adminId + `) `
  6189. }
  6190. pars1 := pars
  6191. //condition1 += ` AND c.status = "正式" `
  6192. condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
  6193. pars1 = append(pars1, today, today)
  6194. condition1 += ` AND a.contract_type = ? `
  6195. pars1 = append(pars1, "新签合同")
  6196. total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
  6197. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6198. err = countErr
  6199. return
  6200. }
  6201. newCompanyTotal = total
  6202. if dataType == "新签客户" {
  6203. //页表页数据总和
  6204. total, countErr = models.GetTodayStackCompanyProductCount(condition1, pars1)
  6205. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6206. err = countErr
  6207. return
  6208. }
  6209. dataTotal = total
  6210. listCondition = condition1
  6211. listPars = pars1
  6212. }
  6213. }
  6214. //续约客户数
  6215. {
  6216. condition1 := condition
  6217. if adminId != "" {
  6218. condition1 += ` AND a.seller_id_init in (` + adminId + `) `
  6219. }
  6220. pars1 := pars
  6221. //condition1 += ` AND c.status = "正式" `
  6222. condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
  6223. pars1 = append(pars1, today, today)
  6224. condition1 += ` AND a.contract_type = ? `
  6225. pars1 = append(pars1, "续约合同")
  6226. //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
  6227. pars1 = append(pars1, today)
  6228. total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
  6229. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6230. err = countErr
  6231. return
  6232. }
  6233. renewalCompanyTotal = total
  6234. if dataType == "续约客户" {
  6235. //页表页数据总和
  6236. total, countErr = models.GetTodayStackCompanyProductCountV2(condition1, pars1)
  6237. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6238. err = countErr
  6239. return
  6240. }
  6241. dataTotal = total
  6242. listCondition = condition1
  6243. listPars = pars1
  6244. }
  6245. }
  6246. //未续约客户数
  6247. {
  6248. if adminId != "" {
  6249. condition += ` AND c.seller_id in (` + adminId + `) `
  6250. }
  6251. condition1 := condition
  6252. pars1 := pars
  6253. condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
  6254. pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
  6255. condition1 += ` AND a.operation = 'try_out' `
  6256. total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
  6257. if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6258. err = countErr
  6259. return
  6260. }
  6261. notRenewalCompanyTotal = total
  6262. condition1 += conditionAscribRai
  6263. pars1 = append(pars1, parsAscribeRai)
  6264. if dataType == "未续约客户" {
  6265. //页表页数据总和
  6266. //统计数据
  6267. for _, v := range []string{"试用", "非试用"} {
  6268. totalCondition1 := condition1
  6269. totalPars1 := pars1
  6270. var tmpTotal int
  6271. if v == "试用" {
  6272. totalCondition1 += ` AND c.status = "试用" `
  6273. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  6274. if err != nil {
  6275. return
  6276. }
  6277. notRenewalTryOut = tmpTotal
  6278. } else if v == "非试用" {
  6279. totalCondition1 += ` AND c.status IN ("冻结","流失") `
  6280. tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
  6281. if err != nil && err.Error() != utils.ErrNoRow() {
  6282. return
  6283. }
  6284. notRenewalNotTryOut = tmpTotal
  6285. }
  6286. }
  6287. //列表数据数量
  6288. if tryOutType == "试用" {
  6289. condition1 += ` AND c.status = "试用" `
  6290. total = notRenewalTryOut
  6291. } else if tryOutType == "非试用" {
  6292. condition1 += ` AND c.status IN ("冻结","流失") `
  6293. total = notRenewalNotTryOut
  6294. }
  6295. //total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
  6296. //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
  6297. // err = countErr
  6298. // return
  6299. //}
  6300. dataTotal = total
  6301. listCondition = condition1
  6302. listPars = pars1
  6303. if tryOutType == "试用" {
  6304. listCondition += ` AND c.status = "试用" `
  6305. } else if tryOutType == "非试用" {
  6306. listCondition += ` AND c.status IN ("冻结","流失") `
  6307. }
  6308. tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
  6309. if countErr != nil {
  6310. err = countErr
  6311. return
  6312. }
  6313. for i := 0; i < len(tmpList); i++ {
  6314. endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
  6315. if parseErr != nil {
  6316. err = parseErr
  6317. return
  6318. }
  6319. tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
  6320. }
  6321. list = tmpList
  6322. }
  6323. }
  6324. switch dataType {
  6325. case "新签客户":
  6326. tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
  6327. if countErr != nil {
  6328. err = countErr
  6329. return
  6330. }
  6331. list = tmpList
  6332. case "续约客户":
  6333. tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
  6334. if countErr != nil {
  6335. err = countErr
  6336. return
  6337. }
  6338. list = tmpList
  6339. }
  6340. if dataType == "续约客户" {
  6341. var ids []string
  6342. oldCompanyMap := make(map[int]*models.IncrementalList)
  6343. oldMoneyMap := make(map[int]float64)
  6344. countMap := make(map[int]int)
  6345. for _, item := range list {
  6346. ids = append(ids, strconv.Itoa(item.CompanyId))
  6347. }
  6348. if len(ids) > 0 {
  6349. idStr := strings.Join(ids, ",")
  6350. lists, contractErr := models.GetLastContractMoney(idStr)
  6351. if contractErr != nil {
  6352. err = contractErr
  6353. return
  6354. }
  6355. for _, item := range lists {
  6356. _, countOk := countMap[item.CompanyId]
  6357. _, ok := oldCompanyMap[item.CompanyId]
  6358. if !ok {
  6359. oldCompanyMap[item.CompanyId] = item
  6360. oldMoneyMap[item.CompanyId] = item.Money
  6361. } else if !countOk {
  6362. countMap[item.CompanyId] = 1
  6363. oldCompanyMap[item.CompanyId] = item
  6364. }
  6365. }
  6366. //给list赋值
  6367. for _, item := range list {
  6368. if item.ProductName == "权益" {
  6369. oldMoney, _ := oldMoneyMap[item.CompanyId]
  6370. lastContract, _ := oldCompanyMap[item.CompanyId]
  6371. if oldMoney > lastContract.Money {
  6372. item.PackageDifference = "增加套餐"
  6373. } else if oldMoney < lastContract.Money {
  6374. item.PackageDifference = "减少套餐"
  6375. } else {
  6376. item.PackageDifference = "维持套餐"
  6377. }
  6378. }
  6379. }
  6380. }
  6381. }
  6382. var ascribecompanyIds []int
  6383. for _, item := range list {
  6384. ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
  6385. }
  6386. //归因标签
  6387. mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
  6388. mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
  6389. for _, item := range list {
  6390. item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  6391. item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  6392. item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
  6393. }
  6394. listLen := len(list)
  6395. var companyContractIds []int
  6396. for i := 0; i < listLen; i++ {
  6397. item := list[i]
  6398. //剩余可用天数
  6399. expireDay := "0"
  6400. endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
  6401. var sub time.Duration
  6402. if dataType != "未续约客户" {
  6403. endDateTime = endDateTime.AddDate(0, 0, 1)
  6404. sub = endDateTime.Sub(time.Now())
  6405. //if sub < 0 {
  6406. // sub = 0
  6407. //}
  6408. } else {
  6409. sub = time.Now().Sub(endDateTime)
  6410. }
  6411. expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
  6412. list[i].ExpireDay = expireDay
  6413. companyContractIds = append(companyContractIds, item.CompanyContractId)
  6414. }
  6415. //合并合同所对应的权限
  6416. mappermissionName, err := cygxService.GetCompanyContractPermissionNameMapById(companyContractIds)
  6417. if err != nil {
  6418. return
  6419. }
  6420. for _, v := range list {
  6421. v.PermissionName = mappermissionName[v.CompanyContractId]
  6422. }
  6423. var stackCompanyStatisticList []*models.StackCompanyStatisticList
  6424. for _, v := range list {
  6425. stackCompanyStatistic := models.StackCompanyStatisticList{
  6426. Type: dataType,
  6427. CompanyId: v.CompanyId,
  6428. CompanyName: v.CompanyName,
  6429. ProductId: v.ProductId,
  6430. ProductName: v.ProductName,
  6431. ContractNum: v.Count,
  6432. SellerId: v.SellerId,
  6433. SellerName: v.SellerNameInit,
  6434. ShareSeller: v.ShareSellerInit,
  6435. Date: today,
  6436. StartDate: v.StartDate,
  6437. EndDate: v.EndDate,
  6438. RegionType: v.RegionType,
  6439. //CreateTime :v.CreateTime,
  6440. CreateTimeStr: v.CreateTime,
  6441. ExpireDay: v.ExpireDay,
  6442. RenewalReason: v.RenewalReason,
  6443. RenewalTodo: v.RenewalTodo,
  6444. Status: v.Status,
  6445. PackageDifference: v.PackageDifference,
  6446. AscribeContent: v.AscribeContent,
  6447. IsShowNoRenewedNote: v.IsShowNoRenewedNote,
  6448. Content: v.Content,
  6449. PermissionName: mappermissionName[v.CompanyContractId],
  6450. Money: v.Money,
  6451. }
  6452. stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
  6453. }
  6454. page := paging.GetPaging(currentIndex, pageSize, dataTotal)
  6455. resp := response.StackCompanyListResp{
  6456. Paging: page,
  6457. List: stackCompanyStatisticList,
  6458. NewCompanyTotal: newCompanyTotal,
  6459. RenewalCompanyTotal: renewalCompanyTotal,
  6460. NotRenewalCompanyTotal: notRenewalCompanyTotal,
  6461. NotRenewalTryOut: notRenewalTryOut,
  6462. NotRenewalNotTryOut: notRenewalNotTryOut,
  6463. }
  6464. return resp, err
  6465. }