statistic_report.go 249 KB

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