statistic_report.go 234 KB

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