123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975 |
- package controllers
- import (
- "encoding/json"
- "errors"
- "fmt"
- "github.com/rdlucklib/rdluck_tools/paging"
- "github.com/shopspring/decimal"
- "github.com/tealeg/xlsx"
- "hongze/hz_crm_api/models"
- "hongze/hz_crm_api/models/company"
- "hongze/hz_crm_api/models/fms"
- "hongze/hz_crm_api/models/response"
- "hongze/hz_crm_api/models/roadshow"
- statisticModels "hongze/hz_crm_api/models/statistic_report"
- "hongze/hz_crm_api/models/system"
- "hongze/hz_crm_api/services"
- "hongze/hz_crm_api/services/alarm_msg"
- contractService "hongze/hz_crm_api/services/contract"
- cygxService "hongze/hz_crm_api/services/cygx"
- fmsService "hongze/hz_crm_api/services/fms"
- "hongze/hz_crm_api/services/statistic_report"
- "hongze/hz_crm_api/utils"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "sync"
- "time"
- )
- // StatisticReportController 统计报告基类
- type StatisticReportController struct {
- BaseAuthController
- }
- // StatisticReportCommonController 统计报告
- type StatisticReportCommonController struct {
- BaseCommonController
- }
- // getQueryParams 获取基础查询信息
- func getQueryParams(condition string, pars []interface{}, sysUser *system.Admin, tableAlias string) (newCondition string, newPars []interface{}) {
- if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
- condition += " AND " + tableAlias + "product_id=?"
- pars = append(pars, 1)
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
- condition += " AND " + tableAlias + "product_id=?"
- pars = append(pars, 2)
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
- //超级管理员账户,不做条件限制
- } else {
- //如果不是研究员,那么去找对应的 部门、小组、销售
- if sysUser.Authority == 0 {
- //普通用户
- condition += " AND " + tableAlias + "seller_id=?"
- pars = append(pars, sysUser.AdminId)
- } else if sysUser.Authority == 1 {
- //部门主管
- condition += " AND " + tableAlias + "department_id=?"
- pars = append(pars, sysUser.DepartmentId)
- } else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_GROUP {
- //权益小组负责人
- condition += " AND " + tableAlias + "group_id=?"
- pars = append(pars, sysUser.GroupId)
- } else if sysUser.Authority == 2 && sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP {
- //ficc销售主管
- pid, err := company.GetParentIdFromGroup(sysUser.GroupId)
- if err != nil {
- fmt.Println(err.Error())
- return
- }
- var ids []*string
- if pid != nil && *pid != 0 {
- ids, err = company.GetGroupIdsByParentId(*pid)
- if err != nil {
- fmt.Println(err.Error())
- }
- } else {
- ids, err = company.GetGroupIdsByParentId(sysUser.GroupId)
- if err != nil {
- fmt.Println(err.Error())
- }
- }
- var idSlice []string
- var sid string
- for _, id := range ids {
- idSlice = append(idSlice, *id)
- }
- //加入父级groupId
- if *pid > 0 {
- idSlice = append(idSlice, strconv.Itoa(*pid))
- } else {
- idSlice = append(idSlice, strconv.Itoa(sysUser.GroupId))
- }
- sid = strings.Join(idSlice, ",")
- condition += " AND " + tableAlias + `group_id IN (` + sid + `) `
- fmt.Println("condition:", condition)
- //pars = append(pars, sysUser.GroupId)
- } else if sysUser.Authority == 4 {
- //ficc小组负责人
- condition += " AND " + tableAlias + "group_id=?"
- pars = append(pars, sysUser.GroupId)
- } else {
- //不知道什么类型的用户(后面新增的位置类型客户)
- condition += " AND " + tableAlias + "seller_id=?"
- pars = append(pars, sysUser.AdminId)
- }
- }
- newCondition = condition
- newPars = pars
- return
- }
- // Home
- // @Title 获取首页工作台数据
- // @Description 获取首页工作台数据接口
- // @Success 200 {object} response.WorktopResp
- // @router /home [get]
- func (this *StatisticReportController) Home() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- todayStr := utils.GetToday("20060102")
- //近6个月客户增量数据
- var incrementalCompanyChartList response.IncrementalCompanyChartResp
- ch := make(chan response.IncrementalCompanyChartResp, 1)
- go getIncrementalCompanyList(sysUser, ch)
- //未来6个月即将到期
- var willExpireList response.WillExpireChartResp
- ch2 := make(chan response.WillExpireChartResp, 1)
- go getWillExpireList(sysUser, ch2)
- //近6个月收入统计
- var incomeList response.IncomeChartResp
- ch3 := make(chan response.IncomeChartResp, 1)
- go getIncomeList(sysUser, ch3)
- var formalCompanyCount, trialCompanyTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- today := utils.GetToday(utils.FormatDate)
- //正式客户数
- {
- key := "admin:home:formalCompanyCount:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisCount, redisErr := utils.Rc.RedisInt(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "b.")
- condition += ` AND b.status = "正式" `
- tmpFormalCompanyCount, err := models.GetCurrCompanyCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取正式客户总数失败"
- br.ErrMsg = "获取正式客户总数失败,Err:" + err.Error()
- return
- }
- redisCount = tmpFormalCompanyCount
- _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- }
- formalCompanyCount = redisCount
- }
- //试用客户数
- {
- key := "admin:home:trialCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisCount, redisErr := utils.Rc.RedisInt(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- //condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- //condition += " AND a.create_time <= ?"
- //pars = append(pars, time.Now())
- //
- //condition += ` AND a.operation in ("add","receive")`
- //tmpTrialCompanyTotal, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
- condition, pars = getQueryParams(condition, pars, sysUser, "b.")
- condition += ` AND b.status = "试用" `
- tmpTrialCompanyTotal, err := models.GetCurrCompanyCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取试用客户总数失败"
- br.ErrMsg = "获取试用客户总数失败,Err:" + err.Error()
- return
- }
- redisCount = tmpTrialCompanyTotal
- _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- }
- trialCompanyTotal = redisCount
- }
- //新签客户数
- {
- key := "admin:home:newCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisCount, redisErr := utils.Rc.RedisInt(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- //condition += ` AND c.status ="正式" `
- condition += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars = append(pars, today, today)
- condition += ` AND a.contract_type = ? `
- pars = append(pars, "新签合同")
- total, err := models.GetIncrementalNewCompanyCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取新签客户失败"
- br.ErrMsg = "获取新签客户失败,Err:" + err.Error()
- return
- }
- redisCount = total
- _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- }
- newCompanyTotal = redisCount
- }
- //续约客户数
- {
- key := "admin:home:renewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisCount, redisErr := utils.Rc.RedisInt(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- //condition += ` AND c.status="正式" `
- condition += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars = append(pars, today, today)
- condition += ` AND a.contract_type = ? `
- pars = append(pars, "续约合同")
- total, err := models.GetIncrementalNewCompanyCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取续约客户失败"
- br.ErrMsg = "获取续约客户失败,Err:" + err.Error()
- return
- }
- redisCount = total
- _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- }
- renewalCompanyTotal = redisCount
- }
- //未续约客户数
- //{
- // key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- // redisCount, redisErr := utils.Rc.RedisInt(key)
- // if redisErr != nil {
- // var condition string
- // var pars []interface{}
- //
- // //根据当前角色来获取查询条件
- // condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- // condition += ` AND c.status not in ("永续","正式") `
- // total, err := models.GetIncrementalNewCompanyCount(condition, pars)
- // if err != nil && err.Error() != utils.ErrNoRow() {
- // br.Msg = "获取未续约客户失败"
- // br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
- // return
- // }
- // redisCount = total
- // _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- // }
- // notRenewalCompanyTotal = redisCount
- //}
- //未续约客户数
- {
- key := "admin:home:notRenewalCompanyTotal:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisCount, redisErr := utils.Rc.RedisInt(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- condition += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
- pars = append(pars, time.Now().Format(utils.FormatDateTime))
- condition += ` AND a.operation = 'try_out' `
- total, err := models.GetIncrementalCompanyCountByOperationRecord(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取未续约客户失败"
- br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
- return
- }
- redisCount = total
- _ = utils.Rc.Put(key, redisCount, time.Minute*30)
- }
- notRenewalCompanyTotal = redisCount
- }
- //合同数据
- contractChartData := response.ContractChartResp{}
- {
- key := "admin:home:contractChartData:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisContractChartData, redisErr := utils.Rc.RedisString(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- condition += ` AND a.end_date >= ? `
- pars = append(pars, today)
- //condition += ` AND c.status = "正式" `
- tmpContractCompanyCount, tmpContractTotal, tmpMoney, err := models.GetContractStatListCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取未续约客户失败"
- br.ErrMsg = "获取未续约客户失败,Err:" + err.Error()
- return
- }
- return
- }
- //数据赋值
- contractChartData.Title = "当前有效合同存量"
- contractChartData.FormalCompanyCount = tmpContractCompanyCount
- contractChartData.ContractTotal = tmpContractTotal
- contractChartData.MoneyTotal = tmpMoney
- //入缓存
- redisJsonData, err := json.Marshal(contractChartData)
- if err == nil {
- _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
- }
- } else {
- err := json.Unmarshal([]byte(redisContractChartData), &contractChartData)
- if err != nil {
- fmt.Println("合同数据,json转换失败:", err)
- }
- }
- }
- for v := range ch {
- incrementalCompanyChartList = v
- close(ch)
- }
- for v := range ch2 {
- willExpireList = v
- close(ch2)
- }
- for v := range ch3 {
- incomeList = v
- close(ch3)
- }
- resp := response.WorktopResp{
- FormalCompanyCount: formalCompanyCount,
- TrialCompanyTotal: trialCompanyTotal,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- IncrementalCompanyChartList: incrementalCompanyChartList,
- WillExpireChartList: willExpireList,
- IncomeChartList: incomeList,
- ContractData: contractChartData,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // 查询从2021/01开始的,每个月的客户增量数据
- func getIncrementalCompanyList(sysUser *system.Admin, ch chan response.IncrementalCompanyChartResp) (incrementalCompanyChart response.IncrementalCompanyChartResp, err error) {
- defer func() {
- if err != nil {
- go alarm_msg.SendAlarmMsg("查询近6个月的客户增量数据异常,Err:"+err.Error(), 3)
- //go utils.SendEmail(utils.APPNAME+"查询近6个月的客户增量数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
- }
- ch <- incrementalCompanyChart
- }()
- todayStr := utils.GetToday("20060102")
- key := "admin:home:incrementalCompanyList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisJsonData, redisErr := utils.Rc.RedisString(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- var dateSlice []string
- var newCompanySlice, renewalCompanySlice []int
- //var notRenewalCompanySlice []int
- yearNum := time.Now().Year() - 2021
- monthNum := time.Now().Month() - 1
- numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月
- for i := numMonth; i >= 0; i-- {
- timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
- dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
- //开始日期
- startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
- startDate = fmt.Sprint(startDate, "-01")
- //结束日期
- endDateTime := timeNow.AddDate(0, -i+1, 0)
- endDate := endDateTime.Format("2006-01")
- //因为就算是当月的后续事件还没到,也要计入数据统计,所以不做限制到当天处理
- //if endDateTime.After(time.Now()) {
- // endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
- //} else {
- // endDate = fmt.Sprint(endDate, "-01")
- //}
- endDate = fmt.Sprint(endDate, "-01")
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- newCompanySlice = append(newCompanySlice, total)
- }
- //续约客户数
- {
- //2022-02-07 13:26:48注释掉,更改成以下的逻辑,续约客户定义修改:续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
- //condition1 := condition
- //pars1 := pars
- //condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
- //pars1 = append(pars1, startDate, endDate)
- //condition1 += ` AND a.contract_type = ? `
- //pars1 = append(pars1, "续约合同")
- //total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- // err = countErr
- // return
- //}
- //renewalCompanySlice = append(renewalCompanySlice, total)
- //2022-02-07 13:26:48;更改成以下的逻辑,续约客户定义修改:续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
- pars1 = append(pars1, endDate)
- total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- renewalCompanySlice = append(renewalCompanySlice, total)
- }
- //未续约客户数
- //{
- // condition1 := condition
- // pars1 := pars
- //
- // condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
- // pars1 = append(pars1, fmt.Sprint(startDate, " 00:00:00"), fmt.Sprint(endDate, " 00:00:00"))
- // condition1 += ` AND a.operation = ? `
- // pars1 = append(pars1, "try_out")
- // total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- // if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- // err = countErr
- // return
- // }
- // notRenewalCompanySlice = append(notRenewalCompanySlice, total)
- //}
- }
- incrementalCompanyChart.Title = "客户增量图"
- incrementalCompanyChart.Date = dateSlice
- incrementalCompanyChart.NewCompanyTotal = newCompanySlice
- incrementalCompanyChart.RenewalCompanyTotal = renewalCompanySlice
- //incrementalCompanyChart.NotRenewalCompanyTotal = notRenewalCompanySlice
- redisJsonData, err := json.Marshal(incrementalCompanyChart)
- if err == nil {
- _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
- }
- } else {
- err = json.Unmarshal([]byte(redisJsonData), &incrementalCompanyChart)
- if err != nil {
- fmt.Println("近6个月客户增量图,json转换失败")
- }
- }
- return
- }
- // 获取未来近6个月的即将到期客户
- func getWillExpireList(sysUser *system.Admin, ch chan response.WillExpireChartResp) (willExpireChart response.WillExpireChartResp, err error) {
- defer func() {
- if err != nil {
- go alarm_msg.SendAlarmMsg("获取未来近6个月的即将到期客户数据异常,Err:"+err.Error(), 3)
- //go utils.SendEmail(utils.APPNAME+"获取未来近6个月的即将到期客户数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
- }
- ch <- willExpireChart
- }()
- todayStr := utils.GetToday("20060102")
- key := "admin:home:willExpireList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisJsonData, redisErr := utils.Rc.RedisString(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "a.")
- var dateSlice []string
- var companySlice []int
- for i := 0; i < 6; i++ {
- //timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
- //startDate := timeNow.Format(utils.FormatDate)
- startDate := utils.GetToday(utils.FormatDate)
- //endDate := timeNow.AddDate(0, i+1, 0).Format(utils.FormatDate)
- endDate := time.Now().AddDate(0, i+1, 0).Format(utils.FormatDate)
- dateSlice = append(dateSlice, fmt.Sprint("未来", i+1, "个月"))
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
- pars1 = append(pars1, startDate, endDate)
- total, countErr := models.GetWillExpireCompanyListCountV2(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- companySlice = append(companySlice, total)
- }
- willExpireChart.Title = "即将到期客户数"
- willExpireChart.Date = dateSlice
- willExpireChart.CompanyTotal = companySlice
- redisJsonData, err := json.Marshal(willExpireChart)
- if err == nil {
- _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
- }
- } else {
- err = json.Unmarshal([]byte(redisJsonData), &willExpireChart)
- if err != nil {
- fmt.Println("未来近6个月的即将到期客户,json转换失败")
- }
- }
- return
- }
- // 获取近12个月的收入统计数据
- func getIncomeList(sysUser *system.Admin, ch chan response.IncomeChartResp) (incomeChart response.IncomeChartResp, err error) {
- defer func() {
- if err != nil {
- go alarm_msg.SendAlarmMsg("获取近12个月的收入统计数据异常,Err:"+err.Error(), 3)
- //go utils.SendEmail(utils.APPNAME+"获取近12个月的收入统计数据异常:"+time.Now().Format("2006-01-02 15:04:05"), err.Error(), utils.EmailSendToUsers)
- }
- ch <- incomeChart
- }()
- todayStr := utils.GetToday("20060102")
- key := "admin:home:incomeList:" + todayStr + ":" + strconv.Itoa(sysUser.AdminId)
- redisJsonData, redisErr := utils.Rc.RedisString(key)
- if redisErr != nil {
- var condition string
- var pars []interface{}
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- var dateSlice []string
- var contractTotalSlice []int
- var moneySlice []float64
- yearNum := time.Now().Year() - 2021
- monthNum := time.Now().Month() - 1
- numMonth := yearNum*12 + int(monthNum) //距离2021-01存在多少个月
- for i := numMonth; i >= 0; i-- {
- timeNow, _ := time.Parse("2006-01", time.Now().Format("2006-01"))
- dateSlice = append(dateSlice, timeNow.AddDate(0, -i, 0).Format("06/01"))
- //开始日期
- startDate := timeNow.AddDate(0, -i, 0).Format("2006-01")
- startDate = fmt.Sprint(startDate, "-01")
- //结束日期
- endDateTime := timeNow.AddDate(0, -i+1, 0)
- endDate := endDateTime.Format("2006-01")
- //因为就算是当月的后续事件还没到,也要计入数据统计,所以不做限制到当天处理
- //if endDateTime.After(time.Now()) {
- // endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
- //} else {
- // endDate = fmt.Sprint(endDate, "-01")
- //}
- endDate = fmt.Sprint(endDate, "-01")
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date < ? `
- pars1 = append(pars1, startDate, endDate)
- total, money, countErr := models.GetIncomeListCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- contractTotalSlice = append(contractTotalSlice, total)
- moneySlice = append(moneySlice, money)
- }
- incomeChart.Title = "收入统计图"
- incomeChart.Date = dateSlice
- incomeChart.ContractTotal = contractTotalSlice
- incomeChart.MoneyTotal = moneySlice
- redisJsonData, err := json.Marshal(incomeChart)
- if err == nil {
- _ = utils.Rc.Put(key, string(redisJsonData), time.Minute*30)
- }
- } else {
- err = json.Unmarshal([]byte(redisJsonData), &incomeChart)
- if err != nil {
- fmt.Println("近6个月的收入统计数据,json转换失败")
- }
- }
- return
- }
- // WillExpireList
- // @Title 获取即将过期的客户列表
- // @Description 获取即将过期的客户列表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param StartDate query string true "开始日期"
- // @Param EndDate query string true "结束日期"
- // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Success 200 {object} response.WillExpireCompanyListResp
- // @router /will_expire_list [get]
- func (this *StatisticReportController) WillExpireList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- keyword := this.GetString("Keyword")
- if startDate == "" {
- startDate = time.Now().Format(utils.FormatDate)
- //br.Msg = "获取失败,开始日期未传"
- //br.ErrMsg = "获取失败,开始日期未传"
- //return
- }
- if endDate == "" {
- endDate = time.Now().AddDate(100, 0, 0).Format(utils.FormatDate)
- //br.Msg = "获取失败,结束日期未传"
- //br.ErrMsg = "获取失败,结束日期未传"
- //return
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition string
- var pars []interface{}
- //today := utils.GetToday(utils.FormatDate)
- condition += ` AND a.contract_end_date >= ? AND a.contract_end_date <= ? `
- pars = append(pars, startDate, endDate)
- if adminId != "" {
- condition += ` AND a.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "a.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- totalCompany, err := models.GetWillExpireCompanyListCountV2(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- totalContract, err := models.GetWillExpireContactListCountV2(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list, err := models.GetWillExpireCompanyListV2(condition, pars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- listLen := len(list)
- permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)
- if listLen > 0 {
- companyIdSlice := make([]string, 0)
- for _, v := range list {
- companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- }
- companyIds := strings.Join(companyIdSlice, ",")
- permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
- if permissionErr != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
- return
- }
- for _, permission := range permissionList {
- key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
- permissionListMap[key] = append(permissionListMap[key], permission)
- }
- }
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- if sub < 0 {
- sub = 0
- }
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
- if permissionList, ok := permissionListMap[key]; ok {
- for _, permission := range permissionList {
- if item.ProductId == permission.ProductId {
- list[i].PermissionList = append(list[i].PermissionList, permission)
- }
- }
- //list[i].PermissionList = permissionList
- }
- }
- page := paging.GetPaging(currentIndex, pageSize, totalContract)
- resp := response.WillExpireCompanyListResp{
- Paging: page,
- List: list,
- TotalCompany: totalCompany,
- }
- //导出excel
- if isExport {
- WillExpireListExport(this, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // WillExpireListExport 即将过期的客户报表导出
- func WillExpireListExport(this *StatisticReportController, resp response.WillExpireCompanyListResp, br *models.BaseResponse) {
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("即将到期客户数据")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 3, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("即将到期客户数:", resp.TotalCompany))
- //表头
- titleRow := sheel.AddRow()
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- cellTime := titleRow.AddCell()
- cellTime.SetStyle(style)
- cellTime.SetValue("服务期限")
- cellDay := titleRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue("剩余天数")
- for _, v := range resp.List {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
- cellDay := dataRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue(v.ExpireDay)
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "即将到期客户数据_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- func (this *StatisticReportController) WillExpireListOld() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- if startDate == "" {
- br.Msg = "获取失败,开始日期未传"
- br.ErrMsg = "获取失败,开始日期未传"
- return
- }
- if endDate == "" {
- br.Msg = "获取失败,结束日期未传"
- br.ErrMsg = "获取失败,结束日期未传"
- return
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition string
- var pars []interface{}
- //today := utils.GetToday(utils.FormatDate)
- condition += ` AND a.end_date >= ? AND a.end_date <= ? `
- pars = append(pars, startDate, endDate)
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- totalCompany, err := models.GetWillExpireCompanyListCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- totalContract, err := models.GetWillExpireContactListCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list, err := models.GetWillExpireCompanyList(condition, pars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- listLen := len(list)
- permissionListMap := make(map[string][]*company.CompanyReportPermissionAndName)
- if listLen > 0 {
- companyIdSlice := make([]string, 0)
- for _, v := range list {
- companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- }
- companyIds := strings.Join(companyIdSlice, ",")
- permissionList, permissionErr := company.GetCompanyReportPermissionListByCompanyIds(companyIds)
- if permissionErr != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
- return
- }
- for _, permission := range permissionList {
- key := fmt.Sprint(permission.CompanyId, "_", permission.ProductId)
- permissionListMap[key] = append(permissionListMap[key], permission)
- }
- }
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- if sub < 0 {
- sub = 0
- }
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- key := fmt.Sprint(item.CompanyId, "_", item.ProductId)
- if permissionList, ok := permissionListMap[key]; ok {
- for _, permission := range permissionList {
- if item.ProductId == permission.ProductId {
- list[i].PermissionList = append(list[i].PermissionList, permission)
- }
- }
- //list[i].PermissionList = permissionList
- }
- }
- page := paging.GetPaging(currentIndex, pageSize, totalContract)
- resp := response.WillExpireCompanyListResp{
- Paging: page,
- List: list,
- TotalCompany: totalCompany,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // ContractList
- // @Title 获取合同数据报表
- // @Description 获取合同数据报表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param EndDate query string true "结束日期"
- // @Param CompanyType query string false "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string false "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param DataType query string false "报表类型,枚举值:`普通数据`,`类型数据`;传空字符串或者不传为:普通数据"
- // @Param SourceType query string false "合同类型,枚举值:`系统合同`,`上传附件`;传空字符串或者不传为全部合同"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Success 200 {object} models.ContractStatListResp
- // @router /contract_list [get]
- func (this *StatisticReportController) ContractList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- endDate := this.GetString("EndDate")
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- keyword := this.GetString("Keyword")
- dataType := this.GetString("DataType") //数据报表类型
- sourceType := this.GetString("SourceType") //合同来源
- if endDate == "" {
- br.Msg = "获取失败,结束日期未传"
- br.ErrMsg = "获取失败,结束日期未传"
- return
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition string
- var pars []interface{}
- //上传附件
- var sourceFileCondition string
- var sourceFilePars []interface{}
- //系统合同
- var sourceSystemCondition string
- var sourceSystemPars []interface{}
- condition += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars = append(pars, endDate, endDate)
- sourceFileCondition += ` AND a.create_time <= ? `
- sourceFilePars = append(sourceFilePars, endDate)
- sourceSystemCondition += ` AND a.check_back_file_time <= "` + endDate + ` 23:59:59"`
- //sourceSystemPars = append(sourceSystemPars, endDate)
- //condition += ` AND c.status = "正式" `
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- sourceFileCondition += ` AND c.seller_id in (` + adminId + `) `
- sourceSystemCondition += ` AND a.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- sourceFileCondition, sourceFilePars = getQueryParams(sourceFileCondition, sourceFilePars, sysUser, "c.")
- //合同
- if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
- sourceSystemCondition += ` AND a.product_id=? `
- sourceSystemPars = append(sourceSystemPars, 1)
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
- sourceSystemCondition += ` AND a.product_id=? `
- sourceSystemPars = append(sourceSystemPars, 2)
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FINANCE {
- //超级管理员账户,不做条件限制
- } else {
- //如果不是研究员,那么去找对应的 部门、小组、销售
- if sysUser.Authority == 0 {
- //普通用户
- sourceSystemCondition += ` AND a.seller_id=? `
- sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
- } else if sysUser.Authority == 1 {
- //部门主管
- sourceSystemCondition += ` AND b.department_id=? `
- sourceSystemPars = append(sourceSystemPars, sysUser.DepartmentId)
- } else if sysUser.Authority == 2 {
- //小组负责人
- sourceSystemCondition += ` AND b.group_id=? `
- sourceSystemPars = append(sourceSystemPars, sysUser.GroupId)
- } else {
- //不知道什么类型的用户(后面新增的位置类型客户)
- sourceSystemCondition += ` AND a.seller_id=? `
- sourceSystemPars = append(sourceSystemPars, sysUser.AdminId)
- }
- }
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- dataTotal := 0 //页面数据总数
- total, totalContract, money, err := models.GetContractStatListCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //上传附件
- totalFileContract, err := models.GetContractStatListCountBySource("上传附件", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //系统合同
- totalSystemContract, err := models.GetContractStatListCountBySource("系统合同", sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list := make([]*models.ContractStatList, 0)
- if dataType == "类型数据" {
- if sourceType != "" {
- condition += ` AND a.source=? `
- pars = append(pars, sourceType)
- }
- //列表数据
- tmpList, err := models.GetContractStatListBySource(sourceType, sourceFileCondition, sourceSystemCondition, sourceFilePars, sourceSystemPars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- for _, v := range tmpList {
- if v.ProductId == 1 {
- v.ProductName = "ficc"
- } else {
- v.ProductName = "权益"
- }
- }
- list = tmpList
- } else {
- //列表数据
- tmpList, err := models.GetContractStatList(condition, pars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- }
- //listLen := len(list)
- //for i := 0; i < listLen; i++ {
- // item := list[i]
- //}
- if dataType == "类型数据" {
- switch sourceType {
- case "上传附件":
- dataTotal = totalFileContract
- case "系统合同":
- dataTotal = totalSystemContract
- default:
- dataTotal = totalFileContract + totalSystemContract
- }
- } else {
- dataTotal = total
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.ContractStatListResp{
- Paging: page,
- List: list,
- TotalMoney: money,
- TotalCompany: total,
- TotalFileContract: totalFileContract,
- TotalSystemContract: totalSystemContract,
- TotalContract: totalContract,
- }
- //导出excel
- if isExport {
- ContractListExport(this, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // ContractListExport 合同数据报表导出
- func ContractListExport(this *StatisticReportController, resp response.ContractStatListResp, br *models.BaseResponse) {
- dataType := this.GetString("DataType") //数据报表类型
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("合同数据报表")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 5, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("有效合同数:", resp.TotalContract))
- cell2 := statisticRow.AddCell()
- cell2.SetStyle(style)
- cell2.SetValue(fmt.Sprint("有效合同总金额:", resp.TotalMoney))
- cell3 := statisticRow.AddCell()
- cell3.SetStyle(style)
- cell3.SetValue(fmt.Sprint("正式客户数:", resp.TotalCompany))
- cell4 := statisticRow.AddCell()
- cell4.SetStyle(style)
- cell4.SetValue(fmt.Sprint("总上传附件合同数:", resp.TotalFileContract))
- cell5 := statisticRow.AddCell()
- cell5.SetStyle(style)
- cell5.SetValue(fmt.Sprint("总系统生成合同数:", resp.TotalSystemContract))
- //表头
- titleRow := sheel.AddRow()
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- if dataType == "类型数据" {
- cellContractNum := titleRow.AddCell()
- cellContractNum.SetStyle(style)
- cellContractNum.SetValue("生成方式")
- cellContractPrice := titleRow.AddCell()
- cellContractPrice.SetStyle(style)
- cellContractPrice.SetValue("合同提交时间")
- } else {
- cellContractNum := titleRow.AddCell()
- cellContractNum.SetStyle(style)
- cellContractNum.SetValue("有效合同数")
- cellContractPrice := titleRow.AddCell()
- cellContractPrice.SetStyle(style)
- cellContractPrice.SetValue("有效合同总金额")
- }
- for _, v := range resp.List {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- if dataType == "类型数据" {
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- cellDataTime.SetValue(v.Source)
- cellDay := dataRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue(v.CreateTime)
- } else {
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- cellDataTime.SetValue(v.Count)
- cellDay := dataRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue(v.SumMoney)
- }
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "合同数据报表_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- // CompanyContractList
- // @Title 获取企业客户的合同数据报表
- // @Description 获取企业客户的合同数据报表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param EndDate query string true "结束日期"
- // @Param CompanyId query int true "企业客户id"
- // @Success 200 {object} response.CompanyContractStatListResp
- // @router /company_contract_list [get]
- func (this *StatisticReportController) CompanyContractList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- endDate := this.GetString("EndDate")
- companyId := this.GetString("CompanyId")
- //companyType := this.GetString("CompanyType")
- if endDate == "" {
- br.Msg = "获取失败,结束日期未传"
- br.ErrMsg = "获取失败,结束日期未传"
- return
- }
- sysUser := this.SysUser
- var condition string
- var pars []interface{}
- condition += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars = append(pars, endDate, endDate)
- if companyId == "" {
- br.Msg = "获取失败,客户id未传"
- br.ErrMsg = "获取失败,客户id未传"
- return
- }
- condition += ` AND a.company_id = ? `
- pars = append(pars, companyId)
- //根据当前角色来获取查询条件
- if strings.Contains(sysUser.RoleTypeCode, "ficc") {
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- } else if strings.Contains(sysUser.RoleTypeCode, "rai") {
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- }
- //switch companyType {
- //case "ficc":
- // condition += ` AND a.product_id = ? `
- // pars = append(pars, 1)
- //case "权益":
- // condition += ` AND a.product_id = ? `
- // pars = append(pars, 2)
- //case "":
- //default:
- // br.Msg = "获取失败,客户类型异常"
- // br.ErrMsg = "获取失败,客户类型异常"
- // return
- //}
- list, err := models.GetCompanyContractStatList(condition, pars)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- listLen := len(list)
- permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
- if listLen > 0 {
- companyContractIdSlice := make([]string, 0)
- for _, v := range list {
- companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
- }
- companyContractIds := strings.Join(companyContractIdSlice, ",")
- permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
- if permissionErr != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
- return
- }
- // CRM8.8-权益权限主客观合并
- permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)
- //列表数据处理
- for i := 0; i < listLen; i++ {
- item := list[i]
- //权限拼接
- companyContractPermissionList := make([]models.CompanyContractPermission, 0)
- companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
- for _, permission := range permissionList {
- if permission.IsUpgrade == 1 {
- permission.ChartPermissionName += "(升级)"
- }
- if permission.CompanyContractId == item.CompanyContractId {
- companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
- }
- permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
- }
- for classifyName, permissionList := range companyContractPermissionMap {
- companyContractPermission := models.CompanyContractPermission{
- ClassifyName: classifyName,
- PermissionList: permissionList,
- }
- companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
- }
- list[i].PermissionList = companyContractPermissionList
- }
- }
- resp := response.CompanyContractStatListResp{
- List: list,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // ContractDetailList
- // @Title 获取合同详情
- // @Description 获取企业客户的合同数据报表接口
- // @Param CompanyContractId query int true "客户合同id,进行过客户申请的"
- // @Param ContractId query int true "系统合同id"
- // @Success 200 {object} response.CompanyContractStatListResp
- // @router /contract_detail_list [get]
- func (this *StatisticReportController) ContractDetailList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- list := make([]*models.CompanyContractStatList, 0)
- item := models.CompanyContractStatList{}
- companyContractId, _ := this.GetInt("CompanyContractId")
- contractId, _ := this.GetInt("ContractId")
- companyContractPermissionList := make([]models.CompanyContractPermission, 0)
- if companyContractId > 0 {
- contractInfo, err := company.GetCompanyContractDetailByCompanyContractId(companyContractId)
- if err != nil {
- br.Msg = "获取合同失败"
- br.ErrMsg = "获取合同失败,Err:" + err.Error()
- return
- }
- permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
- permissionList, err := company.GetCompanyContractPermissionListByContractId(contractInfo.CompanyContractId)
- if err != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + err.Error()
- return
- }
- companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
- for _, permission := range permissionList {
- //权限拼接
- if permission.IsUpgrade == 1 {
- permission.PermissionName += "(升级)"
- }
- companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
- permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
- }
- for classifyName, permissionList := range companyContractPermissionMap {
- companyContractPermission := models.CompanyContractPermission{
- ClassifyName: classifyName,
- PermissionList: permissionList,
- }
- companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
- }
- item = models.CompanyContractStatList{
- CompanyContractId: contractInfo.CompanyContractId,
- ContractType: contractInfo.ContractType,
- ProductId: contractInfo.ProductId,
- ProductName: contractInfo.ProductName,
- CompanyId: contractInfo.CompanyId,
- ContractCode: contractInfo.ContractCode,
- StartDate: contractInfo.StartDate,
- EndDate: contractInfo.EndDate,
- Money: contractInfo.Money,
- PayMethod: contractInfo.PayMethod,
- PayChannel: contractInfo.PayChannel,
- PermissionList: companyContractPermissionList,
- }
- list = append(list, &item)
- } else if contractId > 0 {
- contractInfo, err := contractService.GetContractDetail(contractId)
- if err != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + err.Error()
- return
- }
- productName := "ficc"
- if contractInfo.ProductId == 2 {
- productName = `权益`
- }
- //合同中包含的产品权限
- permissionLookList, _ := contractService.GetPermissionByContractService(contractInfo.ProductId, contractInfo.Service)
- //权限处理
- for _, v := range permissionLookList {
- permissionList := make([]*company.CompanyContractPermissionName, 0)
- checkIdMap := make(map[int]int)
- for _, checkId := range v.CheckList {
- checkIdMap[checkId] = checkId
- }
- for _, permission := range v.Items {
- if _, ok := checkIdMap[permission.ChartPermissionId]; ok {
- tmpCompanyContractPermissionName := &company.CompanyContractPermissionName{
- ChartPermissionId: permission.ChartPermissionId,
- ChartPermissionName: permission.PermissionName,
- ClassifyName: permission.ClassifyName,
- StartDate: permission.StartDate,
- EndDate: permission.EndDate,
- //CreateTime :permission.ChartPermissionId,
- //ModifyTime :permission.ChartPermissionId,
- }
- permissionList = append(permissionList, tmpCompanyContractPermissionName)
- }
- }
- if len(permissionList) > 0 {
- companyContractPermission := models.CompanyContractPermission{
- ClassifyName: v.ClassifyName,
- PermissionList: permissionList,
- }
- companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
- }
- }
- item = models.CompanyContractStatList{
- //CompanyContractId :contractInfo.CompanyContractId,
- ContractType: contractInfo.ContractType,
- ProductId: contractInfo.ProductId,
- ProductName: productName,
- ContractCode: contractInfo.ContractCode,
- StartDate: contractInfo.StartDate.Format(utils.FormatDate),
- EndDate: contractInfo.EndDate.Format(utils.FormatDate),
- Money: contractInfo.Price,
- PayMethod: contractInfo.PayRemark,
- PayChannel: contractInfo.PayChannel,
- PermissionList: companyContractPermissionList,
- }
- list = append(list, &item)
- }
- resp := response.CompanyContractStatListResp{
- List: list,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // IncomeList
- // @Title 获取收入统计列表
- // @Description 获取收入统计列表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param StartDate query string true "开始月份"
- // @Param EndDate query string true "结束月份"
- // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Success 200 {object} response.IncomeListResp
- // @router /income_list [get]
- func (this *StatisticReportController) IncomeList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- keyword := this.GetString("Keyword")
- //if startDate == "" || endDate == "" {
- // br.Msg = "获取失败,开始日期或结束日期未传"
- // br.ErrMsg = "获取失败,开始日期或结束日期未传"
- // return
- //}
- if startDate == "" {
- startDate = "2015-01"
- }
- if endDate == "" {
- endDate = time.Now().AddDate(100, 0, 0).Format("2006-01")
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- var condition string
- var pars []interface{}
- //开始时间
- startDayTimes, startDayErr := time.Parse("2006-01", startDate)
- if startDayErr != nil {
- br.Msg = "获取失败,开始日期格式异常"
- br.ErrMsg = "获取失败,开始日期格式异常" + startDayErr.Error()
- return
- }
- startDay := startDayTimes.Format(utils.FormatDate)
- //结束时间
- endDayTimes, endDayErr := time.Parse("2006-01", endDate)
- if endDayErr != nil {
- br.Msg = "获取失败,结束日期格式异常"
- br.ErrMsg = "获取失败,结束日期格式异常" + endDayErr.Error()
- return
- }
- //本月最后一天
- endDayTimes = endDayTimes.AddDate(0, 1, -1)
- endDay := endDayTimes.Format(utils.FormatDate)
- //条件
- condition += ` AND a.start_date >= ? AND a.start_date <= ?`
- pars = append(pars, startDay, endDay)
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- total, money, err := models.GetIncomeListCount(condition, pars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list, err := models.GetIncomeList(condition, pars, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- listLen := len(list)
- if listLen > 0 {
- permissionListMap := make(map[int][]*company.CompanyContractPermissionName)
- companyContractIdSlice := make([]string, 0)
- for _, v := range list {
- companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
- }
- companyContractIds := strings.Join(companyContractIdSlice, ",")
- //49, 50,28
- permissionList, permissionErr := company.GetCompanyContractPermissionListByContractIds(companyContractIds)
- if permissionErr != nil {
- br.Msg = "获取权限失败"
- br.ErrMsg = "获取权限失败,Err:" + permissionErr.Error()
- return
- }
- // CRM8.8-权益主客观权限合并
- permissionList = contractService.EquityMergeSubjectAndObjectPermission(permissionList)
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- if sub < 0 {
- sub = 0
- }
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- //权限拼接
- companyContractPermissionList := make([]models.CompanyContractPermission, 0)
- companyContractPermissionMap := make(map[string][]*company.CompanyContractPermissionName)
- for _, permission := range permissionList {
- if permission.CompanyContractId == item.CompanyContractId {
- if permission.IsUpgrade == 1 {
- permission.ChartPermissionName += "(升级)"
- }
- companyContractPermissionMap[permission.ClassifyName] = append(companyContractPermissionMap[permission.ClassifyName], permission)
- }
- permissionListMap[permission.CompanyContractId] = append(permissionListMap[permission.CompanyContractId], permission)
- }
- for classifyName, permissionList := range companyContractPermissionMap {
- companyContractPermission := models.CompanyContractPermission{
- ClassifyName: classifyName,
- PermissionList: permissionList,
- }
- companyContractPermissionList = append(companyContractPermissionList, companyContractPermission)
- }
- list[i].PermissionList = companyContractPermissionList
- }
- }
- page := paging.GetPaging(currentIndex, pageSize, total)
- resp := response.IncomeListResp{
- Paging: page,
- List: list,
- Total: total,
- Money: money,
- }
- //导出excel
- if isExport {
- IncomeListExport(this, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // IncomeListExport 收入统计报表导出
- func IncomeListExport(this *StatisticReportController, resp response.IncomeListResp, br *models.BaseResponse) {
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("收入统计报表")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 3, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("签约合同数:", resp.Total))
- cell2 := statisticRow.AddCell()
- cell2.SetStyle(style)
- cell2.SetValue(fmt.Sprint("签约合同总金额:", resp.Money))
- //表头
- titleRow := sheel.AddRow()
- cellContractNo := titleRow.AddCell()
- cellContractNo.SetStyle(style)
- cellContractNo.SetValue("合同编号")
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- cellContractPrice := titleRow.AddCell()
- cellContractPrice.SetStyle(style)
- cellContractPrice.SetValue("合同金额")
- cellContractPayMethod := titleRow.AddCell()
- cellContractPayMethod.SetStyle(style)
- cellContractPayMethod.SetValue("付款方式")
- cellContractPayChannel := titleRow.AddCell()
- cellContractPayChannel.SetStyle(style)
- cellContractPayChannel.SetValue("付款渠道")
- cellContractDate := titleRow.AddCell()
- cellContractDate.SetStyle(style)
- cellContractDate.SetValue("服务期限")
- for _, v := range resp.List {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataContractNo := dataRow.AddCell()
- cellDataContractNo.SetStyle(style)
- cellDataContractNo.SetValue(v.ContractCode)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- cellDataPrice := dataRow.AddCell()
- cellDataPrice.SetStyle(style)
- cellDataPrice.SetValue(v.Money)
- cellDataPayMethod := dataRow.AddCell()
- cellDataPayMethod.SetStyle(style)
- cellDataPayMethod.SetValue(v.PayMethod)
- cellDataPayChannel := dataRow.AddCell()
- cellDataPayChannel.SetStyle(style)
- cellDataPayChannel.SetValue(v.PayChannel)
- cellDay := dataRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "收入统计报表_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- // StackCompanyList
- // @Title 获取存量客户数据列表
- // @Description 获取存量客户数据列表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param Date query string false "日期"
- // @Param DataType query string false "报表类型,枚举值:`新签客户`,`续约客户`,`未续约客户`"
- // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Param IsConfirm query int false "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
- // @Param CompanyAscribeId query int false "归因ID"
- // @Success 200 {object} response.StackCompanyListResp
- // @router /stack_company_list [get]
- func (this *StatisticReportController) StackCompanyList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- dataType := this.GetString("DataType")
- tryOutType := this.GetString("TryOutType")
- keyword := this.GetString("Keyword")
- date := this.GetString("Date")
- isConfirm, _ := this.GetInt("IsConfirm", -1) // CRM 13.9
- companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
- if date == "" {
- br.Msg = "获取失败,请选择日期"
- br.ErrMsg = "获取失败,请选择日期"
- return
- }
- //获取筛选时间的时间戳
- formatTime, err := time.Parse(utils.FormatDate, date)
- if err != nil {
- br.Msg = "获取失败,日期格式异常"
- br.ErrMsg = "获取失败,日期格式异常"
- return
- }
- dateTime := formatTime.Unix()
- //获取今天零点的时间戳
- todayStr := time.Now().Format(utils.FormatDate)
- todayTime, _ := time.Parse(utils.FormatDate, todayStr)
- todayTimeNumber := todayTime.Unix()
- var resp response.StackCompanyListResp
- //历史统计数据
- if dateTime < todayTimeNumber {
- tmpResp, err := getHistoryStackCompanyList(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, date, keyword)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- resp = tmpResp
- } else {
- //获取实时统计数据(今天数据)
- tmpResp, err := getTodayStackCompanyListV2(sysUser, currentIndex, pageSize, isConfirm, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- resp = tmpResp
- }
- //导出excel
- if isExport {
- StackCompanyListExport(this, dataType, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // StackCompanyListExport 获取存量客户数据报表导出
- func StackCompanyListExport(this *StatisticReportController, dataType string, resp response.StackCompanyListResp, br *models.BaseResponse) {
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("存量客户数据")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 3, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("新签客户数:", resp.NewCompanyTotal))
- cell2 := statisticRow.AddCell()
- cell2.SetStyle(style)
- cell2.SetValue(fmt.Sprint("续约客户数:", resp.RenewalCompanyTotal))
- cell3 := statisticRow.AddCell()
- cell3.SetStyle(style)
- cell3.SetValue(fmt.Sprint("未续约客户数:", resp.NotRenewalCompanyTotal))
- //表头
- titleRow := sheel.AddRow()
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- switch dataType {
- case "未续约客户":
- cellTime := titleRow.AddCell()
- cellTime.SetStyle(style)
- cellTime.SetValue("最近合同到期时间")
- cellRemark := titleRow.AddCell()
- cellRemark.SetStyle(style)
- cellRemark.SetValue("未续约说明")
- cellDay := titleRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue("超出过期天数")
- cellAscribeContent := titleRow.AddCell()
- cellAscribeContent.SetStyle(style)
- cellAscribeContent.SetValue("不续约归因")
- cellContent := titleRow.AddCell()
- cellContent.SetStyle(style)
- cellContent.SetValue("详细原因")
- default:
- cellTime := titleRow.AddCell()
- cellTime.SetStyle(style)
- cellTime.SetValue("服务期限")
- cellDay := titleRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue("剩余天数")
- }
- for _, v := range resp.List {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- switch dataType {
- case "新签客户":
- cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
- case "续约客户":
- cellDataTime.SetValue(fmt.Sprint(v.StartDate, " ~ ", v.EndDate))
- case "未续约客户":
- cellDataTime.SetValue(v.EndDate)
- //未续约说明
- cellDataRemark := dataRow.AddCell()
- cellDataRemark.SetStyle(style)
- cellDataRemark.SetValue(v.RenewalReason)
- }
- cellDay := dataRow.AddCell()
- cellDay.SetStyle(style)
- cellDay.SetValue(v.ExpireDay)
- switch dataType {
- case "未续约客户":
- cellAscribeContent := dataRow.AddCell()
- cellAscribeContent.SetStyle(style)
- cellAscribeContent.SetValue(v.AscribeContent)
- cellContent := dataRow.AddCell()
- cellContent.SetStyle(style)
- cellContent.SetValue(v.Content)
- }
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "存量客户数据_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- // 获取历史的数据
- func getHistoryStackCompanyList(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, date, keyword string) (returnData response.StackCompanyListResp, err error) {
- if date == "" {
- err = errors.New("请选择日期")
- return
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition string
- var pars []interface{}
- //条件
- condition += ` AND date = ? `
- pars = append(pars, date)
- var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
- var parsAscribeRai []interface{}
- //是否确认续约 CRM 13.9
- if isConfirm != -1 {
- var conditionConfirm string
- var parsConfirm []interface{}
- companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
- if e != nil && e.Error() != utils.ErrNoRow() {
- err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
- return
- }
- var companyIds []int
- if len(companyConfirmList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyConfirmList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- if isConfirm == 0 {
- conditionAscribRai += ` AND c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 待确认
- } else {
- conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)` // 已确认
- }
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- //归因ID CRM 13.9
- if companyAscribeId > 0 {
- var conditionAscribe string
- var parsAscribe []interface{}
- conditionAscribe = " AND company_ascribe_id = ? "
- parsAscribe = append(parsAscribe, companyAscribeId)
- companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
- if e != nil && e.Error() != utils.ErrNoRow() {
- err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
- return
- }
- var companyIds []int
- if len(companyNoRenewedAscribeList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyNoRenewedAscribeList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- if adminId != "" {
- condition += ` AND a.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "a.")
- }
- if regionType != "" {
- condition += ` AND region_type = ? `
- pars = append(pars, regionType)
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- err = errors.New("客户类型异常")
- return
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and c.company_name like "%` + keyword + `%" `
- }
- var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- var notRenewalTryOut, notRenewalNotTryOut int
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.type = ? `
- pars1 = append(pars, "新签客户")
- total, countErr := models.GetStackCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //列表页数据总和
- total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- }
- }
- //续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.type = ? `
- pars1 = append(pars, "续约客户")
- total, countErr := models.GetStackCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //列表页数据总和
- total, countErr := models.GetStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- }
- }
- //未续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.type = ? `
- pars1 = append(pars, "未续约客户")
- total, countErr := models.GetStackCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- notRenewalCompanyTotal = total
- condition1 += conditionAscribRai
- pars1 = append(pars1, parsAscribeRai)
- if dataType == "未续约客户" {
- //列表页数据总和
- //统计数据
- for _, v := range []string{"试用", "非试用"} {
- totalCondition1 := condition1
- totalPars1 := pars1
- var tmpTotal int
- if v == "试用" {
- totalCondition1 += ` AND b.status = "试用" `
- tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
- if err != nil {
- return
- }
- notRenewalTryOut = tmpTotal
- } else if v == "非试用" {
- totalCondition1 += ` AND b.status IN ("冻结","流失") `
- tmpTotal, err = models.GetNotRenewalStackCompanyProductCount(totalCondition1, totalPars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- return
- }
- notRenewalNotTryOut = tmpTotal
- }
- }
- //列表数据数量
- if tryOutType == "试用" {
- condition1 += ` AND b.status = "试用" `
- total = notRenewalTryOut
- } else if tryOutType == "非试用" {
- condition1 += ` AND b.status IN ("冻结","流失") `
- total = notRenewalNotTryOut
- }
- total, countErr := models.GetNotRenewalStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- }
- }
- //报表类型,新签客户`,`续约客户`,`未续约客户`
- condition += ` AND a.type = ? `
- pars = append(pars, dataType)
- orderBy := ``
- if dataType == "新签客户" || dataType == "续约客户" {
- orderBy = `start_date desc`
- }
- if tryOutType == "试用" {
- condition += ` AND b.status = "试用" `
- } else if tryOutType == "非试用" {
- condition += ` AND b.status IN ("冻结","流失") `
- }
- list, countErr := models.GetStackCompanyList(condition, orderBy, pars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- listLen := len(list)
- //moreListMap := make(map[int][]*models.StackCompanyStatisticList)
- if dataType == "续约客户" {
- var ids []string
- var ascribecompanyIds []int
- oldCompanyMap := make(map[int]*models.IncrementalList)
- oldMoneyMap := make(map[int]float64)
- countMap := make(map[int]int)
- for _, item := range list {
- ids = append(ids, strconv.Itoa(item.CompanyId))
- ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
- }
- //归因标签
- mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
- mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
- if len(ids) > 0 {
- idStr := strings.Join(ids, ",")
- lists, contractErr := models.GetLastContractMoney(idStr)
- if contractErr != nil {
- err = contractErr
- return
- }
- for _, item := range lists {
- _, countOk := countMap[item.CompanyId]
- _, ok := oldCompanyMap[item.CompanyId]
- if !ok {
- oldCompanyMap[item.CompanyId] = item
- oldMoneyMap[item.CompanyId] = item.Money
- } else if !countOk {
- countMap[item.CompanyId] = 1
- oldCompanyMap[item.CompanyId] = item
- }
- }
- //给list赋值
- for _, item := range list {
- if item.ProductName == "权益" {
- oldMoney, _ := oldMoneyMap[item.CompanyId]
- lastContract, _ := oldCompanyMap[item.CompanyId]
- if oldMoney > lastContract.Money {
- item.PackageDifference = "增加套餐"
- } else if oldMoney < lastContract.Money {
- item.PackageDifference = "减少套餐"
- } else {
- item.PackageDifference = "维持套餐"
- }
- }
- item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- }
- }
- }
- //获取其他产品数据
- //if listLen > 0 {
- // companyIdSlice := make([]string, 0)
- // statisticIdSlice := make([]string, 0)
- // for _, v := range list {
- // if v.Count > 1 {
- // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- // statisticIdSlice = append(statisticIdSlice, strconv.Itoa(v.StatisticId))
- // }
- // }
- // if len(companyIdSlice) > 0 {
- // companyIds := strings.Join(companyIdSlice, ",")
- // statisticIds := strings.Join(statisticIdSlice, ",")
- // stackCompanyList2, list2Err := models.GetStackCompanyListByCompanyIds(companyIds, statisticIds, condition, pars)
- // //companyType
- // if list2Err != nil {
- // err = errors.New("获取其他产品失败,Err:" + list2Err.Error())
- // return
- // }
- //
- // for _, stackCompany := range stackCompanyList2 {
- // moreListMap[stackCompany.CompanyId] = append(moreListMap[stackCompany.CompanyId], stackCompany)
- // }
- // }
- //}
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- //if sub < 0 {
- // sub = 0
- //}
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- //其他产品数据处理
- //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
- // for _, otherCompanyProduct := range otherCompanyProductList {
- // list[i].ProductName += "/" + otherCompanyProduct.ProductName
- // list[i].SellerName += "/" + otherCompanyProduct.SellerName
- // list[i].StartDate += "/" + otherCompanyProduct.StartDate
- // list[i].EndDate += "/" + otherCompanyProduct.EndDate
- //
- // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
- // endDateTime = endDateTime.AddDate(0, 0, 1)
- // sub := endDateTime.Sub(time.Now())
- // //if sub < 0 {
- // // sub = 0
- // //}
- // tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- // list[i].ExpireDay += "/" + tmpExpireDay
- // }
- //}
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.StackCompanyListResp{
- Paging: page,
- List: list,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- NotRenewalTryOut: notRenewalTryOut,
- NotRenewalNotTryOut: notRenewalNotTryOut,
- }
- return resp, err
- }
- // 获取今日的数据
- func getTodayStackCompanyList(sysUser *system.Admin, currentIndex, pageSize int, adminId, regionType, companyType, dataType string) (returnData response.StackCompanyListResp, err error) {
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition, listCondition string
- var pars, listPars []interface{}
- today := utils.GetToday(utils.FormatDate)
- //条件
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- err = errors.New("客户类型异常")
- return
- }
- var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND c.status = "正式" AND a.start_date <= ? AND a.end_date >= ? `
- pars1 = append(pars1, today, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //页表页数据总和
- total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND c.status = "正式" `
- condition1 += " AND a.end_date >= ?"
- pars1 = append(pars1, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //页表页数据总和
- total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //未续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND c.status not in ("永续","正式") `
- //condition1 += " AND a.end_date < ?"
- //pars1 = append(pars1, today)
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- notRenewalCompanyTotal = total
- if dataType == "未续约客户" {
- //页表页数据总和
- total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- list, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- listLen := len(list)
- //moreListMap := make(map[int][]*models.IncrementalList)
- //获取其他产品数据
- //if listLen > 0 {
- // companyIdSlice := make([]string, 0)
- // companyContractIdSlice := make([]string, 0)
- // for _, v := range list {
- // if v.Count > 1 {
- // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
- // }
- // }
- //if len(companyIdSlice) > 0 {
- // companyIds := strings.Join(companyIdSlice, ",")
- // companyContractIds := strings.Join(companyContractIdSlice, ",")
- // incrementalList2, list2Err := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, listCondition, listPars)
- // //companyType
- // if list2Err != nil {
- // err = errors.New("获取其他产品失败,Err:" + list2Err.Error())
- // return
- // }
- //
- // for _, incremental := range incrementalList2 {
- // moreListMap[incremental.CompanyId] = append(moreListMap[incremental.CompanyId], incremental)
- // }
- //}
- //}
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- expireDay := "0"
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- var sub time.Duration
- if dataType != "未续约客户" {
- sub = endDateTime.Sub(time.Now())
- //if sub < 0 {
- // sub = 0
- //}
- } else {
- sub = time.Now().Sub(endDateTime)
- }
- expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- //其他产品数据拼接
- //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
- // for _, otherCompanyProduct := range otherCompanyProductList {
- // list[i].ProductName += "/" + otherCompanyProduct.ProductName
- // list[i].SellerName += "/" + otherCompanyProduct.SellerName
- // list[i].StartDate += "/" + otherCompanyProduct.StartDate
- // list[i].EndDate += "/" + otherCompanyProduct.EndDate
- //
- // tmpExpireDay := "0"
- // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
- // endDateTime = endDateTime.AddDate(0, 0, 1)
- // var sub time.Duration
- // if dataType != "未续约客户" {
- // sub = endDateTime.Sub(time.Now())
- // //if sub < 0 {
- // // sub = 0
- // //}
- // } else {
- // sub = time.Now().Sub(endDateTime)
- // }
- // tmpExpireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
- //
- // list[i].ExpireDay += "/" + tmpExpireDay
- // }
- //}
- }
- var stackCompanyStatisticList []*models.StackCompanyStatisticList
- for _, v := range list {
- stackCompanyStatistic := models.StackCompanyStatisticList{
- Type: dataType,
- CompanyId: v.CompanyId,
- CompanyName: v.CompanyName,
- ProductId: v.ProductId,
- ProductName: v.ProductName,
- ContractNum: v.Count,
- SellerId: v.SellerId,
- SellerName: v.SellerName,
- Date: today,
- StartDate: v.StartDate,
- EndDate: v.EndDate,
- RegionType: v.RegionType,
- //CreateTime :v.CreateTime,
- CreateTimeStr: v.CreateTime,
- ExpireDay: v.ExpireDay,
- }
- stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.StackCompanyListResp{
- Paging: page,
- List: stackCompanyStatisticList,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- }
- return resp, err
- }
- func getTodayStackCompanyListV2(sysUser *system.Admin, currentIndex, pageSize, isConfirm, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition, listCondition string
- var pars, listPars []interface{}
- today := utils.GetToday(utils.FormatDate)
- //条件
- var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
- var parsAscribeRai []interface{}
- //是否确认续约 CRM 13.9
- if isConfirm != -1 {
- var conditionConfirm string
- var parsConfirm []interface{}
- companyConfirmList, e := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
- if e != nil && e.Error() != utils.ErrNoRow() {
- err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
- return
- }
- var companyIds []int
- if len(companyConfirmList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyConfirmList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- if isConfirm == 0 {
- conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(companyIds)) + `) AND c.product_id = 2 ) ` // 待确认
- } else {
- conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `) OR c.product_id = 2 )` // 已确认
- }
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- //归因ID CRM 13.9
- if companyAscribeId > 0 {
- var conditionAscribe string
- var parsAscribe []interface{}
- conditionAscribe = " AND company_ascribe_id = ? "
- parsAscribe = append(parsAscribe, companyAscribeId)
- companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
- if e != nil && e.Error() != utils.ErrNoRow() {
- err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
- return
- }
- var companyIds []int
- if len(companyNoRenewedAscribeList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyNoRenewedAscribeList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- switch companyType {
- case "ficc":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- err = errors.New("客户类型异常")
- return
- }
- var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- var notRenewalTryOut, notRenewalNotTryOut int
- var list []*models.IncrementalList
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- //condition1 += ` AND c.status = "正式" `
- condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars1 = append(pars1, today, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //页表页数据总和
- total, countErr := models.GetTodayStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //续约客户数
- {
- condition1 := condition
- pars1 := pars
- //condition1 += ` AND c.status = "正式" `
- condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars1 = append(pars1, today, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
- pars1 = append(pars1, today)
- total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //页表页数据总和
- total, countErr := models.GetTodayStackCompanyProductCountV2(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //未续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
- pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
- condition1 += ` AND a.operation = 'try_out' `
- total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- notRenewalCompanyTotal = total
- condition1 += conditionAscribRai
- pars1 = append(pars1, parsAscribeRai)
- if dataType == "未续约客户" {
- //页表页数据总和
- //统计数据
- for _, v := range []string{"试用", "非试用"} {
- totalCondition1 := condition1
- totalPars1 := pars1
- var tmpTotal int
- if v == "试用" {
- totalCondition1 += ` AND c.status = "试用" `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil {
- return
- }
- notRenewalTryOut = tmpTotal
- } else if v == "非试用" {
- totalCondition1 += ` AND c.status IN ("冻结","流失") `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- return
- }
- notRenewalNotTryOut = tmpTotal
- }
- }
- //列表数据数量
- if tryOutType == "试用" {
- condition1 += ` AND c.status = "试用" `
- total = notRenewalTryOut
- } else if tryOutType == "非试用" {
- condition1 += ` AND c.status IN ("冻结","流失") `
- total = notRenewalNotTryOut
- }
- //total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
- //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- // err = countErr
- // return
- //}
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- if tryOutType == "试用" {
- listCondition += ` AND c.status = "试用" `
- } else if tryOutType == "非试用" {
- listCondition += ` AND c.status IN ("冻结","流失") `
- }
- tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- for i := 0; i < len(tmpList); i++ {
- endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
- if parseErr != nil {
- err = parseErr
- return
- }
- tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
- }
- list = tmpList
- }
- }
- switch dataType {
- case "新签客户":
- tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- list = tmpList
- case "续约客户":
- tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- list = tmpList
- }
- if dataType == "续约客户" {
- var ids []string
- oldCompanyMap := make(map[int]*models.IncrementalList)
- oldMoneyMap := make(map[int]float64)
- countMap := make(map[int]int)
- for _, item := range list {
- ids = append(ids, strconv.Itoa(item.CompanyId))
- }
- if len(ids) > 0 {
- idStr := strings.Join(ids, ",")
- lists, contractErr := models.GetLastContractMoney(idStr)
- if contractErr != nil {
- err = contractErr
- return
- }
- for _, item := range lists {
- _, countOk := countMap[item.CompanyId]
- _, ok := oldCompanyMap[item.CompanyId]
- if !ok {
- oldCompanyMap[item.CompanyId] = item
- oldMoneyMap[item.CompanyId] = item.Money
- } else if !countOk {
- countMap[item.CompanyId] = 1
- oldCompanyMap[item.CompanyId] = item
- }
- }
- //给list赋值
- for _, item := range list {
- if item.ProductName == "权益" {
- oldMoney, _ := oldMoneyMap[item.CompanyId]
- lastContract, _ := oldCompanyMap[item.CompanyId]
- if oldMoney > lastContract.Money {
- item.PackageDifference = "增加套餐"
- } else if oldMoney < lastContract.Money {
- item.PackageDifference = "减少套餐"
- } else {
- item.PackageDifference = "维持套餐"
- }
- }
- }
- }
- }
- var ascribecompanyIds []int
- for _, item := range list {
- ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
- }
- //归因标签
- mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
- mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
- for _, item := range list {
- item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- }
- listLen := len(list)
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- expireDay := "0"
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- var sub time.Duration
- if dataType != "未续约客户" {
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub = endDateTime.Sub(time.Now())
- //if sub < 0 {
- // sub = 0
- //}
- } else {
- sub = time.Now().Sub(endDateTime)
- }
- expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- }
- var stackCompanyStatisticList []*models.StackCompanyStatisticList
- for _, v := range list {
- stackCompanyStatistic := models.StackCompanyStatisticList{
- Type: dataType,
- CompanyId: v.CompanyId,
- CompanyName: v.CompanyName,
- ProductId: v.ProductId,
- ProductName: v.ProductName,
- ContractNum: v.Count,
- SellerId: v.SellerId,
- SellerName: v.SellerName,
- Date: today,
- StartDate: v.StartDate,
- EndDate: v.EndDate,
- RegionType: v.RegionType,
- //CreateTime :v.CreateTime,
- CreateTimeStr: v.CreateTime,
- ExpireDay: v.ExpireDay,
- RenewalReason: v.RenewalReason,
- RenewalTodo: v.RenewalTodo,
- Status: v.Status,
- PackageDifference: v.PackageDifference,
- AscribeContent: v.AscribeContent,
- IsShowNoRenewedNote: v.IsShowNoRenewedNote,
- Content: v.Content,
- }
- stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.StackCompanyListResp{
- Paging: page,
- List: stackCompanyStatisticList,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- NotRenewalTryOut: notRenewalTryOut,
- NotRenewalNotTryOut: notRenewalNotTryOut,
- }
- return resp, err
- }
- // IncrementalCompanyList
- // @Title 获取增量客户数据列表
- // @Description 获取增量客户数据列表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param StartDate query string false "开始日期"
- // @Param EndDate query string false "结束日期"
- // @Param DataType query string false "报表类型,枚举值:`新增试用`,`新签客户`,`续约客户`,`未续约客户`"
- // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Param IsConfirm query int false "是否确认续约: -1-默认全部; 0-待确认; 1-已确认"
- // @Param CompanyAscribeId query int false "归因ID"
- // @Success 200 {object} response.IncrementalCompanyListResp
- // @router /incremental_company_list [get]
- func (this *StatisticReportController) IncrementalCompanyList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- dataType := this.GetString("DataType")
- tryOutType := this.GetString("TryOutType")
- keyword := this.GetString("Keyword")
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- isConfirm, _ := this.GetInt("IsConfirm", -1) // CRM 13.9
- companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
- //if startDate == "" || endDate == "" {
- // br.Msg = "获取失败,开始日期或结束日期未传"
- // br.ErrMsg = "获取失败,开始日期或结束日期未传"
- // return
- //}
- if startDate == "" {
- startDate = "2015-01-01"
- }
- if endDate == "" {
- endDate = time.Now().Format(utils.FormatDate)
- }
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- var condition string
- var pars []interface{}
- //条件
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
- var conditionAscribRaiTotal string // 处理权益未续约客户总量查询条件
- var parsAscribeRai []interface{}
- var parsAscribeRaiTotal []interface{} // 处理权益未续约客户总量查询条件
- var conditionConfirm string
- var parsConfirm []interface{}
- companyConfirmList, err := company.GetCompanyNoRenewedAscribeList(conditionConfirm, parsConfirm, 0, 0)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
- return
- }
- var noRenewedcompanyIds []int //已经确定未续约的公司ID
- if len(companyConfirmList) == 0 {
- noRenewedcompanyIds = append(noRenewedcompanyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyConfirmList {
- noRenewedcompanyIds = append(noRenewedcompanyIds, v.CompanyId)
- }
- }
- //是否确认续约 CRM 13.9
- conditionAscribRaiTotal += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) OR c.product_id = 1 OR a.create_time < '2023-01-01' ) ` // 已确认
- parsAscribeRaiTotal = append(parsAscribeRaiTotal, noRenewedcompanyIds)
- if isConfirm != -1 {
- if isConfirm == 0 {
- conditionAscribRai += ` AND ( c.company_id NOT IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) AND c.product_id = 2 AND a.create_time >= '2023-01-01' ) ` // 待确认
- } else {
- conditionAscribRai += ` AND ( c.company_id IN (` + utils.GetOrmInReplace(len(noRenewedcompanyIds)) + `) OR c.product_id = 1 OR a.create_time < '2023-01-01' ) ` // 已确认
- }
- parsAscribeRai = append(parsAscribeRai, noRenewedcompanyIds)
- }
- //归因ID CRM 13.9
- if companyAscribeId > 0 {
- var conditionAscribe string
- var parsAscribe []interface{}
- conditionAscribe = " AND company_ascribe_id = ? "
- parsAscribe = append(parsAscribe, companyAscribeId)
- companyNoRenewedAscribeList, err := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,GetCompanyNoRenewedAscribeList Err:" + err.Error()
- return
- }
- var companyIds []int
- if len(companyNoRenewedAscribeList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyNoRenewedAscribeList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- switch companyType {
- case "ficc":
- condition += ` AND c.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND c.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- var list []*models.IncrementalList
- //moreListMap := make(map[int][]*models.IncrementalList)
- var dataTotal, trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- var notRenewalTryOut, notRenewalNotTryOut int
- //试用客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
- pars1 = append(pars1, startDate, endDate)
- total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- trialTotal = total
- if dataType == "新增试用" {
- //列表数据数量
- total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //列表页数据
- tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- dataTotal = total
- }
- }
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //列表数据数量
- total, err := models.GetIncrementalNewCompanyProductCount(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //列表页数据
- tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- dataTotal = total
- //获取其他产品
- //if len(list) > 0 {
- // companyIdSlice := make([]string, 0)
- // companyContractIdSlice := make([]string, 0)
- // for _, v := range list {
- // if v.Count > 1 {
- // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
- // }
- // }
- // if len(companyIdSlice) > 0 {
- // companyIds := strings.Join(companyIdSlice, ",")
- // companyContractIds := strings.Join(companyContractIdSlice, ",")
- // otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
- // //companyType
- // if otherListErr != nil {
- // br.Msg = "获取其他产品失败"
- // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
- // return
- // }
- //
- // for _, otherCompanyContract := range otherList {
- // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
- // }
- // }
- //}
- }
- }
- //续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
- pars1 = append(pars1, endDate)
- total, err := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //列表数据数量
- total, err := models.GetIncrementalNewCompanyProductCountV2(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //列表页数据
- tmpList, err := models.GetIncrementalNewCompanyListV2(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- dataTotal = total
- var ids []string
- companyMap := make(map[int]*models.IncrementalList)
- oldCompanyMap := make(map[int]*models.IncrementalList)
- countMap := make(map[int]int)
- for _, item := range tmpList {
- ids = append(ids, strconv.Itoa(item.CompanyId))
- companyMap[item.CompanyId] = item
- }
- if len(ids) > 0 {
- idStr := strings.Join(ids, ",")
- lists, err := models.GetLastContractMoney(idStr)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- for _, item := range lists {
- _, countOk := countMap[item.CompanyId]
- _, ok := oldCompanyMap[item.CompanyId]
- if !ok {
- oldCompanyMap[item.CompanyId] = item
- } else if !countOk {
- countMap[item.CompanyId] = 1
- oldCompanyMap[item.CompanyId] = item
- }
- }
- //给list赋值
- for _, item := range list {
- if item.ProductName == "权益" {
- lastContract, _ := oldCompanyMap[item.CompanyId]
- if item.Money > lastContract.Money {
- item.PackageDifference = "增加套餐"
- } else if item.Money < lastContract.Money {
- item.PackageDifference = "减少套餐"
- } else {
- item.PackageDifference = "维持套餐"
- }
- }
- }
- }
- //获取其他产品
- //if len(list) > 0 {
- // companyIdSlice := make([]string, 0)
- // companyContractIdSlice := make([]string, 0)
- // for _, v := range list {
- // if v.Count > 1 {
- // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- // companyContractIdSlice = append(companyContractIdSlice, strconv.Itoa(v.CompanyContractId))
- // }
- // }
- // if len(companyIdSlice) > 0 {
- // companyIds := strings.Join(companyIdSlice, ",")
- // companyContractIds := strings.Join(companyContractIdSlice, ",")
- // otherList, otherListErr := models.GetOtherIncrementalNewCompanyList(companyIds, companyContractIds, condition1, pars1)
- // //companyType
- // if otherListErr != nil {
- // br.Msg = "获取其他产品失败"
- // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
- // return
- // }
- //
- // for _, otherCompanyContract := range otherList {
- // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
- // }
- // }
- //}
- }
- }
- //未续约客户数
- {
- condition1 := condition
- pars1 := pars
- endDateTime, err := time.Parse(utils.FormatDate, endDate)
- if err != nil {
- br.Msg = "结束时间异常"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //选择的日期加一天的原因是因为:筛选条件是截止到时分秒的,如果要把选择的这一天也统计进去,那么需要在选择的结束日期基础上加上一天
- tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
- condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
- pars1 = append(pars1, startDate, tryOutEndDate)
- condition1 += ` AND a.operation = ? `
- pars1 = append(pars1, "try_out")
- condition1 += ` AND c.status not in ("永续","正式","关闭") `
- //未续约这里只统计已经确定的
- notRenewalCondition := condition1
- notRenewalPars := pars1
- notRenewalCondition += conditionAscribRaiTotal
- notRenewalPars = append(notRenewalPars, parsAscribeRaiTotal)
- total, err := models.GetIncrementalCompanyProductCountByOperationRecord(notRenewalCondition, notRenewalPars)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- notRenewalCompanyTotal = total
- condition1 += conditionAscribRai
- pars1 = append(pars1, parsAscribeRai)
- if dataType == "未续约客户" {
- //统计数据
- for _, v := range []string{"试用", "非试用"} {
- totalCondition1 := condition1
- totalPars1 := pars1
- var tmpTotal int
- if v == "试用" {
- totalCondition1 += ` AND c.status = "试用" `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- notRenewalTryOut = tmpTotal
- } else if v == "非试用" {
- totalCondition1 += ` AND c.status IN ("冻结","流失") `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- notRenewalNotTryOut = tmpTotal
- }
- }
- //列表数据数量
- if tryOutType == "试用" {
- condition1 += ` AND c.status = "试用" `
- total = notRenewalTryOut
- } else if tryOutType == "非试用" {
- condition1 += ` AND c.status IN ("冻结","流失") `
- total = notRenewalNotTryOut
- }
- //total, err := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
- //if err != nil && err.Error() != utils.ErrNoRow() {
- // br.Msg = "获取失败"
- // br.ErrMsg = "获取失败,Err:" + err.Error()
- // return
- //}
- //分页total单独计算
- total, err = models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //列表页数据
- tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- var ascribecompanyIds []int
- for _, item := range tmpList {
- endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
- item.EndDate = endDateTime.Format(utils.FormatDate)
- ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
- }
- //归因标签
- mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
- mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
- for _, item := range tmpList {
- item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- if item.ProductId == utils.COMPANY_PRODUCT_RAI_ID { //权益客户的销售,按照创建时候对应的销售展示
- item.SellerName = item.SellerNameInit
- }
- }
- list = tmpList
- dataTotal = total
- //获取其他产品
- //if len(list) > 0 {
- // companyIdSlice := make([]string, 0)
- // for _, v := range list {
- // if v.Count > 1 {
- // companyIdSlice = append(companyIdSlice, strconv.Itoa(v.CompanyId))
- // }
- // }
- // if len(companyIdSlice) > 0 {
- // companyIds := strings.Join(companyIdSlice, ",")
- // otherList, otherListErr := models.GetOtherIncrementalCompanyListByOperationRecord(companyIds, condition1, pars1)
- // //companyType
- // if otherListErr != nil {
- // br.Msg = "获取其他产品失败"
- // br.ErrMsg = "获取其他产品失败,Err:" + otherListErr.Error()
- // return
- // }
- //
- // for _, otherCompanyContract := range otherList {
- // moreListMap[otherCompanyContract.CompanyId] = append(moreListMap[otherCompanyContract.CompanyId], otherCompanyContract)
- // }
- // }
- //}
- }
- }
- listLen := len(list)
- if listLen == 0 {
- list = make([]*models.IncrementalList, 0)
- }
- for i := 0; i < listLen; i++ {
- item := list[i]
- //新增试用不需要计算剩余日期
- if dataType != "新增试用" {
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- }
- //if otherCompanyProductList, ok := moreListMap[item.CompanyId]; ok {
- // for _, otherCompanyProduct := range otherCompanyProductList {
- // //只有改产品不是同一产品,且并没有拼接过,那么才去拼接
- // if item.ProductId != otherCompanyProduct.ProductId && strings.Contains(list[i].ProductName, "/") == false {
- // list[i].ProductName += "/" + otherCompanyProduct.ProductName
- // list[i].SellerName += "/" + otherCompanyProduct.SellerName
- // list[i].StartDate += "/" + otherCompanyProduct.StartDate
- // list[i].EndDate += "/" + otherCompanyProduct.EndDate
- //
- // endDateTime, _ := time.Parse(utils.FormatDate, otherCompanyProduct.EndDate)
- // endDateTime = endDateTime.AddDate(0, 0, 1)
- // sub := endDateTime.Sub(time.Now())
- // //if sub < 0 {
- // // sub = 0
- // //}
- // tmpExpireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- // list[i].ExpireDay += "/" + tmpExpireDay
- // }
- // }
- //}
- //if company2
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.IncrementalCompanyListResp{
- Paging: page,
- List: list,
- TrialTotal: trialTotal,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- NotRenewalTryOut: notRenewalTryOut,
- NotRenewalNotTryOut: notRenewalNotTryOut,
- }
- //导出excel
- if isExport {
- IncrementalCompanyListExport(this, dataType, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // IncrementalCompanyListExport 导出增量客户数据报表excel
- func IncrementalCompanyListExport(this *StatisticReportController, dataType string, resp response.IncrementalCompanyListResp, br *models.BaseResponse) {
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("增量客户数据")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 3, 18)
- sheel.SetColWidth(4, 4, 40)
- sheel.SetColWidth(5, 5, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("新增试用客户数:", resp.TrialTotal))
- cell2 := statisticRow.AddCell()
- cell2.SetStyle(style)
- cell2.SetValue(fmt.Sprint("新签客户数:", resp.NewCompanyTotal))
- cell3 := statisticRow.AddCell()
- cell3.SetStyle(style)
- cell3.SetValue(fmt.Sprint("续约客户数:", resp.RenewalCompanyTotal))
- cell4 := statisticRow.AddCell()
- cell4.SetStyle(style)
- cell4.SetValue(fmt.Sprint("未续约客户数:", resp.NotRenewalCompanyTotal))
- //表头
- titleRow := sheel.AddRow()
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- permissionMap := make(map[int][]string)
- tmpPermissionMap := make(map[int]map[string][]string)
- companyContractIdList := make([]string, 0)
- for _, v := range resp.List {
- companyContractIdList = append(companyContractIdList, fmt.Sprint(v.CompanyContractId))
- }
- if dataType == "新签客户" || dataType == "续约客户" {
- cellMoney := titleRow.AddCell()
- cellMoney.SetStyle(style)
- cellMoney.SetValue("合同金额")
- cellPermission := titleRow.AddCell()
- cellPermission.SetStyle(style)
- cellPermission.SetValue("合同品种")
- //这么大费周章的目的是为了:权益的品种存在主观、客观的区分,如果一个品种既存在主观,又存在客观,那么就展示品种名称,否则就要列出品种名称+主、客观类型
- if len(companyContractIdList) > 0 {
- list, tmpErr := company.GetCompanyContractPermissionListByContractIds(strings.Join(companyContractIdList, ","))
- if tmpErr != nil {
- err = tmpErr
- return
- }
- for _, v := range list {
- tmpPermissionNameMap, ok := tmpPermissionMap[v.CompanyContractId]
- if ok {
- tmpPermissionNameList, ok2 := tmpPermissionNameMap[v.ChartPermissionName]
- if ok2 {
- tmpPermissionNameList = append(tmpPermissionNameList, v.PermissionRemark)
- } else {
- tmpPermissionNameList = []string{v.PermissionRemark}
- }
- tmpPermissionNameMap[v.ChartPermissionName] = tmpPermissionNameList
- } else {
- tmpPermissionNameMap = make(map[string][]string)
- tmpPermissionNameMap[v.ChartPermissionName] = []string{v.PermissionRemark}
- }
- tmpPermissionMap[v.CompanyContractId] = tmpPermissionNameMap
- }
- }
- }
- for companyContractId, tmpPermissionNameMap := range tmpPermissionMap {
- tmpPermissionName := ``
- tmpPermissionList := []string{}
- for tmpChartPermissionName, tmpChartPermissionNameList := range tmpPermissionNameMap {
- if len(tmpChartPermissionNameList) > 1 {
- tmpPermissionName = tmpChartPermissionName
- } else {
- tmpPermissionName = tmpChartPermissionNameList[0]
- }
- tmpPermissionList = append(tmpPermissionList, tmpPermissionName)
- }
- permissionMap[companyContractId] = tmpPermissionList
- }
- cellTime := titleRow.AddCell()
- cellTime.SetStyle(style)
- switch dataType {
- case "新增试用":
- cellTime.SetValue("新增时间")
- case "新签客户":
- cellTime.SetValue("签约时间")
- case "续约客户":
- cellTime.SetValue("续约时间")
- case "未续约客户":
- cellTime.SetValue("最近合同到期时间")
- cellAscribeContent := titleRow.AddCell()
- cellAscribeContent.SetStyle(style)
- cellAscribeContent.SetValue("不续约归因")
- cellContent := titleRow.AddCell()
- cellContent.SetStyle(style)
- cellContent.SetValue("详细原因")
- }
- for _, v := range resp.List {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- if dataType == "新签客户" || dataType == "续约客户" {
- cellDataMoney := dataRow.AddCell()
- cellDataMoney.SetStyle(style)
- cellDataMoney.SetValue(v.Money)
- cellDataPermission := dataRow.AddCell()
- cellDataPermission.SetStyle(style)
- if permissionStrList, ok := permissionMap[v.CompanyContractId]; ok {
- cellDataPermission.SetValue(strings.Join(permissionStrList, ","))
- }
- }
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- switch dataType {
- case "新增试用":
- cellDataTime.SetValue(v.CreateTime)
- case "新签客户":
- cellDataTime.SetValue(v.StartDate)
- case "续约客户":
- cellDataTime.SetValue(v.StartDate)
- case "未续约客户":
- cellDataTime.SetValue(v.EndDate)
- cellAscribeContent := dataRow.AddCell()
- cellAscribeContent.SetStyle(style)
- cellAscribeContent.SetValue(v.AscribeContent)
- cellContent := dataRow.AddCell()
- cellContent.SetStyle(style)
- cellContent.SetValue(v.Content)
- }
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "增量客户数据_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- // IncrementalCompanyListExport
- // @Title 增量客户数据导出
- // @Description 增量客户数据导出接口
- // @Param CompanyType query string true "客户类型:传空字符串或者不传为全部,'ficc','权益'"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param StartDate query string false "开始日期"
- // @Param EndDate query string false "结束日期"
- // @Param DataType query string false "报表类型,枚举值:`新增试用`,`新签客户`,`续约客户`,`未续约客户`"
- // @Success 200 Ret=200 导出成功
- // @router /incremental_company/export [get]
- func (this *StatisticReportController) IncrementalCompanyListExport() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- dataType := this.GetString("DataType")
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- if startDate == "" || endDate == "" {
- br.Msg = "获取失败,开始日期或结束日期未传"
- br.ErrMsg = "获取失败,开始日期或结束日期未传"
- return
- }
- var startSize int
- currentIndex := 1
- pageSize := 10000
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition string
- var pars []interface{}
- //条件
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- switch companyType {
- case "ficc":
- condition += ` AND c.product_id = ? `
- pars = append(pars, 1)
- case "权益":
- condition += ` AND c.product_id = ? `
- pars = append(pars, 2)
- case "":
- default:
- br.Msg = "获取失败,客户类型异常"
- br.ErrMsg = "获取失败,客户类型异常"
- return
- }
- var list []*models.IncrementalList
- //moreListMap := make(map[int][]*models.IncrementalList)
- var trialTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- //试用客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.create_time >= ? AND a.create_time <= ? AND a.operation in ("add","receive") `
- pars1 = append(pars1, startDate, endDate)
- total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- trialTotal = total
- if dataType == "新增试用" {
- //列表页数据
- tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- }
- }
- //新签客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //列表页数据
- tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- }
- }
- //续约客户数
- {
- condition1 := condition
- pars1 := pars
- condition1 += ` AND a.start_date >= ? AND a.start_date <= ? `
- pars1 = append(pars1, startDate, endDate)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- total, err := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //列表页数据
- tmpList, err := models.GetIncrementalNewCompanyList(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- list = tmpList
- }
- }
- //未续约客户数
- {
- condition1 := condition
- pars1 := pars
- endDateTime, err := time.Parse(utils.FormatDate, endDate)
- if err != nil {
- br.Msg = "结束时间异常"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- //选择的日期加一天的原因是因为:筛选条件是截止到时分秒的,如果要把选择的这一天也统计进去,那么需要在选择的结束日期基础上加上一天
- tryOutEndDate := endDateTime.AddDate(0, 0, 1).Format(utils.FormatDate)
- condition1 += ` AND a.create_time >= ? AND a.create_time < ? `
- pars1 = append(pars1, startDate, tryOutEndDate)
- condition1 += ` AND a.operation = ? `
- pars1 = append(pars1, "try_out")
- condition1 += ` AND c.status not in ("永续","正式") `
- total, err := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- notRenewalCompanyTotal = total
- if dataType == "未续约客户" {
- //列表页数据
- tmpList, err := models.GetIncrementalCompanyListByOperationRecord(condition1, pars1, startSize, pageSize)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- for _, item := range tmpList {
- endDateTime, _ := time.Parse(utils.FormatDateTime, item.CreateTime)
- item.EndDate = endDateTime.Format(utils.FormatDate)
- }
- list = tmpList
- }
- }
- listLen := len(list)
- for i := 0; i < listLen; i++ {
- item := list[i]
- //新增试用不需要计算剩余日期
- if dataType != "新增试用" {
- //剩余可用天数
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub := endDateTime.Sub(time.Now())
- expireDay := fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- }
- }
- dir, err := os.Executable()
- exPath := filepath.Dir(dir)
- downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
- xlsxFile := xlsx.NewFile()
- if err != nil {
- br.Msg = "生成文件失败"
- br.ErrMsg = "生成文件失败"
- return
- }
- style := xlsx.NewStyle()
- alignment := xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- }
- style.Alignment = alignment
- style.ApplyAlignment = true
- sheel, err := xlsxFile.AddSheet("增量客户数据")
- if err != nil {
- br.Msg = "新增Sheet失败"
- br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
- return
- }
- sheel.SetColWidth(0, 0, 30)
- sheel.SetColWidth(1, 1, 15)
- sheel.SetColWidth(2, 2, 15)
- sheel.SetColWidth(3, 3, 18)
- //统计数据
- statisticRow := sheel.AddRow()
- cell1 := statisticRow.AddCell()
- cell1.SetStyle(style)
- cell1.SetValue(fmt.Sprint("新增试用客户数:", trialTotal))
- cell2 := statisticRow.AddCell()
- cell2.SetStyle(style)
- cell2.SetValue(fmt.Sprint("新签客户数:", newCompanyTotal))
- cell3 := statisticRow.AddCell()
- cell3.SetStyle(style)
- cell3.SetValue(fmt.Sprint("续约客户数:", renewalCompanyTotal))
- cell4 := statisticRow.AddCell()
- cell4.SetStyle(style)
- cell4.SetValue(fmt.Sprint("未续约客户数:", notRenewalCompanyTotal))
- //表头
- titleRow := sheel.AddRow()
- cellName := titleRow.AddCell()
- cellName.SetStyle(style)
- cellName.SetValue("客户名称")
- cellProName := titleRow.AddCell()
- cellProName.SetStyle(style)
- cellProName.SetValue("客户类型")
- cellSellerName := titleRow.AddCell()
- cellSellerName.SetStyle(style)
- cellSellerName.SetValue("所属销售")
- cellTime := titleRow.AddCell()
- cellTime.SetStyle(style)
- switch dataType {
- case "新增试用":
- cellTime.SetValue("新增时间")
- case "新签客户":
- cellTime.SetValue("签约时间")
- case "续约客户":
- cellTime.SetValue("续约时间")
- case "未续约客户":
- cellTime.SetValue("最近合同到期时间")
- }
- for _, v := range list {
- dataRow := sheel.AddRow()
- dataRow.SetHeight(20)
- cellDataName := dataRow.AddCell()
- cellDataName.SetStyle(style)
- cellDataName.SetValue(v.CompanyName)
- cellDataProName := dataRow.AddCell()
- cellDataProName.SetStyle(style)
- cellDataProName.SetValue(v.ProductName)
- cellDataSellerName := dataRow.AddCell()
- cellDataSellerName.SetStyle(style)
- cellDataSellerName.SetValue(v.SellerName)
- cellDataTime := dataRow.AddCell()
- cellDataTime.SetStyle(style)
- switch dataType {
- case "新增试用":
- cellDataTime.SetValue(v.CreateTime)
- case "新签客户":
- cellDataTime.SetValue(v.StartDate)
- case "续约客户":
- cellDataTime.SetValue(v.StartDate)
- case "未续约客户":
- cellDataTime.SetValue(v.EndDate)
- }
- }
- err = xlsxFile.Save(downLoadnFilePath)
- if err != nil {
- br.Msg = "保存文件失败"
- br.ErrMsg = "保存文件失败"
- return
- }
- randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
- downloadFileName := "增量客户数据_" + randStr + ".xlsx"
- this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
- defer func() {
- os.Remove(downLoadnFilePath)
- }()
- br.Ret = 200
- br.Success = true
- br.Msg = "导出成功"
- }
- // MoreRenewReason 未续约说明列表
- // @Title 未续约说明列表
- // @Description 未续约说明列表
- // @Param CompanyId query string true "客户id"
- // @Param ProductId query string true "产品id"
- // @Success 200 {object} response.MoreRenewReasonResp
- // @router /more_renew_reason [get]
- func (this *StatisticReportController) MoreRenewReason() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- CompanyId := this.GetString("CompanyId")
- ProductId := this.GetString("ProductId")
- renewalReason, err := models.GetMoreRenewalReason(CompanyId, ProductId)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- resp := make([]response.MoreRenewReasonResp, len(renewalReason))
- for i, reason := range renewalReason {
- createDate := reason.CreateTime.Format("2006.01.02")
- resp[i].RenewalReason = reason.RenewalReason
- resp[i].RenewalTodo = reason.RenewalTodo
- resp[i].CreateTime = createDate
- resp[i].ExpirationTimeExceeded = strconv.Itoa(reason.ExpirationTimeExceeded)
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // StackCompanyReport
- // @Title 获取存量客户统计数据
- // @Description 获取存量客户统计数据接口
- // @Param ProductId query string true "产品id"
- // @Param Date query string true "日期,格式:2022-04-06"
- // @Success 200 {object} statistic_report.CompanyReportRecordResp
- // @router /report/stack_company [get]
- func (this *StatisticReportController) StackCompanyReport() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- date := this.GetString("Date")
- productId, _ := this.GetInt("ProductId", 1)
- //获取列表
- companyReportDataMapList, firstDate, err := statistic_report.GetDateData(date, productId)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- //获取销售人员分组数据
- var group []services.AdminGroup
- var groupIdRelationMap map[int]int
- var groupMap map[int][]*roadshow.Researcher
- if productId == 1 {
- group, groupIdRelationMap, err = services.GetFiccSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "ficc_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- } else {
- group, groupIdRelationMap, err = services.GetRaiSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "rai_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- }
- //数据处理
- groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
- allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
- companyReportRecordResp := statistic_report.CompanyReportRecordResp{
- List: groupReportRecordList,
- CompanyReportRecordNumList: allCompanyReportRecordNum,
- }
- startDateIndexList := make(map[int]string) //开始时间间隔map
- endDateIndexList := make(map[int]string) //结束时间间隔map
- tmpAllTryOutNumMap := make(map[int]int)
- tmpAllFormalNumMap := make(map[int]int)
- tmpAllActiveNumMap := make(map[int]int)
- tmpAllAllActiveNumMap := make(map[int]int)
- tmpAllNoIncrementalActiveNumMap := make(map[int]int)
- tmpAllTryStagePushMap := make(map[int]int)
- tmpAllTryStageFollowMap := make(map[int]int)
- tmpAllTryStageReadyMap := make(map[int]int)
- tmpAllTryStageInitMap := make(map[int]int)
- for _, v := range group {
- v.ResearcherList = groupMap[v.GroupId]
- tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
- tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
- tmpGroupTryOutNumMap := make(map[int]int)
- tmpGroupFormalNumMap := make(map[int]int)
- tmpGroupActiveNumMap := make(map[int]int)
- tmpGroupAllActiveNumMap := make(map[int]int)
- tmpGroupNoIncrementalActiveNumMap := make(map[int]int)
- tmpGroupTryStagePushMap := make(map[int]int)
- tmpGroupTryStageFollowMap := make(map[int]int)
- tmpGroupTryStageReadyMap := make(map[int]int)
- tmpGroupTryStageInitMap := make(map[int]int)
- for _, researcher := range groupMap[v.GroupId] {
- //组内研究员数据
- //每个区间的数据
- tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
- for index, adminData := range companyReportDataMapList {
- startDateIndexList[index] = adminData.StartDate
- endDateIndexList[index] = adminData.EndDate
- var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
- var tmpTryStagePushNum, tmpTryStageFollowNum, tmpTryStageReadyNum, tmpTryStageInitNum int
- if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
- tmpTryOutNum = num
- }
- if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
- tmpFormalNum = num
- }
- if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
- tmpActiveStatus = num
- }
- if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
- tmpAllActiveStatus = num
- }
- if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
- tmpNoIncrementalActiveStatus = num
- }
- // 每个用户的试用标签统计 推进-跟踪-预备-未分类
- if num, ok := adminData.TryStagePushNum[researcher.AdminId]; ok {
- tmpTryStagePushNum = num
- }
- if num, ok := adminData.TryStageFollowNum[researcher.AdminId]; ok {
- tmpTryStageFollowNum = num
- }
- if num, ok := adminData.TryStageReadyNum[researcher.AdminId]; ok {
- tmpTryStageReadyNum = num
- }
- if num, ok := adminData.TryStageInitNum[researcher.AdminId]; ok {
- tmpTryStageInitNum = num
- }
- tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpTryOutNum,
- FormalNum: tmpFormalNum,
- ActiveNum: tmpActiveStatus,
- AllActiveNum: tmpAllActiveStatus,
- NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
- StartDate: adminData.StartDate,
- EndDate: adminData.EndDate,
- TryStagePushNum: tmpTryStagePushNum,
- TryStageFollowNum: tmpTryStageFollowNum,
- TryStageReadyNum: tmpTryStageReadyNum,
- TryStageInitNum: tmpTryStageInitNum,
- }
- tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)
- //组内数据汇总
- tmpGroupTryOutNumMap[index] += tmpTryOutNum
- tmpGroupFormalNumMap[index] += tmpFormalNum
- tmpGroupActiveNumMap[index] += tmpActiveStatus
- tmpGroupAllActiveNumMap[index] += tmpActiveStatus
- tmpGroupNoIncrementalActiveNumMap[index] += tmpActiveStatus
- tmpGroupTryStagePushMap[index] += tmpTryStagePushNum
- tmpGroupTryStageFollowMap[index] += tmpTryStageFollowNum
- tmpGroupTryStageReadyMap[index] += tmpTryStageReadyNum
- tmpGroupTryStageInitMap[index] += tmpTryStageInitNum
- //总数据汇总
- tmpAllTryOutNumMap[index] += tmpTryOutNum
- tmpAllFormalNumMap[index] += tmpFormalNum
- tmpAllActiveNumMap[index] += tmpActiveStatus
- tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
- tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
- // 总数据试用标签数据汇总
- tmpAllTryStagePushMap[index] += tmpTryStagePushNum
- tmpAllTryStageFollowMap[index] += tmpTryStageFollowNum
- tmpAllTryStageReadyMap[index] += tmpTryStageReadyNum
- tmpAllTryStageInitMap[index] += tmpTryStageInitNum
- }
- tmpAdminReportRecord := statistic_report.AdminReportRecord{
- Name: researcher.RealName,
- AdminId: researcher.AdminId,
- CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
- }
- tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
- }
- for i := 0; i < len(tmpGroupActiveNumMap); i++ {
- tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpGroupTryOutNumMap[i],
- FormalNum: tmpGroupFormalNumMap[i],
- ActiveNum: tmpGroupActiveNumMap[i],
- AllActiveNum: tmpGroupAllActiveNumMap[i],
- NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- TryStagePushNum: tmpGroupTryStagePushMap[i],
- TryStageFollowNum: tmpGroupTryStageFollowMap[i],
- TryStageReadyNum: tmpGroupTryStageReadyMap[i],
- TryStageInitNum: tmpGroupTryStageInitMap[i],
- }
- tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
- }
- groupReportRecord := statistic_report.GroupReportRecord{
- Item: tmpGroupAdminReportRecord,
- Name: v.GroupName,
- GroupId: v.GroupId,
- CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
- }
- groupReportRecordList = append(groupReportRecordList, groupReportRecord)
- }
- //总体汇总数据
- for i := 0; i < len(tmpAllFormalNumMap); i++ {
- tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpAllTryOutNumMap[i],
- FormalNum: tmpAllFormalNumMap[i],
- ActiveNum: tmpAllActiveNumMap[i],
- AllActiveNum: tmpAllAllActiveNumMap[i],
- NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- TryStagePushNum: tmpAllTryStagePushMap[i],
- TryStageFollowNum: tmpAllTryStageFollowMap[i],
- TryStageReadyNum: tmpAllTryStageReadyMap[i],
- TryStageInitNum: tmpAllTryStageInitMap[i],
- }
- allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
- }
- companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
- tmpList := groupReportRecordList
- //因为RoleTypeCode不一样,所以需要重新从数据库取数据
- adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
- adminGroupId := adminInfo.GroupId
- if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
- adminGroupId = tmpGroupId
- }
- switch adminInfo.RoleTypeCode {
- case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyReportRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_RAI_GROUP:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyReportRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
- //管理员、超管看全部数据
- companyReportRecordResp.List = tmpList
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = companyReportRecordResp
- }
- // IncrementalCompanyReport
- // @Title 获取增量客户统计数据
- // @Description 获取增量客户统计数据接口
- // @Param DataType query string true "枚举值:week、month、time_interval"
- // @Param ProductId query int true "客户类型 ficc:1 权益:2"
- // @Param StartDate query string true "开始日期,格式:2022-04-06"
- // @Param EndDate query string true "结束日期,格式:2022-04-06"
- // @Success 200 {object} statistic_report.CompanyReportRecordResp
- // @router /report/incremental_company [get]
- func (this *StatisticReportController) IncrementalCompanyReport() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- dataType := this.GetString("DataType")
- productId, _ := this.GetInt("ProductId", 1)
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- var companyReportDataMapList []statistic_report.CompanyReportDataMap
- var err error
- var firstDate time.Time
- switch dataType {
- //获取列表
- case "week":
- nowWeekMonday := utils.GetNowWeekMonday() //本周周一
- //companyReportDataMapList, firstDate, err = statistic_report.GetWeekData()
- companyReportDataMapList, firstDate, err = statistic_report.GetWeekDataNum(nowWeekMonday, productId, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "month":
- nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
- //companyReportDataMapList, firstDate, err = statistic_report.GetMonthData()
- companyReportDataMapList, firstDate, err = statistic_report.GetMonthDataNum(nowMonthFirstDay, productId, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "time_interval":
- if startDate == `` || endDate == `` {
- br.Msg = "开始日期或结束日期不能为空"
- br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
- return
- }
- companyReportDataMapList, firstDate, err = statistic_report.GetTimeIntervalData(productId, startDate, endDate)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- }
- //获取销售人员分组数据
- var group []services.AdminGroup
- var groupIdRelationMap map[int]int
- var groupMap map[int][]*roadshow.Researcher
- if productId == 1 {
- group, groupIdRelationMap, err = services.GetFiccSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "ficc_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- } else {
- group, groupIdRelationMap, err = services.GetRaiSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "rai_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- }
- //数据处理
- groupReportRecordList := make([]statistic_report.GroupReportRecord, 0)
- allCompanyReportRecordNum := make([]statistic_report.CompanyReportRecordNum, 0)
- companyReportRecordResp := statistic_report.CompanyReportRecordResp{
- List: groupReportRecordList,
- CompanyReportRecordNumList: allCompanyReportRecordNum,
- }
- startDateIndexList := make(map[int]string) //开始时间间隔map
- endDateIndexList := make(map[int]string) //结束时间间隔map
- //客户数汇总
- tmpAllTryOutNumMap := make(map[int]int)
- tmpAllFormalNumMap := make(map[int]int)
- tmpAllActiveNumMap := make(map[int]int)
- tmpAllAllActiveNumMap := make(map[int]int)
- tmpAllNoIncrementalActiveNumMap := make(map[int]int)
- //id集合汇总
- tmpAllTryOutIdMap := make(map[int]string)
- tmpAllFormalIdMap := make(map[int]string)
- tmpAllActiveIdMap := make(map[int]string)
- tmpAllAllActiveIdMap := make(map[int]string)
- tmpAllNoIncrementalActiveIdMap := make(map[int]string)
- for _, v := range group {
- v.ResearcherList = groupMap[v.GroupId]
- tmpGroupAdminReportRecord := make([]statistic_report.AdminReportRecord, 0)
- tmpGroupCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
- //数量统计
- tmpGroupTryOutNumMap := make(map[int]int)
- tmpGroupFormalNumMap := make(map[int]int)
- tmpGroupActiveNumMap := make(map[int]int)
- tmpGroupAllActiveNumMap := make(map[int]int)
- tmpGroupNoIncrementalActiveNumMap := make(map[int]int)
- //id集合
- tmpGroupTryOutIdSliceMap := make(map[int][]string)
- tmpGroupFormalIdSliceMap := make(map[int][]string)
- tmpGroupActiveIdSliceMap := make(map[int][]string)
- tmpGroupAllActiveIdSliceMap := make(map[int][]string)
- tmpGroupNoIncrementalActiveIdSliceMap := make(map[int][]string)
- //id集合
- tmpGroupTryOutIdMap := make(map[int]string)
- tmpGroupFormalIdMap := make(map[int]string)
- tmpGroupActiveIdMap := make(map[int]string)
- tmpGroupAllActiveIdMap := make(map[int]string)
- tmpGroupNoIncrementalActiveIdMap := make(map[int]string)
- for _, researcher := range groupMap[v.GroupId] {
- //组内研究员数据
- //每个区间的数据
- tmpCompanyReportRecordNumList := make([]statistic_report.CompanyReportRecordNum, 0)
- for index, adminData := range companyReportDataMapList {
- startDateIndexList[index] = adminData.StartDate
- endDateIndexList[index] = adminData.EndDate
- var tmpTryOutNum, tmpFormalNum, tmpActiveStatus, tmpAllActiveStatus, tmpNoIncrementalActiveStatus int
- //var tmpTryOutIds, tmpFormalIds, tmpActiveIds string
- var tmpTryOutIdSlice, tmpFormalIdSlice, tmpActiveIdSlice, tmpAllActiveIdSlice, tmpNoIncrementalActiveIdSlice []string
- var tmpTryOutId, tmpFormalId, tmpActiveId, tmpAllActiveId, tmpNoIncrementalActiveId string
- if num, ok := adminData.TryOutMap[researcher.AdminId]; ok {
- tmpTryOutNum = num
- tmpTryOutIdSlice = append(tmpTryOutIdSlice, adminData.TryOutIdMap[researcher.AdminId])
- tmpTryOutId = strings.Join(tmpTryOutIdSlice, ",")
- }
- if num, ok := adminData.FormalMap[researcher.AdminId]; ok {
- tmpFormalNum = num
- tmpFormalIdSlice = append(tmpFormalIdSlice, adminData.FormalIdMap[researcher.AdminId])
- tmpFormalId = strings.Join(tmpFormalIdSlice, ",")
- }
- if num, ok := adminData.ActiveMap[researcher.AdminId]; ok {
- tmpActiveStatus = num
- tmpActiveIdSlice = append(tmpActiveIdSlice, adminData.ActiveIdMap[researcher.AdminId])
- tmpActiveId = strings.Join(tmpActiveIdSlice, ",")
- }
- if num, ok := adminData.AllActiveMap[researcher.AdminId]; ok {
- tmpAllActiveStatus = num
- tmpAllActiveIdSlice = append(tmpAllActiveIdSlice, adminData.AllActiveIdMap[researcher.AdminId])
- tmpAllActiveId = strings.Join(tmpAllActiveIdSlice, ",")
- }
- if num, ok := adminData.NoIncrementalActiveMap[researcher.AdminId]; ok {
- tmpNoIncrementalActiveStatus = num
- tmpNoIncrementalActiveIdSlice = append(tmpNoIncrementalActiveIdSlice, adminData.NoIncrementalActiveIdMap[researcher.AdminId])
- tmpNoIncrementalActiveId = strings.Join(tmpNoIncrementalActiveIdSlice, ",")
- }
- tmpAdminRsReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpTryOutNum,
- TryOutIds: tmpTryOutId,
- FormalNum: tmpFormalNum,
- FormalIds: tmpFormalId,
- ActiveNum: tmpActiveStatus,
- ActiveIds: tmpActiveId,
- AllActiveNum: tmpAllActiveStatus,
- AllActiveIds: tmpAllActiveId,
- NoIncrementalActiveNum: tmpNoIncrementalActiveStatus,
- NoIncrementalActiveIds: tmpNoIncrementalActiveId,
- StartDate: adminData.StartDate,
- EndDate: adminData.EndDate,
- }
- tmpCompanyReportRecordNumList = append(tmpCompanyReportRecordNumList, tmpAdminRsReportRecordNum)
- //组内数据汇总
- if _, ok := tmpGroupTryOutNumMap[index]; !ok {
- tmpGroupTryOutNumMap[index] = 0
- }
- if _, ok := tmpGroupFormalNumMap[index]; !ok {
- tmpGroupFormalNumMap[index] = 0
- }
- if _, ok := tmpGroupActiveNumMap[index]; !ok {
- tmpGroupActiveNumMap[index] = 0
- }
- if _, ok := tmpGroupAllActiveNumMap[index]; !ok {
- tmpGroupAllActiveNumMap[index] = 0
- }
- if _, ok := tmpGroupNoIncrementalActiveNumMap[index]; !ok {
- tmpGroupNoIncrementalActiveNumMap[index] = 0
- }
- tmpGroupTryOutNumMap[index] += tmpTryOutNum
- tmpGroupFormalNumMap[index] += tmpFormalNum
- tmpGroupActiveNumMap[index] += tmpActiveStatus
- tmpGroupAllActiveNumMap[index] += tmpAllActiveStatus
- tmpGroupNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
- //组内数据汇总
- if _, ok := tmpGroupTryOutIdMap[index]; !ok {
- tmpGroupTryOutIdMap[index] = ""
- }
- if _, ok := tmpGroupFormalIdMap[index]; !ok {
- tmpGroupFormalIdMap[index] = ""
- }
- if _, ok := tmpGroupActiveIdMap[index]; !ok {
- tmpGroupActiveIdMap[index] = ""
- }
- if tmpTryOutId != "" {
- tmpGroupTryOutIdSliceMap[index] = append(tmpGroupTryOutIdSliceMap[index], tmpTryOutId)
- }
- if tmpFormalId != "" {
- tmpGroupFormalIdSliceMap[index] = append(tmpGroupFormalIdSliceMap[index], tmpFormalId)
- }
- if tmpActiveId != "" {
- tmpGroupActiveIdSliceMap[index] = append(tmpGroupActiveIdSliceMap[index], tmpActiveId)
- }
- if tmpAllActiveId != "" {
- tmpGroupAllActiveIdSliceMap[index] = append(tmpGroupAllActiveIdSliceMap[index], tmpAllActiveId)
- }
- if tmpNoIncrementalActiveId != "" {
- tmpGroupNoIncrementalActiveIdSliceMap[index] = append(tmpGroupNoIncrementalActiveIdSliceMap[index], tmpNoIncrementalActiveId)
- }
- //总数据汇总
- if _, ok := tmpAllTryOutNumMap[index]; !ok {
- tmpAllTryOutNumMap[index] = 0
- }
- if _, ok := tmpAllFormalNumMap[index]; !ok {
- tmpAllFormalNumMap[index] = 0
- }
- if _, ok := tmpAllActiveNumMap[index]; !ok {
- tmpAllActiveNumMap[index] = 0
- }
- if _, ok := tmpAllAllActiveNumMap[index]; !ok {
- tmpAllAllActiveNumMap[index] = 0
- }
- if _, ok := tmpAllNoIncrementalActiveNumMap[index]; !ok {
- tmpAllNoIncrementalActiveNumMap[index] = 0
- }
- tmpAllTryOutNumMap[index] += tmpTryOutNum
- tmpAllFormalNumMap[index] += tmpFormalNum
- tmpAllActiveNumMap[index] += tmpActiveStatus
- tmpAllAllActiveNumMap[index] += tmpAllActiveStatus
- tmpAllNoIncrementalActiveNumMap[index] += tmpNoIncrementalActiveStatus
- ////总数据汇总
- //if _, ok := tmpAllTryOutIdMap[index]; !ok {
- // tmpAllTryOutIdMap[index] = ""
- //}
- //if _, ok := tmpAllFormalIdMap[index]; !ok {
- // tmpAllFormalIdMap[index] = ""
- //}
- //if _, ok := tmpAllActiveIdMap[index]; !ok {
- // tmpAllActiveIdMap[index] = ""
- //}
- //tmpAllTryOutIdMap[index] += tmpTryOutId
- //tmpAllFormalIdMap[index] += tmpFormalId
- //tmpAllActiveIdMap[index] += tmpActiveId
- }
- tmpAdminReportRecord := statistic_report.AdminReportRecord{
- Name: researcher.RealName,
- AdminId: researcher.AdminId,
- CompanyReportRecordNumList: tmpCompanyReportRecordNumList,
- }
- tmpGroupAdminReportRecord = append(tmpGroupAdminReportRecord, tmpAdminReportRecord)
- }
- for i := 0; i < len(tmpGroupActiveNumMap); i++ {
- tmpGroupTryOutIdMap[i] = strings.Join(tmpGroupTryOutIdSliceMap[i], ",")
- tmpGroupFormalIdMap[i] = strings.Join(tmpGroupFormalIdSliceMap[i], ",")
- tmpGroupActiveIdMap[i] = strings.Join(tmpGroupActiveIdSliceMap[i], ",")
- tmpGroupAllActiveIdMap[i] = strings.Join(tmpGroupAllActiveIdSliceMap[i], ",")
- tmpGroupNoIncrementalActiveIdMap[i] = strings.Join(tmpGroupNoIncrementalActiveIdSliceMap[i], ",")
- tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpGroupTryOutNumMap[i],
- TryOutIds: tmpGroupTryOutIdMap[i],
- FormalNum: tmpGroupFormalNumMap[i],
- FormalIds: tmpGroupFormalIdMap[i],
- ActiveNum: tmpGroupActiveNumMap[i],
- ActiveIds: tmpGroupActiveIdMap[i],
- AllActiveNum: tmpGroupAllActiveNumMap[i],
- AllActiveIds: tmpGroupAllActiveIdMap[i],
- NoIncrementalActiveNum: tmpGroupNoIncrementalActiveNumMap[i],
- NoIncrementalActiveIds: tmpGroupNoIncrementalActiveIdMap[i],
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- }
- tmpGroupCompanyReportRecordNumList = append(tmpGroupCompanyReportRecordNumList, tmpGroupCompanyReportRecordNum)
- }
- groupReportRecord := statistic_report.GroupReportRecord{
- Item: tmpGroupAdminReportRecord,
- Name: v.GroupName,
- GroupId: v.GroupId,
- CompanyReportRecordNumList: tmpGroupCompanyReportRecordNumList,
- }
- groupReportRecordList = append(groupReportRecordList, groupReportRecord)
- }
- //总体汇总数据
- for i := 0; i < len(tmpAllFormalNumMap); i++ {
- tmpGroupCompanyReportRecordNum := statistic_report.CompanyReportRecordNum{
- TryOutNum: tmpAllTryOutNumMap[i],
- TryOutIds: tmpAllTryOutIdMap[i],
- FormalNum: tmpAllFormalNumMap[i],
- FormalIds: tmpAllFormalIdMap[i],
- ActiveNum: tmpAllActiveNumMap[i],
- ActiveIds: tmpAllActiveIdMap[i],
- AllActiveNum: tmpAllAllActiveNumMap[i],
- AllActiveIds: tmpAllAllActiveIdMap[i],
- NoIncrementalActiveNum: tmpAllNoIncrementalActiveNumMap[i],
- NoIncrementalActiveIds: tmpAllNoIncrementalActiveIdMap[i],
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- }
- allCompanyReportRecordNum = append(allCompanyReportRecordNum, tmpGroupCompanyReportRecordNum)
- }
- companyReportRecordResp.CompanyReportRecordNumList = allCompanyReportRecordNum
- tmpList := groupReportRecordList
- //因为RoleTypeCode不一样,所以需要重新从数据库取数据
- adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
- adminGroupId := adminInfo.GroupId
- if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
- adminGroupId = tmpGroupId
- }
- switch adminInfo.RoleTypeCode {
- case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyReportRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_RAI_GROUP:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminReportRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyReportRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
- //管理员、超管看全部数据
- companyReportRecordResp.List = tmpList
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = companyReportRecordResp
- }
- // CompanyList
- // @Title 客户列表
- // @Description 客户列表接口
- // @Param request body statisticModels.IncrementalCompanyListReq true "type json string"
- // @Success 200 {object} statistic_report.CompanyListResp
- // @router /report/company_list [post]
- func (this *StatisticReportController) CompanyList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- //roleTypeCode := sysUser.RoleTypeCode
- var req statisticModels.IncrementalCompanyListReq
- err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
- if err != nil {
- br.Msg = "参数解析异常!"
- br.ErrMsg = "参数解析失败,Err:" + err.Error()
- return
- }
- resp, err, errMsg := statistic_report.CompanyList(sysUser, req)
- if err != nil {
- br.Msg = err.Error()
- br.ErrMsg = errMsg
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // RenewCompanyStatistics
- // @Title 获取续约客户统计数据
- // @Description 获取续约客户统计数据接口
- // @Param DataType query string true "枚举值:week、month、time_interval"
- // @Param ProductId query int true "客户类型 ficc:1 权益:2"
- // @Param StartDate query string true "开始日期,格式:2022-04-06"
- // @Param EndDate query string true "结束日期,格式:2022-04-06"
- // @Success 200 {object} statistic_report.CompanyRenewRecordResp
- // @router /report/renew_company [get]
- func (this *StatisticReportController) RenewCompanyStatistics() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- dataType := this.GetString("DataType")
- productId, _ := this.GetInt("ProductId", 1)
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- var companyRenewDataMapList []statistic_report.CompanyRenewDataMap
- var err error
- var firstDate time.Time
- switch dataType {
- //获取列表
- case "week":
- nowWeekMonday := utils.GetNowWeekMonday() //本周周一
- //companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
- companyRenewDataMapList, firstDate, err = statistic_report.GetRenewWeekDataNum(nowWeekMonday, productId, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "month":
- nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
- //companyRenewDataMapList, firstDate, err = statistic_report.GetMonthData()
- companyRenewDataMapList, firstDate, err = statistic_report.GetRenewMonthDataNum(nowMonthFirstDay, productId, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "time_interval":
- if startDate == `` || endDate == `` {
- br.Msg = "开始日期或结束日期不能为空"
- br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
- return
- }
- companyRenewDataMapList, firstDate, err = statistic_report.GetRenewTimeIntervalData(productId, startDate, endDate)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- }
- var group []services.AdminGroup
- var groupIdRelationMap map[int]int
- var groupMap map[int][]*roadshow.Researcher
- //获取销售人员分组数据
- if productId == 1 {
- group, groupIdRelationMap, err = services.GetFiccSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetFiccSeller(firstDate, groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "ficc_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- } else {
- group, groupIdRelationMap, err = services.GetRaiSystemGroup()
- if err != nil {
- br.Msg = "获取信息失败!"
- br.ErrMsg = "获取分组信息失败!Err:" + err.Error()
- return
- }
- researcherList, tmpErr := services.GetRaiSeller(groupIdRelationMap)
- if tmpErr != nil {
- err = tmpErr
- }
- groupMap = make(map[int][]*roadshow.Researcher)
- for _, v := range researcherList {
- if v.RoleTypeCode == "rai_admin" {
- findItems := groupMap[1]
- findItems = append(findItems, v)
- groupMap[1] = findItems
- } else {
- if findItems, ok := groupMap[v.GroupId]; ok {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- } else {
- findItems = append(findItems, v)
- groupMap[v.GroupId] = findItems
- }
- }
- }
- }
- //数据处理
- groupRenewRecordList := make([]statistic_report.GroupRenewRecord, 0)
- allCompanyRenewRecordNum := make([]statistic_report.CompanyRenewRecordNum, 0)
- companyRenewRecordResp := statistic_report.CompanyRenewRecordResp{
- List: groupRenewRecordList,
- CompanyRenewRecordNumList: allCompanyRenewRecordNum,
- }
- startDateIndexList := make(map[int]string) //开始时间间隔map
- endDateIndexList := make(map[int]string) //结束时间间隔map
- //客户数汇总
- tmpAllNotRenewNumMap := make(map[int]int)
- tmpAllRenewFollowNumMap := make(map[int]int)
- tmpAllExpireNumMap := make(map[int]int)
- tmpAllRenewNumMap := make(map[int]int)
- tmpAllUnusualRenewNumMap := make(map[int]int) // 续约异常客户数量汇总
- tmpAllFormalCompanyNumMap := make(map[int]int) // 当期正式客户数量汇总
- //id集合汇总
- tmpAllNotRenewIdMap := make(map[int]string)
- tmpAllRenewFollowIdMap := make(map[int]string)
- tmpAllExpireIdMap := make(map[int]string)
- tmpAllRenewIdMap := make(map[int]string)
- tmpAllUnusualRenewIdMap := make(map[int]string) // 续约异常客户id汇总
- tmpAllUnusualRenewIdSlice := make(map[int][]string, 0)
- for _, v := range group {
- v.ResearcherList = groupMap[v.GroupId]
- tmpGroupAdminRenewRecord := make([]statistic_report.AdminRenewRecord, 0)
- tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)
- //数量统计
- tmpGroupNotRenewNumMap := make(map[int]int)
- tmpGroupRenewFollowNumMap := make(map[int]int)
- tmpGroupExpireNumMap := make(map[int]int)
- tmpGroupRenewNumMap := make(map[int]int)
- tmpGroupUnusualRenewNumMap := make(map[int]int) //组内续约异常客户数
- //id集合
- tmpGroupNotRenewIdSliceMap := make(map[int][]string)
- tmpGroupRenewFollowIdSliceMap := make(map[int][]string)
- tmpGroupExpireIdSliceMap := make(map[int][]string)
- tmpGroupRenewIdSliceMap := make(map[int][]string)
- tmpGroupUnusualRenewIdSliceMap := make(map[int][]string) // 组内续约异常客户id汇总
- //id集合
- tmpGroupNotRenewIdMap := make(map[int]string)
- tmpGroupRenewFollowIdMap := make(map[int]string)
- tmpGroupExpireIdMap := make(map[int]string)
- tmpGroupRenewIdMap := make(map[int]string)
- tmpGroupUnusualRenewIdMap := make(map[int]string) // 组内续约异常客户id汇总
- for _, researcher := range groupMap[v.GroupId] {
- //组内研究员数据
- //每个区间的数据
- tmpCompanyRenewRecordNumList := make([]statistic_report.CompanyRenewRecordNum, 0)
- for index, adminData := range companyRenewDataMapList {
- startDateIndexList[index] = adminData.StartDate
- endDateIndexList[index] = adminData.EndDate
- var tmpNotRenewNum, tmpRenewFollowNum, tmpExpireStatus, tmpRenewStatus, tmpUnusualRenewStatus int
- //var tmpNotRenewIds, tmpRenewFollowIds, tmpExpireIds string
- var tmpNotRenewIdSlice, tmpRenewFollowIdSlice, tmpExpireIdSlice, tmpRenewIdSlice, tmpUnusualRenewIdSlice []string
- var tmpNotRenewId, tmpRenewFollowId, tmpExpireId, tmpRenewId, tmpUnusualRenewId string
- if num, ok := adminData.NotRenewMap[researcher.AdminId]; ok {
- tmpNotRenewNum = num
- tmpNotRenewIdSlice = append(tmpNotRenewIdSlice, adminData.NotRenewIdMap[researcher.AdminId])
- tmpNotRenewId = strings.Join(tmpNotRenewIdSlice, ",")
- }
- if num, ok := adminData.RenewFollowMap[researcher.AdminId]; ok {
- tmpRenewFollowNum = num
- tmpRenewFollowIdSlice = append(tmpRenewFollowIdSlice, adminData.RenewFollowIdMap[researcher.AdminId])
- tmpRenewFollowId = strings.Join(tmpRenewFollowIdSlice, ",")
- }
- if num, ok := adminData.ExpireMap[researcher.AdminId]; ok {
- tmpExpireStatus = num
- tmpExpireIdSlice = append(tmpExpireIdSlice, adminData.ExpireIdMap[researcher.AdminId])
- tmpExpireId = strings.Join(tmpExpireIdSlice, ",")
- }
- if num, ok := adminData.RenewMap[researcher.AdminId]; ok {
- tmpRenewStatus = num
- tmpRenewIdSlice = append(tmpRenewIdSlice, adminData.RenewIdMap[researcher.AdminId])
- tmpRenewId = strings.Join(tmpRenewIdSlice, ",")
- }
- // 续约异常客户
- if num, ok := adminData.UnusualRenewMap[researcher.AdminId]; ok {
- tmpUnusualRenewStatus = num
- tmpUnusualRenewIdSlice = append(tmpUnusualRenewIdSlice, adminData.UnusualRenewIdMap[researcher.AdminId])
- tmpUnusualRenewId = strings.Join(tmpUnusualRenewIdSlice, ",")
- }
- tmpAdminRsRenewRecordNum := statistic_report.CompanyRenewRecordNum{
- NotRenewNum: tmpNotRenewNum,
- NotRenewIds: tmpNotRenewId,
- RenewFollowNum: tmpRenewFollowNum,
- RenewFollowIds: tmpRenewFollowId,
- ExpireNum: tmpExpireStatus,
- ExpireIds: tmpExpireId,
- RenewNum: tmpRenewStatus,
- RenewIds: tmpRenewId,
- UnusualRenewNum: tmpUnusualRenewStatus,
- UnusualRenewIds: tmpUnusualRenewId,
- StartDate: adminData.StartDate,
- EndDate: adminData.EndDate,
- }
- tmpCompanyRenewRecordNumList = append(tmpCompanyRenewRecordNumList, tmpAdminRsRenewRecordNum)
- //组内数据汇总
- if _, ok := tmpGroupNotRenewNumMap[index]; !ok {
- tmpGroupNotRenewNumMap[index] = 0
- }
- if _, ok := tmpGroupRenewFollowNumMap[index]; !ok {
- tmpGroupRenewFollowNumMap[index] = 0
- }
- if _, ok := tmpGroupExpireNumMap[index]; !ok {
- tmpGroupExpireNumMap[index] = 0
- }
- if _, ok := tmpGroupRenewNumMap[index]; !ok {
- tmpGroupRenewNumMap[index] = 0
- }
- if _, ok := tmpGroupUnusualRenewNumMap[index]; !ok {
- tmpGroupUnusualRenewNumMap[index] = 0
- }
- tmpGroupNotRenewNumMap[index] += tmpNotRenewNum
- tmpGroupRenewFollowNumMap[index] += tmpRenewFollowNum
- tmpGroupExpireNumMap[index] += tmpExpireStatus
- tmpGroupRenewNumMap[index] += tmpRenewStatus
- tmpGroupUnusualRenewNumMap[index] += tmpUnusualRenewStatus
- //组内数据汇总
- if _, ok := tmpGroupNotRenewIdMap[index]; !ok {
- tmpGroupNotRenewIdMap[index] = ""
- }
- if _, ok := tmpGroupRenewFollowIdMap[index]; !ok {
- tmpGroupRenewFollowIdMap[index] = ""
- }
- if _, ok := tmpGroupExpireIdMap[index]; !ok {
- tmpGroupExpireIdMap[index] = ""
- }
- if tmpNotRenewId != "" {
- tmpGroupNotRenewIdSliceMap[index] = append(tmpGroupNotRenewIdSliceMap[index], tmpNotRenewId)
- }
- if tmpRenewFollowId != "" {
- tmpGroupRenewFollowIdSliceMap[index] = append(tmpGroupRenewFollowIdSliceMap[index], tmpRenewFollowId)
- }
- if tmpExpireId != "" {
- tmpGroupExpireIdSliceMap[index] = append(tmpGroupExpireIdSliceMap[index], tmpExpireId)
- }
- if tmpRenewId != "" {
- tmpGroupRenewIdSliceMap[index] = append(tmpGroupRenewIdSliceMap[index], tmpRenewId)
- }
- if tmpUnusualRenewId != "" {
- tmpGroupUnusualRenewIdSliceMap[index] = append(tmpGroupUnusualRenewIdSliceMap[index], tmpUnusualRenewId)
- tmpSlice := strings.Split(tmpUnusualRenewId, ",")
- tmpAllUnusualRenewIdSlice[index] = append(tmpAllUnusualRenewIdSlice[index], tmpSlice...)
- }
- //总数据汇总
- if _, ok := tmpAllNotRenewNumMap[index]; !ok {
- tmpAllNotRenewNumMap[index] = 0
- }
- if _, ok := tmpAllRenewFollowNumMap[index]; !ok {
- tmpAllRenewFollowNumMap[index] = 0
- }
- if _, ok := tmpAllExpireNumMap[index]; !ok {
- tmpAllExpireNumMap[index] = 0
- }
- if _, ok := tmpAllRenewNumMap[index]; !ok {
- tmpAllRenewNumMap[index] = 0
- }
- tmpAllNotRenewNumMap[index] += tmpNotRenewNum
- tmpAllRenewFollowNumMap[index] += tmpRenewFollowNum
- tmpAllExpireNumMap[index] += tmpExpireStatus
- tmpAllRenewNumMap[index] += tmpRenewStatus
- tmpAllUnusualRenewNumMap[index] = adminData.UnusualRenewTotal
- tmpAllFormalCompanyNumMap[index] = adminData.FormalCompanyTotal
- }
- tmpAdminRenewRecord := statistic_report.AdminRenewRecord{
- Name: researcher.RealName,
- AdminId: researcher.AdminId,
- CompanyRenewRecordNumList: tmpCompanyRenewRecordNumList,
- }
- tmpGroupAdminRenewRecord = append(tmpGroupAdminRenewRecord, tmpAdminRenewRecord)
- }
- for i := 0; i < len(tmpGroupExpireNumMap); i++ {
- tmpGroupNotRenewIdMap[i] = strings.Join(tmpGroupNotRenewIdSliceMap[i], ",")
- tmpGroupRenewFollowIdMap[i] = strings.Join(tmpGroupRenewFollowIdSliceMap[i], ",")
- tmpGroupExpireIdMap[i] = strings.Join(tmpGroupExpireIdSliceMap[i], ",")
- tmpGroupRenewIdMap[i] = strings.Join(tmpGroupRenewIdSliceMap[i], ",")
- tmpGroupUnusualRenewIdMap[i] = strings.Join(tmpGroupUnusualRenewIdSliceMap[i], ",")
- tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
- NotRenewNum: tmpGroupNotRenewNumMap[i],
- NotRenewIds: tmpGroupNotRenewIdMap[i],
- RenewFollowNum: tmpGroupRenewFollowNumMap[i],
- RenewFollowIds: tmpGroupRenewFollowIdMap[i],
- ExpireNum: tmpGroupExpireNumMap[i],
- ExpireIds: tmpGroupExpireIdMap[i],
- RenewNum: tmpGroupRenewNumMap[i],
- RenewIds: tmpGroupRenewIdMap[i],
- UnusualRenewNum: tmpGroupUnusualRenewNumMap[i],
- UnusualRenewIds: tmpGroupUnusualRenewIdMap[i],
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- }
- tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, tmpGroupCompanyRenewRecordNum)
- }
- groupRenewRecord := statistic_report.GroupRenewRecord{
- Item: tmpGroupAdminRenewRecord,
- Name: v.GroupName,
- GroupId: v.GroupId,
- CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
- }
- groupRenewRecordList = append(groupRenewRecordList, groupRenewRecord)
- }
- // 总体数据汇总,去掉重复销售的公司个数
- //总体汇总数据
- for i := 0; i < len(tmpAllRenewFollowNumMap); i++ {
- // 未续约统计数据去重
- unusualRenewIdsFinal := make([]string, 0)
- unusualRenewIdsMap := make(map[string]struct{})
- for _, id := range tmpAllUnusualRenewIdSlice[i] {
- if _, ok := unusualRenewIdsMap[id]; !ok {
- unusualRenewIdsFinal = append(unusualRenewIdsFinal, id)
- unusualRenewIdsMap[id] = struct{}{}
- }
- }
- tmpAllUnusualRenewNumMap[i] = len(unusualRenewIdsFinal)
- tmpAllUnusualRenewIdMap[i] = strings.Join(unusualRenewIdsFinal, ",")
- unusualRate := ``
- if tmpAllUnusualRenewNumMap[i] > 0 && tmpAllFormalCompanyNumMap[i] > 0 {
- unusualRate = decimal.NewFromInt(int64(tmpAllUnusualRenewNumMap[i])*100).Div(decimal.NewFromInt(int64(tmpAllFormalCompanyNumMap[i]))).Round(2).String() + "%"
- }
- tmpGroupCompanyRenewRecordNum := statistic_report.CompanyRenewRecordNum{
- NotRenewNum: tmpAllNotRenewNumMap[i],
- NotRenewIds: tmpAllNotRenewIdMap[i],
- RenewFollowNum: tmpAllRenewFollowNumMap[i],
- RenewFollowIds: tmpAllRenewFollowIdMap[i],
- ExpireNum: tmpAllExpireNumMap[i],
- ExpireIds: tmpAllExpireIdMap[i],
- RenewNum: tmpAllRenewNumMap[i],
- RenewIds: tmpAllRenewIdMap[i],
- UnusualRenewNum: tmpAllUnusualRenewNumMap[i],
- UnusualRenewIds: tmpAllUnusualRenewIdMap[i],
- UnusualRate: unusualRate, // 异常率
- StartDate: startDateIndexList[i],
- EndDate: endDateIndexList[i],
- }
- allCompanyRenewRecordNum = append(allCompanyRenewRecordNum, tmpGroupCompanyRenewRecordNum)
- }
- companyRenewRecordResp.CompanyRenewRecordNumList = allCompanyRenewRecordNum
- tmpList := groupRenewRecordList
- //因为RoleTypeCode不一样,所以需要重新从数据库取数据
- adminInfo, _ := system.GetSysAdminById(sysUser.AdminId)
- adminGroupId := adminInfo.GroupId
- if tmpGroupId, ok := groupIdRelationMap[adminGroupId]; ok {
- adminGroupId = tmpGroupId
- }
- if productId == 2 {
- //对权益组排个序
- tmpList = statistic_report.SortGroupSellers(tmpList)
- }
- switch adminInfo.RoleTypeCode {
- case utils.ROLE_TYPE_CODE_FICC_GROUP, utils.ROLE_TYPE_CODE_FICC_TEAM:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyRenewRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_RAI_GROUP:
- for index, v := range tmpList {
- //如果不是同一个分组,那么就移除该分组下的人员数据
- if v.GroupId != adminGroupId {
- tmpList[index].Item = make([]statistic_report.AdminRenewRecord, 0)
- } else {
- tmpList[index], tmpList[0] = tmpList[0], tmpList[index]
- }
- }
- companyRenewRecordResp.List = tmpList
- case utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_RAI_ADMIN:
- //管理员、超管看全部数据
- companyRenewRecordResp.List = tmpList
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = companyRenewRecordResp
- }
- // List
- // @Title 商品到款统计列表
- // @Description 商品到款统计列表
- // @Param Keyword query string false "关键词"
- // @Param ServiceType query int false "套餐类型"
- // @Param StartDate query string false "合同开始日期"
- // @Param EndDate query string false "合同结束日期"
- // @Param TimeType query int false "时间类型: 1-开票时间; 2-到款时间"
- // @Param hasInvoice query string false "是否已开票: 0-否; 1-是; 空-全部"
- // @Param HasPayment query string false "是否已到款: 0-否; 1-是; 空-全部"
- // @Param ListParam query int false "套餐类型: 0-全部; 1-ficc; 2-权益"
- // @Param SortParam query string false "排序字段参数,用来排序的字段, 枚举值:'invoice_time':开票日 、 'payment_date':到款日"
- // @Param SortType query string true "如何排序,是正序还是倒序,枚举值:`asc 正序`,`desc 倒叙`"
- // @Success 200 {object} fms.ContractRegisterItem
- // @router /census/invoice_payment/list [get]
- func (this *StatisticReportController) InvoicePaymentList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- keyword := this.GetString("Keyword")
- serviceType := this.GetString("ServiceType")
- timeType, _ := this.GetInt("TimeType")
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- hasInvoice := this.GetString("HasInvoice")
- hasPayment := this.GetString("HasPayment")
- sortParam := this.GetString("SortParam")
- sortType := this.GetString("SortType")
- sellerIdstr := this.GetString("SellerIds")
- cond := `1 = 1`
- pars := make([]interface{}, 0)
- // 客户姓名/销售
- if keyword != "" {
- kw := "%" + keyword + "%"
- cond += ` AND b.company_name LIKE ?`
- pars = append(pars, kw)
- }
- if sellerIdstr != "" {
- //sellerIds := strings.Split(sellerIdstr, ",")
- cond += ` AND (c.seller_id in (` +sellerIdstr+ `) OR d.seller_id in (` +sellerIdstr+ `))`
- //pars = append(pars, sellerIds, sellerIds)
- }
- // 套餐筛选
- if serviceType != "" {
- serviceTypes := strings.Split(serviceType, ",")
- tempRegisterIds, e := fms.GetContractRegisterIdsByTempId(serviceTypes)
- if e != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取合同登记IDs失败,Err:" + e.Error()
- return
- }
- if len(tempRegisterIds) > 0 {
- cond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(tempRegisterIds)) + `)`
- pars = append(pars, tempRegisterIds)
- } else {
- cond += ` AND 1 = 2`
- }
- }
- var depId int
- if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
- depId = 2
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
- depId = 5
- }
- dshiAdminId := 13
- if utils.RunMode == "debug" {
- dshiAdminId = 233
- }
- if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN {
- sellerIdsList, err := system.GetSellerIdsByDepId(depId)
- if err != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款统计列表总数失败,Err:" + err.Error()
- return
- }
- cond += ` AND (c.seller_id IN (` + strings.Join(sellerIdsList, ",") + `) OR d.seller_id IN (` + strings.Join(sellerIdsList, ",") + `))`
- } else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_GROUP && sysUser.AdminId == dshiAdminId {
- groupTeamSellerList, err := system.GetSysUserByParentIdGroupId(5)
- if err != nil {
- br.Msg = "获取销售失败"
- br.ErrMsg = "获取销售失败,Err:" + err.Error()
- return
- }
- sellerIdsList := ""
- for _, v := range groupTeamSellerList {
- sellerIdsList += strconv.Itoa(v.AdminId) + ","
- }
- sellerIdsList = strings.TrimRight(sellerIdsList, ",")
- cond += ` AND (c.seller_id IN (` + sellerIdsList + `) OR d.seller_id IN (` + sellerIdsList + `))`
- pars = append(pars)
- } else if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
- cond += ` AND (c.seller_id=? OR d.seller_id=?)`
- pars = append(pars, sysUser.AdminId, sysUser.AdminId)
- }
- // 开票到款日期
- if timeType != 0 {
- if timeType == 1 && startDate != "" && endDate != "" {
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- cond += ` AND (c.invoice_time BETWEEN ? AND ?) `
- pars = append(pars, st, ed)
- } else if timeType == 2 && startDate != "" && endDate != "" {
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- cond += ` AND (d.invoice_time BETWEEN ? AND ?) `
- pars = append(pars, st, ed)
- } else if timeType == 3 && startDate != "" && endDate != "" {
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- cond += ` AND (c.invoice_time BETWEEN ? AND ?) AND (d.invoice_time BETWEEN ? AND ?) `
- pars = append(pars, st, ed, st, ed)
- }
- } else if startDate != "" && endDate != "" {
- st := fmt.Sprint(startDate, " 00:00:00")
- ed := fmt.Sprint(endDate, " 23:59:59")
- cond += ` AND ((c.invoice_time BETWEEN ? AND ?) or (d.invoice_time BETWEEN ? AND ?))`
- pars = append(pars, st, ed, st, ed)
- }
- if hasInvoice == "1" {
- cond += ` AND a.invoice_id > 0 `
- } else if hasInvoice == "0" {
- cond += ` AND a.invoice_id = 0 `
- }
- if hasPayment == "1" {
- cond += ` AND a.payment_id > 0 `
- } else if hasPayment == "0" {
- cond += ` AND a.payment_id = 0 `
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- //排序
- if sortType == "" {
- sortType = "desc"
- }
- if sortType != "desc" && sortType != "asc" {
- br.Msg = "排序类型不正确!"
- return
- }
- var order string
- if sortParam == "" {
- order = ` ORDER BY sort_invoice_id ,sort_payment_id desc,c.invoice_time desc,c.amount desc,a.create_time desc `
- } else if sortParam == "invoice_time" {
- if sortType == "asc" {
- order = ` ORDER BY sort_invoice_id desc,c.invoice_time ,c.amount ,a.create_time ASC `
- } else {
- order = ` ORDER BY sort_invoice_id ,c.invoice_time desc,c.amount desc,a.create_time desc `
- }
- } else if sortParam == "payment_date" {
- if sortType == "asc" {
- order = ` ORDER BY sort_payment_id desc,d.invoice_time ,d.amount ,a.create_time `
- } else {
- order = ` ORDER BY sort_payment_id ,d.invoice_time desc,d.amount desc,a.create_time desc `
- }
- } else {
- br.Msg = "排序字段不正确!"
- return
- }
- registerList, total, e := fms.GetInvoicePaymentCensusPageList(cond, pars, order, startSize, pageSize)
- if e != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款统计列表总数失败,Err:" + e.Error()
- return
- }
- queryRegisterIds := make([]int, 0)
- for i := range registerList {
- queryRegisterIds = append(queryRegisterIds, registerList[i].ContractRegisterId)
- }
- //fmt.Println("queryRegisterIds:",queryRegisterIds)
- results := new(fms.InvoicePaymentCensusResp)
- if len(queryRegisterIds) > 0 {
- // 获取汇总数据IDs, 用于查询合计数据
- summaryIdsCond := cond
- summaryIdsPars := pars
- summaryIds, e := fms.GetInvoicePaymentCensusSummaryDataIds(summaryIdsCond, summaryIdsPars)
- if e != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款汇总IDs失败,Err:" + e.Error()
- return
- }
- //fmt.Println("summaryIds:",summaryIds)
- var listErr, totalErr, totalGroupErr error
- wg := sync.WaitGroup{}
- // 响应列表
- respList := make([]*fms.InvoicePaymentCensusItem, 0)
- summaryList := make([]*fms.InvoicePaymentSummaryItem, 0)
- wg.Add(1)
- go func() {
- defer wg.Done()
- // 获取汇总数据
- summaryCond := cond
- summaryCond += ` AND a.register_id IN (` + utils.GetOrmInReplace(len(queryRegisterIds)) + `)`
- summaryPars := pars
- summaryPars = append(summaryPars, queryRegisterIds)
- summaryData, e := fms.GetInvoicePaymentCensusSummaryData(summaryCond, summaryPars)
- if e != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款汇总列表失败,Err:" + e.Error()
- return
- }
- summaryList = summaryData
- //summaryIds := make([]int, 0)
- paymentIds := make([]int, 0)
- for i := range summaryList {
- //summaryIds = append(summaryIds, summaryList[i].SummaryId)
- if summaryList[i].PaymentId > 0 {
- paymentIds = append(paymentIds, summaryList[i].PaymentId)
- }
- }
- // 合同套餐
- /*contractServiceCond := `contract_register_id IN ?`
- contractServicePars := make([]interface{}, 0)
- contractServicePars = append(contractServicePars, queryRegisterIds)
- contractServiceOB := new(fms.ContractService)
- contractServiceList, e := contractServiceOB.List(contractServiceCond, contractServicePars)
- if e != nil {
- listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
- return
- }
- contractServiceMap := make(map[int][]*fms.ContractService, 0)
- servicesNameMap := make(map[int][]string, 0)
- for i := range contractServiceList {
- if contractServiceMap[contractServiceList[i].ContractRegisterId] == nil {
- contractServiceMap[contractServiceList[i].ContractRegisterId] = make([]*fms.ContractService, 0)
- }
- contractServiceMap[contractServiceList[i].ContractRegisterId] = append(contractServiceMap[contractServiceList[i].ContractRegisterId], contractServiceList[i])
- servicesNameMap[contractServiceList[i].ContractRegisterId] = append(servicesNameMap[contractServiceList[i].ContractRegisterId], contractServiceList[i].Title)
- }
- */
- servicesNameMap, serviceFormatMap, e := fmsService.GetContractServiceNameFormat(queryRegisterIds)
- if e != nil {
- listErr = fmt.Errorf("获取合同套餐列表失败, Err: %s", e.Error())
- return
- }
- // 到款套餐分配
- serviceAmountMap := make(map[int][]*fms.ContractPaymentServiceAmount, 0)
- if len(paymentIds) > 0 {
- serviceAmountCond := ` AND contract_payment_id IN (` + utils.GetOrmInReplace(len(paymentIds)) + `)`
- serviceAmountPars := make([]interface{}, 0)
- serviceAmountPars = append(serviceAmountPars, paymentIds)
- serviceAmountOB := new(fms.ContractPaymentServiceAmount)
- serviceAmountList, e := serviceAmountOB.List(serviceAmountCond, serviceAmountPars)
- if e != nil {
- listErr = fmt.Errorf("获取到款套餐分配列表失败, Err: %s", e.Error())
- return
- }
- for i := range serviceAmountList {
- if serviceAmountMap[serviceAmountList[i].ContractPaymentId] == nil {
- serviceAmountMap[serviceAmountList[i].ContractPaymentId] = make([]*fms.ContractPaymentServiceAmount, 0)
- }
- serviceAmountMap[serviceAmountList[i].ContractPaymentId] = append(serviceAmountMap[serviceAmountList[i].ContractPaymentId], serviceAmountList[i])
- }
- }
- // 重组汇总数据
- summaryMap := make(map[int][]*fms.InvoicePaymentCensusInfo)
- amountMap := make(map[string]*fms.ContractPaymentServiceAmount)
- for i := range summaryList {
- v := new(fms.InvoicePaymentCensusInfo)
- v.InvoiceId = summaryList[i].InvoiceId
- v.InvoiceDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].InvoiceDate)
- v.InvoiceAmount = summaryList[i].InvoiceAmount
- v.SellerId = summaryList[i].SellerId
- v.SellerName = summaryList[i].SellerName
- v.SellerGroupId = summaryList[i].SellerGroupId
- v.SellerGroupName = summaryList[i].SellerGroupName
- v.SellerType = summaryList[i].ServiceProductId
- v.PaymentId = summaryList[i].PaymentId
- v.PaymentDate = utils.TimeTransferString(utils.FormatDate, summaryList[i].PaymentDate)
- v.PaymentAmount = summaryList[i].PaymentAmount
- v.PayType = summaryList[i].PayType
- // 套餐到款分配
- svaList := make([]*fms.ContractPaymentServiceAmountItem, 0)
- amountList := serviceAmountMap[summaryList[i].PaymentId]
- if amountList != nil {
- for i := range amountList {
- k := fmt.Sprintf("%d-%d", amountList[i].ContractPaymentId, amountList[i].ServiceTemplateId)
- amountMap[k] = amountList[i]
- }
- }
- // 合同对应的所有套餐
- svList := serviceFormatMap[summaryList[i].RegisterId]
- if svList != nil {
- for ii := range svList {
- vv := new(fms.ContractPaymentServiceAmountItem)
- vv.ServiceTemplateId = svList[ii].ServiceTemplateId
- vv.ServiceTemplateName = svList[ii].FormatTitle
- vv.ServiceTemplatePid = svList[ii].ServiceTemplatePid
- vv.ServiceProductId = svList[ii].ServiceProductId
- k2 := fmt.Sprintf("%d-%d", summaryList[i].PaymentId, svList[ii].ServiceTemplateId)
- a := amountMap[k2]
- if a != nil {
- vv.ContractPaymentServiceAmountId = a.ContractPaymentServiceAmountId
- vv.ContractPaymentId = a.ContractPaymentId
- vv.Amount = a.Amount
- }
- svaList = append(svaList, vv)
- }
- }
- v.ServiceAmountList = svaList
- summaryMap[summaryList[i].SummaryId] = append(summaryMap[summaryList[i].SummaryId], v)
- }
- // 响应列表
- for i := range registerList {
- v := new(fms.InvoicePaymentCensusItem)
- v.SummaryId = registerList[i].SummaryId
- v.ContractRegisterId = registerList[i].ContractRegisterId
- v.CompanyName = registerList[i].CompanyName
- v.NewCompany = registerList[i].NewCompany
- v.StartDate = utils.TimeTransferString(utils.FormatDate, registerList[i].StartDate)
- v.EndDate = utils.TimeTransferString(utils.FormatDate, registerList[i].EndDate)
- v.ServicesName = servicesNameMap[registerList[i].ContractRegisterId]
- v.InvoicePaymentList = summaryMap[registerList[i].SummaryId]
- v.ContractType = registerList[i].ContractType
- v.ActualPayCompanies = registerList[i].ActualPayCompanies
- respList = append(respList, v)
- }
- }()
- // 开票到款金额合计(换算后)
- var invoiceTotal, paymentTotal, amountTotal float64
- wg.Add(1)
- go func() {
- defer wg.Done()
- if len(summaryIds) == 0 {
- return
- }
- amountTotalCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
- amountTotalPars := make([]interface{}, 0)
- amountTotalPars = append(amountTotalPars, summaryIds)
- invoiceSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 1)
- if e != nil {
- totalErr = fmt.Errorf("获取汇总开票金额合计失败, Err: %s", e.Error())
- return
- }
- invoiceTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSum), 64)
- paymentSum, e := fms.GetContractSummaryInvoicePaymentAmountTotal(amountTotalCond, amountTotalPars, 2)
- if e != nil {
- totalErr = fmt.Errorf("获取汇总到款金额合计失败, Err: %s", e.Error())
- return
- }
- paymentTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSum), 64)
- amountCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `) AND (a.invoice_id <> 0 OR (a.payment_id <> 0 AND a.invoice_id =0))`
- amountPars := make([]interface{}, 0)
- amountPars = append(amountPars, summaryIds)
- amountSum, e := fms.GetContractSummaryInvoicePaymentAmount(amountCond, amountPars)
- if e != nil {
- totalErr = fmt.Errorf("获取汇总金额合计失败, Err: %s", e.Error())
- return
- }
- amountTotal, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", amountSum), 64)
- }()
- // 分币种金额统计
- invoiceCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
- paymentCurrencyTotals := make([]*fms.InvoiceListCurrencyTotal, 0)
- wg.Add(1)
- go func() {
- defer wg.Done()
- currencyOB := new(fms.CurrencyUnit)
- currencyCond := `enable = 1`
- currencyPars := make([]interface{}, 0)
- currencyList, e := currencyOB.List(currencyCond, currencyPars)
- if e != nil {
- totalGroupErr = fmt.Errorf("获取货币列表失败, Err: %s", e.Error())
- return
- }
- unitMap := make(map[string]string)
- for i := range currencyList {
- unitMap[currencyList[i].Code] = currencyList[i].UnitName
- invoiceCurrencyTotals = append(invoiceCurrencyTotals, &fms.InvoiceListCurrencyTotal{
- Name: currencyList[i].Name,
- UnitName: currencyList[i].UnitName,
- Code: currencyList[i].Code,
- FlagImg: currencyList[i].FlagImg,
- })
- paymentCurrencyTotals = append(paymentCurrencyTotals, &fms.InvoiceListCurrencyTotal{
- Name: currencyList[i].Name,
- UnitName: currencyList[i].UnitName,
- Code: currencyList[i].Code,
- FlagImg: currencyList[i].FlagImg,
- })
- }
- if len(summaryIds) == 0 {
- return
- }
- totalGroupCond := `a.id IN (` + utils.GetOrmInReplace(len(summaryIds)) + `)`
- totalGroupPars := make([]interface{}, 0)
- totalGroupPars = append(totalGroupPars, summaryIds)
- invoiceSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 1)
- if e != nil {
- totalGroupErr = fmt.Errorf("获取汇总货币合计开票金额失败, Err: %s", e.Error())
- return
- }
- paymentSumGroup, e := fms.GetSummaryListCurrencySum(totalGroupCond, totalGroupPars, 2)
- if e != nil {
- totalGroupErr = fmt.Errorf("获取汇总货币合计到款金额失败, Err: %s", e.Error())
- return
- }
- invoiceSumMap := make(map[string]float64)
- paymentSumMap := make(map[string]float64)
- for i := range invoiceSumGroup {
- invoiceSumMap[invoiceSumGroup[i].CurrencyUnit] = invoiceSumGroup[i].OriginAmountTotal
- continue
- }
- for i := range paymentSumGroup {
- paymentSumMap[paymentSumGroup[i].CurrencyUnit] = paymentSumGroup[i].OriginAmountTotal
- continue
- }
- for i := range invoiceCurrencyTotals {
- a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", invoiceSumMap[invoiceCurrencyTotals[i].Code]), 64)
- invoiceCurrencyTotals[i].Amount = a
- }
- for i := range paymentCurrencyTotals {
- a, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", paymentSumMap[paymentCurrencyTotals[i].Code]), 64)
- paymentCurrencyTotals[i].Amount = a
- }
- }()
- wg.Wait()
- if listErr != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款汇总失败,Err:" + listErr.Error()
- return
- }
- if totalErr != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款汇总失败,Err:" + totalErr.Error()
- return
- }
- if totalGroupErr != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取商品到款汇总失败,Err:" + totalGroupErr.Error()
- return
- }
- results.DataList = respList
- results.InvoiceTotal = invoiceTotal
- results.PaymentTotal = paymentTotal
- results.AmountTotal = amountTotal
- results.InvoiceCurrencyTotal = invoiceCurrencyTotals
- results.PaymentCurrencyTotal = paymentCurrencyTotals
- }
- page := paging.GetPaging(currentIndex, pageSize, int(total))
- results.Paging = page
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = results
- }
- // SimpleList
- // @Title 合同套餐列表
- // @Description 合同套餐列表
- // @Param ProductId query int false "套餐类型: 1-FICC(默认); 2-权益"
- // @Success 200 {object} crm.ContractSearchListResp
- // @router /contract/service/simple [get]
- func (this *StatisticReportController) SimpleList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- list, err := fms.GetContractServiceTemplateSecond()
- if err != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取产品套餐失败,Err:" + err.Error()
- return
- }
- allList := make([]*fms.ContractServiceTemplateItem, 0)
- allMap := make(map[int][]*fms.ContractServiceTemplateMapItems)
- respList := make([]*fms.ContractServiceTemplateList, 0)
- for i := 0; i < len(list); i++ {
- if list[i].Title == "行业套餐" {
- industryList, e := fms.GetContractServiceTemplateMapByParentId(list[i].ServiceTemplateId)
- if e != nil {
- br.Msg = "获取失败!"
- br.ErrMsg = "获取套餐失败,Err:" + e.Error()
- return
- }
- for _, sv := range industryList {
- allList = append(allList, sv)
- }
- } else {
- allList = append(allList, list[i])
- }
- }
- for i := 0; i < len(allList); i++ {
- item := allList[i]
- v := new(fms.ContractServiceTemplateMapItems)
- v.ContractServiceTemplateItem = *item
- allMap[item.ProductId] = append(allMap[item.ProductId], v)
- }
- allTitleMap := map[int]string{
- 1: "FICC套餐",
- 2: "权益套餐",
- }
- tmp1 := &fms.ContractServiceTemplateList{
- Title: allTitleMap[1],
- Children: allMap[1],
- }
- tmp2 := &fms.ContractServiceTemplateList{
- Title: allTitleMap[2],
- Children: allMap[2],
- }
- respList = append(respList, tmp1)
- respList = append(respList, tmp2)
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = respList
- }
- // UnusualRenewCompanyStatistics
- // @Title 获取续约异常的客户统计数据
- // @Description 获取续约客户统计数据接口
- // @Param DataType query string true "枚举值:week、month、time_interval"
- // @Param Source query int true "类型,枚举值,1:续约异常客户;2:续约正常客户;3:超时续约客户;4:合同到期后一个月未续约客户;5:合同到期未续约客户;6:合同到期前一个月还未续约的客户;7:合同到期前两个月还未续约客户;8:合同到期前3个月还未续约客户;9:合同到期前4个月还未续约客户"
- // @Param StartDate query string true "开始日期,格式:2022-04-06"
- // @Param EndDate query string true "结束日期,格式:2022-04-06"
- // @Success 200 {object} statistic_report.CompanyUnusualRenewRecordResp
- // @router /report/unusual_renew_company [get]
- func (this *StatisticReportController) UnusualRenewCompanyStatistics() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- dataType := this.GetString("DataType")
- productId, _ := this.GetInt("ProductId", 1)
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- source, _ := this.GetInt("Source", 1)
- var companyUnusualRenewDataMapList []statistic_report.UnusualCompanyRenewDataMap
- var err error
- //var firstDate time.Time
- switch dataType {
- //获取列表
- case "week":
- nowWeekMonday := utils.GetNowWeekMonday() //本周周一
- //companyRenewDataMapList, firstDate, err = statistic_report.GetWeekData()
- companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewWeekDataNum(nowWeekMonday, productId, source, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "month":
- nowMonthFirstDay := utils.GetNowMonthFirstDay() //本月第一天
- companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewMonthDataNum(nowMonthFirstDay, productId, source, 6)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- case "time_interval":
- if startDate == `` || endDate == `` {
- br.Msg = "开始日期或结束日期不能为空"
- br.ErrMsg = "开始日期或结束日期不能为空,Err:" + err.Error()
- return
- }
- companyUnusualRenewDataMapList, _, err = statistic_report.GetUnusualRenewTimeIntervalData(productId, source, startDate, endDate)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- }
- groupId := 0
- if utils.RunMode == "release" {
- groupId = 37
- } else {
- groupId = 61
- }
- subAdmins, err := system.GetAdminByGroupId(groupId)
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取销售失败"
- br.ErrMsg = "获取销售失败,Err:" + err.Error()
- return
- }
- //数据处理
- list := make([]statistic_report.GroupUnusualRenewRecord, 0)
- summaryList := make([]statistic_report.SummaryUnusualRenewRecordNum, 0)
- companyRenewRecordResp := statistic_report.CompanyUnusualRenewRecordResp{
- List: list,
- SummaryList: summaryList,
- }
- unusualRenewTotal := make(map[int]int)
- adminDataUnusualRenewTotal := make(map[int]int)
- // 每日期组数据的汇总客户id
- companyIdIndexMap := make(map[int][]string)
- for k, v := range subAdmins {
- tmpGroupCompanyRenewRecordNumList := make([]statistic_report.CompanyUnusualRenewRecordNum, 0)
- for index, adminData := range companyUnusualRenewDataMapList {
- tmpGroupCompanyRenewRecordNumList = append(tmpGroupCompanyRenewRecordNumList, statistic_report.CompanyUnusualRenewRecordNum{
- UnusualRenewNum: adminData.UnusualRenewMap[v.AdminId],
- UnusualRenewIds: adminData.UnusualRenewIdMap[v.AdminId],
- StartDate: adminData.StartDate,
- EndDate: adminData.EndDate,
- })
- unusualRenewTotal[index] = unusualRenewTotal[index] + adminData.UnusualRenewMap[v.AdminId]
- if adminData.UnusualRenewIdMap[v.AdminId] != `` {
- tmpCompanyIdList, ok := companyIdIndexMap[index]
- if !ok {
- tmpCompanyIdList = make([]string, 0)
- }
- companyIdIndexMap[index] = append(tmpCompanyIdList, adminData.UnusualRenewIdMap[v.AdminId])
- adminDataUnusualRenewTotal[index] = adminData.FormalCompanyTotal
- }
- if k == 0 {
- /*unusualRate := ``
- if adminData.UnusualRenewTotal > 0 && adminData.FormalCompanyTotal > 0 {
- unusualRate = decimal.NewFromInt(int64(adminData.UnusualRenewTotal)*100).Div(decimal.NewFromInt(int64(adminData.FormalCompanyTotal))).Round(2).String() + `%`
- }*/
- summaryList = append(summaryList, statistic_report.SummaryUnusualRenewRecordNum{
- UnusualRenewNum: 0,
- UnusualRate: "0",
- })
- }
- }
- list = append(list, statistic_report.GroupUnusualRenewRecord{
- SellerId: v.AdminId,
- SellerName: v.RealName,
- CompanyRenewRecordNumList: tmpGroupCompanyRenewRecordNumList,
- })
- }
- // 汇总数据
- for index, _ := range summaryList {
- totalSum, ok1 := unusualRenewTotal[index]
- if ok1 {
- summaryList[index].UnusualRenewNum = totalSum
- unusualRate := ``
- formalCompanyTotal, ok2 := adminDataUnusualRenewTotal[index]
- if ok2 {
- if totalSum > 0 && formalCompanyTotal > 0 {
- unusualRate = decimal.NewFromInt(int64(totalSum)*100).Div(decimal.NewFromInt(int64(formalCompanyTotal))).Round(2).String() + `%`
- summaryList[index].UnusualRate = unusualRate
- }
- }
- }
- tmpCompanyIdList, ok := companyIdIndexMap[index]
- if ok {
- summaryList[index].UnusualRenewIds = strings.Join(tmpCompanyIdList, ",")
- }
- }
- companyRenewRecordResp.List = list
- companyRenewRecordResp.SummaryList = summaryList
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = companyRenewRecordResp
- }
- // UnusualRenewCompanyList
- // @Title 获取未续约的公司合同列表
- // @Description 获取未续约的公司合同列表
- // @Param ProductId query int false "套餐类型: 1-FICC(默认); 2-权益"
- // @Param Source query int true "类型,枚举值,1:续约异常客户;2:续约正常客户;3:超时续约客户;4:合同到期后一个月未续约客户;5:合同到期未续约客户;6:合同到期前一个月还未续约的客户;7:合同到期前两个月还未续约客户;8:合同到期前3个月还未续约客户;9:合同到期前4个月还未续约客户"
- // @Param StartDate query string true "开始日期,格式:2022-04"
- // @Param EndDate query string true "结束日期,格式:2022-04"
- // @Success 200 {object} company.GetUnusualRenewListGroupMonthResp
- // @router /report/unusual_renew_company/chart [get]
- func (this *StatisticReportController) UnusualRenewCompanyList() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- // 起始日期
- // 截止日期
- productId, _ := this.GetInt("ProductId", 1)
- startDate := this.GetString("StartDate")
- endDate := this.GetString("EndDate")
- source, _ := this.GetInt("Source", 1)
- if startDate == `` || endDate == `` {
- br.Msg = "开始日期或结束日期不能为空"
- return
- }
- allList := make([]*company.GetUnusualRenewListGroupMonth, 0)
- resp := new(company.GetUnusualRenewListGroupMonthResp)
- resp.List = allList
- newStartDate := startDate + "-01"
- newEndDate := endDate + "-01"
- startDateTimer, _ := time.ParseInLocation(utils.FormatDate, newStartDate, time.Local)
- endDateTimer, _ := time.ParseInLocation(utils.FormatDate, newEndDate, time.Local)
- endDateTimer = endDateTimer.AddDate(0, 1, 0).Add(-1 * time.Second) //本月最后一天
- // 按月分组
- monthMap := make(map[string]int)
- monthCompanyMap := make(map[string]struct{})
- monthList := make([]string, 0)
- tmpDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, startDate, time.Local)
- tmpEndDate, _ := time.ParseInLocation(utils.FormatYearMonthDate, endDate, time.Local)
- for tmpDate.Before(tmpEndDate) || tmpDate == tmpEndDate {
- monthMap[tmpDate.Format(utils.FormatYearMonthDate)] = 0
- monthList = append(monthList, tmpDate.Format(utils.FormatYearMonthDate))
- tmpDate = tmpDate.AddDate(0, 1, 0)
- }
- // 只查询ficc销售下的客户
- roleTypeCode := "('ficc_seller','ficc_group','ficc_team')"
- researcherList, err := roadshow.GetSellerList(roleTypeCode, "")
- if err != nil {
- return
- }
- if err != nil && err.Error() != utils.ErrNoRow() {
- br.Msg = "获取销售失败"
- br.ErrMsg = "获取销售失败,Err:" + err.Error()
- return
- }
- if len(researcherList) == 0 {
- resp = &company.GetUnusualRenewListGroupMonthResp{
- List: allList,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- return
- }
- subAdminIds := make([]string, 0)
- for _, v := range researcherList {
- subAdminIds = append(subAdminIds, strconv.Itoa(v.AdminId))
- }
- sellerIds := strings.Join(subAdminIds, ",")
- list, err := company.GetUnusualRenewList(startDateTimer, endDateTimer, productId, source, sellerIds)
- if err != nil {
- br.Msg = "数据异常"
- br.ErrMsg = "数据异常,Err:" + err.Error()
- return
- }
- if len(list) > 0 {
- for _, v := range list {
- t := v.ModifyTime.Format(utils.FormatYearMonthDate)
- name := fmt.Sprintf("%s_%d", t, v.CompanyId)
- if _, ok := monthCompanyMap[name]; !ok {
- if num, ok1 := monthMap[t]; ok1 {
- monthMap[t] = num + 1
- }
- monthCompanyMap[name] = struct{}{}
- }
- }
- }
- for _, v := range monthList {
- n, _ := monthMap[v]
- tmp := &company.GetUnusualRenewListGroupMonth{
- Date: v,
- CompanyNum: n,
- }
- allList = append(allList, tmp)
- }
- resp = &company.GetUnusualRenewListGroupMonthResp{
- List: allList,
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- // StackCompanyListRai
- // @Title 获取权益存量客户数据列表
- // @Description 获取权益存量客户数据列表接口
- // @Param PageSize query int true "每页数据条数"
- // @Param CurrentIndex query int true "当前页页码,从1开始"
- // @Param Keyword query string true "客户名称"
- // @Param AdminId query string true "销售id,多个用英文逗号隔开,空字符串为全部"
- // @Param RegionType query string false "所属区域:传空字符串或者不传为全部,'国内','海外'"
- // @Param DataType query string false "报表类型,枚举值:`新签客户`,`续约客户`,`未续约客户`"
- // @Param TryOutType query string false " '试用', '非试用' 非试用即为冻结/流失"
- // @Param IsExport query bool false "是否导出excel,默认是false"
- // @Param CompanyAscribeId query int false "归因ID"
- // @Success 200 {object} response.StackCompanyListResp
- // @router /stack_company_list_rai [get]
- func (this *StatisticReportController) StackCompanyListRai() {
- br := new(models.BaseResponse).Init()
- defer func() {
- this.Data["json"] = br
- this.ServeJSON()
- }()
- sysUser := this.SysUser
- if sysUser == nil {
- br.Msg = "请登录"
- br.ErrMsg = "请登录,SysUser Is Empty"
- br.Ret = 408
- return
- }
- pageSize, _ := this.GetInt("PageSize")
- currentIndex, _ := this.GetInt("CurrentIndex")
- //是否导出报表
- isExport, _ := this.GetBool("IsExport")
- if isExport {
- pageSize = 10000
- currentIndex = 1
- }
- adminId := this.GetString("AdminId")
- regionType := this.GetString("RegionType")
- companyType := this.GetString("CompanyType")
- dataType := this.GetString("DataType")
- tryOutType := this.GetString("TryOutType")
- keyword := this.GetString("Keyword")
- companyAscribeId, _ := this.GetInt("CompanyAscribeId", -1) // CRM 13.9
- var resp response.StackCompanyListResp
- //历史统计数据
- //获取实时统计数据(今天数据)
- tmpResp, err := getTodayStackCompanyListV2Rai(sysUser, currentIndex, pageSize, companyAscribeId, adminId, regionType, companyType, dataType, tryOutType, keyword)
- if err != nil {
- br.Msg = "获取失败"
- br.ErrMsg = "获取失败,Err:" + err.Error()
- return
- }
- resp = tmpResp
- //导出excel
- if isExport {
- StackCompanyListExport(this, dataType, resp, br)
- return
- }
- br.Ret = 200
- br.Success = true
- br.Msg = "获取成功"
- br.Data = resp
- }
- func getTodayStackCompanyListV2Rai(sysUser *system.Admin, currentIndex, pageSize, companyAscribeId int, adminId, regionType, companyType, dataType, tryOutType, keyword string) (returnData response.StackCompanyListResp, err error) {
- var startSize int
- if pageSize <= 0 {
- pageSize = utils.PageSize20
- }
- if currentIndex <= 0 {
- currentIndex = 1
- }
- startSize = utils.StartIndex(currentIndex, pageSize)
- var condition, listCondition string
- var pars, listPars []interface{}
- today := utils.GetToday(utils.FormatDate)
- //条件
- var conditionAscribRai string // 处理权益未续约客户检索列表SQL查询条件
- var parsAscribeRai []interface{}
- //归因ID CRM 13.9
- if companyAscribeId > 0 {
- var conditionAscribe string
- var parsAscribe []interface{}
- conditionAscribe = " AND company_ascribe_id = ? "
- parsAscribe = append(parsAscribe, companyAscribeId)
- companyNoRenewedAscribeList, e := company.GetCompanyNoRenewedAscribeList(conditionAscribe, parsAscribe, 0, 0)
- if e != nil && e.Error() != utils.ErrNoRow() {
- err = errors.New("GetCompanyNoRenewedAscribeList" + e.Error())
- return
- }
- var companyIds []int
- if len(companyNoRenewedAscribeList) == 0 {
- companyIds = append(companyIds, 0) // 给一个不存在的ID
- } else {
- for _, v := range companyNoRenewedAscribeList {
- companyIds = append(companyIds, v.CompanyId)
- }
- }
- conditionAscribRai += ` AND c.company_id IN (` + utils.GetOrmInReplace(len(companyIds)) + `)`
- parsAscribeRai = append(parsAscribeRai, companyIds)
- }
- if adminId != "" {
- //condition += ` AND c.seller_id in (` + adminId + `) `
- //pars = append(pars, adminId)
- } else {
- //根据当前角色来获取查询条件
- condition, pars = getQueryParams(condition, pars, sysUser, "c.")
- }
- if regionType != "" {
- condition += ` AND b.region_type = ? `
- pars = append(pars, regionType)
- }
- //关键字搜索
- if keyword != "" {
- condition += ` and b.company_name like "%` + keyword + `%" `
- }
- condition += ` AND a.product_id = ? `
- pars = append(pars, 2)
- var dataTotal, newCompanyTotal, renewalCompanyTotal, notRenewalCompanyTotal int
- var notRenewalTryOut, notRenewalNotTryOut int
- var list []*models.IncrementalList
- //新签客户数
- {
- condition1 := condition
- if adminId != "" {
- condition1 += ` AND a.seller_id_init in (` + adminId + `) `
- }
- pars1 := pars
- //condition1 += ` AND c.status = "正式" `
- condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars1 = append(pars1, today, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "新签合同")
- total, countErr := models.GetIncrementalNewCompanyCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- newCompanyTotal = total
- if dataType == "新签客户" {
- //页表页数据总和
- total, countErr = models.GetTodayStackCompanyProductCount(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //续约客户数
- {
- condition1 := condition
- if adminId != "" {
- condition1 += ` AND a.seller_id_init in (` + adminId + `) `
- }
- pars1 := pars
- //condition1 += ` AND c.status = "正式" `
- condition1 += ` AND a.start_date <= ? AND a.end_date >= ? `
- pars1 = append(pars1, today, today)
- condition1 += ` AND a.contract_type = ? `
- pars1 = append(pars1, "续约合同")
- //额外条件(续约合同的起始日期包含在所选时间段内且不包含在新签合同存续期内的客户)
- pars1 = append(pars1, today)
- total, countErr := models.GetIncrementalNewCompanyCountV2(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- renewalCompanyTotal = total
- if dataType == "续约客户" {
- //页表页数据总和
- total, countErr = models.GetTodayStackCompanyProductCountV2(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- }
- }
- //未续约客户数
- {
- if adminId != "" {
- condition += ` AND c.seller_id in (` + adminId + `) `
- }
- condition1 := condition
- pars1 := pars
- condition1 += ` AND c.status not in ("永续","正式") AND a.create_time <= ? `
- pars1 = append(pars1, time.Now().Format(utils.FormatDateTime))
- condition1 += ` AND a.operation = 'try_out' `
- total, countErr := models.GetIncrementalCompanyCountByOperationRecord(condition1, pars1)
- if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- err = countErr
- return
- }
- notRenewalCompanyTotal = total
- condition1 += conditionAscribRai
- pars1 = append(pars1, parsAscribeRai)
- if dataType == "未续约客户" {
- //页表页数据总和
- //统计数据
- for _, v := range []string{"试用", "非试用"} {
- totalCondition1 := condition1
- totalPars1 := pars1
- var tmpTotal int
- if v == "试用" {
- totalCondition1 += ` AND c.status = "试用" `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil {
- return
- }
- notRenewalTryOut = tmpTotal
- } else if v == "非试用" {
- totalCondition1 += ` AND c.status IN ("冻结","流失") `
- tmpTotal, err = models.GetIncrementalCompanyProductCountByOperationRecord(totalCondition1, totalPars1)
- if err != nil && err.Error() != utils.ErrNoRow() {
- return
- }
- notRenewalNotTryOut = tmpTotal
- }
- }
- //列表数据数量
- if tryOutType == "试用" {
- condition1 += ` AND c.status = "试用" `
- total = notRenewalTryOut
- } else if tryOutType == "非试用" {
- condition1 += ` AND c.status IN ("冻结","流失") `
- total = notRenewalNotTryOut
- }
- //total, countErr := models.GetIncrementalCompanyProductCountByOperationRecord(condition1, pars1)
- //if countErr != nil && countErr.Error() != utils.ErrNoRow() {
- // err = countErr
- // return
- //}
- dataTotal = total
- listCondition = condition1
- listPars = pars1
- if tryOutType == "试用" {
- listCondition += ` AND c.status = "试用" `
- } else if tryOutType == "非试用" {
- listCondition += ` AND c.status IN ("冻结","流失") `
- }
- tmpList, countErr := models.GetIncrementalCompanyListByOperationRecord(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- for i := 0; i < len(tmpList); i++ {
- endDateTime, parseErr := time.Parse(utils.FormatDateTime, tmpList[i].CreateTime)
- if parseErr != nil {
- err = parseErr
- return
- }
- tmpList[i].EndDate = endDateTime.Format(utils.FormatDate)
- }
- list = tmpList
- }
- }
- switch dataType {
- case "新签客户":
- tmpList, countErr := models.GetTodayStackCompanyList(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- list = tmpList
- case "续约客户":
- tmpList, countErr := models.GetTodayStackCompanyListV2(listCondition, listPars, startSize, pageSize)
- if countErr != nil {
- err = countErr
- return
- }
- list = tmpList
- }
- if dataType == "续约客户" {
- var ids []string
- oldCompanyMap := make(map[int]*models.IncrementalList)
- oldMoneyMap := make(map[int]float64)
- countMap := make(map[int]int)
- for _, item := range list {
- ids = append(ids, strconv.Itoa(item.CompanyId))
- }
- if len(ids) > 0 {
- idStr := strings.Join(ids, ",")
- lists, contractErr := models.GetLastContractMoney(idStr)
- if contractErr != nil {
- err = contractErr
- return
- }
- for _, item := range lists {
- _, countOk := countMap[item.CompanyId]
- _, ok := oldCompanyMap[item.CompanyId]
- if !ok {
- oldCompanyMap[item.CompanyId] = item
- oldMoneyMap[item.CompanyId] = item.Money
- } else if !countOk {
- countMap[item.CompanyId] = 1
- oldCompanyMap[item.CompanyId] = item
- }
- }
- //给list赋值
- for _, item := range list {
- if item.ProductName == "权益" {
- oldMoney, _ := oldMoneyMap[item.CompanyId]
- lastContract, _ := oldCompanyMap[item.CompanyId]
- if oldMoney > lastContract.Money {
- item.PackageDifference = "增加套餐"
- } else if oldMoney < lastContract.Money {
- item.PackageDifference = "减少套餐"
- } else {
- item.PackageDifference = "维持套餐"
- }
- }
- }
- }
- }
- var ascribecompanyIds []int
- for _, item := range list {
- ascribecompanyIds = append(ascribecompanyIds, item.CompanyId)
- }
- //归因标签
- mapGetCompanyAscribeContent, mapContent := services.GetCompanyAscribeContentMap(ascribecompanyIds)
- mapNoRenewedNote := services.GetCompanyNoRenewedNoteMap(ascribecompanyIds)
- for _, item := range list {
- item.AscribeContent = mapGetCompanyAscribeContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.Content = mapContent[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- item.IsShowNoRenewedNote = mapNoRenewedNote[fmt.Sprint("CID_", item.CompanyId, "PID_", item.ProductId)]
- }
- listLen := len(list)
- var companyContractIds []int
- for i := 0; i < listLen; i++ {
- item := list[i]
- //剩余可用天数
- expireDay := "0"
- endDateTime, _ := time.Parse(utils.FormatDate, item.EndDate)
- var sub time.Duration
- if dataType != "未续约客户" {
- endDateTime = endDateTime.AddDate(0, 0, 1)
- sub = endDateTime.Sub(time.Now())
- //if sub < 0 {
- // sub = 0
- //}
- } else {
- sub = time.Now().Sub(endDateTime)
- }
- expireDay = fmt.Sprintf("%v", int(sub.Hours()/24))
- list[i].ExpireDay = expireDay
- companyContractIds = append(companyContractIds, item.CompanyContractId)
- }
- //合并合同所对应的权限
- mappermissionName, err := cygxService.GetCompanyContractPermissionNameMapById(companyContractIds)
- if err != nil {
- return
- }
- for _, v := range list {
- v.PermissionName = mappermissionName[v.CompanyContractId]
- }
- var stackCompanyStatisticList []*models.StackCompanyStatisticList
- for _, v := range list {
- stackCompanyStatistic := models.StackCompanyStatisticList{
- Type: dataType,
- CompanyId: v.CompanyId,
- CompanyName: v.CompanyName,
- ProductId: v.ProductId,
- ProductName: v.ProductName,
- ContractNum: v.Count,
- SellerId: v.SellerId,
- SellerName: v.SellerNameInit,
- ShareSeller: v.ShareSellerInit,
- Date: today,
- StartDate: v.StartDate,
- EndDate: v.EndDate,
- RegionType: v.RegionType,
- //CreateTime :v.CreateTime,
- CreateTimeStr: v.CreateTime,
- ExpireDay: v.ExpireDay,
- RenewalReason: v.RenewalReason,
- RenewalTodo: v.RenewalTodo,
- Status: v.Status,
- PackageDifference: v.PackageDifference,
- AscribeContent: v.AscribeContent,
- IsShowNoRenewedNote: v.IsShowNoRenewedNote,
- Content: v.Content,
- PermissionName: mappermissionName[v.CompanyContractId],
- Money: v.Money,
- }
- stackCompanyStatisticList = append(stackCompanyStatisticList, &stackCompanyStatistic)
- }
- page := paging.GetPaging(currentIndex, pageSize, dataTotal)
- resp := response.StackCompanyListResp{
- Paging: page,
- List: stackCompanyStatisticList,
- NewCompanyTotal: newCompanyTotal,
- RenewalCompanyTotal: renewalCompanyTotal,
- NotRenewalCompanyTotal: notRenewalCompanyTotal,
- NotRenewalTryOut: notRenewalTryOut,
- NotRenewalNotTryOut: notRenewalNotTryOut,
- }
- return resp, err
- }
|