statistic_report.go 229 KB

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