statistic_report.go 234 KB

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