statistic_report.go 214 KB

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