statistic_report.go 243 KB

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