StatisticsController.cs 445 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334
  1. using Aspose.Cells;
  2. using FluentValidation;
  3. using Humanizer;
  4. using NPOI.SS.Formula.Functions;
  5. using OASystem.API.OAMethodLib;
  6. using OASystem.API.OAMethodLib.JuHeAPI;
  7. using OASystem.Domain.AesEncryption;
  8. using OASystem.Domain.Dtos.Statistics;
  9. using OASystem.Domain.Entities.Customer;
  10. using OASystem.Domain.Entities.Financial;
  11. using OASystem.Domain.Entities.Groups;
  12. using OASystem.Domain.ViewModels.Financial;
  13. using OASystem.Domain.ViewModels.Groups;
  14. using OASystem.Domain.ViewModels.Statistics;
  15. using OASystem.Infrastructure.Repositories.Groups;
  16. using SqlSugar;
  17. using StackExchange.Redis;
  18. using System.ComponentModel;
  19. using System.ComponentModel.DataAnnotations;
  20. using System.Data;
  21. using System.Diagnostics.Eventing.Reader;
  22. using static OASystem.API.OAMethodLib.GeneralMethod;
  23. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  24. namespace OASystem.API.Controllers
  25. {
  26. /// <summary>
  27. /// 统计模块
  28. /// </summary>
  29. [Route("api/[controller]")]
  30. [ApiController]
  31. public class StatisticsController : ControllerBase
  32. {
  33. //private readonly int _decimalPlaces;
  34. private readonly IConfiguration _config;
  35. private readonly IMapper _mapper;
  36. private readonly SqlSugarClient _sqlSugar;
  37. private readonly DelegationInfoRepository _groupRep;
  38. private readonly SetDataRepository _setDataRep;
  39. private readonly TeamRateRepository _teamRateRep;
  40. private readonly VisitingClientsRepository _visitingClientsRep;
  41. private readonly IJuHeApiService _juHeApiService;
  42. /// <summary>
  43. /// Init
  44. /// </summary>
  45. /// <param name="mapper"></param>
  46. /// <param name="config"></param>
  47. /// <param name="sqlSugar"></param>
  48. /// <param name="groupRep"></param>
  49. /// <param name="setDataRep"></param>
  50. /// <param name="teamRate"></param>
  51. /// <param name="visitingClientsRep"></param>
  52. /// <param name="juHeApiService"></param>
  53. public StatisticsController(
  54. IMapper mapper,
  55. IConfiguration config,
  56. SqlSugarClient sqlSugar,
  57. DelegationInfoRepository groupRep,
  58. SetDataRepository setDataRep,
  59. TeamRateRepository teamRate,
  60. VisitingClientsRepository visitingClientsRep,
  61. IJuHeApiService juHeApiService
  62. )
  63. {
  64. _mapper = mapper;
  65. _config = config;
  66. _groupRep = groupRep;
  67. _setDataRep = setDataRep;
  68. _sqlSugar = sqlSugar;
  69. _teamRateRep = teamRate;
  70. _visitingClientsRep = visitingClientsRep;
  71. _juHeApiService = juHeApiService;
  72. }
  73. #region 团组报表
  74. /// <summary>
  75. /// 团组报表
  76. /// </summary>
  77. /// <param name="dto"></param>
  78. /// <returns></returns>
  79. [HttpPost("PostGroupStatementItems")]
  80. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  81. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto dto)
  82. {
  83. #region 参数验证
  84. if (dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  85. if (dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  86. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  87. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  88. #endregion
  89. if (dto.PortType < 1 || dto.PortType > 3)
  90. return Ok(JsonView(false, "端口类型错误"));
  91. try
  92. {
  93. // 构建基础查询 - 使用正确的SQLSugar链式调用
  94. var query = _sqlSugar.Queryable<Grp_DelegationInfo>()
  95. .LeftJoin<Sys_SetData>((gdi, ssd) => gdi.TeamDid == ssd.Id)
  96. .LeftJoin<Sys_SetData>((gdi, ssd, ssd1) => gdi.TeamLevSId == ssd1.Id)
  97. .LeftJoin<Sys_Users>((gdi, ssd, ssd1, su) => gdi.JietuanOperator == su.Id)
  98. .Where((gdi, ssd, ssd1, su) => gdi.IsDel == 0);
  99. // 状态筛选
  100. if (dto.IsSure == 0)
  101. {
  102. query = query.Where((gdi, ssd, ssd1, su) => gdi.IsSure == 0);
  103. }
  104. else if (dto.IsSure == 1)
  105. {
  106. query = query.Where((gdi, ssd, ssd1, su) => gdi.IsSure == 1);
  107. }
  108. // 多字段搜索 - 使用正确的表别名
  109. if (!string.IsNullOrWhiteSpace(dto.SearchCriteria))
  110. {
  111. var keywords = dto.SearchCriteria.Trim()
  112. .Split(new[] { ' ', ',', ',' }, StringSplitOptions.RemoveEmptyEntries);
  113. foreach (var keyword in keywords.Where(k => !string.IsNullOrWhiteSpace(k)))
  114. {
  115. var cleanKeyword = keyword.Trim();
  116. query = query.Where((gdi, ssd, ssd1, su) =>
  117. gdi.TeamName.Contains(cleanKeyword) ||
  118. gdi.ClientName.Contains(cleanKeyword) ||
  119. su.CnName.Contains(cleanKeyword) ||
  120. gdi.TourCode.Contains(cleanKeyword) ||
  121. gdi.ClientUnit.Contains(cleanKeyword) ||
  122. ssd.Name.Contains(cleanKeyword) ||
  123. ssd1.Name.Contains(cleanKeyword)
  124. );
  125. }
  126. }
  127. // 排序
  128. query = query.OrderBy((gdi, ssd, ssd1, su) => gdi.VisitDate, OrderByType.Desc);
  129. // 查询数据
  130. var totalCount = new RefAsync<int>(0);
  131. var data = await query
  132. .Select((gdi, ssd, ssd1, su) => new
  133. {
  134. Id = gdi.Id,
  135. TourCode = gdi.TourCode,
  136. TeamName = gdi.TeamName,
  137. ClientName = gdi.ClientName,
  138. ClientUnit = gdi.ClientUnit,
  139. VisitDate = gdi.VisitDate,
  140. VisitDays = gdi.VisitDays,
  141. VisitPNumber = gdi.VisitPNumber,
  142. IsSure = gdi.IsSure,
  143. TeamTypeId = ssd.Id,
  144. TeamTypeName = ssd.Name, // 使用正确的字段名
  145. TeamLevId = ssd1.Id,
  146. TeamLevName = ssd1.Name, // 使用正确的字段名
  147. JietuanOperatorName = su.CnName
  148. })
  149. .Distinct() // 确保数据不重复
  150. .ToPageListAsync(dto.PageIndex, dto.PageSize, totalCount);
  151. // 如果有数据,单独查询每个团组的最后收款时间
  152. if (data.Any())
  153. {
  154. var delegationIds = data.Select(x => x.Id).ToList();
  155. // 查询每个团组的最新收款时间
  156. var lastCollectionTimes = await _sqlSugar.Queryable<Fin_ProceedsReceived>()
  157. .Where(pr => delegationIds.Contains(pr.Diid))
  158. .GroupBy(pr => pr.Diid)
  159. .Select(pr => new
  160. {
  161. Diid = pr.Diid,
  162. LastTime = SqlFunc.AggregateMax(pr.CreateTime)
  163. })
  164. .ToListAsync();
  165. // 转换为最终的视图模型
  166. var lastCollectionDict = lastCollectionTimes.ToDictionary(x => x.Diid, x => x.LastTime);
  167. var resultData = data.Select(item => new GroupStatementItemView
  168. {
  169. Id = item.Id,
  170. TourCode = item.TourCode,
  171. TeamName = item.TeamName,
  172. ClientName = item.ClientName,
  173. ClientUnit = item.ClientUnit,
  174. VisitDate = item.VisitDate,
  175. VisitDays = item.VisitDays,
  176. VisitPNumber = item.VisitPNumber,
  177. IsSure = item.IsSure,
  178. TeamTypeId = item.TeamTypeId,
  179. TeamType = item.TeamTypeName, // 映射到正确的属性
  180. TeamLevId = item.TeamLevId,
  181. TeamLev = item.TeamLevName, // 映射到正确的属性
  182. JietuanOperator = item.JietuanOperatorName,
  183. LastCollectionTime = lastCollectionDict.TryGetValue(item.Id, out var lastTime) ? lastTime : null
  184. }).ToList();
  185. var result = new
  186. {
  187. PageFuncAuth = pageFunAuthView,
  188. Data = resultData
  189. };
  190. return Ok(JsonView(true, "查询成功!", result, totalCount));
  191. }
  192. // 没有数据的情况
  193. return Ok(JsonView(true, "查询成功!", new
  194. {
  195. PageFuncAuth = pageFunAuthView,
  196. Data = new List<GroupStatementItemView>()
  197. }));
  198. }
  199. catch (Exception ex)
  200. {
  201. return Ok(JsonView(false, "查询失败:" + ex.Message));
  202. }
  203. }
  204. /// <summary>
  205. /// 团组报表
  206. /// Details
  207. /// </summary>
  208. /// <param name="_dto">团组列表请求dto</param>
  209. /// <returns></returns>
  210. [HttpPost("PostGroupStatementDetails")]
  211. //[JsonConverter(typeof(DecimalConverter), 2)]
  212. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  213. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  214. {
  215. /*
  216. * 团组报表计算方式
  217. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  218. * 应收金额 = 应收表.Sum()
  219. * 已收金额 = 已收表.Sum()
  220. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  221. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  222. *
  223. */
  224. #region 参数验证
  225. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  226. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  227. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  228. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  229. #region 页面操作权限验证
  230. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  231. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  232. #endregion
  233. #endregion
  234. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  235. {
  236. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  237. #region 费用类型 币种,转账,客户信息
  238. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  239. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  240. .Where(it => it.IsDel == 0)
  241. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  242. .ToListAsync();
  243. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  244. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  245. var visitDate = groupInfo.VisitDate;
  246. #endregion
  247. #region 团组收入
  248. GroupIncomeView _giView = new GroupIncomeView();
  249. /*
  250. * 应收报表
  251. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  252. */
  253. decimal frTotalAmount = 0.00M;//应收总金额
  254. 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,
  255. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  256. From Fin_ForeignReceivables fr
  257. Left Join Sys_SetData sd On fr.Currency = sd.Id
  258. Left Join Sys_Users u On fr.Auditor = u.Id
  259. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  260. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  261. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  262. //if (_frViews1.Count > 0)
  263. //{
  264. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  265. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  266. //}
  267. _frViews.ForEach(x =>
  268. {
  269. string namePrefix = string.Empty;
  270. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  271. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  272. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  273. x.PriceName = $"{namePrefix}{x.PriceName}";
  274. });
  275. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  276. _giView.Receivables = _frViews;
  277. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  278. /*
  279. * 已收报表
  280. */
  281. decimal prTotalAmount = 0.00M;//已收总金额
  282. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  283. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  284. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  285. From Fin_ProceedsReceived pr
  286. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  287. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  288. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  289. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  290. prTotalAmount = _prViews.Sum(it => it.Price);
  291. _giView.ProceedsReceivedViews = _prViews;
  292. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  293. /*
  294. * 超支费用
  295. */
  296. decimal exTotalAmount = 0.00M;
  297. // 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,
  298. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  299. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  300. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  301. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  302. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  303. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  304. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  305. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  306. //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 " : " ");
  307. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  308. // #region 超支费用 - 模拟数据
  309. // //if (_ExtraCostsViews.Count < 1)
  310. // //{
  311. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  312. // // {
  313. // // GECId = 0,
  314. // // GECDiId = 2334,
  315. // // PriceName = "模拟数据-超支费用名称",
  316. // // PayMoney = 1000.00M,
  317. // // PaymentCurrency = "CNY",
  318. // // DayRate = 1.0000M,
  319. // // CNYPrice = 1000.00M,
  320. // // Payee = "模拟数据-超支费用收款方",
  321. // // OrbitalPrivateTransfer = 1,
  322. // // PayWay = "刷卡",
  323. // // CardType = "招行卡",
  324. // // IsPay = 1,
  325. // // Applicant = "刘华举"
  326. // // });
  327. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  328. // // {
  329. // // GECId = 0,
  330. // // GECDiId = 2334,
  331. // // PriceName = "模拟数据-超支费用名称",
  332. // // PayMoney = 1000.00M,
  333. // // PaymentCurrency = "CNY",
  334. // // DayRate = 1.0000M,
  335. // // CNYPrice = 1000.00M,
  336. // // Payee = "模拟数据-超支费用收款方",
  337. // // OrbitalPrivateTransfer = 1,
  338. // // PayWay = "刷卡",
  339. // // CardType = "招行卡",
  340. // // IsPay = 1,
  341. // // Applicant = "刘华举"
  342. // // });
  343. // //}
  344. // #endregion
  345. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  346. // _giView.ExtraCostsViews = _ExtraCostsViews;
  347. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  348. /*
  349. * 收款退还
  350. */
  351. decimal promTotalAmount = 0.00M;// 收款退还总金额
  352. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  353. //删除了 And prom.PriceType = 1
  354. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  355. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  356. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  357. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  358. From Fin_PaymentRefundAndOtherMoney prom
  359. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  360. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  361. Where prom.IsDel = 0
  362. And prom.PayType = 1
  363. And ccp.CTable = 285
  364. {1}
  365. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  366. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  367. foreach (var ropItem in _promDatas)
  368. {
  369. string thisCueencyCode = "Unknown";
  370. string thisCueencyName = "Unknown";
  371. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  372. if (currency != null)
  373. {
  374. thisCueencyCode = currency.Name;
  375. thisCueencyName = currency.Remark;
  376. }
  377. string orbitalPrivateTransferStr = "Unknown";
  378. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  379. if (orbitalPrivateTransfer != null)
  380. {
  381. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  382. }
  383. string payStr = "Unknown";
  384. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  385. if (pay != null)
  386. {
  387. payStr = pay.Name;
  388. }
  389. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  390. {
  391. Id = ropItem.Id,
  392. DiId = ropItem.DIId,
  393. PriceName = ropItem.PrPriceName,
  394. PayCurrencyCode = thisCueencyCode,
  395. PayCurrencyName = thisCueencyName,
  396. Price = ropItem.PrPrice,
  397. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  398. ThisRate = ropItem.DayRate,
  399. Payee = ropItem.Payee,
  400. PayTime = ropItem.AuditGMDate,
  401. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  402. PayType = payStr,
  403. IsPay = ropItem.IsPay,
  404. Applicant = ropItem.Appliction
  405. };
  406. _promView.Add(gsd_PaymentRefund);
  407. }
  408. #region 收款退还 - 模拟数据
  409. //if (_promView.Count < 1)
  410. //{
  411. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  412. // {
  413. // Id = 0,
  414. // DiId = 2334,
  415. // PriceName = "模拟数据-费用名称",
  416. // PayCurrencyCode = "CNY",
  417. // PayCurrencyName = "人民币",
  418. // Price = 1000.00M,
  419. // CNYPrice = 1000.00M,
  420. // ThisRate = 1.00M,
  421. // Payee = "模拟数据-收款方",
  422. // PayTime = "2023-01-01 15:20:01",
  423. // OrbitalPrivateTransfer = 1,
  424. // PayType = "刷卡",
  425. // IsPay = 1,
  426. // Applicant = "刘华举"
  427. // });
  428. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  429. // {
  430. // Id = 0,
  431. // DiId = 2334,
  432. // PriceName = "模拟数据-费用名称",
  433. // PayCurrencyCode = "CNY",
  434. // PayCurrencyName = "人民币",
  435. // Price = 1000.00M,
  436. // CNYPrice = 1000.00M,
  437. // ThisRate = 1.00M,
  438. // Payee = "模拟数据-收款方",
  439. // PayTime = "2023-01-01 15:20:01",
  440. // OrbitalPrivateTransfer = 1,
  441. // PayType = "刷卡",
  442. // IsPay = 1,
  443. // Applicant = "刘华举"
  444. // });
  445. //}
  446. #endregion
  447. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  448. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  449. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  450. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  451. _view.GroupIncome = _giView;
  452. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  453. #endregion
  454. #region 团组支出
  455. GroupExpenditureView _geView = new GroupExpenditureView();
  456. var isAudit = _dto.isAudit;
  457. var isAuditSql = string.Format($" AND (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3) ");
  458. var isAuditStatus = new int[] {
  459. 1, //已通过
  460. 3, //自动审核
  461. };
  462. #region 酒店预定费用 76 isAuditSql
  463. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  464. //ccp.RMBPrice As CNYPrice
  465. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  466. string hotelFeeSql = string.Format(@"
  467. SELECT
  468. hr.Id AS HrId,
  469. hr.DiId AS HrDiId,
  470. hr.City,
  471. hr.HotelName,
  472. hr.CheckInDate,
  473. hr.CheckOutDate,
  474. hr.CardPrice AS RoomPrice,
  475. sd1.Name AS PaymentCurrency,
  476. hr.SingleRoomPrice,
  477. hr.SingleRoomCount,
  478. hr.DoubleRoomPrice,
  479. hr.DoubleRoomCount,
  480. hr.SuiteRoomPrice,
  481. hr.SuiteRoomCount,
  482. hr.OtherRoomPrice,
  483. hr.OtherRoomCount,
  484. hr.BreakfastPrice,
  485. sd4.Name AS BreakfastCurrency,
  486. hr.Isoppay,
  487. hr.GovernmentRent,
  488. sd5.Name AS GovernmentRentCurrency,
  489. hr.CityTax,
  490. sd6.Name AS CityTaxCurrency,
  491. ccp.PayMoney,
  492. (
  493. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  494. ) AS CNYPrice,
  495. ccp.PayPercentage,
  496. ccp.DayRate,
  497. ccp.Payee,
  498. ccp.OrbitalPrivateTransfer,
  499. sd2.Name AS PayWay,
  500. sd3.Name AS CardType,
  501. ccp.IsPay,
  502. u.CnName AS Applicant
  503. FROM
  504. Grp_HotelReservations hr
  505. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  506. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  507. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  508. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  509. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  510. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  511. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  512. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  513. WHERE
  514. hr.IsDel = 0
  515. AND ccp.IsDel = 0
  516. AND ccp.CTable = 76 {1}
  517. AND ccp.PayMoney <> 0
  518. AND hr.DiId = {0}
  519. ORDER BY
  520. CheckInDate Asc",
  521. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  522. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  523. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  524. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  525. decimal HotelCNYTotalPrice = 0.00M;
  526. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  527. foreach (var item in groupHotelFeeViews)
  528. {
  529. if (groupHotelContentFeeViews.Count > 0)
  530. {
  531. string paymentStr = string.Empty;
  532. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  533. item.RoomPrice = roomData?.Price ?? 0.00M;
  534. if (item.RoomPrice != 0)
  535. {
  536. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  537. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  538. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  539. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  540. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  541. 收款方:{roomData?.Payee}<br/>
  542. 费用标识:{feeMark1} <br/>
  543. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  544. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  545. 是否由地接支付:{isFeeMark1} <br/>";
  546. }
  547. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  548. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  549. if (item.BreakfastPrice != 0)
  550. {
  551. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  552. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  553. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  554. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  555. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  556. 收款方:{breakfastData?.Payee}<br/>
  557. 费用标识:{feeMark2} <br/>
  558. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  559. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  560. 是否由地接支付:{isFeeMark2} <br/>";
  561. }
  562. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  563. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  564. if (item.GovernmentRent != 0)
  565. {
  566. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  567. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  568. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  569. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  570. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  571. 收款方:{landTaxData?.Payee}<br/>
  572. 费用标识:{feeMark3} <br/>
  573. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  574. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  575. 是否由地接支付:{isFeeMark3} <br/>";
  576. }
  577. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  578. item.CityTax = cityTaxData?.Price ?? 0.00M;
  579. if (item.CityTax != 0)
  580. {
  581. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  582. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  583. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  584. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  585. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  586. 收款方:{cityTaxData?.Payee}<br/>
  587. 费用标识:{feeMark4} <br/>
  588. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  589. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  590. 是否由地接支付:{isFeeMark4} <br/>";
  591. }
  592. if (!string.IsNullOrEmpty(paymentStr))
  593. {
  594. item.IsPay = 2;
  595. item.PayTips = paymentStr;
  596. }
  597. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  598. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  599. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  600. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  601. }
  602. else
  603. {
  604. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  605. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  606. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  607. (item.OtherRoomCount * item.OtherRoomPrice);
  608. //item.RoomPrice = item.CardPrice;
  609. item.RoomPriceCurrency = item.PaymentCurrency;
  610. }
  611. HotelCNYTotalPrice += item.CNYPrice;
  612. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  613. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  614. }
  615. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  616. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  617. #endregion
  618. #region 地接费用 79 isAuditSql
  619. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  620. string CTGGRFeeSql = string.Empty;
  621. if (visitDate > Convert.ToDateTime("2024-04-17"))
  622. {
  623. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  624. sd2.name As PaymentCurrency,ccp.PayPercentage,
  625. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  626. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  627. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  628. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  629. From Grp_CarTouristGuideGroundReservations ctggr
  630. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  631. cggrc.DatePrice,cggrc.PriceContent
  632. From Grp_CarTouristGuideGroundReservationsContent cggrc
  633. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  634. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  635. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  636. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  637. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  638. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  639. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  640. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  641. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  642. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  643. }
  644. else
  645. {
  646. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  647. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  648. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  649. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  650. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  651. ccp.Payee,ccp.AuditGMDate,
  652. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  653. From Grp_CarTouristGuideGroundReservations ctggr
  654. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  655. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  656. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  657. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  658. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  659. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  660. }
  661. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  662. string CTGGRFeeStr = "";
  663. decimal CTGGRCNYTotalPrice = 0.00M;
  664. //按1 地区,2 币种,3 汇率 分组计算
  665. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  666. foreach (var ctggfr in groupCTGGRFeeDatas)
  667. {
  668. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  669. if (ctggfr_curr.Count() > 0)
  670. {
  671. foreach (var curr in ctggfr_curr)
  672. {
  673. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  674. if (ctggfr_rate.Count() > 0)
  675. {
  676. foreach (var rate in ctggfr_rate)
  677. {
  678. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  679. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  680. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  681. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  682. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  683. }
  684. }
  685. else
  686. {
  687. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  688. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  689. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  690. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  691. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  692. }
  693. }
  694. }
  695. else
  696. {
  697. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  698. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  699. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  700. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  701. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  702. }
  703. }
  704. foreach (var item in groupCTGGRFeeViews)
  705. {
  706. if (!string.IsNullOrEmpty(item.AuditGMDate))
  707. {
  708. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  709. }
  710. if (item.DatePrice != DateTime.MinValue)
  711. {
  712. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  713. }
  714. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  715. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  716. //CTGGRCNYTotalPrice += item.CNYPrice;
  717. }
  718. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  719. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  720. #endregion
  721. #region 机票预订费用 85 isAuditSql
  722. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  723. //ccp.RMBPrice As CNYPrice
  724. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  725. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  726. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  727. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  728. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  729. atr.CType
  730. From Grp_AirTicketReservations atr
  731. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  732. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  733. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  734. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  735. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  736. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  737. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime",
  738. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  739. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  740. string str = "";
  741. List<dynamic> airClientPris = new List<dynamic>();
  742. decimal AirCNYTotalPrice = 0.00M;
  743. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  744. decimal JJCAveragePrice = 0.00M;
  745. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  746. decimal GWCAveragePrice = 0.00M;
  747. //if (groupAirFeeViews.Count > 0)
  748. //{
  749. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  750. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  751. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  752. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  753. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  754. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  755. //}
  756. // 原始数据
  757. var flights = await _sqlSugar.Queryable<Grp_AirTicketReservations>().Where(it => it.DIId == _dto.DiId && it.IsDel == 0).ToListAsync();
  758. int Index = 0;
  759. foreach (var item in groupAirFeeViews)
  760. {
  761. // 2026版处理 航班信息
  762. var currFlight = flights.Where(it => it.Id == item.AirId).FirstOrDefault();
  763. if (currFlight != null)
  764. {
  765. if (currFlight.CreateTime >= Convert.ToDateTime("2026-01-01 00:00:00"))
  766. {
  767. item.FlightsCode = string.Join("、", currFlight.AirTicketBasicInfos.Select(x => x.FlightsCode).ToList());
  768. item.FlightsCity = string.Join("/", currFlight.AirTicketBasicInfos.Select(x => x.FlightsCity).ToList());
  769. item.FlightsDate = currFlight.AirTicketBasicInfos.FirstOrDefault()?.FlightsDate ?? "";
  770. item.FlightsTime = currFlight.AirTicketBasicInfos.FirstOrDefault()?.FlightsTime ?? "";
  771. }
  772. }
  773. if (item.AirId > 2924)
  774. {
  775. string itemClientName = "";
  776. if (!string.IsNullOrEmpty(item.ClientName))
  777. {
  778. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  779. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  780. if (m_EnName.Success || m_ZHName.Success)
  781. {
  782. itemClientName = item.ClientName;
  783. AirCNYTotalPrice += item.CNYPrice;
  784. continue;
  785. }
  786. string[] clientIds = Array.Empty<string>();
  787. if (item.ClientName.Contains(','))
  788. {
  789. clientIds = item.ClientName.Split(',');
  790. }
  791. else
  792. {
  793. clientIds = new string[] { item.ClientName };
  794. }
  795. if (clientIds.Length > 0)
  796. {
  797. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  798. if (output.Contains(-1))
  799. {
  800. itemClientName += $@"行程单";
  801. output = output.Where(val => val != -1).ToArray();
  802. }
  803. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  804. decimal unitCost = 0.00M;
  805. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  806. int clienIndex = 1;
  807. foreach (var client in clients)
  808. {
  809. airClientPris.Add(new
  810. {
  811. CnName = client.LastName + client.FirstName,
  812. EnName = client.Pinyin,
  813. Price = unitCost,
  814. AirType = item.AirTypeName
  815. });
  816. string six = "";
  817. if (client.Sex == 0) six = "Mr";
  818. else if (client.Sex == 1) six = "Ms";
  819. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  820. clienIndex++;
  821. }
  822. }
  823. }
  824. item.ClientName = itemClientName;
  825. }
  826. else
  827. {
  828. string clientPinYinName = "";
  829. decimal unitCost = 0.00M;
  830. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  831. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  832. Regex r = new Regex("[0-9]");
  833. string name1 = item.ClientName;
  834. name1 = r.Replace(name1, "");
  835. string[] clientNames = name1.Split('.');
  836. for (int i = 0; i < item.ClientNum; i++)
  837. {
  838. string name = "";
  839. if (clientNames.Length > 0)
  840. {
  841. int index = i + 1;
  842. if (index < clientNames.Length)
  843. {
  844. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  845. if (!string.IsNullOrEmpty(name))
  846. {
  847. airClientPris.Add(new
  848. {
  849. CnName = name,
  850. EnName = name,
  851. Price = unitCost,
  852. AirType = item.AirTypeName
  853. });
  854. }
  855. //if (name.Length > 0)
  856. //{
  857. // string nameLastStr = name[name.Length - 1].ToString();
  858. // if (nameLastStr.IsNumeric())
  859. // {
  860. // name = name.Substring(0, name.Length - 1).Trim();
  861. // }
  862. //}
  863. }
  864. }
  865. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  866. }
  867. }
  868. if (!string.IsNullOrEmpty(item.AuditGMDate))
  869. {
  870. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  871. }
  872. AirCNYTotalPrice += item.CNYPrice;
  873. }
  874. _geView.GroupAirFeeViews = groupAirFeeViews;
  875. if (airClientPris.Count > 0)
  876. {
  877. var peoplePriStr = "";
  878. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  879. .Select(group => group.First())
  880. .ToList();
  881. int airClientPrisIndex = 1;
  882. foreach (var item in airClientPris1)
  883. {
  884. decimal price = 0.00M;
  885. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  886. foreach (var pri in prices)
  887. {
  888. price += pri.Price;
  889. }
  890. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  891. airClientPrisIndex++;
  892. }
  893. if (!string.IsNullOrEmpty(peoplePriStr))
  894. {
  895. str = $@"其中:{peoplePriStr}";
  896. }
  897. //经济舱均价
  898. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  899. if (airJJCPris.Count > 0)
  900. {
  901. decimal jjcTotalPrice = 0.00M;
  902. foreach (var item in airJJCPris)
  903. {
  904. jjcTotalPrice += item.Price;
  905. }
  906. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  907. .Select(group => group.First())
  908. .ToList().Count;
  909. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  910. }
  911. //公务舱均价
  912. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  913. if (airGWCPris.Count > 0)
  914. {
  915. decimal gwcTotalPrice = 0.00M;
  916. foreach (var item in airGWCPris)
  917. {
  918. gwcTotalPrice += item.Price;
  919. }
  920. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  921. .Select(group => group.First())
  922. .ToList().Count;
  923. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  924. }
  925. }
  926. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  927. #endregion
  928. #region 签证费用 80 isAuditSql
  929. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  930. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  931. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  932. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  933. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  934. From Grp_VisaInfo vi
  935. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  936. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  937. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  938. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  939. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  940. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime",
  941. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  942. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  943. decimal VisaCNYTotalPirce = 0.00M;
  944. foreach (var item in groupVisaFeeViews)
  945. {
  946. string itemClientName = "";
  947. string visaClients = item.VisaClient;
  948. if (!string.IsNullOrEmpty(visaClients))
  949. {
  950. string[] clientIds = Array.Empty<string>();
  951. if (visaClients.Contains(','))
  952. {
  953. clientIds = visaClients.Split(',');
  954. }
  955. else
  956. {
  957. clientIds = new string[] { visaClients };
  958. }
  959. if (clientIds.Length > 0)
  960. {
  961. List<int> clientIds1 = new List<int>() { };
  962. foreach (var clientIdStr in clientIds)
  963. {
  964. if (clientIdStr.IsNumeric())
  965. {
  966. clientIds1.Add(int.Parse(clientIdStr));
  967. }
  968. }
  969. if (clientIds1.Count > 0)
  970. {
  971. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  972. foreach (var client in clients)
  973. {
  974. itemClientName += $"{client.LastName + client.FirstName},";
  975. }
  976. }
  977. else
  978. {
  979. itemClientName = visaClients;
  980. }
  981. }
  982. }
  983. if (itemClientName.Length > 0)
  984. {
  985. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  986. }
  987. item.VisaClient = itemClientName;
  988. VisaCNYTotalPirce += item.CNYPrice;
  989. if (!string.IsNullOrEmpty(item.AuditGMDate))
  990. {
  991. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  992. }
  993. }
  994. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  995. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#0.00"));
  996. #endregion
  997. #region 邀请/公务活动 81 isAuditSql
  998. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  999. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  1000. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1001. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1002. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  1003. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  1004. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  1005. From Grp_InvitationOfficialActivities ioa
  1006. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1007. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1008. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1009. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1010. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1011. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1012. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1013. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1014. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1015. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime",
  1016. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty );
  1017. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  1018. #region 邀请/公务活动 - 模拟数据
  1019. //if (groupInvitationalFeeViews.Count < 1)
  1020. //{
  1021. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  1022. // {
  1023. // IOAId = 0,
  1024. // IOADiId = 2334,
  1025. // InviterArea = "模拟数据-邀请方地区",
  1026. // Inviter = "模拟数据-邀请方",
  1027. // InviteTime = "2023-10-10",
  1028. // InviteCost = 100.00M,
  1029. // InviteCurrency = "EUR",
  1030. // SendCost = 100.00M,
  1031. // SendCurrency = "EUR",
  1032. // EventsCost = 10000.00M,
  1033. // EventsCurrency = "EUR",
  1034. // TranslateCost = 300.00M,
  1035. // TranslateCurrency = "EUR",
  1036. // PayMoney = 10500.00M,
  1037. // PaymentCurrency = "EUR",
  1038. // CNYPrice = 76765.50M,
  1039. // Payee = "模拟数据-收款方",
  1040. // AuditGMDate = "2023-12-05",
  1041. // OrbitalPrivateTransfer = 1,
  1042. // PayWay = "刷卡",
  1043. // IsPay = 1,
  1044. // Applicant = "刘华举"
  1045. // });
  1046. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  1047. // {
  1048. // IOAId = 0,
  1049. // IOADiId = 2334,
  1050. // InviterArea = "模拟数据-邀请方地区",
  1051. // Inviter = "模拟数据-邀请方",
  1052. // InviteTime = "2023-10-10",
  1053. // InviteCost = 100.00M,
  1054. // InviteCurrency = "EUR",
  1055. // SendCost = 100.00M,
  1056. // SendCurrency = "EUR",
  1057. // EventsCost = 10000.00M,
  1058. // EventsCurrency = "EUR",
  1059. // TranslateCost = 300.00M,
  1060. // TranslateCurrency = "EUR",
  1061. // PayMoney = 10500.00M,
  1062. // PaymentCurrency = "EUR",
  1063. // CNYPrice = 76765.50M,
  1064. // Payee = "模拟数据-收款方",
  1065. // AuditGMDate = "2023-12-05",
  1066. // OrbitalPrivateTransfer = 1,
  1067. // PayWay = "刷卡",
  1068. // IsPay = 1,
  1069. // Applicant = "刘华举"
  1070. // });
  1071. //}
  1072. #endregion
  1073. decimal InvitationalCNYTotalPrice = 0.00M;
  1074. foreach (var item in groupInvitationalFeeViews)
  1075. {
  1076. InvitationalCNYTotalPrice += item.CNYPrice2;
  1077. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1078. {
  1079. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1080. }
  1081. string currencyRateStr = "";
  1082. List<string> currencys = new List<string>();
  1083. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  1084. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  1085. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  1086. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  1087. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  1088. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  1089. item.CurrencyRateStr = currencyRateStr;
  1090. }
  1091. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  1092. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#0.00"));
  1093. #endregion
  1094. #region 保险费用 82 isAuditSql
  1095. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1096. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1097. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1098. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1099. From Grp_Customers ic
  1100. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1101. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1102. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1103. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1104. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime",
  1105. _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1106. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1107. decimal InsuranceCNYTotalPrice = 0.00M;
  1108. foreach (var item in groupInsuranceFeeViews)
  1109. {
  1110. InsuranceCNYTotalPrice += item.CNYPrice;
  1111. string itemClientName = "";
  1112. string insClients = item.ClientName;
  1113. if (!string.IsNullOrEmpty(insClients))
  1114. {
  1115. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1116. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1117. //if (m_EnName.Success || m_ZHName.Success)
  1118. //{
  1119. // itemClientName = insClients;
  1120. // continue;
  1121. //}
  1122. string[] clientIds = Array.Empty<string>();
  1123. if (insClients.Contains(','))
  1124. {
  1125. clientIds = insClients.Split(',');
  1126. }
  1127. else
  1128. {
  1129. clientIds = new string[] { insClients };
  1130. }
  1131. if (clientIds.Length > 0)
  1132. {
  1133. List<int> output = new List<int>();
  1134. foreach (var clientId in clientIds)
  1135. {
  1136. if (clientId.IsNumeric())
  1137. {
  1138. output.Add(int.Parse(clientId));
  1139. }
  1140. }
  1141. if (output.Count > 0)
  1142. {
  1143. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1144. foreach (var client in clients)
  1145. {
  1146. itemClientName += $"{client.LastName + client.FirstName},";
  1147. }
  1148. if (itemClientName.Length > 0)
  1149. {
  1150. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1151. }
  1152. }
  1153. else
  1154. {
  1155. itemClientName = insClients;
  1156. }
  1157. }
  1158. }
  1159. item.ClientName = itemClientName;
  1160. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1161. {
  1162. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1163. }
  1164. }
  1165. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1166. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1167. #endregion
  1168. #region 其他款项费用 98 isAuditSql
  1169. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1170. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,
  1171. CASE
  1172. WHEN dp.PaymentPercent <> 100
  1173. THEN dp.PriceName
  1174. + '('
  1175. + dp.PaymentType
  1176. + ')'
  1177. -- + ' '
  1178. -- + CAST(CAST(dp.PaymentPercent AS INT) AS VARCHAR(10))
  1179. -- + '%)'
  1180. ELSE dp.PriceName
  1181. END AS PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1182. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1183. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1184. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1185. From Grp_DecreasePayments dp
  1186. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1187. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1188. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1189. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1190. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1191. Order By CreateTime", _dto.DiId, _dto.isAudit ? isAuditSql : string.Empty);
  1192. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1193. #region 保险费用 - 模拟数据
  1194. //if (groupDecreaseFeeViews.Count < 1)
  1195. //{
  1196. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1197. // {
  1198. // DPId = 0,
  1199. // DPDiId = 2334,
  1200. // PriceName = "模拟数据-费用名称",
  1201. // PayMoney = 1000.00M,
  1202. // PayMoneyCurrency = "CNY",
  1203. // DayRate = 1.0000M,
  1204. // CNYPrice = 1.0000M,
  1205. // AuditGMDate = "2023-12-10 12:13:00",
  1206. // Payee = "模拟数据-付款方",
  1207. // OrbitalPrivateTransfer = 1,
  1208. // PayWay = "现金",
  1209. // IsPay = 1,
  1210. // Applicant = "刘华举"
  1211. // });
  1212. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1213. // {
  1214. // DPId = 0,
  1215. // DPDiId = 2334,
  1216. // PriceName = "模拟数据-费用名称",
  1217. // PayMoney = 1000.00M,
  1218. // PayMoneyCurrency = "CNY",
  1219. // DayRate = 1.0000M,
  1220. // CNYPrice = 1.0000M,
  1221. // AuditGMDate = "2023-12-10 12:13:00",
  1222. // Payee = "模拟数据-付款方",
  1223. // OrbitalPrivateTransfer = 1,
  1224. // PayWay = "现金",
  1225. // IsPay = 1,
  1226. // Applicant = "刘华举"
  1227. // });
  1228. //}
  1229. #endregion
  1230. decimal DecreaseCNYTotalPrice = 0.00M;
  1231. foreach (var item in groupDecreaseFeeViews)
  1232. {
  1233. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1234. DecreaseCNYTotalPrice += item.CNYPrice;
  1235. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1236. {
  1237. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1238. }
  1239. }
  1240. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1241. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1242. #endregion
  1243. #region 公司内部操作人员提成(提成表) isAudit
  1244. var royaltyDatas = await _sqlSugar
  1245. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1246. new JoinQueryInfos(
  1247. JoinType.Left, rc.UserId == u1.Id,
  1248. JoinType.Left, rc.CreateUserId == u2.Id
  1249. ))
  1250. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId)
  1251. .WhereIF(isAudit, (rc, u1, u2) => rc.IsConfirm == 1)
  1252. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1253. {
  1254. GroupId = rc.TeamId,
  1255. OverviewInfo = rc.Temp,
  1256. DetailedInfo = rc.ChiArr,
  1257. Amount = rc.Price,
  1258. IsConfirm = rc.IsConfirm,
  1259. IsSeed = rc.IsSeed,
  1260. RoyaltyUserName = u1.CnName,
  1261. CreateUserName = u2.CnName,
  1262. CreateTime = rc.CreateTime
  1263. })
  1264. .ToListAsync();
  1265. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  1266. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  1267. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  1268. #endregion
  1269. #region 公司内部人员报销(日付表) isAuditStatus
  1270. var reimburseDatas = await _sqlSugar
  1271. .Queryable<Fin_DailyFeePayment, Sys_Users, Sys_SetData, Sys_Company>((dfp, u, sd1, c) =>
  1272. new JoinQueryInfos(
  1273. JoinType.Left, dfp.CreateUserId == u.Id,
  1274. JoinType.Left, dfp.TransferTypeId == sd1.Id,
  1275. JoinType.Left, dfp.CompanyId == c.Id
  1276. ))
  1277. .Where((dfp, u, sd1, c) => dfp.IsDel == 0 && dfp.PriceTypeId == 1353 && dfp.GroupId == _dto.DiId)
  1278. .WhereIF(isAudit, (dfp, u, sd1, c) => isAuditStatus.Contains(dfp.FAudit) && isAuditStatus.Contains(dfp.MAudit))
  1279. .Select((dfp, u, sd1, c) => new GroupReimburseFeeInfoView()
  1280. {
  1281. TotalAmt = dfp.SumPrice,
  1282. //FeeItems = SqlFunc.Subqueryable<Fin_DailyFeePaymentContent>()
  1283. // .Where(x => x.DFPId == dfp.Id && x.IsDel == 0)
  1284. // .Select(x => new GroupReimburseFeeSubInfo()
  1285. // {
  1286. // PriceName = x.PriceName,
  1287. // Quantity = x.Quantity,
  1288. // Price = x.Price,
  1289. // SubTotal = x.ItemTotal,
  1290. // Remark = x.Remark
  1291. // })
  1292. // .ToList(),
  1293. AppReason = dfp.Instructions,
  1294. TransferLabel = sd1.Name,
  1295. ApplyComp = c.CompanyName,
  1296. FAudit = dfp.FAudit,
  1297. MAudit = dfp.MAudit,
  1298. PayStatusFlag = dfp.IsPay == 0 ? "未付款" : "已付款",
  1299. ApplyName = u.CnName,
  1300. ApplyTime = dfp.CreateTime
  1301. })
  1302. .ToListAsync();
  1303. var reimburseTotalPrice = reimburseDatas.Sum(x => x.TotalAmt);
  1304. _geView.GroupReimburseFeeViews = reimburseDatas;
  1305. _geView.GroupReimburseFeeStr = string.Format(@"人民币总费用:{0} CNY", reimburseTotalPrice.ToString("#0.00"));
  1306. #endregion
  1307. _view.GroupExpenditure = _geView;
  1308. #endregion
  1309. /*
  1310. * 团组报表计算方式
  1311. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1312. * 应收金额 = 应收表.Sum()
  1313. * 已收金额 = 已收表.Sum()
  1314. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1315. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1316. *
  1317. */
  1318. decimal _totalExpenditure = 0.00M; //总支出
  1319. decimal _amountReceivable = 0.00M; //应收金额
  1320. decimal _amountReceived = 0.00M; //已收金额
  1321. decimal _receivableProfit = 0.00M; //应收利润
  1322. decimal _receivedProfit = 0.00M; //已收利润
  1323. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1324. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice + reimburseTotalPrice;
  1325. _amountReceivable = frTotalAmount;
  1326. _amountReceived = prTotalAmount;
  1327. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1328. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1329. _view.FeeTotalStr = string.Format(@$"<span>
  1330. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1331. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1332. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1333. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1334. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1335. </span>");
  1336. return Ok(JsonView(true, "查询成功!", _view));
  1337. }
  1338. else
  1339. {
  1340. return Ok(JsonView(false, "查询成功"));
  1341. }
  1342. }
  1343. /// <summary>
  1344. /// 团组报表
  1345. /// Excel 下载
  1346. /// </summary>
  1347. /// <param name="_dto">团组列表请求dto</param>
  1348. /// <returns></returns>
  1349. [HttpPost("PostGroupStatementExportExcel")]
  1350. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1351. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1352. {
  1353. //pageId 38
  1354. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1355. //默认查看所有数据
  1356. bool isAudit = _dto.isAudit;
  1357. #region 参数验证
  1358. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1359. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1360. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1361. #region 页面操作权限验证
  1362. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1363. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1364. #endregion
  1365. #endregion
  1366. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1367. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1368. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1369. string groupNo = groupInfo.TourCode,
  1370. groupName = groupInfo.TeamName.Replace("|", "、"),
  1371. lister = userInfo?.CnName ?? "-";
  1372. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1373. .Where(it => it.IsDel == 0)
  1374. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1375. .ToList();
  1376. //获取模板
  1377. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1378. var designer = new WorkbookDesigner();
  1379. designer.Workbook = new Workbook(tempPath);
  1380. // 获取工作簿中的工作表集合
  1381. var worksheets = designer.Workbook.Worksheets;
  1382. #region 获取sheet,定义datatable,局部变量
  1383. //酒店费用相关
  1384. var hotelFeeSheet = worksheets["酒店费用"];
  1385. var hotelFeeDt = new DataTable($"HotelFeeView");
  1386. decimal hotelCNYTotalCost = 0.00M;
  1387. //地接费用相关
  1388. var OPFeeSheet = worksheets["地接费用"];
  1389. var OPFeeDt = new DataTable($"OPFeeView");
  1390. var OPFeeLabel = string.Empty;
  1391. decimal OPCNYTotalCost = 0.00M;
  1392. //签证费用相关
  1393. var visaFeeSheet = worksheets["签证费用"];
  1394. var visaFeeDt = new DataTable($"VisaFeeView");
  1395. decimal visaCNYTotalCost = 0.00M;
  1396. //邀请费用相关
  1397. var OAFeeSheet = worksheets["邀请费用"];
  1398. var OAFeeDt = new DataTable($"OAFeeView");
  1399. decimal OACNYTotalCost = 0.00M;
  1400. //机票费用相关
  1401. var airTicketFeeSheet = worksheets["机票费用"];
  1402. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1403. decimal airTicketCNYTotalCost = 0.00M;
  1404. //保险费用相关
  1405. var insureFeeSheet = worksheets["保险费用"];
  1406. var insureFeeDt = new DataTable($"InsureFeeView");
  1407. decimal insureCNYTotalCost = 0.00M;
  1408. //其他费用相关
  1409. var otherFeeSheet = worksheets["其他费用"];
  1410. var otherFeeDt = new DataTable($"OtherFeeView");
  1411. decimal otherCNYTotalCost = 0.00M;
  1412. //收款退还相关
  1413. var SKTHFeeSheet = worksheets["收款退还"];
  1414. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1415. decimal SKTHCNYTotalCost = 0.00M;
  1416. //操作提成
  1417. var royaltyFeeSheet = worksheets["操作提成"];
  1418. var royaltyFeeDt = new DataTable($"royaltyFeeView");
  1419. decimal royaltyCNYTotalCost = 0.00M;
  1420. var totalAmount = 0.00M; //支出成本合计
  1421. var accountsAmount = 0.00M; //应收金额合计
  1422. var receivedAmount = 0.00M; //已收金额合计
  1423. var accountsProfit = 0.00M; //应收利润合计
  1424. var receiveProfit = 0.00M; //已收利润合计
  1425. var profitMargin = 0.00M; //利润差合计
  1426. //应收合计相关
  1427. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1428. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1429. //已收合计相关
  1430. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1431. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1432. //团组收入支出利润
  1433. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1434. #endregion
  1435. #region 酒店费用
  1436. if (hotelFeeSheet != null)
  1437. {
  1438. string hotelFeeSql = string.Format(@"
  1439. SELECT
  1440. hr.Id AS HrId,
  1441. hr.DiId AS HrDiId,
  1442. hr.City,
  1443. hr.HotelName,
  1444. hr.CheckInDate,
  1445. hr.CheckOutDate,
  1446. hr.CardPrice AS RoomPrice,
  1447. sd1.Name AS PaymentCurrency,
  1448. hr.SingleRoomPrice,
  1449. hr.SingleRoomCount,
  1450. hr.DoubleRoomPrice,
  1451. hr.DoubleRoomCount,
  1452. hr.SuiteRoomPrice,
  1453. hr.SuiteRoomCount,
  1454. hr.OtherRoomPrice,
  1455. hr.OtherRoomCount,
  1456. hr.BreakfastPrice,
  1457. sd4.Name AS BreakfastCurrency,
  1458. hr.Isoppay,
  1459. hr.GovernmentRent,
  1460. sd5.Name AS GovernmentRentCurrency,
  1461. hr.CityTax,
  1462. sd6.Name AS CityTaxCurrency,
  1463. ccp.PayMoney,
  1464. (
  1465. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1466. ) AS CNYPrice,
  1467. ccp.PayPercentage,
  1468. ccp.DayRate,
  1469. ccp.Payee,
  1470. ccp.OrbitalPrivateTransfer,
  1471. sd2.Name AS PayWay,
  1472. sd3.Name AS CardType,
  1473. ccp.IsPay,
  1474. u.CnName AS Applicant,
  1475. hr.Remark
  1476. FROM
  1477. Grp_HotelReservations hr
  1478. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1479. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1480. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1481. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1482. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1483. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1484. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1485. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1486. WHERE
  1487. hr.IsDel = 0
  1488. AND ccp.IsDel = 0
  1489. AND ccp.CTable = 76 {1}
  1490. AND ccp.PayMoney <> 0
  1491. AND hr.DiId = {0}
  1492. ORDER BY
  1493. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1494. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1495. if (groupHotelFeeViews.Any())
  1496. {
  1497. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1498. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1499. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1500. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1501. foreach (var item in groupHotelFeeViews)
  1502. {
  1503. if (groupHotelContentFeeViews.Count > 0)
  1504. {
  1505. string paymentStr = string.Empty;
  1506. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1507. item.RoomPrice = roomData?.Price ?? 0.00M;
  1508. if (item.RoomPrice != 0)
  1509. {
  1510. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1511. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1512. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1513. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1514. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1515. 收款方:{roomData?.Payee}<br/>
  1516. 费用标识:{feeMark1} <br/>
  1517. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1518. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1519. 是否由地接支付:{isFeeMark1} <br/>";
  1520. }
  1521. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1522. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1523. if (item.BreakfastPrice != 0)
  1524. {
  1525. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1526. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1527. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1528. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1529. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1530. 收款方:{breakfastData?.Payee}<br/>
  1531. 费用标识:{feeMark2} <br/>
  1532. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1533. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1534. 是否由地接支付:{isFeeMark2} <br/>";
  1535. }
  1536. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1537. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1538. if (item.GovernmentRent != 0)
  1539. {
  1540. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1541. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1542. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1543. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1544. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1545. 收款方:{landTaxData?.Payee}<br/>
  1546. 费用标识:{feeMark3} <br/>
  1547. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1548. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1549. 是否由地接支付:{isFeeMark3} <br/>";
  1550. }
  1551. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1552. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1553. if (item.CityTax != 0)
  1554. {
  1555. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1556. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1557. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1558. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1559. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1560. 收款方:{cityTaxData?.Payee}<br/>
  1561. 费用标识:{feeMark4} <br/>
  1562. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1563. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1564. 是否由地接支付:{isFeeMark4} <br/>";
  1565. }
  1566. if (!string.IsNullOrEmpty(paymentStr))
  1567. {
  1568. item.IsPay = 2;
  1569. item.PayTips = paymentStr;
  1570. }
  1571. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1572. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1573. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1574. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1575. }
  1576. else
  1577. {
  1578. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1579. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1580. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1581. (item.OtherRoomCount * item.OtherRoomPrice);
  1582. //item.RoomPrice = item.CardPrice;
  1583. item.RoomPriceCurrency = item.PaymentCurrency;
  1584. }
  1585. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1586. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1587. }
  1588. }
  1589. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1590. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1591. hotelFeeDt.TableName = $"HotelFeeView";
  1592. }
  1593. #endregion
  1594. #region 地接费用
  1595. if (OPFeeSheet != null)
  1596. {
  1597. string CTGGRFeeSql = string.Empty;
  1598. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1599. {
  1600. CTGGRFeeSql = string.Format(@"
  1601. Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1602. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1603. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1604. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1605. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1606. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1607. From Grp_CarTouristGuideGroundReservations ctggr
  1608. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1609. cggrc.DatePrice,cggrc.PriceContent
  1610. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1611. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1612. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1613. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1614. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1615. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1616. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1617. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1618. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1619. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1620. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1621. }
  1622. else
  1623. {
  1624. CTGGRFeeSql = string.Format(@"
  1625. Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1626. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1627. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1628. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1629. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1630. ccp.Payee,ccp.AuditGMDate,
  1631. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1632. From Grp_CarTouristGuideGroundReservations ctggr
  1633. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1634. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1635. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1636. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1637. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1638. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1639. }
  1640. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1641. string CTGGRFeeStr = "";
  1642. var OPToDataTableViews = groupOPFeeViews;
  1643. decimal CTGGRCNYTotalPrice = 0.00M;
  1644. //按1 地区,2 币种,3 汇率 分组计算
  1645. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1646. foreach (var ctggfr in groupCTGGRFeeDatas)
  1647. {
  1648. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1649. if (ctggfr_curr.Count() > 0)
  1650. {
  1651. foreach (var curr in ctggfr_curr)
  1652. {
  1653. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1654. if (ctggfr_rate.Count() > 0)
  1655. {
  1656. foreach (var rate in ctggfr_rate)
  1657. {
  1658. 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");
  1659. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1660. }
  1661. }
  1662. else
  1663. {
  1664. 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");
  1665. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1666. }
  1667. }
  1668. }
  1669. else
  1670. {
  1671. 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");
  1672. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1673. }
  1674. }
  1675. foreach (var item in groupOPFeeViews)
  1676. {
  1677. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1678. {
  1679. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1680. }
  1681. if (item.DatePrice != DateTime.MinValue)
  1682. {
  1683. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1684. }
  1685. }
  1686. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1687. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1688. OPFeeLabel = CTGGRFeeStr;
  1689. OPFeeDt.TableName = $"OPFeeView";
  1690. }
  1691. #endregion
  1692. #region 签证费用
  1693. if (visaFeeSheet != null)
  1694. {
  1695. string groupVisaFeeSql = string.Format(@"
  1696. Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1697. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1698. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1699. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1700. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1701. From Grp_VisaInfo vi
  1702. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1703. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1704. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1705. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1706. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1707. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1708. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1709. foreach (var item in groupVisaFeeViews)
  1710. {
  1711. string names = string.Empty;
  1712. string visaClients = item.VisaClient;
  1713. if (!string.IsNullOrEmpty(visaClients))
  1714. {
  1715. var clientIds = Array.Empty<string>();
  1716. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1717. else clientIds = new string[] { visaClients };
  1718. if (clientIds.Length > 0)
  1719. {
  1720. var clientIds1 = new List<int>() { };
  1721. foreach (var clientIdStr in clientIds)
  1722. {
  1723. var isInt = int.TryParse(clientIdStr, out int id);
  1724. if (isInt) clientIds1.Add(id);
  1725. }
  1726. if (clientIds1.Count > 0)
  1727. {
  1728. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1729. foreach (var client in clients)
  1730. {
  1731. EncryptionProcessor.DecryptProperties(client);
  1732. names += $"{client.LastName + client.FirstName},";
  1733. }
  1734. }
  1735. else names = visaClients;
  1736. }
  1737. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1738. item.VisaClient = names;
  1739. }
  1740. }
  1741. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1742. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1743. visaFeeDt.TableName = $"VisaFeeView";
  1744. }
  1745. #endregion
  1746. #region 邀请费用
  1747. if (OAFeeSheet != null)
  1748. {
  1749. string feeSql = string.Format(@"
  1750. Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1751. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1752. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1753. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1754. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1755. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1756. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1757. From Grp_InvitationOfficialActivities ioa
  1758. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1759. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1760. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1761. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1762. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1763. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1764. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1765. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1766. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1767. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1768. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1769. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1770. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1771. OAFeeDt.TableName = $"OAFeeView";
  1772. }
  1773. #endregion
  1774. #region 机票费用
  1775. if (airTicketFeeSheet != null)
  1776. {
  1777. string feeSql = string.Format(@"
  1778. Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1779. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1780. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1781. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1782. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1783. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1784. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1785. From Grp_AirTicketReservations atr
  1786. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1787. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1788. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1789. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1790. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1791. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1792. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1793. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1794. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1795. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1796. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1797. }
  1798. #endregion
  1799. #region 保险费用
  1800. if (insureFeeSheet != null)
  1801. {
  1802. string feeSql = string.Format(@"
  1803. Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1804. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1805. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1806. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1807. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1808. From Grp_Customers ic
  1809. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1810. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1811. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1812. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1813. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1814. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1815. foreach (var item in feeViews)
  1816. {
  1817. string itemClientName = "";
  1818. string insClients = item.ClientName;
  1819. if (!string.IsNullOrEmpty(insClients))
  1820. {
  1821. string[] clientIds = Array.Empty<string>();
  1822. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1823. else clientIds = new string[] { insClients };
  1824. if (clientIds.Length > 0)
  1825. {
  1826. List<int> output = new List<int>();
  1827. foreach (var clientId in clientIds)
  1828. if (int.TryParse(clientId, out int id))
  1829. output.Add(id);
  1830. if (output.Count > 0)
  1831. {
  1832. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1833. foreach (var client in clients)
  1834. {
  1835. EncryptionProcessor.DecryptProperties(client);
  1836. itemClientName += $"{client.LastName + client.FirstName},";
  1837. }
  1838. if (itemClientName.Length > 0)
  1839. {
  1840. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1841. }
  1842. }
  1843. else itemClientName = insClients;
  1844. }
  1845. }
  1846. item.ClientName = itemClientName;
  1847. }
  1848. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1849. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1850. insureFeeDt.TableName = $"InsureFeeView";
  1851. }
  1852. #endregion
  1853. #region 其他费用
  1854. if (insureFeeSheet != null)
  1855. {
  1856. string feeSql = string.Format(@"
  1857. Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1858. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1859. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1860. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1861. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1862. From Grp_DecreasePayments dp
  1863. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1864. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1865. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1866. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1867. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1868. Order By CreateTime", diId, isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1869. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1870. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1871. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1872. otherFeeDt.TableName = $"OtherFeeView";
  1873. }
  1874. #endregion
  1875. #region 收款退还
  1876. if (SKTHFeeSheet != null)
  1877. {
  1878. //删除了 And prom.PriceType = 1
  1879. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1880. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1881. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1882. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1883. From Fin_PaymentRefundAndOtherMoney prom
  1884. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1885. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1886. Where prom.IsDel = 0
  1887. And prom.PayType = 1
  1888. And ccp.CTable = 285
  1889. {1}
  1890. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1891. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1892. if (_promDatas.Any())
  1893. {
  1894. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1895. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1896. foreach (var ropItem in _promDatas)
  1897. {
  1898. string thisCueencyCode = "Unknown";
  1899. string thisCueencyName = "Unknown";
  1900. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1901. if (currency != null)
  1902. {
  1903. thisCueencyCode = currency.Name;
  1904. thisCueencyName = currency.Remark;
  1905. }
  1906. string orbitalPrivateTransferStr = "Unknown";
  1907. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1908. if (orbitalPrivateTransfer != null)
  1909. {
  1910. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1911. }
  1912. string payStr = "Unknown";
  1913. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1914. if (pay != null)
  1915. {
  1916. payStr = pay.Name;
  1917. }
  1918. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1919. {
  1920. Id = ropItem.Id,
  1921. DiId = ropItem.DIId,
  1922. PriceName = ropItem.PrPriceName,
  1923. PayCurrencyCode = thisCueencyCode,
  1924. PayCurrencyName = thisCueencyName,
  1925. Price = ropItem.PrPrice,
  1926. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1927. ThisRate = ropItem.DayRate,
  1928. Payee = ropItem.Payee,
  1929. PayTime = ropItem.AuditGMDate,
  1930. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1931. PayType = payStr,
  1932. IsPay = ropItem.IsPay,
  1933. Applicant = ropItem.Appliction,
  1934. Remark = ropItem.SKTHRemark
  1935. };
  1936. _promView.Add(gsd_PaymentRefund);
  1937. }
  1938. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1939. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1940. SKTHFeeDt.TableName = $"SKTHFeeView";
  1941. }
  1942. }
  1943. #endregion
  1944. #region 操作提成
  1945. if (SKTHFeeSheet != null)
  1946. {
  1947. var _royaltyDatas = await _sqlSugar
  1948. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  1949. new JoinQueryInfos(
  1950. JoinType.Left, rc.UserId == u1.Id,
  1951. JoinType.Left, rc.CreateUserId == u2.Id
  1952. ))
  1953. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  1954. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  1955. {
  1956. GroupId = rc.TeamId,
  1957. OverviewInfo = rc.Temp,
  1958. DetailedInfo = rc.ChiArr,
  1959. Amount = rc.Price,
  1960. IsConfirm = rc.IsConfirm,
  1961. IsSeed = rc.IsSeed,
  1962. RoyaltyUserName = u1.CnName,
  1963. CreateUserName = u2.CnName,
  1964. CreateTime = rc.CreateTime
  1965. })
  1966. .ToListAsync();
  1967. if (_royaltyDatas.Any())
  1968. {
  1969. decimal royaltyCNYTotalPrice = _royaltyDatas.Sum(x => x.Amount);
  1970. var _royaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeExcelView>>(_royaltyDatas);
  1971. royaltyCNYTotalCost = _royaltyFeeViews.Sum(x => x.Amount);
  1972. royaltyFeeDt = CommonFun.ToDataTableArray(_royaltyFeeViews);
  1973. royaltyFeeDt.TableName = $"RoyaltyFeeView";
  1974. }
  1975. }
  1976. #endregion
  1977. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1978. //decimal frTotalAmount = 0.00M;//应收总金额
  1979. 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,
  1980. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1981. From Fin_ForeignReceivables fr
  1982. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1983. Left Join Sys_Users u On fr.Auditor = u.Id
  1984. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1985. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1986. _frViews.ForEach(x =>
  1987. {
  1988. string namePrefix = string.Empty;
  1989. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1990. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1991. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1992. x.PriceName = $"{namePrefix}{x.PriceName}";
  1993. });
  1994. if (_frViews.Any())
  1995. {
  1996. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1997. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1998. receivableFeeDt.TableName = $"ReceivedFeeView";
  1999. }
  2000. #endregion
  2001. #region 已收金额
  2002. //decimal prTotalAmount = 0.00M;//已收总金额
  2003. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2004. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2005. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2006. From Fin_ProceedsReceived pr
  2007. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2008. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2009. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2010. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2011. if (_prViews.Any())
  2012. {
  2013. receivedAmount = _prViews.Sum(it => it.Price);
  2014. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  2015. receivedFeeDt.TableName = $"ReceivableFeeView";
  2016. }
  2017. #endregion
  2018. #region 团组收入支出利润
  2019. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  2020. new DataColumn(){ ColumnName = "ModuleName"},
  2021. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  2022. new DataColumn(){ ColumnName = "FeeCurrency"},
  2023. });
  2024. var groupIEProfitDt_rows = new[] {
  2025. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  2026. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  2027. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  2028. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  2029. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  2030. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  2031. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  2032. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  2033. new object[] { $"操作提成费用", royaltyCNYTotalCost, $"CNY" },
  2034. };
  2035. // 批量添加
  2036. foreach (var rowData in groupIEProfitDt_rows)
  2037. {
  2038. groupIEProfitDt.Rows.Add(rowData);
  2039. }
  2040. #endregion
  2041. #region 统一填充数据源
  2042. designer.SetDataSource("GroupNo", groupNo);
  2043. designer.SetDataSource("GroupName", groupName);
  2044. designer.SetDataSource("Lister", lister);
  2045. //酒店
  2046. designer.SetDataSource(hotelFeeDt);
  2047. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  2048. //地接
  2049. designer.SetDataSource(OPFeeDt);
  2050. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  2051. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  2052. //签证
  2053. designer.SetDataSource(visaFeeDt);
  2054. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  2055. //商邀
  2056. designer.SetDataSource(OAFeeDt);
  2057. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  2058. //机票
  2059. designer.SetDataSource(airTicketFeeDt);
  2060. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  2061. //保险
  2062. designer.SetDataSource(insureFeeDt);
  2063. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  2064. //其他费用
  2065. designer.SetDataSource(otherFeeDt);
  2066. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  2067. //收款退还
  2068. designer.SetDataSource(SKTHFeeDt);
  2069. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  2070. //操作提成
  2071. designer.SetDataSource(royaltyFeeDt);
  2072. designer.SetDataSource("RoyaltyCNYTotalCost", $"{royaltyCNYTotalCost.ToString("#0.00")} CNY");
  2073. //已收金额
  2074. designer.SetDataSource(receivedFeeDt);
  2075. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  2076. //应收金额
  2077. designer.SetDataSource(receivableFeeDt);
  2078. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  2079. //应收已收 -- 尾款
  2080. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  2081. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  2082. //团组收入支出利润
  2083. designer.SetDataSource(groupIEProfitDt);
  2084. #region 各项费用计算
  2085. /*
  2086. * 团组报表计算方式
  2087. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2088. * 应收金额 = 应收表.Sum() - 收款退还
  2089. * 已收金额 = 已收表.Sum() - 收款退还
  2090. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  2091. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  2092. * 利润差 = 应收利润 - 已收利润
  2093. */
  2094. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost + royaltyCNYTotalCost;//合计金额
  2095. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  2096. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  2097. profitMargin = accountsProfit - receiveProfit; //利润差
  2098. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  2099. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  2100. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  2101. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  2102. #endregion
  2103. designer.Process();
  2104. #endregion
  2105. #region 单元格样式设置 未付款设置为红色
  2106. /*
  2107. * 设置单元格样式
  2108. */
  2109. //背景颜色
  2110. Style style = designer.Workbook.CreateStyle();
  2111. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  2112. style.Pattern = BackgroundType.Solid;
  2113. //字体
  2114. style.Font.Name = "微软雅黑"; // 字体名称
  2115. style.Font.Size = 10; // 字体大小
  2116. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  2117. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  2118. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  2119. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  2120. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  2121. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  2122. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  2123. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  2124. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  2125. #endregion
  2126. //文件名
  2127. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  2128. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  2129. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  2130. return Ok(JsonView(true, "成功", url));
  2131. }
  2132. /// <summary>
  2133. /// 团组报表
  2134. /// 利润相关数据
  2135. /// </summary>
  2136. /// <returns></returns>
  2137. [HttpPost("PostGroupStatementDetails1")]
  2138. //[JsonConverter(typeof(DecimalConverter), 2)]
  2139. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2140. public async Task<IActionResult> PostGroupStatementDetails1()
  2141. {
  2142. var groupInfos = _sqlSugar.Queryable<Grp_DelegationInfo>()
  2143. .Where(x => x.IsDel == 0 && x.VisitDate >= DateTime.Parse("2024-01-01") && x.VisitDate <= DateTime.Parse("2024-12-31"))
  2144. .OrderByDescending(x => x.VisitDate)
  2145. .ToList();
  2146. #region 费用类型 币种,转账,客户信息
  2147. List<Sys_SetData> _setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  2148. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  2149. .Where(it => it.IsDel == 0)
  2150. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  2151. .ToList();
  2152. // foreach (var item1 in _clientDatas) EncryptionProcessor.DecryptProperties(item1);
  2153. #endregion
  2154. var _views = new List<GroupStatisticsInfo>();
  2155. int index1 = 0;
  2156. foreach (var info in groupInfos)
  2157. {
  2158. var _dto = new { DiId = info.Id, isAudit = false };
  2159. /*
  2160. * 团组报表计算方式
  2161. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2162. * 应收金额 = 应收表.Sum()
  2163. * 已收金额 = 已收表.Sum()
  2164. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2165. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2166. *
  2167. */
  2168. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  2169. var groupInfo = info;
  2170. var visitDate = info.VisitDate;
  2171. #region 团组收入
  2172. GroupIncomeView _giView = new GroupIncomeView();
  2173. /*
  2174. * 应收报表
  2175. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  2176. */
  2177. decimal frTotalAmount = 0.00M;//应收总金额
  2178. 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,
  2179. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2180. From Fin_ForeignReceivables fr
  2181. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2182. Left Join Sys_Users u On fr.Auditor = u.Id
  2183. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  2184. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2185. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  2186. //if (_frViews1.Count > 0)
  2187. //{
  2188. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  2189. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  2190. //}
  2191. _frViews.ForEach(x =>
  2192. {
  2193. string namePrefix = string.Empty;
  2194. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  2195. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  2196. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  2197. x.PriceName = $"{namePrefix}{x.PriceName}";
  2198. });
  2199. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2200. _giView.Receivables = _frViews;
  2201. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2202. /*
  2203. * 已收报表
  2204. */
  2205. decimal prTotalAmount = 0.00M;//已收总金额
  2206. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2207. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2208. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2209. From Fin_ProceedsReceived pr
  2210. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2211. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2212. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  2213. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2214. prTotalAmount = _prViews.Sum(it => it.Price);
  2215. _giView.ProceedsReceivedViews = _prViews;
  2216. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  2217. /*
  2218. * 超支费用
  2219. */
  2220. decimal exTotalAmount = 0.00M;
  2221. // 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,
  2222. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2223. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2224. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  2225. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2226. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2227. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2228. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2229. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2230. //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 " : " ");
  2231. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  2232. // #region 超支费用 - 模拟数据
  2233. // //if (_ExtraCostsViews.Count < 1)
  2234. // //{
  2235. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2236. // // {
  2237. // // GECId = 0,
  2238. // // GECDiId = 2334,
  2239. // // PriceName = "模拟数据-超支费用名称",
  2240. // // PayMoney = 1000.00M,
  2241. // // PaymentCurrency = "CNY",
  2242. // // DayRate = 1.0000M,
  2243. // // CNYPrice = 1000.00M,
  2244. // // Payee = "模拟数据-超支费用收款方",
  2245. // // OrbitalPrivateTransfer = 1,
  2246. // // PayWay = "刷卡",
  2247. // // CardType = "招行卡",
  2248. // // IsPay = 1,
  2249. // // Applicant = "刘华举"
  2250. // // });
  2251. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  2252. // // {
  2253. // // GECId = 0,
  2254. // // GECDiId = 2334,
  2255. // // PriceName = "模拟数据-超支费用名称",
  2256. // // PayMoney = 1000.00M,
  2257. // // PaymentCurrency = "CNY",
  2258. // // DayRate = 1.0000M,
  2259. // // CNYPrice = 1000.00M,
  2260. // // Payee = "模拟数据-超支费用收款方",
  2261. // // OrbitalPrivateTransfer = 1,
  2262. // // PayWay = "刷卡",
  2263. // // CardType = "招行卡",
  2264. // // IsPay = 1,
  2265. // // Applicant = "刘华举"
  2266. // // });
  2267. // //}
  2268. // #endregion
  2269. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2270. // _giView.ExtraCostsViews = _ExtraCostsViews;
  2271. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2272. /*
  2273. * 收款退还
  2274. */
  2275. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2276. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2277. //删除了 And prom.PriceType = 1
  2278. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2279. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2280. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  2281. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  2282. From Fin_PaymentRefundAndOtherMoney prom
  2283. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2284. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2285. Where prom.IsDel = 0
  2286. And prom.PayType = 1
  2287. And ccp.CTable = 285
  2288. {1}
  2289. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2290. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2291. foreach (var ropItem in _promDatas)
  2292. {
  2293. string thisCueencyCode = "Unknown";
  2294. string thisCueencyName = "Unknown";
  2295. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2296. if (currency != null)
  2297. {
  2298. thisCueencyCode = currency.Name;
  2299. thisCueencyName = currency.Remark;
  2300. }
  2301. string orbitalPrivateTransferStr = "Unknown";
  2302. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2303. if (orbitalPrivateTransfer != null)
  2304. {
  2305. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2306. }
  2307. string payStr = "Unknown";
  2308. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2309. if (pay != null)
  2310. {
  2311. payStr = pay.Name;
  2312. }
  2313. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2314. {
  2315. Id = ropItem.Id,
  2316. DiId = ropItem.DIId,
  2317. PriceName = ropItem.PrPriceName,
  2318. PayCurrencyCode = thisCueencyCode,
  2319. PayCurrencyName = thisCueencyName,
  2320. Price = ropItem.PrPrice,
  2321. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  2322. ThisRate = ropItem.DayRate,
  2323. Payee = ropItem.Payee,
  2324. PayTime = ropItem.AuditGMDate,
  2325. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2326. PayType = payStr,
  2327. IsPay = ropItem.IsPay,
  2328. Applicant = ropItem.Appliction
  2329. };
  2330. _promView.Add(gsd_PaymentRefund);
  2331. }
  2332. #region 收款退还 - 模拟数据
  2333. //if (_promView.Count < 1)
  2334. //{
  2335. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2336. // {
  2337. // Id = 0,
  2338. // DiId = 2334,
  2339. // PriceName = "模拟数据-费用名称",
  2340. // PayCurrencyCode = "CNY",
  2341. // PayCurrencyName = "人民币",
  2342. // Price = 1000.00M,
  2343. // CNYPrice = 1000.00M,
  2344. // ThisRate = 1.00M,
  2345. // Payee = "模拟数据-收款方",
  2346. // PayTime = "2023-01-01 15:20:01",
  2347. // OrbitalPrivateTransfer = 1,
  2348. // PayType = "刷卡",
  2349. // IsPay = 1,
  2350. // Applicant = "刘华举"
  2351. // });
  2352. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  2353. // {
  2354. // Id = 0,
  2355. // DiId = 2334,
  2356. // PriceName = "模拟数据-费用名称",
  2357. // PayCurrencyCode = "CNY",
  2358. // PayCurrencyName = "人民币",
  2359. // Price = 1000.00M,
  2360. // CNYPrice = 1000.00M,
  2361. // ThisRate = 1.00M,
  2362. // Payee = "模拟数据-收款方",
  2363. // PayTime = "2023-01-01 15:20:01",
  2364. // OrbitalPrivateTransfer = 1,
  2365. // PayType = "刷卡",
  2366. // IsPay = 1,
  2367. // Applicant = "刘华举"
  2368. // });
  2369. //}
  2370. #endregion
  2371. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2372. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  2373. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  2374. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  2375. _view.GroupIncome = _giView;
  2376. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  2377. #endregion
  2378. #region 团组支出
  2379. GroupExpenditureView _geView = new GroupExpenditureView();
  2380. #region 酒店预定费用
  2381. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2382. //ccp.RMBPrice As CNYPrice
  2383. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2384. string hotelFeeSql = string.Format(@"
  2385. SELECT
  2386. hr.Id AS HrId,
  2387. hr.DiId AS HrDiId,
  2388. hr.City,
  2389. hr.HotelName,
  2390. hr.CheckInDate,
  2391. hr.CheckOutDate,
  2392. hr.CardPrice AS RoomPrice,
  2393. sd1.Name AS PaymentCurrency,
  2394. hr.SingleRoomPrice,
  2395. hr.SingleRoomCount,
  2396. hr.DoubleRoomPrice,
  2397. hr.DoubleRoomCount,
  2398. hr.SuiteRoomPrice,
  2399. hr.SuiteRoomCount,
  2400. hr.OtherRoomPrice,
  2401. hr.OtherRoomCount,
  2402. hr.BreakfastPrice,
  2403. sd4.Name AS BreakfastCurrency,
  2404. hr.Isoppay,
  2405. hr.GovernmentRent,
  2406. sd5.Name AS GovernmentRentCurrency,
  2407. hr.CityTax,
  2408. sd6.Name AS CityTaxCurrency,
  2409. ccp.PayMoney,
  2410. (
  2411. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  2412. ) AS CNYPrice,
  2413. ccp.PayPercentage,
  2414. ccp.DayRate,
  2415. ccp.Payee,
  2416. ccp.OrbitalPrivateTransfer,
  2417. sd2.Name AS PayWay,
  2418. sd3.Name AS CardType,
  2419. ccp.IsPay,
  2420. u.CnName AS Applicant
  2421. FROM
  2422. Grp_HotelReservations hr
  2423. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  2424. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  2425. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  2426. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  2427. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  2428. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  2429. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  2430. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  2431. WHERE
  2432. hr.IsDel = 0
  2433. AND ccp.IsDel = 0
  2434. AND ccp.CTable = 76 {1}
  2435. AND ccp.PayMoney <> 0
  2436. AND hr.DiId = {0}
  2437. ORDER BY
  2438. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  2439. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2440. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  2441. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  2442. decimal HotelCNYTotalPrice = 0.00M;
  2443. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  2444. foreach (var item in groupHotelFeeViews)
  2445. {
  2446. if (groupHotelContentFeeViews.Count > 0)
  2447. {
  2448. string paymentStr = string.Empty;
  2449. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  2450. item.RoomPrice = roomData?.Price ?? 0.00M;
  2451. if (item.RoomPrice != 0)
  2452. {
  2453. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  2454. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  2455. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2456. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  2457. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  2458. 收款方:{roomData?.Payee}<br/>
  2459. 费用标识:{feeMark1} <br/>
  2460. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2461. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  2462. 是否由地接支付:{isFeeMark1} <br/>";
  2463. }
  2464. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  2465. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  2466. if (item.BreakfastPrice != 0)
  2467. {
  2468. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  2469. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  2470. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2471. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  2472. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  2473. 收款方:{breakfastData?.Payee}<br/>
  2474. 费用标识:{feeMark2} <br/>
  2475. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  2476. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  2477. 是否由地接支付:{isFeeMark2} <br/>";
  2478. }
  2479. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  2480. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  2481. if (item.GovernmentRent != 0)
  2482. {
  2483. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  2484. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  2485. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2486. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2487. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  2488. 收款方:{landTaxData?.Payee}<br/>
  2489. 费用标识:{feeMark3} <br/>
  2490. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  2491. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  2492. 是否由地接支付:{isFeeMark3} <br/>";
  2493. }
  2494. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  2495. item.CityTax = cityTaxData?.Price ?? 0.00M;
  2496. if (item.CityTax != 0)
  2497. {
  2498. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  2499. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  2500. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  2501. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  2502. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  2503. 收款方:{cityTaxData?.Payee}<br/>
  2504. 费用标识:{feeMark4} <br/>
  2505. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  2506. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  2507. 是否由地接支付:{isFeeMark4} <br/>";
  2508. }
  2509. if (!string.IsNullOrEmpty(paymentStr))
  2510. {
  2511. item.IsPay = 2;
  2512. item.PayTips = paymentStr;
  2513. }
  2514. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  2515. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  2516. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  2517. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  2518. }
  2519. else
  2520. {
  2521. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  2522. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  2523. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  2524. (item.OtherRoomCount * item.OtherRoomPrice);
  2525. //item.RoomPrice = item.CardPrice;
  2526. item.RoomPriceCurrency = item.PaymentCurrency;
  2527. }
  2528. HotelCNYTotalPrice += item.CNYPrice;
  2529. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  2530. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  2531. }
  2532. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  2533. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  2534. #endregion
  2535. #region 地接费用
  2536. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2537. string CTGGRFeeSql = string.Empty;
  2538. if (visitDate > Convert.ToDateTime("2024-04-17"))
  2539. {
  2540. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  2541. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2542. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  2543. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  2544. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2545. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2546. From Grp_CarTouristGuideGroundReservations ctggr
  2547. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  2548. cggrc.DatePrice,cggrc.PriceContent
  2549. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2550. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2551. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2552. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2553. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2554. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2555. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2556. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2557. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2558. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2559. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2560. }
  2561. else
  2562. {
  2563. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  2564. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  2565. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  2566. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  2567. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  2568. ccp.Payee,ccp.AuditGMDate,
  2569. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2570. From Grp_CarTouristGuideGroundReservations ctggr
  2571. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2572. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2573. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2574. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2575. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  2576. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  2577. }
  2578. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2579. string CTGGRFeeStr = "";
  2580. decimal CTGGRCNYTotalPrice = 0.00M;
  2581. //按1 地区,2 币种,3 汇率 分组计算
  2582. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  2583. foreach (var ctggfr in groupCTGGRFeeDatas)
  2584. {
  2585. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  2586. if (ctggfr_curr.Count() > 0)
  2587. {
  2588. foreach (var curr in ctggfr_curr)
  2589. {
  2590. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  2591. if (ctggfr_rate.Count() > 0)
  2592. {
  2593. foreach (var rate in ctggfr_rate)
  2594. {
  2595. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  2596. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  2597. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2598. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2599. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2600. }
  2601. }
  2602. else
  2603. {
  2604. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2605. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2606. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2607. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2608. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2609. }
  2610. }
  2611. }
  2612. else
  2613. {
  2614. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  2615. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  2616. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  2617. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  2618. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2619. }
  2620. }
  2621. foreach (var item in groupCTGGRFeeViews)
  2622. {
  2623. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2624. {
  2625. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2626. }
  2627. if (item.DatePrice != DateTime.MinValue)
  2628. {
  2629. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  2630. }
  2631. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  2632. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  2633. //CTGGRCNYTotalPrice += item.CNYPrice;
  2634. }
  2635. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  2636. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  2637. #endregion
  2638. #region 机票预订费用
  2639. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2640. //ccp.RMBPrice As CNYPrice
  2641. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2642. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2643. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2644. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2645. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  2646. atr.CType
  2647. From Grp_AirTicketReservations atr
  2648. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2649. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2650. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2651. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2652. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2653. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2654. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2655. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2656. string str = "";
  2657. List<dynamic> airClientPris = new List<dynamic>();
  2658. decimal AirCNYTotalPrice = 0.00M;
  2659. //decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M;
  2660. decimal JJCAveragePrice = 0.00M;
  2661. //decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M;
  2662. decimal GWCAveragePrice = 0.00M;
  2663. //if (groupAirFeeViews.Count > 0)
  2664. //{
  2665. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  2666. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  2667. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  2668. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  2669. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  2670. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  2671. //}
  2672. int Index = 0;
  2673. foreach (var item in groupAirFeeViews)
  2674. {
  2675. if (item.AirId > 2924)
  2676. {
  2677. string itemClientName = "";
  2678. if (!string.IsNullOrEmpty(item.ClientName))
  2679. {
  2680. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  2681. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  2682. if (m_EnName.Success || m_ZHName.Success)
  2683. {
  2684. itemClientName = item.ClientName;
  2685. AirCNYTotalPrice += item.CNYPrice;
  2686. continue;
  2687. }
  2688. string[] clientIds = Array.Empty<string>();
  2689. if (item.ClientName.Contains(','))
  2690. {
  2691. clientIds = item.ClientName.Split(',');
  2692. }
  2693. else
  2694. {
  2695. clientIds = new string[] { item.ClientName };
  2696. }
  2697. if (clientIds.Length > 0)
  2698. {
  2699. int[] output = System.Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  2700. if (output.Contains(-1))
  2701. {
  2702. itemClientName += $@"行程单";
  2703. output = output.Where(val => val != -1).ToArray();
  2704. }
  2705. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  2706. decimal unitCost = 0.00M;
  2707. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  2708. int clienIndex = 1;
  2709. foreach (var client in clients)
  2710. {
  2711. airClientPris.Add(new
  2712. {
  2713. CnName = client.LastName + client.FirstName,
  2714. EnName = client.Pinyin,
  2715. Price = unitCost,
  2716. AirType = item.AirTypeName
  2717. });
  2718. string six = "";
  2719. if (client.Sex == 0) six = "Mr";
  2720. else if (client.Sex == 1) six = "Ms";
  2721. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  2722. clienIndex++;
  2723. }
  2724. }
  2725. }
  2726. item.ClientName = itemClientName;
  2727. }
  2728. else
  2729. {
  2730. string clientPinYinName = "";
  2731. decimal unitCost = 0.00M;
  2732. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  2733. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  2734. Regex r = new Regex("[0-9]");
  2735. string name1 = item.ClientName;
  2736. name1 = r.Replace(name1, "");
  2737. string[] clientNames = name1.Split('.');
  2738. for (int i = 0; i < item.ClientNum; i++)
  2739. {
  2740. string name = "";
  2741. if (clientNames.Length > 0)
  2742. {
  2743. int index = i + 1;
  2744. if (index < clientNames.Length)
  2745. {
  2746. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  2747. if (!string.IsNullOrEmpty(name))
  2748. {
  2749. airClientPris.Add(new
  2750. {
  2751. CnName = name,
  2752. EnName = name,
  2753. Price = unitCost,
  2754. AirType = item.AirTypeName
  2755. });
  2756. }
  2757. //if (name.Length > 0)
  2758. //{
  2759. // string nameLastStr = name[name.Length - 1].ToString();
  2760. // if (nameLastStr.IsNumeric())
  2761. // {
  2762. // name = name.Substring(0, name.Length - 1).Trim();
  2763. // }
  2764. //}
  2765. }
  2766. }
  2767. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  2768. }
  2769. }
  2770. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2771. {
  2772. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2773. }
  2774. AirCNYTotalPrice += item.CNYPrice;
  2775. }
  2776. _geView.GroupAirFeeViews = groupAirFeeViews;
  2777. if (airClientPris.Count > 0)
  2778. {
  2779. var peoplePriStr = "";
  2780. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  2781. .Select(group => group.First())
  2782. .ToList();
  2783. int airClientPrisIndex = 1;
  2784. foreach (var item in airClientPris1)
  2785. {
  2786. decimal price = 0.00M;
  2787. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  2788. foreach (var pri in prices)
  2789. {
  2790. price += pri.Price;
  2791. }
  2792. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  2793. airClientPrisIndex++;
  2794. }
  2795. if (!string.IsNullOrEmpty(peoplePriStr))
  2796. {
  2797. str = $@"其中:{peoplePriStr}";
  2798. }
  2799. //经济舱均价
  2800. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  2801. if (airJJCPris.Count > 0)
  2802. {
  2803. decimal jjcTotalPrice = 0.00M;
  2804. foreach (var item in airJJCPris)
  2805. {
  2806. jjcTotalPrice += item.Price;
  2807. }
  2808. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  2809. .Select(group => group.First())
  2810. .ToList().Count;
  2811. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  2812. }
  2813. //公务舱均价
  2814. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  2815. if (airGWCPris.Count > 0)
  2816. {
  2817. decimal gwcTotalPrice = 0.00M;
  2818. foreach (var item in airGWCPris)
  2819. {
  2820. gwcTotalPrice += item.Price;
  2821. }
  2822. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  2823. .Select(group => group.First())
  2824. .ToList().Count;
  2825. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  2826. }
  2827. }
  2828. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  2829. #endregion
  2830. #region 签证费用
  2831. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2832. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2833. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2834. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  2835. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  2836. From Grp_VisaInfo vi
  2837. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2838. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2839. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2840. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2841. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2842. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2843. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2844. decimal VisaCNYTotalPirce = 0.00M;
  2845. foreach (var item in groupVisaFeeViews)
  2846. {
  2847. string itemClientName = "";
  2848. string visaClients = item.VisaClient;
  2849. if (!string.IsNullOrEmpty(visaClients))
  2850. {
  2851. string[] clientIds = Array.Empty<string>();
  2852. if (visaClients.Contains(','))
  2853. {
  2854. clientIds = visaClients.Split(',');
  2855. }
  2856. else
  2857. {
  2858. clientIds = new string[] { visaClients };
  2859. }
  2860. if (clientIds.Length > 0)
  2861. {
  2862. List<int> clientIds1 = new List<int>() { };
  2863. foreach (var clientIdStr in clientIds)
  2864. {
  2865. if (clientIdStr.IsNumeric())
  2866. {
  2867. clientIds1.Add(int.Parse(clientIdStr));
  2868. }
  2869. }
  2870. if (clientIds1.Count > 0)
  2871. {
  2872. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  2873. foreach (var client in clients)
  2874. {
  2875. itemClientName += $"{client.LastName + client.FirstName},";
  2876. }
  2877. }
  2878. else
  2879. {
  2880. itemClientName = visaClients;
  2881. }
  2882. }
  2883. }
  2884. if (itemClientName.Length > 0)
  2885. {
  2886. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  2887. }
  2888. item.VisaClient = itemClientName;
  2889. VisaCNYTotalPirce += item.CNYPrice;
  2890. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2891. {
  2892. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2893. }
  2894. }
  2895. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  2896. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#0.00"));
  2897. #endregion
  2898. #region 邀请/公务活动 CTable = 81
  2899. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2900. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2901. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2902. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2903. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  2904. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  2905. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2906. From Grp_InvitationOfficialActivities ioa
  2907. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2908. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2909. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2910. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2911. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2912. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2913. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2914. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2915. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2916. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  2917. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2918. #region 邀请/公务活动 - 模拟数据
  2919. //if (groupInvitationalFeeViews.Count < 1)
  2920. //{
  2921. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2922. // {
  2923. // IOAId = 0,
  2924. // IOADiId = 2334,
  2925. // InviterArea = "模拟数据-邀请方地区",
  2926. // Inviter = "模拟数据-邀请方",
  2927. // InviteTime = "2023-10-10",
  2928. // InviteCost = 100.00M,
  2929. // InviteCurrency = "EUR",
  2930. // SendCost = 100.00M,
  2931. // SendCurrency = "EUR",
  2932. // EventsCost = 10000.00M,
  2933. // EventsCurrency = "EUR",
  2934. // TranslateCost = 300.00M,
  2935. // TranslateCurrency = "EUR",
  2936. // PayMoney = 10500.00M,
  2937. // PaymentCurrency = "EUR",
  2938. // CNYPrice = 76765.50M,
  2939. // Payee = "模拟数据-收款方",
  2940. // AuditGMDate = "2023-12-05",
  2941. // OrbitalPrivateTransfer = 1,
  2942. // PayWay = "刷卡",
  2943. // IsPay = 1,
  2944. // Applicant = "刘华举"
  2945. // });
  2946. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  2947. // {
  2948. // IOAId = 0,
  2949. // IOADiId = 2334,
  2950. // InviterArea = "模拟数据-邀请方地区",
  2951. // Inviter = "模拟数据-邀请方",
  2952. // InviteTime = "2023-10-10",
  2953. // InviteCost = 100.00M,
  2954. // InviteCurrency = "EUR",
  2955. // SendCost = 100.00M,
  2956. // SendCurrency = "EUR",
  2957. // EventsCost = 10000.00M,
  2958. // EventsCurrency = "EUR",
  2959. // TranslateCost = 300.00M,
  2960. // TranslateCurrency = "EUR",
  2961. // PayMoney = 10500.00M,
  2962. // PaymentCurrency = "EUR",
  2963. // CNYPrice = 76765.50M,
  2964. // Payee = "模拟数据-收款方",
  2965. // AuditGMDate = "2023-12-05",
  2966. // OrbitalPrivateTransfer = 1,
  2967. // PayWay = "刷卡",
  2968. // IsPay = 1,
  2969. // Applicant = "刘华举"
  2970. // });
  2971. //}
  2972. #endregion
  2973. decimal InvitationalCNYTotalPrice = 0.00M;
  2974. foreach (var item in groupInvitationalFeeViews)
  2975. {
  2976. InvitationalCNYTotalPrice += item.CNYPrice2;
  2977. if (!string.IsNullOrEmpty(item.AuditGMDate))
  2978. {
  2979. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  2980. }
  2981. string currencyRateStr = "";
  2982. List<string> currencys = new List<string>();
  2983. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  2984. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  2985. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  2986. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  2987. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  2988. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  2989. item.CurrencyRateStr = currencyRateStr;
  2990. }
  2991. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  2992. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#0.00"));
  2993. #endregion
  2994. #region 保险费用
  2995. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2996. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  2997. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2998. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2999. From Grp_Customers ic
  3000. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3001. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3002. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3003. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3004. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  3005. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3006. decimal InsuranceCNYTotalPrice = 0.00M;
  3007. foreach (var item in groupInsuranceFeeViews)
  3008. {
  3009. InsuranceCNYTotalPrice += item.CNYPrice;
  3010. string itemClientName = "";
  3011. string insClients = item.ClientName;
  3012. if (!string.IsNullOrEmpty(insClients))
  3013. {
  3014. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  3015. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  3016. //if (m_EnName.Success || m_ZHName.Success)
  3017. //{
  3018. // itemClientName = insClients;
  3019. // continue;
  3020. //}
  3021. string[] clientIds = Array.Empty<string>();
  3022. if (insClients.Contains(','))
  3023. {
  3024. clientIds = insClients.Split(',');
  3025. }
  3026. else
  3027. {
  3028. clientIds = new string[] { insClients };
  3029. }
  3030. if (clientIds.Length > 0)
  3031. {
  3032. List<int> output = new List<int>();
  3033. foreach (var clientId in clientIds)
  3034. {
  3035. if (clientId.IsNumeric())
  3036. {
  3037. output.Add(int.Parse(clientId));
  3038. }
  3039. }
  3040. if (output.Count > 0)
  3041. {
  3042. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  3043. foreach (var client in clients)
  3044. {
  3045. itemClientName += $"{client.LastName + client.FirstName},";
  3046. }
  3047. if (itemClientName.Length > 0)
  3048. {
  3049. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  3050. }
  3051. }
  3052. else
  3053. {
  3054. itemClientName = insClients;
  3055. }
  3056. }
  3057. }
  3058. item.ClientName = itemClientName;
  3059. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3060. {
  3061. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3062. }
  3063. }
  3064. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  3065. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  3066. #endregion
  3067. #region 其他款项费用 98
  3068. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3069. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3070. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3071. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3072. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3073. From Grp_DecreasePayments dp
  3074. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3075. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3076. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3077. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3078. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  3079. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  3080. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3081. #region 保险费用 - 模拟数据
  3082. //if (groupDecreaseFeeViews.Count < 1)
  3083. //{
  3084. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  3085. // {
  3086. // DPId = 0,
  3087. // DPDiId = 2334,
  3088. // PriceName = "模拟数据-费用名称",
  3089. // PayMoney = 1000.00M,
  3090. // PayMoneyCurrency = "CNY",
  3091. // DayRate = 1.0000M,
  3092. // CNYPrice = 1.0000M,
  3093. // AuditGMDate = "2023-12-10 12:13:00",
  3094. // Payee = "模拟数据-付款方",
  3095. // OrbitalPrivateTransfer = 1,
  3096. // PayWay = "现金",
  3097. // IsPay = 1,
  3098. // Applicant = "刘华举"
  3099. // });
  3100. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  3101. // {
  3102. // DPId = 0,
  3103. // DPDiId = 2334,
  3104. // PriceName = "模拟数据-费用名称",
  3105. // PayMoney = 1000.00M,
  3106. // PayMoneyCurrency = "CNY",
  3107. // DayRate = 1.0000M,
  3108. // CNYPrice = 1.0000M,
  3109. // AuditGMDate = "2023-12-10 12:13:00",
  3110. // Payee = "模拟数据-付款方",
  3111. // OrbitalPrivateTransfer = 1,
  3112. // PayWay = "现金",
  3113. // IsPay = 1,
  3114. // Applicant = "刘华举"
  3115. // });
  3116. //}
  3117. #endregion
  3118. decimal DecreaseCNYTotalPrice = 0.00M;
  3119. foreach (var item in groupDecreaseFeeViews)
  3120. {
  3121. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  3122. DecreaseCNYTotalPrice += item.CNYPrice;
  3123. if (!string.IsNullOrEmpty(item.AuditGMDate))
  3124. {
  3125. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  3126. }
  3127. }
  3128. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  3129. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  3130. #endregion
  3131. #region 公司内部操作人员提成
  3132. var royaltyDatas = await _sqlSugar
  3133. .Queryable<Fin_RoyaltyConfirm, Sys_Users, Sys_Users>((rc, u1, u2) =>
  3134. new JoinQueryInfos(
  3135. JoinType.Left, rc.UserId == u1.Id,
  3136. JoinType.Left, rc.CreateUserId == u2.Id
  3137. ))
  3138. .Where((rc, u1, u2) => rc.IsDel == 0 && rc.TeamId == _dto.DiId && rc.IsConfirm == 1)
  3139. .Select((rc, u1, u2) => new GroupRoyaltyFeeInfo()
  3140. {
  3141. GroupId = rc.TeamId,
  3142. OverviewInfo = rc.Temp,
  3143. DetailedInfo = rc.ChiArr,
  3144. Amount = rc.Price,
  3145. IsConfirm = rc.IsConfirm,
  3146. IsSeed = rc.IsSeed,
  3147. RoyaltyUserName = u1.CnName,
  3148. CreateUserName = u2.CnName,
  3149. CreateTime = rc.CreateTime
  3150. })
  3151. .ToListAsync();
  3152. decimal royaltyCNYTotalPrice = royaltyDatas.Sum(x => x.Amount);
  3153. _geView.GroupRoyaltyFeeViews = _mapper.Map<List<GroupRoyaltyFeeView>>(royaltyDatas);
  3154. _geView.GroupRoyaltyFeeStr = string.Format(@"人民币总费用:{0} CNY", royaltyCNYTotalPrice.ToString("#0.00"));
  3155. #endregion
  3156. _view.GroupExpenditure = _geView;
  3157. #endregion
  3158. /*
  3159. * 团组报表计算方式
  3160. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3161. * 应收金额 = 应收表.Sum()
  3162. * 已收金额 = 已收表.Sum()
  3163. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3164. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3165. *
  3166. */
  3167. decimal _totalExpenditure = 0.00M; //总支出
  3168. decimal _amountReceivable = 0.00M; //应收金额
  3169. decimal _amountReceived = 0.00M; //已收金额
  3170. decimal _receivableProfit = 0.00M; //应收利润
  3171. decimal _receivedProfit = 0.00M; //已收利润
  3172. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3173. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount + royaltyCNYTotalPrice;
  3174. _amountReceivable = frTotalAmount;
  3175. _amountReceived = prTotalAmount;
  3176. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3177. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3178. _view.FeeTotalStr = string.Format(@$"<span>
  3179. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  3180. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  3181. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  3182. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  3183. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  3184. </span>");
  3185. index1++;
  3186. _views.Add(new GroupStatisticsInfo()
  3187. {
  3188. Index = index1,
  3189. Id = info.Id,
  3190. GroupName = info.TeamName,
  3191. VisitDate = info.VisitDate,
  3192. Receivable = Math.Floor(_amountReceivable * 100) / 100,
  3193. Cost = Math.Floor(_totalExpenditure * 100) / 100,
  3194. Grossprofit = Math.Floor((_amountReceivable - _totalExpenditure) * 100) / 100,
  3195. });
  3196. }
  3197. return Ok(JsonView(true, "查询成功!", _views));
  3198. }
  3199. private class GroupStatisticsInfo
  3200. {
  3201. public int Index { get; set; }
  3202. public int Id { get; set; }
  3203. public string GroupName { get; set; }
  3204. public DateTime VisitDate { get; set; }
  3205. public decimal Receivable { get; set; }
  3206. public decimal Cost { get; set; }
  3207. public decimal Grossprofit { get; set; }
  3208. }
  3209. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet, DataTable dt, Style style, string judgeLable, int startIndex, string startRange, string endRange)
  3210. {
  3211. if (designer == null) return;
  3212. if (sheet == null) return;
  3213. if (style == null) return;
  3214. if (dt == null) return;
  3215. if (string.IsNullOrEmpty(startRange)) return;
  3216. if (string.IsNullOrEmpty(endRange)) return;
  3217. for (int i = 0; i < dt.Rows.Count; i++)
  3218. {
  3219. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  3220. if (string.IsNullOrEmpty(isPayStr)) continue;
  3221. if (isPayStr.Contains("未付款"))
  3222. {
  3223. var excelIndex = startIndex + i;
  3224. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  3225. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  3226. }
  3227. }
  3228. }
  3229. /// <summary>
  3230. /// 团组报表 - 会务超支验证excel下载
  3231. /// </summary>
  3232. /// <param name="dto"></param>
  3233. /// <returns></returns>
  3234. [HttpPost("PostGroupStatementValidateExpenses")]
  3235. public async Task<IActionResult> PostGroupStatementValidateExpenses(PostGroupStatementValidateExpensesDto dto)
  3236. {
  3237. // 1. 参数与业务校验
  3238. if (dto.GroupId <= 0 || dto.CurrUserId <= 0) return Ok(JsonView(false, "参数非法"));
  3239. var isConfGroup = await _sqlSugar.Queryable<Grp_DelegationInfo, Sys_SetData>((g, s) => g.TeamDid == s.Id)
  3240. .Where((g, s) => g.IsDel == 0 && g.Id == dto.GroupId && s.STid == 10 && s.Name.Contains("会务活动"))
  3241. .AnyAsync();
  3242. if (!isConfGroup) return Ok(JsonView(false, "当前团组非会务团组,禁止操作"));
  3243. // 2. 数据查询与处理
  3244. var feeList = await _sqlSugar.Queryable<Grp_DecreasePayments>()
  3245. .InnerJoin<Grp_CreditCardPayment>((x, y) => x.Id == y.CId && x.DiId == y.DIId && y.CTable == 98)
  3246. .LeftJoin<Sys_Users>((x, y, z) => x.CreateUserId == z.Id)
  3247. .Where((x, y, z) => x.IsDel == 0 && x.DiId == dto.GroupId)
  3248. .Select((x, y, z) => new ConfValidateExpensesView
  3249. {
  3250. PriceName = x.PriceName,
  3251. FeeEntry = y.PayMoney * y.DayRate,
  3252. AuditStatus = y.IsAuditGM.ToString(),
  3253. AuditTime = y.AuditGMDate,
  3254. PayLabel = y.IsPay.ToString(),
  3255. Remark = x.Remark,
  3256. Applicant = z.CnName,
  3257. ApplicantTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
  3258. }).ToListAsync();
  3259. if (!feeList.Any()) return Ok(JsonView(false, "未检索到实际费用记录"));
  3260. var expenseData = await _sqlSugar.Queryable<Grp_ConferenceAffairsCostChild>()
  3261. .InnerJoin<Grp_ConferenceAffairsCost>((x, y) => x.ConferenceAffairsCostId == y.Id)
  3262. .Where((x, y) => y.IsDel == 0 && y.Diid == dto.GroupId && x.ReviewStatus == 1)
  3263. .Select((x, y) => new { x.PriceName, Total = x.CostPrice * x.Rate * x.Count })
  3264. .ToListAsync();
  3265. var expenseDict = expenseData.ToDictionary(k => k.PriceName, v => v.Total);
  3266. // 数据转换逻辑
  3267. int index = 1;
  3268. foreach (var item in feeList.OrderBy(x => x.PriceName).ThenBy(x => x.ApplicantTime))
  3269. {
  3270. item.Index = index++;
  3271. item.AuditStatus = MapAuditStatus(item.AuditStatus);
  3272. item.PayLabel = item.PayLabel == "1" ? "已支付" : "未支付";
  3273. if (expenseDict.TryGetValue(item.PriceName, out decimal budget))
  3274. {
  3275. item.ExpenseEntry = budget;
  3276. item.OverspentLabel = item.FeeEntry > budget ? "超支" : "未超支";
  3277. }
  3278. else
  3279. {
  3280. item.OverspentLabel = item.FeeEntry <= 0 ? "未超支" : "成本未录入项(系统判定超支)";
  3281. }
  3282. }
  3283. // 3. 路径与导出
  3284. try
  3285. {
  3286. var groupName = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == dto.GroupId).Select(x => x.TeamName).FirstAsync() ?? "未知团组";
  3287. string baseUrl = AppSettingsHelper.Get("ExcelBaseUrl").TrimEnd('/');
  3288. string basePath = AppSettingsHelper.Get("ExcelBasePath").TrimEnd('\\').TrimEnd('/');
  3289. string fptPath = AppSettingsHelper.Get("ExcelFtpPath");
  3290. string dirName = "GroupConf";
  3291. // 目录不存在时创建
  3292. string targetDir = Path.Combine(basePath, dirName);
  3293. if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
  3294. string fileName = $"{groupName}_会务校验_{DateTime.Now:yyyyMMddHHmm}.xlsx";
  3295. string fullPath = Path.Combine(targetDir, fileName);
  3296. // 生成文件
  3297. var isSuccess = await ExportToExcel(feeList, fullPath, "超支验证明细");
  3298. if (isSuccess)
  3299. {
  3300. return Ok(JsonView(true, "操作成功", new { url = $"{baseUrl}{fptPath}{dirName}/{fileName}" }));
  3301. }
  3302. return Ok(JsonView(false, "文件生成失败"));
  3303. }
  3304. catch (Exception ex)
  3305. {
  3306. return Ok(JsonView(false, $"导出异常:{ex.Message}"));
  3307. }
  3308. }
  3309. private string MapAuditStatus(string status) => status switch
  3310. {
  3311. "0" => "未审核",
  3312. "1" => "已审核",
  3313. "2" => "未通过",
  3314. "3" => "自动审核",
  3315. _ => "未知"
  3316. };
  3317. public static async Task<bool> ExportToExcel<T>(IEnumerable<T> data, string absolutePath, string sheetName)
  3318. {
  3319. Workbook workbook = new Workbook();
  3320. Worksheet sheet = workbook.Worksheets[0];
  3321. sheet.Name = sheetName;
  3322. PropertyInfo[] props = typeof(T).GetProperties();
  3323. // 1. 表头处理
  3324. Style headerStyle = workbook.CreateStyle();
  3325. headerStyle.Font.Name = "微软雅黑";
  3326. headerStyle.Font.IsBold = true;
  3327. headerStyle.Pattern = BackgroundType.Solid;
  3328. headerStyle.ForegroundColor = System.Drawing.Color.LightGray;
  3329. headerStyle.HorizontalAlignment = TextAlignmentType.Center;
  3330. for (int i = 0; i < props.Length; i++)
  3331. {
  3332. var attr = props[i].GetCustomAttribute<DisplayAttribute>();
  3333. sheet.Cells[0, i].PutValue(attr?.Name ?? props[i].Name);
  3334. sheet.Cells[0, i].SetStyle(headerStyle);
  3335. }
  3336. // 2. 数据处理
  3337. var list = data.ToList();
  3338. for (int r = 0; r < list.Count; r++)
  3339. {
  3340. for (int c = 0; c < props.Length; c++)
  3341. {
  3342. var val = props[c].GetValue(list[r]);
  3343. Aspose.Cells.Cell cell = sheet.Cells[r + 1, c];
  3344. cell.PutValue(val);
  3345. // 高亮逻辑:仅在超支单元格设置红色
  3346. if (props[c].Name == "OverspentLabel" && val?.ToString()?.Contains("超支") == true)
  3347. {
  3348. Style s = cell.GetStyle();
  3349. s.Font.Color = System.Drawing.Color.Red;
  3350. s.Font.IsBold = true;
  3351. cell.SetStyle(s);
  3352. }
  3353. }
  3354. }
  3355. sheet.AutoFitColumns();
  3356. // 3. 物理保存
  3357. try
  3358. {
  3359. using (FileStream fs = new FileStream(absolutePath, FileMode.Create, FileAccess.Write, FileShare.None))
  3360. {
  3361. workbook.Save(fs, SaveFormat.Xlsx);
  3362. await fs.FlushAsync();
  3363. }
  3364. return System.IO.File.Exists(absolutePath);
  3365. }
  3366. catch { return false; }
  3367. }
  3368. #endregion
  3369. #region 报表/折线图统计
  3370. //企业利润-团组利润
  3371. //企业利润-会务利润
  3372. /// <summary>
  3373. /// 企业利润
  3374. /// Details
  3375. /// 待添加权限验证
  3376. /// </summary>
  3377. /// <param name="_dto">团组列表请求dto</param>
  3378. /// <returns></returns>
  3379. [HttpPost("PostCorporateProfit")]
  3380. //[JsonConverter(typeof(DecimalConverter), 2)]
  3381. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3382. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  3383. {
  3384. #region 参数验证
  3385. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3386. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3387. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3388. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  3389. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  3390. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3391. #region 页面操作权限验证
  3392. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3393. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3394. #endregion
  3395. string sqlWhere = string.Empty;
  3396. //起止时间
  3397. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3398. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3399. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3400. //业务类型
  3401. List<int> groupTypeId = new List<int>();
  3402. if (_dto.BusinessType == 2) //团组
  3403. {
  3404. groupTypeId.AddRange(new List<int>() {
  3405. 38, // 政府团
  3406. 39, // 企业团
  3407. 40, // 散客团
  3408. 1048 // 高校团
  3409. });
  3410. }
  3411. else if (_dto.BusinessType == 3) //会务
  3412. {
  3413. groupTypeId.AddRange(new List<int>() {
  3414. 102, // 未知
  3415. 248, // 非团组
  3416. 302, // 成都-会务活动
  3417. 691, // 四川-会务活动
  3418. 762, // 四川-赛事项目收入
  3419. 1047 // 成都-赛事项目收入
  3420. });
  3421. }
  3422. if (groupTypeId.Count > 0)
  3423. {
  3424. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  3425. }
  3426. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3427. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3428. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3429. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  3430. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  3431. List<MonthInfo> months = new List<MonthInfo>();
  3432. if (_dto.StatisticsType == 1) //月份
  3433. {
  3434. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  3435. }
  3436. else if (_dto.StatisticsType == 1) //季度
  3437. {
  3438. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  3439. }
  3440. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  3441. foreach (var item in months)
  3442. {
  3443. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  3444. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  3445. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  3446. _view.Add(new CorporateProfitMonthView()
  3447. {
  3448. Month = item.Month,
  3449. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  3450. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  3451. });
  3452. }
  3453. return Ok(JsonView(true, "操作成功!", _view));
  3454. #endregion
  3455. }
  3456. /// <summary>
  3457. /// 计算团组利润
  3458. /// </summary>
  3459. /// <param name="diIds"></param>
  3460. /// <returns></returns>
  3461. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  3462. {
  3463. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  3464. if (diIds.Count < 1)
  3465. {
  3466. return corporateProfits;
  3467. }
  3468. #region 计算团组利润
  3469. /*
  3470. * 团组报表计算方式
  3471. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3472. * 应收金额 = 应收表.Sum()
  3473. * 已收金额 = 已收表.Sum()
  3474. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3475. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3476. *
  3477. */
  3478. string diIdStr = string.Join(",", diIds);
  3479. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  3480. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  3481. #region 费用类型 币种,转账,客户信息
  3482. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  3483. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  3484. #endregion
  3485. foreach (var _diId in diIds)
  3486. {
  3487. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  3488. #region 团组收入
  3489. /*
  3490. * 应收报表
  3491. */
  3492. decimal frTotalAmount = 0.00M;//应收总金额
  3493. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  3494. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  3495. From Fin_ForeignReceivables fr
  3496. Left Join Sys_SetData sd On fr.Currency = sd.Id
  3497. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  3498. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  3499. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  3500. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  3501. /*
  3502. * 已收报表
  3503. */
  3504. decimal prTotalAmount = 0.00M;//已收总金额
  3505. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  3506. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  3507. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  3508. From Fin_ProceedsReceived pr
  3509. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  3510. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  3511. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  3512. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  3513. prTotalAmount = _prViews.Sum(it => it.Price);
  3514. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  3515. /*
  3516. * 超支费用
  3517. */
  3518. decimal exTotalAmount = 0.00M;
  3519. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  3520. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3521. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  3522. From OA2023DB.dbo.Fin_GroupExtraCost gec
  3523. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  3524. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3525. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3526. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3527. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3528. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  3529. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  3530. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  3531. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  3532. /*
  3533. * 收款退还
  3534. */
  3535. decimal promTotalAmount = 0.00M;// 收款退还总金额
  3536. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  3537. //删除了 And prom.PriceType = 1
  3538. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  3539. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  3540. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  3541. From Fin_PaymentRefundAndOtherMoney prom
  3542. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  3543. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3544. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  3545. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  3546. And prom.DiId = {0} Order By PrCreateTime", _diId);
  3547. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  3548. foreach (var ropItem in _promDatas)
  3549. {
  3550. string thisCueencyCode = "Unknown";
  3551. string thisCueencyName = "Unknown";
  3552. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  3553. if (currency != null)
  3554. {
  3555. thisCueencyCode = currency.Name;
  3556. thisCueencyName = currency.Remark;
  3557. }
  3558. string orbitalPrivateTransferStr = "Unknown";
  3559. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  3560. if (orbitalPrivateTransfer != null)
  3561. {
  3562. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  3563. }
  3564. string payStr = "Unknown";
  3565. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  3566. if (pay != null)
  3567. {
  3568. payStr = pay.Name;
  3569. }
  3570. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  3571. {
  3572. Id = ropItem.Id,
  3573. DiId = ropItem.DIId,
  3574. PriceName = ropItem.PrPriceName,
  3575. PayCurrencyCode = thisCueencyCode,
  3576. PayCurrencyName = thisCueencyName,
  3577. Price = ropItem.PrPrice,
  3578. CNYPrice = ropItem.RMBPrice,
  3579. ThisRate = ropItem.DayRate,
  3580. Payee = ropItem.Payee,
  3581. PayTime = ropItem.AuditGMDate,
  3582. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  3583. PayType = payStr,
  3584. IsPay = ropItem.IsPay,
  3585. Applicant = ropItem.Appliction
  3586. };
  3587. _promView.Add(gsd_PaymentRefund);
  3588. }
  3589. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  3590. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  3591. #endregion
  3592. #region 团组支出
  3593. GroupExpenditureView _geView = new GroupExpenditureView();
  3594. #region 酒店预定费用
  3595. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  3596. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  3597. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  3598. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  3599. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  3600. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  3601. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  3602. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  3603. From Grp_HotelReservations hr
  3604. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  3605. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3606. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3607. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3608. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3609. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  3610. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  3611. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  3612. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  3613. Order By CheckInDate Asc", _diId);
  3614. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  3615. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  3616. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  3617. #endregion
  3618. #region 地接费用
  3619. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  3620. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  3621. sd2.name As PaymentCurrency,ccp.PayPercentage,
  3622. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  3623. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  3624. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3625. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  3626. From Grp_CarTouristGuideGroundReservations ctggr
  3627. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  3628. cggrc.PriceContent
  3629. From Grp_CarTouristGuideGroundReservationsContent cggrc
  3630. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  3631. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  3632. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  3633. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  3634. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  3635. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  3636. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  3637. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3638. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  3639. Order By CreateTime", _diId);
  3640. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  3641. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3642. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  3643. #endregion
  3644. #region 机票预订费用
  3645. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  3646. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  3647. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  3648. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  3649. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  3650. From Grp_AirTicketReservations atr
  3651. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  3652. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3653. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3654. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3655. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  3656. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3657. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  3658. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  3659. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  3660. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  3661. #endregion
  3662. #region 签证费用
  3663. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  3664. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3665. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  3666. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  3667. From Grp_VisaInfo vi
  3668. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  3669. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3670. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3671. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  3672. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3673. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  3674. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  3675. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  3676. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  3677. #endregion
  3678. #region 邀请/公务活动 CTable = 81
  3679. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  3680. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  3681. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  3682. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  3683. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  3684. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  3685. From Grp_InvitationOfficialActivities ioa
  3686. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  3687. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3688. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3689. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  3690. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  3691. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  3692. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  3693. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  3694. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3695. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  3696. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  3697. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  3698. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  3699. #endregion
  3700. #region 保险费用
  3701. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  3702. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  3703. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3704. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  3705. From Grp_Customers ic
  3706. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  3707. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3708. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3709. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3710. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  3711. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  3712. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  3713. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  3714. #endregion
  3715. #region 其他款项费用 98
  3716. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  3717. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  3718. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  3719. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  3720. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  3721. From Grp_DecreasePayments dp
  3722. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  3723. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  3724. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  3725. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  3726. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  3727. Order By CreateTime", _diId);
  3728. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  3729. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  3730. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  3731. #endregion
  3732. #endregion
  3733. /*
  3734. * 团组报表计算方式
  3735. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  3736. * 应收金额 = 应收表.Sum()
  3737. * 已收金额 = 已收表.Sum()
  3738. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  3739. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  3740. *
  3741. */
  3742. decimal _totalExpenditure = 0.00M; //总支出
  3743. decimal _amountReceivable = 0.00M; //应收金额
  3744. decimal _amountReceived = 0.00M; //已收金额
  3745. decimal _receivableProfit = 0.00M; //应收利润
  3746. decimal _receivedProfit = 0.00M; //已收利润
  3747. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  3748. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  3749. _amountReceivable = frTotalAmount;
  3750. _amountReceived = prTotalAmount;
  3751. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  3752. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  3753. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  3754. corporateProfits.Add(new CorporateProfit()
  3755. {
  3756. DiId = _diId,
  3757. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  3758. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  3759. TotalExpenditure = _totalExpenditure,
  3760. ExpenditureItem = expenditureInfos,
  3761. AmountReceivable = _amountReceivable,
  3762. AmountReceived = _amountReceived,
  3763. ReceivableProfit = _receivableProfit,
  3764. ReceivedProfit = _receivedProfit,
  3765. });
  3766. }
  3767. #endregion
  3768. return corporateProfits;
  3769. }
  3770. //未来预测-地区接团/出团量
  3771. //未来预测-地区酒店预订量
  3772. //未来预测-地区机票预订量
  3773. //未来预测-地区车辆预订量
  3774. /// <summary>
  3775. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  3776. /// Details
  3777. /// 待添加权限验证
  3778. /// </summary>
  3779. /// <param name="_dto">团组列表请求dto</param>
  3780. /// <returns></returns>
  3781. [HttpPost("PostRegionalBookingsNumber")]
  3782. //[JsonConverter(typeof(DecimalConverter), 2)]
  3783. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3784. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  3785. {
  3786. #region 参数验证
  3787. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  3788. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  3789. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  3790. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  3791. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3792. #region 页面操作权限验证
  3793. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3794. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3795. #endregion
  3796. string sqlWhere = string.Empty;
  3797. //起止时间
  3798. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  3799. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  3800. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  3801. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  3802. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  3803. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  3804. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  3805. foreach (var item in groupInfos)
  3806. {
  3807. var data = await GroupBookingsNumber(_dto.Type, item);
  3808. if (data.TypeItem.Count > 0)
  3809. {
  3810. datas.Add(data);
  3811. }
  3812. }
  3813. //类型处理
  3814. if (_dto.Type == 1)//接团
  3815. {
  3816. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  3817. //dynamic groupData = null;
  3818. foreach (var item in datas)
  3819. {
  3820. if (item.TypeItem.Count > 0)
  3821. {
  3822. foreach (var item1 in item.TypeItem)
  3823. {
  3824. if (item1.RegionItem.Count > 0)
  3825. {
  3826. GroupInfo groupInfo = new GroupInfo()
  3827. {
  3828. DiId = item.DiId,
  3829. TeamName = item.GroupName,
  3830. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3831. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3832. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3833. };
  3834. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  3835. }
  3836. }
  3837. }
  3838. }
  3839. var viewsGroup = views.GroupBy(it => it.Name);
  3840. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  3841. foreach (var item in viewsGroup)
  3842. {
  3843. List<GroupInfo> infos = new List<GroupInfo>();
  3844. foreach (var item1 in item)
  3845. {
  3846. infos.AddRange(item1.GroupItem);
  3847. }
  3848. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  3849. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  3850. }
  3851. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3852. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  3853. }
  3854. else if (_dto.Type == 2)
  3855. {
  3856. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  3857. foreach (var item in datas)
  3858. {
  3859. if (item.TypeItem.Count > 0)
  3860. {
  3861. foreach (var item1 in item.TypeItem)
  3862. {
  3863. if (item1.RegionItem.Count > 0)
  3864. {
  3865. foreach (var item2 in item1.RegionItem)
  3866. {
  3867. GroupInfo groupInfo = new GroupInfo()
  3868. {
  3869. DiId = item.DiId,
  3870. TeamName = item.GroupName,
  3871. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  3872. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  3873. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  3874. };
  3875. List<HotelInfo> hotels = new List<HotelInfo>();
  3876. foreach (var item3 in item2.Data)
  3877. {
  3878. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  3879. HotelInfo hotelInfo = new HotelInfo()
  3880. {
  3881. HotelName = statisticsHotelInfos.HotelName,
  3882. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  3883. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  3884. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  3885. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  3886. GroupInfo = groupInfo
  3887. };
  3888. hotels.Add(hotelInfo);
  3889. }
  3890. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  3891. }
  3892. }
  3893. }
  3894. }
  3895. }
  3896. var viewsGroup = views.GroupBy(it => it.Name);
  3897. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  3898. foreach (var item in viewsGroup)
  3899. {
  3900. List<HotelInfo> infos = new List<HotelInfo>();
  3901. foreach (var item1 in item)
  3902. {
  3903. infos.AddRange(item1.HotelItem);
  3904. }
  3905. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  3906. }
  3907. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  3908. return Ok(JsonView(true, "操作成功!", views, views.Count));
  3909. }
  3910. return Ok(JsonView(false, "操作失败!"));
  3911. #endregion
  3912. }
  3913. /// <summary>
  3914. /// 计算团组ALLType预订数量
  3915. /// </summary>
  3916. /// <param name="type"></param>
  3917. /// <param name="info"></param>
  3918. /// <returns></returns>
  3919. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  3920. {
  3921. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  3922. if (info == null)
  3923. {
  3924. return _view;
  3925. }
  3926. _view.DiId = info.Id;
  3927. _view.GroupName = info.TeamName;
  3928. List<TypeInfo> _types = new List<TypeInfo>();
  3929. #region 计算团组ALLType预订数量
  3930. if (type == 1)
  3931. {
  3932. //接团 客户集团所在地区
  3933. string group_region = string.Empty;
  3934. int group_number = 0;
  3935. if (!string.IsNullOrEmpty(info.ClientUnit))
  3936. {
  3937. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  3938. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  3939. .FirstAsync();
  3940. if (_NewClientData != null)
  3941. {
  3942. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  3943. if (regionInfo != null)
  3944. {
  3945. group_region = regionInfo.Name.Replace("级", "");
  3946. group_number++;
  3947. }
  3948. }
  3949. }
  3950. if (group_number > 0)
  3951. {
  3952. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  3953. }
  3954. }
  3955. else if (type == 2)
  3956. {
  3957. //酒店
  3958. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  3959. if (hotelInfos.Count > 0)
  3960. {
  3961. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  3962. foreach (var item in hotelInfos)
  3963. {
  3964. var hotelNumberInfo = new StatisticsHotelInfo()
  3965. {
  3966. HotelName = item.HotelName,
  3967. SingleRoomNum = item.SingleRoomCount,
  3968. DoubleRoomNum = item.DoubleRoomCount,
  3969. SuiteRoomNum = item.SuiteRoomCount,
  3970. OtherRoomNum = item.OtherRoomCount,
  3971. };
  3972. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  3973. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  3974. {
  3975. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  3976. if (hotelRegion != null)
  3977. {
  3978. hotelRegions.Remove(hotelRegion);
  3979. if (hotelRegion.Data.Count > 0)
  3980. {
  3981. hotelRegion.Data.Add(hotelNumberInfo);
  3982. }
  3983. hotelRegion.Number += hotelRoomTotal;
  3984. hotelRegions.Add(hotelRegion);
  3985. }
  3986. }
  3987. else
  3988. {
  3989. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  3990. }
  3991. }
  3992. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  3993. }
  3994. }
  3995. else if (type == 3)
  3996. {
  3997. //机票
  3998. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  3999. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  4000. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  4001. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  4002. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  4003. .ToListAsync();
  4004. if (airTicketInfos.Count > 0)
  4005. {
  4006. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  4007. foreach (var item in airTicketInfos)
  4008. {
  4009. var ticketClass = new
  4010. {
  4011. TiketClass = item.AirType,
  4012. Number = item.ClientNum
  4013. };
  4014. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  4015. {
  4016. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  4017. if (airTicketRegion != null)
  4018. {
  4019. airTicketRegions.Remove(airTicketRegion);
  4020. if (airTicketRegion.Data.Count > 0)
  4021. {
  4022. airTicketRegion.Data.Add(ticketClass);
  4023. }
  4024. airTicketRegion.Number += item.ClientNum;
  4025. airTicketRegions.Add(airTicketRegion);
  4026. }
  4027. }
  4028. else
  4029. {
  4030. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  4031. }
  4032. }
  4033. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  4034. }
  4035. }
  4036. else if (type == 4)
  4037. {
  4038. //车辆
  4039. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4040. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  4041. if (opInfos.Count > 0)
  4042. {
  4043. List<RegionInfo> opRegions = new List<RegionInfo>();
  4044. foreach (var item in opInfos)
  4045. {
  4046. int carNum = 0;
  4047. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  4048. if (opContentInfo.Count > 0)
  4049. {
  4050. foreach (var item1 in opContentInfo)
  4051. {
  4052. if (item1.Price > 0 && item1.Count > 0)
  4053. {
  4054. carNum += item1.Count;
  4055. }
  4056. }
  4057. }
  4058. if (carNum > 0)
  4059. {
  4060. var opData = new
  4061. {
  4062. ServiceCompany = item.ServiceCompany,
  4063. BusName = item.BusName,
  4064. Numbuer = carNum
  4065. };
  4066. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  4067. {
  4068. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  4069. if (opRegion != null)
  4070. {
  4071. opRegions.Remove(opRegion);
  4072. if (opRegion.Data.Count > 0)
  4073. {
  4074. opRegion.Data.Add(opData);
  4075. }
  4076. opRegion.Number += carNum;
  4077. opRegions.Add(opRegion);
  4078. }
  4079. }
  4080. else
  4081. {
  4082. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  4083. }
  4084. }
  4085. }
  4086. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  4087. }
  4088. }
  4089. #endregion
  4090. _view.TypeItem = _types;
  4091. return _view;
  4092. }
  4093. #endregion
  4094. #region 市场部销售额
  4095. /// <summary>
  4096. /// 市场部销售额
  4097. /// Init 基础数据(公司/人员/年份/季度/月份)
  4098. /// </summary>
  4099. /// <param name="_dto">市场部销售额请求dto</param>
  4100. /// <returns></returns>
  4101. [HttpPost("PostMarketingSalesInitData")]
  4102. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4103. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  4104. {
  4105. #region 参数验证
  4106. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  4107. var validResult = await validationRules.ValidateAsync(_dto);
  4108. if (!validResult.IsValid)
  4109. {
  4110. var errors = new StringBuilder();
  4111. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4112. return Ok(JsonView(false, errors.ToString()));
  4113. }
  4114. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4115. #region 页面操作权限验证
  4116. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4117. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4118. #endregion
  4119. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  4120. .Select(it => new { id = it.Id, name = it.CompanyName })
  4121. .ToList();
  4122. List<int> companyIds = companyData.Select(it => it.id).ToList();
  4123. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  4124. .Select(it => it.JietuanOperator)
  4125. .ToList();
  4126. var userData = _sqlSugar.Queryable<Sys_Users>()
  4127. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  4128. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  4129. .ToList();
  4130. companyData.Insert(0, new { id = -1, name = "全部" });
  4131. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  4132. #region 年份
  4133. var dtData = new List<dynamic>();
  4134. int dt = DateTime.Now.Year;
  4135. for (int y = dt; y >= dt - 4; y--)
  4136. {
  4137. //季度
  4138. var quarterDatas = new List<dynamic>();
  4139. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  4140. for (int q = 0; q < 4; q++)
  4141. {
  4142. dynamic quarterData = null;
  4143. if (q == 0)
  4144. {
  4145. var monthDatas = new List<dynamic>();
  4146. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  4147. for (int m = 1; m < 4; m++)
  4148. {
  4149. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4150. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4151. }
  4152. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  4153. quarterData = new { name = "第一季度", monthData = monthDatas };
  4154. }
  4155. else if (q == 1)
  4156. {
  4157. var monthDatas = new List<dynamic>();
  4158. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  4159. for (int m = 4; m < 7; m++)
  4160. {
  4161. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4162. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4163. }
  4164. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  4165. quarterData = new { name = "第二季度", monthData = monthDatas };
  4166. }
  4167. else if (q == 2)
  4168. {
  4169. var monthDatas = new List<dynamic>();
  4170. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  4171. for (int m = 7; m < 10; m++)
  4172. {
  4173. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4174. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4175. }
  4176. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  4177. quarterData = new { name = "第三季度", monthData = monthDatas };
  4178. }
  4179. else if (q == 3)
  4180. {
  4181. var monthDatas = new List<dynamic>();
  4182. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  4183. for (int m = 10; m < 13; m++)
  4184. {
  4185. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  4186. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  4187. }
  4188. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  4189. quarterData = new { name = "第四季度", monthData = monthDatas };
  4190. }
  4191. quarterDatas.Add(quarterData);
  4192. }
  4193. dtData.Add(new
  4194. {
  4195. year = y,
  4196. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  4197. quarterData = quarterDatas,
  4198. });
  4199. }
  4200. #endregion
  4201. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  4202. #endregion
  4203. }
  4204. private static string ConvertToChinese(int month)
  4205. {
  4206. if (month < 1 || month > 12)
  4207. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  4208. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  4209. var dateTimeFormat = cultureInfo.DateTimeFormat;
  4210. return dateTimeFormat.GetMonthName(month);
  4211. }
  4212. /// <summary>
  4213. /// 市场部销售额
  4214. /// 年度/季度/月度 报表(同比)
  4215. /// </summary>
  4216. /// <param name="_dto">市场部销售额请求dto</param>
  4217. /// <returns></returns>
  4218. [HttpPost("PostMarketingSalesStatistics")]
  4219. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4220. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  4221. {
  4222. #region 参数验证
  4223. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4224. var validResult = await validationRules.ValidateAsync(_dto);
  4225. if (!validResult.IsValid)
  4226. {
  4227. var errors = new StringBuilder();
  4228. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4229. return Ok(JsonView(false, errors.ToString()));
  4230. }
  4231. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4232. #region 页面操作权限验证
  4233. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4234. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4235. #endregion
  4236. #endregion
  4237. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4238. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  4239. }
  4240. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  4241. {
  4242. //全部人员Id
  4243. //查询所有公司的市场部
  4244. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  4245. var userIds = new List<int>();
  4246. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  4247. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  4248. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  4249. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  4250. .ToListAsync();
  4251. userIds = userDatas.Select(it => it.Id).ToList();
  4252. if (companyId > 0)
  4253. {
  4254. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  4255. }
  4256. if (groupPickupUserId > 0)
  4257. {
  4258. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  4259. }
  4260. return userIds;
  4261. }
  4262. /// <summary>
  4263. /// 计算团组销售额
  4264. /// </summary>
  4265. /// <param name="companyId"></param>
  4266. /// <param name="groupPickupUserId"></param>
  4267. /// <param name="beginDt"></param>
  4268. /// <param name="endDt"></param>
  4269. /// <returns></returns>
  4270. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  4271. {
  4272. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  4273. var _view = new SalesYOYView();
  4274. List<int> userIds = new List<int>();
  4275. userIds = await GetUserIds(companyId, groupPickupUserId);
  4276. string userSqlWhere = "";
  4277. if (userIds.Count > 0)
  4278. {
  4279. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  4280. }
  4281. else
  4282. {
  4283. _view = new SalesYOYView
  4284. {
  4285. thisYearSales = "0.00",
  4286. lastYearSales = "0.00",
  4287. };
  4288. return _view;
  4289. }
  4290. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  4291. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  4292. // string salesSql = string.Format(@"
  4293. //SELECT
  4294. // 'ThisSales' As [Name],
  4295. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4296. //FROM
  4297. // (
  4298. // SELECT di.VisitDate,
  4299. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4300. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4301. // ) AS Sales
  4302. // FROM
  4303. // Grp_DelegationInfo di
  4304. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4305. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4306. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4307. // ) temp
  4308. //Union ALL
  4309. //SELECT
  4310. // 'LastSales' As [Name],
  4311. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4312. //FROM
  4313. // (
  4314. // SELECT di.VisitDate,
  4315. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4316. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4317. // ) AS Sales
  4318. // FROM
  4319. // Grp_DelegationInfo di
  4320. // WHERE di.IsDel = 0 AND di.IsSure = 1
  4321. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4322. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4323. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4324. string salesSql = string.Format(@"
  4325. SELECT
  4326. 'ThisSales' As [Name],
  4327. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4328. FROM
  4329. (
  4330. SELECT di.VisitDate,
  4331. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4332. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4333. ) AS Sales
  4334. FROM
  4335. Grp_DelegationInfo di
  4336. WHERE di.IsDel = 0
  4337. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  4338. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  4339. ) temp
  4340. Union ALL
  4341. SELECT
  4342. 'LastSales' As [Name],
  4343. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  4344. FROM
  4345. (
  4346. SELECT di.VisitDate,
  4347. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  4348. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  4349. ) AS Sales
  4350. FROM
  4351. Grp_DelegationInfo di
  4352. WHERE di.IsDel = 0
  4353. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  4354. AND di.IsBid = 0
  4355. AND di.TeamName Not Like '%投标%'
  4356. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  4357. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  4358. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  4359. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  4360. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  4361. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  4362. return new SalesYOYView()
  4363. {
  4364. thisYearSales = thisSales.ToString("#0.00"),
  4365. lastYearSales = lastSales.ToString("#0.00"),
  4366. yoy = yoy.ToString("#0.00")
  4367. };
  4368. }
  4369. private class SalesView
  4370. {
  4371. public string Name { get; set; }
  4372. public decimal Sales { get; set; }
  4373. }
  4374. private class SalesYOYView
  4375. {
  4376. public string thisYearSales { get; set; }
  4377. public string lastYearSales { get; set; }
  4378. public string yoy { get; set; } = "1.00";
  4379. }
  4380. /// <summary>
  4381. /// 市场部销售额
  4382. /// 团组列表
  4383. /// </summary>
  4384. /// <param name="_dto">市场部销售额请求dto</param>
  4385. /// <returns></returns>
  4386. [HttpPost("PostMarketingSalesGroupList")]
  4387. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4388. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  4389. {
  4390. #region 参数验证
  4391. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4392. var validResult = await validationRules.ValidateAsync(_dto);
  4393. if (!validResult.IsValid)
  4394. {
  4395. var errors = new StringBuilder();
  4396. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4397. return Ok(JsonView(false, errors.ToString()));
  4398. }
  4399. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4400. #region 页面操作权限验证
  4401. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4402. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4403. #endregion
  4404. #endregion
  4405. string userSql = "";
  4406. List<int> userIds = new List<int>();
  4407. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4408. if (userIds.Count <= 0)
  4409. {
  4410. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4411. }
  4412. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4413. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4414. {
  4415. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4416. }
  4417. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4418. // string sql = string.Format(@$"SELECT
  4419. // ROW_NUMBER() OVER (
  4420. // ORDER BY
  4421. // CollectionDays
  4422. // ) AS RowNumber,
  4423. // *
  4424. //FROM
  4425. // (
  4426. // SELECT
  4427. // di.Id,
  4428. // di.TeamName,
  4429. // di.ClientUnit,
  4430. // di.ClientName,
  4431. // di.VisitDate,
  4432. // di.VisitPNumber,
  4433. // di.JietuanOperator,
  4434. // di.VisitEndDate,
  4435. // (
  4436. // SELECT
  4437. // CAST(
  4438. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4439. // ) AS GroupSales
  4440. // FROM
  4441. // Fin_ForeignReceivables
  4442. // WHERE
  4443. // IsDel = 0
  4444. // AND di.Id = Diid
  4445. // AND AddingWay IN (0, 1, 2)
  4446. // ) AS GroupSales,
  4447. // u.CnName AS GroupPickupUser,
  4448. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4449. // FROM
  4450. // Grp_DelegationInfo di
  4451. // WITH
  4452. // (NoLock)
  4453. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4454. // WHERE
  4455. // di.Isdel = 0
  4456. // AND di.IsSure = 1 {userSql}
  4457. // AND VisitDate Between '{beginDt}' And '{endDt}'
  4458. // ) Temp ");
  4459. string sql = string.Format(@$"SELECT
  4460. ROW_NUMBER() OVER (
  4461. ORDER BY
  4462. CollectionDays
  4463. ) AS RowNumber,
  4464. *
  4465. FROM
  4466. (
  4467. SELECT
  4468. di.Id,
  4469. di.TeamName,
  4470. di.ClientUnit,
  4471. di.ClientName,
  4472. di.VisitDate,
  4473. di.VisitPNumber,
  4474. di.JietuanOperator,
  4475. di.VisitEndDate,
  4476. (
  4477. SELECT
  4478. CAST(
  4479. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4480. ) AS GroupSales
  4481. FROM
  4482. Fin_ForeignReceivables
  4483. WHERE
  4484. IsDel = 0
  4485. AND di.Id = Diid
  4486. AND AddingWay IN (0, 1, 2)
  4487. ) AS GroupSales,
  4488. u.CnName AS GroupPickupUser,
  4489. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4490. FROM
  4491. Grp_DelegationInfo di
  4492. WITH
  4493. (NoLock)
  4494. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4495. WHERE
  4496. di.Isdel = 0
  4497. AND (
  4498. SELECT
  4499. CAST(
  4500. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4501. ) AS GroupSales
  4502. FROM
  4503. Fin_ForeignReceivables
  4504. WHERE
  4505. IsDel = 0
  4506. AND di.Id = Diid
  4507. AND AddingWay IN (0, 1, 2)
  4508. ) > 0
  4509. {userSql}
  4510. AND di.IsBid = 0
  4511. AND di.TeamName Not Like '%投标%'
  4512. AND VisitDate Between '{beginDt}' And '{endDt}'
  4513. ) Temp ");
  4514. RefAsync<int> total = 0;
  4515. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4516. return Ok(JsonView(true, "操作成功!", groupData, total));
  4517. }
  4518. /// <summary>
  4519. /// 市场部销售额
  4520. /// 团组列表Excel下载
  4521. /// </summary>
  4522. /// <param name="_dto">市场部销售额请求dto</param>
  4523. /// <returns></returns>
  4524. [HttpPost("PostMarketingSalesGroupExcel")]
  4525. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4526. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  4527. {
  4528. #region 参数验证
  4529. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4530. var validResult = await validationRules.ValidateAsync(_dto);
  4531. if (!validResult.IsValid)
  4532. {
  4533. var errors = new StringBuilder();
  4534. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4535. return Ok(JsonView(false, errors.ToString()));
  4536. }
  4537. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4538. #region 页面操作权限验证
  4539. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4540. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4541. #endregion
  4542. #endregion
  4543. string userSql = "";
  4544. var userIds = new List<int>();
  4545. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4546. if (userIds.Count <= 0)
  4547. {
  4548. return Ok(JsonView(false));
  4549. }
  4550. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4551. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4552. {
  4553. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4554. }
  4555. string beginDt = $"{_dto.BeginDt} 00:00:00",
  4556. endDt = $"{_dto.EndDt} 23:59:59";
  4557. string sql = string.Format(@$"SELECT
  4558. ROW_NUMBER() OVER (
  4559. ORDER BY
  4560. CollectionDays
  4561. ) AS RowNumber,
  4562. *
  4563. FROM
  4564. (
  4565. SELECT
  4566. di.Id,
  4567. di.TeamName,
  4568. di.ClientUnit,
  4569. di.ClientName,
  4570. di.VisitDate,
  4571. di.VisitPNumber,
  4572. di.JietuanOperator,
  4573. di.VisitEndDate,
  4574. (
  4575. SELECT
  4576. CAST(
  4577. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4578. ) AS GroupSales
  4579. FROM
  4580. Fin_ForeignReceivables
  4581. WHERE
  4582. IsDel = 0
  4583. AND di.Id = Diid
  4584. AND AddingWay IN (0, 1, 2)
  4585. ) AS GroupSales,
  4586. u.CnName AS GroupPickupUser,
  4587. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4588. FROM
  4589. Grp_DelegationInfo di
  4590. WITH
  4591. (NoLock)
  4592. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4593. WHERE
  4594. di.Isdel = 0
  4595. AND (
  4596. SELECT
  4597. CAST(
  4598. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4599. ) AS GroupSales
  4600. FROM
  4601. Fin_ForeignReceivables
  4602. WHERE
  4603. IsDel = 0
  4604. AND di.Id = Diid
  4605. AND AddingWay IN (0, 1, 2)
  4606. ) > 0
  4607. {userSql}
  4608. AND di.IsBid = 0
  4609. AND di.TeamName Not Like '%投标%'
  4610. AND VisitDate Between '{beginDt}' And '{endDt}'
  4611. ) Temp ");
  4612. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  4613. if (view.Count < 1) return Ok(JsonView(false, "暂无数据!"));
  4614. //DataTable dt = GeneralMethod.
  4615. DataTable dt = CommonFun.GetDataTableFromIList(view);
  4616. dt.TableName = $"_view";
  4617. WorkbookDesigner designer = new WorkbookDesigner();
  4618. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  4619. designer.SetDataSource(dt);
  4620. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  4621. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  4622. designer.Process();
  4623. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  4624. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  4625. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  4626. return Ok(JsonView(true, "操作成功", new { url = rst }));
  4627. }
  4628. /// <summary>
  4629. /// 市场部销售额
  4630. /// 客户类型、客户等级 统计
  4631. /// </summary>
  4632. /// <param name="_dto">市场部销售额请求dto</param>
  4633. /// <returns></returns>
  4634. [HttpPost("PostMarketingSalesGroupStatistics")]
  4635. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4636. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  4637. {
  4638. #region 参数验证
  4639. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4640. var validResult = await validationRules.ValidateAsync(_dto);
  4641. if (!validResult.IsValid)
  4642. {
  4643. var errors = new StringBuilder();
  4644. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4645. return Ok(JsonView(false, errors.ToString()));
  4646. }
  4647. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4648. #region 页面操作权限验证
  4649. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4650. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4651. #endregion
  4652. #endregion
  4653. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4654. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4655. string userSql = "";
  4656. if (userIds.Count > 0)
  4657. {
  4658. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4659. }
  4660. else
  4661. {
  4662. if (_dto.PortType == 2 || _dto.PortType == 3)
  4663. {
  4664. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  4665. }
  4666. else
  4667. {
  4668. return Ok(JsonView(true, "操作成功!", new
  4669. {
  4670. customerTypeData = new List<object> { },
  4671. clientGradeData = new List<object> { }
  4672. }));
  4673. }
  4674. }
  4675. string sql = "";
  4676. if (_dto.StatisticsType == 1)
  4677. {
  4678. sql = string.Format(@$"Select
  4679. sd.[Name],
  4680. Count(*) As [Count]
  4681. From Grp_DelegationInfo di
  4682. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4683. Where di.Isdel = 0
  4684. And (
  4685. SELECT
  4686. CAST(
  4687. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4688. ) AS GroupSales
  4689. FROM
  4690. Fin_ForeignReceivables fr
  4691. WHERE
  4692. fr.IsDel = 0
  4693. AND di.Id = fr.Diid
  4694. AND AddingWay IN (0, 1, 2)
  4695. ) > 0
  4696. {userSql}
  4697. AND di.IsBid = 0
  4698. AND di.TeamName Not Like '%投标%'
  4699. And VisitDate Between '{beginDt}' And '{endDt}'
  4700. Group By [Name]
  4701. Order By Count Desc");
  4702. }
  4703. else if (_dto.StatisticsType == 2)
  4704. {
  4705. sql = string.Format(@$"Select
  4706. sd.[Name],
  4707. Count(*) As [Count]
  4708. From Grp_DelegationInfo di
  4709. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4710. Where di.Isdel = 0
  4711. And (
  4712. SELECT
  4713. CAST(
  4714. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4715. ) AS GroupSales
  4716. FROM
  4717. Fin_ForeignReceivables fr
  4718. WHERE
  4719. fr.IsDel = 0
  4720. AND di.Id = fr.Diid
  4721. AND AddingWay IN (0, 1, 2)
  4722. ) > 0
  4723. {userSql}
  4724. AND di.IsBid = 0
  4725. AND di.TeamName Not Like '%投标%'
  4726. And VisitDate Between '{beginDt}' And '{endDt}'
  4727. Group By [Name]
  4728. Order By Count Desc");
  4729. }
  4730. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  4731. if (_dto.PortType == 1)
  4732. {
  4733. string sql1 = string.Format(@$"Select
  4734. sd.[Name],
  4735. Count(*) As [Count]
  4736. From Grp_DelegationInfo di
  4737. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4738. Where di.Isdel = 0
  4739. And (
  4740. SELECT
  4741. CAST(
  4742. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4743. ) AS GroupSales
  4744. FROM
  4745. Fin_ForeignReceivables fr
  4746. WHERE
  4747. fr.IsDel = 0
  4748. AND di.Id = fr.Diid
  4749. AND AddingWay IN (0, 1, 2)
  4750. ) > 0
  4751. {userSql}
  4752. AND di.IsBid = 0
  4753. AND di.TeamName Not Like '%投标%'
  4754. And VisitDate Between '{beginDt}' And '{endDt}'
  4755. Group By [Name]
  4756. Order By Count Desc");
  4757. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4758. string sql2 = string.Format(@$"Select
  4759. sd.[Name],
  4760. Count(*) As [Count]
  4761. From Grp_DelegationInfo di
  4762. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4763. Where di.Isdel = 0
  4764. And (
  4765. SELECT
  4766. CAST(
  4767. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4768. ) AS GroupSales
  4769. FROM
  4770. Fin_ForeignReceivables fr
  4771. WHERE
  4772. fr.IsDel = 0
  4773. AND di.Id = fr.Diid
  4774. AND AddingWay IN (0, 1, 2)
  4775. ) > 0
  4776. {userSql}
  4777. AND di.IsBid = 0
  4778. AND di.TeamName Not Like '%投标%'
  4779. And VisitDate Between '{beginDt}' And '{endDt}'
  4780. Group By [Name]
  4781. Order By Count Desc");
  4782. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  4783. return Ok(JsonView(true, "操作成功!", new
  4784. {
  4785. customerTypeData = customerTypeData,
  4786. clientGradeData = clientGradeData
  4787. }));
  4788. }
  4789. else if (_dto.PortType == 2 || _dto.PortType == 3)
  4790. {
  4791. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  4792. return Ok(JsonView(true, "操作成功!", data, data.Count));
  4793. }
  4794. else return Ok(JsonView(false, MsgTips.Port));
  4795. }
  4796. /// <summary>
  4797. /// 市场部销售额
  4798. /// 接单排名
  4799. /// </summary>
  4800. /// <param name="_dto">市场部销售额请求dto</param>
  4801. /// <returns></returns>
  4802. [HttpPost("PostMarketingSalesOrderRanking")]
  4803. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4804. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  4805. {
  4806. #region 参数验证
  4807. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4808. var validResult = await validationRules.ValidateAsync(_dto);
  4809. if (!validResult.IsValid)
  4810. {
  4811. var errors = new StringBuilder();
  4812. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4813. return Ok(JsonView(false, errors.ToString()));
  4814. }
  4815. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4816. #region 页面操作权限验证
  4817. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4818. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4819. #endregion
  4820. #endregion
  4821. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4822. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4823. string userSql = "";
  4824. if (userIds.Count > 0)
  4825. {
  4826. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  4827. }
  4828. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4829. string sql = string.Format(@$"Select
  4830. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  4831. u.CnName As UserName,
  4832. Count(*) As [Count]
  4833. From Grp_DelegationInfo di
  4834. Left Join Sys_Users u On di.JietuanOperator = u.Id
  4835. Where di.Isdel = 0
  4836. AND (
  4837. SELECT
  4838. CAST(
  4839. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4840. ) AS GroupSales
  4841. FROM
  4842. Fin_ForeignReceivables fr
  4843. WHERE
  4844. fr.IsDel = 0
  4845. AND di.Id = fr.Diid
  4846. AND AddingWay IN (0, 1, 2)
  4847. ) > 0
  4848. {userSql}
  4849. AND di.IsBid = 0
  4850. AND di.TeamName Not Like '%投标%'
  4851. AND VisitDate Between '{beginDt}' AND '{endDt}'
  4852. Group By CnName");
  4853. RefAsync<int> total = 0;
  4854. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4855. return Ok(JsonView(true, "操作成功!", rankingData, total));
  4856. }
  4857. /// <summary>
  4858. /// 市场部销售额
  4859. /// 团组列表、客户类型、客户等级、接单排名
  4860. /// </summary>
  4861. /// <param name="_dto">市场部销售额请求dto</param>
  4862. /// <returns></returns>
  4863. [HttpPost("PostMarketingSalesGroupItem")]
  4864. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4865. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  4866. {
  4867. #region 参数验证
  4868. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  4869. var validResult = await validationRules.ValidateAsync(_dto);
  4870. if (!validResult.IsValid)
  4871. {
  4872. var errors = new StringBuilder();
  4873. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  4874. return Ok(JsonView(false, errors.ToString()));
  4875. }
  4876. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  4877. #region 页面操作权限验证
  4878. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  4879. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  4880. #endregion
  4881. #endregion
  4882. string userSql = "";
  4883. List<int> userIds = new List<int>();
  4884. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  4885. if (userIds.Count <= 0)
  4886. {
  4887. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  4888. }
  4889. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  4890. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  4891. {
  4892. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  4893. }
  4894. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  4895. #region 团组List
  4896. string sql = string.Format(@$"SELECT
  4897. ROW_NUMBER() OVER (
  4898. ORDER BY
  4899. CollectionDays
  4900. ) AS RowNumber,
  4901. *
  4902. FROM
  4903. (
  4904. SELECT
  4905. di.Id,
  4906. di.TeamName,
  4907. di.ClientUnit,
  4908. di.ClientName,
  4909. di.VisitDate,
  4910. di.VisitPNumber,
  4911. di.JietuanOperator,
  4912. di.VisitEndDate,
  4913. (
  4914. SELECT
  4915. CAST(
  4916. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4917. ) AS GroupSales
  4918. FROM
  4919. Fin_ForeignReceivables
  4920. WHERE
  4921. IsDel = 0
  4922. AND di.Id = Diid
  4923. AND AddingWay IN (0, 1, 2)
  4924. ) AS GroupSales,
  4925. u.CnName AS GroupPickupUser,
  4926. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  4927. FROM
  4928. Grp_DelegationInfo di
  4929. WITH
  4930. (NoLock)
  4931. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  4932. WHERE
  4933. di.Isdel = 0
  4934. AND (
  4935. SELECT
  4936. CAST(
  4937. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4938. ) AS GroupSales
  4939. FROM
  4940. Fin_ForeignReceivables fr
  4941. WHERE
  4942. fr.IsDel = 0
  4943. AND di.Id = fr.Diid
  4944. AND AddingWay IN (0, 1, 2)
  4945. ) > 0
  4946. {userSql}
  4947. AND di.IsBid = 0
  4948. AND di.TeamName Not Like '%投标%'
  4949. AND VisitDate Between '{beginDt}' And '{endDt}'
  4950. ) Temp ");
  4951. RefAsync<int> total = 0;
  4952. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  4953. #endregion
  4954. #region 客户类型、客户等级 统计
  4955. string sql1 = string.Format(@$"Select
  4956. sd.[Name],
  4957. Count(*) As [Count]
  4958. From Grp_DelegationInfo di
  4959. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  4960. Where di.Isdel = 0
  4961. And (
  4962. SELECT
  4963. CAST(
  4964. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4965. ) AS GroupSales
  4966. FROM
  4967. Fin_ForeignReceivables fr
  4968. WHERE
  4969. fr.IsDel = 0
  4970. AND di.Id = fr.Diid
  4971. AND AddingWay IN (0, 1, 2)
  4972. ) > 0
  4973. {userSql}
  4974. AND di.IsBid = 0
  4975. AND di.TeamName Not Like '%投标%'
  4976. And VisitDate Between '{beginDt}' And '{endDt}'
  4977. Group By [Name]
  4978. Order By Count Desc");
  4979. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  4980. string sql2 = string.Format(@$"Select
  4981. sd.[Name],
  4982. Count(*) As [Count]
  4983. From Grp_DelegationInfo di
  4984. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  4985. Where di.Isdel = 0
  4986. And (
  4987. SELECT
  4988. CAST(
  4989. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  4990. ) AS GroupSales
  4991. FROM
  4992. Fin_ForeignReceivables fr
  4993. WHERE
  4994. fr.IsDel = 0
  4995. AND di.Id = fr.Diid
  4996. AND AddingWay IN (0, 1, 2)
  4997. ) > 0
  4998. {userSql}
  4999. AND di.IsBid = 0
  5000. AND di.TeamName Not Like '%投标%'
  5001. And VisitDate Between '{beginDt}' And '{endDt}'
  5002. Group By [Name]
  5003. Order By Count Desc");
  5004. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  5005. #endregion
  5006. #region 接单排名
  5007. string sql4 = string.Format(@$"Select
  5008. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  5009. u.CnName As UserName,
  5010. Count(*) As [Count]
  5011. From Grp_DelegationInfo di
  5012. Left Join Sys_Users u On di.JietuanOperator = u.Id
  5013. Where di.Isdel = 0
  5014. And (
  5015. SELECT
  5016. CAST(
  5017. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  5018. ) AS GroupSales
  5019. FROM
  5020. Fin_ForeignReceivables fr
  5021. WHERE
  5022. fr.IsDel = 0
  5023. AND di.Id = fr.Diid
  5024. AND AddingWay IN (0, 1, 2)
  5025. ) > 0
  5026. {userSql}
  5027. AND di.IsBid = 0
  5028. AND di.TeamName Not Like '%投标%'
  5029. And VisitDate Between '{beginDt}' And '{endDt}'
  5030. Group By CnName");
  5031. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  5032. #endregion
  5033. var viewData = new
  5034. {
  5035. groupData = groupData,
  5036. groupTotal = total,
  5037. customerTypeData = customerTypeData,
  5038. clientGradeData = clientGradeData,
  5039. rankingData = rankingData
  5040. };
  5041. return Ok(JsonView(true, "操作成功!", viewData, total));
  5042. }
  5043. /// <summary>
  5044. /// 市场部销售额
  5045. /// 客户拜访列表
  5046. /// </summary>
  5047. /// <param name="_dto">市场部销售额请求dto</param>
  5048. /// <returns></returns>
  5049. [HttpPost("PostMarketingSalesVCList")]
  5050. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5051. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  5052. {
  5053. #region 参数验证
  5054. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5055. var validResult = await validationRules.ValidateAsync(_dto);
  5056. if (!validResult.IsValid)
  5057. {
  5058. var errors = new StringBuilder();
  5059. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5060. return Ok(JsonView(false, errors.ToString()));
  5061. }
  5062. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5063. #region 页面操作权限验证
  5064. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5065. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5066. #endregion
  5067. #endregion
  5068. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  5069. }
  5070. /// <summary>
  5071. /// 市场部销售额
  5072. /// 客户拜访 操作(添加 Or 编辑)
  5073. /// </summary>
  5074. /// <param name="_dto">市场部销售额请求dto</param>
  5075. /// <returns></returns>
  5076. [HttpPost("PostMarketingSalesVCOperate")]
  5077. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5078. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  5079. {
  5080. #region 参数验证
  5081. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5082. var validResult = await validationRules.ValidateAsync(_dto);
  5083. if (!validResult.IsValid)
  5084. {
  5085. var errors = new StringBuilder();
  5086. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5087. return Ok(JsonView(false, errors.ToString()));
  5088. }
  5089. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5090. #region 页面操作权限验证
  5091. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5092. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5093. #endregion
  5094. #endregion
  5095. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  5096. }
  5097. /// <summary>
  5098. /// 市场部销售额
  5099. /// 客户拜访 Del
  5100. /// </summary>
  5101. /// <param name="_dto">市场部销售额请求dto</param>
  5102. /// <returns></returns>
  5103. [HttpPost("PostMarketingSalesVCDel")]
  5104. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5105. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  5106. {
  5107. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  5108. }
  5109. /// <summary>
  5110. /// 市场部销售额
  5111. /// 客户拜访 操作 save
  5112. /// </summary>
  5113. /// <param name="_dto">市场部销售额请求dto</param>
  5114. /// <returns></returns>
  5115. [HttpPost("PostMarketingSalesVCSave")]
  5116. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5117. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  5118. {
  5119. #region 参数验证
  5120. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  5121. var validResult = await validationRules.ValidateAsync(_dto);
  5122. if (!validResult.IsValid)
  5123. {
  5124. var errors = new StringBuilder();
  5125. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  5126. return Ok(JsonView(false, errors.ToString()));
  5127. }
  5128. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5129. #region 页面操作权限验证
  5130. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5131. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  5132. #endregion
  5133. #endregion
  5134. return Ok(await _visitingClientsRep._Save(_dto));
  5135. }
  5136. #endregion
  5137. #region 日付报表
  5138. /// <summary>
  5139. /// 日付类型数据
  5140. /// </summary>
  5141. /// <param name="_dto"></param>
  5142. /// <returns></returns>
  5143. [HttpPost("DailypaymentTypeInit")]
  5144. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5145. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  5146. {
  5147. #region 参数验证
  5148. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5149. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5150. #region 页面操作权限验证
  5151. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5152. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5153. #endregion
  5154. #endregion
  5155. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5156. {
  5157. var defaultParentIds = new List<int>()
  5158. {
  5159. 48, // 人员费用
  5160. 49, // 办公费用
  5161. 50, // 销售费用
  5162. 51, // 其他费用
  5163. 55, // 大运会
  5164. 90, // 各部门基础固定费用明细
  5165. 104, // 团组费用
  5166. 116, // 物资采购
  5167. };
  5168. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5169. .CreateRedisRepository()
  5170. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5171. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  5172. .Includes(x => x.SubData)
  5173. .Where(x => defaultParentIds.Contains(x.Id))
  5174. .ToListAsync();
  5175. dailyTypeData.ForEach(x =>
  5176. {
  5177. x.SubData.ForEach(y =>
  5178. {
  5179. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  5180. y.IsChecked = currId != 0;
  5181. });
  5182. });
  5183. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  5184. .Where(x => x.IsDel == 0)
  5185. .Select(x => new { id = x.Id, name = x.CompanyName })
  5186. .ToListAsync();
  5187. return Ok(JsonView(true, "查询成功!", new { dailyTypeData, companyData }));
  5188. }
  5189. else return Ok(JsonView(false, "查询失败"));
  5190. }
  5191. /// <summary>
  5192. /// 日付类型数据 Save
  5193. /// </summary>
  5194. /// <param name="_dto"></param>
  5195. /// <returns></returns>
  5196. [HttpPost("DailypaymentTypeDataSave")]
  5197. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5198. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  5199. {
  5200. #region 参数验证
  5201. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  5202. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5203. #region 页面操作权限验证
  5204. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5205. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5206. #endregion
  5207. #endregion
  5208. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5209. {
  5210. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  5211. var res = await RedisRepository.RedisFactory
  5212. .CreateRedisRepository()
  5213. .StringSetAsync(
  5214. key: "DailypaymentTypeData",
  5215. _dto.TypeIds,
  5216. timeout: null);
  5217. if (!res) return Ok(JsonView(false, "操作失败"));
  5218. return Ok(JsonView(true, "操作成功!"));
  5219. }
  5220. else return Ok(JsonView(false, "操作失败"));
  5221. }
  5222. /// <summary>
  5223. /// 日付数据列表
  5224. /// </summary>
  5225. /// <param name="_dto"></param>
  5226. /// <returns></returns>
  5227. [HttpPost("DailypaymentRange")]
  5228. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5229. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  5230. {
  5231. #region 参数验证
  5232. var validator = new DailypaymentRangeDtoValidator();
  5233. var validationRes = validator.Validate(_dto);
  5234. if (!validationRes.IsValid)
  5235. {
  5236. StringBuilder sb = new StringBuilder();
  5237. foreach (var item in validationRes.Errors)
  5238. {
  5239. sb.AppendLine(item.ErrorMessage);
  5240. }
  5241. return Ok(JsonView(false, sb.ToString()));
  5242. }
  5243. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  5244. #region 页面操作权限验证
  5245. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  5246. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  5247. #endregion
  5248. #endregion
  5249. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  5250. {
  5251. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  5252. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  5253. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  5254. var dailypaymentTypeData = await RedisRepository.RedisFactory
  5255. .CreateRedisRepository()
  5256. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  5257. var sql = string.Format(@"
  5258. Select
  5259. dfp.Id,
  5260. dfp.Instructions,
  5261. dfp.PriceTypeId,
  5262. sd1.Name As FeeType,
  5263. dfp.TransferTypeId,
  5264. sd2.Name As TransferType,
  5265. dfp.SumPrice,
  5266. dfp.FAuditDate,
  5267. dfp.MAuditDate,
  5268. dfp.CompanyId,
  5269. c.CompanyName,
  5270. dfp.CreateUserId As ApplicantId,
  5271. u.CnName As Applicant,
  5272. dfp.CreateTime As ApplicantDt,
  5273. dfp.Instructions+u.CnName As ViewStr
  5274. From Fin_DailyFeePayment dfp
  5275. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  5276. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  5277. Left Join Sys_Company c On dfp.CompanyId = c.Id
  5278. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  5279. Where dfp.IsDel = 0
  5280. -- And dfp.IsPay = 1
  5281. ");//--Order By dfp.CreateTime Desc
  5282. if (_dto.Type == 1) //data
  5283. {
  5284. RefAsync<int> total = 0;
  5285. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  5286. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5287. .WhereIF(dailypaymentTypeData.Count > 0,
  5288. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5289. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5290. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5291. .OrderByDescending(x => x.ApplicantDt)
  5292. .ToPageListAsync(
  5293. pageNumber: _dto.PageIndex,
  5294. pageSize: _dto.PageSize,
  5295. totalNumber: total
  5296. );
  5297. _sqlSugar.ThenMapper(_view, x =>
  5298. {
  5299. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5300. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5301. .Where(x => x.IsDel == 0)
  5302. .ToList();
  5303. });
  5304. //单独处理
  5305. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  5306. }
  5307. else if (_dto.Type == 2) //view
  5308. {
  5309. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  5310. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  5311. .WhereIF(dailypaymentTypeData.Count > 0,
  5312. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  5313. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  5314. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  5315. .OrderByDescending(x => x.ApplicantDt)
  5316. .ToPageListAsync(
  5317. pageNumber: 1,
  5318. pageSize: 99999
  5319. );
  5320. _sqlSugar.ThenMapper(_view, x =>
  5321. {
  5322. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  5323. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  5324. .Where(x => x.IsDel == 0)
  5325. .ToList();
  5326. string str = "";
  5327. int index = 1;
  5328. foreach (var item in x.Contents)
  5329. {
  5330. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  5331. if (index == x.Contents.Count) str += str1;
  5332. else str += str1 + "\r\n";
  5333. index++;
  5334. }
  5335. x.ContentStr = str;
  5336. });
  5337. if (_view.Count > 0)
  5338. {
  5339. //DataTable dt = GeneralMethod.
  5340. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  5341. dt.TableName = $"_view";
  5342. decimal total = _view.Sum(x => x.SumPrice);
  5343. WorkbookDesigner designer = new WorkbookDesigner();
  5344. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  5345. designer.SetDataSource(dt);
  5346. designer.SetDataSource("Total", total);
  5347. designer.Workbook.Worksheets[0].Name = "日付报表";
  5348. designer.Process();
  5349. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  5350. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  5351. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  5352. return Ok(JsonView(true, "操作成功", new { url = rst }));
  5353. }
  5354. return Ok(JsonView(true, ",暂无数据"));
  5355. }
  5356. return Ok(JsonView(false, "操作失败"));
  5357. }
  5358. else return Ok(JsonView(false, "操作失败"));
  5359. }
  5360. #endregion
  5361. #region 统计模块
  5362. /// <summary>
  5363. /// 同比
  5364. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  5365. /// </summary>
  5366. /// <param name="_dto">市场部销售额请求dto</param>
  5367. /// <returns></returns>
  5368. [HttpPost("StatisticsYOY")]
  5369. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5370. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  5371. {
  5372. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  5373. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5374. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  5375. endDt = $"{_dto.Year}-12-31 23:59:59";
  5376. string sql = string.Format(@"
  5377. SELECT
  5378. di.Id,
  5379. di.TeamName,
  5380. di.VisitDate,
  5381. YEAR(di.VisitDate) AS YEAR,
  5382. MONTH(di.VisitDate) AS MONTH,
  5383. (
  5384. SELECT
  5385. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  5386. FROM
  5387. Fin_ForeignReceivables
  5388. WHERE
  5389. IsDel = 0
  5390. AND AddingWay IN (0, 1, 2)
  5391. AND di.Id = Diid
  5392. ) AS SaleAmount,
  5393. (
  5394. SELECT
  5395. CAST(
  5396. SUM(
  5397. (
  5398. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  5399. )
  5400. ) AS DECIMAL(12, 2)
  5401. )
  5402. FROM
  5403. Grp_AirTicketReservations atr
  5404. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5405. AND ccp.CTable = 85
  5406. AND atr.Id = ccp.CId
  5407. WHERE
  5408. atr.IsDel = 0
  5409. AND ccp.IsAuditGM = 1
  5410. AND ccp.IsPay = 1
  5411. AND di.Id = atr.DiId
  5412. ) AirTicketAmount,
  5413. (
  5414. SELECT
  5415. CAST(
  5416. SUM(
  5417. (
  5418. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5419. )
  5420. ) AS DECIMAL(12, 2)
  5421. )
  5422. FROM
  5423. Grp_CarTouristGuideGroundReservations ctggr
  5424. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5425. AND ccp.CTable = 79
  5426. AND ctggr.Id = ccp.CId
  5427. WHERE
  5428. ctggr.IsDel = 0
  5429. AND ccp.IsAuditGM = 1
  5430. AND ccp.IsPay = 1
  5431. AND di.Id = ctggr.DiId
  5432. ) AS OPAmount,
  5433. (
  5434. SELECT
  5435. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5436. FROM
  5437. Grp_DecreasePayments dp
  5438. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5439. AND ccp.CTable = 98
  5440. AND dp.Id = ccp.CId
  5441. WHERE
  5442. dp.IsDel = 0
  5443. AND ccp.Ctable = 98
  5444. AND ccp.IsAuditGM = 1
  5445. AND ccp.IsPay = 1
  5446. AND di.Id = dp.Diid
  5447. ) AS OtherCostAmount,
  5448. (
  5449. SELECT
  5450. CAST(
  5451. SUM(
  5452. (
  5453. (ccp.PayMoney * ccp.DayRate)
  5454. )
  5455. ) AS DECIMAL(12, 2)
  5456. )
  5457. FROM
  5458. Grp_VisaInfo vi
  5459. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5460. AND ccp.CTable = 80
  5461. AND vi.Id = ccp.CId
  5462. WHERE
  5463. vi.IsDel = 0
  5464. AND ccp.IsAuditGM = 1
  5465. AND ccp.IsPay = 1
  5466. AND di.Id = vi.DIId
  5467. ) AS VisaAmount,
  5468. (
  5469. SELECT
  5470. CAST(
  5471. SUM(
  5472. (ccp.PayMoney * ccp.DayRate)
  5473. ) AS DECIMAL(12, 2)
  5474. )
  5475. FROM
  5476. Grp_InvitationOfficialActivities ioa
  5477. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5478. AND ccp.CTable = 81
  5479. AND ioa.Id = ccp.CId
  5480. WHERE
  5481. ioa.IsDel = 0
  5482. AND ccp.IsAuditGM = 1
  5483. AND ccp.IsPay = 1
  5484. AND di.Id = ioa.Diid
  5485. ) AS OAAmount,
  5486. (
  5487. SELECT
  5488. CAST(
  5489. SUM(
  5490. (ccp.PayMoney * ccp.DayRate)
  5491. ) AS DECIMAL(12, 2)
  5492. )
  5493. FROM
  5494. Grp_Customers ic
  5495. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5496. AND ccp.CTable = 82
  5497. AND ic.Id = ccp.CId
  5498. WHERE
  5499. ic.IsDel = 0
  5500. AND ccp.IsAuditGM = 1
  5501. AND ccp.IsPay = 1
  5502. AND di.Id = ic.DiId
  5503. ) AS InsureAmount,
  5504. (
  5505. SELECT
  5506. CAST(
  5507. SUM(
  5508. (ccp.PayMoney * ccp.DayRate)
  5509. ) AS DECIMAL(12, 2)
  5510. )
  5511. FROM
  5512. Grp_HotelReservations hr
  5513. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5514. WHERE
  5515. hr.IsDel = 0
  5516. AND ccp.IsDel = 0
  5517. AND ccp.CTable = 76
  5518. AND ccp.IsAuditGM = 1
  5519. AND ccp.PayMoney <> 0
  5520. AND ccp.IsPay = 1
  5521. AND di.Id = hr.DiId
  5522. ) AS HotelAmount,
  5523. (
  5524. SELECT
  5525. CAST(
  5526. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  5527. )
  5528. FROM
  5529. OA2023DB.dbo.Fin_GroupExtraCost gec
  5530. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  5531. WHERE
  5532. ccp.IsDel = 0
  5533. AND ccp.CTable = 1015
  5534. AND ccp.IsAuditGM = 1
  5535. AND ccp.IsPay = 1
  5536. AND di.Id = gec.DiId
  5537. ) AS ExcessAmount,
  5538. (
  5539. SELECT
  5540. CAST(
  5541. SUM(
  5542. (ccp.PayMoney * ccp.DayRate)
  5543. ) AS DECIMAL(12, 2)
  5544. )
  5545. FROM
  5546. Fin_PaymentRefundAndOtherMoney prom
  5547. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  5548. AND prom.Id = ccp.CId
  5549. WHERE
  5550. prom.IsDel = 0
  5551. AND prom.PayType = 1
  5552. AND ccp.CTable = 285
  5553. AND ccp.IsAuditGM = 1
  5554. AND ccp.IsPay = 1
  5555. AND di.Id = prom.DiId
  5556. ) AS SKTHAmount
  5557. FROM
  5558. Grp_DelegationInfo di
  5559. WHERE
  5560. di.IsDel = 0
  5561. AND di.TeamDid IN (38,39,40,1048)
  5562. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5563. ORDER BY
  5564. di.VisitDate
  5565. ", beginDt, endDt);
  5566. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  5567. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  5568. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  5569. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  5570. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  5571. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  5572. int monthIndex = 1;
  5573. while (monthIndex < 13)
  5574. {
  5575. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  5576. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  5577. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  5578. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  5579. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5580. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  5581. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5582. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  5583. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  5584. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  5585. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  5586. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  5587. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  5588. monthIndex++;
  5589. }
  5590. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  5591. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  5592. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  5593. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  5594. }
  5595. /// <summary>
  5596. /// 国交数据统计-机票相关
  5597. /// 机票票数、机票到达地、预订平台
  5598. /// </summary>
  5599. /// <param name="_dto"></param>
  5600. /// <returns></returns>
  5601. [HttpPost("StatisticsAirTicket")]
  5602. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5603. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  5604. {
  5605. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5606. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5607. endDt = $"{_dto.Year}-12-31 23:59:59";
  5608. string sql = string.Format(@"
  5609. SELECT
  5610. atr.DIId,
  5611. atr.FlightsDate,
  5612. YEAR(atr.FlightsDate) AS YEAR,
  5613. MONTH(atr.FlightsDate) AS MONTH,
  5614. atr.CType,
  5615. sd.Name As CTypeName,
  5616. atr.FlightsCity,
  5617. atr.ClientNum,
  5618. atr.ClientName,
  5619. di.TeamName As 'GroupName',
  5620. CASE
  5621. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  5622. ELSE ccp.Payee
  5623. END AS 'Platform'
  5624. FROM
  5625. Grp_AirTicketReservations atr
  5626. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  5627. AND ccp.IsDel = 0
  5628. AND CTable = 85
  5629. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  5630. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  5631. WHERE
  5632. atr.IsDel = 0
  5633. AND di.TeamDid IN (38,39,40,1048)
  5634. AND atr.CType IN(457,458,459,460,574,575)
  5635. AND CHARINDEX('行程单',atr.ClientName) = 0
  5636. AND CHARINDEX('返点',atr.ClientName) = 0
  5637. AND CHARINDEX('-1',atr.ClientName) = 0
  5638. AND ccp.IsPay = 1
  5639. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  5640. ORDER BY atr.FlightsDate
  5641. ", beginDt, endDt);
  5642. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  5643. var groupIds = data.Select(x => x.DIId).ToList();
  5644. //处理城市数据
  5645. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5646. //处理团组名称
  5647. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  5648. data.ForEach(x =>
  5649. {
  5650. string cityName = "";
  5651. if (!string.IsNullOrEmpty(x.FlightsCity))
  5652. {
  5653. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  5654. int cityNum = cityCode.Length / 3;
  5655. if (cityCode.Length % 3 == 0)
  5656. {
  5657. for (int i = 0; i < cityNum; i++)
  5658. {
  5659. string code = "";
  5660. if (i == 0) code = cityCode.Substring(0, 3);
  5661. else code = cityCode.Substring(i * 3, 3);
  5662. if (!string.IsNullOrEmpty(code))
  5663. {
  5664. if (i == cityNum - 1)
  5665. {
  5666. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5667. }
  5668. else
  5669. {
  5670. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  5671. cityName += str1 + "、";
  5672. }
  5673. }
  5674. }
  5675. }
  5676. }
  5677. x.FlightsCityName = cityName;
  5678. });
  5679. var airTicketNumData = new List<AirTicketReturnView>();
  5680. var airTicketAreaData = new List<AirTicketCityReturnView>();
  5681. int monthIndex = 1;
  5682. while (monthIndex < 13)
  5683. {
  5684. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  5685. //机票票数处理
  5686. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  5687. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  5688. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  5689. foreach (var item in monthData)
  5690. {
  5691. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  5692. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  5693. }
  5694. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  5695. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  5696. foreach (var item in aitTicketInfosGroupBy)
  5697. {
  5698. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  5699. }
  5700. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  5701. linkGroupIds = linkGroupIds.Distinct().ToList();
  5702. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  5703. //机票城市处理
  5704. //城市处理
  5705. var airTicketCityInfos = new List<string>();
  5706. foreach (var item in monthData)
  5707. {
  5708. if (!string.IsNullOrEmpty(item.FlightsCityName))
  5709. {
  5710. if (item.FlightsCityName.Contains("、"))
  5711. {
  5712. var cityArray = item.FlightsCityName.Split("、").ToList();
  5713. foreach (var item1 in cityArray)
  5714. {
  5715. if (!string.IsNullOrEmpty(item1))
  5716. {
  5717. airTicketCityInfos.Add(item1);
  5718. }
  5719. }
  5720. }
  5721. else
  5722. {
  5723. airTicketCityInfos.Add(item.FlightsCityName);
  5724. }
  5725. }
  5726. }
  5727. //int quantity1 = airTicketCityInfos.Count;
  5728. int city_totalquantity = 0;
  5729. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  5730. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  5731. foreach (var item in airTicketCityInfosGroupby)
  5732. {
  5733. var city_quantity = item.ToList().Count;
  5734. city_totalquantity += city_quantity;
  5735. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  5736. }
  5737. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  5738. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  5739. monthIndex++;
  5740. }
  5741. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  5742. .Select(g => new
  5743. {
  5744. platform = g.Key,
  5745. total = g.Sum(x => x.ClientNum),
  5746. children = g.GroupBy(g1 => g1.DIId)
  5747. .Select(g1 => new
  5748. {
  5749. diId = g1.Key,
  5750. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  5751. total = g1.Sum(x1 => x1.ClientNum),
  5752. children = g1.Select(x1 => new
  5753. {
  5754. //diId = x1.DIId,
  5755. //groupName = x1.GroupName,
  5756. flightsCityName = x1.FlightsCityName,
  5757. total = x1.ClientNum
  5758. })
  5759. .ToList()
  5760. })
  5761. .OrderByDescending(x1 => x1.total)
  5762. .ToList()
  5763. })
  5764. .OrderByDescending(x => x.total)
  5765. .ToList();
  5766. return Ok(JsonView(true, "操作成功!", new
  5767. {
  5768. airTicketNumData = airTicketNumData,
  5769. airTicketAreaData = airTicketAreaData,
  5770. airTicketPlatformData = airTicketPlatformData
  5771. }));
  5772. }
  5773. /// <summary>
  5774. /// 国交数据统计-酒店
  5775. /// 国家TOP10、地区TOP10、预订平台
  5776. /// </summary>
  5777. /// <param name="_dto"></param>
  5778. /// <returns></returns>
  5779. [HttpPost("StatisticsHotel")]
  5780. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5781. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  5782. {
  5783. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5784. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5785. endDt = $"{_dto.Year}-12-31 23:59:59";
  5786. string sql = string.Format(@"
  5787. SELECT
  5788. hr.DIId,
  5789. CASE
  5790. WHEN ntf.Country IS NULL THEN '未选择'
  5791. ELSE ntf.Country
  5792. END AS 'Country',
  5793. hr.City,
  5794. hr.HotelName,
  5795. sd.Name AS BookinSite,
  5796. hr.CheckInDate,
  5797. YEAR(hr.CheckInDate) AS YEAR,
  5798. MONTH(hr.CheckInDate) AS MONTH,
  5799. hr.CheckOutDate,
  5800. hr.SingleRoomCount,
  5801. hr.DoubleRoomCount,
  5802. hr.SuiteRoomCount,
  5803. hr.OtherRoomCount
  5804. FROM
  5805. Grp_HotelReservations hr
  5806. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5807. AND ccp.IsDel = 0
  5808. AND CTable = 76
  5809. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  5810. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  5811. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  5812. WHERE
  5813. hr.IsDel = 0
  5814. AND di.TeamDid IN (38,39,40,1048)
  5815. AND ccp.IsPay = 1
  5816. AND (
  5817. hr.SingleRoomCount > 0
  5818. OR hr.DoubleRoomCount > 0
  5819. OR hr.SuiteRoomCount > 0
  5820. OR hr.OtherRoomCount > 0
  5821. )
  5822. AND CHARINDEX('早餐',hr.HotelName) = 0
  5823. AND CHARINDEX('晚餐',hr.HotelName) = 0
  5824. AND CHARINDEX('升级',hr.HotelName) = 0
  5825. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  5826. AND CHARINDEX('城市税',hr.HotelName) = 0
  5827. AND CHARINDEX('退款',hr.HotelName) = 0
  5828. AND CHARINDEX('返现',hr.HotelName) = 0
  5829. AND CHARINDEX('会议室',hr.HotelName) = 0
  5830. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  5831. AND CHARINDEX('运费',hr.HotelName) = 0
  5832. AND CHARINDEX('地接',hr.HotelName) = 0
  5833. AND CHARINDEX('损失',hr.HotelName) = 0
  5834. AND CHARINDEX('补差',hr.HotelName) = 0
  5835. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  5836. ORDER BY
  5837. hr.CheckInDate
  5838. ", beginDt, endDt);
  5839. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  5840. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  5841. .Select(g => new
  5842. {
  5843. Country = g.Key,
  5844. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5845. hotelData = g.GroupBy(x => x.HotelName)
  5846. .Select(g1 => new
  5847. {
  5848. hotelName = g1.Key,
  5849. roomNights = g1.Sum(x => x.RoomNights),
  5850. roomTotal = g1.Sum(x => x.RoomTotal),
  5851. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5852. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5853. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5854. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5855. })
  5856. .ToList(),
  5857. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5858. })
  5859. .OrderByDescending(x => x.BookingRoomNum)
  5860. .Take(10)
  5861. .ToList();
  5862. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  5863. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  5864. .Select(g => new
  5865. {
  5866. city = g.Key,
  5867. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5868. hotelData = g.GroupBy(x => x.HotelName)
  5869. .Select(g1 => new
  5870. {
  5871. hotelName = g1.Key,
  5872. roomNights = g1.Sum(x => x.RoomNights),
  5873. roomTotal = g1.Sum(x => x.RoomTotal),
  5874. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5875. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5876. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5877. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5878. })
  5879. .ToList(),
  5880. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5881. })
  5882. .OrderByDescending(x => x.BookingRoomNum)
  5883. .Take(10)
  5884. .ToList();
  5885. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  5886. .Select(g => new
  5887. {
  5888. Platform = g.Key,
  5889. BookingRoomNum = g.Sum(x => x.RoomTotal),
  5890. hotelData = g.GroupBy(x => x.HotelName)
  5891. .Select(g1 => new
  5892. {
  5893. hotelName = g1.Key,
  5894. roomNights = g1.Sum(x => x.RoomNights),
  5895. roomTotal = g1.Sum(x => x.RoomTotal),
  5896. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  5897. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  5898. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  5899. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  5900. })
  5901. .ToList(),
  5902. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  5903. })
  5904. .OrderByDescending(x => x.BookingRoomNum)
  5905. .ToList();
  5906. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  5907. }
  5908. /// <summary>
  5909. /// 国交数据统计
  5910. /// 商邀邀请国家数量TOP10
  5911. /// </summary>
  5912. /// <param name="_dto"></param>
  5913. /// <returns></returns>
  5914. [HttpPost("StatisticsInvitation")]
  5915. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5916. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  5917. {
  5918. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5919. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5920. endDt = $"{_dto.Year}-12-31 23:59:59";
  5921. string sql = string.Format(@"
  5922. SELECT
  5923. oa.DiId,
  5924. di.TeamName AS GroupName,
  5925. oa.Country,
  5926. oa.Area AS City,
  5927. oa.Client,
  5928. oa.Date
  5929. FROM
  5930. Res_OfficialActivities oa
  5931. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  5932. WHERE
  5933. oa.IsDel = 0
  5934. AND oa.Date BETWEEN '{0}' AND '{1}'
  5935. ", beginDt, endDt);
  5936. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  5937. var groupByCountry = data.GroupBy(x => x.Country)
  5938. .Select(g => new
  5939. {
  5940. Country = g.Key,
  5941. TimeNum = g.Count(),
  5942. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5943. })
  5944. .OrderByDescending(x => x.TimeNum)
  5945. .Take(10)
  5946. .ToList();
  5947. var groupByClient = data.GroupBy(x => x.Client)
  5948. .Select(g => new
  5949. {
  5950. Country = g.Key,
  5951. TimeNum = g.Count(),
  5952. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  5953. })
  5954. .OrderByDescending(x => x.TimeNum)
  5955. .Take(10)
  5956. .ToList();
  5957. return Ok(JsonView(true, "操作成功!", new { groupByCountry = groupByCountry, groupByClient = groupByClient }));
  5958. }
  5959. /// <summary>
  5960. /// 会务数据统计
  5961. /// 会务城市TOP10排序
  5962. /// </summary>
  5963. /// <param name="_dto"></param>
  5964. /// <returns></returns>
  5965. [HttpPost("StatisticsConferenceCity")]
  5966. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5967. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  5968. {
  5969. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  5970. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5971. endDt = $"{_dto.Year}-12-31 23:59:59";
  5972. string sql = string.Format(@"
  5973. SELECT
  5974. ioa.DiId,
  5975. ioa.InviterArea AS Country
  5976. FROM
  5977. Grp_InvitationOfficialActivities ioa
  5978. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  5979. AND ccp.IsDel = 0
  5980. AND ccp.CTable = 81
  5981. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  5982. WHERE
  5983. ioa.IsDel = 0
  5984. AND di.TeamDid IN (102,248,302,691,762,1047)
  5985. AND ccp.IsPay = 1
  5986. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  5987. ", beginDt, endDt);
  5988. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  5989. var groupByData = data.GroupBy(x => x.Country)
  5990. .Select(g => new
  5991. {
  5992. Country = g.Key,
  5993. TimeNum = g.Count(),
  5994. LinkGroupIds = g.Select(x => x.DIId).ToList()
  5995. })
  5996. .OrderByDescending(x => x.TimeNum)
  5997. .Take(10)
  5998. .ToList();
  5999. return Ok(JsonView(true, "操作成功!", groupByData));
  6000. }
  6001. /// <summary>
  6002. /// 团组数据统计
  6003. /// 团组合作前十的客户TOP10排序
  6004. /// </summary>
  6005. /// <param name="_dto"></param>
  6006. /// <returns></returns>
  6007. [HttpPost("StatisticsCooperativeCustomer")]
  6008. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6009. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  6010. {
  6011. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6012. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6013. endDt = $"{_dto.Year}-12-31 23:59:59";
  6014. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6015. _endDt = Convert.ToDateTime(endDt);
  6016. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6017. .Where(x => x.IsDel == 0)
  6018. //.Where(x => x.IsSure == 1)
  6019. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6020. .ToListAsync();
  6021. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  6022. var view = groupInfos1.Select(x =>
  6023. new
  6024. {
  6025. clienName = x.Key,
  6026. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  6027. visitsNum = x.Count()
  6028. }
  6029. )
  6030. .OrderByDescending(x => x.visitsNum)
  6031. .Take(10)
  6032. .ToList();
  6033. return Ok(JsonView(true, "操作成功!", view));
  6034. }
  6035. /// <summary>
  6036. /// 团组数据统计
  6037. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  6038. /// </summary>
  6039. /// <param name="_dto"></param>
  6040. /// <returns></returns>
  6041. [HttpPost("StatisticsCooperativeCustomerType")]
  6042. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6043. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  6044. {
  6045. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6046. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6047. endDt = $"{_dto.Year}-12-31 23:59:59";
  6048. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6049. _endDt = Convert.ToDateTime(endDt);
  6050. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6051. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  6052. .Where((di, sd) => di.IsDel == 0)
  6053. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  6054. .Select((di, sd) => new
  6055. {
  6056. Id = di.Id,
  6057. GroupTypeId = di.TeamDid,
  6058. GroupTypeName = sd.Name,
  6059. })
  6060. .ToListAsync();
  6061. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  6062. var view = groupInfos1.Select(x =>
  6063. new
  6064. {
  6065. groupTypeName = x.Key,
  6066. groupNum = x.Count(),
  6067. linkGroupId = x.Select(x1 => x1.Id).ToList()
  6068. }
  6069. )
  6070. .OrderByDescending(x => x.groupNum)
  6071. .ToList();
  6072. return Ok(JsonView(true, "操作成功!", view));
  6073. }
  6074. /// <summary>
  6075. /// 团组数据统计
  6076. /// 团组数量
  6077. /// </summary>
  6078. /// <param name="_dto"></param>
  6079. /// <returns></returns>
  6080. [HttpPost("StatisticsGroupNum")]
  6081. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6082. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  6083. {
  6084. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6085. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6086. endDt = $"{_dto.Year}-12-31 23:59:59";
  6087. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6088. _endDt = Convert.ToDateTime(endDt);
  6089. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6090. .Where(x => x.IsDel == 0)
  6091. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6092. .Select(x => new StatisticsGroupInfoEntity
  6093. {
  6094. Id = x.Id,
  6095. VisitDate = x.VisitDate,
  6096. Month = x.VisitDate.Month,
  6097. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  6098. VisitPNumber = x.VisitPNumber
  6099. })
  6100. .MergeTable()
  6101. .OrderBy(x => new { x.Month })
  6102. .ToListAsync();
  6103. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  6104. var groupNumYearData = new
  6105. {
  6106. year = _dto.Year,
  6107. yearName = _dto.Year + "年",
  6108. num = groupInfos.Count,
  6109. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6110. };
  6111. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  6112. .Select(x => new
  6113. {
  6114. Quarter = x.Key,
  6115. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6116. Num = x.Count(),
  6117. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6118. })
  6119. .OrderBy(x => x.Quarter)
  6120. .ToList();
  6121. groupNumData.ForEach(x =>
  6122. {
  6123. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  6124. });
  6125. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  6126. .Select(x => new
  6127. {
  6128. Month = x.Key,
  6129. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6130. Num = x.Count(),
  6131. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6132. })
  6133. .OrderBy(x => x.Month)
  6134. .ToList();
  6135. return Ok(JsonView(true, "操作成功!", new
  6136. {
  6137. yearData = groupNumYearData,
  6138. quarterData = groupNumData,
  6139. monthData = groupNumMonthData,
  6140. remark = groupNumStr
  6141. }));
  6142. }
  6143. /// <summary>
  6144. /// 团组数据统计
  6145. /// 团组人数
  6146. /// </summary>
  6147. /// <param name="_dto"></param>
  6148. /// <returns></returns>
  6149. [HttpPost("StatisticsGroupPeopleNum")]
  6150. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6151. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  6152. {
  6153. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  6154. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6155. endDt = $"{_dto.Year}-12-31 23:59:59";
  6156. DateTime _beginDt = Convert.ToDateTime(beginDt),
  6157. _endDt = Convert.ToDateTime(endDt);
  6158. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  6159. .Where(x => x.IsDel == 0)
  6160. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  6161. .Select(x => new StatisticsGroupInfoEntity
  6162. {
  6163. Id = x.Id,
  6164. VisitDate = x.VisitDate,
  6165. Month = x.VisitDate.Month,
  6166. VisitPNumber = x.VisitPNumber
  6167. })
  6168. .MergeTable()
  6169. .OrderBy(x => new { x.Month })
  6170. .ToListAsync();
  6171. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  6172. var groupPeopleNumYearData = new
  6173. {
  6174. year = _dto.Year,
  6175. yearName = _dto.Year + "年",
  6176. num = groupInfos.Sum(x => x.VisitPNumber),
  6177. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  6178. };
  6179. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  6180. .Select(x => new
  6181. {
  6182. Quarter = x.Key,
  6183. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  6184. Num = x.Sum(x1 => x1.VisitPNumber),
  6185. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6186. })
  6187. .OrderBy(x => x.Quarter)
  6188. .ToList();
  6189. groupPeopleNumData.ForEach(x =>
  6190. {
  6191. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  6192. });
  6193. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  6194. .Select(x => new
  6195. {
  6196. Month = x.Key,
  6197. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  6198. Num = x.Sum(x1 => x1.VisitPNumber),
  6199. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  6200. })
  6201. .OrderBy(x => x.Month)
  6202. .ToList();
  6203. return Ok(JsonView(true, "操作成功!", new
  6204. {
  6205. yearData = groupPeopleNumYearData,
  6206. quarterData = groupPeopleNumData,
  6207. monthData = groupPeopleNumMonthData,
  6208. remark = groupPeopleNumStr
  6209. }));
  6210. }
  6211. /// <summary>
  6212. /// 团组数据统计
  6213. /// OP 成本
  6214. /// </summary>
  6215. /// <param name="_dto"></param>
  6216. /// <returns></returns>
  6217. [HttpPost("StatisticsOP")]
  6218. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6219. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  6220. {
  6221. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6222. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  6223. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  6224. string beginDt = $"{lastYear}-01-01 00:00:00",
  6225. endDt = $"{thisYear}-12-31 23:59:59";
  6226. string sql = string.Format(@"
  6227. SELECT
  6228. temp.Id,
  6229. DiId,
  6230. PaymentTime,
  6231. [Year],
  6232. [Quarter],
  6233. [Month],
  6234. Area,
  6235. FeeType,
  6236. sd1.Name AS FeeTypeName,
  6237. FeeSubType,
  6238. sd2.Name AS FeeSubTypeName,
  6239. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  6240. FROM
  6241. (
  6242. SELECT
  6243. ctggr.Id,
  6244. ctggr.DiId,
  6245. ctggr.Area,
  6246. CASE
  6247. WHEN ctggr.PriceType IS NULL THEN 1069
  6248. ELSE ctggr.PriceType
  6249. END AS FeeType,
  6250. ctggrc.SId AS FeeSubType,
  6251. ctggrc.Price,
  6252. CASE
  6253. WHEN ctggrc.Count IS NULL THEN 1
  6254. ELSE ctggrc.Count
  6255. END AS Qauntity,
  6256. ccp.DayRate AS ExchangeRate,
  6257. ctggrc.CreateTime AS PaymentTime,
  6258. YEAR(ctggrc.CreateTime) AS [Year],
  6259. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  6260. MONTH(ctggrc.CreateTime) AS [Month]
  6261. FROM
  6262. Grp_CarTouristGuideGroundReservations ctggr
  6263. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  6264. AND ctggrc.IsDel = 0
  6265. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  6266. AND ccp.CTable = 79
  6267. AND ccp.IsDel = 0
  6268. WHERE
  6269. ctggr.IsDel = 0
  6270. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  6271. AND ctggrc.Price > 0 --筛选真实存在的数据
  6272. AND ccp.IsPay = 1
  6273. ) temp
  6274. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  6275. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  6276. WHERE
  6277. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  6278. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  6279. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  6280. ORDER BY
  6281. temp.[Year],
  6282. temp.[Quarter],
  6283. temp.[Month]
  6284. ", beginDt, endDt);
  6285. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  6286. //处理地区相关信息
  6287. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  6288. for (int i = 0; i < opInfos.Count; i++)
  6289. {
  6290. string country = string.Empty, city = string.Empty;
  6291. int dataId = 0;
  6292. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  6293. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  6294. if (isCountryId)
  6295. {
  6296. var countryInfo = countrys.Find(x => x.Id == dataId);
  6297. country = countryInfo?.Country ?? "";
  6298. if (citySelecter.Contains(countryInfo?.City)) city = country;
  6299. else city = countryInfo?.City ?? "";
  6300. }
  6301. else
  6302. {
  6303. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  6304. if (countryInfo1 != null)
  6305. {
  6306. country = countryInfo1?.Country ?? "";
  6307. city = countryInfo1?.City ?? country;
  6308. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6309. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6310. else city = countryInfo2?.City ?? country;
  6311. }
  6312. else
  6313. {
  6314. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  6315. if (countryInfo2 != null)
  6316. {
  6317. country = countryInfo2?.Country ?? "";
  6318. city = countryInfo2?.City ?? "";
  6319. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  6320. }
  6321. }
  6322. }
  6323. opInfos[i].Country = country;
  6324. opInfos[i].City = city;
  6325. }
  6326. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  6327. if (_dto.Type == 1)
  6328. {
  6329. //同比增长率=(本期数-同期数)/ 同期数
  6330. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  6331. .Select(x => new StatisticsOPYOY(
  6332. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  6333. feeName: x.Key,
  6334. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  6335. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  6336. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  6337. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  6338. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  6339. .Select(x1 => new StatisticsOPSubFeeYOY(
  6340. feeId: x1.Key,
  6341. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  6342. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6343. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6344. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6345. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6346. cityData: x1.GroupBy(x2 => x2.City)
  6347. .Select(x2 => new StatisticsOPCityYOY(
  6348. cityName: x2.Key,
  6349. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6350. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6351. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6352. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  6353. ))
  6354. .ToArray()
  6355. ))
  6356. .ToArray()
  6357. ))
  6358. .OrderBy(x => x.FeeId)
  6359. .ToList();
  6360. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  6361. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  6362. if (opParentYearDataSelector.Count > 0)
  6363. {
  6364. foreach (var item in opParentYearDataSelector)
  6365. {
  6366. yearData.Add(
  6367. new StatisticsOPYOY(feeId: item.Id,
  6368. feeName: item.Name,
  6369. currPeriodFee: 0.00M,
  6370. samePeriodFee: 0.00M,
  6371. currPeriodGroupTotal: 0,
  6372. samePeriodGroupTotal: 0,
  6373. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  6374. ));
  6375. }
  6376. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  6377. }
  6378. return Ok(JsonView(true, "操作成功!", yearData));
  6379. }
  6380. else if (_dto.Type == 2)
  6381. {
  6382. var monthData = opInfos.GroupBy(x => x.Month)
  6383. .Select(x => new StatisticsOPMonthYOY(
  6384. monthId: x.Key,
  6385. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  6386. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  6387. .Select(x1 => new StatisticsOPYOY(
  6388. feeId: x1.Key,
  6389. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  6390. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  6391. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  6392. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  6393. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  6394. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  6395. .Select(x2 => new StatisticsOPSubFeeYOY(
  6396. feeId: x2.Key,
  6397. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  6398. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  6399. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  6400. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  6401. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  6402. cityData: x2.GroupBy(x3 => x3.City)
  6403. .Select(x3 => new StatisticsOPCityYOY(
  6404. cityName: x3.Key,
  6405. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  6406. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  6407. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  6408. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  6409. ))
  6410. .ToArray()
  6411. ))
  6412. .ToArray()
  6413. ))
  6414. .ToArray()
  6415. ))
  6416. //.OrderBy(x => x.MonthId)
  6417. .ToList();
  6418. //1、月份是否足够十二月
  6419. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  6420. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  6421. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  6422. if (newMonthIds.Count > 0)
  6423. {
  6424. foreach (var item in newMonthIds)
  6425. {
  6426. monthData.Add(new StatisticsOPMonthYOY(
  6427. monthId: item,
  6428. monthName: System.Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  6429. feeDatas: System.Array.Empty<StatisticsOPYOY>()
  6430. ));
  6431. }
  6432. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  6433. }
  6434. //2、费用父类是否足够
  6435. for (int i = 0; i < monthData.Count; i++)
  6436. {
  6437. var month = monthData[i];
  6438. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  6439. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  6440. if (opParentFeeDataSelector.Count > 0)
  6441. {
  6442. var feeDatas = month.FeeDatas.ToList();
  6443. foreach (var item in opParentFeeDataSelector)
  6444. {
  6445. feeDatas.Add(new StatisticsOPYOY(
  6446. feeId: item.Id,
  6447. feeName: item.Name,
  6448. currPeriodFee: 0.00M,
  6449. samePeriodFee: 0.00M,
  6450. currPeriodGroupTotal: 0,
  6451. samePeriodGroupTotal: 0,
  6452. subFeeData: System.Array.Empty<StatisticsOPSubFeeYOY>()
  6453. ));
  6454. }
  6455. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  6456. monthData[i].FeeDatas = feeDatas.ToArray();
  6457. }
  6458. }
  6459. //3、费用子类是否足够
  6460. return Ok(JsonView(true, "操作成功!", monthData));
  6461. }
  6462. return Ok(JsonView(false, "操作失败!"));
  6463. }
  6464. /// <summary>
  6465. /// 团组数据统计
  6466. /// 团组预算/实际成本
  6467. /// </summary>
  6468. /// <param name="_dto"></param>
  6469. /// <returns></returns>
  6470. [HttpPost("StatisticsGroupCost")]
  6471. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6472. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  6473. {
  6474. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  6475. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  6476. endDt = $"{_dto.Year}-12-31 23:59:59";
  6477. var sql = string.Format(@"
  6478. SELECT
  6479. ROW_NUMBER() OVER(
  6480. ORDER BY
  6481. di.VisitDate DESC
  6482. ) AS 'RowNumber',
  6483. di.Id,
  6484. di.TeamName AS 'GroupName',
  6485. di.ClientUnit,
  6486. di.VisitDate,
  6487. di.VisitDays,
  6488. di.VisitPNumber,
  6489. (
  6490. SELECT
  6491. TOP 1 CASE
  6492. ISNUMERIC (gcp.Currency)
  6493. WHEN 1 THEN (
  6494. SELECT
  6495. Name
  6496. FROM
  6497. Sys_SetData sd
  6498. WHERE
  6499. CAST(gcp.Currency AS INT) = sd.Id
  6500. )
  6501. ELSE gcp.Currency
  6502. END AS 'CurrencyCode'
  6503. FROM
  6504. Grp_GroupCostParameter gcp
  6505. WHERE
  6506. gcp.IsDel = 0
  6507. AND gcp.DiId = di.Id
  6508. ) Budget_CurrencyCode,
  6509. --预算币种
  6510. (
  6511. SELECT
  6512. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  6513. FROM
  6514. Grp_GroupCostParameter gcp
  6515. WHERE
  6516. gcp.IsDel = 0
  6517. AND gcp.DiId = di.Id
  6518. ) Budget_Rate,
  6519. --预算汇率
  6520. (
  6521. SELECT
  6522. CAST(
  6523. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  6524. )
  6525. FROM
  6526. Grp_GroupCostParameter gcp
  6527. WHERE
  6528. gcp.IsDel = 0
  6529. AND gcp.DiId = di.id
  6530. ) Budget_VisaAmount,
  6531. -- 预算签证成本
  6532. (
  6533. SELECT
  6534. CAST(
  6535. SUM(
  6536. (
  6537. (ccp.PayMoney * ccp.DayRate)
  6538. )
  6539. ) AS DECIMAL(12, 2)
  6540. )
  6541. FROM
  6542. Grp_VisaInfo vi
  6543. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6544. AND ccp.CTable = 80
  6545. AND vi.Id = ccp.CId
  6546. WHERE
  6547. vi.IsDel = 0
  6548. AND ccp.IsAuditGM = 1
  6549. AND ccp.IsPay = 1
  6550. AND di.Id = vi.DIId
  6551. ) AS Reality_VisaAmount,
  6552. -- 实际签证成本
  6553. (
  6554. SELECT
  6555. CAST(
  6556. SUM(
  6557. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  6558. ) AS DECIMAL(12, 2)
  6559. )
  6560. FROM
  6561. Grp_GroupCostParameter gcp
  6562. WHERE
  6563. gcp.IsDel = 0
  6564. AND gcp.DiId = di.id
  6565. ) Budget_AirTicketAmount,
  6566. -- 预算机票成本
  6567. (
  6568. SELECT
  6569. CAST(
  6570. SUM(
  6571. (
  6572. (ccp.PayMoney * ccp.DayRate)
  6573. )
  6574. ) AS DECIMAL(12, 2)
  6575. )
  6576. FROM
  6577. Grp_AirTicketReservations atr
  6578. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6579. AND ccp.CTable = 85
  6580. AND atr.Id = ccp.CId
  6581. WHERE
  6582. atr.IsDel = 0
  6583. AND ccp.IsAuditGM = 1
  6584. AND ccp.IsPay = 1
  6585. AND di.Id = atr.DiId
  6586. ) Reality_AirTicketAmount,
  6587. --实际机票
  6588. (
  6589. SELECT
  6590. CAST(
  6591. SUM(
  6592. 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)
  6593. ) AS DECIMAL(12, 2)
  6594. )
  6595. FROM
  6596. Grp_GroupCostParameter gcp
  6597. WHERE
  6598. gcp.IsDel = 0
  6599. AND gcp.DiId = di.id
  6600. ) Budget_HotelAmount,
  6601. -- 预算酒店成本
  6602. (
  6603. SELECT
  6604. CAST(
  6605. SUM(
  6606. (ccp.PayMoney * ccp.DayRate)
  6607. ) AS DECIMAL(12, 2)
  6608. )
  6609. FROM
  6610. Grp_HotelReservations hr
  6611. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  6612. WHERE
  6613. hr.IsDel = 0
  6614. AND ccp.IsDel = 0
  6615. AND ccp.CTable = 76
  6616. AND ccp.IsAuditGM = 1
  6617. AND ccp.PayMoney <> 0
  6618. AND ccp.IsPay = 1
  6619. AND di.Id = hr.DiId
  6620. ) AS Reality_HotelAmount,
  6621. -- 实际酒店成本
  6622. (
  6623. SELECT
  6624. CAST(
  6625. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  6626. )
  6627. FROM
  6628. Grp_GroupCostParameter gcp
  6629. WHERE
  6630. gcp.IsDel = 0
  6631. AND gcp.DiId = di.id
  6632. ) Budget_OPAmount,
  6633. -- 预算 OP
  6634. (
  6635. SELECT
  6636. CAST(
  6637. SUM(
  6638. (
  6639. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  6640. )
  6641. ) AS DECIMAL(12, 2)
  6642. )
  6643. FROM
  6644. Grp_CarTouristGuideGroundReservations ctggr
  6645. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  6646. AND ccp.CTable = 79
  6647. AND ctggr.Id = ccp.CId
  6648. WHERE
  6649. ctggr.IsDel = 0
  6650. AND ccp.IsAuditGM = 1
  6651. AND ccp.IsPay = 1
  6652. AND di.Id = ctggr.DiId
  6653. ) AS Reality_OPAmount,
  6654. -- 实际 OP
  6655. (
  6656. SELECT
  6657. CAST(
  6658. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  6659. )
  6660. FROM
  6661. Grp_GroupCostParameter gcp
  6662. WHERE
  6663. gcp.IsDel = 0
  6664. AND gcp.DiId = di.id
  6665. ) Budget_OAAmount,
  6666. -- 预算 商邀
  6667. (
  6668. SELECT
  6669. CAST(
  6670. SUM(
  6671. (ccp.PayMoney * ccp.DayRate)
  6672. ) AS DECIMAL(12, 2)
  6673. )
  6674. FROM
  6675. Grp_InvitationOfficialActivities ioa
  6676. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6677. AND ccp.CTable = 81
  6678. AND ioa.Id = ccp.CId
  6679. WHERE
  6680. ioa.IsDel = 0
  6681. AND ccp.IsAuditGM = 1
  6682. AND ccp.IsPay = 1
  6683. AND di.Id = ioa.Diid
  6684. ) AS Reality_OAAmount,
  6685. -- 实际 商邀
  6686. (
  6687. SELECT
  6688. CAST(
  6689. SUM(
  6690. 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)
  6691. ) AS DECIMAL(12, 2)
  6692. )
  6693. FROM
  6694. Grp_GroupCostParameter gcp
  6695. WHERE
  6696. gcp.IsDel = 0
  6697. AND gcp.DiId = di.id
  6698. ) Budget_OtherAmount,
  6699. -- 预算其他成本
  6700. (
  6701. SELECT
  6702. CAST(
  6703. SUM(
  6704. (ccp.PayMoney * ccp.DayRate)
  6705. ) AS DECIMAL(12, 2)
  6706. )
  6707. FROM
  6708. Grp_Customers ic
  6709. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6710. AND ccp.CTable = 82
  6711. AND ic.Id = ccp.CId
  6712. WHERE
  6713. ic.IsDel = 0
  6714. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  6715. AND di.Id = ic.DiId
  6716. ) AS Reality_InsureAmount,
  6717. -- 实际保险成本
  6718. (
  6719. SELECT
  6720. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  6721. FROM
  6722. Grp_DecreasePayments dp
  6723. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  6724. AND ccp.CTable = 98
  6725. AND dp.Id = ccp.CId
  6726. WHERE
  6727. dp.IsDel = 0
  6728. AND ccp.Ctable = 98
  6729. AND ccp.IsAuditGM = 1
  6730. AND ccp.IsPay = 1
  6731. AND di.Id = dp.Diid
  6732. ) AS Reality_OtherCostAmount -- 实际其他款项
  6733. FROM
  6734. Grp_DelegationInfo di
  6735. WHERE
  6736. di.IsDel = 0
  6737. AND di.IsBid = 0
  6738. --AND di.TeamDid IN (38, 39, 40, 1048)
  6739. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  6740. ", beginDt, endDt);
  6741. if (!string.IsNullOrEmpty(_dto.Search))
  6742. {
  6743. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  6744. }
  6745. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  6746. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  6747. var total = view.Count;
  6748. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  6749. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  6750. if (data.Count > 0)
  6751. {
  6752. var diIds = data.Select(x => x.Id).ToList();
  6753. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  6754. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  6755. .Where(x => x.IsDel == 0 &&
  6756. diIds.Contains(x.DIId) &&
  6757. x.IsPay == 1 &&
  6758. x.IsAuditGM == 1
  6759. )
  6760. .ToListAsync();
  6761. for (int i = 0; i < data.Count; i++)
  6762. {
  6763. var info = data[i];
  6764. info.RowNumber = i + 1;
  6765. #region 1:签证 80
  6766. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  6767. var visaDesc = "-";
  6768. if (visaDatas.Count > 0)
  6769. {
  6770. visaDesc = $"实际币种金额:";
  6771. foreach (var visa in visaDatas)
  6772. {
  6773. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  6774. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  6775. }
  6776. }
  6777. info.Reality_VisaAmountDesc = visaDesc;
  6778. #endregion
  6779. #region 2:机票 85
  6780. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  6781. var airDesc = "-";
  6782. if (airDatas.Count > 0)
  6783. {
  6784. airDesc = $"实际币种金额:";
  6785. foreach (var air in airDatas)
  6786. {
  6787. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  6788. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  6789. }
  6790. }
  6791. info.Reality_AirTicketAmountDesc = airDesc;
  6792. #endregion
  6793. #region 3:酒店 76
  6794. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0).ToList();
  6795. var hotelDesc = "-";
  6796. if (hotelDatas.Count > 0)
  6797. {
  6798. hotelDesc = $"实际币种金额:";
  6799. foreach (var hotel in hotelDatas)
  6800. {
  6801. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  6802. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  6803. }
  6804. }
  6805. info.Reality_HotelAmountDesc = hotelDesc;
  6806. #endregion
  6807. #region 4:OP 79
  6808. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  6809. var opDesc = "-";
  6810. if (opDatas.Count > 0)
  6811. {
  6812. opDesc = $"实际币种金额;";
  6813. foreach (var op in opDatas)
  6814. {
  6815. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  6816. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  6817. }
  6818. }
  6819. info.Reality_OPAmountDesc = opDesc;
  6820. #endregion
  6821. #region 5:商邀 81
  6822. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  6823. var oaDesc = "-";
  6824. if (oaDatas.Count > 0)
  6825. {
  6826. oaDesc = $"实际币种金额:";
  6827. foreach (var oa in oaDatas)
  6828. {
  6829. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  6830. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  6831. }
  6832. }
  6833. info.Reality_OAAmountDesc = oaDesc;
  6834. #endregion
  6835. #region 6:其他款项(保险 82、其他款项 98)
  6836. var cTables = new List<int>() { 82, 98 };
  6837. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  6838. var otherDesc = "-";
  6839. if (otherDatas.Count > 0)
  6840. {
  6841. otherDesc = $"实际币种金额:";
  6842. foreach (var other in otherDatas)
  6843. {
  6844. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  6845. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  6846. }
  6847. }
  6848. info.Reality_OtherCostAmountDesc = otherDesc;
  6849. #endregion
  6850. }
  6851. }
  6852. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  6853. return Ok(JsonView(briefData, total));
  6854. }
  6855. /// <summary>
  6856. /// 团组数据统计
  6857. /// 当前时间团组所在城市
  6858. /// </summary>
  6859. /// <param name="dto"></param>
  6860. /// <returns></returns>
  6861. [HttpPost("StatisticsNowCityOfGroup")]
  6862. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  6863. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  6864. {
  6865. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  6866. var nowLable = DateTime.Now.ToString("yyyy-MM-dd");
  6867. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  6868. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql)
  6869. .Select(x => new { x.Id, x.VisitCountry, x.TeamName, x.ClientUnit, x.VisitStartDate, x.VisitEndDate }).
  6870. ToListAsync();
  6871. if (!groupInfos.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  6872. var groupIds = groupInfos.Select(x => x.Id).ToList();
  6873. //三字码
  6874. var threeDatas = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  6875. //国家
  6876. var countryDatas = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.City)).ToListAsync();
  6877. //公务
  6878. var OADatas = await _sqlSugar
  6879. .Queryable<Res_OfficialActivities>().Where(x => x.IsDel == 0 && groupIds.Contains(x.DiId) && !string.IsNullOrEmpty(x.Country) && !string.IsNullOrEmpty(x.Area))
  6880. .ToListAsync();
  6881. //酒店
  6882. var hotelDatas = await _sqlSugar.Queryable<Grp_HotelReservations>()
  6883. .LeftJoin<Grp_NationalTravelFee>((hr, ntf) => hr.AreaId == ntf.Id)
  6884. .Where((hr, ntf) => hr.IsDel == 0 && groupIds.Contains(hr.DiId))
  6885. .Select((hr, ntf) => new
  6886. {
  6887. hr.DiId,
  6888. hr.AreaId,
  6889. hr.HotelName,
  6890. hr.CheckInDate,
  6891. hr.CheckOutDate,
  6892. hr.HotelAddress,
  6893. ntf.Country,
  6894. ntf.City
  6895. })
  6896. .ToListAsync();
  6897. //机票
  6898. /*
  6899. *舱位类型
  6900. *457 头等舱
  6901. *458 公务舱
  6902. *459 超经舱
  6903. *460 经济舱
  6904. *461 退票
  6905. *565 其他
  6906. *574 长段公务舱
  6907. *575 短途经济舱
  6908. *1023 行程单打印费
  6909. *1024 选座费
  6910. */
  6911. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  6912. var airDatas = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  6913. .Where(atr => atr.IsDel == 0 && groupIds.Contains(atr.DIId) && classTypes.Contains(atr.CType))
  6914. .ToListAsync();
  6915. string[] characters = { "|", "、" };
  6916. var result = new List<StatisticsNowCityOfGroupResultView>();
  6917. foreach (var item in groupInfos)
  6918. {
  6919. string statusText = string.Empty,
  6920. address = string.Empty;
  6921. var countrys = item.VisitCountry;
  6922. if (string.IsNullOrEmpty(countrys)) continue;
  6923. var currCountrys = item.VisitCountry.Split(characters, StringSplitOptions.RemoveEmptyEntries);
  6924. var stutus = true;
  6925. #region 公务
  6926. var currOADatas = OADatas.Where(x => x.DiId == item.Id && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6927. if (currOADatas.Any())
  6928. {
  6929. foreach (var curr_oa in currOADatas)
  6930. {
  6931. var localTime = GetCountryOrCityCurrentDateTime(curr_oa.Country, curr_oa.Area);
  6932. if (localTime == null) continue;
  6933. var currOaDtStart = Convert.ToDateTime($"{Convert.ToDateTime(curr_oa.Date).ToString("yyyy-MM-dd")} {curr_oa.Time}");
  6934. var currOaDtEnd = currOaDtStart.AddHours(2);
  6935. var currTimeZoneStatus = localTime >= currOaDtStart && localTime <= currOaDtEnd;
  6936. if (!currTimeZoneStatus) continue;
  6937. stutus = false;
  6938. statusText = "公务活动中";
  6939. address = curr_oa.Address;
  6940. break;
  6941. }
  6942. }
  6943. #endregion
  6944. #region 酒店
  6945. var currHotelDatas = hotelDatas.Where(x => x.DiId == item.Id && !string.IsNullOrEmpty(x.Country) && currCountrys.Any(c => x.Country.Contains(c))).ToList();
  6946. if (stutus && hotelDatas.Any())
  6947. {
  6948. foreach (var curr_hotel in currHotelDatas)
  6949. {
  6950. var checkInDt = Convert.ToDateTime(curr_hotel.CheckInDate);
  6951. List<(DateTime start, DateTime end)> timeRanges = new List<(DateTime, DateTime)>();
  6952. while (checkInDt <= Convert.ToDateTime(curr_hotel.CheckOutDate))
  6953. {
  6954. int year = checkInDt.Year,
  6955. month = checkInDt.Month,
  6956. day = checkInDt.Day;
  6957. timeRanges.Add((new DateTime(year, month, day, 0, 0, 0), new DateTime(year, month, day, 9, 0, 0)));
  6958. timeRanges.Add((new DateTime(year, month, day, 18, 0, 0), new DateTime(year, month, day, 23, 59, 59)));
  6959. checkInDt = checkInDt.AddDays(1);
  6960. }
  6961. if (!timeRanges.Any()) continue;
  6962. if (string.IsNullOrEmpty(curr_hotel.Country) && string.IsNullOrEmpty(curr_hotel.City)) continue;
  6963. var countryInfo = countryDatas.Where(x => x.Id == curr_hotel.AreaId).FirstOrDefault();
  6964. if (countryInfo == null) continue;
  6965. var localTime = GetCountryOrCityCurrentDateTime(countryInfo.Country, countryInfo.City);
  6966. var currTimeZoneStatus = timeRanges.Any(range => localTime >= range.start && localTime <= range.end);
  6967. if (!currTimeZoneStatus) continue;
  6968. stutus = false;
  6969. statusText = "入住酒店中";
  6970. address = curr_hotel.HotelAddress;
  6971. break;
  6972. }
  6973. }
  6974. #endregion
  6975. #region 机票--通过三字码解析处理
  6976. var airTicketDatas = GetTableByBlackCode(item.Id);
  6977. if (stutus && airTicketDatas != null)
  6978. {
  6979. foreach (DataRow curr_airTicket in airTicketDatas.Rows)
  6980. {
  6981. string departDate = curr_airTicket["Date"].ToString(), //出发日期
  6982. departThree = curr_airTicket["Three"].ToString(), //城市三字码
  6983. departTime = curr_airTicket["StartTime"].ToString(), //出发时刻
  6984. departTerminal = curr_airTicket["StartBuilding"].ToString(), //出发航站楼
  6985. arriveTerminal = curr_airTicket["EndBuilding"].ToString(), //抵达航站楼
  6986. arrivedDate = curr_airTicket["ArrivedDate"].ToString(), //抵达日期
  6987. arrivedTime = curr_airTicket["EndTime"].ToString(), //抵达日期
  6988. flightTime = curr_airTicket["FlightTime"].ToString(); //飞行时间
  6989. if (string.IsNullOrEmpty(departThree)) continue;
  6990. string departAirThree = departThree.Substring(0, 3),
  6991. arriveAirThree = departThree.Substring(3, 3);
  6992. string departCountry = string.Empty,
  6993. departCity = string.Empty,
  6994. departAirport = string.Empty,
  6995. arriveCountry = string.Empty,
  6996. arriveCity = string.Empty,
  6997. arriveAirport = string.Empty;
  6998. var departCountryInfo = threeDatas.Find(x => x.Three.Equals(departAirThree));
  6999. var arriveCountryInfo = threeDatas.Find(x => x.Three.Equals(arriveAirThree));
  7000. if (departCountryInfo == null || arriveCountryInfo == null) continue;
  7001. departCountry = departCountryInfo.Country;
  7002. departCity = departCountryInfo.City;
  7003. departAirport = departCountryInfo.AirPort;
  7004. arriveCountry = arriveCountryInfo.Country;
  7005. arriveCity = arriveCountryInfo.City;
  7006. arriveAirport = arriveCountryInfo.AirPort;
  7007. var arriveDateTimeBool = DateTime.TryParse(arrivedDate + " " + arrivedTime.Insert(2, ":"), out DateTime arriveDateTime);
  7008. if (!arriveDateTimeBool) continue;
  7009. var filghtHoursBool = int.TryParse(flightTime.Split("H")[0].ToString(), out int filghtHours);
  7010. var filghtMinutesBool = int.TryParse(flightTime.Split("H")[1].Remove(2).ToString(), out int filghtMinutes);
  7011. if (!filghtHoursBool || !filghtHoursBool) continue;
  7012. var departDateTime = arriveDateTime.AddHours(-filghtHours).AddMinutes(-filghtMinutes);
  7013. var localTime = GetCountryOrCityCurrentDateTime(arriveCountry, arriveCity);
  7014. var currTimeZoneStatus = localTime >= departDateTime && localTime <= arriveDateTime;
  7015. if (!currTimeZoneStatus) continue;
  7016. stutus = false;
  7017. statusText = $"正飞往{arriveCity}城市中";
  7018. address = $"{arriveCountry}{arriveAirport}{arriveTerminal}";
  7019. break;
  7020. }
  7021. }
  7022. if (stutus) statusText = $"其他";
  7023. #endregion
  7024. result.Add(new StatisticsNowCityOfGroupResultView()
  7025. {
  7026. GroupName = item.TeamName,
  7027. Client = item.ClientUnit,
  7028. StatusText = statusText,
  7029. Address = address
  7030. });
  7031. }
  7032. result.AddRange(new List<StatisticsNowCityOfGroupResultView>() {
  7033. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组1",Client = "模拟数据单位1",StatusText = "正在公务中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7034. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组2",Client = "模拟数据单位2",StatusText = "入住酒店中",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7035. new StatisticsNowCityOfGroupResultView(){ GroupName = "模拟数据团组3",Client = "模拟数据单位3",StatusText = "其他",Address = "日本〒104-0032 Tokyo, Chuo City, Hatchobori, 1 Chome−12−8 EAST2階" },
  7036. });
  7037. var result1 = result.GroupBy(x => x.Address).Select(g => new
  7038. {
  7039. address = g.Key,
  7040. Items = g.ToList().Select(gg => new { gg.GroupName, gg.Client, gg.StatusText }).ToList()
  7041. });
  7042. if (!result1.Any()) return Ok(JsonView(false, "今天暂无出行的的团!"));
  7043. return Ok(JsonView(result1));
  7044. }
  7045. private StatisticsNowCityOfGroupView CitySplit(string cityLable, List<Res_ThreeCode> cities)
  7046. {
  7047. var info = new StatisticsNowCityOfGroupView();
  7048. if (string.IsNullOrEmpty(cityLable)) return info;
  7049. var cityArray = cityLable.Split("-");
  7050. var departCityCode = cityArray[0];
  7051. var arriveCityCode = cityArray[1];
  7052. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  7053. info.DepartAirportCode = departCityCode;
  7054. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  7055. info.DepartCityName = departAirportInfo?.City ?? "-";
  7056. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  7057. info.ArriveAirportCode = arriveCityCode;
  7058. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  7059. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  7060. return info;
  7061. }
  7062. #endregion
  7063. #region 企业利润
  7064. /// <summary>
  7065. /// 日常费用排除项
  7066. /// </summary>
  7067. private readonly List<int> _priceTypeIds = new List<int>()
  7068. {
  7069. 686, // 信用卡还款
  7070. 687, // 张总私人费用
  7071. 688, // 代报销社保生育补贴
  7072. 306, // 人事行政费用-张总家用类
  7073. 325, // 会展部备用金
  7074. 689 // 团组签证保险
  7075. };
  7076. /// <summary>
  7077. /// 企业利润 infos
  7078. /// </summary>
  7079. /// <param name="beginDt"></param>
  7080. /// <param name="endDt"></param>
  7081. /// <returns></returns>
  7082. private async Task<CorporateProfitInfosView> CorporateProfitInfos(string beginDt, string endDt)
  7083. {
  7084. var view = new CorporateProfitInfosView();
  7085. #region 已审核SQL
  7086. // string sql = string.Format(@"SELECT
  7087. // ROW_NUMBER() OVER(ORDER BY di.VisitDate Asc) AS 'RowIndex',
  7088. // di.Id,
  7089. // di.ClientName,
  7090. // di.TeamName,
  7091. // di.TeamDid,
  7092. // ss.Name AS 'GroupTypeName',
  7093. // di.VisitDate,
  7094. // di.VisitPNumber,
  7095. // (
  7096. // SELECT
  7097. // SUM(ffr.ItemSumPrice)
  7098. // FROM
  7099. // OA2023DB.dbo.Fin_ForeignReceivables ffr
  7100. // WHERE
  7101. // ffr.IsDel = 0
  7102. // AND ffr.Diid = di.Id
  7103. // ) 'ReceivableAmount',
  7104. // (
  7105. // SELECT
  7106. // SUM(fpr.Price)
  7107. // FROM
  7108. // OA2023DB.dbo.Fin_ProceedsReceived fpr
  7109. // WHERE
  7110. // fpr.IsDel = 0
  7111. // AND fpr.DIId = di.Id
  7112. // ) 'ReceivedAmount',
  7113. // (
  7114. // SELECT
  7115. // SUM(ccp.PayMoney * ccp.DayRate)
  7116. // FROM
  7117. // Fin_PaymentRefundAndOtherMoney prom
  7118. // INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7119. // AND prom.DiId = ccp.DIId
  7120. // WHERE
  7121. // prom.IsDel = 0
  7122. // AND prom.PayType = 1
  7123. // AND ccp.CTable = 285
  7124. // AND ccp.IsAuditGM = 1
  7125. // AND prom.DiId = di.Id
  7126. // ) AS 'RefundedAmount',
  7127. // (
  7128. // SELECT
  7129. // SUM(ccp.PayMoney * ccp.DayRate)
  7130. // FROM
  7131. // Grp_HotelReservations hr
  7132. // INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7133. // WHERE
  7134. // hr.IsDel = 0
  7135. // AND ccp.IsDel = 0
  7136. // AND ccp.CTable = 76
  7137. // AND (
  7138. // ccp.IsAuditGM = 1
  7139. // OR ccp.IsAuditGM = 3
  7140. // )
  7141. // AND hr.DiId = di.Id
  7142. // ) AS 'HotelAmount',
  7143. // (
  7144. // SELECT
  7145. // SUM(
  7146. // (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7147. // )
  7148. // FROM
  7149. // Grp_CarTouristGuideGroundReservations ctggr
  7150. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7151. // AND ccp.CTable = 79
  7152. // AND ctggr.Id = ccp.CId
  7153. // WHERE
  7154. // ctggr.IsDel = 0
  7155. // AND (
  7156. // ccp.IsAuditGM = 1
  7157. // OR ccp.IsAuditGM = 3
  7158. // )
  7159. // AND ctggr.DiId = di.Id
  7160. // ) AS 'LocalGuideAmount',
  7161. // (
  7162. // SELECT
  7163. // SUM(ccp.PayMoney * ccp.DayRate)
  7164. // FROM
  7165. // Grp_AirTicketReservations atr
  7166. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7167. // AND ccp.CTable = 85
  7168. // AND atr.Id = ccp.CId
  7169. // WHERE
  7170. // atr.IsDel = 0
  7171. // AND ccp.IsAuditGM = 1
  7172. // AND atr.DIId = di.Id
  7173. // ) AS 'AirTicketAmount',
  7174. // (
  7175. // SELECT
  7176. // SUM(ccp.PayMoney * ccp.DayRate)
  7177. // FROM
  7178. // Grp_VisaInfo vi
  7179. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7180. // AND ccp.CTable = 80
  7181. // AND vi.Id = ccp.CId
  7182. // WHERE
  7183. // vi.IsDel = 0
  7184. // AND ccp.IsAuditGM = 1
  7185. // AND vi.DIId = di.Id
  7186. // ) AS 'VisaAmount',
  7187. // (
  7188. // SELECT
  7189. // SUM(ccp.PayMoney * ccp.DayRate)
  7190. // FROM
  7191. // Grp_InvitationOfficialActivities ioa
  7192. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7193. // AND ccp.CTable = 81
  7194. // AND ioa.Id = ccp.CId
  7195. // WHERE
  7196. // ioa.IsDel = 0
  7197. // AND ccp.IsAuditGM = 1
  7198. // AND ioa.DiId = di.Id
  7199. // ) AS 'OAAmount',
  7200. // (
  7201. // SELECT
  7202. // SUM(ccp.PayMoney * ccp.DayRate)
  7203. // FROM
  7204. // Grp_Customers ic
  7205. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7206. // AND ccp.CTable = 82
  7207. // AND ic.Id = ccp.CId
  7208. // WHERE
  7209. // ic.IsDel = 0
  7210. // AND ccp.IsAuditGM = 1
  7211. // AND ic.DiId = di.Id
  7212. // ) AS 'InsureAmount',
  7213. // (
  7214. // SELECT
  7215. // SUM(ccp.PayMoney * ccp.DayRate)
  7216. // FROM
  7217. // Grp_DecreasePayments dp
  7218. // INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7219. // AND ccp.CTable = 98
  7220. // AND dp.Id = ccp.CId
  7221. // WHERE
  7222. // dp.IsDel = 0
  7223. // AND ccp.IsAuditGM = 1
  7224. // AND dp.Diid = di.Id
  7225. // ) AS 'OtherAmount'
  7226. //FROM
  7227. // OA2023DB.dbo.Grp_DelegationInfo di
  7228. // LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7229. //WHERE
  7230. // di.IsDel = 0
  7231. // AND di.IsBid = 0
  7232. // AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7233. #endregion
  7234. //含未审核SQL
  7235. string sql = string.Format(@"SELECT
  7236. ROW_NUMBER() OVER(
  7237. ORDER BY
  7238. di.VisitDate Asc
  7239. ) AS 'RowIndex',
  7240. di.Id,
  7241. di.ClientName,
  7242. di.TeamName,
  7243. di.TeamDid,
  7244. ss.Name AS 'GroupTypeName',
  7245. di.VisitDate,
  7246. di.VisitPNumber,
  7247. (
  7248. SELECT
  7249. SUM(ffr.ItemSumPrice)
  7250. FROM
  7251. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7252. WHERE
  7253. ffr.IsDel = 0
  7254. AND ffr.Diid = di.Id
  7255. ) 'ReceivableAmount',
  7256. (
  7257. SELECT
  7258. SUM(fpr.Price)
  7259. FROM
  7260. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7261. WHERE
  7262. fpr.IsDel = 0
  7263. AND fpr.DIId = di.Id
  7264. ) 'ReceivedAmount',
  7265. (
  7266. SELECT
  7267. SUM(ccp.PayMoney * ccp.DayRate)
  7268. FROM
  7269. Fin_PaymentRefundAndOtherMoney prom
  7270. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7271. AND prom.DiId = ccp.DIId
  7272. WHERE
  7273. prom.IsDel = 0
  7274. AND prom.PayType = 1
  7275. AND ccp.CTable = 285 --AND ccp.IsAuditGM = 1
  7276. AND ccp.IsAuditGM != 2
  7277. AND prom.DiId = di.Id
  7278. ) AS 'RefundedAmount',
  7279. (
  7280. SELECT
  7281. SUM(ccp.PayMoney * ccp.DayRate)
  7282. FROM
  7283. Grp_HotelReservations hr
  7284. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7285. WHERE
  7286. hr.IsDel = 0
  7287. AND ccp.IsDel = 0
  7288. AND ccp.CTable = 76 -- AND (
  7289. -- ccp.IsAuditGM = 1
  7290. -- OR ccp.IsAuditGM = 3
  7291. -- )
  7292. AND ccp.IsAuditGM != 2
  7293. AND hr.DiId = di.Id
  7294. ) AS 'HotelAmount',
  7295. (
  7296. SELECT
  7297. SUM(
  7298. (ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate)
  7299. )
  7300. FROM
  7301. Grp_CarTouristGuideGroundReservations ctggr
  7302. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7303. AND ccp.CTable = 79
  7304. AND ctggr.Id = ccp.CId
  7305. WHERE
  7306. ctggr.IsDel = 0 -- AND (
  7307. -- ccp.IsAuditGM = 1
  7308. -- OR ccp.IsAuditGM = 3
  7309. -- )
  7310. AND ccp.IsAuditGM != 2
  7311. AND ctggr.DiId = di.Id
  7312. ) AS 'LocalGuideAmount',
  7313. (
  7314. SELECT
  7315. SUM(ccp.PayMoney * ccp.DayRate)
  7316. FROM
  7317. Grp_AirTicketReservations atr
  7318. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7319. AND ccp.CTable = 85
  7320. AND atr.Id = ccp.CId
  7321. WHERE
  7322. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7323. AND ccp.IsAuditGM != 2
  7324. AND atr.DIId = di.Id
  7325. ) AS 'AirTicketAmount',
  7326. (
  7327. SELECT
  7328. SUM(ccp.PayMoney * ccp.DayRate)
  7329. FROM
  7330. Grp_VisaInfo vi
  7331. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7332. AND ccp.CTable = 80
  7333. AND vi.Id = ccp.CId
  7334. WHERE
  7335. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7336. AND ccp.IsAuditGM != 2
  7337. AND vi.DIId = di.Id
  7338. ) AS 'VisaAmount',
  7339. (
  7340. SELECT
  7341. SUM(ccp.PayMoney * ccp.DayRate)
  7342. FROM
  7343. Grp_InvitationOfficialActivities ioa
  7344. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7345. AND ccp.CTable = 81
  7346. AND ioa.Id = ccp.CId
  7347. WHERE
  7348. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7349. AND ccp.IsAuditGM != 2
  7350. AND ioa.DiId = di.Id
  7351. ) AS 'OAAmount',
  7352. (
  7353. SELECT
  7354. SUM(ccp.PayMoney * ccp.DayRate)
  7355. FROM
  7356. Grp_Customers ic
  7357. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7358. AND ccp.CTable = 82
  7359. AND ic.Id = ccp.CId
  7360. WHERE
  7361. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7362. AND ccp.IsAuditGM != 2
  7363. AND ic.DiId = di.Id
  7364. ) AS 'InsureAmount',
  7365. (
  7366. SELECT
  7367. SUM(ccp.PayMoney * ccp.DayRate)
  7368. FROM
  7369. Grp_DecreasePayments dp
  7370. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7371. AND ccp.CTable = 98
  7372. AND dp.Id = ccp.CId
  7373. WHERE
  7374. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7375. AND ccp.IsAuditGM != 2
  7376. AND dp.Diid = di.Id
  7377. ) AS 'OtherAmount',
  7378. (
  7379. SELECT
  7380. SUM(dfp.SumPrice)
  7381. FROM
  7382. Fin_DailyFeePayment dfp
  7383. WHERE
  7384. dfp.IsDel = 0
  7385. AND dfp.GroupId = di.Id
  7386. ) AS 'DailyAmout'
  7387. FROM
  7388. OA2023DB.dbo.Grp_DelegationInfo di
  7389. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7390. WHERE
  7391. di.IsDel = 0
  7392. -- AND di.IsBid = 0
  7393. AND di.VisitDate BETWEEN '{0}' AND '{1}'", beginDt, endDt);
  7394. var groupItems = await _sqlSugar.SqlQueryable<CorporateProfitInfo>(sql).ToArrayAsync();
  7395. if (groupItems.Any())
  7396. {
  7397. // 排除 投标、延期、取消 等团组名称包含的关键词 并且 团组成本费用为0 排除在外
  7398. var excludeKeywords = new List<string> { "测试", "延期", "投标", "取消" };
  7399. groupItems = groupItems.Where(g =>
  7400. !excludeKeywords.Any(keyword => g.TeamName.Contains(keyword)) &&
  7401. g.CostTotal != 0
  7402. ).ToArray();
  7403. var groupIds = groupItems.Select(x => x.Id).ToArray();
  7404. var feeCountInfos = await CorporateProfitFeeCount(groupIds);
  7405. if (feeCountInfos.Any())
  7406. {
  7407. foreach (var item in groupItems)
  7408. {
  7409. var tips = feeCountInfos.FirstOrDefault(x => x.Id == item.Id)?.FeeCountTipsLabel ?? "";
  7410. if (!string.IsNullOrEmpty(tips)) item.FeeCountTipsLabel = tips;
  7411. }
  7412. }
  7413. }
  7414. var dailySql = string.Format(@"SELECT
  7415. dfp.Id,
  7416. dfp.CompanyId,
  7417. sc.CompanyName,
  7418. sd.DepName AS 'Branch',
  7419. su.CnName AS 'Applicant',
  7420. dfp.PriceTypeId,
  7421. sst.Id AS 'PriceParentTypeId',
  7422. sst.Name AS 'PriceParentTypeName',
  7423. ss.Id AS 'PriceTypeId',
  7424. ss.Name AS 'PriceypeName',
  7425. dfp.Instructions,
  7426. dfp.SumPrice AS 'CNYTotal',
  7427. dfpc.PriceName,
  7428. dfpc.Quantity,
  7429. dfpc.Price,
  7430. dfpc.ItemTotal,
  7431. dfpc.Remark,
  7432. dfp.CreateTime
  7433. From
  7434. Fin_DailyFeePayment dfp
  7435. INNER JOIN Fin_DailyFeePaymentContent dfpc on dfp.Id = dfpc.DFPId
  7436. LEFT JOIN Sys_Company sc on dfp.CompanyId = sc.Id
  7437. LEFT JOIN Sys_Users su on dfp.CreateUserId = su.Id
  7438. LEFT JOIN Sys_Department sd on su.DepId = sd.Id
  7439. LEFT JOIN Sys_SetData ss on dfp.PriceTypeId = ss.Id
  7440. LEFT JOIN Sys_SetDataType sst on ss.STid = sst.Id
  7441. WHERE
  7442. dfp.IsDel = 0
  7443. AND dfpc.IsDel = 0
  7444. AND dfp.CreateTime BETWEEN '{0}' AND '{1}'
  7445. -- AND dfp.IsPay = 1
  7446. ORDER BY
  7447. dfp.CompanyId,
  7448. su.DepId,
  7449. dfp.CreateUserId,
  7450. dfp.PriceTypeId,
  7451. dfp.CreateTime ASC", beginDt, endDt);
  7452. var dailyItems = await _sqlSugar.SqlQueryable<DailyInfo>(dailySql).ToArrayAsync();
  7453. view.GroupItems = groupItems.OrderBy(x => x.RowIndex).ToArray();
  7454. view.DailyItems = dailyItems;
  7455. return view;
  7456. }
  7457. /// <summary>
  7458. /// 企业利润
  7459. /// 团组费用条数统计
  7460. /// </summary>
  7461. /// <param name="groupIds"></param>
  7462. /// <returns></returns>
  7463. private async Task<CorporateProfitFeeCount[]> CorporateProfitFeeCount(int[] groupIds)
  7464. {
  7465. if (!groupIds.Any()) return Array.Empty<CorporateProfitFeeCount>();
  7466. //含未审核SQL
  7467. string sql = string.Format(@"SELECT
  7468. ROW_NUMBER() OVER(
  7469. ORDER BY
  7470. di.VisitDate Asc
  7471. ) AS 'RowIndex',
  7472. di.Id,
  7473. di.TeamName,
  7474. di.VisitDate,
  7475. (
  7476. SELECT
  7477. Count(1)
  7478. FROM
  7479. OA2023DB.dbo.Fin_ForeignReceivables ffr
  7480. WHERE
  7481. ffr.IsDel = 0
  7482. AND ffr.Diid = di.Id
  7483. ) 'ReceivableTotal',
  7484. (
  7485. SELECT
  7486. Count(1)
  7487. FROM
  7488. OA2023DB.dbo.Fin_ProceedsReceived fpr
  7489. WHERE
  7490. fpr.IsDel = 0
  7491. AND fpr.DIId = di.Id
  7492. ) 'ReceivedTotal',
  7493. (
  7494. SELECT
  7495. Count(1)
  7496. FROM
  7497. Fin_PaymentRefundAndOtherMoney prom
  7498. INNER JOIN Grp_CreditCardPayment ccp ON prom.Id = ccp.CId
  7499. AND prom.DiId = ccp.DIId
  7500. WHERE
  7501. prom.IsDel = 0
  7502. AND prom.PayType = 1
  7503. AND ccp.CTable = 285
  7504. --AND ccp.IsAuditGM = 1
  7505. AND ccp.IsAuditGM != 2
  7506. AND prom.DiId = di.Id
  7507. ) AS 'RefundedTotal',
  7508. (
  7509. SELECT
  7510. Count(1)
  7511. FROM
  7512. Grp_HotelReservations hr
  7513. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  7514. WHERE
  7515. hr.IsDel = 0
  7516. AND ccp.IsDel = 0
  7517. AND ccp.CTable = 76 -- AND (
  7518. -- ccp.IsAuditGM = 1
  7519. -- OR ccp.IsAuditGM = 3
  7520. -- )
  7521. AND ccp.IsAuditGM != 2
  7522. AND hr.DiId = di.Id
  7523. ) AS 'HotelTotal',
  7524. (
  7525. SELECT
  7526. Count(1)
  7527. FROM
  7528. Grp_CarTouristGuideGroundReservations ctggr
  7529. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  7530. AND ccp.CTable = 79
  7531. AND ctggr.Id = ccp.CId
  7532. WHERE
  7533. ctggr.IsDel = 0 -- AND (
  7534. -- ccp.IsAuditGM = 1
  7535. -- OR ccp.IsAuditGM = 3
  7536. -- )
  7537. AND ccp.IsAuditGM != 2
  7538. AND ctggr.DiId = di.Id
  7539. ) AS 'LocalGuideTotal',
  7540. (
  7541. SELECT
  7542. Count(1)
  7543. FROM
  7544. Grp_AirTicketReservations atr
  7545. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7546. AND ccp.CTable = 85
  7547. AND atr.Id = ccp.CId
  7548. WHERE
  7549. atr.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7550. AND ccp.IsAuditGM != 2
  7551. AND atr.DIId = di.Id
  7552. ) AS 'AirTicketToal',
  7553. (
  7554. SELECT
  7555. Count(1)
  7556. FROM
  7557. Grp_VisaInfo vi
  7558. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7559. AND ccp.CTable = 80
  7560. AND vi.Id = ccp.CId
  7561. WHERE
  7562. vi.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7563. AND ccp.IsAuditGM != 2
  7564. AND vi.DIId = di.Id
  7565. ) AS 'VisaTotal',
  7566. (
  7567. SELECT
  7568. Count(1)
  7569. FROM
  7570. Grp_InvitationOfficialActivities ioa
  7571. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7572. AND ccp.CTable = 81
  7573. AND ioa.Id = ccp.CId
  7574. WHERE
  7575. ioa.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7576. AND ccp.IsAuditGM != 2
  7577. AND ioa.DiId = di.Id
  7578. ) AS 'OATotal',
  7579. (
  7580. SELECT
  7581. Count(1)
  7582. FROM
  7583. Grp_Customers ic
  7584. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7585. AND ccp.CTable = 82
  7586. AND ic.Id = ccp.CId
  7587. WHERE
  7588. ic.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7589. AND ccp.IsAuditGM != 2
  7590. AND ic.DiId = di.Id
  7591. ) AS 'InsureTotal',
  7592. (
  7593. SELECT
  7594. Count(1)
  7595. FROM
  7596. Grp_DecreasePayments dp
  7597. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  7598. AND ccp.CTable = 98
  7599. AND dp.Id = ccp.CId
  7600. WHERE
  7601. dp.IsDel = 0 -- AND ccp.IsAuditGM = 1
  7602. AND ccp.IsAuditGM != 2
  7603. AND dp.Diid = di.Id
  7604. ) AS 'OtherTotal'
  7605. FROM
  7606. OA2023DB.dbo.Grp_DelegationInfo di
  7607. LEFT JOIN Sys_SetData ss ON di.TeamDid = ss.Id
  7608. WHERE
  7609. di.IsDel = 0
  7610. AND di.IsBid = 0
  7611. AND di.Id IN({0})", string.Join(",", groupIds));
  7612. return await _sqlSugar.SqlQueryable<CorporateProfitFeeCount>(sql).ToArrayAsync();
  7613. }
  7614. /// <summary>
  7615. /// 团组利润item详情
  7616. /// </summary>
  7617. /// <param name="type">
  7618. /// 1:详情
  7619. /// 2:excel 生成
  7620. /// </param>
  7621. /// <param name="begin"></param>
  7622. /// <param name="end"></param>
  7623. /// <returns></returns>
  7624. private async Task<CorporateProfitItemView> CorporateProfitItems(int type, string begin, string end)
  7625. {
  7626. var data = await CorporateProfitInfos(begin, end);
  7627. var groupItems = data.GroupItems;
  7628. var dailyItems = data.DailyItems;
  7629. var companyDailyItems = dailyItems
  7630. .Where(x => !_priceTypeIds.Contains(x.PriceTypeId))
  7631. .GroupBy(x => x.CompanyName)
  7632. .Select(g => new { CompanyName = g.Key, CNYTotal = g.Sum(x => x.CNYTotal) })
  7633. .OrderBy(x => x.CNYTotal)
  7634. .ToArray();
  7635. //业务类型
  7636. var groupTypeIds = new List<int>() {
  7637. 38, // 政府团
  7638. 39, // 企业团
  7639. 40, // 散客团
  7640. 1048 // 高校团
  7641. };
  7642. var inforTypeIds = new List<int>() {
  7643. 302, // 成都-会务活动
  7644. 691, // 四川-会务活动
  7645. 1539, // 纽茵-会务活动
  7646. 1548 // 重庆-会务活动
  7647. };
  7648. //团组 收款、成本、利润 合计
  7649. var groupCollectionTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7650. var groupReceivableTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7651. var groupCostTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7652. var groupProfitTotal = groupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7653. //非团组 收款、成本、利润 合计
  7654. var notGroupCollectionTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CollectionTotal);
  7655. var notGroupReceivableTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableProfitTotal);
  7656. var notGroupCostTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal);
  7657. var notGroupProfitTotal = groupItems.Where(x => !groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ProfitTotal);
  7658. //会务数量
  7659. int inforCount = groupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count();
  7660. //服务人数
  7661. int serviceCount = groupItems.Sum(x => x.VisitPNumber);
  7662. //总利润
  7663. decimal totalProfit = groupProfitTotal + notGroupProfitTotal;
  7664. var dailyLabel = $"*不含日付费用类型(信用卡还款、张总私人费用、代报销社保生育补贴、人事行政费用 - 张总家用类、会展部备用金、团组签证保险)\r\n";
  7665. var dailyExcelLabel = dailyLabel;
  7666. if (companyDailyItems.Any())
  7667. {
  7668. foreach (var dailyFee in companyDailyItems)
  7669. {
  7670. dailyLabel += $"<p>[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal:#0.00} CNY </p>";
  7671. dailyExcelLabel += $"[{dailyFee.CompanyName}]日常产生费用:{dailyFee.CNYTotal:#0.00} CNY \r\n";
  7672. }
  7673. }
  7674. string label = string.Format(@$"<div style='color:black'><p>团组收款合计:{groupCollectionTotal:#0.00} CNY&nbsp;团组产生费用合计:{groupCostTotal:#0.00} CNY&nbsp;团组利润合计:{groupProfitTotal:#0.00} CNY</p><p>非团组收款合计:{notGroupCollectionTotal:#0.00} CNY&nbsp;非团组产生费用合计:{notGroupCostTotal:#0.00} CNY&nbsp;非团组利润合计:{notGroupProfitTotal.ToString("#0.00")} CNY</p>{dailyLabel}<p>其中会务:{inforCount}个</p><p>服务人数:{serviceCount}人</p>总利润:{totalProfit:#0.00} CNY</div>");
  7675. var datas = _mapper.Map<CorporateProfitItem[]>(groupItems);
  7676. if (type == 2) //excel 下载
  7677. {
  7678. var designer = new WorkbookDesigner();
  7679. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/团组利润模板.xls";
  7680. designer.Workbook = new Workbook(tempPath);
  7681. designer.SetDataSource("ReceivablesTemp", datas);
  7682. designer.SetDataSource("ReceivableProfitTotal", groupReceivableTotal.ToString("#0.00"));
  7683. designer.SetDataSource("NotReceivableProfitTotal", notGroupReceivableTotal.ToString("#0.00"));
  7684. designer.SetDataSource("SumAccounts", groupCollectionTotal.ToString("#0.00"));
  7685. designer.SetDataSource("SumReceived", groupCostTotal.ToString("#0.00"));
  7686. designer.SetDataSource("SumBalance", groupProfitTotal.ToString("#0.00"));
  7687. designer.SetDataSource("notSumAccounts", notGroupCollectionTotal.ToString("#0.00"));
  7688. designer.SetDataSource("notSumReceived", notGroupCostTotal.ToString("#0.00"));
  7689. designer.SetDataSource("SumOfNotTeamBalance", notGroupProfitTotal.ToString("#0.00"));
  7690. designer.SetDataSource("DailyLabel", dailyExcelLabel);
  7691. designer.SetDataSource("MeetingNumber", inforCount + "个");
  7692. designer.SetDataSource("ServiceNumber", serviceCount + "人");
  7693. designer.SetDataSource("SumAllBalance", totalProfit.ToString("#0.00"));
  7694. //根据数据源处理生成报表内容
  7695. designer.Process();
  7696. string fileName = $"团组利润({Convert.ToDateTime(begin).ToString("yyyy年MM月dd日")}~{Convert.ToDateTime(end).ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  7697. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7698. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7699. label = url;
  7700. }
  7701. return new CorporateProfitItemView()
  7702. {
  7703. Items = datas,
  7704. Label = label
  7705. };
  7706. }
  7707. /// <summary>
  7708. /// 企业利润
  7709. /// Item
  7710. /// </summary>
  7711. /// <param name="dto"></param>
  7712. /// <returns></returns>
  7713. [HttpPost("CorporateProfitItem")]
  7714. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7715. public async Task<IActionResult> CorporateProfitItem(CorporateProfitItemDto dto)
  7716. {
  7717. int portType = dto.PortType,
  7718. userId = dto.UserId,
  7719. pageId = dto.PageId;
  7720. #region 参数验证
  7721. //var validationRules = new CorporateProfitItemDtoFoalidator();
  7722. //var validResult = await validationRules.ValidateAsync(dto);
  7723. //if (!validResult.IsValid)
  7724. //{
  7725. // var errors = new StringBuilder();
  7726. // foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7727. // return Ok(JsonView(false, errors.ToString()));
  7728. //}
  7729. //#region 页面操作权限验证
  7730. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId, pageId);
  7731. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  7732. //#endregion
  7733. #endregion
  7734. string beginDt = $"{dto.BeginDt} 00:00:00",
  7735. endDt = $"{dto.EndDt} 23:59:59";
  7736. return Ok(JsonView(true, "操作成功!", await CorporateProfitItems(1, beginDt, endDt)));
  7737. }
  7738. /// <summary>
  7739. /// 企业利润 Excel导出
  7740. /// </summary>
  7741. /// <param name="dto"></param>
  7742. /// <returns></returns>
  7743. [HttpPost("CorporateProfitExcelDownload")]
  7744. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  7745. public async Task<IActionResult> CorporateProfitExcelDownload(CorporateProfitExcelDownloadDto dto)
  7746. {
  7747. int portType = dto.PortType,
  7748. userId = dto.UserId,
  7749. pageId = dto.PageId,
  7750. excelType = dto.ExcelType;
  7751. #region 参数验证
  7752. var validationRules = new CorporateProfitExcelDownloadDtoFoalidator();
  7753. var validResult = await validationRules.ValidateAsync(dto);
  7754. if (!validResult.IsValid)
  7755. {
  7756. var errors = new StringBuilder();
  7757. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  7758. return Ok(JsonView(false, errors.ToString()));
  7759. }
  7760. #region 页面操作权限验证
  7761. //var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(userId,pageId);
  7762. //if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
  7763. #endregion
  7764. #endregion
  7765. // 基础转换:解析传入的起止时间
  7766. DateTime beginDate = DateTime.Parse(dto.BeginDt).Date; // 强制取 00:00:00
  7767. DateTime endDate = DateTime.Parse(dto.EndDt).Date.AddDays(1).AddSeconds(-1); // 强制取 23:59:59
  7768. // 本月:按照时间范围的【最大月份】起止时间
  7769. // 逻辑:以 endDate 为基准,计算它所在月份的第一天和最后一天
  7770. DateTime monthBase = endDate;
  7771. DateTime monthBegin = new DateTime(monthBase.Year, monthBase.Month, 1);
  7772. DateTime monthEnd = monthBegin.AddMonths(1).AddSeconds(-1); // 自动处理 28/30/31 天及跨年
  7773. var montData = await CorporateProfitInfos(monthBegin.ToString("yyyy-MM-dd HH:mm:ss"), monthEnd.ToString("yyyy-MM-dd HH:mm:ss"));
  7774. var monthGroupItems = montData.GroupItems;
  7775. var monthDailyItems = montData.DailyItems;
  7776. var yearData = await CorporateProfitInfos(beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  7777. var yearGroupItems = yearData.GroupItems;
  7778. var yearDailyItems = yearData.DailyItems;
  7779. //筛选不统计的费用类型
  7780. //if (yearDailyItems.Any()) yearDailyItems = yearDailyItems.Where(x => !priceTypeIds.Contains(x.PriceTypeId)).ToArray();
  7781. #region 公共参数
  7782. //团组收款、成本、利润 合计
  7783. decimal monthGroupCollectionTotal = monthGroupItems.Sum(x => x.CollectionTotal),
  7784. monthGroupCostTotal = monthGroupItems.Sum(x => x.CostTotal),
  7785. yearGroupCollectionTotal = yearGroupItems.Sum(x => x.CollectionTotal),
  7786. yearGroupCostTotal = yearGroupItems.Sum(x => x.CostTotal);
  7787. // 日付申请 48 人员费用、 49 办公费用、50 销售费用、51 其他费用、55 大运会、90 各部门基础固定费用明细
  7788. decimal monthStaffCosts = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7789. monthOfficeExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7790. monthCostSales = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7791. monthOtherFees = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7792. monthDyhFees = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7793. monthDepartFixedExpenses = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal),
  7794. yearStaffCosts = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.CNYTotal),
  7795. yearOfficeExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.CNYTotal),
  7796. yearCostSales = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.CNYTotal),
  7797. yearOtherFees = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.CNYTotal),
  7798. yearDyhFees = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.CNYTotal),
  7799. yearDepartFixedExpenses = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.CNYTotal);
  7800. #endregion
  7801. //月度报表、季度报表、年度报表
  7802. if (excelType == 1 || excelType == 2 || excelType == 3)
  7803. {
  7804. var designer = new WorkbookDesigner();
  7805. string fileName = $"({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls",
  7806. fileNamePrefix = string.Empty,
  7807. tempPath = string.Empty,
  7808. workSheetName = string.Empty;
  7809. if (excelType == 1)
  7810. {
  7811. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/月度报表模板.xls";
  7812. workSheetName = "月度报表";
  7813. fileNamePrefix = "月度报表";
  7814. }
  7815. else if (excelType == 2)
  7816. {
  7817. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/季度报表模板.xls";
  7818. workSheetName = "季度报表";
  7819. fileNamePrefix = "季度报表";
  7820. }
  7821. else if (excelType == 3)
  7822. {
  7823. tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/年度报表模板.xls";
  7824. workSheetName = "年度报表";
  7825. fileNamePrefix = "年度报表";
  7826. }
  7827. else return Ok(JsonView(false));
  7828. designer.Workbook = new Workbook(tempPath);
  7829. designer.Workbook.Worksheets[0].Name = workSheetName;
  7830. #region 填充值
  7831. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7832. designer.SetDataSource("Time", time);
  7833. designer.SetDataSource("MonthReceivedPrice", monthGroupCollectionTotal.ToString("#0.00"));//本月已收
  7834. designer.SetDataSource("YearReceivedPrice", yearGroupCollectionTotal.ToString("#0.00")); //本年已收
  7835. designer.SetDataSource("MonthSumReceives", monthGroupCollectionTotal.ToString("#0.00"));//本月团组收款
  7836. designer.SetDataSource("MonthTeamCost", monthGroupCostTotal.ToString("#0.00")); //本月团组成本
  7837. designer.SetDataSource("YearSumReceives", yearGroupCollectionTotal.ToString("#0.00"));//本年团组收款
  7838. designer.SetDataSource("YearTeamCost", yearGroupCostTotal.ToString("#0.00")); //本年团组成本
  7839. designer.SetDataSource("MonthStaffCosts", monthStaffCosts.ToString("#0.00"));//本月人员费用
  7840. designer.SetDataSource("YearStaffCosts", yearStaffCosts.ToString("#0.00")); //本年人员费用
  7841. designer.SetDataSource("MonthOfficeExpenses", monthOfficeExpenses.ToString("#0.00"));//本月办公费用
  7842. designer.SetDataSource("YearOfficeExpenses", yearOfficeExpenses.ToString("#0.00")); //本年办公费用
  7843. designer.SetDataSource("MonthCostSales", monthCostSales.ToString("#0.00"));//本月销售费用
  7844. designer.SetDataSource("YearCostSales", yearCostSales.ToString("#0.00")); //本年销售费用
  7845. designer.SetDataSource("MonthOtherFees", monthOtherFees.ToString("#0.00"));//本月其他费用
  7846. designer.SetDataSource("YearOtherFees", yearOtherFees.ToString("#0.00")); //本年其他费用
  7847. designer.SetDataSource("MonthDYHFees", monthDyhFees.ToString("#0.00"));//本月大运会费用
  7848. designer.SetDataSource("YearDYHFees", yearDyhFees.ToString("#0.00")); //本年大运会费用
  7849. designer.SetDataSource("MonthDepartFixedFees", monthDepartFixedExpenses.ToString("#0.00"));//本月各部门基础固定费用明细费用
  7850. designer.SetDataSource("YearDepartFixedFees", yearDepartFixedExpenses.ToString("#0.00")); //本年各部门基础固定费用明细费用
  7851. // 填表时间
  7852. string fillingTime = $"填报时间:{DateTime.Now:yyyy.MM.dd}";
  7853. designer.SetDataSource("FillingTime", fillingTime);
  7854. #endregion
  7855. //根据数据源处理生成报表内容
  7856. designer.Process();
  7857. fileName = fileNamePrefix + fileName;
  7858. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  7859. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  7860. return Ok(JsonView(true, "操作成功!", url));
  7861. }
  7862. //利润报表
  7863. else if (excelType == 4)
  7864. {
  7865. var designer = new WorkbookDesigner();
  7866. var tempPath = $"{AppSettingsHelper.Get("ExcelBasePath")}Template/利润报表New.xlsx";
  7867. designer.Workbook = new Workbook(tempPath);
  7868. #region 填充值
  7869. string time = $"所属期间: {beginDate.ToString("yyyy 年 MM 月 dd 日")} 至 {endDate.ToString("yyyy 年 MM 月 dd 日")}";
  7870. designer.SetDataSource("Time", time);
  7871. //业务类型
  7872. var groupTypeIds = new List<int>() {
  7873. 38, // 政府团
  7874. 39, // 企业团
  7875. 40, // 散客团
  7876. 1048 // 高校团
  7877. };
  7878. var inforTypeIds = new List<int>() {
  7879. 302, // 成都-会务活动
  7880. 691, // 四川-会务活动
  7881. 1539, // 纽茵-会务活动
  7882. 1548 // 重庆-会务活动
  7883. };
  7884. var competitionTypeIds = new List<int>() {
  7885. 762, // 四川-赛事项目收入
  7886. 1047, // 成都-赛事项目收入
  7887. };
  7888. var otherTypeIds = new List<int>();
  7889. otherTypeIds.AddRange(groupTypeIds);
  7890. otherTypeIds.AddRange(inforTypeIds);
  7891. otherTypeIds.AddRange(competitionTypeIds);
  7892. decimal monthAllIncomes = monthGroupItems.Sum(x => x.ReceivableAmount), //月-收入
  7893. monthTzIncomes = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7894. monthHwIncomes = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7895. monthSsIncomes = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7896. monthQtIncomes = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7897. monthAllCost = monthGroupItems.Sum(x => x.CostTotal), //月-成本
  7898. monthTzCost = monthGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7899. monthHwCost = monthGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7900. monthSsCost = monthGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7901. monthQtCost = monthGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7902. monthAllGross = monthAllIncomes - monthAllCost, //月-毛利金额
  7903. monthTzGross = monthTzIncomes - monthTzCost,
  7904. monthHwGross = monthHwIncomes - monthHwCost,
  7905. monthSsGross = monthSsIncomes - monthSsCost,
  7906. monthQtGross = monthQtIncomes - monthQtCost,
  7907. yearAllIncomes = yearGroupItems.Sum(x => x.ReceivableAmount), //年-收入
  7908. yearTzIncomes = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7909. yearHwIncomes = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7910. yearSsIncomes = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7911. yearQtIncomes = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.ReceivableAmount),
  7912. yearAllCost = yearGroupItems.Sum(x => x.CostTotal), //年-成本
  7913. yearTzCost = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7914. yearHwCost = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7915. yearSsCost = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7916. yearQtCost = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Sum(x => x.CostTotal),
  7917. yearAllGross = yearAllIncomes - yearAllCost, //年-毛利金额
  7918. yearTzGross = yearTzIncomes - yearTzCost,
  7919. yearHwGross = yearHwIncomes - yearHwCost,
  7920. yearSsGross = yearSsIncomes - yearSsCost,
  7921. yearQtGross = yearQtIncomes - yearQtCost;
  7922. //年-团数量
  7923. int yearAllCount = yearGroupItems.Length,
  7924. yearTzCount = yearGroupItems.Where(x => groupTypeIds.Contains(x.TeamDid)).Count(),
  7925. yearHwCount = yearGroupItems.Where(x => inforTypeIds.Contains(x.TeamDid)).Count(),
  7926. yearSsCount = yearGroupItems.Where(x => competitionTypeIds.Contains(x.TeamDid)).Count(),
  7927. yearQtCount = yearGroupItems.Where(x => !otherTypeIds.Contains(x.TeamDid)).Count();
  7928. //年-利率
  7929. string yearAllRate = "0.00 %",
  7930. yearTzRate = "0.00 %",
  7931. yearHwRate = "0.00 %",
  7932. yearSsRate = "0.00 %",
  7933. yearQtRate = "0.00 %";
  7934. if (yearAllIncomes != 0) yearAllRate = (yearAllGross / yearAllIncomes * 100).ToString("#0.00") + "%";
  7935. if (yearTzIncomes != 0) yearTzRate = (yearTzGross / yearTzIncomes * 100).ToString("#0.00") + "%";
  7936. if (yearHwIncomes != 0) yearHwRate = (yearHwGross / yearHwIncomes * 100).ToString("#0.00") + "%";
  7937. if (yearSsIncomes != 0) yearSsRate = (yearSsGross / yearSsIncomes * 100).ToString("#0.00") + "%";
  7938. if (yearQtIncomes != 0) yearQtRate = (yearQtGross / yearQtIncomes * 100).ToString("#0.00") + "%";
  7939. #region 月
  7940. //收入
  7941. designer.SetDataSource("MonthAllIncomes", monthAllIncomes.ToString("#0.00"));
  7942. designer.SetDataSource("MonthtzIncomes", monthTzIncomes.ToString("#0.00"));
  7943. designer.SetDataSource("MonthhwIncomes", monthHwIncomes.ToString("#0.00"));
  7944. designer.SetDataSource("MonthssIncomes", monthSsIncomes.ToString("#0.00"));
  7945. designer.SetDataSource("MonthqtIncomes", monthQtIncomes.ToString("#0.00"));
  7946. //成本
  7947. designer.SetDataSource("MonthAllCost", monthAllCost.ToString("#0.00"));
  7948. designer.SetDataSource("MonthtzCost", monthTzCost.ToString("#0.00"));
  7949. designer.SetDataSource("MonthhwCost", monthHwCost.ToString("#0.00"));
  7950. designer.SetDataSource("MonthssCost", monthSsCost.ToString("#0.00"));
  7951. designer.SetDataSource("MonthqtCost", monthQtCost.ToString("#0.00"));
  7952. //毛利金额
  7953. designer.SetDataSource("MonthAllGross", monthAllGross.ToString("#0.00"));
  7954. designer.SetDataSource("MonthtzGross", monthTzGross.ToString("#0.00"));
  7955. designer.SetDataSource("MonthhwGross", monthHwGross.ToString("#0.00"));
  7956. designer.SetDataSource("MonthssGross", monthSsGross.ToString("#0.00"));
  7957. designer.SetDataSource("MonthqtGross", monthQtGross.ToString("#0.00"));
  7958. #endregion
  7959. #region 年
  7960. //收入
  7961. designer.SetDataSource("YearAllIncomes", yearAllIncomes.ToString("#0.00"));
  7962. designer.SetDataSource("YeartzIncomes", yearTzIncomes.ToString("#0.00"));
  7963. designer.SetDataSource("YearhwIncomes", yearHwIncomes.ToString("#0.00"));
  7964. designer.SetDataSource("YearssIncomes", yearSsIncomes.ToString("#0.00"));
  7965. designer.SetDataSource("YearqtIncomes", yearQtIncomes.ToString("#0.00"));
  7966. //成本
  7967. designer.SetDataSource("YearAllCost", yearAllCost.ToString("#0.00"));
  7968. designer.SetDataSource("YeartzCost", yearTzCost.ToString("#0.00"));
  7969. designer.SetDataSource("YearhwCost", yearHwCost.ToString("#0.00"));
  7970. designer.SetDataSource("YearssCost", yearSsCost.ToString("#0.00"));
  7971. designer.SetDataSource("YearqtCost", yearQtCost.ToString("#0.00"));
  7972. //毛利金额
  7973. designer.SetDataSource("YearAllGross", yearAllGross.ToString("#0.00"));
  7974. designer.SetDataSource("YeartzGross", yearTzGross.ToString("#0.00"));
  7975. designer.SetDataSource("YearhwGross", yearHwGross.ToString("#0.00"));
  7976. designer.SetDataSource("YearssGross", yearSsGross.ToString("#0.00"));
  7977. designer.SetDataSource("YearqtGross", yearQtGross.ToString("#0.00"));
  7978. //毛利率
  7979. designer.SetDataSource("YearAllRate", yearAllRate);
  7980. designer.SetDataSource("YeartzRate", yearTzRate);
  7981. designer.SetDataSource("YearhwRate", yearHwRate);
  7982. designer.SetDataSource("YearssRate", yearSsRate);
  7983. designer.SetDataSource("YearqtRate", yearQtRate);
  7984. //数量
  7985. designer.SetDataSource("AllCount", yearAllCount.ToString());
  7986. designer.SetDataSource("tzCount", yearTzCount.ToString());
  7987. designer.SetDataSource("hwCount", yearHwCount.ToString());
  7988. designer.SetDataSource("ssCount", yearSsCount.ToString());
  7989. designer.SetDataSource("qtCount", yearQtCount.ToString());
  7990. #endregion
  7991. #region 日付相关
  7992. var dailyViewItems = new List<CorporateProfitDailyView>();
  7993. var dailyTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  7994. var conmmentTexts = new List<CorporateProfitDailyCommentView>();
  7995. #region 员工费用 48
  7996. decimal monthStaffCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal),
  7997. yearStaffCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 48).Sum(x => x.ItemTotal);
  7998. dailyViewItems.Add(new CorporateProfitDailyView() { No = "一", PriceName = "人员费用", ThisMonthAmount = monthStaffCostTotal, ThisYearAmount = yearStaffCostTotal });
  7999. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8000. {
  8001. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray()),
  8002. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 48).ToArray())
  8003. });
  8004. var dailyStaffTypes = dailyTypes.Where(x => x.STid == 48).OrderBy(x => x.Id).ToList();
  8005. foreach (var item in dailyStaffTypes)
  8006. {
  8007. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8008. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8009. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8010. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8011. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8012. {
  8013. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8014. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8015. });
  8016. }
  8017. #endregion
  8018. #region 办公费用
  8019. decimal monthWorkCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal), //总费用
  8020. yearWorkCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 49).Sum(x => x.ItemTotal);
  8021. dailyViewItems.Add(new CorporateProfitDailyView() { No = "二", PriceName = "办公费用", ThisMonthAmount = monthWorkCostTotal, ThisYearAmount = yearWorkCostTotal });
  8022. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8023. {
  8024. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray()),
  8025. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 49).ToArray())
  8026. });
  8027. var dailyWorkTypes = dailyTypes.Where(x => x.STid == 49).OrderBy(x => x.Id).ToList();
  8028. foreach (var item in dailyWorkTypes)
  8029. {
  8030. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8031. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8032. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8033. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8034. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8035. {
  8036. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8037. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8038. });
  8039. }
  8040. #endregion
  8041. #region 销售费用
  8042. decimal monthSalesCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal), //总费用
  8043. yearSalesCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 50).Sum(x => x.ItemTotal);
  8044. dailyViewItems.Add(new CorporateProfitDailyView() { No = "三", PriceName = "销售费用", ThisMonthAmount = monthSalesCostTotal, ThisYearAmount = yearSalesCostTotal });
  8045. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8046. {
  8047. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray()),
  8048. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 50).ToArray())
  8049. });
  8050. var dailySalesTypes = dailyTypes.Where(x => x.STid == 50).OrderBy(x => x.Id).ToList();
  8051. foreach (var item in dailySalesTypes)
  8052. {
  8053. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8054. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8055. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8056. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8057. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8058. {
  8059. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8060. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8061. });
  8062. }
  8063. #endregion
  8064. #region 51 其他费用
  8065. decimal monthOtherCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal), //总费用
  8066. yearOtherCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 51).Sum(x => x.ItemTotal);
  8067. dailyViewItems.Add(new CorporateProfitDailyView() { No = "四", PriceName = "其他费用", ThisMonthAmount = monthOtherCostTotal, ThisYearAmount = yearOtherCostTotal });
  8068. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8069. {
  8070. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray()),
  8071. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 51).ToArray())
  8072. });
  8073. var dailyOtherTypes = dailyTypes.Where(x => x.STid == 51).OrderBy(x => x.Id).ToList();
  8074. foreach (var item in dailyOtherTypes)
  8075. {
  8076. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8077. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8078. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8079. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8080. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8081. {
  8082. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8083. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8084. });
  8085. }
  8086. #endregion
  8087. #region 55 大运会
  8088. decimal monthDyhCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal), //总费用
  8089. yearDyhCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 55).Sum(x => x.ItemTotal);
  8090. dailyViewItems.Add(new CorporateProfitDailyView() { No = "五", PriceName = "大运会", ThisMonthAmount = monthDyhCostTotal, ThisYearAmount = yearDyhCostTotal });
  8091. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8092. {
  8093. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray()),
  8094. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 55).ToArray())
  8095. });
  8096. var dailyDyhTypes = dailyTypes.Where(x => x.STid == 55).OrderBy(x => x.Id).ToList();
  8097. foreach (var item in dailyDyhTypes)
  8098. {
  8099. string priceName = !string.IsNullOrEmpty(item.Remark) ? item.Remark : item.Name;
  8100. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8101. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8102. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8103. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8104. {
  8105. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8106. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8107. });
  8108. }
  8109. #endregion
  8110. #region 90 各部门基础固定费用明细
  8111. decimal monthBasicCostTotal = monthDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal), //总费用
  8112. yearBasicCostTotal = yearDailyItems.Where(x => x.PriceParentTypeId == 90).Sum(x => x.ItemTotal);
  8113. dailyViewItems.Add(new CorporateProfitDailyView() { No = "六", PriceName = "各部门基础固定费用明细", ThisMonthAmount = monthBasicCostTotal, ThisYearAmount = yearBasicCostTotal });
  8114. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8115. {
  8116. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray()),
  8117. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceParentTypeId == 90).ToArray())
  8118. });
  8119. var dailyBasicTypes = dailyTypes.Where(x => x.STid == 90).OrderBy(x => x.Id).ToList();
  8120. foreach (var item in dailyBasicTypes)
  8121. {
  8122. string priceName = item.Name;
  8123. decimal monthAmount = monthDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal),
  8124. yearAmount = yearDailyItems.Where(x => x.PriceTypeId == item.Id).Sum(x => x.ItemTotal);
  8125. dailyViewItems.Add(new CorporateProfitDailyView() { PriceName = priceName, ThisMonthAmount = monthAmount, ThisYearAmount = yearAmount });
  8126. conmmentTexts.Add(new CorporateProfitDailyCommentView()
  8127. {
  8128. MonthComment = DailyListToString(monthDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray()),
  8129. YearComment = DailyListToString(yearDailyItems.Where(x => x.PriceTypeId == item.Id).ToArray())
  8130. });
  8131. }
  8132. #endregion
  8133. // 办公费用
  8134. // 月
  8135. decimal officePirceMonth = monthStaffCostTotal + monthWorkCostTotal + monthSalesCostTotal + monthOtherCostTotal + monthDyhCostTotal + monthBasicCostTotal;
  8136. designer.SetDataSource("officePirceMonth", officePirceMonth.ToString("#0.00"));
  8137. // 年
  8138. decimal officePirceYear = yearStaffCostTotal + yearWorkCostTotal + yearSalesCostTotal + yearOtherCostTotal + yearDyhCostTotal + yearBasicCostTotal;
  8139. designer.SetDataSource("officePirceYear", officePirceYear.ToString("#0.00"));
  8140. // 排除不统计的费用类型后的小计
  8141. // 月
  8142. decimal officePirceMonth1 = monthDailyItems.Where(x => !_priceTypeIds.Contains(x.PriceTypeId)).Sum(x => x.ItemTotal);
  8143. designer.SetDataSource("officePirceMonth1", officePirceMonth1.ToString("#0.00"));
  8144. // 年
  8145. decimal officePirceYear1 = yearDailyItems.Where(x => !_priceTypeIds.Contains(x.PriceTypeId)).Sum(x => x.ItemTotal);
  8146. designer.SetDataSource("officePirceYear1", officePirceYear1.ToString("#0.00"));
  8147. //designer.SetDataSource("DailyView", dailyViewItems);
  8148. var dt = CommonFun.ToDataTableArray(dailyViewItems);
  8149. dt.TableName = "DailyView";
  8150. designer.SetDataSource(dt);
  8151. #endregion
  8152. #endregion
  8153. //根据数据源处理生成报表内容
  8154. designer.Process();
  8155. var dailySheet = designer.Workbook.Worksheets[1];
  8156. //渲染批注
  8157. for (int i = 0; i < dailyViewItems.Count; i++)
  8158. {
  8159. string monthComment = $"C{i + 3}",
  8160. yearComment = $"D{i + 3}";
  8161. int monthCommentIndex = dailySheet.Comments.Add(monthComment),
  8162. yearCommentIndex = dailySheet.Comments.Add(yearComment);
  8163. if (dailyViewItems[i].ThisMonthAmount != 0.00M)
  8164. {
  8165. string commentText1 = conmmentTexts[i].MonthComment;
  8166. Aspose.Cells.Comment comment = dailySheet.Comments[monthCommentIndex];
  8167. comment.Note = commentText1;
  8168. comment.Width = 400;
  8169. comment.Height = 400;
  8170. comment.Font.Color = Color.Red;
  8171. }
  8172. if (dailyViewItems[i].ThisYearAmount != 0.00M)
  8173. {
  8174. string commentText2 = conmmentTexts[i].YearComment;
  8175. Aspose.Cells.Comment comment = dailySheet.Comments[yearCommentIndex];
  8176. comment.Note = commentText2;
  8177. comment.Width = 400;
  8178. comment.Height = 400;
  8179. comment.Font.Color = Color.Red;
  8180. }
  8181. }
  8182. string fileName = $"利润报表({beginDate.ToString("yyyy年MM月dd日")}~{endDate.ToString("yyyy年MM月dd日")}){Guid.NewGuid().ToString()}.xls";
  8183. designer.Workbook.Save($"{AppSettingsHelper.Get("ExcelBasePath")}CorporateProfit/{fileName}");
  8184. string url = $"{AppSettingsHelper.Get("ExcelBaseUrl")}Office/Excel/CorporateProfit/{fileName}";
  8185. return Ok(JsonView(true, "操作成功!", url));
  8186. }
  8187. else if (excelType == 5)
  8188. {
  8189. var view = await CorporateProfitItems(2, beginDate.ToString("yyyy-MM-dd HH:mm:ss"), endDate.ToString("yyyy-MM-dd HH:mm:ss"));
  8190. return Ok(JsonView(true, "操作成功!", view.Label));
  8191. }
  8192. return Ok(JsonView(false));
  8193. }
  8194. private static string DailyListToString(DailyInfo[] infos)
  8195. {
  8196. StringBuilder sb = new StringBuilder();
  8197. int index = 1;
  8198. foreach (var info in infos)
  8199. {
  8200. sb.Append(index + "、");
  8201. sb.Append($"[{info.ItemTotal.ToString("#0.00")}]:{info.PriceName};");
  8202. sb.Append(Environment.NewLine);
  8203. index++;
  8204. }
  8205. return sb.ToString();
  8206. }
  8207. #endregion
  8208. }
  8209. }