StatisticsController.cs 396 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140
  1. using Aspose.Cells;
  2. using Aspose.Words.Tables;
  3. using EyeSoft.Collections.Generic;
  4. using FluentValidation;
  5. using Google.Protobuf.WellKnownTypes;
  6. using Microsoft.AspNetCore.Mvc.ViewEngines;
  7. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  8. using Microsoft.Extensions.Hosting;
  9. using MySqlX.XDevAPI.Relational;
  10. using NetUV.Core.Handles;
  11. using NodaTime;
  12. using NPOI.POIFS.Properties;
  13. using NPOI.SS.Formula.Functions;
  14. using NPOI.SS.Formula.PTG;
  15. using NPOI.XSSF.Streaming.Values;
  16. using OASystem.API.OAMethodLib;
  17. using OASystem.API.OAMethodLib.JuHeAPI;
  18. using OASystem.Domain.AesEncryption;
  19. using OASystem.Domain.Dtos.Statistics;
  20. using OASystem.Domain.Entities.Customer;
  21. using OASystem.Domain.Entities.Financial;
  22. using OASystem.Domain.Entities.Groups;
  23. using OASystem.Domain.ViewModels.Financial;
  24. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  25. using OASystem.Domain.ViewModels.QiYeWeChat;
  26. using OASystem.Domain.ViewModels.Statistics;
  27. using OASystem.Infrastructure.Repositories.Groups;
  28. using System;
  29. using System.Data;
  30. using TencentCloud.Ocr.V20181119.Models;
  31. using static OASystem.API.OAMethodLib.GeneralMethod;
  32. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  33. namespace OASystem.API.Controllers
  34. {
  35. /// <summary>
  36. /// 统计模块
  37. /// </summary>
  38. [Route("api/[controller]")]
  39. [ApiController]
  40. public class StatisticsController : ControllerBase
  41. {
  42. private readonly int _decimalPlaces;
  43. private readonly IConfiguration _config;
  44. private readonly IMapper _mapper;
  45. private readonly SqlSugarClient _sqlSugar;
  46. private readonly DelegationInfoRepository _groupRep;
  47. private readonly SetDataRepository _setDataRep;
  48. private readonly TeamRateRepository _teamRateRep;
  49. private readonly VisitingClientsRepository _visitingClientsRep;
  50. private readonly IJuHeApiService _juHeApiService;
  51. /// <summary>
  52. /// Init
  53. /// </summary>
  54. /// <param name="mapper"></param>
  55. /// <param name="config"></param>
  56. /// <param name="sqlSugar"></param>
  57. /// <param name="groupRep"></param>
  58. /// <param name="setDataRep"></param>
  59. /// <param name="teamRate"></param>
  60. /// <param name="visitingClientsRep"></param>
  61. /// <param name="juHeApiService"></param>
  62. public StatisticsController(
  63. IMapper mapper,
  64. IConfiguration config,
  65. SqlSugarClient sqlSugar,
  66. DelegationInfoRepository groupRep,
  67. SetDataRepository setDataRep,
  68. TeamRateRepository teamRate,
  69. VisitingClientsRepository visitingClientsRep,
  70. IJuHeApiService juHeApiService
  71. )
  72. {
  73. _mapper = mapper;
  74. _config = config;
  75. _groupRep = groupRep;
  76. _setDataRep = setDataRep;
  77. _sqlSugar = sqlSugar;
  78. _teamRateRep = teamRate;
  79. _visitingClientsRep = visitingClientsRep;
  80. _juHeApiService = juHeApiService;
  81. }
  82. #region 团组报表
  83. /// <summary>
  84. /// 团组报表
  85. /// Items
  86. /// </summary>
  87. /// <param name="_dto">团组列表请求dto</param>
  88. /// <returns></returns>
  89. [HttpPost("PostGroupStatementItems")]
  90. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  91. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  92. {
  93. #region 参数验证
  94. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  95. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  96. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  97. #region 页面操作权限验证
  98. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  99. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  100. #endregion
  101. #endregion
  102. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  103. {
  104. string sqlWhere = string.Empty;
  105. if (_dto.IsSure == 0) //未完成
  106. {
  107. sqlWhere += string.Format(@" And IsSure = 0");
  108. }
  109. else if (_dto.IsSure == 1) //已完成
  110. {
  111. sqlWhere += string.Format(@" And IsSure = 1");
  112. }
  113. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  114. {
  115. string tj = _dto.SearchCriteria;
  116. sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
  117. tj, tj, tj, tj, tj);
  118. }
  119. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  120. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  121. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  122. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  123. pr.LastCollectionTime
  124. From Grp_DelegationInfo gdi
  125. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  126. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  127. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  128. Left Join (
  129. SELECT Diid, MAX(CreateTime) LastCollectionTime
  130. FROM Fin_ProceedsReceived
  131. Where IsDel = 0
  132. GROUP BY Diid
  133. ) pr On gdi.Id = pr.Diid
  134. Where gdi.IsDel = 0 {0} ", sqlWhere);
  135. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  136. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  137. var _view = new
  138. {
  139. PageFuncAuth = pageFunAuthView,
  140. Data = _DelegationList
  141. };
  142. return Ok(JsonView(true, "查询成功!", _view, total));
  143. }
  144. else
  145. {
  146. return Ok(JsonView(false, "查询失败"));
  147. }
  148. }
  149. /// <summary>
  150. /// 团组报表
  151. /// Details
  152. /// </summary>
  153. /// <param name="_dto">团组列表请求dto</param>
  154. /// <returns></returns>
  155. [HttpPost("PostGroupStatementDetails")]
  156. //[JsonConverter(typeof(DecimalConverter), 2)]
  157. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  158. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  159. {
  160. /*
  161. * 团组报表计算方式
  162. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  163. * 应收金额 = 应收表.Sum()
  164. * 已收金额 = 已收表.Sum()
  165. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  166. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  167. *
  168. */
  169. #region 参数验证
  170. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  171. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  172. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  173. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  174. #region 页面操作权限验证
  175. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  176. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  177. #endregion
  178. #endregion
  179. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  180. {
  181. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  182. #region 费用类型 币种,转账,客户信息
  183. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  184. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  185. .Where(it => it.IsDel == 0)
  186. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  187. .ToListAsync();
  188. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  189. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  190. var visitDate = groupInfo.VisitDate;
  191. #endregion
  192. #region 团组收入
  193. GroupIncomeView _giView = new GroupIncomeView();
  194. /*
  195. * 应收报表
  196. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  197. */
  198. decimal frTotalAmount = 0.00M;//应收总金额
  199. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  200. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  201. From Fin_ForeignReceivables fr
  202. Left Join Sys_SetData sd On fr.Currency = sd.Id
  203. Left Join Sys_Users u On fr.Auditor = u.Id
  204. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  205. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  206. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  207. //if (_frViews1.Count > 0)
  208. //{
  209. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  210. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  211. //}
  212. _frViews.ForEach(x =>
  213. {
  214. string namePrefix = string.Empty;
  215. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  216. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  217. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  218. x.PriceName = $"{namePrefix}{x.PriceName}";
  219. });
  220. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  221. _giView.Receivables = _frViews;
  222. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  223. /*
  224. * 已收报表
  225. */
  226. decimal prTotalAmount = 0.00M;//已收总金额
  227. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  228. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  229. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  230. From Fin_ProceedsReceived pr
  231. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  232. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  233. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  234. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  235. prTotalAmount = _prViews.Sum(it => it.Price);
  236. _giView.ProceedsReceivedViews = _prViews;
  237. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  238. /*
  239. * 超支费用
  240. */
  241. decimal exTotalAmount = 0.00M;
  242. // string ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,(gec.PriceSum * gec.Coefficient) As PayMoney,sd1.Name As PaymentCurrency,
  243. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  244. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  245. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  246. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  247. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  248. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  249. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  250. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  251. //Where ccp.IsDel = 0 And ccp.CTable = 1015 {1} And ccp.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1 And ccp.IsPay = 1 " : " ");
  252. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  253. // #region 超支费用 - 模拟数据
  254. // //if (_ExtraCostsViews.Count < 1)
  255. // //{
  256. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  257. // // {
  258. // // GECId = 0,
  259. // // GECDiId = 2334,
  260. // // PriceName = "模拟数据-超支费用名称",
  261. // // PayMoney = 1000.00M,
  262. // // PaymentCurrency = "CNY",
  263. // // DayRate = 1.0000M,
  264. // // CNYPrice = 1000.00M,
  265. // // Payee = "模拟数据-超支费用收款方",
  266. // // OrbitalPrivateTransfer = 1,
  267. // // PayWay = "刷卡",
  268. // // CardType = "招行卡",
  269. // // IsPay = 1,
  270. // // Applicant = "刘华举"
  271. // // });
  272. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  273. // // {
  274. // // GECId = 0,
  275. // // GECDiId = 2334,
  276. // // PriceName = "模拟数据-超支费用名称",
  277. // // PayMoney = 1000.00M,
  278. // // PaymentCurrency = "CNY",
  279. // // DayRate = 1.0000M,
  280. // // CNYPrice = 1000.00M,
  281. // // Payee = "模拟数据-超支费用收款方",
  282. // // OrbitalPrivateTransfer = 1,
  283. // // PayWay = "刷卡",
  284. // // CardType = "招行卡",
  285. // // IsPay = 1,
  286. // // Applicant = "刘华举"
  287. // // });
  288. // //}
  289. // #endregion
  290. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  291. // _giView.ExtraCostsViews = _ExtraCostsViews;
  292. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  293. /*
  294. * 收款退还
  295. */
  296. decimal promTotalAmount = 0.00M;// 收款退还总金额
  297. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  298. //删除了 And prom.PriceType = 1
  299. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  300. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  301. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  302. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  303. From Fin_PaymentRefundAndOtherMoney prom
  304. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  305. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  306. Where prom.IsDel = 0
  307. And prom.PayType = 1
  308. And ccp.CTable = 285
  309. {1}
  310. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  311. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  312. foreach (var ropItem in _promDatas)
  313. {
  314. string thisCueencyCode = "Unknown";
  315. string thisCueencyName = "Unknown";
  316. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  317. if (currency != null)
  318. {
  319. thisCueencyCode = currency.Name;
  320. thisCueencyName = currency.Remark;
  321. }
  322. string orbitalPrivateTransferStr = "Unknown";
  323. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  324. if (orbitalPrivateTransfer != null)
  325. {
  326. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  327. }
  328. string payStr = "Unknown";
  329. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  330. if (pay != null)
  331. {
  332. payStr = pay.Name;
  333. }
  334. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  335. {
  336. Id = ropItem.Id,
  337. DiId = ropItem.DIId,
  338. PriceName = ropItem.PrPriceName,
  339. PayCurrencyCode = thisCueencyCode,
  340. PayCurrencyName = thisCueencyName,
  341. Price = ropItem.PrPrice,
  342. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  343. ThisRate = ropItem.DayRate,
  344. Payee = ropItem.Payee,
  345. PayTime = ropItem.AuditGMDate,
  346. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  347. PayType = payStr,
  348. IsPay = ropItem.IsPay,
  349. Applicant = ropItem.Appliction
  350. };
  351. _promView.Add(gsd_PaymentRefund);
  352. }
  353. #region 收款退还 - 模拟数据
  354. //if (_promView.Count < 1)
  355. //{
  356. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  357. // {
  358. // Id = 0,
  359. // DiId = 2334,
  360. // PriceName = "模拟数据-费用名称",
  361. // PayCurrencyCode = "CNY",
  362. // PayCurrencyName = "人民币",
  363. // Price = 1000.00M,
  364. // CNYPrice = 1000.00M,
  365. // ThisRate = 1.00M,
  366. // Payee = "模拟数据-收款方",
  367. // PayTime = "2023-01-01 15:20:01",
  368. // OrbitalPrivateTransfer = 1,
  369. // PayType = "刷卡",
  370. // IsPay = 1,
  371. // Applicant = "刘华举"
  372. // });
  373. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  374. // {
  375. // Id = 0,
  376. // DiId = 2334,
  377. // PriceName = "模拟数据-费用名称",
  378. // PayCurrencyCode = "CNY",
  379. // PayCurrencyName = "人民币",
  380. // Price = 1000.00M,
  381. // CNYPrice = 1000.00M,
  382. // ThisRate = 1.00M,
  383. // Payee = "模拟数据-收款方",
  384. // PayTime = "2023-01-01 15:20:01",
  385. // OrbitalPrivateTransfer = 1,
  386. // PayType = "刷卡",
  387. // IsPay = 1,
  388. // Applicant = "刘华举"
  389. // });
  390. //}
  391. #endregion
  392. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  393. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  394. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  395. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  396. _view.GroupIncome = _giView;
  397. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  398. #endregion
  399. #region 团组支出
  400. GroupExpenditureView _geView = new GroupExpenditureView();
  401. #region 酒店预定费用
  402. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  403. //ccp.RMBPrice As CNYPrice
  404. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  405. string hotelFeeSql = string.Format(@"
  406. SELECT
  407. hr.Id AS HrId,
  408. hr.DiId AS HrDiId,
  409. hr.City,
  410. hr.HotelName,
  411. hr.CheckInDate,
  412. hr.CheckOutDate,
  413. hr.CardPrice AS RoomPrice,
  414. sd1.Name AS PaymentCurrency,
  415. hr.SingleRoomPrice,
  416. hr.SingleRoomCount,
  417. hr.DoubleRoomPrice,
  418. hr.DoubleRoomCount,
  419. hr.SuiteRoomPrice,
  420. hr.SuiteRoomCount,
  421. hr.OtherRoomPrice,
  422. hr.OtherRoomCount,
  423. hr.BreakfastPrice,
  424. sd4.Name AS BreakfastCurrency,
  425. hr.Isoppay,
  426. hr.GovernmentRent,
  427. sd5.Name AS GovernmentRentCurrency,
  428. hr.CityTax,
  429. sd6.Name AS CityTaxCurrency,
  430. ccp.PayMoney,
  431. (
  432. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  433. ) AS CNYPrice,
  434. ccp.PayPercentage,
  435. ccp.DayRate,
  436. ccp.Payee,
  437. ccp.OrbitalPrivateTransfer,
  438. sd2.Name AS PayWay,
  439. sd3.Name AS CardType,
  440. ccp.IsPay,
  441. u.CnName AS Applicant
  442. FROM
  443. Grp_HotelReservations hr
  444. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  445. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  446. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  447. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  448. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  449. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  450. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  451. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  452. WHERE
  453. hr.IsDel = 0
  454. AND ccp.IsDel = 0
  455. AND ccp.CTable = 76 {1}
  456. AND ccp.PayMoney <> 0
  457. AND hr.DiId = {0}
  458. ORDER BY
  459. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  460. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  461. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  462. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  463. decimal HotelCNYTotalPrice = 0.00M;
  464. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  465. foreach (var item in groupHotelFeeViews)
  466. {
  467. if (groupHotelContentFeeViews.Count > 0)
  468. {
  469. string paymentStr = string.Empty;
  470. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  471. item.RoomPrice = roomData?.Price ?? 0.00M;
  472. if (item.RoomPrice != 0)
  473. {
  474. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  475. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  476. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  477. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  478. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  479. 收款方:{roomData?.Payee}<br/>
  480. 费用标识:{feeMark1} <br/>
  481. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  482. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  483. 是否由地接支付:{isFeeMark1} <br/>";
  484. }
  485. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  486. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  487. if (item.BreakfastPrice != 0)
  488. {
  489. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  490. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  491. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  492. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  493. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  494. 收款方:{breakfastData?.Payee}<br/>
  495. 费用标识:{feeMark2} <br/>
  496. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  497. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  498. 是否由地接支付:{isFeeMark2} <br/>";
  499. }
  500. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  501. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  502. if (item.GovernmentRent != 0)
  503. {
  504. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  505. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  506. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  507. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  508. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  509. 收款方:{landTaxData?.Payee}<br/>
  510. 费用标识:{feeMark3} <br/>
  511. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  512. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  513. 是否由地接支付:{isFeeMark3} <br/>";
  514. }
  515. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  516. item.CityTax = cityTaxData?.Price ?? 0.00M;
  517. if (item.CityTax != 0)
  518. {
  519. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  520. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  521. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  522. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  523. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  524. 收款方:{cityTaxData?.Payee}<br/>
  525. 费用标识:{feeMark4} <br/>
  526. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  527. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  528. 是否由地接支付:{isFeeMark4} <br/>";
  529. }
  530. if (!string.IsNullOrEmpty(paymentStr))
  531. {
  532. item.IsPay = 2;
  533. item.PayTips = paymentStr;
  534. }
  535. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  536. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  537. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  538. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  539. }
  540. else
  541. {
  542. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  543. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  544. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  545. (item.OtherRoomCount * item.OtherRoomPrice);
  546. //item.RoomPrice = item.CardPrice;
  547. item.RoomPriceCurrency = item.PaymentCurrency;
  548. }
  549. HotelCNYTotalPrice += item.CNYPrice;
  550. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  551. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  552. }
  553. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  554. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  555. #endregion
  556. #region 地接费用
  557. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  558. string CTGGRFeeSql = string.Empty;
  559. if (visitDate > Convert.ToDateTime("2024-04-17"))
  560. {
  561. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  562. sd2.name As PaymentCurrency,ccp.PayPercentage,
  563. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  564. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  565. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  566. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  567. From Grp_CarTouristGuideGroundReservations ctggr
  568. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  569. cggrc.DatePrice,cggrc.PriceContent
  570. From Grp_CarTouristGuideGroundReservationsContent cggrc
  571. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  572. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  573. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  574. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  575. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  576. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  577. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  578. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  579. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  580. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  581. }
  582. else
  583. {
  584. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  585. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  586. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  587. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  588. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  589. ccp.Payee,ccp.AuditGMDate,
  590. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  591. From Grp_CarTouristGuideGroundReservations ctggr
  592. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  593. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  594. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  595. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  596. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  597. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  598. }
  599. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  600. string CTGGRFeeStr = "";
  601. decimal CTGGRCNYTotalPrice = 0.00M;
  602. //按1 地区,2 币种,3 汇率 分组计算
  603. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  604. foreach (var ctggfr in groupCTGGRFeeDatas)
  605. {
  606. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  607. if (ctggfr_curr.Count() > 0)
  608. {
  609. foreach (var curr in ctggfr_curr)
  610. {
  611. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  612. if (ctggfr_rate.Count() > 0)
  613. {
  614. foreach (var rate in ctggfr_rate)
  615. {
  616. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  617. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  618. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  619. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  620. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  621. }
  622. }
  623. else
  624. {
  625. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  626. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  627. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  628. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  629. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  630. }
  631. }
  632. }
  633. else
  634. {
  635. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  636. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  637. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  638. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  639. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  640. }
  641. }
  642. foreach (var item in groupCTGGRFeeViews)
  643. {
  644. if (!string.IsNullOrEmpty(item.AuditGMDate))
  645. {
  646. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  647. }
  648. if (item.DatePrice != null)
  649. {
  650. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  651. }
  652. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  653. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  654. //CTGGRCNYTotalPrice += item.CNYPrice;
  655. }
  656. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  657. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  658. #endregion
  659. #region 机票预订费用
  660. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  661. //ccp.RMBPrice As CNYPrice
  662. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  663. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  664. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  665. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  666. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  667. atr.CType
  668. From Grp_AirTicketReservations atr
  669. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  670. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  671. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  672. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  673. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  674. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  675. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  676. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  677. string str = "";
  678. List<dynamic> airClientPris = new List<dynamic>();
  679. decimal AirCNYTotalPrice = 0.00M;
  680. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  681. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  682. //if (groupAirFeeViews.Count > 0)
  683. //{
  684. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  685. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  686. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  687. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  688. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  689. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  690. //}
  691. int Index = 0;
  692. foreach (var item in groupAirFeeViews)
  693. {
  694. if (item.AirId > 2924)
  695. {
  696. string itemClientName = "";
  697. if (!string.IsNullOrEmpty(item.ClientName))
  698. {
  699. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  700. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  701. if (m_EnName.Success || m_ZHName.Success)
  702. {
  703. itemClientName = item.ClientName;
  704. decimal unitCost = 0.00M;
  705. AirCNYTotalPrice += item.CNYPrice;
  706. continue;
  707. }
  708. string[] clientIds = new string[] { };
  709. if (item.ClientName.Contains(','))
  710. {
  711. clientIds = item.ClientName.Split(',');
  712. }
  713. else
  714. {
  715. clientIds = new string[] { item.ClientName };
  716. }
  717. if (clientIds.Length > 0)
  718. {
  719. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  720. if (output.Contains(-1))
  721. {
  722. itemClientName += $@"行程单";
  723. output = output.Where(val => val != -1).ToArray();
  724. }
  725. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  726. decimal unitCost = 0.00M;
  727. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  728. int clienIndex = 1;
  729. foreach (var client in clients)
  730. {
  731. airClientPris.Add(new
  732. {
  733. CnName = client.LastName + client.FirstName,
  734. EnName = client.Pinyin,
  735. Price = unitCost,
  736. AirType = item.AirTypeName
  737. });
  738. string six = "";
  739. if (client.Sex == 0) six = "Mr";
  740. else if (client.Sex == 1) six = "Ms";
  741. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  742. clienIndex++;
  743. }
  744. }
  745. }
  746. item.ClientName = itemClientName;
  747. }
  748. else
  749. {
  750. string clientPinYinName = "";
  751. decimal unitCost = 0.00M;
  752. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  753. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  754. Regex r = new Regex("[0-9]");
  755. string name1 = item.ClientName;
  756. name1 = r.Replace(name1, "");
  757. string[] clientNames = name1.Split('.');
  758. for (int i = 0; i < item.ClientNum; i++)
  759. {
  760. string name = "";
  761. if (clientNames.Length > 0)
  762. {
  763. int index = i + 1;
  764. if (index < clientNames.Length)
  765. {
  766. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  767. if (!string.IsNullOrEmpty(name))
  768. {
  769. airClientPris.Add(new
  770. {
  771. CnName = name,
  772. EnName = name,
  773. Price = unitCost,
  774. AirType = item.AirTypeName
  775. });
  776. }
  777. //if (name.Length > 0)
  778. //{
  779. // string nameLastStr = name[name.Length - 1].ToString();
  780. // if (nameLastStr.IsNumeric())
  781. // {
  782. // name = name.Substring(0, name.Length - 1).Trim();
  783. // }
  784. //}
  785. }
  786. }
  787. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  788. }
  789. }
  790. if (!string.IsNullOrEmpty(item.AuditGMDate))
  791. {
  792. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  793. }
  794. AirCNYTotalPrice += item.CNYPrice;
  795. }
  796. _geView.GroupAirFeeViews = groupAirFeeViews;
  797. if (airClientPris.Count > 0)
  798. {
  799. var peoplePriStr = "";
  800. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  801. .Select(group => group.First())
  802. .ToList();
  803. int airClientPrisIndex = 1;
  804. foreach (var item in airClientPris1)
  805. {
  806. decimal price = 0.00M;
  807. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  808. foreach (var pri in prices)
  809. {
  810. price += pri.Price;
  811. }
  812. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  813. airClientPrisIndex++;
  814. }
  815. if (!string.IsNullOrEmpty(peoplePriStr))
  816. {
  817. str = $@"其中:{peoplePriStr}";
  818. }
  819. //经济舱均价
  820. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  821. if (airJJCPris.Count > 0)
  822. {
  823. decimal jjcTotalPrice = 0.00M;
  824. foreach (var item in airJJCPris)
  825. {
  826. jjcTotalPrice += item.Price;
  827. }
  828. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  829. .Select(group => group.First())
  830. .ToList().Count;
  831. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  832. }
  833. //公务舱均价
  834. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  835. if (airGWCPris.Count > 0)
  836. {
  837. decimal gwcTotalPrice = 0.00M;
  838. foreach (var item in airGWCPris)
  839. {
  840. gwcTotalPrice += item.Price;
  841. }
  842. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  843. .Select(group => group.First())
  844. .ToList().Count;
  845. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  846. }
  847. }
  848. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  849. #endregion
  850. #region 签证费用
  851. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  852. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  853. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  854. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  855. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  856. From Grp_VisaInfo vi
  857. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  858. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  859. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  860. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  861. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  862. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  863. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  864. decimal VisaCNYTotalPirce = 0.00M;
  865. foreach (var item in groupVisaFeeViews)
  866. {
  867. string itemClientName = "";
  868. string visaClients = item.VisaClient;
  869. if (!string.IsNullOrEmpty(visaClients))
  870. {
  871. string[] clientIds = new string[] { };
  872. if (visaClients.Contains(','))
  873. {
  874. clientIds = visaClients.Split(',');
  875. }
  876. else
  877. {
  878. clientIds = new string[] { visaClients };
  879. }
  880. if (clientIds.Length > 0)
  881. {
  882. List<int> clientIds1 = new List<int>() { };
  883. foreach (var clientIdStr in clientIds)
  884. {
  885. if (clientIdStr.IsNumeric())
  886. {
  887. clientIds1.Add(int.Parse(clientIdStr));
  888. }
  889. }
  890. if (clientIds1.Count > 0)
  891. {
  892. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  893. foreach (var client in clients)
  894. {
  895. itemClientName += $"{client.LastName + client.FirstName},";
  896. }
  897. }
  898. else
  899. {
  900. itemClientName = visaClients;
  901. }
  902. }
  903. }
  904. if (itemClientName.Length > 0)
  905. {
  906. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  907. }
  908. item.VisaClient = itemClientName;
  909. VisaCNYTotalPirce += item.CNYPrice;
  910. if (!string.IsNullOrEmpty(item.AuditGMDate))
  911. {
  912. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  913. }
  914. }
  915. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  916. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  917. #endregion
  918. #region 邀请/公务活动 CTable = 81
  919. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  920. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  921. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  922. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  923. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  924. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  925. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  926. From Grp_InvitationOfficialActivities ioa
  927. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  928. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  929. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  930. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  931. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  932. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  933. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  934. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  935. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  936. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  937. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  938. #region 邀请/公务活动 - 模拟数据
  939. //if (groupInvitationalFeeViews.Count < 1)
  940. //{
  941. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  942. // {
  943. // IOAId = 0,
  944. // IOADiId = 2334,
  945. // InviterArea = "模拟数据-邀请方地区",
  946. // Inviter = "模拟数据-邀请方",
  947. // InviteTime = "2023-10-10",
  948. // InviteCost = 100.00M,
  949. // InviteCurrency = "EUR",
  950. // SendCost = 100.00M,
  951. // SendCurrency = "EUR",
  952. // EventsCost = 10000.00M,
  953. // EventsCurrency = "EUR",
  954. // TranslateCost = 300.00M,
  955. // TranslateCurrency = "EUR",
  956. // PayMoney = 10500.00M,
  957. // PaymentCurrency = "EUR",
  958. // CNYPrice = 76765.50M,
  959. // Payee = "模拟数据-收款方",
  960. // AuditGMDate = "2023-12-05",
  961. // OrbitalPrivateTransfer = 1,
  962. // PayWay = "刷卡",
  963. // IsPay = 1,
  964. // Applicant = "刘华举"
  965. // });
  966. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  967. // {
  968. // IOAId = 0,
  969. // IOADiId = 2334,
  970. // InviterArea = "模拟数据-邀请方地区",
  971. // Inviter = "模拟数据-邀请方",
  972. // InviteTime = "2023-10-10",
  973. // InviteCost = 100.00M,
  974. // InviteCurrency = "EUR",
  975. // SendCost = 100.00M,
  976. // SendCurrency = "EUR",
  977. // EventsCost = 10000.00M,
  978. // EventsCurrency = "EUR",
  979. // TranslateCost = 300.00M,
  980. // TranslateCurrency = "EUR",
  981. // PayMoney = 10500.00M,
  982. // PaymentCurrency = "EUR",
  983. // CNYPrice = 76765.50M,
  984. // Payee = "模拟数据-收款方",
  985. // AuditGMDate = "2023-12-05",
  986. // OrbitalPrivateTransfer = 1,
  987. // PayWay = "刷卡",
  988. // IsPay = 1,
  989. // Applicant = "刘华举"
  990. // });
  991. //}
  992. #endregion
  993. decimal InvitationalCNYTotalPrice = 0.00M;
  994. foreach (var item in groupInvitationalFeeViews)
  995. {
  996. InvitationalCNYTotalPrice += item.CNYPrice2;
  997. if (!string.IsNullOrEmpty(item.AuditGMDate))
  998. {
  999. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1000. }
  1001. string currencyRateStr = "";
  1002. List<string> currencys = new List<string>();
  1003. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  1004. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  1005. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  1006. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  1007. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  1008. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  1009. item.CurrencyRateStr = currencyRateStr;
  1010. }
  1011. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  1012. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  1013. #endregion
  1014. #region 保险费用
  1015. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1016. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1017. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1018. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1019. From Grp_Customers ic
  1020. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1021. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1022. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1023. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1024. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1025. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1026. decimal InsuranceCNYTotalPrice = 0.00M;
  1027. foreach (var item in groupInsuranceFeeViews)
  1028. {
  1029. InsuranceCNYTotalPrice += item.CNYPrice;
  1030. string itemClientName = "";
  1031. string insClients = item.ClientName;
  1032. if (!string.IsNullOrEmpty(insClients))
  1033. {
  1034. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1035. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1036. //if (m_EnName.Success || m_ZHName.Success)
  1037. //{
  1038. // itemClientName = insClients;
  1039. // continue;
  1040. //}
  1041. string[] clientIds = new string[] { };
  1042. if (insClients.Contains(','))
  1043. {
  1044. clientIds = insClients.Split(',');
  1045. }
  1046. else
  1047. {
  1048. clientIds = new string[] { insClients };
  1049. }
  1050. if (clientIds.Length > 0)
  1051. {
  1052. List<int> output = new List<int>();
  1053. foreach (var clientId in clientIds)
  1054. {
  1055. if (clientId.IsNumeric())
  1056. {
  1057. output.Add(int.Parse(clientId));
  1058. }
  1059. }
  1060. if (output.Count > 0)
  1061. {
  1062. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1063. foreach (var client in clients)
  1064. {
  1065. itemClientName += $"{client.LastName + client.FirstName},";
  1066. }
  1067. if (itemClientName.Length > 0)
  1068. {
  1069. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1070. }
  1071. }
  1072. else
  1073. {
  1074. itemClientName = insClients;
  1075. }
  1076. }
  1077. }
  1078. item.ClientName = itemClientName;
  1079. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1080. {
  1081. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1082. }
  1083. }
  1084. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1085. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1086. #endregion
  1087. #region 其他款项费用 98
  1088. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1089. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1090. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1091. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1092. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1093. From Grp_DecreasePayments dp
  1094. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1095. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1096. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1097. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1098. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1099. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1100. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1101. #region 保险费用 - 模拟数据
  1102. //if (groupDecreaseFeeViews.Count < 1)
  1103. //{
  1104. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1105. // {
  1106. // DPId = 0,
  1107. // DPDiId = 2334,
  1108. // PriceName = "模拟数据-费用名称",
  1109. // PayMoney = 1000.00M,
  1110. // PayMoneyCurrency = "CNY",
  1111. // DayRate = 1.0000M,
  1112. // CNYPrice = 1.0000M,
  1113. // AuditGMDate = "2023-12-10 12:13:00",
  1114. // Payee = "模拟数据-付款方",
  1115. // OrbitalPrivateTransfer = 1,
  1116. // PayWay = "现金",
  1117. // IsPay = 1,
  1118. // Applicant = "刘华举"
  1119. // });
  1120. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1121. // {
  1122. // DPId = 0,
  1123. // DPDiId = 2334,
  1124. // PriceName = "模拟数据-费用名称",
  1125. // PayMoney = 1000.00M,
  1126. // PayMoneyCurrency = "CNY",
  1127. // DayRate = 1.0000M,
  1128. // CNYPrice = 1.0000M,
  1129. // AuditGMDate = "2023-12-10 12:13:00",
  1130. // Payee = "模拟数据-付款方",
  1131. // OrbitalPrivateTransfer = 1,
  1132. // PayWay = "现金",
  1133. // IsPay = 1,
  1134. // Applicant = "刘华举"
  1135. // });
  1136. //}
  1137. #endregion
  1138. decimal DecreaseCNYTotalPrice = 0.00M;
  1139. foreach (var item in groupDecreaseFeeViews)
  1140. {
  1141. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1142. DecreaseCNYTotalPrice += item.CNYPrice;
  1143. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1144. {
  1145. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1146. }
  1147. }
  1148. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1149. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1150. #endregion
  1151. #region 公司内部操作人员提成
  1152. var royaltyDatas = await _sqlSugar
  1153. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1154. new JoinQueryInfos(
  1155. JoinType.Left, rc.UserId == u1.Id,
  1156. JoinType.Left, rc.CreateUserId == u2.Id
  1157. ))
  1158. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1159. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1160. {
  1161. GroupId = rc.TeamId,
  1162. OverviewInfo = rc.Temp,
  1163. DetailedInfo = rc.ChiArr,
  1164. Amount = rc.Price,
  1165. IsConfirm = rc.IsConfirm ,
  1166. IsSeed = rc.IsSeed ,
  1167. RoyaltyUserName = u1.CnName,
  1168. CreateUserName = u2.CnName,
  1169. CreateTime = rc.CreateTime
  1170. })
  1171. .ToListAsync();
  1172. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  1173. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  1174. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  1175. #endregion
  1176. _view.GroupExpenditure = _geView;
  1177. #endregion
  1178. /*
  1179. * 团组报表计算方式
  1180. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1181. * 应收金额 = 应收表.Sum()
  1182. * 已收金额 = 已收表.Sum()
  1183. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1184. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1185. *
  1186. */
  1187. decimal _totalExpenditure = 0.00M; //总支出
  1188. decimal _amountReceivable = 0.00M; //应收金额
  1189. decimal _amountReceived = 0.00M; //已收金额
  1190. decimal _receivableProfit = 0.00M; //应收利润
  1191. decimal _receivedProfit = 0.00M; //已收利润
  1192. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1193. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  1194. _amountReceivable = frTotalAmount;
  1195. _amountReceived = prTotalAmount;
  1196. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1197. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1198. _view.FeeTotalStr = string.Format(@$"<span>
  1199. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1200. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1201. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1202. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1203. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1204. </span>");
  1205. return Ok(JsonView(true, "查询成功!", _view));
  1206. }
  1207. else
  1208. {
  1209. return Ok(JsonView(false, "查询成功"));
  1210. }
  1211. }
  1212. /// <summary>
  1213. /// 团组报表
  1214. /// Excel 下载
  1215. /// </summary>
  1216. /// <param name="_dto">团组列表请求dto</param>
  1217. /// <returns></returns>
  1218. [HttpPost("PostGroupStatementExportExcel")]
  1219. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1220. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1221. {
  1222. //pageId 38
  1223. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1224. bool isAudit = _dto.isAudit;
  1225. #region 参数验证
  1226. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1227. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1228. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1229. #region 页面操作权限验证
  1230. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1231. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1232. #endregion
  1233. #endregion
  1234. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1235. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1236. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1237. string groupNo = groupInfo.TourCode,
  1238. groupName = groupInfo.TeamName.Replace("|", "、"),
  1239. lister = userInfo?.CnName ?? "-";
  1240. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1241. .Where(it => it.IsDel == 0)
  1242. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1243. .ToList();
  1244. //获取模板
  1245. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1246. var designer = new WorkbookDesigner();
  1247. designer.Workbook = new Workbook(tempPath);
  1248. // 获取工作簿中的工作表集合
  1249. var worksheets = designer.Workbook.Worksheets;
  1250. #region 获取sheet,定义datatable,局部变量
  1251. //酒店费用相关
  1252. var hotelFeeSheet = worksheets["酒店费用"];
  1253. var hotelFeeDt = new DataTable($"HotelFeeView");
  1254. decimal hotelCNYTotalCost = 0.00M;
  1255. //地接费用相关
  1256. var OPFeeSheet = worksheets["地接费用"];
  1257. var OPFeeDt = new DataTable($"OPFeeView");
  1258. var OPFeeLabel = string.Empty;
  1259. decimal OPCNYTotalCost = 0.00M;
  1260. //签证费用相关
  1261. var visaFeeSheet = worksheets["签证费用"];
  1262. var visaFeeDt = new DataTable($"VisaFeeView");
  1263. decimal visaCNYTotalCost = 0.00M;
  1264. //邀请费用相关
  1265. var OAFeeSheet = worksheets["邀请费用"];
  1266. var OAFeeDt = new DataTable($"OAFeeView");
  1267. decimal OACNYTotalCost = 0.00M;
  1268. //机票费用相关
  1269. var airTicketFeeSheet = worksheets["机票费用"];
  1270. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1271. decimal airTicketCNYTotalCost = 0.00M;
  1272. //保险费用相关
  1273. var insureFeeSheet = worksheets["保险费用"];
  1274. var insureFeeDt = new DataTable($"InsureFeeView");
  1275. decimal insureCNYTotalCost = 0.00M;
  1276. //其他费用相关
  1277. var otherFeeSheet = worksheets["其他费用"];
  1278. var otherFeeDt = new DataTable($"OtherFeeView");
  1279. decimal otherCNYTotalCost = 0.00M;
  1280. //收款退还相关
  1281. var SKTHFeeSheet = worksheets["收款退还"];
  1282. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1283. decimal SKTHCNYTotalCost = 0.00M;
  1284. //操作提成
  1285. var royaltyFeeSheet = worksheets["操作提成"];
  1286. var royaltyFeeDt = new DataTable($"royaltyFeeView");
  1287. decimal royaltyCNYTotalCost = 0.00M;
  1288. var totalAmount = 0.00M; //支出成本合计
  1289. var accountsAmount = 0.00M; //应收金额合计
  1290. var receivedAmount = 0.00M; //已收金额合计
  1291. var accountsProfit = 0.00M; //应收利润合计
  1292. var receiveProfit = 0.00M; //已收利润合计
  1293. var profitMargin = 0.00M; //利润差合计
  1294. //应收合计相关
  1295. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1296. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1297. //已收合计相关
  1298. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1299. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1300. //团组收入支出利润
  1301. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1302. #endregion
  1303. #region 酒店费用
  1304. if (hotelFeeSheet != null)
  1305. {
  1306. string hotelFeeSql = string.Format(@"
  1307. SELECT
  1308. hr.Id AS HrId,
  1309. hr.DiId AS HrDiId,
  1310. hr.City,
  1311. hr.HotelName,
  1312. hr.CheckInDate,
  1313. hr.CheckOutDate,
  1314. hr.CardPrice AS RoomPrice,
  1315. sd1.Name AS PaymentCurrency,
  1316. hr.SingleRoomPrice,
  1317. hr.SingleRoomCount,
  1318. hr.DoubleRoomPrice,
  1319. hr.DoubleRoomCount,
  1320. hr.SuiteRoomPrice,
  1321. hr.SuiteRoomCount,
  1322. hr.OtherRoomPrice,
  1323. hr.OtherRoomCount,
  1324. hr.BreakfastPrice,
  1325. sd4.Name AS BreakfastCurrency,
  1326. hr.Isoppay,
  1327. hr.GovernmentRent,
  1328. sd5.Name AS GovernmentRentCurrency,
  1329. hr.CityTax,
  1330. sd6.Name AS CityTaxCurrency,
  1331. ccp.PayMoney,
  1332. (
  1333. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1334. ) AS CNYPrice,
  1335. ccp.PayPercentage,
  1336. ccp.DayRate,
  1337. ccp.Payee,
  1338. ccp.OrbitalPrivateTransfer,
  1339. sd2.Name AS PayWay,
  1340. sd3.Name AS CardType,
  1341. ccp.IsPay,
  1342. u.CnName AS Applicant,
  1343. hr.Remark
  1344. FROM
  1345. Grp_HotelReservations hr
  1346. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1347. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1348. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1349. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1350. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1351. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1352. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1353. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1354. WHERE
  1355. hr.IsDel = 0
  1356. AND ccp.IsDel = 0
  1357. AND ccp.CTable = 76 {1}
  1358. AND ccp.PayMoney <> 0
  1359. AND hr.DiId = {0}
  1360. ORDER BY
  1361. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1362. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1363. if (groupHotelFeeViews.Any())
  1364. {
  1365. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1366. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1367. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1368. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1369. foreach (var item in groupHotelFeeViews)
  1370. {
  1371. if (groupHotelContentFeeViews.Count > 0)
  1372. {
  1373. string paymentStr = string.Empty;
  1374. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1375. item.RoomPrice = roomData?.Price ?? 0.00M;
  1376. if (item.RoomPrice != 0)
  1377. {
  1378. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1379. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1380. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1381. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1382. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1383. 收款方:{roomData?.Payee}<br/>
  1384. 费用标识:{feeMark1} <br/>
  1385. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1386. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1387. 是否由地接支付:{isFeeMark1} <br/>";
  1388. }
  1389. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1390. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1391. if (item.BreakfastPrice != 0)
  1392. {
  1393. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1394. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1395. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1396. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1397. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1398. 收款方:{breakfastData?.Payee}<br/>
  1399. 费用标识:{feeMark2} <br/>
  1400. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1401. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1402. 是否由地接支付:{isFeeMark2} <br/>";
  1403. }
  1404. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1405. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1406. if (item.GovernmentRent != 0)
  1407. {
  1408. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1409. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1410. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1411. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1412. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1413. 收款方:{landTaxData?.Payee}<br/>
  1414. 费用标识:{feeMark3} <br/>
  1415. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1416. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1417. 是否由地接支付:{isFeeMark3} <br/>";
  1418. }
  1419. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1420. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1421. if (item.CityTax != 0)
  1422. {
  1423. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1424. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1425. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1426. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1427. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1428. 收款方:{cityTaxData?.Payee}<br/>
  1429. 费用标识:{feeMark4} <br/>
  1430. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1431. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1432. 是否由地接支付:{isFeeMark4} <br/>";
  1433. }
  1434. if (!string.IsNullOrEmpty(paymentStr))
  1435. {
  1436. item.IsPay = 2;
  1437. item.PayTips = paymentStr;
  1438. }
  1439. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1440. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1441. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1442. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1443. }
  1444. else
  1445. {
  1446. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1447. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1448. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1449. (item.OtherRoomCount * item.OtherRoomPrice);
  1450. //item.RoomPrice = item.CardPrice;
  1451. item.RoomPriceCurrency = item.PaymentCurrency;
  1452. }
  1453. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1454. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1455. }
  1456. }
  1457. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1458. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1459. hotelFeeDt.TableName = $"HotelFeeView";
  1460. }
  1461. #endregion
  1462. #region 地接费用
  1463. if (OPFeeSheet != null)
  1464. {
  1465. string CTGGRFeeSql = string.Empty;
  1466. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1467. {
  1468. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1469. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1470. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1471. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1472. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1473. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1474. From Grp_CarTouristGuideGroundReservations ctggr
  1475. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1476. cggrc.DatePrice,cggrc.PriceContent
  1477. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1478. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1479. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1480. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1481. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1482. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1483. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1484. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1485. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1486. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1487. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1488. }
  1489. else
  1490. {
  1491. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1492. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1493. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1494. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1495. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1496. ccp.Payee,ccp.AuditGMDate,
  1497. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1498. From Grp_CarTouristGuideGroundReservations ctggr
  1499. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1500. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1501. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1502. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1503. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1504. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1505. }
  1506. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1507. string CTGGRFeeStr = "";
  1508. var OPToDataTableViews = groupOPFeeViews;
  1509. decimal CTGGRCNYTotalPrice = 0.00M;
  1510. //按1 地区,2 币种,3 汇率 分组计算
  1511. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1512. foreach (var ctggfr in groupCTGGRFeeDatas)
  1513. {
  1514. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1515. if (ctggfr_curr.Count() > 0)
  1516. {
  1517. foreach (var curr in ctggfr_curr)
  1518. {
  1519. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1520. if (ctggfr_rate.Count() > 0)
  1521. {
  1522. foreach (var rate in ctggfr_rate)
  1523. {
  1524. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")} {rate.FirstOrDefault()?.PaymentCurrency}(人民币:{rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1525. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1526. }
  1527. }
  1528. else
  1529. {
  1530. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")} {curr.FirstOrDefault()?.PaymentCurrency}(人民币:{curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1531. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1532. }
  1533. }
  1534. }
  1535. else
  1536. {
  1537. CTGGRFeeStr += string.Format($"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")} {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:{ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:{ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\n");
  1538. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1539. }
  1540. }
  1541. foreach (var item in groupOPFeeViews)
  1542. {
  1543. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1544. {
  1545. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1546. }
  1547. if (item.DatePrice != null)
  1548. {
  1549. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1550. }
  1551. }
  1552. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1553. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1554. OPFeeLabel = CTGGRFeeStr;
  1555. OPFeeDt.TableName = $"OPFeeView";
  1556. }
  1557. #endregion
  1558. #region 签证费用
  1559. if (visaFeeSheet != null)
  1560. {
  1561. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1562. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1563. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1564. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1565. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1566. From Grp_VisaInfo vi
  1567. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1568. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1569. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1570. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1571. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1572. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1573. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1574. foreach (var item in groupVisaFeeViews)
  1575. {
  1576. string names = string.Empty;
  1577. string visaClients = item.VisaClient;
  1578. if (!string.IsNullOrEmpty(visaClients))
  1579. {
  1580. var clientIds = new string[] { };
  1581. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1582. else clientIds = new string[] { visaClients };
  1583. if (clientIds.Length > 0)
  1584. {
  1585. var clientIds1 = new List<int>() { };
  1586. foreach (var clientIdStr in clientIds)
  1587. {
  1588. var isInt = int.TryParse(clientIdStr, out int id);
  1589. if (isInt) clientIds1.Add(id);
  1590. }
  1591. if (clientIds1.Count > 0)
  1592. {
  1593. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1594. foreach (var client in clients)
  1595. {
  1596. EncryptionProcessor.DecryptProperties(client);
  1597. names += $"{client.LastName + client.FirstName},";
  1598. }
  1599. }
  1600. else names = visaClients;
  1601. }
  1602. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1603. item.VisaClient = names;
  1604. }
  1605. }
  1606. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1607. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1608. visaFeeDt.TableName = $"VisaFeeView";
  1609. }
  1610. #endregion
  1611. #region 邀请费用
  1612. if (OAFeeSheet != null)
  1613. {
  1614. string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1615. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1616. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1617. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1618. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1619. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1620. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1621. From Grp_InvitationOfficialActivities ioa
  1622. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1623. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1624. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1625. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1626. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1627. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1628. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1629. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1630. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1631. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1632. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1633. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1634. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1635. OAFeeDt.TableName = $"OAFeeView";
  1636. }
  1637. #endregion
  1638. #region 机票费用
  1639. if (airTicketFeeSheet != null)
  1640. {
  1641. string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1642. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1643. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1644. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1645. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1646. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1647. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1648. From Grp_AirTicketReservations atr
  1649. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1650. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1651. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1652. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1653. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1654. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1655. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1656. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1657. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1658. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1659. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1660. }
  1661. #endregion
  1662. #region 保险费用
  1663. if (insureFeeSheet != null)
  1664. {
  1665. string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1666. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1667. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1668. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1669. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1670. From Grp_Customers ic
  1671. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1672. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1673. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1674. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1675. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1676. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1677. foreach (var item in feeViews)
  1678. {
  1679. string itemClientName = "";
  1680. string insClients = item.ClientName;
  1681. if (!string.IsNullOrEmpty(insClients))
  1682. {
  1683. string[] clientIds = new string[] { };
  1684. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1685. else clientIds = new string[] { insClients };
  1686. if (clientIds.Length > 0)
  1687. {
  1688. List<int> output = new List<int>();
  1689. foreach (var clientId in clientIds)
  1690. if (int.TryParse(clientId, out int id))
  1691. output.Add(id);
  1692. if (output.Count > 0)
  1693. {
  1694. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1695. foreach (var client in clients)
  1696. {
  1697. EncryptionProcessor.DecryptProperties(client);
  1698. itemClientName += $"{client.LastName + client.FirstName},";
  1699. }
  1700. if (itemClientName.Length > 0)
  1701. {
  1702. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1703. }
  1704. }
  1705. else itemClientName = insClients;
  1706. }
  1707. }
  1708. item.ClientName = itemClientName;
  1709. }
  1710. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1711. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1712. insureFeeDt.TableName = $"InsureFeeView";
  1713. }
  1714. #endregion
  1715. #region 其他费用
  1716. if (insureFeeSheet != null)
  1717. {
  1718. string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1719. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1720. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1721. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1722. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1723. From Grp_DecreasePayments dp
  1724. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1725. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1726. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1727. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1728. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1729. Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1730. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1731. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1732. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1733. otherFeeDt.TableName = $"OtherFeeView";
  1734. }
  1735. #endregion
  1736. #region 收款退还
  1737. if (SKTHFeeSheet != null)
  1738. {
  1739. //删除了 And prom.PriceType = 1
  1740. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1741. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1742. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1743. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1744. From Fin_PaymentRefundAndOtherMoney prom
  1745. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1746. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1747. Where prom.IsDel = 0
  1748. And prom.PayType = 1
  1749. And ccp.CTable = 285
  1750. {1}
  1751. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1752. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1753. if (_promDatas.Any())
  1754. {
  1755. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1756. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1757. foreach (var ropItem in _promDatas)
  1758. {
  1759. string thisCueencyCode = "Unknown";
  1760. string thisCueencyName = "Unknown";
  1761. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1762. if (currency != null)
  1763. {
  1764. thisCueencyCode = currency.Name;
  1765. thisCueencyName = currency.Remark;
  1766. }
  1767. string orbitalPrivateTransferStr = "Unknown";
  1768. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1769. if (orbitalPrivateTransfer != null)
  1770. {
  1771. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1772. }
  1773. string payStr = "Unknown";
  1774. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1775. if (pay != null)
  1776. {
  1777. payStr = pay.Name;
  1778. }
  1779. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1780. {
  1781. Id = ropItem.Id,
  1782. DiId = ropItem.DIId,
  1783. PriceName = ropItem.PrPriceName,
  1784. PayCurrencyCode = thisCueencyCode,
  1785. PayCurrencyName = thisCueencyName,
  1786. Price = ropItem.PrPrice,
  1787. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1788. ThisRate = ropItem.DayRate,
  1789. Payee = ropItem.Payee,
  1790. PayTime = ropItem.AuditGMDate,
  1791. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1792. PayType = payStr,
  1793. IsPay = ropItem.IsPay,
  1794. Applicant = ropItem.Appliction,
  1795. Remark = ropItem.SKTHRemark
  1796. };
  1797. _promView.Add(gsd_PaymentRefund);
  1798. }
  1799. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1800. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1801. SKTHFeeDt.TableName = $"SKTHFeeView";
  1802. }
  1803. }
  1804. #endregion
  1805. #region 操作提成
  1806. if (SKTHFeeSheet != null)
  1807. {
  1808. var _royaltyDatas = await _sqlSugar
  1809. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1810. new JoinQueryInfos(
  1811. JoinType.Left, rc.UserId == u1.Id,
  1812. JoinType.Left, rc.CreateUserId == u2.Id
  1813. ))
  1814. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1815. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1816. {
  1817. GroupId = rc.TeamId,
  1818. OverviewInfo = rc.Temp,
  1819. DetailedInfo = rc.ChiArr,
  1820. Amount = rc.Price,
  1821. IsConfirm = rc.IsConfirm,
  1822. IsSeed = rc.IsSeed,
  1823. RoyaltyUserName = u1.CnName,
  1824. CreateUserName = u2.CnName,
  1825. CreateTime = rc.CreateTime
  1826. })
  1827. .ToListAsync();
  1828. if (_royaltyDatas.Any())
  1829. {
  1830. decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
  1831. var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
  1832. royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
  1833. royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
  1834. royaltyFeeDt.TableName = $"RoyaltyFeeView";
  1835. }
  1836. }
  1837. #endregion
  1838. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1839. decimal frTotalAmount = 0.00M;//应收总金额
  1840. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  1841. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1842. From Fin_ForeignReceivables fr
  1843. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1844. Left Join Sys_Users u On fr.Auditor = u.Id
  1845. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1846. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1847. _frViews.ForEach(x =>
  1848. {
  1849. string namePrefix = string.Empty;
  1850. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1851. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1852. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1853. x.PriceName = $"{namePrefix}{x.PriceName}";
  1854. });
  1855. if (_frViews.Any())
  1856. {
  1857. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1858. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1859. receivableFeeDt.TableName = $"ReceivedFeeView";
  1860. }
  1861. #endregion
  1862. #region 已收金额
  1863. decimal prTotalAmount = 0.00M;//已收总金额
  1864. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1865. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1866. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1867. From Fin_ProceedsReceived pr
  1868. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1869. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1870. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  1871. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1872. if (_prViews.Any())
  1873. {
  1874. receivedAmount = _prViews.Sum(it => it.Price);
  1875. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  1876. receivedFeeDt.TableName = $"ReceivableFeeView";
  1877. }
  1878. #endregion
  1879. #region 团组收入支出利润
  1880. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  1881. new DataColumn(){ ColumnName = "ModuleName"},
  1882. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  1883. new DataColumn(){ ColumnName = "FeeCurrency"},
  1884. });
  1885. var groupIEProfitDt_rows = new[] {
  1886. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  1887. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  1888. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  1889. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  1890. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  1891. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  1892. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  1893. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  1894. new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
  1895. };
  1896. // 批量添加
  1897. foreach (var rowData in groupIEProfitDt_rows)
  1898. {
  1899. groupIEProfitDt.Rows.Add(rowData);
  1900. }
  1901. #endregion
  1902. #region 统一填充数据源
  1903. designer.SetDataSource("GroupNo", groupNo);
  1904. designer.SetDataSource("GroupName", groupName);
  1905. designer.SetDataSource("Lister", lister);
  1906. //酒店
  1907. designer.SetDataSource(hotelFeeDt);
  1908. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  1909. //地接
  1910. designer.SetDataSource(OPFeeDt);
  1911. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  1912. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  1913. //签证
  1914. designer.SetDataSource(visaFeeDt);
  1915. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  1916. //商邀
  1917. designer.SetDataSource(OAFeeDt);
  1918. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  1919. //机票
  1920. designer.SetDataSource(airTicketFeeDt);
  1921. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  1922. //保险
  1923. designer.SetDataSource(insureFeeDt);
  1924. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  1925. //其他费用
  1926. designer.SetDataSource(otherFeeDt);
  1927. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  1928. //收款退还
  1929. designer.SetDataSource(SKTHFeeDt);
  1930. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  1931. //操作提成
  1932. designer.SetDataSource(royaltyFeeDt);
  1933. designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
  1934. //已收金额
  1935. designer.SetDataSource(receivedFeeDt);
  1936. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  1937. //应收金额
  1938. designer.SetDataSource(receivableFeeDt);
  1939. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  1940. //应收已收 -- 尾款
  1941. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  1942. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  1943. //团组收入支出利润
  1944. designer.SetDataSource(groupIEProfitDt);
  1945. #region 各项费用计算
  1946. /*
  1947. * 团组报表计算方式
  1948. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1949. * 应收金额 = 应收表.Sum() - 收款退还
  1950. * 已收金额 = 已收表.Sum() - 收款退还
  1951. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  1952. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  1953. * 利润差 = 应收利润 - 已收利润
  1954. */
  1955. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
  1956. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  1957. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  1958. profitMargin = accountsProfit - receiveProfit; //利润差
  1959. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  1960. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  1961. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  1962. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  1963. #endregion
  1964. designer.Process();
  1965. #endregion
  1966. #region 单元格样式设置 未付款设置为红色
  1967. /*
  1968. * 设置单元格样式
  1969. */
  1970. //背景颜色
  1971. Style style = designer.Workbook.CreateStyle();
  1972. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  1973. style.Pattern = BackgroundType.Solid;
  1974. //字体
  1975. style.Font.Name = "微软雅黑"; // 字体名称
  1976. style.Font.Size = 10; // 字体大小
  1977. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  1978. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  1979. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  1980. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  1981. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  1982. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  1983. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  1984. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  1985. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  1986. #endregion
  1987. //文件名
  1988. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  1989. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  1990. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  1991. return Ok(JsonView(true, "成功", url));
  1992. }
  1993. /// <summary>
  1994. /// 团组报表
  1995. /// 利润相关数据
  1996. /// </summary>
  1997. /// <returns></returns>
  1998. [HttpPost("PostGroupStatementDetails1")]
  1999. //[JsonConverter(typeof(DecimalConverter), 2)]
  2000. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2001. public async Task<IActionResult> PostGroupStatementDetails1()
  2002. {
  2003. var groupInfos = _sqlSugar.Queryable<Grp_DelegationInfo>()
  2004. .Where(x => x.IsDel == 0 && x.VisitDate >= DateTime.Parse ("2024-01-01") && x.VisitDate <= DateTime.Parse("2024-12-31"))
  2005. .OrderByDescending(x => x.VisitDate)
  2006. .ToList();
  2007. #region 费用类型 币种,转账,客户信息
  2008. List<Sys_SetData> _setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2009. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  2010. .Where(it => it.IsDel == 0)
  2011. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  2012. .ToList();
  2013. // foreach (var item1 in _clientDatas) EncryptionProcessor.DecryptProperties(item1);
  2014. #endregion
  2015. var _views = new List<GroupStatisticsInfo>();
  2016. int index1 = 0;
  2017. foreach (var info in groupInfos)
  2018. {
  2019. var _dto = new { DiId = info.Id, isAudit = false };
  2020. /*
  2021. * 团组报表计算方式
  2022. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2023. * 应收金额 = 应收表.Sum()
  2024. * 已收金额 = 已收表.Sum()
  2025. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2026. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2027. *
  2028. */
  2029. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  2030. var groupInfo = info;
  2031. var visitDate = info.VisitDate;
  2032. #region 团组收入
  2033. GroupIncomeView _giView = new GroupIncomeView();
  2034. /*
  2035. * 应收报表
  2036. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  2037. */
  2038. decimal frTotalAmount = 0.00M;//应收总金额
  2039. string _frSql = string.Format(@" Select fr.Id,fr.AddingWay,fr.Status,u.CnName As Auditor,fr.AuditTime,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  2040. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2041. From Fin_ForeignReceivables fr
  2042. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2043. Left Join Sys_Users u On fr.Auditor = u.Id
  2044. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  2045. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2046. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  2047. //if (_frViews1.Count > 0)
  2048. //{
  2049. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  2050. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  2051. //}
  2052. _frViews.ForEach(x =>
  2053. {
  2054. string namePrefix = string.Empty;
  2055. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  2056. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  2057. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  2058. x.PriceName = $"{namePrefix}{x.PriceName}";
  2059. });
  2060. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2061. _giView.Receivables = _frViews;
  2062. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2063. /*
  2064. * 已收报表
  2065. */
  2066. decimal prTotalAmount = 0.00M;//已收总金额
  2067. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2068. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2069. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2070. From Fin_ProceedsReceived pr
  2071. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2072. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2073. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2074. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2075. prTotalAmount = _prViews.Sum(it => it.Price);
  2076. _giView.ProceedsReceivedViews = _prViews;
  2077. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  2078. /*
  2079. * 超支费用
  2080. */
  2081. decimal exTotalAmount = 0.00M;
  2082. // string ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,(gec.PriceSum * gec.Coefficient) As PayMoney,sd1.Name As PaymentCurrency,
  2083. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2084. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2085. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  2086. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2087. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2088. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2089. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2090. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2091. //Where ccp.IsDel = 0 And ccp.CTable = 1015 {1} And ccp.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1 And ccp.IsPay = 1 " : " ");
  2092. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  2093. // #region 超支费用 - 模拟数据
  2094. // //if (_ExtraCostsViews.Count < 1)
  2095. // //{
  2096. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2097. // // {
  2098. // // GECId = 0,
  2099. // // GECDiId = 2334,
  2100. // // PriceName = "模拟数据-超支费用名称",
  2101. // // PayMoney = 1000.00M,
  2102. // // PaymentCurrency = "CNY",
  2103. // // DayRate = 1.0000M,
  2104. // // CNYPrice = 1000.00M,
  2105. // // Payee = "模拟数据-超支费用收款方",
  2106. // // OrbitalPrivateTransfer = 1,
  2107. // // PayWay = "刷卡",
  2108. // // CardType = "招行卡",
  2109. // // IsPay = 1,
  2110. // // Applicant = "刘华举"
  2111. // // });
  2112. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2113. // // {
  2114. // // GECId = 0,
  2115. // // GECDiId = 2334,
  2116. // // PriceName = "模拟数据-超支费用名称",
  2117. // // PayMoney = 1000.00M,
  2118. // // PaymentCurrency = "CNY",
  2119. // // DayRate = 1.0000M,
  2120. // // CNYPrice = 1000.00M,
  2121. // // Payee = "模拟数据-超支费用收款方",
  2122. // // OrbitalPrivateTransfer = 1,
  2123. // // PayWay = "刷卡",
  2124. // // CardType = "招行卡",
  2125. // // IsPay = 1,
  2126. // // Applicant = "刘华举"
  2127. // // });
  2128. // //}
  2129. // #endregion
  2130. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2131. // _giView.ExtraCostsViews = _ExtraCostsViews;
  2132. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2133. /*
  2134. * 收款退还
  2135. */
  2136. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2137. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2138. //删除了 And prom.PriceType = 1
  2139. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2140. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2141. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  2142. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  2143. From Fin_PaymentRefundAndOtherMoney prom
  2144. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2145. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2146. Where prom.IsDel = 0
  2147. And prom.PayType = 1
  2148. And ccp.CTable = 285
  2149. {1}
  2150. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2151. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2152. foreach (var ropItem in _promDatas)
  2153. {
  2154. string thisCueencyCode = "Unknown";
  2155. string thisCueencyName = "Unknown";
  2156. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2157. if (currency != null)
  2158. {
  2159. thisCueencyCode = currency.Name;
  2160. thisCueencyName = currency.Remark;
  2161. }
  2162. string orbitalPrivateTransferStr = "Unknown";
  2163. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2164. if (orbitalPrivateTransfer != null)
  2165. {
  2166. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2167. }
  2168. string payStr = "Unknown";
  2169. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2170. if (pay != null)
  2171. {
  2172. payStr = pay.Name;
  2173. }
  2174. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2175. {
  2176. Id = ropItem.Id,
  2177. DiId = ropItem.DIId,
  2178. PriceName = ropItem.PrPriceName,
  2179. PayCurrencyCode = thisCueencyCode,
  2180. PayCurrencyName = thisCueencyName,
  2181. Price = ropItem.PrPrice,
  2182. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  2183. ThisRate = ropItem.DayRate,
  2184. Payee = ropItem.Payee,
  2185. PayTime = ropItem.AuditGMDate,
  2186. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2187. PayType = payStr,
  2188. IsPay = ropItem.IsPay,
  2189. Applicant = ropItem.Appliction
  2190. };
  2191. _promView.Add(gsd_PaymentRefund);
  2192. }
  2193. #region 收款退还 - 模拟数据
  2194. //if (_promView.Count < 1)
  2195. //{
  2196. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2197. // {
  2198. // Id = 0,
  2199. // DiId = 2334,
  2200. // PriceName = "模拟数据-费用名称",
  2201. // PayCurrencyCode = "CNY",
  2202. // PayCurrencyName = "人民币",
  2203. // Price = 1000.00M,
  2204. // CNYPrice = 1000.00M,
  2205. // ThisRate = 1.00M,
  2206. // Payee = "模拟数据-收款方",
  2207. // PayTime = "2023-01-01 15:20:01",
  2208. // OrbitalPrivateTransfer = 1,
  2209. // PayType = "刷卡",
  2210. // IsPay = 1,
  2211. // Applicant = "刘华举"
  2212. // });
  2213. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2214. // {
  2215. // Id = 0,
  2216. // DiId = 2334,
  2217. // PriceName = "模拟数据-费用名称",
  2218. // PayCurrencyCode = "CNY",
  2219. // PayCurrencyName = "人民币",
  2220. // Price = 1000.00M,
  2221. // CNYPrice = 1000.00M,
  2222. // ThisRate = 1.00M,
  2223. // Payee = "模拟数据-收款方",
  2224. // PayTime = "2023-01-01 15:20:01",
  2225. // OrbitalPrivateTransfer = 1,
  2226. // PayType = "刷卡",
  2227. // IsPay = 1,
  2228. // Applicant = "刘华举"
  2229. // });
  2230. //}
  2231. #endregion
  2232. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2233. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  2234. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2235. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  2236. _view.GroupIncome = _giView;
  2237. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  2238. #endregion
  2239. #region 团组支出
  2240. GroupExpenditureView _geView = new GroupExpenditureView();
  2241. #region 酒店预定费用
  2242. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2243. //ccp.RMBPrice As CNYPrice
  2244. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2245. string hotelFeeSql = string.Format(@"
  2246. SELECT
  2247. hr.Id AS HrId,
  2248. hr.DiId AS HrDiId,
  2249. hr.City,
  2250. hr.HotelName,
  2251. hr.CheckInDate,
  2252. hr.CheckOutDate,
  2253. hr.CardPrice AS RoomPrice,
  2254. sd1.Name AS PaymentCurrency,
  2255. hr.SingleRoomPrice,
  2256. hr.SingleRoomCount,
  2257. hr.DoubleRoomPrice,
  2258. hr.DoubleRoomCount,
  2259. hr.SuiteRoomPrice,
  2260. hr.SuiteRoomCount,
  2261. hr.OtherRoomPrice,
  2262. hr.OtherRoomCount,
  2263. hr.BreakfastPrice,
  2264. sd4.Name AS BreakfastCurrency,
  2265. hr.Isoppay,
  2266. hr.GovernmentRent,
  2267. sd5.Name AS GovernmentRentCurrency,
  2268. hr.CityTax,
  2269. sd6.Name AS CityTaxCurrency,
  2270. ccp.PayMoney,
  2271. (
  2272. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2273. ) AS CNYPrice,
  2274. ccp.PayPercentage,
  2275. ccp.DayRate,
  2276. ccp.Payee,
  2277. ccp.OrbitalPrivateTransfer,
  2278. sd2.Name AS PayWay,
  2279. sd3.Name AS CardType,
  2280. ccp.IsPay,
  2281. u.CnName AS Applicant
  2282. FROM
  2283. Grp_HotelReservations hr
  2284. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  2285. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  2286. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  2287. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  2288. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  2289. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  2290. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  2291. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  2292. WHERE
  2293. hr.IsDel = 0
  2294. AND ccp.IsDel = 0
  2295. AND ccp.CTable = 76 {1}
  2296. AND ccp.PayMoney <> 0
  2297. AND hr.DiId = {0}
  2298. ORDER BY
  2299. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  2300. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2301. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  2302. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  2303. decimal HotelCNYTotalPrice = 0.00M;
  2304. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  2305. foreach (var item in groupHotelFeeViews)
  2306. {
  2307. if (groupHotelContentFeeViews.Count > 0)
  2308. {
  2309. string paymentStr = string.Empty;
  2310. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  2311. item.RoomPrice = roomData?.Price ?? 0.00M;
  2312. if (item.RoomPrice != 0)
  2313. {
  2314. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  2315. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  2316. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2317. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  2318. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  2319. 收款方:{roomData?.Payee}<br/>
  2320. 费用标识:{feeMark1} <br/>
  2321. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2322. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  2323. 是否由地接支付:{isFeeMark1} <br/>";
  2324. }
  2325. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  2326. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  2327. if (item.BreakfastPrice != 0)
  2328. {
  2329. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  2330. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  2331. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2332. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  2333. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  2334. 收款方:{breakfastData?.Payee}<br/>
  2335. 费用标识:{feeMark2} <br/>
  2336. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2337. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  2338. 是否由地接支付:{isFeeMark2} <br/>";
  2339. }
  2340. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  2341. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  2342. if (item.GovernmentRent != 0)
  2343. {
  2344. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  2345. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  2346. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2347. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2348. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  2349. 收款方:{landTaxData?.Payee}<br/>
  2350. 费用标识:{feeMark3} <br/>
  2351. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  2352. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  2353. 是否由地接支付:{isFeeMark3} <br/>";
  2354. }
  2355. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  2356. item.CityTax = cityTaxData?.Price ?? 0.00M;
  2357. if (item.CityTax != 0)
  2358. {
  2359. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  2360. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  2361. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2362. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2363. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  2364. 收款方:{cityTaxData?.Payee}<br/>
  2365. 费用标识:{feeMark4} <br/>
  2366. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  2367. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  2368. 是否由地接支付:{isFeeMark4} <br/>";
  2369. }
  2370. if (!string.IsNullOrEmpty(paymentStr))
  2371. {
  2372. item.IsPay = 2;
  2373. item.PayTips = paymentStr;
  2374. }
  2375. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  2376. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  2377. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  2378. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  2379. }
  2380. else
  2381. {
  2382. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  2383. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  2384. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  2385. (item.OtherRoomCount * item.OtherRoomPrice);
  2386. //item.RoomPrice = item.CardPrice;
  2387. item.RoomPriceCurrency = item.PaymentCurrency;
  2388. }
  2389. HotelCNYTotalPrice += item.CNYPrice;
  2390. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  2391. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  2392. }
  2393. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  2394. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  2395. #endregion
  2396. #region 地接费用
  2397. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2398. string CTGGRFeeSql = string.Empty;
  2399. if (visitDate > Convert.ToDateTime("2024-04-17"))
  2400. {
  2401. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  2402. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2403. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  2404. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  2405. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2406. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2407. From Grp_CarTouristGuideGroundReservations ctggr
  2408. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  2409. cggrc.DatePrice,cggrc.PriceContent
  2410. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2411. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2412. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2413. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2414. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2415. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2416. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2417. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2418. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2419. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2420. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2421. }
  2422. else
  2423. {
  2424. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  2425. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  2426. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  2427. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  2428. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  2429. ccp.Payee,ccp.AuditGMDate,
  2430. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2431. From Grp_CarTouristGuideGroundReservations ctggr
  2432. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2433. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2434. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2435. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2436. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2437. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2438. }
  2439. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2440. string CTGGRFeeStr = "";
  2441. decimal CTGGRCNYTotalPrice = 0.00M;
  2442. //按1 地区,2 币种,3 汇率 分组计算
  2443. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  2444. foreach (var ctggfr in groupCTGGRFeeDatas)
  2445. {
  2446. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  2447. if (ctggfr_curr.Count() > 0)
  2448. {
  2449. foreach (var curr in ctggfr_curr)
  2450. {
  2451. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  2452. if (ctggfr_rate.Count() > 0)
  2453. {
  2454. foreach (var rate in ctggfr_rate)
  2455. {
  2456. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  2457. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  2458. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2459. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2460. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2461. }
  2462. }
  2463. else
  2464. {
  2465. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2466. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2467. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2468. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2469. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2470. }
  2471. }
  2472. }
  2473. else
  2474. {
  2475. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2476. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2477. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2478. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2479. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2480. }
  2481. }
  2482. foreach (var item in groupCTGGRFeeViews)
  2483. {
  2484. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2485. {
  2486. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2487. }
  2488. if (item.DatePrice != null)
  2489. {
  2490. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  2491. }
  2492. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  2493. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  2494. //CTGGRCNYTotalPrice += item.CNYPrice;
  2495. }
  2496. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  2497. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  2498. #endregion
  2499. #region 机票预订费用
  2500. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2501. //ccp.RMBPrice As CNYPrice
  2502. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2503. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2504. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2505. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2506. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  2507. atr.CType
  2508. From Grp_AirTicketReservations atr
  2509. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2510. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2511. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2512. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2513. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2514. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2515. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2516. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2517. string str = "";
  2518. List<dynamic> airClientPris = new List<dynamic>();
  2519. decimal AirCNYTotalPrice = 0.00M;
  2520. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  2521. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  2522. //if (groupAirFeeViews.Count > 0)
  2523. //{
  2524. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  2525. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  2526. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  2527. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  2528. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  2529. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  2530. //}
  2531. int Index = 0;
  2532. foreach (var item in groupAirFeeViews)
  2533. {
  2534. if (item.AirId > 2924)
  2535. {
  2536. string itemClientName = "";
  2537. if (!string.IsNullOrEmpty(item.ClientName))
  2538. {
  2539. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2540. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2541. if (m_EnName.Success || m_ZHName.Success)
  2542. {
  2543. itemClientName = item.ClientName;
  2544. decimal unitCost = 0.00M;
  2545. AirCNYTotalPrice += item.CNYPrice;
  2546. continue;
  2547. }
  2548. string[] clientIds = new string[] { };
  2549. if (item.ClientName.Contains(','))
  2550. {
  2551. clientIds = item.ClientName.Split(',');
  2552. }
  2553. else
  2554. {
  2555. clientIds = new string[] { item.ClientName };
  2556. }
  2557. if (clientIds.Length > 0)
  2558. {
  2559. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  2560. if (output.Contains(-1))
  2561. {
  2562. itemClientName += $@"行程单";
  2563. output = output.Where(val => val != -1).ToArray();
  2564. }
  2565. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2566. decimal unitCost = 0.00M;
  2567. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  2568. int clienIndex = 1;
  2569. foreach (var client in clients)
  2570. {
  2571. airClientPris.Add(new
  2572. {
  2573. CnName = client.LastName + client.FirstName,
  2574. EnName = client.Pinyin,
  2575. Price = unitCost,
  2576. AirType = item.AirTypeName
  2577. });
  2578. string six = "";
  2579. if (client.Sex == 0) six = "Mr";
  2580. else if (client.Sex == 1) six = "Ms";
  2581. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  2582. clienIndex++;
  2583. }
  2584. }
  2585. }
  2586. item.ClientName = itemClientName;
  2587. }
  2588. else
  2589. {
  2590. string clientPinYinName = "";
  2591. decimal unitCost = 0.00M;
  2592. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  2593. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  2594. Regex r = new Regex("[0-9]");
  2595. string name1 = item.ClientName;
  2596. name1 = r.Replace(name1, "");
  2597. string[] clientNames = name1.Split('.');
  2598. for (int i = 0; i < item.ClientNum; i++)
  2599. {
  2600. string name = "";
  2601. if (clientNames.Length > 0)
  2602. {
  2603. int index = i + 1;
  2604. if (index < clientNames.Length)
  2605. {
  2606. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  2607. if (!string.IsNullOrEmpty(name))
  2608. {
  2609. airClientPris.Add(new
  2610. {
  2611. CnName = name,
  2612. EnName = name,
  2613. Price = unitCost,
  2614. AirType = item.AirTypeName
  2615. });
  2616. }
  2617. //if (name.Length > 0)
  2618. //{
  2619. // string nameLastStr = name[name.Length - 1].ToString();
  2620. // if (nameLastStr.IsNumeric())
  2621. // {
  2622. // name = name.Substring(0, name.Length - 1).Trim();
  2623. // }
  2624. //}
  2625. }
  2626. }
  2627. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  2628. }
  2629. }
  2630. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2631. {
  2632. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2633. }
  2634. AirCNYTotalPrice += item.CNYPrice;
  2635. }
  2636. _geView.GroupAirFeeViews = groupAirFeeViews;
  2637. if (airClientPris.Count > 0)
  2638. {
  2639. var peoplePriStr = "";
  2640. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  2641. .Select(group => group.First())
  2642. .ToList();
  2643. int airClientPrisIndex = 1;
  2644. foreach (var item in airClientPris1)
  2645. {
  2646. decimal price = 0.00M;
  2647. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  2648. foreach (var pri in prices)
  2649. {
  2650. price += pri.Price;
  2651. }
  2652. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  2653. airClientPrisIndex++;
  2654. }
  2655. if (!string.IsNullOrEmpty(peoplePriStr))
  2656. {
  2657. str = $@"其中:{peoplePriStr}";
  2658. }
  2659. //经济舱均价
  2660. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  2661. if (airJJCPris.Count > 0)
  2662. {
  2663. decimal jjcTotalPrice = 0.00M;
  2664. foreach (var item in airJJCPris)
  2665. {
  2666. jjcTotalPrice += item.Price;
  2667. }
  2668. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  2669. .Select(group => group.First())
  2670. .ToList().Count;
  2671. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  2672. }
  2673. //公务舱均价
  2674. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  2675. if (airGWCPris.Count > 0)
  2676. {
  2677. decimal gwcTotalPrice = 0.00M;
  2678. foreach (var item in airGWCPris)
  2679. {
  2680. gwcTotalPrice += item.Price;
  2681. }
  2682. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  2683. .Select(group => group.First())
  2684. .ToList().Count;
  2685. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  2686. }
  2687. }
  2688. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  2689. #endregion
  2690. #region 签证费用
  2691. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2692. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2693. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2694. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  2695. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2696. From Grp_VisaInfo vi
  2697. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2698. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2699. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2700. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2701. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2702. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2703. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2704. decimal VisaCNYTotalPirce = 0.00M;
  2705. foreach (var item in groupVisaFeeViews)
  2706. {
  2707. string itemClientName = "";
  2708. string visaClients = item.VisaClient;
  2709. if (!string.IsNullOrEmpty(visaClients))
  2710. {
  2711. string[] clientIds = new string[] { };
  2712. if (visaClients.Contains(','))
  2713. {
  2714. clientIds = visaClients.Split(',');
  2715. }
  2716. else
  2717. {
  2718. clientIds = new string[] { visaClients };
  2719. }
  2720. if (clientIds.Length > 0)
  2721. {
  2722. List<int> clientIds1 = new List<int>() { };
  2723. foreach (var clientIdStr in clientIds)
  2724. {
  2725. if (clientIdStr.IsNumeric())
  2726. {
  2727. clientIds1.Add(int.Parse(clientIdStr));
  2728. }
  2729. }
  2730. if (clientIds1.Count > 0)
  2731. {
  2732. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  2733. foreach (var client in clients)
  2734. {
  2735. itemClientName += $"{client.LastName + client.FirstName},";
  2736. }
  2737. }
  2738. else
  2739. {
  2740. itemClientName = visaClients;
  2741. }
  2742. }
  2743. }
  2744. if (itemClientName.Length > 0)
  2745. {
  2746. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2747. }
  2748. item.VisaClient = itemClientName;
  2749. VisaCNYTotalPirce += item.CNYPrice;
  2750. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2751. {
  2752. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2753. }
  2754. }
  2755. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  2756. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  2757. #endregion
  2758. #region 邀请/公务活动 CTable = 81
  2759. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2760. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2761. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2762. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2763. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  2764. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  2765. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2766. From Grp_InvitationOfficialActivities ioa
  2767. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2768. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2769. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2770. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2771. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2772. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2773. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2774. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2775. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2776. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2777. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2778. #region 邀请/公务活动 - 模拟数据
  2779. //if (groupInvitationalFeeViews.Count < 1)
  2780. //{
  2781. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2782. // {
  2783. // IOAId = 0,
  2784. // IOADiId = 2334,
  2785. // InviterArea = "模拟数据-邀请方地区",
  2786. // Inviter = "模拟数据-邀请方",
  2787. // InviteTime = "2023-10-10",
  2788. // InviteCost = 100.00M,
  2789. // InviteCurrency = "EUR",
  2790. // SendCost = 100.00M,
  2791. // SendCurrency = "EUR",
  2792. // EventsCost = 10000.00M,
  2793. // EventsCurrency = "EUR",
  2794. // TranslateCost = 300.00M,
  2795. // TranslateCurrency = "EUR",
  2796. // PayMoney = 10500.00M,
  2797. // PaymentCurrency = "EUR",
  2798. // CNYPrice = 76765.50M,
  2799. // Payee = "模拟数据-收款方",
  2800. // AuditGMDate = "2023-12-05",
  2801. // OrbitalPrivateTransfer = 1,
  2802. // PayWay = "刷卡",
  2803. // IsPay = 1,
  2804. // Applicant = "刘华举"
  2805. // });
  2806. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2807. // {
  2808. // IOAId = 0,
  2809. // IOADiId = 2334,
  2810. // InviterArea = "模拟数据-邀请方地区",
  2811. // Inviter = "模拟数据-邀请方",
  2812. // InviteTime = "2023-10-10",
  2813. // InviteCost = 100.00M,
  2814. // InviteCurrency = "EUR",
  2815. // SendCost = 100.00M,
  2816. // SendCurrency = "EUR",
  2817. // EventsCost = 10000.00M,
  2818. // EventsCurrency = "EUR",
  2819. // TranslateCost = 300.00M,
  2820. // TranslateCurrency = "EUR",
  2821. // PayMoney = 10500.00M,
  2822. // PaymentCurrency = "EUR",
  2823. // CNYPrice = 76765.50M,
  2824. // Payee = "模拟数据-收款方",
  2825. // AuditGMDate = "2023-12-05",
  2826. // OrbitalPrivateTransfer = 1,
  2827. // PayWay = "刷卡",
  2828. // IsPay = 1,
  2829. // Applicant = "刘华举"
  2830. // });
  2831. //}
  2832. #endregion
  2833. decimal InvitationalCNYTotalPrice = 0.00M;
  2834. foreach (var item in groupInvitationalFeeViews)
  2835. {
  2836. InvitationalCNYTotalPrice += item.CNYPrice2;
  2837. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2838. {
  2839. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2840. }
  2841. string currencyRateStr = "";
  2842. List<string> currencys = new List<string>();
  2843. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  2844. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  2845. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  2846. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  2847. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  2848. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  2849. item.CurrencyRateStr = currencyRateStr;
  2850. }
  2851. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  2852. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  2853. #endregion
  2854. #region 保险费用
  2855. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2856. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  2857. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2858. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2859. From Grp_Customers ic
  2860. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  2861. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2862. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2863. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2864. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2865. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  2866. decimal InsuranceCNYTotalPrice = 0.00M;
  2867. foreach (var item in groupInsuranceFeeViews)
  2868. {
  2869. InsuranceCNYTotalPrice += item.CNYPrice;
  2870. string itemClientName = "";
  2871. string insClients = item.ClientName;
  2872. if (!string.IsNullOrEmpty(insClients))
  2873. {
  2874. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2875. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2876. //if (m_EnName.Success || m_ZHName.Success)
  2877. //{
  2878. // itemClientName = insClients;
  2879. // continue;
  2880. //}
  2881. string[] clientIds = new string[] { };
  2882. if (insClients.Contains(','))
  2883. {
  2884. clientIds = insClients.Split(',');
  2885. }
  2886. else
  2887. {
  2888. clientIds = new string[] { insClients };
  2889. }
  2890. if (clientIds.Length > 0)
  2891. {
  2892. List<int> output = new List<int>();
  2893. foreach (var clientId in clientIds)
  2894. {
  2895. if (clientId.IsNumeric())
  2896. {
  2897. output.Add(int.Parse(clientId));
  2898. }
  2899. }
  2900. if (output.Count > 0)
  2901. {
  2902. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2903. foreach (var client in clients)
  2904. {
  2905. itemClientName += $"{client.LastName + client.FirstName},";
  2906. }
  2907. if (itemClientName.Length > 0)
  2908. {
  2909. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2910. }
  2911. }
  2912. else
  2913. {
  2914. itemClientName = insClients;
  2915. }
  2916. }
  2917. }
  2918. item.ClientName = itemClientName;
  2919. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2920. {
  2921. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2922. }
  2923. }
  2924. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  2925. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  2926. #endregion
  2927. #region 其他款项费用 98
  2928. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  2929. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2930. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  2931. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2932. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  2933. From Grp_DecreasePayments dp
  2934. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  2935. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2936. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2937. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2938. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  2939. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2940. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  2941. #region 保险费用 - 模拟数据
  2942. //if (groupDecreaseFeeViews.Count < 1)
  2943. //{
  2944. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  2945. // {
  2946. // DPId = 0,
  2947. // DPDiId = 2334,
  2948. // PriceName = "模拟数据-费用名称",
  2949. // PayMoney = 1000.00M,
  2950. // PayMoneyCurrency = "CNY",
  2951. // DayRate = 1.0000M,
  2952. // CNYPrice = 1.0000M,
  2953. // AuditGMDate = "2023-12-10 12:13:00",
  2954. // Payee = "模拟数据-付款方",
  2955. // OrbitalPrivateTransfer = 1,
  2956. // PayWay = "现金",
  2957. // IsPay = 1,
  2958. // Applicant = "刘华举"
  2959. // });
  2960. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  2961. // {
  2962. // DPId = 0,
  2963. // DPDiId = 2334,
  2964. // PriceName = "模拟数据-费用名称",
  2965. // PayMoney = 1000.00M,
  2966. // PayMoneyCurrency = "CNY",
  2967. // DayRate = 1.0000M,
  2968. // CNYPrice = 1.0000M,
  2969. // AuditGMDate = "2023-12-10 12:13:00",
  2970. // Payee = "模拟数据-付款方",
  2971. // OrbitalPrivateTransfer = 1,
  2972. // PayWay = "现金",
  2973. // IsPay = 1,
  2974. // Applicant = "刘华举"
  2975. // });
  2976. //}
  2977. #endregion
  2978. decimal DecreaseCNYTotalPrice = 0.00M;
  2979. foreach (var item in groupDecreaseFeeViews)
  2980. {
  2981. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  2982. DecreaseCNYTotalPrice += item.CNYPrice;
  2983. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2984. {
  2985. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2986. }
  2987. }
  2988. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  2989. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  2990. #endregion
  2991. #region 公司内部操作人员提成
  2992. var royaltyDatas = await _sqlSugar
  2993. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  2994. new JoinQueryInfos(
  2995. JoinType.Left, rc.UserId == u1.Id,
  2996. JoinType.Left, rc.CreateUserId == u2.Id
  2997. ))
  2998. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  2999. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  3000. {
  3001. GroupId = rc.TeamId,
  3002. OverviewInfo = rc.Temp,
  3003. DetailedInfo = rc.ChiArr,
  3004. Amount = rc.Price,
  3005. IsConfirm = rc.IsConfirm,
  3006. IsSeed = rc.IsSeed,
  3007. RoyaltyUserName = u1.CnName,
  3008. CreateUserName = u2.CnName,
  3009. CreateTime = rc.CreateTime
  3010. })
  3011. .ToListAsync();
  3012. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  3013. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  3014. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  3015. #endregion
  3016. _view.GroupExpenditure = _geView;
  3017. #endregion
  3018. /*
  3019. * 团组报表计算方式
  3020. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3021. * 应收金额 = 应收表.Sum()
  3022. * 已收金额 = 已收表.Sum()
  3023. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3024. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3025. *
  3026. */
  3027. decimal _totalExpenditure = 0.00M; //总支出
  3028. decimal _amountReceivable = 0.00M; //应收金额
  3029. decimal _amountReceived = 0.00M; //已收金额
  3030. decimal _receivableProfit = 0.00M; //应收利润
  3031. decimal _receivedProfit = 0.00M; //已收利润
  3032. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3033. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  3034. _amountReceivable = frTotalAmount;
  3035. _amountReceived = prTotalAmount;
  3036. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3037. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3038. _view.FeeTotalStr = string.Format(@$"<span>
  3039. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  3040. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  3041. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  3042. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  3043. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  3044. </span>");
  3045. index1++;
  3046. _views.Add(new GroupStatisticsInfo()
  3047. {
  3048. Index = index1,
  3049. Id = info.Id,
  3050. GroupName = info.TeamName,
  3051. VisitDate = info.VisitDate,
  3052. Receivable = Math.Floor(_amountReceivable * 100) / 100,
  3053. Cost = Math.Floor(_totalExpenditure * 100) / 100,
  3054. Grossprofit = Math.Floor((_amountReceivable - _totalExpenditure) * 100) / 100,
  3055. });
  3056. }
  3057. return Ok(JsonView(true, "查询成功!", _views));
  3058. }
  3059. private class GroupStatisticsInfo
  3060. {
  3061. public int Index { get; set; }
  3062. public int Id { get; set; }
  3063. public string GroupName { get; set; }
  3064. public DateTime VisitDate { get; set; }
  3065. public decimal Receivable { get; set; }
  3066. public decimal Cost { get; set; }
  3067. public decimal Grossprofit { get; set; }
  3068. }
  3069. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  3070. {
  3071. if (designer == null) return;
  3072. if (sheet == null) return;
  3073. if (style == null) return;
  3074. if (dt == null) return;
  3075. if (string.IsNullOrEmpty(startRange)) return;
  3076. if (string.IsNullOrEmpty(endRange)) return;
  3077. for (int i = 0; i < dt.Rows.Count; i++)
  3078. {
  3079. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  3080. if (string.IsNullOrEmpty(isPayStr)) continue;
  3081. if (isPayStr.Contains("未付款"))
  3082. {
  3083. var excelIndex = startIndex + i;
  3084. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  3085. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  3086. }
  3087. }
  3088. }
  3089. #endregion
  3090. #region 报表/折线图统计
  3091. //企业利润-团组利润
  3092. //企业利润-会务利润
  3093. /// <summary>
  3094. /// 企业利润
  3095. /// Details
  3096. /// 待添加权限验证
  3097. /// </summary>
  3098. /// <param name="_dto">团组列表请求dto</param>
  3099. /// <returns></returns>
  3100. [HttpPost("PostCorporateProfit")]
  3101. //[JsonConverter(typeof(DecimalConverter), 2)]
  3102. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3103. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  3104. {
  3105. #region 参数验证
  3106. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3107. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3108. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3109. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  3110. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  3111. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3112. #region 页面操作权限验证
  3113. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3114. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3115. #endregion
  3116. string sqlWhere = string.Empty;
  3117. //起止时间
  3118. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3119. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3120. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3121. //业务类型
  3122. List<int> groupTypeId = new List<int>();
  3123. if (_dto.BusinessType == 2) //团组
  3124. {
  3125. groupTypeId.AddRange(new List<int>() {
  3126. 38, // 政府团
  3127. 39, // 企业团
  3128. 40, // 散客团
  3129. 1048 // 高校团
  3130. });
  3131. }
  3132. else if (_dto.BusinessType == 3) //会务
  3133. {
  3134. groupTypeId.AddRange(new List<int>() {
  3135. 102, // 未知
  3136. 248, // 非团组
  3137. 302, // 成都-会务活动
  3138. 691, // 四川-会务活动
  3139. 762, // 四川-赛事项目收入
  3140. 1047 // 成都-赛事项目收入
  3141. });
  3142. }
  3143. if (groupTypeId.Count > 0)
  3144. {
  3145. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  3146. }
  3147. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3148. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3149. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3150. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  3151. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  3152. List<MonthInfo> months = new List<MonthInfo>();
  3153. if (_dto.StatisticsType == 1) //月份
  3154. {
  3155. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  3156. }
  3157. else if (_dto.StatisticsType == 1) //季度
  3158. {
  3159. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  3160. }
  3161. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  3162. foreach (var item in months)
  3163. {
  3164. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  3165. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  3166. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  3167. _view.Add(new CorporateProfitMonthView()
  3168. {
  3169. Month = item.Month,
  3170. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  3171. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  3172. });
  3173. }
  3174. return Ok(JsonView(true, "操作成功!", _view));
  3175. #endregion
  3176. }
  3177. /// <summary>
  3178. /// 计算团组利润
  3179. /// </summary>
  3180. /// <param name="diIds"></param>
  3181. /// <returns></returns>
  3182. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  3183. {
  3184. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  3185. if (diIds.Count < 1)
  3186. {
  3187. return corporateProfits;
  3188. }
  3189. #region 计算团组利润
  3190. /*
  3191. * 团组报表计算方式
  3192. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3193. * 应收金额 = 应收表.Sum()
  3194. * 已收金额 = 已收表.Sum()
  3195. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3196. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3197. *
  3198. */
  3199. string diIdStr = string.Join(",", diIds);
  3200. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  3201. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  3202. #region 费用类型 币种,转账,客户信息
  3203. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  3204. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  3205. #endregion
  3206. foreach (var _diId in diIds)
  3207. {
  3208. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  3209. #region 团组收入
  3210. /*
  3211. * 应收报表
  3212. */
  3213. decimal frTotalAmount = 0.00M;//应收总金额
  3214. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  3215. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  3216. From Fin_ForeignReceivables fr
  3217. Left Join Sys_SetData sd On fr.Currency = sd.Id
  3218. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  3219. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  3220. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  3221. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  3222. /*
  3223. * 已收报表
  3224. */
  3225. decimal prTotalAmount = 0.00M;//已收总金额
  3226. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  3227. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  3228. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  3229. From Fin_ProceedsReceived pr
  3230. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  3231. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  3232. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  3233. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  3234. prTotalAmount = _prViews.Sum(it => it.Price);
  3235. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  3236. /*
  3237. * 超支费用
  3238. */
  3239. decimal exTotalAmount = 0.00M;
  3240. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  3241. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3242. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  3243. From OA2023DB.dbo.Fin_GroupExtraCost gec
  3244. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  3245. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3246. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3247. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3248. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3249. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  3250. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  3251. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  3252. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  3253. /*
  3254. * 收款退还
  3255. */
  3256. decimal promTotalAmount = 0.00M;// 收款退还总金额
  3257. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  3258. //删除了 And prom.PriceType = 1
  3259. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  3260. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  3261. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  3262. From Fin_PaymentRefundAndOtherMoney prom
  3263. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  3264. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3265. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  3266. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  3267. And prom.DiId = {0} Order By PrCreateTime", _diId);
  3268. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  3269. foreach (var ropItem in _promDatas)
  3270. {
  3271. string thisCueencyCode = "Unknown";
  3272. string thisCueencyName = "Unknown";
  3273. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  3274. if (currency != null)
  3275. {
  3276. thisCueencyCode = currency.Name;
  3277. thisCueencyName = currency.Remark;
  3278. }
  3279. string orbitalPrivateTransferStr = "Unknown";
  3280. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  3281. if (orbitalPrivateTransfer != null)
  3282. {
  3283. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  3284. }
  3285. string payStr = "Unknown";
  3286. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  3287. if (pay != null)
  3288. {
  3289. payStr = pay.Name;
  3290. }
  3291. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  3292. {
  3293. Id = ropItem.Id,
  3294. DiId = ropItem.DIId,
  3295. PriceName = ropItem.PrPriceName,
  3296. PayCurrencyCode = thisCueencyCode,
  3297. PayCurrencyName = thisCueencyName,
  3298. Price = ropItem.PrPrice,
  3299. CNYPrice = ropItem.RMBPrice,
  3300. ThisRate = ropItem.DayRate,
  3301. Payee = ropItem.Payee,
  3302. PayTime = ropItem.AuditGMDate,
  3303. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  3304. PayType = payStr,
  3305. IsPay = ropItem.IsPay,
  3306. Applicant = ropItem.Appliction
  3307. };
  3308. _promView.Add(gsd_PaymentRefund);
  3309. }
  3310. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  3311. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  3312. #endregion
  3313. #region 团组支出
  3314. GroupExpenditureView _geView = new GroupExpenditureView();
  3315. #region 酒店预定费用
  3316. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  3317. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  3318. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  3319. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  3320. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  3321. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  3322. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  3323. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  3324. From Grp_HotelReservations hr
  3325. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  3326. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3327. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3328. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3329. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3330. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  3331. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  3332. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  3333. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  3334. Order By CheckInDate Asc", _diId);
  3335. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  3336. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  3337. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  3338. #endregion
  3339. #region 地接费用
  3340. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  3341. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  3342. sd2.name As PaymentCurrency,ccp.PayPercentage,
  3343. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  3344. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  3345. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3346. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  3347. From Grp_CarTouristGuideGroundReservations ctggr
  3348. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  3349. cggrc.PriceContent
  3350. From Grp_CarTouristGuideGroundReservationsContent cggrc
  3351. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  3352. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  3353. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  3354. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  3355. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  3356. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  3357. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  3358. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3359. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  3360. Order By CreateTime", _diId);
  3361. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  3362. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3363. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  3364. #endregion
  3365. #region 机票预订费用
  3366. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  3367. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  3368. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  3369. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  3370. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  3371. From Grp_AirTicketReservations atr
  3372. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  3373. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3374. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3375. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3376. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  3377. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3378. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  3379. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  3380. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  3381. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  3382. #endregion
  3383. #region 签证费用
  3384. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  3385. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3386. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3387. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  3388. From Grp_VisaInfo vi
  3389. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  3390. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3391. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3392. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3393. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3394. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  3395. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  3396. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  3397. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  3398. #endregion
  3399. #region 邀请/公务活动 CTable = 81
  3400. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  3401. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  3402. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  3403. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  3404. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3405. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  3406. From Grp_InvitationOfficialActivities ioa
  3407. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  3408. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3409. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3410. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  3411. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  3412. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  3413. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  3414. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  3415. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3416. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  3417. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  3418. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  3419. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  3420. #endregion
  3421. #region 保险费用
  3422. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3423. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  3424. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3425. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3426. From Grp_Customers ic
  3427. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3428. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3429. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3430. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3431. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  3432. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3433. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  3434. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  3435. #endregion
  3436. #region 其他款项费用 98
  3437. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3438. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3439. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3440. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3441. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3442. From Grp_DecreasePayments dp
  3443. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3444. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3445. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3446. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3447. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  3448. Order By CreateTime", _diId);
  3449. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3450. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3451. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  3452. #endregion
  3453. #endregion
  3454. /*
  3455. * 团组报表计算方式
  3456. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3457. * 应收金额 = 应收表.Sum()
  3458. * 已收金额 = 已收表.Sum()
  3459. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3460. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3461. *
  3462. */
  3463. decimal _totalExpenditure = 0.00M; //总支出
  3464. decimal _amountReceivable = 0.00M; //应收金额
  3465. decimal _amountReceived = 0.00M; //已收金额
  3466. decimal _receivableProfit = 0.00M; //应收利润
  3467. decimal _receivedProfit = 0.00M; //已收利润
  3468. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3469. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  3470. _amountReceivable = frTotalAmount;
  3471. _amountReceived = prTotalAmount;
  3472. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3473. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3474. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  3475. corporateProfits.Add(new CorporateProfit()
  3476. {
  3477. DiId = _diId,
  3478. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  3479. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  3480. TotalExpenditure = _totalExpenditure,
  3481. ExpenditureItem = expenditureInfos,
  3482. AmountReceivable = _amountReceivable,
  3483. AmountReceived = _amountReceived,
  3484. ReceivableProfit = _receivableProfit,
  3485. ReceivedProfit = _receivedProfit,
  3486. });
  3487. }
  3488. #endregion
  3489. return corporateProfits;
  3490. }
  3491. //未来预测-地区接团/出团量
  3492. //未来预测-地区酒店预订量
  3493. //未来预测-地区机票预订量
  3494. //未来预测-地区车辆预订量
  3495. /// <summary>
  3496. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  3497. /// Details
  3498. /// 待添加权限验证
  3499. /// </summary>
  3500. /// <param name="_dto">团组列表请求dto</param>
  3501. /// <returns></returns>
  3502. [HttpPost("PostRegionalBookingsNumber")]
  3503. //[JsonConverter(typeof(DecimalConverter), 2)]
  3504. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3505. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  3506. {
  3507. #region 参数验证
  3508. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3509. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3510. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  3511. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3512. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3513. #region 页面操作权限验证
  3514. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3515. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3516. #endregion
  3517. string sqlWhere = string.Empty;
  3518. //起止时间
  3519. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3520. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3521. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3522. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3523. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3524. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3525. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  3526. foreach (var item in groupInfos)
  3527. {
  3528. var data = await GroupBookingsNumber(_dto.Type, item);
  3529. if (data.TypeItem.Count > 0)
  3530. {
  3531. datas.Add(data);
  3532. }
  3533. }
  3534. //类型处理
  3535. if (_dto.Type == 1)//接团
  3536. {
  3537. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  3538. dynamic groupData = null;
  3539. foreach (var item in datas)
  3540. {
  3541. if (item.TypeItem.Count > 0)
  3542. {
  3543. foreach (var item1 in item.TypeItem)
  3544. {
  3545. if (item1.RegionItem.Count > 0)
  3546. {
  3547. GroupInfo groupInfo = new GroupInfo()
  3548. {
  3549. DiId = item.DiId,
  3550. TeamName = item.GroupName,
  3551. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3552. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3553. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3554. };
  3555. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  3556. }
  3557. }
  3558. }
  3559. }
  3560. var viewsGroup = views.GroupBy(it => it.Name);
  3561. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  3562. foreach (var item in viewsGroup)
  3563. {
  3564. List<GroupInfo> infos = new List<GroupInfo>();
  3565. foreach (var item1 in item)
  3566. {
  3567. infos.AddRange(item1.GroupItem);
  3568. }
  3569. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  3570. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  3571. }
  3572. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3573. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  3574. }
  3575. else if (_dto.Type == 2)
  3576. {
  3577. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  3578. foreach (var item in datas)
  3579. {
  3580. if (item.TypeItem.Count > 0)
  3581. {
  3582. foreach (var item1 in item.TypeItem)
  3583. {
  3584. if (item1.RegionItem.Count > 0)
  3585. {
  3586. foreach (var item2 in item1.RegionItem)
  3587. {
  3588. GroupInfo groupInfo = new GroupInfo()
  3589. {
  3590. DiId = item.DiId,
  3591. TeamName = item.GroupName,
  3592. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3593. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3594. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3595. };
  3596. List<HotelInfo> hotels = new List<HotelInfo>();
  3597. foreach (var item3 in item2.Data)
  3598. {
  3599. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  3600. HotelInfo hotelInfo = new HotelInfo()
  3601. {
  3602. HotelName = statisticsHotelInfos.HotelName,
  3603. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  3604. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  3605. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  3606. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  3607. GroupInfo = groupInfo
  3608. };
  3609. hotels.Add(hotelInfo);
  3610. }
  3611. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  3612. }
  3613. }
  3614. }
  3615. }
  3616. }
  3617. var viewsGroup = views.GroupBy(it => it.Name);
  3618. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  3619. foreach (var item in viewsGroup)
  3620. {
  3621. List<HotelInfo> infos = new List<HotelInfo>();
  3622. foreach (var item1 in item)
  3623. {
  3624. infos.AddRange(item1.HotelItem);
  3625. }
  3626. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  3627. }
  3628. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3629. return Ok(JsonView(true, "操作成功!", views, views.Count));
  3630. }
  3631. return Ok(JsonView(false, "操作失败!"));
  3632. #endregion
  3633. }
  3634. /// <summary>
  3635. /// 计算团组ALLType预订数量
  3636. /// </summary>
  3637. /// <param name="diIds"></param>
  3638. /// <returns></returns>
  3639. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  3640. {
  3641. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  3642. if (info == null)
  3643. {
  3644. return _view;
  3645. }
  3646. _view.DiId = info.Id;
  3647. _view.GroupName = info.TeamName;
  3648. List<TypeInfo> _types = new List<TypeInfo>();
  3649. #region 计算团组ALLType预订数量
  3650. if (type == 1)
  3651. {
  3652. //接团 客户集团所在地区
  3653. string group_region = string.Empty;
  3654. int group_number = 0;
  3655. if (!string.IsNullOrEmpty(info.ClientUnit))
  3656. {
  3657. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  3658. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  3659. .FirstAsync();
  3660. if (_NewClientData != null)
  3661. {
  3662. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  3663. if (regionInfo != null)
  3664. {
  3665. group_region = regionInfo.Name.Replace("级", "");
  3666. group_number++;
  3667. }
  3668. }
  3669. }
  3670. if (group_number > 0)
  3671. {
  3672. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  3673. }
  3674. }
  3675. else if (type == 2)
  3676. {
  3677. //酒店
  3678. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3679. if (hotelInfos.Count > 0)
  3680. {
  3681. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  3682. foreach (var item in hotelInfos)
  3683. {
  3684. var hotelNumberInfo = new StatisticsHotelInfo()
  3685. {
  3686. HotelName = item.HotelName,
  3687. SingleRoomNum = item.SingleRoomCount,
  3688. DoubleRoomNum = item.DoubleRoomCount,
  3689. SuiteRoomNum = item.SuiteRoomCount,
  3690. OtherRoomNum = item.OtherRoomCount,
  3691. };
  3692. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  3693. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  3694. {
  3695. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  3696. if (hotelRegion != null)
  3697. {
  3698. hotelRegions.Remove(hotelRegion);
  3699. if (hotelRegion.Data.Count > 0)
  3700. {
  3701. hotelRegion.Data.Add(hotelNumberInfo);
  3702. }
  3703. hotelRegion.Number += hotelRoomTotal;
  3704. hotelRegions.Add(hotelRegion);
  3705. }
  3706. }
  3707. else
  3708. {
  3709. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  3710. }
  3711. }
  3712. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  3713. }
  3714. }
  3715. else if (type == 3)
  3716. {
  3717. //机票
  3718. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  3719. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  3720. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  3721. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  3722. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  3723. .ToListAsync();
  3724. if (airTicketInfos.Count > 0)
  3725. {
  3726. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  3727. foreach (var item in airTicketInfos)
  3728. {
  3729. var ticketClass = new
  3730. {
  3731. TiketClass = item.AirType,
  3732. Number = item.ClientNum
  3733. };
  3734. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  3735. {
  3736. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  3737. if (airTicketRegion != null)
  3738. {
  3739. airTicketRegions.Remove(airTicketRegion);
  3740. if (airTicketRegion.Data.Count > 0)
  3741. {
  3742. airTicketRegion.Data.Add(ticketClass);
  3743. }
  3744. airTicketRegion.Number += item.ClientNum;
  3745. airTicketRegions.Add(airTicketRegion);
  3746. }
  3747. }
  3748. else
  3749. {
  3750. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  3751. }
  3752. }
  3753. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  3754. }
  3755. }
  3756. else if (type == 4)
  3757. {
  3758. //车辆
  3759. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3760. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3761. if (opInfos.Count > 0)
  3762. {
  3763. List<RegionInfo> opRegions = new List<RegionInfo>();
  3764. foreach (var item in opInfos)
  3765. {
  3766. int carNum = 0;
  3767. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  3768. if (opContentInfo.Count > 0)
  3769. {
  3770. foreach (var item1 in opContentInfo)
  3771. {
  3772. if (item1.Price > 0 && item1.Count > 0)
  3773. {
  3774. carNum += item1.Count;
  3775. }
  3776. }
  3777. }
  3778. if (carNum > 0)
  3779. {
  3780. var opData = new
  3781. {
  3782. ServiceCompany = item.ServiceCompany,
  3783. BusName = item.BusName,
  3784. Numbuer = carNum
  3785. };
  3786. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  3787. {
  3788. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  3789. if (opRegion != null)
  3790. {
  3791. opRegions.Remove(opRegion);
  3792. if (opRegion.Data.Count > 0)
  3793. {
  3794. opRegion.Data.Add(opData);
  3795. }
  3796. opRegion.Number += carNum;
  3797. opRegions.Add(opRegion);
  3798. }
  3799. }
  3800. else
  3801. {
  3802. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  3803. }
  3804. }
  3805. }
  3806. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  3807. }
  3808. }
  3809. #endregion
  3810. _view.TypeItem = _types;
  3811. return _view;
  3812. }
  3813. #endregion
  3814. #region 市场部销售额
  3815. /// <summary>
  3816. /// 市场部销售额
  3817. /// Init 基础数据(公司/人员/年份/季度/月份)
  3818. /// </summary>
  3819. /// <param name="_dto">市场部销售额请求dto</param>
  3820. /// <returns></returns>
  3821. [HttpPost("PostMarketingSalesInitData")]
  3822. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3823. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  3824. {
  3825. #region 参数验证
  3826. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  3827. var validResult = await validationRules.ValidateAsync(_dto);
  3828. if (!validResult.IsValid)
  3829. {
  3830. var errors = new StringBuilder();
  3831. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3832. return Ok(JsonView(false, errors.ToString()));
  3833. }
  3834. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3835. #region 页面操作权限验证
  3836. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3837. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3838. #endregion
  3839. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  3840. .Select(it => new { id = it.Id, name = it.CompanyName })
  3841. .ToList();
  3842. List<int> companyIds = companyData.Select(it => it.id).ToList();
  3843. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  3844. .Select(it => it.JietuanOperator)
  3845. .ToList();
  3846. var userData = _sqlSugar.Queryable<Sys_Users>()
  3847. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  3848. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  3849. .ToList();
  3850. companyData.Insert(0, new { id = -1, name = "全部" });
  3851. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  3852. #region 年份
  3853. var dtData = new List<dynamic>();
  3854. int dt = DateTime.Now.Year;
  3855. for (int y = dt; y >= dt - 4; y--)
  3856. {
  3857. //季度
  3858. var quarterDatas = new List<dynamic>();
  3859. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  3860. for (int q = 0; q < 4; q++)
  3861. {
  3862. dynamic quarterData = null;
  3863. if (q == 0)
  3864. {
  3865. var monthDatas = new List<dynamic>();
  3866. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  3867. for (int m = 1; m < 4; m++)
  3868. {
  3869. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3870. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3871. }
  3872. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  3873. quarterData = new { name = "第一季度", monthData = monthDatas };
  3874. }
  3875. else if (q == 1)
  3876. {
  3877. var monthDatas = new List<dynamic>();
  3878. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  3879. for (int m = 4; m < 7; m++)
  3880. {
  3881. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3882. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3883. }
  3884. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  3885. quarterData = new { name = "第二季度", monthData = monthDatas };
  3886. }
  3887. else if (q == 2)
  3888. {
  3889. var monthDatas = new List<dynamic>();
  3890. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  3891. for (int m = 7; m < 10; m++)
  3892. {
  3893. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3894. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3895. }
  3896. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  3897. quarterData = new { name = "第三季度", monthData = monthDatas };
  3898. }
  3899. else if (q == 3)
  3900. {
  3901. var monthDatas = new List<dynamic>();
  3902. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  3903. for (int m = 10; m < 13; m++)
  3904. {
  3905. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  3906. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  3907. }
  3908. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  3909. quarterData = new { name = "第四季度", monthData = monthDatas };
  3910. }
  3911. quarterDatas.Add(quarterData);
  3912. }
  3913. dtData.Add(new
  3914. {
  3915. year = y,
  3916. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  3917. quarterData = quarterDatas,
  3918. });
  3919. }
  3920. #endregion
  3921. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  3922. #endregion
  3923. }
  3924. private static string ConvertToChinese(int month)
  3925. {
  3926. if (month < 1 || month > 12)
  3927. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  3928. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  3929. var dateTimeFormat = cultureInfo.DateTimeFormat;
  3930. return dateTimeFormat.GetMonthName(month);
  3931. }
  3932. /// <summary>
  3933. /// 市场部销售额
  3934. /// 年度/季度/月度 报表(同比)
  3935. /// </summary>
  3936. /// <param name="_dto">市场部销售额请求dto</param>
  3937. /// <returns></returns>
  3938. [HttpPost("PostMarketingSalesStatistics")]
  3939. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3940. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  3941. {
  3942. #region 参数验证
  3943. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3944. var validResult = await validationRules.ValidateAsync(_dto);
  3945. if (!validResult.IsValid)
  3946. {
  3947. var errors = new StringBuilder();
  3948. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3949. return Ok(JsonView(false, errors.ToString()));
  3950. }
  3951. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3952. #region 页面操作权限验证
  3953. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3954. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3955. #endregion
  3956. #endregion
  3957. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3958. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  3959. }
  3960. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  3961. {
  3962. //全部人员Id
  3963. //查询所有公司的市场部
  3964. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  3965. var userIds = new List<int>();
  3966. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  3967. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  3968. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  3969. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  3970. .ToListAsync();
  3971. userIds = userDatas.Select(it => it.Id).ToList();
  3972. if (companyId > 0)
  3973. {
  3974. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  3975. }
  3976. if (groupPickupUserId > 0)
  3977. {
  3978. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  3979. }
  3980. return userIds;
  3981. }
  3982. /// <summary>
  3983. /// 计算团组销售额
  3984. /// </summary>
  3985. /// <param name="companyId"></param>
  3986. /// <param name="groupPickupUserId"></param>
  3987. /// <param name="beginDt"></param>
  3988. /// <param name="endDt"></param>
  3989. /// <returns></returns>
  3990. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  3991. {
  3992. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  3993. var _view = new SalesYOYView();
  3994. List<int> userIds = new List<int>();
  3995. userIds = await GetUserIds(companyId, groupPickupUserId);
  3996. string userSqlWhere = "";
  3997. if (userIds.Count > 0)
  3998. {
  3999. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  4000. }
  4001. else
  4002. {
  4003. _view = new SalesYOYView
  4004. {
  4005. thisYearSales = "0.00",
  4006. lastYearSales = "0.00",
  4007. };
  4008. return _view;
  4009. }
  4010. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  4011. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  4012. // string salesSql = string.Format(@"
  4013. //SELECT
  4014. // 'ThisSales' As [Name],
  4015. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4016. //FROM
  4017. // (
  4018. // SELECT di.VisitDate,
  4019. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4020. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4021. // ) AS Sales
  4022. // FROM
  4023. // Grp_DelegationInfo di
  4024. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4025. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4026. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4027. // ) temp
  4028. //Union ALL
  4029. //SELECT
  4030. // 'LastSales' As [Name],
  4031. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4032. //FROM
  4033. // (
  4034. // SELECT di.VisitDate,
  4035. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4036. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4037. // ) AS Sales
  4038. // FROM
  4039. // Grp_DelegationInfo di
  4040. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4041. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4042. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4043. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4044. string salesSql = string.Format(@"
  4045. SELECT
  4046. 'ThisSales' As [Name],
  4047. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4048. FROM
  4049. (
  4050. SELECT di.VisitDate,
  4051. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4052. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4053. ) AS Sales
  4054. FROM
  4055. Grp_DelegationInfo di
  4056. WHERE di.IsDel = 0
  4057. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4058. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4059. ) temp
  4060. Union ALL
  4061. SELECT
  4062. 'LastSales' As [Name],
  4063. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4064. FROM
  4065. (
  4066. SELECT di.VisitDate,
  4067. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4068. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4069. ) AS Sales
  4070. FROM
  4071. Grp_DelegationInfo di
  4072. WHERE di.IsDel = 0
  4073. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4074. AND di.IsBid = 0
  4075. AND di.TeamName Not Like '%投标%'
  4076. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4077. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4078. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  4079. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  4080. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  4081. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  4082. return new SalesYOYView()
  4083. {
  4084. thisYearSales = thisSales.ToString("#0.00"),
  4085. lastYearSales = lastSales.ToString("#0.00"),
  4086. yoy = yoy.ToString("#0.00")
  4087. };
  4088. }
  4089. private class SalesView
  4090. {
  4091. public string Name { get; set; }
  4092. public decimal Sales { get; set; }
  4093. }
  4094. private class SalesYOYView
  4095. {
  4096. public string thisYearSales { get; set; }
  4097. public string lastYearSales { get; set; }
  4098. public string yoy { get; set; } = "1.00";
  4099. }
  4100. /// <summary>
  4101. /// 市场部销售额
  4102. /// 团组列表
  4103. /// </summary>
  4104. /// <param name="_dto">市场部销售额请求dto</param>
  4105. /// <returns></returns>
  4106. [HttpPost("PostMarketingSalesGroupList")]
  4107. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4108. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  4109. {
  4110. #region 参数验证
  4111. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4112. var validResult = await validationRules.ValidateAsync(_dto);
  4113. if (!validResult.IsValid)
  4114. {
  4115. var errors = new StringBuilder();
  4116. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4117. return Ok(JsonView(false, errors.ToString()));
  4118. }
  4119. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4120. #region 页面操作权限验证
  4121. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4122. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4123. #endregion
  4124. #endregion
  4125. string userSql = "";
  4126. List<int> userIds = new List<int>();
  4127. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4128. if (userIds.Count <= 0)
  4129. {
  4130. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4131. }
  4132. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4133. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4134. {
  4135. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4136. }
  4137. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4138. // string sql = string.Format(@$"SELECT
  4139. // ROW_NUMBER() OVER (
  4140. // ORDER BY
  4141. // CollectionDays
  4142. // ) AS RowNumber,
  4143. // *
  4144. //FROM
  4145. // (
  4146. // SELECT
  4147. // di.Id,
  4148. // di.TeamName,
  4149. // di.ClientUnit,
  4150. // di.ClientName,
  4151. // di.VisitDate,
  4152. // di.VisitPNumber,
  4153. // di.JietuanOperator,
  4154. // di.VisitEndDate,
  4155. // (
  4156. // SELECT
  4157. // CAST(
  4158. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4159. // ) AS GroupSales
  4160. // FROM
  4161. // Fin_ForeignReceivables
  4162. // WHERE
  4163. // IsDel = 0
  4164. // AND di.Id = Diid
  4165. // AND AddingWay IN (0, 1, 2)
  4166. // ) AS GroupSales,
  4167. // u.CnName AS GroupPickupUser,
  4168. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4169. // FROM
  4170. // Grp_DelegationInfo di
  4171. // WITH
  4172. // (NoLock)
  4173. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4174. // WHERE
  4175. // di.Isdel = 0
  4176. // AND di.IsSure = 1 {userSql}
  4177. // AND VisitDate Between '{beginDt}' And '{endDt}'
  4178. // ) Temp ");
  4179. string sql = string.Format(@$"SELECT
  4180. ROW_NUMBER() OVER (
  4181. ORDER BY
  4182. CollectionDays
  4183. ) AS RowNumber,
  4184. *
  4185. FROM
  4186. (
  4187. SELECT
  4188. di.Id,
  4189. di.TeamName,
  4190. di.ClientUnit,
  4191. di.ClientName,
  4192. di.VisitDate,
  4193. di.VisitPNumber,
  4194. di.JietuanOperator,
  4195. di.VisitEndDate,
  4196. (
  4197. SELECT
  4198. CAST(
  4199. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4200. ) AS GroupSales
  4201. FROM
  4202. Fin_ForeignReceivables
  4203. WHERE
  4204. IsDel = 0
  4205. AND di.Id = Diid
  4206. AND AddingWay IN (0, 1, 2)
  4207. ) AS GroupSales,
  4208. u.CnName AS GroupPickupUser,
  4209. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4210. FROM
  4211. Grp_DelegationInfo di
  4212. WITH
  4213. (NoLock)
  4214. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4215. WHERE
  4216. di.Isdel = 0
  4217. AND (
  4218. SELECT
  4219. CAST(
  4220. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4221. ) AS GroupSales
  4222. FROM
  4223. Fin_ForeignReceivables
  4224. WHERE
  4225. IsDel = 0
  4226. AND di.Id = Diid
  4227. AND AddingWay IN (0, 1, 2)
  4228. ) > 0
  4229. {userSql}
  4230. AND di.IsBid = 0
  4231. AND di.TeamName Not Like '%投标%'
  4232. AND VisitDate Between '{beginDt}' And '{endDt}'
  4233. ) Temp ");
  4234. RefAsync<int> total = 0;
  4235. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4236. return Ok(JsonView(true, "操作成功!", groupData, total));
  4237. }
  4238. /// <summary>
  4239. /// 市场部销售额
  4240. /// 团组列表Excel下载
  4241. /// </summary>
  4242. /// <param name="_dto">市场部销售额请求dto</param>
  4243. /// <returns></returns>
  4244. [HttpPost("PostMarketingSalesGroupExcel")]
  4245. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4246. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  4247. {
  4248. #region 参数验证
  4249. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4250. var validResult = await validationRules.ValidateAsync(_dto);
  4251. if (!validResult.IsValid)
  4252. {
  4253. var errors = new StringBuilder();
  4254. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4255. return Ok(JsonView(false, errors.ToString()));
  4256. }
  4257. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4258. #region 页面操作权限验证
  4259. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4260. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4261. #endregion
  4262. #endregion
  4263. string userSql = "";
  4264. var userIds = new List<int>();
  4265. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4266. if (userIds.Count <= 0)
  4267. {
  4268. return Ok(JsonView(false));
  4269. }
  4270. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4271. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4272. {
  4273. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4274. }
  4275. string beginDt = $"{_dto.BeginDt} 00:00:00",
  4276. endDt = $"{_dto.EndDt} 23:59:59";
  4277. string sql = string.Format(@$"SELECT
  4278. ROW_NUMBER() OVER (
  4279. ORDER BY
  4280. CollectionDays
  4281. ) AS RowNumber,
  4282. *
  4283. FROM
  4284. (
  4285. SELECT
  4286. di.Id,
  4287. di.TeamName,
  4288. di.ClientUnit,
  4289. di.ClientName,
  4290. di.VisitDate,
  4291. di.VisitPNumber,
  4292. di.JietuanOperator,
  4293. di.VisitEndDate,
  4294. (
  4295. SELECT
  4296. CAST(
  4297. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4298. ) AS GroupSales
  4299. FROM
  4300. Fin_ForeignReceivables
  4301. WHERE
  4302. IsDel = 0
  4303. AND di.Id = Diid
  4304. AND AddingWay IN (0, 1, 2)
  4305. ) AS GroupSales,
  4306. u.CnName AS GroupPickupUser,
  4307. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4308. FROM
  4309. Grp_DelegationInfo di
  4310. WITH
  4311. (NoLock)
  4312. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4313. WHERE
  4314. di.Isdel = 0
  4315. AND (
  4316. SELECT
  4317. CAST(
  4318. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4319. ) AS GroupSales
  4320. FROM
  4321. Fin_ForeignReceivables
  4322. WHERE
  4323. IsDel = 0
  4324. AND di.Id = Diid
  4325. AND AddingWay IN (0, 1, 2)
  4326. ) > 0
  4327. {userSql}
  4328. AND di.IsBid = 0
  4329. AND di.TeamName Not Like '%投标%'
  4330. AND VisitDate Between '{beginDt}' And '{endDt}'
  4331. ) Temp ");
  4332. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  4333. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  4334. //DataTable dt = GeneralMethod.
  4335. DataTable dt = CommonFun.GetDataTableFromIList(view);
  4336. dt.TableName = $"_view";
  4337. WorkbookDesigner designer = new WorkbookDesigner();
  4338. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  4339. designer.SetDataSource(dt);
  4340. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  4341. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  4342. designer.Process();
  4343. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  4344. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4345. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4346. return Ok(JsonView(true, "操作成功", new { url = rst }));
  4347. }
  4348. /// <summary>
  4349. /// 市场部销售额
  4350. /// 客户类型、客户等级 统计
  4351. /// </summary>
  4352. /// <param name="_dto">市场部销售额请求dto</param>
  4353. /// <returns></returns>
  4354. [HttpPost("PostMarketingSalesGroupStatistics")]
  4355. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4356. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  4357. {
  4358. #region 参数验证
  4359. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4360. var validResult = await validationRules.ValidateAsync(_dto);
  4361. if (!validResult.IsValid)
  4362. {
  4363. var errors = new StringBuilder();
  4364. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4365. return Ok(JsonView(false, errors.ToString()));
  4366. }
  4367. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4368. #region 页面操作权限验证
  4369. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4370. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4371. #endregion
  4372. #endregion
  4373. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4374. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4375. string userSql = "";
  4376. if (userIds.Count > 0)
  4377. {
  4378. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4379. }
  4380. else
  4381. {
  4382. if (_dto.PortType == 2 || _dto.PortType == 3)
  4383. {
  4384. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  4385. }
  4386. else
  4387. {
  4388. return Ok(JsonView(true, "操作成功!", new
  4389. {
  4390. customerTypeData = new List<object> { },
  4391. clientGradeData = new List<object> { }
  4392. }));
  4393. }
  4394. }
  4395. string sql = "";
  4396. if (_dto.StatisticsType == 1)
  4397. {
  4398. sql = string.Format(@$"Select
  4399. sd.[Name],
  4400. Count(*) As [Count]
  4401. From Grp_DelegationInfo di
  4402. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4403. Where di.Isdel = 0
  4404. And (
  4405. SELECT
  4406. CAST(
  4407. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4408. ) AS GroupSales
  4409. FROM
  4410. Fin_ForeignReceivables fr
  4411. WHERE
  4412. fr.IsDel = 0
  4413. AND di.Id = fr.Diid
  4414. AND AddingWay IN (0, 1, 2)
  4415. ) > 0
  4416. {userSql}
  4417. AND di.IsBid = 0
  4418. AND di.TeamName Not Like '%投标%'
  4419. And VisitDate Between '{beginDt}' And '{endDt}'
  4420. Group By [Name]
  4421. Order By Count Desc");
  4422. }
  4423. else if (_dto.StatisticsType == 2)
  4424. {
  4425. sql = string.Format(@$"Select
  4426. sd.[Name],
  4427. Count(*) As [Count]
  4428. From Grp_DelegationInfo di
  4429. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4430. Where di.Isdel = 0
  4431. And (
  4432. SELECT
  4433. CAST(
  4434. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4435. ) AS GroupSales
  4436. FROM
  4437. Fin_ForeignReceivables fr
  4438. WHERE
  4439. fr.IsDel = 0
  4440. AND di.Id = fr.Diid
  4441. AND AddingWay IN (0, 1, 2)
  4442. ) > 0
  4443. {userSql}
  4444. AND di.IsBid = 0
  4445. AND di.TeamName Not Like '%投标%'
  4446. And VisitDate Between '{beginDt}' And '{endDt}'
  4447. Group By [Name]
  4448. Order By Count Desc");
  4449. }
  4450. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  4451. if (_dto.PortType == 1)
  4452. {
  4453. string sql1 = string.Format(@$"Select
  4454. sd.[Name],
  4455. Count(*) As [Count]
  4456. From Grp_DelegationInfo di
  4457. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4458. Where di.Isdel = 0
  4459. And (
  4460. SELECT
  4461. CAST(
  4462. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4463. ) AS GroupSales
  4464. FROM
  4465. Fin_ForeignReceivables fr
  4466. WHERE
  4467. fr.IsDel = 0
  4468. AND di.Id = fr.Diid
  4469. AND AddingWay IN (0, 1, 2)
  4470. ) > 0
  4471. {userSql}
  4472. AND di.IsBid = 0
  4473. AND di.TeamName Not Like '%投标%'
  4474. And VisitDate Between '{beginDt}' And '{endDt}'
  4475. Group By [Name]
  4476. Order By Count Desc");
  4477. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4478. string sql2 = string.Format(@$"Select
  4479. sd.[Name],
  4480. Count(*) As [Count]
  4481. From Grp_DelegationInfo di
  4482. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4483. Where di.Isdel = 0
  4484. And (
  4485. SELECT
  4486. CAST(
  4487. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4488. ) AS GroupSales
  4489. FROM
  4490. Fin_ForeignReceivables fr
  4491. WHERE
  4492. fr.IsDel = 0
  4493. AND di.Id = fr.Diid
  4494. AND AddingWay IN (0, 1, 2)
  4495. ) > 0
  4496. {userSql}
  4497. AND di.IsBid = 0
  4498. AND di.TeamName Not Like '%投标%'
  4499. And VisitDate Between '{beginDt}' And '{endDt}'
  4500. Group By [Name]
  4501. Order By Count Desc");
  4502. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4503. return Ok(JsonView(true, "操作成功!", new
  4504. {
  4505. customerTypeData = customerTypeData,
  4506. clientGradeData = clientGradeData
  4507. }));
  4508. }
  4509. else if (_dto.PortType == 2 || _dto.PortType == 3)
  4510. {
  4511. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  4512. return Ok(JsonView(true, "操作成功!", data, data.Count));
  4513. }
  4514. else return Ok(JsonView(false, MsgTips.Port));
  4515. }
  4516. /// <summary>
  4517. /// 市场部销售额
  4518. /// 接单排名
  4519. /// </summary>
  4520. /// <param name="_dto">市场部销售额请求dto</param>
  4521. /// <returns></returns>
  4522. [HttpPost("PostMarketingSalesOrderRanking")]
  4523. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4524. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  4525. {
  4526. #region 参数验证
  4527. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4528. var validResult = await validationRules.ValidateAsync(_dto);
  4529. if (!validResult.IsValid)
  4530. {
  4531. var errors = new StringBuilder();
  4532. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4533. return Ok(JsonView(false, errors.ToString()));
  4534. }
  4535. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4536. #region 页面操作权限验证
  4537. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4538. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4539. #endregion
  4540. #endregion
  4541. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4542. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4543. string userSql = "";
  4544. if (userIds.Count > 0)
  4545. {
  4546. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4547. }
  4548. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4549. string sql = string.Format(@$"Select
  4550. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4551. u.CnName As UserName,
  4552. Count(*) As [Count]
  4553. From Grp_DelegationInfo di
  4554. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4555. Where di.Isdel = 0
  4556. AND (
  4557. SELECT
  4558. CAST(
  4559. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4560. ) AS GroupSales
  4561. FROM
  4562. Fin_ForeignReceivables fr
  4563. WHERE
  4564. fr.IsDel = 0
  4565. AND di.Id = fr.Diid
  4566. AND AddingWay IN (0, 1, 2)
  4567. ) > 0
  4568. {userSql}
  4569. AND di.IsBid = 0
  4570. AND di.TeamName Not Like '%投标%'
  4571. AND VisitDate Between '{beginDt}' AND '{endDt}'
  4572. Group By CnName");
  4573. RefAsync<int> total = 0;
  4574. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4575. return Ok(JsonView(true, "操作成功!", rankingData, total));
  4576. }
  4577. /// <summary>
  4578. /// 市场部销售额
  4579. /// 团组列表、客户类型、客户等级、接单排名
  4580. /// </summary>
  4581. /// <param name="_dto">市场部销售额请求dto</param>
  4582. /// <returns></returns>
  4583. [HttpPost("PostMarketingSalesGroupItem")]
  4584. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4585. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  4586. {
  4587. #region 参数验证
  4588. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4589. var validResult = await validationRules.ValidateAsync(_dto);
  4590. if (!validResult.IsValid)
  4591. {
  4592. var errors = new StringBuilder();
  4593. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4594. return Ok(JsonView(false, errors.ToString()));
  4595. }
  4596. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4597. #region 页面操作权限验证
  4598. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4599. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4600. #endregion
  4601. #endregion
  4602. string userSql = "";
  4603. List<int> userIds = new List<int>();
  4604. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4605. if (userIds.Count <= 0)
  4606. {
  4607. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4608. }
  4609. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4610. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4611. {
  4612. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4613. }
  4614. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4615. #region 团组List
  4616. string sql = string.Format(@$"SELECT
  4617. ROW_NUMBER() OVER (
  4618. ORDER BY
  4619. CollectionDays
  4620. ) AS RowNumber,
  4621. *
  4622. FROM
  4623. (
  4624. SELECT
  4625. di.Id,
  4626. di.TeamName,
  4627. di.ClientUnit,
  4628. di.ClientName,
  4629. di.VisitDate,
  4630. di.VisitPNumber,
  4631. di.JietuanOperator,
  4632. di.VisitEndDate,
  4633. (
  4634. SELECT
  4635. CAST(
  4636. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4637. ) AS GroupSales
  4638. FROM
  4639. Fin_ForeignReceivables
  4640. WHERE
  4641. IsDel = 0
  4642. AND di.Id = Diid
  4643. AND AddingWay IN (0, 1, 2)
  4644. ) AS GroupSales,
  4645. u.CnName AS GroupPickupUser,
  4646. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4647. FROM
  4648. Grp_DelegationInfo di
  4649. WITH
  4650. (NoLock)
  4651. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4652. WHERE
  4653. di.Isdel = 0
  4654. AND (
  4655. SELECT
  4656. CAST(
  4657. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4658. ) AS GroupSales
  4659. FROM
  4660. Fin_ForeignReceivables fr
  4661. WHERE
  4662. fr.IsDel = 0
  4663. AND di.Id = fr.Diid
  4664. AND AddingWay IN (0, 1, 2)
  4665. ) > 0
  4666. {userSql}
  4667. AND di.IsBid = 0
  4668. AND di.TeamName Not Like '%投标%'
  4669. AND VisitDate Between '{beginDt}' And '{endDt}'
  4670. ) Temp ");
  4671. RefAsync<int> total = 0;
  4672. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4673. #endregion
  4674. #region 客户类型、客户等级 统计
  4675. string sql1 = string.Format(@$"Select
  4676. sd.[Name],
  4677. Count(*) As [Count]
  4678. From Grp_DelegationInfo di
  4679. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4680. Where di.Isdel = 0
  4681. And (
  4682. SELECT
  4683. CAST(
  4684. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4685. ) AS GroupSales
  4686. FROM
  4687. Fin_ForeignReceivables fr
  4688. WHERE
  4689. fr.IsDel = 0
  4690. AND di.Id = fr.Diid
  4691. AND AddingWay IN (0, 1, 2)
  4692. ) > 0
  4693. {userSql}
  4694. AND di.IsBid = 0
  4695. AND di.TeamName Not Like '%投标%'
  4696. And VisitDate Between '{beginDt}' And '{endDt}'
  4697. Group By [Name]
  4698. Order By Count Desc");
  4699. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4700. string sql2 = string.Format(@$"Select
  4701. sd.[Name],
  4702. Count(*) As [Count]
  4703. From Grp_DelegationInfo di
  4704. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4705. Where di.Isdel = 0
  4706. And (
  4707. SELECT
  4708. CAST(
  4709. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4710. ) AS GroupSales
  4711. FROM
  4712. Fin_ForeignReceivables fr
  4713. WHERE
  4714. fr.IsDel = 0
  4715. AND di.Id = fr.Diid
  4716. AND AddingWay IN (0, 1, 2)
  4717. ) > 0
  4718. {userSql}
  4719. AND di.IsBid = 0
  4720. AND di.TeamName Not Like '%投标%'
  4721. And VisitDate Between '{beginDt}' And '{endDt}'
  4722. Group By [Name]
  4723. Order By Count Desc");
  4724. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4725. #endregion
  4726. #region 接单排名
  4727. string sql4 = string.Format(@$"Select
  4728. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4729. u.CnName As UserName,
  4730. Count(*) As [Count]
  4731. From Grp_DelegationInfo di
  4732. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4733. Where di.Isdel = 0
  4734. And (
  4735. SELECT
  4736. CAST(
  4737. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4738. ) AS GroupSales
  4739. FROM
  4740. Fin_ForeignReceivables fr
  4741. WHERE
  4742. fr.IsDel = 0
  4743. AND di.Id = fr.Diid
  4744. AND AddingWay IN (0, 1, 2)
  4745. ) > 0
  4746. {userSql}
  4747. AND di.IsBid = 0
  4748. AND di.TeamName Not Like '%投标%'
  4749. And VisitDate Between '{beginDt}' And '{endDt}'
  4750. Group By CnName");
  4751. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  4752. #endregion
  4753. var viewData = new
  4754. {
  4755. groupData = groupData,
  4756. groupTotal = total,
  4757. customerTypeData = customerTypeData,
  4758. clientGradeData = clientGradeData,
  4759. rankingData = rankingData
  4760. };
  4761. return Ok(JsonView(true, "操作成功!", viewData, total));
  4762. }
  4763. /// <summary>
  4764. /// 市场部销售额
  4765. /// 客户拜访列表
  4766. /// </summary>
  4767. /// <param name="_dto">市场部销售额请求dto</param>
  4768. /// <returns></returns>
  4769. [HttpPost("PostMarketingSalesVCList")]
  4770. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4771. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  4772. {
  4773. #region 参数验证
  4774. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4775. var validResult = await validationRules.ValidateAsync(_dto);
  4776. if (!validResult.IsValid)
  4777. {
  4778. var errors = new StringBuilder();
  4779. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4780. return Ok(JsonView(false, errors.ToString()));
  4781. }
  4782. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4783. #region 页面操作权限验证
  4784. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4785. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4786. #endregion
  4787. #endregion
  4788. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  4789. }
  4790. /// <summary>
  4791. /// 市场部销售额
  4792. /// 客户拜访 操作(添加 Or 编辑)
  4793. /// </summary>
  4794. /// <param name="_dto">市场部销售额请求dto</param>
  4795. /// <returns></returns>
  4796. [HttpPost("PostMarketingSalesVCOperate")]
  4797. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4798. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  4799. {
  4800. #region 参数验证
  4801. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4802. var validResult = await validationRules.ValidateAsync(_dto);
  4803. if (!validResult.IsValid)
  4804. {
  4805. var errors = new StringBuilder();
  4806. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4807. return Ok(JsonView(false, errors.ToString()));
  4808. }
  4809. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4810. #region 页面操作权限验证
  4811. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4812. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4813. #endregion
  4814. #endregion
  4815. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  4816. }
  4817. /// <summary>
  4818. /// 市场部销售额
  4819. /// 客户拜访 Del
  4820. /// </summary>
  4821. /// <param name="_dto">市场部销售额请求dto</param>
  4822. /// <returns></returns>
  4823. [HttpPost("PostMarketingSalesVCDel")]
  4824. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4825. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  4826. {
  4827. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  4828. }
  4829. /// <summary>
  4830. /// 市场部销售额
  4831. /// 客户拜访 操作 save
  4832. /// </summary>
  4833. /// <param name="_dto">市场部销售额请求dto</param>
  4834. /// <returns></returns>
  4835. [HttpPost("PostMarketingSalesVCSave")]
  4836. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4837. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  4838. {
  4839. #region 参数验证
  4840. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  4841. var validResult = await validationRules.ValidateAsync(_dto);
  4842. if (!validResult.IsValid)
  4843. {
  4844. var errors = new StringBuilder();
  4845. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4846. return Ok(JsonView(false, errors.ToString()));
  4847. }
  4848. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4849. #region 页面操作权限验证
  4850. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4851. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4852. #endregion
  4853. #endregion
  4854. return Ok(await _visitingClientsRep._Save(_dto));
  4855. }
  4856. #endregion
  4857. #region 日付报表
  4858. /// <summary>
  4859. /// 日付类型数据
  4860. /// </summary>
  4861. /// <param name="_dto"></param>
  4862. /// <returns></returns>
  4863. [HttpPost("DailypaymentTypeInit")]
  4864. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4865. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  4866. {
  4867. #region 参数验证
  4868. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  4869. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4870. #region 页面操作权限验证
  4871. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4872. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  4873. #endregion
  4874. #endregion
  4875. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  4876. {
  4877. var defaultParentIds = new List<int>() {
  4878. 48,// 人员费用
  4879. 49,// 办公费用
  4880. 50,// 销售费用
  4881. 51,// 其他费用
  4882. 55,// 大运会
  4883. };
  4884. var dailypaymentTypeData = await RedisRepository.RedisFactory
  4885. .CreateRedisRepository()
  4886. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  4887. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  4888. .Includes(x => x.SubData)
  4889. .Where(x => defaultParentIds.Contains(x.Id))
  4890. .ToListAsync();
  4891. dailyTypeData.ForEach(x =>
  4892. {
  4893. x.SubData.ForEach(y =>
  4894. {
  4895. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  4896. y.IsChecked = currId == 0 ? false : true;
  4897. });
  4898. });
  4899. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  4900. .Where(x => x.IsDel == 0)
  4901. .Select(x => new { id = x.Id, name = x.CompanyName })
  4902. .ToListAsync();
  4903. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  4904. }
  4905. else
  4906. {
  4907. return Ok(JsonView(false, "查询失败"));
  4908. }
  4909. }
  4910. /// <summary>
  4911. /// 日付类型数据 Save
  4912. /// </summary>
  4913. /// <param name="_dto"></param>
  4914. /// <returns></returns>
  4915. [HttpPost("DailypaymentTypeDataSave")]
  4916. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4917. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  4918. {
  4919. #region 参数验证
  4920. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  4921. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4922. #region 页面操作权限验证
  4923. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4924. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  4925. #endregion
  4926. #endregion
  4927. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  4928. {
  4929. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  4930. var res = await RedisRepository.RedisFactory
  4931. .CreateRedisRepository()
  4932. .StringSetAsync(
  4933. key: "DailypaymentTypeData",
  4934. _dto.TypeIds,
  4935. timeout: null);
  4936. if (!res) return Ok(JsonView(false, "操作失败"));
  4937. return Ok(JsonView(true, "操作成功!"));
  4938. }
  4939. else return Ok(JsonView(false, "操作失败"));
  4940. }
  4941. /// <summary>
  4942. /// 日付数据列表
  4943. /// </summary>
  4944. /// <param name="_dto"></param>
  4945. /// <returns></returns>
  4946. [HttpPost("DailypaymentRange")]
  4947. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4948. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  4949. {
  4950. #region 参数验证
  4951. var validator = new DailypaymentRangeDtoValidator();
  4952. var validationRes = validator.Validate(_dto);
  4953. if (!validationRes.IsValid)
  4954. {
  4955. StringBuilder sb = new StringBuilder();
  4956. foreach (var item in validationRes.Errors)
  4957. {
  4958. sb.AppendLine(item.ErrorMessage);
  4959. }
  4960. return Ok(JsonView(false, sb.ToString()));
  4961. }
  4962. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4963. #region 页面操作权限验证
  4964. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4965. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  4966. #endregion
  4967. #endregion
  4968. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  4969. {
  4970. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  4971. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  4972. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  4973. var dailypaymentTypeData = await RedisRepository.RedisFactory
  4974. .CreateRedisRepository()
  4975. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  4976. var sql = string.Format(@"
  4977. Select
  4978. dfp.Id,
  4979. dfp.Instructions,
  4980. dfp.PriceTypeId,
  4981. sd1.Name As FeeType,
  4982. dfp.TransferTypeId,
  4983. sd2.Name As TransferType,
  4984. dfp.SumPrice,
  4985. dfp.FAuditDate,
  4986. dfp.MAuditDate,
  4987. dfp.CompanyId,
  4988. c.CompanyName,
  4989. dfp.CreateUserId As ApplicantId,
  4990. u.CnName As Applicant,
  4991. dfp.CreateTime As ApplicantDt,
  4992. dfp.Instructions+u.CnName As ViewStr
  4993. From Fin_DailyFeePayment dfp
  4994. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  4995. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  4996. Left Join Sys_Company c On dfp.CompanyId = c.Id
  4997. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  4998. Where dfp.IsDel = 0 And dfp.IsPay = 1
  4999. ");//--Order By dfp.CreateTime Desc
  5000. if (_dto.Type == 1) //data
  5001. {
  5002. RefAsync<int> total = 0;
  5003. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  5004. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5005. .WhereIF(dailypaymentTypeData.Count > 0,
  5006. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5007. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5008. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5009. .OrderByDescending(x => x.ApplicantDt)
  5010. .ToPageListAsync(
  5011. pageNumber: _dto.PageIndex,
  5012. pageSize: _dto.PageSize,
  5013. totalNumber: total
  5014. );
  5015. _sqlSugar.ThenMapper(_view, x =>
  5016. {
  5017. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5018. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5019. .ToList();
  5020. });
  5021. //单独处理
  5022. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  5023. }
  5024. else if (_dto.Type == 2) //view
  5025. {
  5026. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  5027. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5028. .WhereIF(dailypaymentTypeData.Count > 0,
  5029. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5030. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5031. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5032. .OrderByDescending(x => x.ApplicantDt)
  5033. .ToPageListAsync(
  5034. pageNumber: 1,
  5035. pageSize: 99999
  5036. );
  5037. _sqlSugar.ThenMapper(_view, x =>
  5038. {
  5039. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5040. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5041. .ToList();
  5042. string str = "";
  5043. int index = 1;
  5044. foreach (var item in x.Contents)
  5045. {
  5046. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  5047. if (index == x.Contents.Count) str += str1;
  5048. else str += str1 + "\r\n";
  5049. index++;
  5050. }
  5051. x.ContentStr = str;
  5052. });
  5053. if (_view.Count > 0)
  5054. {
  5055. //DataTable dt = GeneralMethod.
  5056. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  5057. dt.TableName = $"_view";
  5058. decimal total = _view.Sum(x => x.SumPrice);
  5059. WorkbookDesigner designer = new WorkbookDesigner();
  5060. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  5061. designer.SetDataSource(dt);
  5062. designer.SetDataSource("Total", total);
  5063. designer.Workbook.Worksheets[0].Name = "日付报表";
  5064. designer.Process();
  5065. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  5066. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  5067. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  5068. return Ok(JsonView(true, "操作成功", new { url = rst }));
  5069. }
  5070. return Ok(JsonView(true, ",暂无数据"));
  5071. }
  5072. return Ok(JsonView(false, "操作失败"));
  5073. }
  5074. else return Ok(JsonView(false, "操作失败"));
  5075. }
  5076. #endregion
  5077. #region 统计模块
  5078. /// <summary>
  5079. /// 同比
  5080. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  5081. /// </summary>
  5082. /// <param name="_dto">市场部销售额请求dto</param>
  5083. /// <returns></returns>
  5084. [HttpPost("StatisticsYOY")]
  5085. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5086. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  5087. {
  5088. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  5089. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5090. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  5091. endDt = $"{_dto.Year}-12-31 23:59:59";
  5092. string sql = string.Format(@"
  5093. SELECT
  5094. di.Id,
  5095. di.TeamName,
  5096. di.VisitDate,
  5097. YEAR(di.VisitDate) AS YEAR,
  5098. MONTH(di.VisitDate) AS MONTH,
  5099. (
  5100. SELECT
  5101. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  5102. FROM
  5103. Fin_ForeignReceivables
  5104. WHERE
  5105. IsDel = 0
  5106. AND AddingWay IN (0, 1, 2)
  5107. AND di.Id = Diid
  5108. ) AS SaleAmount,
  5109. (
  5110. SELECT
  5111. CAST(
  5112. SUM(
  5113. (
  5114. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  5115. )
  5116. ) AS DECIMAL(12, 2)
  5117. )
  5118. FROM
  5119. Grp_AirTicketReservations atr
  5120. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5121. AND ccp.CTable = 85
  5122. AND atr.Id = ccp.CId
  5123. WHERE
  5124. atr.IsDel = 0
  5125. AND ccp.IsAuditGM = 1
  5126. AND ccp.IsPay = 1
  5127. AND di.Id = atr.DiId
  5128. ) AirTicketAmount,
  5129. (
  5130. SELECT
  5131. CAST(
  5132. SUM(
  5133. (
  5134. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5135. )
  5136. ) AS DECIMAL(12, 2)
  5137. )
  5138. FROM
  5139. Grp_CarTouristGuideGroundReservations ctggr
  5140. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5141. AND ccp.CTable = 79
  5142. AND ctggr.Id = ccp.CId
  5143. WHERE
  5144. ctggr.IsDel = 0
  5145. AND ccp.IsAuditGM = 1
  5146. AND ccp.IsPay = 1
  5147. AND di.Id = ctggr.DiId
  5148. ) AS OPAmount,
  5149. (
  5150. SELECT
  5151. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5152. FROM
  5153. Grp_DecreasePayments dp
  5154. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5155. AND ccp.CTable = 98
  5156. AND dp.Id = ccp.CId
  5157. WHERE
  5158. dp.IsDel = 0
  5159. AND ccp.Ctable = 98
  5160. AND ccp.IsAuditGM = 1
  5161. AND ccp.IsPay = 1
  5162. AND di.Id = dp.Diid
  5163. ) AS OtherCostAmount,
  5164. (
  5165. SELECT
  5166. CAST(
  5167. SUM(
  5168. (
  5169. (ccp.PayMoney * ccp.DayRate)
  5170. )
  5171. ) AS DECIMAL(12, 2)
  5172. )
  5173. FROM
  5174. Grp_VisaInfo vi
  5175. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5176. AND ccp.CTable = 80
  5177. AND vi.Id = ccp.CId
  5178. WHERE
  5179. vi.IsDel = 0
  5180. AND ccp.IsAuditGM = 1
  5181. AND ccp.IsPay = 1
  5182. AND di.Id = vi.DIId
  5183. ) AS VisaAmount,
  5184. (
  5185. SELECT
  5186. CAST(
  5187. SUM(
  5188. (ccp.PayMoney * ccp.DayRate)
  5189. ) AS DECIMAL(12, 2)
  5190. )
  5191. FROM
  5192. Grp_InvitationOfficialActivities ioa
  5193. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5194. AND ccp.CTable = 81
  5195. AND ioa.Id = ccp.CId
  5196. WHERE
  5197. ioa.IsDel = 0
  5198. AND ccp.IsAuditGM = 1
  5199. AND ccp.IsPay = 1
  5200. AND di.Id = ioa.Diid
  5201. ) AS OAAmount,
  5202. (
  5203. SELECT
  5204. CAST(
  5205. SUM(
  5206. (ccp.PayMoney * ccp.DayRate)
  5207. ) AS DECIMAL(12, 2)
  5208. )
  5209. FROM
  5210. Grp_Customers ic
  5211. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5212. AND ccp.CTable = 82
  5213. AND ic.Id = ccp.CId
  5214. WHERE
  5215. ic.IsDel = 0
  5216. AND ccp.IsAuditGM = 1
  5217. AND ccp.IsPay = 1
  5218. AND di.Id = ic.DiId
  5219. ) AS InsureAmount,
  5220. (
  5221. SELECT
  5222. CAST(
  5223. SUM(
  5224. (ccp.PayMoney * ccp.DayRate)
  5225. ) AS DECIMAL(12, 2)
  5226. )
  5227. FROM
  5228. Grp_HotelReservations hr
  5229. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5230. WHERE
  5231. hr.IsDel = 0
  5232. AND ccp.IsDel = 0
  5233. AND ccp.CTable = 76
  5234. AND ccp.IsAuditGM = 1
  5235. AND ccp.PayMoney <> 0
  5236. AND ccp.IsPay = 1
  5237. AND di.Id = hr.DiId
  5238. ) AS HotelAmount,
  5239. (
  5240. SELECT
  5241. CAST(
  5242. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  5243. )
  5244. FROM
  5245. OA2023DB.dbo.Fin_GroupExtraCost gec
  5246. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  5247. WHERE
  5248. ccp.IsDel = 0
  5249. AND ccp.CTable = 1015
  5250. AND ccp.IsAuditGM = 1
  5251. AND ccp.IsPay = 1
  5252. AND di.Id = gec.DiId
  5253. ) AS ExcessAmount,
  5254. (
  5255. SELECT
  5256. CAST(
  5257. SUM(
  5258. (ccp.PayMoney * ccp.DayRate)
  5259. ) AS DECIMAL(12, 2)
  5260. )
  5261. FROM
  5262. Fin_PaymentRefundAndOtherMoney prom
  5263. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  5264. AND prom.Id = ccp.CId
  5265. WHERE
  5266. prom.IsDel = 0
  5267. AND prom.PayType = 1
  5268. AND ccp.CTable = 285
  5269. AND ccp.IsAuditGM = 1
  5270. AND ccp.IsPay = 1
  5271. AND di.Id = prom.DiId
  5272. ) AS SKTHAmount
  5273. FROM
  5274. Grp_DelegationInfo di
  5275. WHERE
  5276. di.IsDel = 0
  5277. AND di.TeamDid IN (38,39,40,1048)
  5278. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5279. ORDER BY
  5280. di.VisitDate
  5281. ", beginDt, endDt);
  5282. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  5283. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  5284. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  5285. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  5286. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  5287. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  5288. int monthIndex = 1;
  5289. while (monthIndex < 13)
  5290. {
  5291. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  5292. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  5293. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  5294. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  5295. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5296. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5297. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5298. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5299. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  5300. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  5301. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  5302. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  5303. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  5304. monthIndex++;
  5305. }
  5306. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  5307. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  5308. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  5309. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  5310. }
  5311. /// <summary>
  5312. /// 国交数据统计-机票相关
  5313. /// 机票票数、机票到达地、预订平台
  5314. /// </summary>
  5315. /// <param name="_dto"></param>
  5316. /// <returns></returns>
  5317. [HttpPost("StatisticsAirTicket")]
  5318. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5319. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  5320. {
  5321. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5322. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5323. endDt = $"{_dto.Year}-12-31 23:59:59";
  5324. string sql = string.Format(@"
  5325. SELECT
  5326. atr.DIId,
  5327. atr.FlightsDate,
  5328. YEAR(atr.FlightsDate) AS YEAR,
  5329. MONTH(atr.FlightsDate) AS MONTH,
  5330. atr.CType,
  5331. sd.Name As CTypeName,
  5332. atr.FlightsCity,
  5333. atr.ClientNum,
  5334. atr.ClientName,
  5335. di.TeamName As 'GroupName',
  5336. CASE
  5337. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  5338. ELSE ccp.Payee
  5339. END AS 'Platform'
  5340. FROM
  5341. Grp_AirTicketReservations atr
  5342. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  5343. AND ccp.IsDel = 0
  5344. AND CTable = 85
  5345. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  5346. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  5347. WHERE
  5348. atr.IsDel = 0
  5349. AND di.TeamDid IN (38,39,40,1048)
  5350. AND atr.CType IN(457,458,459,460,574,575)
  5351. AND CHARINDEX('行程单',atr.ClientName) = 0
  5352. AND CHARINDEX('返点',atr.ClientName) = 0
  5353. AND CHARINDEX('-1',atr.ClientName) = 0
  5354. AND ccp.IsPay = 1
  5355. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  5356. ORDER BY atr.FlightsDate
  5357. ", beginDt, endDt);
  5358. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  5359. var groupIds = data.Select(x => x.DIId).ToList();
  5360. //处理城市数据
  5361. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5362. //处理团组名称
  5363. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  5364. data.ForEach(x =>
  5365. {
  5366. string cityName = "";
  5367. if (!string.IsNullOrEmpty(x.FlightsCity))
  5368. {
  5369. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  5370. int cityNum = cityCode.Length / 3;
  5371. if (cityCode.Length % 3 == 0)
  5372. {
  5373. for (int i = 0; i < cityNum; i++)
  5374. {
  5375. string code = "";
  5376. if (i == 0) code = cityCode.Substring(0, 3);
  5377. else code = cityCode.Substring(i * 3, 3);
  5378. if (!string.IsNullOrEmpty(code))
  5379. {
  5380. if (i == cityNum - 1)
  5381. {
  5382. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5383. }
  5384. else
  5385. {
  5386. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5387. cityName += str1 + "、";
  5388. }
  5389. }
  5390. }
  5391. }
  5392. }
  5393. x.FlightsCityName = cityName;
  5394. });
  5395. var airTicketNumData = new List<AirTicketReturnView>();
  5396. var airTicketAreaData = new List<AirTicketCityReturnView>();
  5397. int monthIndex = 1;
  5398. while (monthIndex < 13)
  5399. {
  5400. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  5401. //机票票数处理
  5402. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  5403. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  5404. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  5405. foreach (var item in monthData)
  5406. {
  5407. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  5408. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  5409. }
  5410. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  5411. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  5412. foreach (var item in aitTicketInfosGroupBy)
  5413. {
  5414. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  5415. }
  5416. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  5417. linkGroupIds = linkGroupIds.Distinct().ToList();
  5418. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  5419. //机票城市处理
  5420. //城市处理
  5421. var airTicketCityInfos = new List<string>();
  5422. foreach (var item in monthData)
  5423. {
  5424. if (!string.IsNullOrEmpty(item.FlightsCityName))
  5425. {
  5426. if (item.FlightsCityName.Contains("、"))
  5427. {
  5428. var cityArray = item.FlightsCityName.Split("、").ToList();
  5429. foreach (var item1 in cityArray)
  5430. {
  5431. if (!string.IsNullOrEmpty(item1))
  5432. {
  5433. airTicketCityInfos.Add(item1);
  5434. }
  5435. }
  5436. }
  5437. else
  5438. {
  5439. airTicketCityInfos.Add(item.FlightsCityName);
  5440. }
  5441. }
  5442. }
  5443. //int quantity1 = airTicketCityInfos.Count;
  5444. int city_totalquantity = 0;
  5445. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  5446. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  5447. foreach (var item in airTicketCityInfosGroupby)
  5448. {
  5449. var city_quantity = item.ToList().Count;
  5450. city_totalquantity += city_quantity;
  5451. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  5452. }
  5453. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  5454. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  5455. monthIndex++;
  5456. }
  5457. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  5458. .Select(g => new
  5459. {
  5460. platform = g.Key,
  5461. total = g.Sum(x => x.ClientNum),
  5462. children = g.GroupBy(g1 => g1.DIId)
  5463. .Select(g1 => new
  5464. {
  5465. diId = g1.Key,
  5466. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  5467. total = g1.Sum(x1 => x1.ClientNum),
  5468. children = g1.Select(x1 => new
  5469. {
  5470. //diId = x1.DIId,
  5471. //groupName = x1.GroupName,
  5472. flightsCityName = x1.FlightsCityName,
  5473. total = x1.ClientNum
  5474. })
  5475. .ToList()
  5476. })
  5477. .OrderByDescending(x1 => x1.total)
  5478. .ToList()
  5479. })
  5480. .OrderByDescending(x => x.total)
  5481. .ToList();
  5482. return Ok(JsonView(true, "操作成功!", new
  5483. {
  5484. airTicketNumData = airTicketNumData,
  5485. airTicketAreaData = airTicketAreaData,
  5486. airTicketPlatformData = airTicketPlatformData
  5487. }));
  5488. }
  5489. /// <summary>
  5490. /// 国交数据统计-酒店
  5491. /// 国家TOP10、地区TOP10、预订平台
  5492. /// </summary>
  5493. /// <param name="_dto"></param>
  5494. /// <returns></returns>
  5495. [HttpPost("StatisticsHotel")]
  5496. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5497. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  5498. {
  5499. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5500. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5501. endDt = $"{_dto.Year}-12-31 23:59:59";
  5502. string sql = string.Format(@"
  5503. SELECT
  5504. hr.DIId,
  5505. CASE
  5506. WHEN ntf.Country IS NULL THEN '未选择'
  5507. ELSE ntf.Country
  5508. END AS 'Country',
  5509. hr.City,
  5510. hr.HotelName,
  5511. sd.Name AS BookinSite,
  5512. hr.CheckInDate,
  5513. YEAR(hr.CheckInDate) AS YEAR,
  5514. MONTH(hr.CheckInDate) AS MONTH,
  5515. hr.CheckOutDate,
  5516. hr.SingleRoomCount,
  5517. hr.DoubleRoomCount,
  5518. hr.SuiteRoomCount,
  5519. hr.OtherRoomCount
  5520. FROM
  5521. Grp_HotelReservations hr
  5522. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5523. AND ccp.IsDel = 0
  5524. AND CTable = 76
  5525. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  5526. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  5527. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  5528. WHERE
  5529. hr.IsDel = 0
  5530. AND di.TeamDid IN (38,39,40,1048)
  5531. AND ccp.IsPay = 1
  5532. AND (
  5533. hr.SingleRoomCount > 0
  5534. OR hr.DoubleRoomCount > 0
  5535. OR hr.SuiteRoomCount > 0
  5536. OR hr.OtherRoomCount > 0
  5537. )
  5538. AND CHARINDEX('早餐',hr.HotelName) = 0
  5539. AND CHARINDEX('晚餐',hr.HotelName) = 0
  5540. AND CHARINDEX('升级',hr.HotelName) = 0
  5541. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  5542. AND CHARINDEX('城市税',hr.HotelName) = 0
  5543. AND CHARINDEX('退款',hr.HotelName) = 0
  5544. AND CHARINDEX('返现',hr.HotelName) = 0
  5545. AND CHARINDEX('会议室',hr.HotelName) = 0
  5546. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  5547. AND CHARINDEX('运费',hr.HotelName) = 0
  5548. AND CHARINDEX('地接',hr.HotelName) = 0
  5549. AND CHARINDEX('损失',hr.HotelName) = 0
  5550. AND CHARINDEX('补差',hr.HotelName) = 0
  5551. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5552. ORDER BY
  5553. hr.CheckInDate
  5554. ", beginDt, endDt);
  5555. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  5556. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  5557. .Select(g => new
  5558. {
  5559. Country = g.Key,
  5560. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5561. hotelData = g.GroupBy(x => x.HotelName)
  5562. .Select(g1 => new
  5563. {
  5564. hotelName = g1.Key,
  5565. roomNights = g1.Sum(x => x.RoomNights),
  5566. roomTotal = g1.Sum(x => x.RoomTotal),
  5567. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5568. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5569. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5570. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5571. })
  5572. .ToList(),
  5573. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5574. })
  5575. .OrderByDescending(x => x.BookingRoomNum)
  5576. .Take(10)
  5577. .ToList();
  5578. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  5579. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  5580. .Select(g => new
  5581. {
  5582. city = g.Key,
  5583. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5584. hotelData = g.GroupBy(x => x.HotelName)
  5585. .Select(g1 => new
  5586. {
  5587. hotelName = g1.Key,
  5588. roomNights = g1.Sum(x => x.RoomNights),
  5589. roomTotal = g1.Sum(x => x.RoomTotal),
  5590. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5591. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5592. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5593. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5594. })
  5595. .ToList(),
  5596. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5597. })
  5598. .OrderByDescending(x => x.BookingRoomNum)
  5599. .Take(10)
  5600. .ToList();
  5601. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  5602. .Select(g => new
  5603. {
  5604. Platform = g.Key,
  5605. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5606. hotelData = g.GroupBy(x => x.HotelName)
  5607. .Select(g1 => new
  5608. {
  5609. hotelName = g1.Key,
  5610. roomNights = g1.Sum(x => x.RoomNights),
  5611. roomTotal = g1.Sum(x => x.RoomTotal),
  5612. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5613. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5614. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5615. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5616. })
  5617. .ToList(),
  5618. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5619. })
  5620. .OrderByDescending(x => x.BookingRoomNum)
  5621. .ToList();
  5622. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  5623. }
  5624. /// <summary>
  5625. /// 国交数据统计
  5626. /// 商邀邀请国家数量TOP10
  5627. /// </summary>
  5628. /// <param name="_dto"></param>
  5629. /// <returns></returns>
  5630. [HttpPost("StatisticsInvitation")]
  5631. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5632. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  5633. {
  5634. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5635. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5636. endDt = $"{_dto.Year}-12-31 23:59:59";
  5637. string sql = string.Format(@"
  5638. SELECT
  5639. oa.DiId,
  5640. di.TeamName AS GroupName,
  5641. oa.Country,
  5642. oa.Area AS City,
  5643. oa.Client,
  5644. oa.Date
  5645. FROM
  5646. Res_OfficialActivities oa
  5647. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  5648. WHERE
  5649. oa.IsDel = 0
  5650. AND oa.Date BETWEEN '{0}' AND '{1}'
  5651. ", beginDt, endDt);
  5652. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  5653. var groupByCountry = data.GroupBy(x => x.Country)
  5654. .Select(g => new
  5655. {
  5656. Country = g.Key,
  5657. TimeNum = g.Count(),
  5658. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5659. })
  5660. .OrderByDescending(x => x.TimeNum)
  5661. .Take(10)
  5662. .ToList();
  5663. var groupByClient = data.GroupBy(x => x.Client)
  5664. .Select(g => new
  5665. {
  5666. Country = g.Key,
  5667. TimeNum = g.Count(),
  5668. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5669. })
  5670. .OrderByDescending(x => x.TimeNum)
  5671. .Take(10)
  5672. .ToList();
  5673. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  5674. }
  5675. /// <summary>
  5676. /// 会务数据统计
  5677. /// 会务城市TOP10排序
  5678. /// </summary>
  5679. /// <param name="_dto"></param>
  5680. /// <returns></returns>
  5681. [HttpPost("StatisticsConferenceCity")]
  5682. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5683. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  5684. {
  5685. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5686. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5687. endDt = $"{_dto.Year}-12-31 23:59:59";
  5688. string sql = string.Format(@"
  5689. SELECT
  5690. ioa.DiId,
  5691. ioa.InviterArea AS Country
  5692. FROM
  5693. Grp_InvitationOfficialActivities ioa
  5694. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  5695. AND ccp.IsDel = 0
  5696. AND ccp.CTable = 81
  5697. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  5698. WHERE
  5699. ioa.IsDel = 0
  5700. AND di.TeamDid IN (102,248,302,691,762,1047)
  5701. AND ccp.IsPay = 1
  5702. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  5703. ", beginDt, endDt);
  5704. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  5705. var groupByData = data.GroupBy(x => x.Country)
  5706. .Select(g => new
  5707. {
  5708. Country = g.Key,
  5709. TimeNum = g.Count(),
  5710. LinkGroupIds = g.Select(x => x.DIId).ToList()
  5711. })
  5712. .OrderByDescending(x => x.TimeNum)
  5713. .Take(10)
  5714. .ToList();
  5715. return Ok(JsonView(true, "操作成功!", groupByData));
  5716. }
  5717. /// <summary>
  5718. /// 团组数据统计
  5719. /// 团组合作前十的客户TOP10排序
  5720. /// </summary>
  5721. /// <param name="_dto"></param>
  5722. /// <returns></returns>
  5723. [HttpPost("StatisticsCooperativeCustomer")]
  5724. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5725. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  5726. {
  5727. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5728. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5729. endDt = $"{_dto.Year}-12-31 23:59:59";
  5730. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5731. _endDt = Convert.ToDateTime(endDt);
  5732. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5733. .Where(x => x.IsDel == 0)
  5734. //.Where(x => x.IsSure == 1)
  5735. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5736. .ToListAsync();
  5737. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  5738. var view = groupInfos1.Select(x =>
  5739. new
  5740. {
  5741. clienName = x.Key,
  5742. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  5743. visitsNum = x.Count()
  5744. }
  5745. )
  5746. .OrderByDescending(x => x.visitsNum)
  5747. .Take(10)
  5748. .ToList();
  5749. return Ok(JsonView(true, "操作成功!", view));
  5750. }
  5751. /// <summary>
  5752. /// 团组数据统计
  5753. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  5754. /// </summary>
  5755. /// <param name="_dto"></param>
  5756. /// <returns></returns>
  5757. [HttpPost("StatisticsCooperativeCustomerType")]
  5758. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5759. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  5760. {
  5761. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5762. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5763. endDt = $"{_dto.Year}-12-31 23:59:59";
  5764. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5765. _endDt = Convert.ToDateTime(endDt);
  5766. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5767. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  5768. .Where((di, sd) => di.IsDel == 0)
  5769. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  5770. .Select((di, sd) => new
  5771. {
  5772. Id = di.Id,
  5773. GroupTypeId = di.TeamDid,
  5774. GroupTypeName = sd.Name,
  5775. })
  5776. .ToListAsync();
  5777. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  5778. var view = groupInfos1.Select(x =>
  5779. new
  5780. {
  5781. groupTypeName = x.Key,
  5782. groupNum = x.Count(),
  5783. linkGroupId = x.Select(x1 => x1.Id).ToList()
  5784. }
  5785. )
  5786. .OrderByDescending(x => x.groupNum)
  5787. .ToList();
  5788. return Ok(JsonView(true, "操作成功!", view));
  5789. }
  5790. /// <summary>
  5791. /// 团组数据统计
  5792. /// 团组数量
  5793. /// </summary>
  5794. /// <param name="_dto"></param>
  5795. /// <returns></returns>
  5796. [HttpPost("StatisticsGroupNum")]
  5797. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5798. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  5799. {
  5800. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5801. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5802. endDt = $"{_dto.Year}-12-31 23:59:59";
  5803. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5804. _endDt = Convert.ToDateTime(endDt);
  5805. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5806. .Where(x => x.IsDel == 0)
  5807. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5808. .Select(x => new StatisticsGroupInfoEntity
  5809. {
  5810. Id = x.Id,
  5811. VisitDate = x.VisitDate,
  5812. Month = x.VisitDate.Month,
  5813. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  5814. VisitPNumber = x.VisitPNumber
  5815. })
  5816. .MergeTable()
  5817. .OrderBy(x => new { x.Month })
  5818. .ToListAsync();
  5819. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  5820. var groupNumYearData = new
  5821. {
  5822. year = _dto.Year,
  5823. yearName = _dto.Year + "年",
  5824. num = groupInfos.Count,
  5825. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  5826. };
  5827. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  5828. .Select(x => new
  5829. {
  5830. Quarter = x.Key,
  5831. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  5832. Num = x.Count(),
  5833. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5834. })
  5835. .OrderBy(x => x.Quarter)
  5836. .ToList();
  5837. groupNumData.ForEach(x =>
  5838. {
  5839. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  5840. });
  5841. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  5842. .Select(x => new
  5843. {
  5844. Month = x.Key,
  5845. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  5846. Num = x.Count(),
  5847. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5848. })
  5849. .OrderBy(x => x.Month)
  5850. .ToList();
  5851. return Ok(JsonView(true, "操作成功!", new
  5852. {
  5853. yearData = groupNumYearData,
  5854. quarterData = groupNumData,
  5855. monthData = groupNumMonthData,
  5856. remark = groupNumStr
  5857. }));
  5858. }
  5859. /// <summary>
  5860. /// 团组数据统计
  5861. /// 团组人数
  5862. /// </summary>
  5863. /// <param name="_dto"></param>
  5864. /// <returns></returns>
  5865. [HttpPost("StatisticsGroupPeopleNum")]
  5866. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5867. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  5868. {
  5869. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5870. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5871. endDt = $"{_dto.Year}-12-31 23:59:59";
  5872. DateTime _beginDt = Convert.ToDateTime(beginDt),
  5873. _endDt = Convert.ToDateTime(endDt);
  5874. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  5875. .Where(x => x.IsDel == 0)
  5876. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  5877. .Select(x => new StatisticsGroupInfoEntity
  5878. {
  5879. Id = x.Id,
  5880. VisitDate = x.VisitDate,
  5881. Month = x.VisitDate.Month,
  5882. VisitPNumber = x.VisitPNumber
  5883. })
  5884. .MergeTable()
  5885. .OrderBy(x => new { x.Month })
  5886. .ToListAsync();
  5887. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  5888. var groupPeopleNumYearData = new
  5889. {
  5890. year = _dto.Year,
  5891. yearName = _dto.Year + "年",
  5892. num = groupInfos.Sum(x => x.VisitPNumber),
  5893. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  5894. };
  5895. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  5896. .Select(x => new
  5897. {
  5898. Quarter = x.Key,
  5899. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  5900. Num = x.Sum(x1 => x1.VisitPNumber),
  5901. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5902. })
  5903. .OrderBy(x => x.Quarter)
  5904. .ToList();
  5905. groupPeopleNumData.ForEach(x =>
  5906. {
  5907. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  5908. });
  5909. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  5910. .Select(x => new
  5911. {
  5912. Month = x.Key,
  5913. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  5914. Num = x.Sum(x1 => x1.VisitPNumber),
  5915. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  5916. })
  5917. .OrderBy(x => x.Month)
  5918. .ToList();
  5919. return Ok(JsonView(true, "操作成功!", new
  5920. {
  5921. yearData = groupPeopleNumYearData,
  5922. quarterData = groupPeopleNumData,
  5923. monthData = groupPeopleNumMonthData,
  5924. remark = groupPeopleNumStr
  5925. }));
  5926. }
  5927. /// <summary>
  5928. /// 团组数据统计
  5929. /// OP 成本
  5930. /// </summary>
  5931. /// <param name="_dto"></param>
  5932. /// <returns></returns>
  5933. [HttpPost("StatisticsOP")]
  5934. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5935. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  5936. {
  5937. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  5938. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  5939. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  5940. string beginDt = $"{lastYear}-01-01 00:00:00",
  5941. endDt = $"{thisYear}-12-31 23:59:59";
  5942. string sql = string.Format(@"
  5943. SELECT
  5944. temp.Id,
  5945. DiId,
  5946. PaymentTime,
  5947. [Year],
  5948. [Quarter],
  5949. [Month],
  5950. Area,
  5951. FeeType,
  5952. sd1.Name AS FeeTypeName,
  5953. FeeSubType,
  5954. sd2.Name AS FeeSubTypeName,
  5955. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  5956. FROM
  5957. (
  5958. SELECT
  5959. ctggr.Id,
  5960. ctggr.DiId,
  5961. ctggr.Area,
  5962. CASE
  5963. WHEN ctggr.PriceType IS NULL THEN 1069
  5964. ELSE ctggr.PriceType
  5965. END AS FeeType,
  5966. ctggrc.SId AS FeeSubType,
  5967. ctggrc.Price,
  5968. CASE
  5969. WHEN ctggrc.Count IS NULL THEN 1
  5970. ELSE ctggrc.Count
  5971. END AS Qauntity,
  5972. ccp.DayRate AS ExchangeRate,
  5973. ctggrc.CreateTime AS PaymentTime,
  5974. YEAR(ctggrc.CreateTime) AS [Year],
  5975. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  5976. MONTH(ctggrc.CreateTime) AS [Month]
  5977. FROM
  5978. Grp_CarTouristGuideGroundReservations ctggr
  5979. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  5980. AND ctggrc.IsDel = 0
  5981. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  5982. AND ccp.CTable = 79
  5983. AND ccp.IsDel = 0
  5984. WHERE
  5985. ctggr.IsDel = 0
  5986. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  5987. AND ctggrc.Price > 0 --筛选真实存在的数据
  5988. AND ccp.IsPay = 1
  5989. ) temp
  5990. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  5991. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  5992. WHERE
  5993. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  5994. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  5995. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5996. ORDER BY
  5997. temp.[Year],
  5998. temp.[Quarter],
  5999. temp.[Month]
  6000. ", beginDt, endDt);
  6001. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  6002. //处理地区相关信息
  6003. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  6004. for (int i = 0; i < opInfos.Count; i++)
  6005. {
  6006. string country = string.Empty, city = string.Empty;
  6007. int dataId = 0;
  6008. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  6009. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  6010. if (isCountryId)
  6011. {
  6012. var countryInfo = countrys.Find(x => x.Id == dataId);
  6013. country = countryInfo?.Country ?? "";
  6014. if (citySelecter.Contains(countryInfo?.City)) city = country;
  6015. else city = countryInfo?.City ?? "";
  6016. }
  6017. else
  6018. {
  6019. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  6020. if (countryInfo1 != null)
  6021. {
  6022. country = countryInfo1?.Country ?? "";
  6023. city = countryInfo1?.City ?? country;
  6024. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6025. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6026. else city = countryInfo2?.City ?? country;
  6027. }
  6028. else
  6029. {
  6030. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6031. if (countryInfo2 != null)
  6032. {
  6033. country = countryInfo2?.Country ?? "";
  6034. city = countryInfo2?.City ?? "";
  6035. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6036. }
  6037. }
  6038. }
  6039. opInfos[i].Country = country;
  6040. opInfos[i].City = city;
  6041. }
  6042. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  6043. if (_dto.Type == 1)
  6044. {
  6045. //同比增长率=(本期数-同期数)/ 同期数
  6046. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  6047. .Select(x => new StatisticsOPYOY(
  6048. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  6049. feeName: x.Key,
  6050. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  6051. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  6052. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  6053. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  6054. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  6055. .Select(x1 => new StatisticsOPSubFeeYOY(
  6056. feeId: x1.Key,
  6057. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  6058. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6059. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6060. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6061. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6062. cityData: x1.GroupBy(x2 => x2.City)
  6063. .Select(x2 => new StatisticsOPCityYOY(
  6064. cityName: x2.Key,
  6065. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6066. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6067. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6068. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  6069. ))
  6070. .ToArray()
  6071. ))
  6072. .ToArray()
  6073. ))
  6074. .OrderBy(x => x.FeeId)
  6075. .ToList();
  6076. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  6077. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  6078. if (opParentYearDataSelector.Count > 0)
  6079. {
  6080. foreach (var item in opParentYearDataSelector)
  6081. {
  6082. yearData.Add(
  6083. new StatisticsOPYOY(feeId: item.Id,
  6084. feeName: item.Name,
  6085. currPeriodFee: 0.00M,
  6086. samePeriodFee: 0.00M,
  6087. currPeriodGroupTotal: 0,
  6088. samePeriodGroupTotal: 0,
  6089. subFeeData: new StatisticsOPSubFeeYOY[] { }
  6090. ));
  6091. }
  6092. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  6093. }
  6094. return Ok(JsonView(true, "操作成功!", yearData));
  6095. }
  6096. else if (_dto.Type == 2)
  6097. {
  6098. var monthData = opInfos.GroupBy(x => x.Month)
  6099. .Select(x => new StatisticsOPMonthYOY(
  6100. monthId: x.Key,
  6101. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  6102. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  6103. .Select(x1 => new StatisticsOPYOY(
  6104. feeId: x1.Key,
  6105. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  6106. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6107. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6108. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6109. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6110. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  6111. .Select(x2 => new StatisticsOPSubFeeYOY(
  6112. feeId: x2.Key,
  6113. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  6114. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6115. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  6116. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6117. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6118. cityData: x2.GroupBy(x3 => x3.City)
  6119. .Select(x3 => new StatisticsOPCityYOY(
  6120. cityName: x3.Key,
  6121. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  6122. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  6123. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  6124. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  6125. ))
  6126. .ToArray()
  6127. ))
  6128. .ToArray()
  6129. ))
  6130. .ToArray()
  6131. ))
  6132. //.OrderBy(x => x.MonthId)
  6133. .ToList();
  6134. //1、月份是否足够十二月
  6135. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  6136. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  6137. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  6138. if (newMonthIds.Count > 0)
  6139. {
  6140. foreach (var item in newMonthIds)
  6141. {
  6142. monthData.Add(new StatisticsOPMonthYOY(
  6143. monthId: item,
  6144. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  6145. feeDatas: Array.Empty<StatisticsOPYOY>()
  6146. ));
  6147. }
  6148. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  6149. }
  6150. //2、费用父类是否足够
  6151. for (int i = 0; i < monthData.Count; i++)
  6152. {
  6153. var month = monthData[i];
  6154. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  6155. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  6156. if (opParentFeeDataSelector.Count > 0)
  6157. {
  6158. var feeDatas = month.FeeDatas.ToList();
  6159. foreach (var item in opParentFeeDataSelector)
  6160. {
  6161. feeDatas.Add(new StatisticsOPYOY(
  6162. feeId: item.Id,
  6163. feeName: item.Name,
  6164. currPeriodFee: 0.00M,
  6165. samePeriodFee: 0.00M,
  6166. currPeriodGroupTotal: 0,
  6167. samePeriodGroupTotal: 0,
  6168. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  6169. ));
  6170. }
  6171. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  6172. monthData[i].FeeDatas = feeDatas.ToArray();
  6173. }
  6174. }
  6175. //3、费用子类是否足够
  6176. return Ok(JsonView(true, "操作成功!", monthData));
  6177. }
  6178. return Ok(JsonView(false, "操作失败!"));
  6179. }
  6180. /// <summary>
  6181. /// 团组数据统计
  6182. /// 团组预算/实际成本
  6183. /// </summary>
  6184. /// <param name="_dto"></param>
  6185. /// <returns></returns>
  6186. [HttpPost("StatisticsGroupCost")]
  6187. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6188. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  6189. {
  6190. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6191. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6192. endDt = $"{_dto.Year}-12-31 23:59:59";
  6193. var sql = string.Format(@"
  6194. SELECT
  6195. ROW_NUMBER() OVER(
  6196. ORDER BY
  6197. di.VisitDate DESC
  6198. ) AS 'RowNumber',
  6199. di.Id,
  6200. di.TeamName AS 'GroupName',
  6201. di.ClientUnit,
  6202. di.VisitDate,
  6203. di.VisitDays,
  6204. di.VisitPNumber,
  6205. (
  6206. SELECT
  6207. TOP 1 CASE
  6208. ISNUMERIC (gcp.Currency)
  6209. WHEN 1 THEN (
  6210. SELECT
  6211. Name
  6212. FROM
  6213. Sys_SetData sd
  6214. WHERE
  6215. CAST(gcp.Currency AS INT) = sd.Id
  6216. )
  6217. ELSE gcp.Currency
  6218. END AS 'CurrencyCode'
  6219. FROM
  6220. Grp_GroupCostParameter gcp
  6221. WHERE
  6222. gcp.IsDel = 0
  6223. AND gcp.DiId = di.Id
  6224. ) Budget_CurrencyCode,
  6225. --预算币种
  6226. (
  6227. SELECT
  6228. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  6229. FROM
  6230. Grp_GroupCostParameter gcp
  6231. WHERE
  6232. gcp.IsDel = 0
  6233. AND gcp.DiId = di.Id
  6234. ) Budget_Rate,
  6235. --预算汇率
  6236. (
  6237. SELECT
  6238. CAST(
  6239. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  6240. )
  6241. FROM
  6242. Grp_GroupCostParameter gcp
  6243. WHERE
  6244. gcp.IsDel = 0
  6245. AND gcp.DiId = di.id
  6246. ) Budget_VisaAmount,
  6247. -- 预算签证成本
  6248. (
  6249. SELECT
  6250. CAST(
  6251. SUM(
  6252. (
  6253. (ccp.PayMoney * ccp.DayRate)
  6254. )
  6255. ) AS DECIMAL(12, 2)
  6256. )
  6257. FROM
  6258. Grp_VisaInfo vi
  6259. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6260. AND ccp.CTable = 80
  6261. AND vi.Id = ccp.CId
  6262. WHERE
  6263. vi.IsDel = 0
  6264. AND ccp.IsAuditGM = 1
  6265. AND ccp.IsPay = 1
  6266. AND di.Id = vi.DIId
  6267. ) AS Reality_VisaAmount,
  6268. -- 实际签证成本
  6269. (
  6270. SELECT
  6271. CAST(
  6272. SUM(
  6273. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  6274. ) AS DECIMAL(12, 2)
  6275. )
  6276. FROM
  6277. Grp_GroupCostParameter gcp
  6278. WHERE
  6279. gcp.IsDel = 0
  6280. AND gcp.DiId = di.id
  6281. ) Budget_AirTicketAmount,
  6282. -- 预算机票成本
  6283. (
  6284. SELECT
  6285. CAST(
  6286. SUM(
  6287. (
  6288. (ccp.PayMoney * ccp.DayRate)
  6289. )
  6290. ) AS DECIMAL(12, 2)
  6291. )
  6292. FROM
  6293. Grp_AirTicketReservations atr
  6294. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6295. AND ccp.CTable = 85
  6296. AND atr.Id = ccp.CId
  6297. WHERE
  6298. atr.IsDel = 0
  6299. AND ccp.IsAuditGM = 1
  6300. AND ccp.IsPay = 1
  6301. AND di.Id = atr.DiId
  6302. ) Reality_AirTicketAmount,
  6303. --实际机票
  6304. (
  6305. SELECT
  6306. CAST(
  6307. SUM(
  6308. COALESCE(gcp.SGRCB, 0) * COALESCE(gcp.SGRNumber, 0) + COALESCE(gcp.TBRCB, 0) * COALESCE(gcp.TBRNumber, 0) + COALESCE(gcp.SUITECB, 0) * COALESCE(gcp.SUITENumber, 0) + COALESCE(gcp.SUITENumber, 0) * COALESCE(gcp.JSESXS, 0)
  6309. ) AS DECIMAL(12, 2)
  6310. )
  6311. FROM
  6312. Grp_GroupCostParameter gcp
  6313. WHERE
  6314. gcp.IsDel = 0
  6315. AND gcp.DiId = di.id
  6316. ) Budget_HotelAmount,
  6317. -- 预算酒店成本
  6318. (
  6319. SELECT
  6320. CAST(
  6321. SUM(
  6322. (ccp.PayMoney * ccp.DayRate)
  6323. ) AS DECIMAL(12, 2)
  6324. )
  6325. FROM
  6326. Grp_HotelReservations hr
  6327. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6328. WHERE
  6329. hr.IsDel = 0
  6330. AND ccp.IsDel = 0
  6331. AND ccp.CTable = 76
  6332. AND ccp.IsAuditGM = 1
  6333. AND ccp.PayMoney <> 0
  6334. AND ccp.IsPay = 1
  6335. AND di.Id = hr.DiId
  6336. ) AS Reality_HotelAmount,
  6337. -- 实际酒店成本
  6338. (
  6339. SELECT
  6340. CAST(
  6341. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  6342. )
  6343. FROM
  6344. Grp_GroupCostParameter gcp
  6345. WHERE
  6346. gcp.IsDel = 0
  6347. AND gcp.DiId = di.id
  6348. ) Budget_OPAmount,
  6349. -- 预算 OP
  6350. (
  6351. SELECT
  6352. CAST(
  6353. SUM(
  6354. (
  6355. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  6356. )
  6357. ) AS DECIMAL(12, 2)
  6358. )
  6359. FROM
  6360. Grp_CarTouristGuideGroundReservations ctggr
  6361. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6362. AND ccp.CTable = 79
  6363. AND ctggr.Id = ccp.CId
  6364. WHERE
  6365. ctggr.IsDel = 0
  6366. AND ccp.IsAuditGM = 1
  6367. AND ccp.IsPay = 1
  6368. AND di.Id = ctggr.DiId
  6369. ) AS Reality_OPAmount,
  6370. -- 实际 OP
  6371. (
  6372. SELECT
  6373. CAST(
  6374. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  6375. )
  6376. FROM
  6377. Grp_GroupCostParameter gcp
  6378. WHERE
  6379. gcp.IsDel = 0
  6380. AND gcp.DiId = di.id
  6381. ) Budget_OAAmount,
  6382. -- 预算 商邀
  6383. (
  6384. SELECT
  6385. CAST(
  6386. SUM(
  6387. (ccp.PayMoney * ccp.DayRate)
  6388. ) AS DECIMAL(12, 2)
  6389. )
  6390. FROM
  6391. Grp_InvitationOfficialActivities ioa
  6392. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6393. AND ccp.CTable = 81
  6394. AND ioa.Id = ccp.CId
  6395. WHERE
  6396. ioa.IsDel = 0
  6397. AND ccp.IsAuditGM = 1
  6398. AND ccp.IsPay = 1
  6399. AND di.Id = ioa.Diid
  6400. ) AS Reality_OAAmount,
  6401. -- 实际 商邀
  6402. (
  6403. SELECT
  6404. CAST(
  6405. SUM(
  6406. COALESCE(gcp.BXCB, 0) * COALESCE(gcp.BXRS, 0) + COALESCE(gcp.HCPCB, 0) * COALESCE(gcp.HCPRS, 0) + COALESCE(gcp.CPCB, 0) * COALESCE(gcp.CPRS, 0) + COALESCE(gcp.HSCB, 0) * COALESCE(gcp.HSRS, 0) + COALESCE(gcp.LYJCB, 0) * COALESCE(gcp.LYJRS, 0)
  6407. ) AS DECIMAL(12, 2)
  6408. )
  6409. FROM
  6410. Grp_GroupCostParameter gcp
  6411. WHERE
  6412. gcp.IsDel = 0
  6413. AND gcp.DiId = di.id
  6414. ) Budget_OtherAmount,
  6415. -- 预算其他成本
  6416. (
  6417. SELECT
  6418. CAST(
  6419. SUM(
  6420. (ccp.PayMoney * ccp.DayRate)
  6421. ) AS DECIMAL(12, 2)
  6422. )
  6423. FROM
  6424. Grp_Customers ic
  6425. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6426. AND ccp.CTable = 82
  6427. AND ic.Id = ccp.CId
  6428. WHERE
  6429. ic.IsDel = 0
  6430. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  6431. AND di.Id = ic.DiId
  6432. ) AS Reality_InsureAmount,
  6433. -- 实际保险成本
  6434. (
  6435. SELECT
  6436. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  6437. FROM
  6438. Grp_DecreasePayments dp
  6439. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6440. AND ccp.CTable = 98
  6441. AND dp.Id = ccp.CId
  6442. WHERE
  6443. dp.IsDel = 0
  6444. AND ccp.Ctable = 98
  6445. AND ccp.IsAuditGM = 1
  6446. AND ccp.IsPay = 1
  6447. AND di.Id = dp.Diid
  6448. ) AS Reality_OtherCostAmount -- 实际其他款项
  6449. FROM
  6450. Grp_DelegationInfo di
  6451. WHERE
  6452. di.IsDel = 0
  6453. AND di.IsBid = 0
  6454. --AND di.TeamDid IN (38, 39, 40, 1048)
  6455. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  6456. ", beginDt, endDt);
  6457. if (!string.IsNullOrEmpty(_dto.Search))
  6458. {
  6459. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  6460. }
  6461. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  6462. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  6463. var total = view.Count;
  6464. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  6465. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  6466. if (data.Count > 0)
  6467. {
  6468. var diIds = data.Select(x => x.Id).ToList();
  6469. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  6470. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6471. .Where(x => x.IsDel == 0 &&
  6472. diIds.Contains(x.DIId) &&
  6473. x.IsPay == 1 &&
  6474. x.IsAuditGM == 1
  6475. )
  6476. .ToListAsync();
  6477. for (int i = 0; i < data.Count; i++)
  6478. {
  6479. var info = data[i];
  6480. info.RowNumber = i + 1;
  6481. #region 1:签证 80
  6482. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  6483. var visaDesc = "-";
  6484. if (visaDatas.Count > 0)
  6485. {
  6486. visaDesc = $"实际币种金额:";
  6487. foreach (var visa in visaDatas)
  6488. {
  6489. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  6490. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  6491. }
  6492. }
  6493. info.Reality_VisaAmountDesc = visaDesc;
  6494. #endregion
  6495. #region 2:机票 85
  6496. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  6497. var airDesc = "-";
  6498. if (airDatas.Count > 0)
  6499. {
  6500. airDesc = $"实际币种金额:";
  6501. foreach (var air in airDatas)
  6502. {
  6503. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  6504. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  6505. }
  6506. }
  6507. info.Reality_AirTicketAmountDesc = airDesc;
  6508. #endregion
  6509. #region 3:酒店 76
  6510. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  6511. var hotelDesc = "-";
  6512. if (hotelDatas.Count > 0)
  6513. {
  6514. hotelDesc = $"实际币种金额:";
  6515. foreach (var hotel in hotelDatas)
  6516. {
  6517. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  6518. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  6519. }
  6520. }
  6521. info.Reality_HotelAmountDesc = hotelDesc;
  6522. #endregion
  6523. #region 4:OP 79
  6524. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  6525. var opDesc = "-";
  6526. if (opDatas.Count > 0)
  6527. {
  6528. opDesc = $"实际币种金额;";
  6529. foreach (var op in opDatas)
  6530. {
  6531. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  6532. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  6533. }
  6534. }
  6535. info.Reality_OPAmountDesc = opDesc;
  6536. #endregion
  6537. #region 5:商邀 81
  6538. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  6539. var oaDesc = "-";
  6540. if (oaDatas.Count > 0)
  6541. {
  6542. oaDesc = $"实际币种金额:";
  6543. foreach (var oa in oaDatas)
  6544. {
  6545. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  6546. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  6547. }
  6548. }
  6549. info.Reality_OAAmountDesc = oaDesc;
  6550. #endregion
  6551. #region 6:其他款项(保险 82、其他款项 98)
  6552. var cTables = new List<int>() { 82, 98 };
  6553. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  6554. var otherDesc = "-";
  6555. if (otherDatas.Count > 0)
  6556. {
  6557. otherDesc = $"实际币种金额:";
  6558. foreach (var other in otherDatas)
  6559. {
  6560. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  6561. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  6562. }
  6563. }
  6564. info.Reality_OtherCostAmountDesc = otherDesc;
  6565. #endregion
  6566. }
  6567. }
  6568. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  6569. return Ok(JsonView(briefData, total));
  6570. }
  6571. /// <summary>
  6572. /// 团组数据统计
  6573. /// 当前时间团组所在城市
  6574. /// </summary>
  6575. /// <param name="dto"></param>
  6576. /// <returns></returns>
  6577. [HttpPost("StatisticsNowCityOfGroup")]
  6578. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6579. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  6580. {
  6581. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  6582. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  6583. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  6584. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  6585. .Select(x => new { x.Id, x.VisitCountry, x.TeamName,x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  6586. ToListAsync();
  6587. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  6588. var groupIds = groupInfos.Select(x => x.Id).ToList();
  6589. //三字码
  6590. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  6591. //国家
  6592. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  6593. //公务
  6594. var OADatas = await _sqlSugar
  6595. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  6596. .ToListAsync();
  6597. //酒店
  6598. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  6599. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  6600. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  6601. .Select((hr, ntf) => new {
  6602. hr.DiId,
  6603. hr.AreaId,
  6604. hr.HotelName,
  6605. hr.CheckInDate,
  6606. hr.CheckOutDate,
  6607. hr.HotelAddress,
  6608. ntf.Country,
  6609. ntf.City
  6610. })
  6611. .ToListAsync();
  6612. //机票
  6613. /*
  6614. *舱位类型
  6615. *457 头等舱
  6616. *458 公务舱
  6617. *459 超经舱
  6618. *460 经济舱
  6619. *461 退票
  6620. *565 其他
  6621. *574 长段公务舱
  6622. *575 短途经济舱
  6623. *1023 行程单打印费
  6624. *1024 选座费
  6625. */
  6626. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  6627. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6628. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  6629. .ToListAsync();
  6630. string[] characters = { "|", "、" };
  6631. var result = new List<StatisticsNowCityOfGroupResultView>();
  6632. foreach (var item in groupInfos)
  6633. {
  6634. string statusText = string.Empty,
  6635. address = string.Empty;
  6636. var countrys = item.VisitCountry;
  6637. if (string.IsNullOrEmpty(countrys)) continue;
  6638. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  6639. var stutus = true;
  6640. #region 公务
  6641. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6642. if (currOADatas.Any())
  6643. {
  6644. foreach (var curr_oa in currOADatas)
  6645. {
  6646. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  6647. if (localTime == null) continue;
  6648. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  6649. var currOaDtEnd = currOaDtStart.AddHours(2);
  6650. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  6651. if (!currTimeZoneStatus) continue;
  6652. stutus = false;
  6653. statusText = "公务活动中";
  6654. address = curr_oa.Address;
  6655. break;
  6656. }
  6657. }
  6658. #endregion
  6659. #region 酒店
  6660. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6661. if (stutus && hotelDatas.Any())
  6662. {
  6663. foreach (var curr_hotel in currHotelDatas)
  6664. {
  6665. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  6666. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  6667. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  6668. {
  6669. int year = checkInDt.Year,
  6670. month = checkInDt.Month,
  6671. day = checkInDt.Day;
  6672. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  6673. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  6674. checkInDt = checkInDt.AddDays(1);
  6675. }
  6676. if (!timeRanges.Any()) continue;
  6677. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  6678. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  6679. if (countryInfo == null) continue;
  6680. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  6681. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  6682. if (!currTimeZoneStatus) continue;
  6683. stutus = false;
  6684. statusText = "入住酒店中";
  6685. address = curr_hotel.HotelAddress;
  6686. break;
  6687. }
  6688. }
  6689. #endregion
  6690. #region 机票--通过三字码解析处理
  6691. var airTicketDatas = GetTableByBlackCode(item.Id);
  6692. if (stutus && airTicketDatas != null)
  6693. {
  6694. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  6695. {
  6696. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  6697. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  6698. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  6699. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  6700. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  6701. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  6702. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  6703. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  6704. if (string.IsNullOrEmpty(departThree)) continue;
  6705. string departAirThree = departThree.Substring(0, 3),
  6706. arriveAirThree = departThree.Substring(3, 3);
  6707. string departCountry = string.Empty,
  6708. departCity = string.Empty,
  6709. departAirport = string.Empty,
  6710. arriveCountry = string.Empty,
  6711. arriveCity = string.Empty,
  6712. arriveAirport = string.Empty;
  6713. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  6714. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  6715. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  6716. departCountry = departCountryInfo.Country;
  6717. departCity = departCountryInfo.City;
  6718. departAirport = departCountryInfo.AirPort;
  6719. arriveCountry = arriveCountryInfo.Country;
  6720. arriveCity = arriveCountryInfo.City;
  6721. arriveAirport = arriveCountryInfo.AirPort;
  6722. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"),out DateTime arriveDateTime);
  6723. if (!arriveDateTimeBool) continue;
  6724. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  6725. var filghtMinutesBool= int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  6726. if (!filghtHoursBool || !filghtHoursBool) continue;
  6727. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  6728. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry,arriveCity);
  6729. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  6730. if (!currTimeZoneStatus) continue;
  6731. stutus = false;
  6732. statusText = $"正飞往{arriveCity}城市中";
  6733. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  6734. break;
  6735. }
  6736. }
  6737. if (stutus) statusText = $"其他";
  6738. #endregion
  6739. result.Add(new StatisticsNowCityOfGroupResultView()
  6740. {
  6741. GroupName = item.TeamName,
  6742. Client = item.ClientUnit,
  6743. StatusText = statusText,
  6744. Address = address
  6745. });
  6746. }
  6747. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  6748. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6749. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6750. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  6751. });
  6752. var result1 = result.GroupBy(x => x.Address).Select(g => new
  6753. {
  6754. address = g.Key,
  6755. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  6756. });
  6757. if (!result1.Any()) return Ok(JsonView(false,"今天暂无出行的的团!"));
  6758. return Ok(JsonView(result1));
  6759. }
  6760. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  6761. {
  6762. var info = new StatisticsNowCityOfGroupView();
  6763. if (string.IsNullOrEmpty(cityLable)) return info;
  6764. var cityArray = cityLable.Split("-");
  6765. var departCityCode = cityArray[0];
  6766. var arriveCityCode = cityArray[1];
  6767. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  6768. info.DepartAirportCode = departCityCode;
  6769. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  6770. info.DepartCityName = departAirportInfo?.City ?? "-";
  6771. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  6772. info.ArriveAirportCode = arriveCityCode;
  6773. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  6774. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  6775. return info;
  6776. }
  6777. #endregion
  6778. #region 企业利润
  6779. /// <summary>
  6780. /// 企业利润 Excel导出
  6781. /// </summary>
  6782. /// <param name="_dto"></param>
  6783. /// <returns></returns>
  6784. [HttpPost("CorporateProfitExcelDownload")]
  6785. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6786. public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
  6787. {
  6788. int portType = dto.PortType,
  6789. userId = dto.UserId,
  6790. pageId = dto.PageId;
  6791. #region 参数验证
  6792. var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
  6793. var validResult = await validationRules.ValidateAsync(dto);
  6794. if (!validResult.IsValid)
  6795. {
  6796. var errors = new StringBuilder();
  6797. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  6798. return Ok(JsonView(false, errors.ToString()));
  6799. }
  6800. #region 页面操作权限验证
  6801. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  6802. //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  6803. #endregion
  6804. #endregion
  6805. DateTime beginDt = DateTime.Parse($"{dto.BeginDt} 00:00:00"),
  6806. endDt = DateTime.Parse($"{dto.EndDt} 23:59:59");
  6807. if (portType == 1 || portType == 2 ||portType == 3) // web/Android/IOS
  6808. {
  6809. //获取模板
  6810. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/利润报表.xlsx");
  6811. var designer = new WorkbookDesigner();
  6812. designer.Workbook = new Workbook(tempPath);
  6813. var currDt = DateTime.Now;
  6814. DateTime startTimeMonth = new DateTime(currDt.Year, currDt.Month, 1); //月初
  6815. DateTime endTimeMonth = startTimeMonth.AddMonths(1).AddDays(-1); //月末
  6816. var yearDic = CalculatePrice(beginDt,endDt);
  6817. var monthDic = CalculatePrice(startTimeMonth, endTimeMonth);
  6818. #region 年
  6819. //收入
  6820. designer.SetDataSource("TotalMoney", yearDic["TotalMoney"].ToString("#0.00"));
  6821. designer.SetDataSource("GroupIncome", yearDic["GroupIncome"].ToString("#0.00"));
  6822. designer.SetDataSource("ActivityIncome", yearDic["ActivityIncome"].ToString("#0.00"));
  6823. designer.SetDataSource("CompetitionIncome", yearDic["CompetitionIncome"].ToString("#0.00"));
  6824. designer.SetDataSource("OtherIncome", yearDic["OtherIncome"].ToString("#0.00"));
  6825. //成本
  6826. designer.SetDataSource("TotalCost", yearDic["TotalCost"].ToString("#0.00"));
  6827. designer.SetDataSource("GroupCost", yearDic["GroupCost"].ToString("#0.00"));
  6828. designer.SetDataSource("ActivityCost", yearDic["ActivityCost"].ToString("#0.00"));
  6829. designer.SetDataSource("CompetitionCost", yearDic["CompetitionCost"].ToString("#0.00"));
  6830. designer.SetDataSource("OtherCost", yearDic["OtherCost"].ToString("#0.00"));
  6831. //毛利金额
  6832. designer.SetDataSource("TotalGrossProfit", yearDic["TotalGrossProfit"].ToString("#0.00"));
  6833. designer.SetDataSource("GroupGrossProfit", yearDic["GroupGrossProfit"].ToString("#0.00"));
  6834. designer.SetDataSource("ActivityGrossProfit", yearDic["ActivityGrossProfit"].ToString("#0.00"));
  6835. designer.SetDataSource("CompetitionGrossProfit", yearDic["CompetitionGrossProfit"].ToString("#0.00"));
  6836. designer.SetDataSource("OtherGrossProfit", yearDic["OtherGrossProfit"].ToString("#0.00"));
  6837. //毛利率
  6838. designer.SetDataSource("TotalInterestRate", yearDic["TotalInterestRate"].ToString("#0.00") + "%");
  6839. designer.SetDataSource("GroupInterestRate", yearDic["GroupInterestRate"].ToString("#0.00") + "%");
  6840. designer.SetDataSource("ActivityInterestRate", yearDic["ActivityInterestRate"].ToString("#0.00") + "%");
  6841. designer.SetDataSource("CompetitionInterestRate", yearDic["CompetitionInterestRate"].ToString("#0.00") + "%");
  6842. designer.SetDataSource("OtherInterestRate", yearDic["OtherInterestRate"].ToString("#0.00") + "%");
  6843. //数量
  6844. designer.SetDataSource("TotalQuantity", yearDic["TotalQuantity"].ToString());
  6845. designer.SetDataSource("GroupQuantity", yearDic["GroupQuantity"].ToString());
  6846. designer.SetDataSource("ActivityQuantity", yearDic["ActivityQuantity"].ToString());
  6847. designer.SetDataSource("CompetitionQuantity", yearDic["CompetitionQuantity"].ToString());
  6848. designer.SetDataSource("OtherQuantity", yearDic["OtherQuantity"].ToString());
  6849. //办公费用
  6850. designer.SetDataSource("OfficeTotalCost", yearDic["OfficeTotalCost"].ToString());
  6851. #endregion
  6852. #region 月
  6853. //收入
  6854. designer.SetDataSource("MonthAllIncomes", monthDic["TotalMoney"].ToString("#0.00"));
  6855. designer.SetDataSource("MonthtzIncomes", monthDic["GroupIncome"].ToString("#0.00"));
  6856. designer.SetDataSource("MonthhwIncomes", monthDic["ActivityIncome"].ToString("#0.00"));
  6857. designer.SetDataSource("MonthssIncomes", monthDic["CompetitionIncome"].ToString("#0.00"));
  6858. designer.SetDataSource("MonthqtIncomes", monthDic["OtherIncome"].ToString("#0.00"));
  6859. //成本
  6860. designer.SetDataSource("MonthAllCost", monthDic["TotalCost"].ToString("#0.00"));
  6861. designer.SetDataSource("MonthtzCost", monthDic["GroupCost"].ToString("#0.00"));
  6862. designer.SetDataSource("MonthhwCost", monthDic["ActivityCost"].ToString("#0.00"));
  6863. designer.SetDataSource("MonthssCost", monthDic["CompetitionCost"].ToString("#0.00"));
  6864. designer.SetDataSource("MonthqtCost", monthDic["OtherCost"].ToString("#0.00"));
  6865. //毛利金额
  6866. designer.SetDataSource("MonthAllGross", monthDic["TotalGrossProfit"].ToString("#0.00"));
  6867. designer.SetDataSource("MonthtzGross", monthDic["GroupGrossProfit"].ToString("#0.00"));
  6868. designer.SetDataSource("MonthhwGross", monthDic["ActivityGrossProfit"].ToString("#0.00"));
  6869. designer.SetDataSource("MonthssGross", monthDic["CompetitionGrossProfit"].ToString("#0.00"));
  6870. designer.SetDataSource("MonthqtGross", monthDic["OtherGrossProfit"].ToString("#0.00"));
  6871. #endregion
  6872. designer.Process();
  6873. //文件名
  6874. string fileName = $"利润报表({dto.BeginDt}至{dto.EndDt}){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  6875. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "CorporateProfit/" + fileName);
  6876. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/CorporateProfit/" + fileName;
  6877. return Ok(JsonView(true, "成功", url));
  6878. }
  6879. return Ok(JsonView(false));
  6880. }
  6881. /// <summary>
  6882. /// 计算团组全部费用
  6883. /// </summary>
  6884. /// <param name="startTime"></param>
  6885. /// <param name="endTime"></param>
  6886. /// <returns></returns>
  6887. private Dictionary<string, decimal> CalculatePrice(DateTime startTime, DateTime endTime)
  6888. {
  6889. DateTime beginDt = startTime,
  6890. endDt = endTime;
  6891. var dic = new Dictionary<string, decimal>();
  6892. decimal totalIncomes = 0.00M; //总收入
  6893. decimal totalCost = 0.00M; //总成本
  6894. #region 团组
  6895. //团组收入,会务收入,赛事项目收入,其他非团组收入
  6896. decimal groupIncome = 0.00M; //团组收入
  6897. decimal activityIncome = 0.00M; //会务收入
  6898. decimal competitionIncome = 0.00M; //赛事项目收入
  6899. decimal otherIncome = 0.00M; //其他非团组收入
  6900. decimal groupCost = 0.00M; //团组成本
  6901. decimal activityCost = 0.00M; //会务成本
  6902. decimal competitionCost = 0.00M; //赛事项目成本
  6903. decimal otherCost = 0.00M; //其他非团组成本
  6904. var groupDatas = _sqlSugar.Queryable<Grp_DelegationInfo>()
  6905. .Where(x => x.IsDel == 0 && x.VisitDate >= beginDt && x.VisitDate <= endDt)
  6906. .Select(x => new { x.Id, x.TeamName,x.TeamDid, x.VisitDate })
  6907. .ToList();
  6908. var groupIds = groupDatas.Select(x => x.Id).ToList();
  6909. //应收
  6910. var receivableDatas = _sqlSugar.Queryable<Fin_ForeignReceivables>().Where(x => x.IsDel == 0 && groupIds.Contains(x.Diid)).ToList();
  6911. //已收
  6912. var receivedDatas = _sqlSugar.Queryable<Fin_ProceedsReceived>().Where(x => x.IsDel == 0 && groupIds.Contains(x.Diid)).ToList();
  6913. //成本
  6914. var costDatas = _sqlSugar.Queryable<Grp_CreditCardPayment>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DIId) && x.IsPay == 1).ToList();
  6915. //提成
  6916. var groupRoyaltyDatas = _sqlSugar.Queryable<Fin_RoyaltyConfirm>().Where(x => x.IsDel == 0 && groupIds.Contains(x.TeamId) && x.IsConfirm == 1).ToList();
  6917. #region 团组
  6918. var groupTyepIds = new List<int> { 38, 39, 40, 1048 };
  6919. var groupIncomIds = groupDatas.Where(x => groupTyepIds.Contains(x.TeamDid)).Select(x => x.Id).ToList();
  6920. //收入
  6921. groupIncome = receivedDatas.Where(x => groupIncomIds.Contains(x.Diid)).Sum(x => x.Price);
  6922. //成本
  6923. groupCost = costDatas.Where(x => groupIncomIds.Contains(x.DIId)).Sum(x => x.PayMoney * x.DayRate);
  6924. //提成
  6925. groupCost += groupRoyaltyDatas.Where(x => groupIncomIds.Contains(x.TeamId)).Sum(x => x.Price);
  6926. #endregion
  6927. #region 会务
  6928. var activityTyepIds = new List<int> { 302, 691 };
  6929. var activityIncomIds = groupDatas.Where(x => activityTyepIds.Contains(x.TeamDid)).Select(x => x.Id).ToList();
  6930. //收入
  6931. activityIncome = receivedDatas.Where(x => activityIncomIds.Contains(x.Diid)).Sum(x => x.Price);
  6932. //成本
  6933. activityCost = costDatas.Where(x => activityIncomIds.Contains(x.DIId)).Sum(x => x.PayMoney * x.DayRate);
  6934. //提成
  6935. activityCost += groupRoyaltyDatas.Where(x => activityIncomIds.Contains(x.TeamId)).Sum(x => x.Price);
  6936. #endregion
  6937. #region 赛事
  6938. var competitionTyepIds = new List<int> { 762, 1047 };
  6939. var competitionIncomIds = groupDatas.Where(x => competitionTyepIds.Contains(x.TeamDid)).Select(x => x.Id).ToList();
  6940. //收入
  6941. competitionIncome = receivedDatas.Where(x => competitionIncomIds.Contains(x.Diid)).Sum(x => x.Price);
  6942. //成本
  6943. competitionCost = costDatas.Where(x => competitionIncomIds.Contains(x.DIId)).Sum(x => x.PayMoney * x.DayRate);
  6944. //提成
  6945. competitionCost += groupRoyaltyDatas.Where(x => competitionIncomIds.Contains(x.TeamId)).Sum(x => x.Price);
  6946. #endregion
  6947. #region 其他非团组
  6948. //收入
  6949. var otherTyepIds = new List<int> { 102, 248 };
  6950. var otherIncomIds = groupDatas.Where(x => otherTyepIds.Contains(x.TeamDid)).Select(x => x.Id).ToList();
  6951. otherIncome = receivedDatas.Where(x => otherIncomIds.Contains(x.Diid)).Sum(x => x.Price);
  6952. //成本
  6953. otherCost = costDatas.Where(x => otherIncomIds.Contains(x.DIId)).Sum(x => x.PayMoney * x.DayRate);
  6954. //提成
  6955. competitionCost += groupRoyaltyDatas.Where(x => otherIncomIds.Contains(x.TeamId)).Sum(x => x.Price);
  6956. #endregion
  6957. #endregion
  6958. #region 办公费用
  6959. //48人员费用 49办公费用 50 销售费用 51 其他费用 55 大运会
  6960. var typeIds = new List<int>() {
  6961. 48, //人员费用
  6962. 49, //办公费用
  6963. 50, //销售费用
  6964. 51, //其他费用
  6965. 55, //大运会
  6966. 90, //各部门基础固定费用明细
  6967. };
  6968. //var priceTypeData = _sqlSugar.Queryable<Sys_SetData>().Where(s => typeIds.Contains(s.Id)).ToList();
  6969. var priceSubTypeDatas = _sqlSugar.Queryable<Sys_SetData>().Where(s => s.IsDel == 0 && typeIds.Contains(s.STid)).ToList();
  6970. var priceSubTypeIds = priceSubTypeDatas.Select(x => x.Id).ToList();
  6971. var dailyFeeDatass = _sqlSugar
  6972. .Queryable<Fin_DailyFeePayment>()
  6973. .Where(x => x.IsDel == 0 && x.CreateTime >= beginDt && x.CreateTime <= endDt && priceSubTypeIds.Contains(x.PriceTypeId) && x.IsPay == 1)
  6974. .ToList();
  6975. //人员费用
  6976. var staffCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 48).Select(x => x.Id).ToList();
  6977. decimal staffCost = dailyFeeDatass.Where(x => staffCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6978. //办公费用
  6979. var officeCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 49).Select(x => x.Id).ToList();
  6980. decimal officeCost = dailyFeeDatass.Where(x => officeCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6981. //销售费用
  6982. var marketingCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 50).Select(x => x.Id).ToList();
  6983. decimal marketingCost = dailyFeeDatass.Where(x => marketingCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6984. //其他费用
  6985. var bg_otherCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 51).Select(x => x.Id).ToList();
  6986. decimal bg_otherCost = dailyFeeDatass.Where(x => bg_otherCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6987. //大运会
  6988. var universityGamesCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 55).Select(x => x.Id).ToList();
  6989. decimal universityGamesCost = dailyFeeDatass.Where(x => universityGamesCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6990. //各部门基础固定费用明细
  6991. var basicCostTypeIds = priceSubTypeDatas.Where(x => x.STid == 90).Select(x => x.Id).ToList();
  6992. decimal basicGamesCost = dailyFeeDatass.Where(x => basicCostTypeIds.Contains(x.PriceTypeId)).Sum(x => x.SumPrice);
  6993. #endregion
  6994. totalCost = costDatas.Sum(x => x.PayMoney * x.DayRate) + groupRoyaltyDatas.Sum(x => x.Price);
  6995. totalIncomes = receivedDatas.Sum(x => x.Price);
  6996. #region 填充值
  6997. #region 本年累计
  6998. decimal totalInterestRate = 0.00M,
  6999. totalGrossProfit = 0.00M;
  7000. if (totalIncomes > 0)
  7001. {
  7002. totalGrossProfit = totalIncomes - totalCost;
  7003. totalInterestRate = totalGrossProfit / totalIncomes * 100;
  7004. }
  7005. //业务数量
  7006. dic.Add("TotalQuantity", groupDatas.Count);
  7007. //应收金额
  7008. dic.Add("TotalMoney", totalIncomes);
  7009. //成本
  7010. dic.Add("TotalCost", totalCost);
  7011. //毛利润
  7012. dic.Add("TotalGrossProfit", totalGrossProfit);
  7013. //利率
  7014. dic.Add("TotalInterestRate", totalInterestRate);
  7015. #endregion
  7016. #region 团组
  7017. decimal groupInterestRate = 0.00M,
  7018. groupGrossProfit = 0.00M;
  7019. if (groupIncome > 0)
  7020. {
  7021. groupGrossProfit = groupIncome - groupCost;
  7022. groupInterestRate = groupGrossProfit / groupIncome * 100;
  7023. }
  7024. //数量
  7025. dic.Add("GroupQuantity", groupIncomIds.Count);
  7026. //收入
  7027. dic.Add("GroupIncome", groupIncome);
  7028. //成本
  7029. dic.Add("GroupCost", groupCost);
  7030. //毛利润
  7031. dic.Add("GroupGrossProfit", groupGrossProfit);
  7032. //利率
  7033. dic.Add("GroupInterestRate", groupInterestRate);
  7034. #endregion
  7035. #region 会务
  7036. decimal activityInterestRate = 0.00M,
  7037. activityGrossProfit = 0.00M;
  7038. if (activityIncome > 0)
  7039. {
  7040. activityGrossProfit = activityIncome - activityCost;
  7041. activityInterestRate = activityGrossProfit / activityIncome * 100;
  7042. }
  7043. //数量
  7044. dic.Add("ActivityQuantity", activityIncomIds.Count);
  7045. //收入
  7046. dic.Add("ActivityIncome", activityIncome);
  7047. //成本
  7048. dic.Add("ActivityCost", activityCost);
  7049. //毛利润
  7050. dic.Add("ActivityGrossProfit", activityGrossProfit);
  7051. //利率
  7052. dic.Add("ActivityInterestRate", activityInterestRate);
  7053. #endregion
  7054. #region 赛事项目
  7055. decimal competitionInterestRate = 0.00M,
  7056. competitionGrossProfit = 0.00M;
  7057. if (competitionIncome > 0)
  7058. {
  7059. competitionGrossProfit = competitionIncome - competitionCost;
  7060. activityInterestRate = competitionGrossProfit / competitionIncome * 100;
  7061. }
  7062. //数量
  7063. dic.Add("CompetitionQuantity", competitionIncomIds.Count);
  7064. //收入
  7065. dic.Add("CompetitionIncome", competitionIncome);
  7066. //成本
  7067. dic.Add("CompetitionCost", competitionCost);
  7068. //毛利润
  7069. dic.Add("CompetitionGrossProfit", competitionGrossProfit);
  7070. //毛利率
  7071. dic.Add("CompetitionInterestRate", competitionInterestRate);
  7072. #endregion
  7073. #region 其他非团组
  7074. decimal otherInterestRate = 0.00M,
  7075. otherGrossProfit = 0.00M;
  7076. if (otherIncome > 0)
  7077. {
  7078. otherGrossProfit = otherIncome - otherCost;
  7079. otherInterestRate = otherGrossProfit / otherIncome * 100;
  7080. }
  7081. //数量
  7082. dic.Add("OtherQuantity", otherIncomIds.Count);
  7083. //收入
  7084. dic.Add("OtherIncome", otherIncome);
  7085. //成本
  7086. dic.Add("OtherCost", otherCost);
  7087. //毛利润
  7088. dic.Add("OtherGrossProfit", otherGrossProfit);
  7089. //毛利率
  7090. dic.Add("OtherInterestRate", otherInterestRate);
  7091. #endregion
  7092. #region 办公费用
  7093. decimal officeTotalCost = dailyFeeDatass.Sum(x => x.SumPrice);
  7094. dic.Add("OfficeTotalCost", officeTotalCost);
  7095. #endregion
  7096. #endregion
  7097. return dic;
  7098. }
  7099. #endregion
  7100. }
  7101. }