statistic_report.go 215 KB

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