StatisticsController.cs 297 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307
  1. using Aspose.Cells;
  2. using Aspose.Words.Tables;
  3. using Microsoft.AspNetCore.Mvc.ViewEngines;
  4. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  5. using MySqlX.XDevAPI.Relational;
  6. using NetUV.Core.Handles;
  7. using NPOI.POIFS.Properties;
  8. using NPOI.SS.Formula.Functions;
  9. using NPOI.SS.Formula.PTG;
  10. using OASystem.API.OAMethodLib;
  11. using OASystem.Domain.AesEncryption;
  12. using OASystem.Domain.Dtos.Statistics;
  13. using OASystem.Domain.Entities.Customer;
  14. using OASystem.Domain.Entities.Groups;
  15. using OASystem.Domain.ViewModels.Financial;
  16. using OASystem.Domain.ViewModels.QiYeWeChat;
  17. using OASystem.Domain.ViewModels.Statistics;
  18. using OASystem.Infrastructure.Repositories.Groups;
  19. using System;
  20. using System.Data;
  21. using static OASystem.API.OAMethodLib.GeneralMethod;
  22. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  23. namespace OASystem.API.Controllers
  24. {
  25. /// <summary>
  26. /// 统计模块
  27. /// </summary>
  28. [Route("api/[controller]")]
  29. [ApiController]
  30. public class StatisticsController : ControllerBase
  31. {
  32. private readonly int _decimalPlaces;
  33. private readonly IConfiguration _config;
  34. private readonly IMapper _mapper;
  35. private readonly SqlSugarClient _sqlSugar;
  36. private readonly DelegationInfoRepository _groupRep;
  37. private readonly SetDataRepository _setDataRep;
  38. private readonly TeamRateRepository _teamRateRep;
  39. private readonly VisitingClientsRepository _visitingClientsRep;
  40. /// <summary>
  41. /// Init
  42. /// </summary>
  43. /// <param name="mapper"></param>
  44. /// <param name="sqlSugar"></param>
  45. /// <param name="groupRep"></param>
  46. /// <param name="setDataRep"></param>
  47. public StatisticsController(
  48. IMapper mapper,
  49. IConfiguration config,
  50. SqlSugarClient sqlSugar,
  51. DelegationInfoRepository groupRep,
  52. SetDataRepository setDataRep,
  53. TeamRateRepository teamRate,
  54. VisitingClientsRepository visitingClientsRep
  55. )
  56. {
  57. _mapper = mapper;
  58. _config = config;
  59. _groupRep = groupRep;
  60. _setDataRep = setDataRep;
  61. _sqlSugar = sqlSugar;
  62. _teamRateRep = teamRate;
  63. _visitingClientsRep = visitingClientsRep;
  64. }
  65. #region 团组报表
  66. /// <summary>
  67. /// 团组报表
  68. /// Items
  69. /// </summary>
  70. /// <param name="_dto">团组列表请求dto</param>
  71. /// <returns></returns>
  72. [HttpPost("PostGroupStatementItems")]
  73. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  74. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  75. {
  76. #region 参数验证
  77. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  78. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  79. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  80. #region 页面操作权限验证
  81. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  82. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  83. #endregion
  84. #endregion
  85. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  86. {
  87. string sqlWhere = string.Empty;
  88. if (_dto.IsSure == 0) //未完成
  89. {
  90. sqlWhere += string.Format(@" And IsSure = 0");
  91. }
  92. else if (_dto.IsSure == 1) //已完成
  93. {
  94. sqlWhere += string.Format(@" And IsSure = 1");
  95. }
  96. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  97. {
  98. string tj = _dto.SearchCriteria;
  99. sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or ClientName Like '%{3}%' Or su.CnName Like '%{4}%')",
  100. tj, tj, tj, tj, tj);
  101. }
  102. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  103. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  104. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  105. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  106. pr.LastCollectionTime
  107. From Grp_DelegationInfo gdi
  108. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  109. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  110. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  111. Left Join (
  112. SELECT Diid, MAX(CreateTime) LastCollectionTime
  113. FROM Fin_ProceedsReceived
  114. Where IsDel = 0
  115. GROUP BY Diid
  116. ) pr On gdi.Id = pr.Diid
  117. Where gdi.IsDel = 0 {0} ", sqlWhere);
  118. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  119. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  120. var _view = new
  121. {
  122. PageFuncAuth = pageFunAuthView,
  123. Data = _DelegationList
  124. };
  125. return Ok(JsonView(true, "查询成功!", _view, total));
  126. }
  127. else
  128. {
  129. return Ok(JsonView(false, "查询失败"));
  130. }
  131. }
  132. /// <summary>
  133. /// 团组报表
  134. /// Details
  135. /// </summary>
  136. /// <param name="_dto">团组列表请求dto</param>
  137. /// <returns></returns>
  138. [HttpPost("PostGroupStatementDetails")]
  139. //[JsonConverter(typeof(DecimalConverter), 2)]
  140. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  141. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  142. {
  143. /*
  144. * 团组报表计算方式
  145. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  146. * 应收金额 = 应收表.Sum()
  147. * 已收金额 = 已收表.Sum()
  148. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  149. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  150. *
  151. */
  152. #region 参数验证
  153. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  154. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  155. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  156. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  157. #region 页面操作权限验证
  158. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  159. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  160. #endregion
  161. #endregion
  162. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  163. {
  164. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  165. #region 费用类型 币种,转账,客户信息
  166. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  167. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>()
  168. .Where(it => it.IsDel == 0)
  169. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  170. .ToListAsync();
  171. foreach (var item in _clientDatas) EncryptionProcessor.DecryptProperties(item);
  172. var groupInfo = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.Id == _dto.DiId).FirstAsync();
  173. var visitDate = groupInfo.VisitDate;
  174. #endregion
  175. #region 团组收入
  176. GroupIncomeView _giView = new GroupIncomeView();
  177. /*
  178. * 应收报表
  179. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  180. */
  181. decimal frTotalAmount = 0.00M;//应收总金额
  182. 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,
  183. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  184. From Fin_ForeignReceivables fr
  185. Left Join Sys_SetData sd On fr.Currency = sd.Id
  186. Left Join Sys_Users u On fr.Auditor = u.Id
  187. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  188. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  189. //List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  190. //if (_frViews1.Count > 0)
  191. //{
  192. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  193. // _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  194. //}
  195. _frViews.ForEach(x =>
  196. {
  197. string namePrefix = string.Empty;
  198. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  199. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  200. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  201. x.PriceName = $"{namePrefix}{x.PriceName}";
  202. });
  203. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  204. _giView.Receivables = _frViews;
  205. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  206. /*
  207. * 已收报表
  208. */
  209. decimal prTotalAmount = 0.00M;//已收总金额
  210. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  211. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  212. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  213. From Fin_ProceedsReceived pr
  214. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  215. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  216. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  217. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  218. prTotalAmount = _prViews.Sum(it => it.Price);
  219. _giView.ProceedsReceivedViews = _prViews;
  220. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount:#0.00} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1():#0.00} CNY");
  221. /*
  222. * 超支费用
  223. */
  224. decimal exTotalAmount = 0.00M;
  225. // 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,
  226. // (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  227. // sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  228. //From OA2023DB.dbo.Fin_GroupExtraCost gec
  229. //Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  230. // Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  231. // Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  232. // Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  233. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  234. //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 " : " ");
  235. // List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(ecSql).ToListAsync();
  236. // #region 超支费用 - 模拟数据
  237. // //if (_ExtraCostsViews.Count < 1)
  238. // //{
  239. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  240. // // {
  241. // // GECId = 0,
  242. // // GECDiId = 2334,
  243. // // PriceName = "模拟数据-超支费用名称",
  244. // // PayMoney = 1000.00M,
  245. // // PaymentCurrency = "CNY",
  246. // // DayRate = 1.0000M,
  247. // // CNYPrice = 1000.00M,
  248. // // Payee = "模拟数据-超支费用收款方",
  249. // // OrbitalPrivateTransfer = 1,
  250. // // PayWay = "刷卡",
  251. // // CardType = "招行卡",
  252. // // IsPay = 1,
  253. // // Applicant = "刘华举"
  254. // // });
  255. // // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  256. // // {
  257. // // GECId = 0,
  258. // // GECDiId = 2334,
  259. // // PriceName = "模拟数据-超支费用名称",
  260. // // PayMoney = 1000.00M,
  261. // // PaymentCurrency = "CNY",
  262. // // DayRate = 1.0000M,
  263. // // CNYPrice = 1000.00M,
  264. // // Payee = "模拟数据-超支费用收款方",
  265. // // OrbitalPrivateTransfer = 1,
  266. // // PayWay = "刷卡",
  267. // // CardType = "招行卡",
  268. // // IsPay = 1,
  269. // // Applicant = "刘华举"
  270. // // });
  271. // //}
  272. // #endregion
  273. // exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  274. // _giView.ExtraCostsViews = _ExtraCostsViews;
  275. // _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  276. /*
  277. * 收款退还
  278. */
  279. decimal promTotalAmount = 0.00M;// 收款退还总金额
  280. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  281. //删除了 And prom.PriceType = 1
  282. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  283. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  284. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  285. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime
  286. From Fin_PaymentRefundAndOtherMoney prom
  287. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  288. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  289. Where prom.IsDel = 0
  290. And prom.PayType = 1
  291. And ccp.CTable = 285
  292. {1}
  293. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  294. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  295. foreach (var ropItem in _promDatas)
  296. {
  297. string thisCueencyCode = "Unknown";
  298. string thisCueencyName = "Unknown";
  299. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  300. if (currency != null)
  301. {
  302. thisCueencyCode = currency.Name;
  303. thisCueencyName = currency.Remark;
  304. }
  305. string orbitalPrivateTransferStr = "Unknown";
  306. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  307. if (orbitalPrivateTransfer != null)
  308. {
  309. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  310. }
  311. string payStr = "Unknown";
  312. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  313. if (pay != null)
  314. {
  315. payStr = pay.Name;
  316. }
  317. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  318. {
  319. Id = ropItem.Id,
  320. DiId = ropItem.DIId,
  321. PriceName = ropItem.PrPriceName,
  322. PayCurrencyCode = thisCueencyCode,
  323. PayCurrencyName = thisCueencyName,
  324. Price = ropItem.PrPrice,
  325. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  326. ThisRate = ropItem.DayRate,
  327. Payee = ropItem.Payee,
  328. PayTime = ropItem.AuditGMDate,
  329. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  330. PayType = payStr,
  331. IsPay = ropItem.IsPay,
  332. Applicant = ropItem.Appliction
  333. };
  334. _promView.Add(gsd_PaymentRefund);
  335. }
  336. #region 收款退还 - 模拟数据
  337. //if (_promView.Count < 1)
  338. //{
  339. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  340. // {
  341. // Id = 0,
  342. // DiId = 2334,
  343. // PriceName = "模拟数据-费用名称",
  344. // PayCurrencyCode = "CNY",
  345. // PayCurrencyName = "人民币",
  346. // Price = 1000.00M,
  347. // CNYPrice = 1000.00M,
  348. // ThisRate = 1.00M,
  349. // Payee = "模拟数据-收款方",
  350. // PayTime = "2023-01-01 15:20:01",
  351. // OrbitalPrivateTransfer = 1,
  352. // PayType = "刷卡",
  353. // IsPay = 1,
  354. // Applicant = "刘华举"
  355. // });
  356. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  357. // {
  358. // Id = 0,
  359. // DiId = 2334,
  360. // PriceName = "模拟数据-费用名称",
  361. // PayCurrencyCode = "CNY",
  362. // PayCurrencyName = "人民币",
  363. // Price = 1000.00M,
  364. // CNYPrice = 1000.00M,
  365. // ThisRate = 1.00M,
  366. // Payee = "模拟数据-收款方",
  367. // PayTime = "2023-01-01 15:20:01",
  368. // OrbitalPrivateTransfer = 1,
  369. // PayType = "刷卡",
  370. // IsPay = 1,
  371. // Applicant = "刘华举"
  372. // });
  373. //}
  374. #endregion
  375. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  376. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  377. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  378. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  379. _view.GroupIncome = _giView;
  380. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  381. #endregion
  382. #region 团组支出
  383. GroupExpenditureView _geView = new GroupExpenditureView();
  384. #region 酒店预定费用
  385. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  386. //ccp.RMBPrice As CNYPrice
  387. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  388. string hotelFeeSql = string.Format(@"
  389. SELECT
  390. hr.Id AS HrId,
  391. hr.DiId AS HrDiId,
  392. hr.City,
  393. hr.HotelName,
  394. hr.CheckInDate,
  395. hr.CheckOutDate,
  396. hr.CardPrice AS RoomPrice,
  397. sd1.Name AS PaymentCurrency,
  398. hr.SingleRoomPrice,
  399. hr.SingleRoomCount,
  400. hr.DoubleRoomPrice,
  401. hr.DoubleRoomCount,
  402. hr.SuiteRoomPrice,
  403. hr.SuiteRoomCount,
  404. hr.OtherRoomPrice,
  405. hr.OtherRoomCount,
  406. hr.BreakfastPrice,
  407. sd4.Name AS BreakfastCurrency,
  408. hr.Isoppay,
  409. hr.GovernmentRent,
  410. sd5.Name AS GovernmentRentCurrency,
  411. hr.CityTax,
  412. sd6.Name AS CityTaxCurrency,
  413. ccp.PayMoney,
  414. (
  415. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  416. ) AS CNYPrice,
  417. ccp.PayPercentage,
  418. ccp.DayRate,
  419. ccp.Payee,
  420. ccp.OrbitalPrivateTransfer,
  421. sd2.Name AS PayWay,
  422. sd3.Name AS CardType,
  423. ccp.IsPay,
  424. u.CnName AS Applicant
  425. FROM
  426. Grp_HotelReservations hr
  427. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  428. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  429. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  430. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  431. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  432. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  433. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  434. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  435. WHERE
  436. hr.IsDel = 0
  437. AND ccp.IsDel = 0
  438. AND ccp.CTable = 76 {1}
  439. AND ccp.PayMoney <> 0
  440. AND hr.DiId = {0}
  441. ORDER BY
  442. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  443. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  444. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  445. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  446. decimal HotelCNYTotalPrice = 0.00M;
  447. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  448. foreach (var item in groupHotelFeeViews)
  449. {
  450. if (groupHotelContentFeeViews.Count > 0)
  451. {
  452. string paymentStr = string.Empty;
  453. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  454. item.RoomPrice = roomData?.Price ?? 0.00M;
  455. if (item.RoomPrice != 0)
  456. {
  457. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  458. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  459. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  460. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  461. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  462. 收款方:{roomData?.Payee}<br/>
  463. 费用标识:{feeMark1} <br/>
  464. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  465. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  466. 是否由地接支付:{isFeeMark1} <br/>";
  467. }
  468. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  469. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  470. if (item.BreakfastPrice != 0)
  471. {
  472. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  473. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  474. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  475. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  476. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  477. 收款方:{breakfastData?.Payee}<br/>
  478. 费用标识:{feeMark2} <br/>
  479. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  480. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  481. 是否由地接支付:{isFeeMark2} <br/>";
  482. }
  483. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  484. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  485. if (item.GovernmentRent != 0)
  486. {
  487. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  488. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  489. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  490. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  491. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  492. 收款方:{landTaxData?.Payee}<br/>
  493. 费用标识:{feeMark3} <br/>
  494. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  495. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  496. 是否由地接支付:{isFeeMark3} <br/>";
  497. }
  498. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  499. item.CityTax = cityTaxData?.Price ?? 0.00M;
  500. if (item.CityTax != 0)
  501. {
  502. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  503. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  504. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  505. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  506. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  507. 收款方:{cityTaxData?.Payee}<br/>
  508. 费用标识:{feeMark4} <br/>
  509. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  510. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  511. 是否由地接支付:{isFeeMark4} <br/>";
  512. }
  513. if (!string.IsNullOrEmpty(paymentStr))
  514. {
  515. item.IsPay = 2;
  516. item.PayTips = paymentStr;
  517. }
  518. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  519. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  520. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  521. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  522. }
  523. else
  524. {
  525. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  526. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  527. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  528. (item.OtherRoomCount * item.OtherRoomPrice);
  529. //item.RoomPrice = item.CardPrice;
  530. item.RoomPriceCurrency = item.PaymentCurrency;
  531. }
  532. HotelCNYTotalPrice += item.CNYPrice;
  533. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  534. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  535. }
  536. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  537. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  538. #endregion
  539. #region 地接费用
  540. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  541. string CTGGRFeeSql = string.Empty;
  542. if (visitDate > Convert.ToDateTime("2024-04-17"))
  543. {
  544. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  545. sd2.name As PaymentCurrency,ccp.PayPercentage,
  546. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  547. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  548. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  549. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  550. From Grp_CarTouristGuideGroundReservations ctggr
  551. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  552. cggrc.DatePrice,cggrc.PriceContent
  553. From Grp_CarTouristGuideGroundReservationsContent cggrc
  554. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  555. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  556. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  557. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  558. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  559. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  560. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  561. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  562. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  563. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  564. }
  565. else
  566. {
  567. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  568. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  569. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  570. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  571. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  572. ccp.Payee,ccp.AuditGMDate,
  573. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  574. From Grp_CarTouristGuideGroundReservations ctggr
  575. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  576. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  577. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  578. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  579. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  580. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  581. }
  582. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  583. string CTGGRFeeStr = "";
  584. decimal CTGGRCNYTotalPrice = 0.00M;
  585. //按1 地区,2 币种,3 汇率 分组计算
  586. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  587. foreach (var ctggfr in groupCTGGRFeeDatas)
  588. {
  589. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  590. if (ctggfr_curr.Count() > 0)
  591. {
  592. foreach (var curr in ctggfr_curr)
  593. {
  594. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  595. if (ctggfr_rate.Count() > 0)
  596. {
  597. foreach (var rate in ctggfr_rate)
  598. {
  599. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  600. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  601. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  602. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  603. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  604. }
  605. }
  606. else
  607. {
  608. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  609. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  610. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  611. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  612. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  613. }
  614. }
  615. }
  616. else
  617. {
  618. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  619. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  620. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  621. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  622. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  623. }
  624. }
  625. foreach (var item in groupCTGGRFeeViews)
  626. {
  627. if (!string.IsNullOrEmpty(item.AuditGMDate))
  628. {
  629. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  630. }
  631. if (item.DatePrice != null)
  632. {
  633. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  634. }
  635. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  636. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  637. //CTGGRCNYTotalPrice += item.CNYPrice;
  638. }
  639. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  640. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  641. #endregion
  642. #region 机票预订费用
  643. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  644. //ccp.RMBPrice As CNYPrice
  645. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  646. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  647. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  648. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  649. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  650. atr.CType
  651. From Grp_AirTicketReservations atr
  652. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  653. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  654. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  655. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  656. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  657. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  658. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  659. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  660. string str = "";
  661. List<dynamic> airClientPris = new List<dynamic>();
  662. decimal AirCNYTotalPrice = 0.00M;
  663. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  664. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  665. //if (groupAirFeeViews.Count > 0)
  666. //{
  667. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  668. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  669. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  670. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  671. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  672. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  673. //}
  674. int Index = 0;
  675. foreach (var item in groupAirFeeViews)
  676. {
  677. if (item.AirId > 2924)
  678. {
  679. string itemClientName = "";
  680. if (!string.IsNullOrEmpty(item.ClientName))
  681. {
  682. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  683. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  684. if (m_EnName.Success || m_ZHName.Success)
  685. {
  686. itemClientName = item.ClientName;
  687. decimal unitCost = 0.00M;
  688. AirCNYTotalPrice += item.CNYPrice;
  689. continue;
  690. }
  691. string[] clientIds = new string[] { };
  692. if (item.ClientName.Contains(','))
  693. {
  694. clientIds = item.ClientName.Split(',');
  695. }
  696. else
  697. {
  698. clientIds = new string[] { item.ClientName };
  699. }
  700. if (clientIds.Length > 0)
  701. {
  702. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  703. if (output.Contains(-1))
  704. {
  705. itemClientName += $@"行程单";
  706. output = output.Where(val => val != -1).ToArray();
  707. }
  708. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  709. decimal unitCost = 0.00M;
  710. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  711. int clienIndex = 1;
  712. foreach (var client in clients)
  713. {
  714. airClientPris.Add(new
  715. {
  716. CnName = client.LastName + client.FirstName,
  717. EnName = client.Pinyin,
  718. Price = unitCost,
  719. AirType = item.AirTypeName
  720. });
  721. string six = "";
  722. if (client.Sex == 0) six = "Mr";
  723. else if (client.Sex == 1) six = "Ms";
  724. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  725. clienIndex++;
  726. }
  727. }
  728. }
  729. item.ClientName = itemClientName;
  730. }
  731. else
  732. {
  733. string clientPinYinName = "";
  734. decimal unitCost = 0.00M;
  735. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  736. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  737. Regex r = new Regex("[0-9]");
  738. string name1 = item.ClientName;
  739. name1 = r.Replace(name1, "");
  740. string[] clientNames = name1.Split('.');
  741. for (int i = 0; i < item.ClientNum; i++)
  742. {
  743. string name = "";
  744. if (clientNames.Length > 0)
  745. {
  746. int index = i + 1;
  747. if (index < clientNames.Length)
  748. {
  749. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  750. if (!string.IsNullOrEmpty(name))
  751. {
  752. airClientPris.Add(new
  753. {
  754. CnName = name,
  755. EnName = name,
  756. Price = unitCost,
  757. AirType = item.AirTypeName
  758. });
  759. }
  760. //if (name.Length > 0)
  761. //{
  762. // string nameLastStr = name[name.Length - 1].ToString();
  763. // if (nameLastStr.IsNumeric())
  764. // {
  765. // name = name.Substring(0, name.Length - 1).Trim();
  766. // }
  767. //}
  768. }
  769. }
  770. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  771. }
  772. }
  773. if (!string.IsNullOrEmpty(item.AuditGMDate))
  774. {
  775. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  776. }
  777. AirCNYTotalPrice += item.CNYPrice;
  778. }
  779. _geView.GroupAirFeeViews = groupAirFeeViews;
  780. if (airClientPris.Count > 0)
  781. {
  782. var peoplePriStr = "";
  783. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  784. .Select(group => group.First())
  785. .ToList();
  786. int airClientPrisIndex = 1;
  787. foreach (var item in airClientPris1)
  788. {
  789. decimal price = 0.00M;
  790. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  791. foreach (var pri in prices)
  792. {
  793. price += pri.Price;
  794. }
  795. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  796. airClientPrisIndex++;
  797. }
  798. if (!string.IsNullOrEmpty(peoplePriStr))
  799. {
  800. str = $@"其中:{peoplePriStr}";
  801. }
  802. //经济舱均价
  803. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  804. if (airJJCPris.Count > 0)
  805. {
  806. decimal jjcTotalPrice = 0.00M;
  807. foreach (var item in airJJCPris)
  808. {
  809. jjcTotalPrice += item.Price;
  810. }
  811. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  812. .Select(group => group.First())
  813. .ToList().Count;
  814. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  815. }
  816. //公务舱均价
  817. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  818. if (airGWCPris.Count > 0)
  819. {
  820. decimal gwcTotalPrice = 0.00M;
  821. foreach (var item in airGWCPris)
  822. {
  823. gwcTotalPrice += item.Price;
  824. }
  825. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  826. .Select(group => group.First())
  827. .ToList().Count;
  828. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  829. }
  830. }
  831. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  832. #endregion
  833. #region 签证费用
  834. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  835. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  836. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  837. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  838. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  839. From Grp_VisaInfo vi
  840. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  841. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  842. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  843. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  844. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  845. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  846. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  847. decimal VisaCNYTotalPirce = 0.00M;
  848. foreach (var item in groupVisaFeeViews)
  849. {
  850. string itemClientName = "";
  851. string visaClients = item.VisaClient;
  852. if (!string.IsNullOrEmpty(visaClients))
  853. {
  854. string[] clientIds = new string[] { };
  855. if (visaClients.Contains(','))
  856. {
  857. clientIds = visaClients.Split(',');
  858. }
  859. else
  860. {
  861. clientIds = new string[] { visaClients };
  862. }
  863. if (clientIds.Length > 0)
  864. {
  865. List<int> clientIds1 = new List<int>() { };
  866. foreach (var clientIdStr in clientIds)
  867. {
  868. if (clientIdStr.IsNumeric())
  869. {
  870. clientIds1.Add(int.Parse(clientIdStr));
  871. }
  872. }
  873. if (clientIds1.Count > 0)
  874. {
  875. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  876. foreach (var client in clients)
  877. {
  878. itemClientName += $"{client.LastName + client.FirstName},";
  879. }
  880. }
  881. else
  882. {
  883. itemClientName = visaClients;
  884. }
  885. }
  886. }
  887. if (itemClientName.Length > 0)
  888. {
  889. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  890. }
  891. item.VisaClient = itemClientName;
  892. VisaCNYTotalPirce += item.CNYPrice;
  893. if (!string.IsNullOrEmpty(item.AuditGMDate))
  894. {
  895. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  896. }
  897. }
  898. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  899. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  900. #endregion
  901. #region 邀请/公务活动 CTable = 81
  902. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  903. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  904. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  905. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  906. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,
  907. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  908. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  909. From Grp_InvitationOfficialActivities ioa
  910. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  911. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  912. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  913. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  914. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  915. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  916. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  917. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  918. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  919. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  920. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  921. #region 邀请/公务活动 - 模拟数据
  922. //if (groupInvitationalFeeViews.Count < 1)
  923. //{
  924. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  925. // {
  926. // IOAId = 0,
  927. // IOADiId = 2334,
  928. // InviterArea = "模拟数据-邀请方地区",
  929. // Inviter = "模拟数据-邀请方",
  930. // InviteTime = "2023-10-10",
  931. // InviteCost = 100.00M,
  932. // InviteCurrency = "EUR",
  933. // SendCost = 100.00M,
  934. // SendCurrency = "EUR",
  935. // EventsCost = 10000.00M,
  936. // EventsCurrency = "EUR",
  937. // TranslateCost = 300.00M,
  938. // TranslateCurrency = "EUR",
  939. // PayMoney = 10500.00M,
  940. // PaymentCurrency = "EUR",
  941. // CNYPrice = 76765.50M,
  942. // Payee = "模拟数据-收款方",
  943. // AuditGMDate = "2023-12-05",
  944. // OrbitalPrivateTransfer = 1,
  945. // PayWay = "刷卡",
  946. // IsPay = 1,
  947. // Applicant = "刘华举"
  948. // });
  949. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  950. // {
  951. // IOAId = 0,
  952. // IOADiId = 2334,
  953. // InviterArea = "模拟数据-邀请方地区",
  954. // Inviter = "模拟数据-邀请方",
  955. // InviteTime = "2023-10-10",
  956. // InviteCost = 100.00M,
  957. // InviteCurrency = "EUR",
  958. // SendCost = 100.00M,
  959. // SendCurrency = "EUR",
  960. // EventsCost = 10000.00M,
  961. // EventsCurrency = "EUR",
  962. // TranslateCost = 300.00M,
  963. // TranslateCurrency = "EUR",
  964. // PayMoney = 10500.00M,
  965. // PaymentCurrency = "EUR",
  966. // CNYPrice = 76765.50M,
  967. // Payee = "模拟数据-收款方",
  968. // AuditGMDate = "2023-12-05",
  969. // OrbitalPrivateTransfer = 1,
  970. // PayWay = "刷卡",
  971. // IsPay = 1,
  972. // Applicant = "刘华举"
  973. // });
  974. //}
  975. #endregion
  976. decimal InvitationalCNYTotalPrice = 0.00M;
  977. foreach (var item in groupInvitationalFeeViews)
  978. {
  979. InvitationalCNYTotalPrice += item.CNYPrice2;
  980. if (!string.IsNullOrEmpty(item.AuditGMDate))
  981. {
  982. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  983. }
  984. string currencyRateStr = "";
  985. List<string> currencys = new List<string>();
  986. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  987. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  988. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  989. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  990. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  991. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  992. item.CurrencyRateStr = currencyRateStr;
  993. }
  994. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  995. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  996. #endregion
  997. #region 保险费用
  998. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  999. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.PayMoney * ccp.DayRate As CNYPrice,
  1000. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1001. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1002. From Grp_Customers ic
  1003. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1004. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1005. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1006. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1007. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1008. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1009. decimal InsuranceCNYTotalPrice = 0.00M;
  1010. foreach (var item in groupInsuranceFeeViews)
  1011. {
  1012. InsuranceCNYTotalPrice += item.CNYPrice;
  1013. string itemClientName = "";
  1014. string insClients = item.ClientName;
  1015. if (!string.IsNullOrEmpty(insClients))
  1016. {
  1017. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  1018. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  1019. //if (m_EnName.Success || m_ZHName.Success)
  1020. //{
  1021. // itemClientName = insClients;
  1022. // continue;
  1023. //}
  1024. string[] clientIds = new string[] { };
  1025. if (insClients.Contains(','))
  1026. {
  1027. clientIds = insClients.Split(',');
  1028. }
  1029. else
  1030. {
  1031. clientIds = new string[] { insClients };
  1032. }
  1033. if (clientIds.Length > 0)
  1034. {
  1035. List<int> output = new List<int>();
  1036. foreach (var clientId in clientIds)
  1037. {
  1038. if (clientId.IsNumeric())
  1039. {
  1040. output.Add(int.Parse(clientId));
  1041. }
  1042. }
  1043. if (output.Count > 0)
  1044. {
  1045. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1046. foreach (var client in clients)
  1047. {
  1048. itemClientName += $"{client.LastName + client.FirstName},";
  1049. }
  1050. if (itemClientName.Length > 0)
  1051. {
  1052. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1053. }
  1054. }
  1055. else
  1056. {
  1057. itemClientName = insClients;
  1058. }
  1059. }
  1060. }
  1061. item.ClientName = itemClientName;
  1062. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1063. {
  1064. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1065. }
  1066. }
  1067. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1068. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1069. #endregion
  1070. #region 其他款项费用 98
  1071. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1072. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1073. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1074. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1075. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1076. From Grp_DecreasePayments dp
  1077. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1078. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1079. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1080. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1081. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1082. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1083. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1084. #region 保险费用 - 模拟数据
  1085. //if (groupDecreaseFeeViews.Count < 1)
  1086. //{
  1087. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1088. // {
  1089. // DPId = 0,
  1090. // DPDiId = 2334,
  1091. // PriceName = "模拟数据-费用名称",
  1092. // PayMoney = 1000.00M,
  1093. // PayMoneyCurrency = "CNY",
  1094. // DayRate = 1.0000M,
  1095. // CNYPrice = 1.0000M,
  1096. // AuditGMDate = "2023-12-10 12:13:00",
  1097. // Payee = "模拟数据-付款方",
  1098. // OrbitalPrivateTransfer = 1,
  1099. // PayWay = "现金",
  1100. // IsPay = 1,
  1101. // Applicant = "刘华举"
  1102. // });
  1103. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1104. // {
  1105. // DPId = 0,
  1106. // DPDiId = 2334,
  1107. // PriceName = "模拟数据-费用名称",
  1108. // PayMoney = 1000.00M,
  1109. // PayMoneyCurrency = "CNY",
  1110. // DayRate = 1.0000M,
  1111. // CNYPrice = 1.0000M,
  1112. // AuditGMDate = "2023-12-10 12:13:00",
  1113. // Payee = "模拟数据-付款方",
  1114. // OrbitalPrivateTransfer = 1,
  1115. // PayWay = "现金",
  1116. // IsPay = 1,
  1117. // Applicant = "刘华举"
  1118. // });
  1119. //}
  1120. #endregion
  1121. decimal DecreaseCNYTotalPrice = 0.00M;
  1122. foreach (var item in groupDecreaseFeeViews)
  1123. {
  1124. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1125. DecreaseCNYTotalPrice += item.CNYPrice;
  1126. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1127. {
  1128. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1129. }
  1130. }
  1131. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1132. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1133. #endregion
  1134. _view.GroupExpenditure = _geView;
  1135. #endregion
  1136. /*
  1137. * 团组报表计算方式
  1138. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1139. * 应收金额 = 应收表.Sum()
  1140. * 已收金额 = 已收表.Sum()
  1141. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1142. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1143. *
  1144. */
  1145. decimal _totalExpenditure = 0.00M; //总支出
  1146. decimal _amountReceivable = 0.00M; //应收金额
  1147. decimal _amountReceived = 0.00M; //已收金额
  1148. decimal _receivableProfit = 0.00M; //应收利润
  1149. decimal _receivedProfit = 0.00M; //已收利润
  1150. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1151. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1152. _amountReceivable = frTotalAmount;
  1153. _amountReceived = prTotalAmount;
  1154. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1155. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1156. _view.FeeTotalStr = string.Format(@$"<span>
  1157. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1158. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1159. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1160. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1161. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1162. </span>");
  1163. return Ok(JsonView(true, "查询成功!", _view));
  1164. }
  1165. else
  1166. {
  1167. return Ok(JsonView(false, "查询成功"));
  1168. }
  1169. }
  1170. /// <summary>
  1171. /// 团组报表
  1172. /// Excel 下载
  1173. /// </summary>
  1174. /// <param name="_dto">团组列表请求dto</param>
  1175. /// <returns></returns>
  1176. [HttpPost("PostGroupStatementExportExcel")]
  1177. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1178. public async Task<IActionResult> PostGroupStatementExportExcel(GroupStatementDetailsDto _dto)
  1179. {
  1180. //pageId 38
  1181. int currUserId = _dto.UserId, pageId = _dto.PageId, diId = _dto.DiId;
  1182. bool isAudit = _dto.isAudit;
  1183. #region 参数验证
  1184. if (currUserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1185. if (pageId < 1) return Ok(JsonView(false, "页面Id为空"));
  1186. if (diId < 1) return Ok(JsonView(false, "数据Id为空"));
  1187. #region 页面操作权限验证
  1188. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(currUserId, pageId);
  1189. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  1190. #endregion
  1191. #endregion
  1192. var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => x.IsDel == 0 && x.Id == diId).First();
  1193. if (groupInfo == null) return Ok(JsonView(false, "暂无该条团组信息!"));
  1194. var userInfo = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == currUserId).First();
  1195. string groupNo = groupInfo.TourCode,
  1196. groupName = groupInfo.TeamName.Replace("|", "、"),
  1197. lister = userInfo?.CnName ?? "-";
  1198. var _clientDatas = _sqlSugar.Queryable<Crm_DeleClient>()
  1199. .Where(it => it.IsDel == 0)
  1200. .Select(x => new Crm_DeleClient { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, Sex = x.Sex })
  1201. .ToList();
  1202. //获取模板
  1203. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
  1204. var designer = new WorkbookDesigner();
  1205. designer.Workbook = new Workbook(tempPath);
  1206. // 获取工作簿中的工作表集合
  1207. var worksheets = designer.Workbook.Worksheets;
  1208. #region 获取sheet,定义datatable,局部变量
  1209. //酒店费用相关
  1210. var hotelFeeSheet = worksheets["酒店费用"];
  1211. var hotelFeeDt = new DataTable($"HotelFeeView");
  1212. decimal hotelCNYTotalCost = 0.00M;
  1213. //地接费用相关
  1214. var OPFeeSheet = worksheets["地接费用"];
  1215. var OPFeeDt = new DataTable($"OPFeeView");
  1216. var OPFeeLabel = string.Empty;
  1217. decimal OPCNYTotalCost = 0.00M;
  1218. //签证费用相关
  1219. var visaFeeSheet = worksheets["签证费用"];
  1220. var visaFeeDt = new DataTable($"VisaFeeView");
  1221. decimal visaCNYTotalCost = 0.00M;
  1222. //邀请费用相关
  1223. var OAFeeSheet = worksheets["邀请费用"];
  1224. var OAFeeDt = new DataTable($"OAFeeView");
  1225. decimal OACNYTotalCost = 0.00M;
  1226. //机票费用相关
  1227. var airTicketFeeSheet = worksheets["机票费用"];
  1228. var airTicketFeeDt = new DataTable($"AirTicketFeeView");
  1229. decimal airTicketCNYTotalCost = 0.00M;
  1230. //保险费用相关
  1231. var insureFeeSheet = worksheets["保险费用"];
  1232. var insureFeeDt = new DataTable($"InsureFeeView");
  1233. decimal insureCNYTotalCost = 0.00M;
  1234. //其他费用相关
  1235. var otherFeeSheet = worksheets["其他费用"];
  1236. var otherFeeDt = new DataTable($"OtherFeeView");
  1237. decimal otherCNYTotalCost = 0.00M;
  1238. //收款退还相关
  1239. var SKTHFeeSheet = worksheets["收款退还"];
  1240. var SKTHFeeDt = new DataTable($"SKTHFeeView");
  1241. decimal SKTHCNYTotalCost = 0.00M;
  1242. var totalAmount = 0.00M; //支出成本合计
  1243. var accountsAmount = 0.00M; //应收金额合计
  1244. var receivedAmount = 0.00M; //已收金额合计
  1245. var accountsProfit = 0.00M; //应收利润合计
  1246. var receiveProfit = 0.00M; //已收利润合计
  1247. var profitMargin = 0.00M; //利润差合计
  1248. //应收合计相关
  1249. var receivableFeeSheet = worksheets["团组收入(未收)"];
  1250. var receivableFeeDt = new DataTable($"ReceivableFeeView");
  1251. //已收合计相关
  1252. var receivedFeeSheet = worksheets["团组收入(已收)"];
  1253. var receivedFeeDt = new DataTable($"ReceivedFeeView");
  1254. //团组收入支出利润
  1255. var groupIEProfitDt = new DataTable($"IEProfitFeeView");
  1256. #endregion
  1257. #region 酒店费用
  1258. if (hotelFeeSheet != null)
  1259. {
  1260. string hotelFeeSql = string.Format(@"
  1261. SELECT
  1262. hr.Id AS HrId,
  1263. hr.DiId AS HrDiId,
  1264. hr.City,
  1265. hr.HotelName,
  1266. hr.CheckInDate,
  1267. hr.CheckOutDate,
  1268. hr.CardPrice AS RoomPrice,
  1269. sd1.Name AS PaymentCurrency,
  1270. hr.SingleRoomPrice,
  1271. hr.SingleRoomCount,
  1272. hr.DoubleRoomPrice,
  1273. hr.DoubleRoomCount,
  1274. hr.SuiteRoomPrice,
  1275. hr.SuiteRoomCount,
  1276. hr.OtherRoomPrice,
  1277. hr.OtherRoomCount,
  1278. hr.BreakfastPrice,
  1279. sd4.Name AS BreakfastCurrency,
  1280. hr.Isoppay,
  1281. hr.GovernmentRent,
  1282. sd5.Name AS GovernmentRentCurrency,
  1283. hr.CityTax,
  1284. sd6.Name AS CityTaxCurrency,
  1285. ccp.PayMoney,
  1286. (
  1287. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  1288. ) AS CNYPrice,
  1289. ccp.PayPercentage,
  1290. ccp.DayRate,
  1291. ccp.Payee,
  1292. ccp.OrbitalPrivateTransfer,
  1293. sd2.Name AS PayWay,
  1294. sd3.Name AS CardType,
  1295. ccp.IsPay,
  1296. u.CnName AS Applicant,
  1297. hr.Remark
  1298. FROM
  1299. Grp_HotelReservations hr
  1300. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  1301. LEFT JOIN Sys_SetData sd1 ON ccp.PaymentCurrency = sd1.Id
  1302. LEFT JOIN Sys_SetData sd2 ON ccp.PayDId = sd2.Id
  1303. LEFT JOIN Sys_SetData sd3 ON ccp.CTDId = sd3.Id
  1304. LEFT JOIN Sys_Users u ON ccp.CreateUserId = u.Id
  1305. LEFT JOIN Sys_SetData sd4 ON hr.BreakfastCurrency = sd4.Id
  1306. LEFT JOIN Sys_SetData sd5 ON hr.GovernmentRentCurrency = sd5.Id
  1307. LEFT JOIN Sys_SetData sd6 ON hr.CityTaxCurrency = sd6.Id
  1308. WHERE
  1309. hr.IsDel = 0
  1310. AND ccp.IsDel = 0
  1311. AND ccp.CTable = 76 {1}
  1312. AND ccp.PayMoney <> 0
  1313. AND hr.DiId = {0}
  1314. ORDER BY
  1315. CheckInDate Asc", _dto.DiId, _dto.isAudit ? "AND (ccp.IsAuditGM = 1 Or ccp.IsAuditGM = 3)" : " ");
  1316. var groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1317. if (groupHotelFeeViews.Any())
  1318. {
  1319. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1320. var hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  1321. var groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  1322. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  1323. foreach (var item in groupHotelFeeViews)
  1324. {
  1325. if (groupHotelContentFeeViews.Count > 0)
  1326. {
  1327. string paymentStr = string.Empty;
  1328. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  1329. item.RoomPrice = roomData?.Price ?? 0.00M;
  1330. if (item.RoomPrice != 0)
  1331. {
  1332. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  1333. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  1334. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1335. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  1336. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  1337. 收款方:{roomData?.Payee}<br/>
  1338. 费用标识:{feeMark1} <br/>
  1339. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1340. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  1341. 是否由地接支付:{isFeeMark1} <br/>";
  1342. }
  1343. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  1344. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  1345. if (item.BreakfastPrice != 0)
  1346. {
  1347. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  1348. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  1349. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1350. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  1351. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  1352. 收款方:{breakfastData?.Payee}<br/>
  1353. 费用标识:{feeMark2} <br/>
  1354. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  1355. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  1356. 是否由地接支付:{isFeeMark2} <br/>";
  1357. }
  1358. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  1359. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  1360. if (item.GovernmentRent != 0)
  1361. {
  1362. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  1363. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  1364. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1365. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1366. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  1367. 收款方:{landTaxData?.Payee}<br/>
  1368. 费用标识:{feeMark3} <br/>
  1369. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  1370. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  1371. 是否由地接支付:{isFeeMark3} <br/>";
  1372. }
  1373. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  1374. item.CityTax = cityTaxData?.Price ?? 0.00M;
  1375. if (item.CityTax != 0)
  1376. {
  1377. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  1378. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  1379. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  1380. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  1381. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  1382. 收款方:{cityTaxData?.Payee}<br/>
  1383. 费用标识:{feeMark4} <br/>
  1384. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  1385. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  1386. 是否由地接支付:{isFeeMark4} <br/>";
  1387. }
  1388. if (!string.IsNullOrEmpty(paymentStr))
  1389. {
  1390. item.IsPay = 2;
  1391. item.PayTips = paymentStr;
  1392. }
  1393. //item.CNYPrice = roomData?.Price ?? 0.00M * roomData?.Rate ?? 0.00M +
  1394. // breakfastData?.Price ?? 0.00M * breakfastData?.Rate ?? 0.00M +
  1395. // landTaxData?.Price ?? 0.00M * landTaxData?.Rate ?? 0.00M +
  1396. // cityTaxData?.Price ?? 0.00M * cityTaxData?.Rate ?? 0.00M;
  1397. }
  1398. else
  1399. {
  1400. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  1401. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  1402. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  1403. (item.OtherRoomCount * item.OtherRoomPrice);
  1404. //item.RoomPrice = item.CardPrice;
  1405. item.RoomPriceCurrency = item.PaymentCurrency;
  1406. }
  1407. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  1408. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  1409. }
  1410. }
  1411. hotelCNYTotalCost = groupHotelFeeViews.Sum(x => x.CNYPrice);
  1412. hotelFeeDt = CommonFun.ToDataTableArray(groupHotelFeeViews);
  1413. hotelFeeDt.TableName = $"HotelFeeView";
  1414. }
  1415. #endregion
  1416. #region 地接费用
  1417. if (OPFeeSheet != null)
  1418. {
  1419. string CTGGRFeeSql = string.Empty;
  1420. if (groupInfo.VisitDate > Convert.ToDateTime("2024-04-17"))
  1421. {
  1422. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  1423. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1424. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  1425. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  1426. ccp.DayRate,(ctggrc.Price * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1427. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1428. From Grp_CarTouristGuideGroundReservations ctggr
  1429. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  1430. cggrc.DatePrice,cggrc.PriceContent
  1431. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1432. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1433. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1434. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1435. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1436. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1437. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1438. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1439. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1440. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1441. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1442. }
  1443. else
  1444. {
  1445. CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,
  1446. ccp.PayMoney,sd2.name As PaymentCurrency,ccp.PayPercentage,
  1447. (ccp.PayMoney * (ccp.PayPercentage / 100)) As AmountPaid,
  1448. (ccp.PayMoney -ccp.PayMoney * (ccp.PayPercentage / 100)) As BalancePayment,
  1449. ccp.DayRate,(ccp.PayMoney * (ccp.PayPercentage / 100) * ccp.DayRate) As CNYPrice,
  1450. ccp.Payee,ccp.AuditGMDate,
  1451. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1452. From Grp_CarTouristGuideGroundReservations ctggr
  1453. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1454. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1455. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1456. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1457. Where ctggr.IsDel = 0 {1} And ctggr.DiId = {0}
  1458. Order By CreateTime", _dto.DiId, _dto.isAudit ? "And (ccp.IsAuditGM = 1 OR ccp.IsAuditGM = 3)" : " ");
  1459. }
  1460. var groupOPFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1461. string CTGGRFeeStr = "";
  1462. var OPToDataTableViews = groupOPFeeViews;
  1463. decimal CTGGRCNYTotalPrice = 0.00M;
  1464. //按1 地区,2 币种,3 汇率 分组计算
  1465. var groupCTGGRFeeDatas = groupOPFeeViews.GroupBy(it => it.Area);
  1466. foreach (var ctggfr in groupCTGGRFeeDatas)
  1467. {
  1468. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  1469. if (ctggfr_curr.Count() > 0)
  1470. {
  1471. foreach (var curr in ctggfr_curr)
  1472. {
  1473. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  1474. if (ctggfr_rate.Count() > 0)
  1475. {
  1476. foreach (var rate in ctggfr_rate)
  1477. {
  1478. 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");
  1479. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1480. }
  1481. }
  1482. else
  1483. {
  1484. 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");
  1485. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1486. }
  1487. }
  1488. }
  1489. else
  1490. {
  1491. 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");
  1492. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1493. }
  1494. }
  1495. foreach (var item in groupOPFeeViews)
  1496. {
  1497. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1498. {
  1499. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1500. }
  1501. if (item.DatePrice != null)
  1502. {
  1503. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  1504. }
  1505. }
  1506. OPCNYTotalCost = CTGGRCNYTotalPrice;
  1507. OPFeeDt = CommonFun.ToDataTableArray(OPToDataTableViews);
  1508. OPFeeLabel = CTGGRFeeStr;
  1509. OPFeeDt.TableName = $"OPFeeView";
  1510. }
  1511. #endregion
  1512. #region 签证费用
  1513. if (visaFeeSheet != null)
  1514. {
  1515. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1516. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,sd2.Name As PaymentModes,sd3.Name As CardTypeName,u.CnName As Applicant,vi.CreateTime,
  1517. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1518. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1519. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,vi.Remark
  1520. From Grp_VisaInfo vi
  1521. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1522. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1523. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1524. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1525. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1526. Where vi.IsDel = 0 {1} And vi.DIId = {0} Order By CreateTime", diId,isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1527. var groupVisaFeeViews = _sqlSugar.SqlQueryable<GroupVisaFeeExcelView>(groupVisaFeeSql).ToList();
  1528. foreach (var item in groupVisaFeeViews)
  1529. {
  1530. string names = string.Empty;
  1531. string visaClients = item.VisaClient;
  1532. if (!string.IsNullOrEmpty(visaClients))
  1533. {
  1534. var clientIds = new string[] { };
  1535. if (visaClients.Contains(',')) clientIds = visaClients.Split(',');
  1536. else clientIds = new string[] { visaClients };
  1537. if (clientIds.Length > 0)
  1538. {
  1539. var clientIds1 = new List<int>() { };
  1540. foreach (var clientIdStr in clientIds)
  1541. {
  1542. var isInt = int.TryParse(clientIdStr, out int id);
  1543. if (isInt) clientIds1.Add(id);
  1544. }
  1545. if (clientIds1.Count > 0)
  1546. {
  1547. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  1548. foreach (var client in clients)
  1549. {
  1550. EncryptionProcessor.DecryptProperties(client);
  1551. names += $"{client.LastName + client.FirstName},";
  1552. }
  1553. }
  1554. else names = visaClients;
  1555. }
  1556. if (names.Length > 0) names = names.Substring(0, names.Length - 1);
  1557. item.VisaClient = names;
  1558. }
  1559. }
  1560. visaCNYTotalCost = groupVisaFeeViews.Sum(x => x.CNYPrice);
  1561. visaFeeDt = CommonFun.ToDataTableArray(groupVisaFeeViews);
  1562. visaFeeDt.TableName = $"VisaFeeView";
  1563. }
  1564. #endregion
  1565. #region 邀请费用
  1566. if (OAFeeSheet != null)
  1567. {
  1568. string feeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,CONVERT(DATE, ioa.InviteTime) AS InviteTime,
  1569. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1570. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1571. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.ConsumptionDate,
  1572. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1573. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1574. ccp.Payee,ioa.Remark,ccp.AuditGMDate,u.CnName As Applicant,ioa.CreateTime
  1575. From Grp_InvitationOfficialActivities ioa
  1576. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1577. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1578. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1579. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1580. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1581. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1582. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1583. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1584. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1585. Where ioa.IsDel = 0 {1} And ioa.Diid = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1586. var feeViews = _sqlSugar.SqlQueryable<GroupOAFeeExcelView>(feeSql).ToList();
  1587. OACNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1588. OAFeeDt = CommonFun.ToDataTableArray(feeViews);
  1589. OAFeeDt.TableName = $"OAFeeView";
  1590. }
  1591. #endregion
  1592. #region 机票费用
  1593. if (airTicketFeeSheet != null)
  1594. {
  1595. string feeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,
  1596. sd4.Name As AirTypeName,atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,
  1597. atr.PriceDescription,ccp.PayMoney,ccp.DayRate,sd1.Name As PayMoneyCurrency,
  1598. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1599. ccp.Payee,Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1600. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1601. sd3.Name As CardType,ccp.AuditGMDate,u.CnName As Applicant,atr.CreateTime,atr.Remark
  1602. From Grp_AirTicketReservations atr
  1603. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  1604. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1605. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1606. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1607. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  1608. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1609. Where atr.IsDel = 0 {1} And atr.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1610. var feeViews = _sqlSugar.SqlQueryable<GroupAirTicketExcelView>(feeSql).ToList();
  1611. airTicketCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1612. airTicketFeeDt = CommonFun.ToDataTableArray(feeViews);
  1613. airTicketFeeDt.TableName = $"AirTicketFeeView";
  1614. }
  1615. #endregion
  1616. #region 保险费用
  1617. if (insureFeeSheet != null)
  1618. {
  1619. string feeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,
  1620. sd1.Name As PayMoneyCurrency,ccp.DayRate,ccp.PayMoney * ccp.DayRate As CNYPrice,ccp.ConsumptionDate,
  1621. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1622. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1623. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,ic.CreateTime,ic.Remark
  1624. From Grp_Customers ic
  1625. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1626. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1627. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1628. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1629. Where ic.IsDel = 0 {1} And ic.DiId = {0} Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1630. var feeViews = _sqlSugar.SqlQueryable<GroupInsureExcelView>(feeSql).ToList();
  1631. foreach (var item in feeViews)
  1632. {
  1633. string itemClientName = "";
  1634. string insClients = item.ClientName;
  1635. if (!string.IsNullOrEmpty(insClients))
  1636. {
  1637. string[] clientIds = new string[] { };
  1638. if (insClients.Contains(',')) clientIds = insClients.Split(',');
  1639. else clientIds = new string[] { insClients };
  1640. if (clientIds.Length > 0)
  1641. {
  1642. List<int> output = new List<int>();
  1643. foreach (var clientId in clientIds)
  1644. if (int.TryParse(clientId, out int id))
  1645. output.Add(id);
  1646. if (output.Count > 0)
  1647. {
  1648. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  1649. foreach (var client in clients)
  1650. {
  1651. EncryptionProcessor.DecryptProperties(client);
  1652. itemClientName += $"{client.LastName + client.FirstName},";
  1653. }
  1654. if (itemClientName.Length > 0)
  1655. {
  1656. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1657. }
  1658. }
  1659. else itemClientName = insClients;
  1660. }
  1661. }
  1662. item.ClientName = itemClientName;
  1663. }
  1664. insureCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1665. insureFeeDt = CommonFun.ToDataTableArray(feeViews);
  1666. insureFeeDt.TableName = $"InsureFeeView";
  1667. }
  1668. #endregion
  1669. #region 其他费用
  1670. if (insureFeeSheet != null)
  1671. {
  1672. string feeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1673. ccp.DayRate,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.ConsumptionDate,
  1674. Case When ccp.OrbitalPrivateTransfer = 0 Then '公转' Else '私转' End As CostMark,
  1675. Case When ccp.IsPay = 0 Then '未付款' Else '已付款' End As IsPay,sd2.Name As PaymentModes,
  1676. ccp.Payee,ccp.AuditGMDate,u.CnName As Applicant,dp.CreateTime,dp.Remark
  1677. From Grp_DecreasePayments dp
  1678. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1679. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1680. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1681. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1682. Where dp.IsDel = 0 And ccp.Ctable = 98 {1} And dp.Diid = {0}
  1683. Order By CreateTime", diId, isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1684. var feeViews = _sqlSugar.SqlQueryable<GroupOtherFeeExcelView>(feeSql).ToList();
  1685. otherCNYTotalCost = feeViews.Sum(x => x.CNYPrice);
  1686. otherFeeDt = CommonFun.ToDataTableArray(feeViews);
  1687. otherFeeDt.TableName = $"OtherFeeView";
  1688. }
  1689. #endregion
  1690. #region 收款退还
  1691. if (SKTHFeeSheet != null)
  1692. {
  1693. //删除了 And prom.PriceType = 1
  1694. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1695. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1696. prom.PayType As PrPayType,prom.PriceType As PrPriceType,
  1697. ccp.RMBPrice * ccp.DayRate As RMBPrice,ccp.*,prom.CreateTime As PrCreateTime,prom.Remark AS SKTHRemark
  1698. From Fin_PaymentRefundAndOtherMoney prom
  1699. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1700. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1701. Where prom.IsDel = 0
  1702. And prom.PayType = 1
  1703. And ccp.CTable = 285
  1704. {1}
  1705. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId, _dto.isAudit ? "And ccp.IsAuditGM = 1" : " ");
  1706. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1707. if (_promDatas.Any())
  1708. {
  1709. var _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1710. var _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1711. foreach (var ropItem in _promDatas)
  1712. {
  1713. string thisCueencyCode = "Unknown";
  1714. string thisCueencyName = "Unknown";
  1715. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1716. if (currency != null)
  1717. {
  1718. thisCueencyCode = currency.Name;
  1719. thisCueencyName = currency.Remark;
  1720. }
  1721. string orbitalPrivateTransferStr = "Unknown";
  1722. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1723. if (orbitalPrivateTransfer != null)
  1724. {
  1725. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1726. }
  1727. string payStr = "Unknown";
  1728. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1729. if (pay != null)
  1730. {
  1731. payStr = pay.Name;
  1732. }
  1733. var gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1734. {
  1735. Id = ropItem.Id,
  1736. DiId = ropItem.DIId,
  1737. PriceName = ropItem.PrPriceName,
  1738. PayCurrencyCode = thisCueencyCode,
  1739. PayCurrencyName = thisCueencyName,
  1740. Price = ropItem.PrPrice,
  1741. CNYPrice = ropItem.PayMoney * ropItem.DayRate,
  1742. ThisRate = ropItem.DayRate,
  1743. Payee = ropItem.Payee,
  1744. PayTime = ropItem.AuditGMDate,
  1745. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1746. PayType = payStr,
  1747. IsPay = ropItem.IsPay,
  1748. Applicant = ropItem.Appliction,
  1749. Remark = ropItem.SKTHRemark
  1750. };
  1751. _promView.Add(gsd_PaymentRefund);
  1752. }
  1753. SKTHCNYTotalCost = _promView.Sum(x => x.CNYPrice);
  1754. SKTHFeeDt = CommonFun.ToDataTableArray(_promView);
  1755. SKTHFeeDt.TableName = $"SKTHFeeView";
  1756. }
  1757. }
  1758. #endregion
  1759. #region 应收金额(增加方式=实际报价时 费用必须审核才能进入团组报表)
  1760. decimal frTotalAmount = 0.00M;//应收总金额
  1761. 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,
  1762. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime,fr.Remark
  1763. From Fin_ForeignReceivables fr
  1764. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1765. Left Join Sys_Users u On fr.Auditor = u.Id
  1766. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  1767. var _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1768. _frViews.ForEach(x =>
  1769. {
  1770. string namePrefix = string.Empty;
  1771. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  1772. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  1773. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  1774. x.PriceName = $"{namePrefix}{x.PriceName}";
  1775. });
  1776. if (_frViews.Any())
  1777. {
  1778. accountsAmount = _frViews.Sum(it => it.ItemSumPrice);
  1779. receivableFeeDt = CommonFun.ToDataTableArray(_frViews);
  1780. receivableFeeDt.TableName = $"ReceivedFeeView";
  1781. }
  1782. #endregion
  1783. #region 已收金额
  1784. decimal prTotalAmount = 0.00M;//已收总金额
  1785. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1786. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1787. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1788. From Fin_ProceedsReceived pr
  1789. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1790. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1791. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  1792. var _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1793. if (_prViews.Any())
  1794. {
  1795. receivedAmount = _prViews.Sum(it => it.Price);
  1796. receivedFeeDt = CommonFun.ToDataTableArray(_prViews);
  1797. receivedFeeDt.TableName = $"ReceivableFeeView";
  1798. }
  1799. #endregion
  1800. #region 团组收入支出利润
  1801. groupIEProfitDt.Columns.AddRange(new DataColumn[] {
  1802. new DataColumn(){ ColumnName = "ModuleName"},
  1803. new DataColumn(){ ColumnName = "FeeTotal",DataType = typeof(decimal)},
  1804. new DataColumn(){ ColumnName = "FeeCurrency"},
  1805. });
  1806. var groupIEProfitDt_rows = new[] {
  1807. new object[] { $"签证费用", visaCNYTotalCost, $"CNY" },
  1808. new object[] { $"酒店费用", hotelCNYTotalCost, $"CNY" },
  1809. new object[] { $"地接费用", OPCNYTotalCost, $"CNY" },
  1810. new object[] { $"商邀费用", OACNYTotalCost, $"CNY" },
  1811. new object[] { $"机票费用", airTicketCNYTotalCost, $"CNY" },
  1812. new object[] { $"保险费用", insureCNYTotalCost, $"CNY" },
  1813. new object[] { $"其他费用", otherCNYTotalCost, $"CNY" },
  1814. new object[] { $"收款退还费用", SKTHCNYTotalCost, $"CNY" },
  1815. };
  1816. // 批量添加
  1817. foreach (var rowData in groupIEProfitDt_rows)
  1818. {
  1819. groupIEProfitDt.Rows.Add(rowData);
  1820. }
  1821. #endregion
  1822. #region 统一填充数据源
  1823. designer.SetDataSource("GroupNo", groupNo);
  1824. designer.SetDataSource("GroupName", groupName);
  1825. designer.SetDataSource("Lister", lister);
  1826. //酒店
  1827. designer.SetDataSource(hotelFeeDt);
  1828. designer.SetDataSource("HotelCNYTotalCost", $"{hotelCNYTotalCost.ToString("#0.00")} CNY");
  1829. //地接
  1830. designer.SetDataSource(OPFeeDt);
  1831. designer.SetDataSource("OPFeeLabel", OPFeeLabel);
  1832. designer.SetDataSource("OPCNYTotalCost", $"{OPCNYTotalCost.ToString("#0.00")} CNY");
  1833. //签证
  1834. designer.SetDataSource(visaFeeDt);
  1835. designer.SetDataSource("VisaCNYTotalCost", $"{visaCNYTotalCost.ToString("#0.00")} CNY");
  1836. //商邀
  1837. designer.SetDataSource(OAFeeDt);
  1838. designer.SetDataSource("OACNYTotalCost", $"{OACNYTotalCost.ToString("#0.00")} CNY");
  1839. //机票
  1840. designer.SetDataSource(airTicketFeeDt);
  1841. designer.SetDataSource("AirTicketCNYTotalCost", $"{airTicketCNYTotalCost.ToString("#0.00")} CNY");
  1842. //保险
  1843. designer.SetDataSource(insureFeeDt);
  1844. designer.SetDataSource("InsureCNYTotalCost", $"{insureCNYTotalCost.ToString("#0.00")} CNY");
  1845. //其他费用
  1846. designer.SetDataSource(otherFeeDt);
  1847. designer.SetDataSource("OtherCNYTotalCost", $"{otherCNYTotalCost.ToString("#0.00")} CNY");
  1848. //收款退还
  1849. designer.SetDataSource(SKTHFeeDt);
  1850. designer.SetDataSource("SKTHCNYTotalCost", $"{SKTHCNYTotalCost.ToString("#0.00")}");
  1851. //已收金额
  1852. designer.SetDataSource(receivedFeeDt);
  1853. designer.SetDataSource("ReceivedAmount", $"{receivedAmount.ToString("#0.00")}");
  1854. //应收金额
  1855. designer.SetDataSource(receivableFeeDt);
  1856. designer.SetDataSource("AccountsAmount", $"{accountsAmount.ToString("#0.00")}");
  1857. //应收已收 -- 尾款
  1858. var balancePayment = accountsAmount - SKTHCNYTotalCost - receivedAmount;
  1859. designer.SetDataSource("BalancePayment", $"{balancePayment.ToString("#0.00")}");
  1860. //团组收入支出利润
  1861. designer.SetDataSource(groupIEProfitDt);
  1862. #region 各项费用计算
  1863. /*
  1864. * 团组报表计算方式
  1865. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1866. * 应收金额 = 应收表.Sum() - 收款退还
  1867. * 已收金额 = 已收表.Sum() - 收款退还
  1868. * 应收利润(应收-支出) = 应收金额 - 当前总支出
  1869. * 已收利润(已收-支出) = 已收金额 - 当前总支出
  1870. * 利润差 = 应收利润 - 已收利润
  1871. */
  1872. totalAmount = visaCNYTotalCost + hotelCNYTotalCost + OPCNYTotalCost + OACNYTotalCost + airTicketCNYTotalCost + insureCNYTotalCost + otherCNYTotalCost;//合计金额
  1873. accountsProfit = accountsAmount - totalAmount - SKTHCNYTotalCost; //应收利润
  1874. receiveProfit = receivedAmount - totalAmount - SKTHCNYTotalCost; //已收利润
  1875. profitMargin = accountsProfit - receiveProfit; //利润差
  1876. designer.SetDataSource("TotalAmount", $"{totalAmount.ToString("#0.00")}");
  1877. designer.SetDataSource("AccountsProfit", $"{accountsProfit.ToString("#0.00")}");
  1878. designer.SetDataSource("ReceiveProfit", $"{receiveProfit.ToString("#0.00")}");
  1879. designer.SetDataSource("ProfitMargin", $"{profitMargin.ToString("#0.00")}");
  1880. #endregion
  1881. designer.Process();
  1882. #endregion
  1883. #region 单元格样式设置 未付款设置为红色
  1884. /*
  1885. * 设置单元格样式
  1886. */
  1887. //背景颜色
  1888. Style style = designer.Workbook.CreateStyle();
  1889. style.ForegroundColor = Color.FromArgb(254, 242, 203);
  1890. style.Pattern = BackgroundType.Solid;
  1891. //字体
  1892. style.Font.Name = "微软雅黑"; // 字体名称
  1893. style.Font.Size = 10; // 字体大小
  1894. style.Font.Color = System.Drawing.Color.Black; // 字体颜色
  1895. StatementExportExcelSetCell(designer, hotelFeeSheet, hotelFeeDt, style, "IsPayLable", 8, "A", "V"); //酒店
  1896. StatementExportExcelSetCell(designer, OPFeeSheet, OPFeeDt, style, "IsPayLabel", 6, "A", "M"); //OP
  1897. StatementExportExcelSetCell(designer, visaFeeSheet, visaFeeDt, style, "IsPay", 6, "A", "I"); //签证
  1898. StatementExportExcelSetCell(designer, OAFeeSheet, OAFeeDt, style, "IsPay", 6, "A", "R"); //商邀
  1899. StatementExportExcelSetCell(designer, airTicketFeeSheet, airTicketFeeDt, style, "IsPay", 6, "A", "M"); //机票
  1900. StatementExportExcelSetCell(designer, insureFeeSheet, insureFeeDt, style, "IsPay", 6, "A", "I"); //保险
  1901. StatementExportExcelSetCell(designer, otherFeeSheet, otherFeeDt, style, "IsPay", 6, "A", "J"); //其他
  1902. StatementExportExcelSetCell(designer, SKTHFeeSheet, SKTHFeeDt, style, "IsPayLable", 6, "A", "K"); //首款退还
  1903. #endregion
  1904. //文件名
  1905. string fileName = $"{groupName}[{groupNo}]_团组费用清单{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  1906. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "GroupStatement/" + fileName);
  1907. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/GroupStatement/" + fileName;
  1908. return Ok(JsonView(true, "成功", url));
  1909. }
  1910. private void StatementExportExcelSetCell(WorkbookDesigner designer, Worksheet sheet,DataTable dt, Style style,string judgeLable, int startIndex, string startRange,string endRange)
  1911. {
  1912. if (designer == null) return;
  1913. if (sheet == null) return;
  1914. if (style == null) return;
  1915. if (dt == null) return;
  1916. if (string.IsNullOrEmpty(startRange)) return;
  1917. if (string.IsNullOrEmpty(endRange)) return;
  1918. for (int i = 0; i < dt.Rows.Count; i++)
  1919. {
  1920. var isPayStr = dt.Rows[i][$"{judgeLable}"].ToString();
  1921. if (string.IsNullOrEmpty(isPayStr)) continue;
  1922. if (isPayStr.Contains("未付款"))
  1923. {
  1924. var excelIndex = startIndex + i;
  1925. Aspose.Cells.Range range = sheet.Cells.CreateRange($"{startRange}{excelIndex}", $"{endRange}{excelIndex}");
  1926. range.ApplyStyle(style, new StyleFlag() { CellShading = true, Font = true });
  1927. }
  1928. }
  1929. }
  1930. #endregion
  1931. #region 报表/折线图统计
  1932. //企业利润-团组利润
  1933. //企业利润-会务利润
  1934. /// <summary>
  1935. /// 企业利润
  1936. /// Details
  1937. /// 待添加权限验证
  1938. /// </summary>
  1939. /// <param name="_dto">团组列表请求dto</param>
  1940. /// <returns></returns>
  1941. [HttpPost("PostCorporateProfit")]
  1942. //[JsonConverter(typeof(DecimalConverter), 2)]
  1943. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1944. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  1945. {
  1946. #region 参数验证
  1947. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1948. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1949. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1950. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  1951. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  1952. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1953. #region 页面操作权限验证
  1954. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1955. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1956. #endregion
  1957. string sqlWhere = string.Empty;
  1958. //起止时间
  1959. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1960. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1961. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1962. //业务类型
  1963. List<int> groupTypeId = new List<int>();
  1964. if (_dto.BusinessType == 2) //团组
  1965. {
  1966. groupTypeId.AddRange(new List<int>() {
  1967. 38, // 政府团
  1968. 39, // 企业团
  1969. 40, // 散客团
  1970. 1048 // 高校团
  1971. });
  1972. }
  1973. else if (_dto.BusinessType == 3) //会务
  1974. {
  1975. groupTypeId.AddRange(new List<int>() {
  1976. 102, // 未知
  1977. 248, // 非团组
  1978. 302, // 成都-会务活动
  1979. 691, // 四川-会务活动
  1980. 762, // 四川-赛事项目收入
  1981. 1047 // 成都-赛事项目收入
  1982. });
  1983. }
  1984. if (groupTypeId.Count > 0)
  1985. {
  1986. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  1987. }
  1988. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  1989. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  1990. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  1991. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  1992. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  1993. List<MonthInfo> months = new List<MonthInfo>();
  1994. if (_dto.StatisticsType == 1) //月份
  1995. {
  1996. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  1997. }
  1998. else if (_dto.StatisticsType == 1) //季度
  1999. {
  2000. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  2001. }
  2002. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  2003. foreach (var item in months)
  2004. {
  2005. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  2006. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  2007. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  2008. _view.Add(new CorporateProfitMonthView()
  2009. {
  2010. Month = item.Month,
  2011. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  2012. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  2013. });
  2014. }
  2015. return Ok(JsonView(true, "操作成功!", _view));
  2016. #endregion
  2017. }
  2018. /// <summary>
  2019. /// 计算团组利润
  2020. /// </summary>
  2021. /// <param name="diIds"></param>
  2022. /// <returns></returns>
  2023. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  2024. {
  2025. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  2026. if (diIds.Count < 1)
  2027. {
  2028. return corporateProfits;
  2029. }
  2030. #region 计算团组利润
  2031. /*
  2032. * 团组报表计算方式
  2033. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2034. * 应收金额 = 应收表.Sum()
  2035. * 已收金额 = 已收表.Sum()
  2036. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2037. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2038. *
  2039. */
  2040. string diIdStr = string.Join(",", diIds);
  2041. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  2042. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  2043. #region 费用类型 币种,转账,客户信息
  2044. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  2045. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  2046. #endregion
  2047. foreach (var _diId in diIds)
  2048. {
  2049. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  2050. #region 团组收入
  2051. /*
  2052. * 应收报表
  2053. */
  2054. decimal frTotalAmount = 0.00M;//应收总金额
  2055. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  2056. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  2057. From Fin_ForeignReceivables fr
  2058. Left Join Sys_SetData sd On fr.Currency = sd.Id
  2059. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  2060. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  2061. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  2062. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  2063. /*
  2064. * 已收报表
  2065. */
  2066. decimal prTotalAmount = 0.00M;//已收总金额
  2067. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  2068. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  2069. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  2070. From Fin_ProceedsReceived pr
  2071. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  2072. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  2073. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  2074. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  2075. prTotalAmount = _prViews.Sum(it => it.Price);
  2076. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  2077. /*
  2078. * 超支费用
  2079. */
  2080. decimal exTotalAmount = 0.00M;
  2081. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  2082. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2083. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  2084. From OA2023DB.dbo.Fin_GroupExtraCost gec
  2085. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  2086. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2087. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2088. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2089. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2090. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  2091. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  2092. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  2093. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  2094. /*
  2095. * 收款退还
  2096. */
  2097. decimal promTotalAmount = 0.00M;// 收款退还总金额
  2098. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  2099. //删除了 And prom.PriceType = 1
  2100. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  2101. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  2102. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  2103. From Fin_PaymentRefundAndOtherMoney prom
  2104. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  2105. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2106. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  2107. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  2108. And prom.DiId = {0} Order By PrCreateTime", _diId);
  2109. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  2110. foreach (var ropItem in _promDatas)
  2111. {
  2112. string thisCueencyCode = "Unknown";
  2113. string thisCueencyName = "Unknown";
  2114. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  2115. if (currency != null)
  2116. {
  2117. thisCueencyCode = currency.Name;
  2118. thisCueencyName = currency.Remark;
  2119. }
  2120. string orbitalPrivateTransferStr = "Unknown";
  2121. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  2122. if (orbitalPrivateTransfer != null)
  2123. {
  2124. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  2125. }
  2126. string payStr = "Unknown";
  2127. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  2128. if (pay != null)
  2129. {
  2130. payStr = pay.Name;
  2131. }
  2132. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  2133. {
  2134. Id = ropItem.Id,
  2135. DiId = ropItem.DIId,
  2136. PriceName = ropItem.PrPriceName,
  2137. PayCurrencyCode = thisCueencyCode,
  2138. PayCurrencyName = thisCueencyName,
  2139. Price = ropItem.PrPrice,
  2140. CNYPrice = ropItem.RMBPrice,
  2141. ThisRate = ropItem.DayRate,
  2142. Payee = ropItem.Payee,
  2143. PayTime = ropItem.AuditGMDate,
  2144. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  2145. PayType = payStr,
  2146. IsPay = ropItem.IsPay,
  2147. Applicant = ropItem.Appliction
  2148. };
  2149. _promView.Add(gsd_PaymentRefund);
  2150. }
  2151. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  2152. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  2153. #endregion
  2154. #region 团组支出
  2155. GroupExpenditureView _geView = new GroupExpenditureView();
  2156. #region 酒店预定费用
  2157. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  2158. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  2159. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  2160. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  2161. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  2162. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  2163. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  2164. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  2165. From Grp_HotelReservations hr
  2166. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  2167. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2168. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2169. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2170. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2171. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  2172. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  2173. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  2174. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  2175. Order By CheckInDate Asc", _diId);
  2176. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  2177. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  2178. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  2179. #endregion
  2180. #region 地接费用
  2181. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  2182. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  2183. sd2.name As PaymentCurrency,ccp.PayPercentage,
  2184. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  2185. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  2186. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2187. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  2188. From Grp_CarTouristGuideGroundReservations ctggr
  2189. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  2190. cggrc.PriceContent
  2191. From Grp_CarTouristGuideGroundReservationsContent cggrc
  2192. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  2193. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  2194. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  2195. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  2196. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  2197. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  2198. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  2199. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2200. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  2201. Order By CreateTime", _diId);
  2202. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  2203. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2204. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  2205. #endregion
  2206. #region 机票预订费用
  2207. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  2208. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  2209. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  2210. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  2211. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  2212. From Grp_AirTicketReservations atr
  2213. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  2214. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2215. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2216. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2217. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  2218. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2219. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  2220. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  2221. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  2222. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  2223. #endregion
  2224. #region 签证费用
  2225. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  2226. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2227. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  2228. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  2229. From Grp_VisaInfo vi
  2230. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  2231. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2232. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2233. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  2234. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2235. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  2236. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  2237. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  2238. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  2239. #endregion
  2240. #region 邀请/公务活动 CTable = 81
  2241. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  2242. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  2243. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  2244. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  2245. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  2246. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  2247. From Grp_InvitationOfficialActivities ioa
  2248. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  2249. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2250. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2251. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  2252. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  2253. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  2254. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  2255. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  2256. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2257. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  2258. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  2259. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  2260. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  2261. #endregion
  2262. #region 保险费用
  2263. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  2264. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  2265. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2266. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  2267. From Grp_Customers ic
  2268. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  2269. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2270. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2271. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2272. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  2273. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  2274. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  2275. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  2276. #endregion
  2277. #region 其他款项费用 98
  2278. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  2279. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  2280. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  2281. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  2282. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  2283. From Grp_DecreasePayments dp
  2284. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  2285. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  2286. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  2287. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  2288. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  2289. Order By CreateTime", _diId);
  2290. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  2291. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  2292. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  2293. #endregion
  2294. #endregion
  2295. /*
  2296. * 团组报表计算方式
  2297. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  2298. * 应收金额 = 应收表.Sum()
  2299. * 已收金额 = 已收表.Sum()
  2300. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  2301. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  2302. *
  2303. */
  2304. decimal _totalExpenditure = 0.00M; //总支出
  2305. decimal _amountReceivable = 0.00M; //应收金额
  2306. decimal _amountReceived = 0.00M; //已收金额
  2307. decimal _receivableProfit = 0.00M; //应收利润
  2308. decimal _receivedProfit = 0.00M; //已收利润
  2309. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  2310. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  2311. _amountReceivable = frTotalAmount;
  2312. _amountReceived = prTotalAmount;
  2313. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  2314. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  2315. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  2316. corporateProfits.Add(new CorporateProfit()
  2317. {
  2318. DiId = _diId,
  2319. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  2320. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  2321. TotalExpenditure = _totalExpenditure,
  2322. ExpenditureItem = expenditureInfos,
  2323. AmountReceivable = _amountReceivable,
  2324. AmountReceived = _amountReceived,
  2325. ReceivableProfit = _receivableProfit,
  2326. ReceivedProfit = _receivedProfit,
  2327. });
  2328. }
  2329. #endregion
  2330. return corporateProfits;
  2331. }
  2332. //未来预测-地区接团/出团量
  2333. //未来预测-地区酒店预订量
  2334. //未来预测-地区机票预订量
  2335. //未来预测-地区车辆预订量
  2336. /// <summary>
  2337. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  2338. /// Details
  2339. /// 待添加权限验证
  2340. /// </summary>
  2341. /// <param name="_dto">团组列表请求dto</param>
  2342. /// <returns></returns>
  2343. [HttpPost("PostRegionalBookingsNumber")]
  2344. //[JsonConverter(typeof(DecimalConverter), 2)]
  2345. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2346. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  2347. {
  2348. #region 参数验证
  2349. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  2350. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  2351. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  2352. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  2353. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2354. #region 页面操作权限验证
  2355. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2356. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2357. #endregion
  2358. string sqlWhere = string.Empty;
  2359. //起止时间
  2360. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  2361. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  2362. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  2363. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  2364. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  2365. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  2366. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  2367. foreach (var item in groupInfos)
  2368. {
  2369. var data = await GroupBookingsNumber(_dto.Type, item);
  2370. if (data.TypeItem.Count > 0)
  2371. {
  2372. datas.Add(data);
  2373. }
  2374. }
  2375. //类型处理
  2376. if (_dto.Type == 1)//接团
  2377. {
  2378. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  2379. dynamic groupData = null;
  2380. foreach (var item in datas)
  2381. {
  2382. if (item.TypeItem.Count > 0)
  2383. {
  2384. foreach (var item1 in item.TypeItem)
  2385. {
  2386. if (item1.RegionItem.Count > 0)
  2387. {
  2388. GroupInfo groupInfo = new GroupInfo()
  2389. {
  2390. DiId = item.DiId,
  2391. TeamName = item.GroupName,
  2392. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2393. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2394. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2395. };
  2396. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  2397. }
  2398. }
  2399. }
  2400. }
  2401. var viewsGroup = views.GroupBy(it => it.Name);
  2402. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  2403. foreach (var item in viewsGroup)
  2404. {
  2405. List<GroupInfo> infos = new List<GroupInfo>();
  2406. foreach (var item1 in item)
  2407. {
  2408. infos.AddRange(item1.GroupItem);
  2409. }
  2410. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  2411. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  2412. }
  2413. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2414. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  2415. }
  2416. else if (_dto.Type == 2)
  2417. {
  2418. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  2419. foreach (var item in datas)
  2420. {
  2421. if (item.TypeItem.Count > 0)
  2422. {
  2423. foreach (var item1 in item.TypeItem)
  2424. {
  2425. if (item1.RegionItem.Count > 0)
  2426. {
  2427. foreach (var item2 in item1.RegionItem)
  2428. {
  2429. GroupInfo groupInfo = new GroupInfo()
  2430. {
  2431. DiId = item.DiId,
  2432. TeamName = item.GroupName,
  2433. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  2434. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  2435. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  2436. };
  2437. List<HotelInfo> hotels = new List<HotelInfo>();
  2438. foreach (var item3 in item2.Data)
  2439. {
  2440. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  2441. HotelInfo hotelInfo = new HotelInfo()
  2442. {
  2443. HotelName = statisticsHotelInfos.HotelName,
  2444. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  2445. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  2446. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  2447. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  2448. GroupInfo = groupInfo
  2449. };
  2450. hotels.Add(hotelInfo);
  2451. }
  2452. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  2453. }
  2454. }
  2455. }
  2456. }
  2457. }
  2458. var viewsGroup = views.GroupBy(it => it.Name);
  2459. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  2460. foreach (var item in viewsGroup)
  2461. {
  2462. List<HotelInfo> infos = new List<HotelInfo>();
  2463. foreach (var item1 in item)
  2464. {
  2465. infos.AddRange(item1.HotelItem);
  2466. }
  2467. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  2468. }
  2469. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  2470. return Ok(JsonView(true, "操作成功!", views, views.Count));
  2471. }
  2472. return Ok(JsonView(false, "操作失败!"));
  2473. #endregion
  2474. }
  2475. /// <summary>
  2476. /// 计算团组ALLType预订数量
  2477. /// </summary>
  2478. /// <param name="diIds"></param>
  2479. /// <returns></returns>
  2480. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  2481. {
  2482. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  2483. if (info == null)
  2484. {
  2485. return _view;
  2486. }
  2487. _view.DiId = info.Id;
  2488. _view.GroupName = info.TeamName;
  2489. List<TypeInfo> _types = new List<TypeInfo>();
  2490. #region 计算团组ALLType预订数量
  2491. if (type == 1)
  2492. {
  2493. //接团 客户集团所在地区
  2494. string group_region = string.Empty;
  2495. int group_number = 0;
  2496. if (!string.IsNullOrEmpty(info.ClientUnit))
  2497. {
  2498. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>()
  2499. .Where(it => it.IsDel == 0 && it.Client.Equals(AesEncryptionHelper.Encrypt(info.ClientUnit)))
  2500. .FirstAsync();
  2501. if (_NewClientData != null)
  2502. {
  2503. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  2504. if (regionInfo != null)
  2505. {
  2506. group_region = regionInfo.Name.Replace("级", "");
  2507. group_number++;
  2508. }
  2509. }
  2510. }
  2511. if (group_number > 0)
  2512. {
  2513. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  2514. }
  2515. }
  2516. else if (type == 2)
  2517. {
  2518. //酒店
  2519. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2520. if (hotelInfos.Count > 0)
  2521. {
  2522. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  2523. foreach (var item in hotelInfos)
  2524. {
  2525. var hotelNumberInfo = new StatisticsHotelInfo()
  2526. {
  2527. HotelName = item.HotelName,
  2528. SingleRoomNum = item.SingleRoomCount,
  2529. DoubleRoomNum = item.DoubleRoomCount,
  2530. SuiteRoomNum = item.SuiteRoomCount,
  2531. OtherRoomNum = item.OtherRoomCount,
  2532. };
  2533. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  2534. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  2535. {
  2536. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  2537. if (hotelRegion != null)
  2538. {
  2539. hotelRegions.Remove(hotelRegion);
  2540. if (hotelRegion.Data.Count > 0)
  2541. {
  2542. hotelRegion.Data.Add(hotelNumberInfo);
  2543. }
  2544. hotelRegion.Number += hotelRoomTotal;
  2545. hotelRegions.Add(hotelRegion);
  2546. }
  2547. }
  2548. else
  2549. {
  2550. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  2551. }
  2552. }
  2553. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  2554. }
  2555. }
  2556. else if (type == 3)
  2557. {
  2558. //机票
  2559. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  2560. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  2561. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  2562. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  2563. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  2564. .ToListAsync();
  2565. if (airTicketInfos.Count > 0)
  2566. {
  2567. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  2568. foreach (var item in airTicketInfos)
  2569. {
  2570. var ticketClass = new
  2571. {
  2572. TiketClass = item.AirType,
  2573. Number = item.ClientNum
  2574. };
  2575. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  2576. {
  2577. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  2578. if (airTicketRegion != null)
  2579. {
  2580. airTicketRegions.Remove(airTicketRegion);
  2581. if (airTicketRegion.Data.Count > 0)
  2582. {
  2583. airTicketRegion.Data.Add(ticketClass);
  2584. }
  2585. airTicketRegion.Number += item.ClientNum;
  2586. airTicketRegions.Add(airTicketRegion);
  2587. }
  2588. }
  2589. else
  2590. {
  2591. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  2592. }
  2593. }
  2594. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  2595. }
  2596. }
  2597. else if (type == 4)
  2598. {
  2599. //车辆
  2600. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2601. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  2602. if (opInfos.Count > 0)
  2603. {
  2604. List<RegionInfo> opRegions = new List<RegionInfo>();
  2605. foreach (var item in opInfos)
  2606. {
  2607. int carNum = 0;
  2608. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  2609. if (opContentInfo.Count > 0)
  2610. {
  2611. foreach (var item1 in opContentInfo)
  2612. {
  2613. if (item1.Price > 0 && item1.Count > 0)
  2614. {
  2615. carNum += item1.Count;
  2616. }
  2617. }
  2618. }
  2619. if (carNum > 0)
  2620. {
  2621. var opData = new
  2622. {
  2623. ServiceCompany = item.ServiceCompany,
  2624. BusName = item.BusName,
  2625. Numbuer = carNum
  2626. };
  2627. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  2628. {
  2629. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  2630. if (opRegion != null)
  2631. {
  2632. opRegions.Remove(opRegion);
  2633. if (opRegion.Data.Count > 0)
  2634. {
  2635. opRegion.Data.Add(opData);
  2636. }
  2637. opRegion.Number += carNum;
  2638. opRegions.Add(opRegion);
  2639. }
  2640. }
  2641. else
  2642. {
  2643. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  2644. }
  2645. }
  2646. }
  2647. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  2648. }
  2649. }
  2650. #endregion
  2651. _view.TypeItem = _types;
  2652. return _view;
  2653. }
  2654. #endregion
  2655. #region 市场部销售额
  2656. /// <summary>
  2657. /// 市场部销售额
  2658. /// Init 基础数据(公司/人员/年份/季度/月份)
  2659. /// </summary>
  2660. /// <param name="_dto">市场部销售额请求dto</param>
  2661. /// <returns></returns>
  2662. [HttpPost("PostMarketingSalesInitData")]
  2663. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2664. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  2665. {
  2666. #region 参数验证
  2667. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  2668. var validResult = await validationRules.ValidateAsync(_dto);
  2669. if (!validResult.IsValid)
  2670. {
  2671. var errors = new StringBuilder();
  2672. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2673. return Ok(JsonView(false, errors.ToString()));
  2674. }
  2675. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2676. #region 页面操作权限验证
  2677. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2678. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2679. #endregion
  2680. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  2681. .Select(it => new { id = it.Id, name = it.CompanyName })
  2682. .ToList();
  2683. List<int> companyIds = companyData.Select(it => it.id).ToList();
  2684. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  2685. .Select(it => it.JietuanOperator)
  2686. .ToList();
  2687. var userData = _sqlSugar.Queryable<Sys_Users>()
  2688. .Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  2689. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  2690. .ToList();
  2691. companyData.Insert(0, new { id = -1, name = "全部" });
  2692. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  2693. #region 年份
  2694. var dtData = new List<dynamic>();
  2695. int dt = DateTime.Now.Year;
  2696. for (int y = dt; y >= dt - 4; y--)
  2697. {
  2698. //季度
  2699. var quarterDatas = new List<dynamic>();
  2700. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  2701. for (int q = 0; q < 4; q++)
  2702. {
  2703. dynamic quarterData = null;
  2704. if (q == 0)
  2705. {
  2706. var monthDatas = new List<dynamic>();
  2707. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  2708. for (int m = 1; m < 4; m++)
  2709. {
  2710. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2711. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2712. }
  2713. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  2714. quarterData = new { name = "第一季度", monthData = monthDatas };
  2715. }
  2716. else if (q == 1)
  2717. {
  2718. var monthDatas = new List<dynamic>();
  2719. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  2720. for (int m = 4; m < 7; m++)
  2721. {
  2722. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2723. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2724. }
  2725. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  2726. quarterData = new { name = "第二季度", monthData = monthDatas };
  2727. }
  2728. else if (q == 2)
  2729. {
  2730. var monthDatas = new List<dynamic>();
  2731. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  2732. for (int m = 7; m < 10; m++)
  2733. {
  2734. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2735. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2736. }
  2737. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  2738. quarterData = new { name = "第三季度", monthData = monthDatas };
  2739. }
  2740. else if (q == 3)
  2741. {
  2742. var monthDatas = new List<dynamic>();
  2743. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  2744. for (int m = 10; m < 13; m++)
  2745. {
  2746. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  2747. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  2748. }
  2749. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  2750. quarterData = new { name = "第四季度", monthData = monthDatas };
  2751. }
  2752. quarterDatas.Add(quarterData);
  2753. }
  2754. dtData.Add(new
  2755. {
  2756. year = y,
  2757. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  2758. quarterData = quarterDatas,
  2759. });
  2760. }
  2761. #endregion
  2762. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  2763. #endregion
  2764. }
  2765. private static string ConvertToChinese(int month)
  2766. {
  2767. if (month < 1 || month > 12)
  2768. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  2769. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  2770. var dateTimeFormat = cultureInfo.DateTimeFormat;
  2771. return dateTimeFormat.GetMonthName(month);
  2772. }
  2773. /// <summary>
  2774. /// 市场部销售额
  2775. /// 年度/季度/月度 报表(同比)
  2776. /// </summary>
  2777. /// <param name="_dto">市场部销售额请求dto</param>
  2778. /// <returns></returns>
  2779. [HttpPost("PostMarketingSalesStatistics")]
  2780. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2781. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  2782. {
  2783. #region 参数验证
  2784. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2785. var validResult = await validationRules.ValidateAsync(_dto);
  2786. if (!validResult.IsValid)
  2787. {
  2788. var errors = new StringBuilder();
  2789. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2790. return Ok(JsonView(false, errors.ToString()));
  2791. }
  2792. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2793. #region 页面操作权限验证
  2794. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2795. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2796. #endregion
  2797. #endregion
  2798. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2799. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  2800. }
  2801. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  2802. {
  2803. //全部人员Id
  2804. //查询所有公司的市场部
  2805. var pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  2806. var userIds = new List<int>();
  2807. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  2808. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  2809. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains(u.Id))
  2810. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  2811. .ToListAsync();
  2812. userIds = userDatas.Select(it => it.Id).ToList();
  2813. if (companyId > 0)
  2814. {
  2815. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2816. }
  2817. if (groupPickupUserId > 0)
  2818. {
  2819. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2820. }
  2821. return userIds;
  2822. }
  2823. /// <summary>
  2824. /// 计算团组销售额
  2825. /// </summary>
  2826. /// <param name="companyId"></param>
  2827. /// <param name="groupPickupUserId"></param>
  2828. /// <param name="beginDt"></param>
  2829. /// <param name="endDt"></param>
  2830. /// <returns></returns>
  2831. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId, string beginDt, string endDt)
  2832. {
  2833. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2834. var _view = new SalesYOYView();
  2835. List<int> userIds = new List<int>();
  2836. userIds = await GetUserIds(companyId, groupPickupUserId);
  2837. string userSqlWhere = "";
  2838. if (userIds.Count > 0)
  2839. {
  2840. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2841. }
  2842. else
  2843. {
  2844. _view = new SalesYOYView
  2845. {
  2846. thisYearSales = "0.00",
  2847. lastYearSales = "0.00",
  2848. };
  2849. return _view;
  2850. }
  2851. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2852. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2853. // string salesSql = string.Format(@"
  2854. //SELECT
  2855. // 'ThisSales' As [Name],
  2856. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2857. //FROM
  2858. // (
  2859. // SELECT di.VisitDate,
  2860. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2861. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2862. // ) AS Sales
  2863. // FROM
  2864. // Grp_DelegationInfo di
  2865. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2866. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2867. // AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2868. // ) temp
  2869. //Union ALL
  2870. //SELECT
  2871. // 'LastSales' As [Name],
  2872. // CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2873. //FROM
  2874. // (
  2875. // SELECT di.VisitDate,
  2876. // (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2877. // WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2878. // ) AS Sales
  2879. // FROM
  2880. // Grp_DelegationInfo di
  2881. // WHERE di.IsDel = 0 AND di.IsSure = 1
  2882. // AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2883. // AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2884. // ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2885. string salesSql = string.Format(@"
  2886. SELECT
  2887. 'ThisSales' As [Name],
  2888. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2889. FROM
  2890. (
  2891. SELECT di.VisitDate,
  2892. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2893. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2894. ) AS Sales
  2895. FROM
  2896. Grp_DelegationInfo di
  2897. WHERE di.IsDel = 0
  2898. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2899. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2900. ) temp
  2901. Union ALL
  2902. SELECT
  2903. 'LastSales' As [Name],
  2904. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2905. FROM
  2906. (
  2907. SELECT di.VisitDate,
  2908. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2909. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2910. ) AS Sales
  2911. FROM
  2912. Grp_DelegationInfo di
  2913. WHERE di.IsDel = 0
  2914. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2915. AND di.IsBid = 0
  2916. AND di.TeamName Not Like '%投标%'
  2917. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2918. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2919. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  2920. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  2921. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  2922. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  2923. return new SalesYOYView()
  2924. {
  2925. thisYearSales = thisSales.ToString("#0.00"),
  2926. lastYearSales = lastSales.ToString("#0.00"),
  2927. yoy = yoy.ToString("#0.00")
  2928. };
  2929. }
  2930. private class SalesView
  2931. {
  2932. public string Name { get; set; }
  2933. public decimal Sales { get; set; }
  2934. }
  2935. private class SalesYOYView
  2936. {
  2937. public string thisYearSales { get; set; }
  2938. public string lastYearSales { get; set; }
  2939. public string yoy { get; set; } = "1.00";
  2940. }
  2941. /// <summary>
  2942. /// 市场部销售额
  2943. /// 团组列表
  2944. /// </summary>
  2945. /// <param name="_dto">市场部销售额请求dto</param>
  2946. /// <returns></returns>
  2947. [HttpPost("PostMarketingSalesGroupList")]
  2948. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2949. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  2950. {
  2951. #region 参数验证
  2952. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2953. var validResult = await validationRules.ValidateAsync(_dto);
  2954. if (!validResult.IsValid)
  2955. {
  2956. var errors = new StringBuilder();
  2957. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2958. return Ok(JsonView(false, errors.ToString()));
  2959. }
  2960. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2961. #region 页面操作权限验证
  2962. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2963. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2964. #endregion
  2965. #endregion
  2966. string userSql = "";
  2967. List<int> userIds = new List<int>();
  2968. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2969. if (userIds.Count <= 0)
  2970. {
  2971. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2972. }
  2973. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2974. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2975. {
  2976. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2977. }
  2978. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2979. // string sql = string.Format(@$"SELECT
  2980. // ROW_NUMBER() OVER (
  2981. // ORDER BY
  2982. // CollectionDays
  2983. // ) AS RowNumber,
  2984. // *
  2985. //FROM
  2986. // (
  2987. // SELECT
  2988. // di.Id,
  2989. // di.TeamName,
  2990. // di.ClientUnit,
  2991. // di.ClientName,
  2992. // di.VisitDate,
  2993. // di.VisitPNumber,
  2994. // di.JietuanOperator,
  2995. // di.VisitEndDate,
  2996. // (
  2997. // SELECT
  2998. // CAST(
  2999. // COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3000. // ) AS GroupSales
  3001. // FROM
  3002. // Fin_ForeignReceivables
  3003. // WHERE
  3004. // IsDel = 0
  3005. // AND di.Id = Diid
  3006. // AND AddingWay IN (0, 1, 2)
  3007. // ) AS GroupSales,
  3008. // u.CnName AS GroupPickupUser,
  3009. // DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3010. // FROM
  3011. // Grp_DelegationInfo di
  3012. // WITH
  3013. // (NoLock)
  3014. // LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3015. // WHERE
  3016. // di.Isdel = 0
  3017. // AND di.IsSure = 1 {userSql}
  3018. // AND VisitDate Between '{beginDt}' And '{endDt}'
  3019. // ) Temp ");
  3020. string sql = string.Format(@$"SELECT
  3021. ROW_NUMBER() OVER (
  3022. ORDER BY
  3023. CollectionDays
  3024. ) AS RowNumber,
  3025. *
  3026. FROM
  3027. (
  3028. SELECT
  3029. di.Id,
  3030. di.TeamName,
  3031. di.ClientUnit,
  3032. di.ClientName,
  3033. di.VisitDate,
  3034. di.VisitPNumber,
  3035. di.JietuanOperator,
  3036. di.VisitEndDate,
  3037. (
  3038. SELECT
  3039. CAST(
  3040. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3041. ) AS GroupSales
  3042. FROM
  3043. Fin_ForeignReceivables
  3044. WHERE
  3045. IsDel = 0
  3046. AND di.Id = Diid
  3047. AND AddingWay IN (0, 1, 2)
  3048. ) AS GroupSales,
  3049. u.CnName AS GroupPickupUser,
  3050. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3051. FROM
  3052. Grp_DelegationInfo di
  3053. WITH
  3054. (NoLock)
  3055. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3056. WHERE
  3057. di.Isdel = 0
  3058. AND (
  3059. SELECT
  3060. CAST(
  3061. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3062. ) AS GroupSales
  3063. FROM
  3064. Fin_ForeignReceivables
  3065. WHERE
  3066. IsDel = 0
  3067. AND di.Id = Diid
  3068. AND AddingWay IN (0, 1, 2)
  3069. ) > 0
  3070. {userSql}
  3071. AND di.IsBid = 0
  3072. AND di.TeamName Not Like '%投标%'
  3073. AND VisitDate Between '{beginDt}' And '{endDt}'
  3074. ) Temp ");
  3075. RefAsync<int> total = 0;
  3076. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3077. return Ok(JsonView(true, "操作成功!", groupData, total));
  3078. }
  3079. /// <summary>
  3080. /// 市场部销售额
  3081. /// 团组列表Excel下载
  3082. /// </summary>
  3083. /// <param name="_dto">市场部销售额请求dto</param>
  3084. /// <returns></returns>
  3085. [HttpPost("PostMarketingSalesGroupExcel")]
  3086. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3087. public async Task<IActionResult> PostMarketingSalesGroupExcel(MarketingSalesGroupListDto _dto)
  3088. {
  3089. #region 参数验证
  3090. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3091. var validResult = await validationRules.ValidateAsync(_dto);
  3092. if (!validResult.IsValid)
  3093. {
  3094. var errors = new StringBuilder();
  3095. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3096. return Ok(JsonView(false, errors.ToString()));
  3097. }
  3098. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3099. #region 页面操作权限验证
  3100. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3101. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3102. #endregion
  3103. #endregion
  3104. string userSql = "";
  3105. var userIds = new List<int>();
  3106. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3107. if (userIds.Count <= 0)
  3108. {
  3109. return Ok(JsonView(false));
  3110. }
  3111. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3112. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3113. {
  3114. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3115. }
  3116. string beginDt = $"{_dto.BeginDt} 00:00:00",
  3117. endDt = $"{_dto.EndDt} 23:59:59";
  3118. string sql = string.Format(@$"SELECT
  3119. ROW_NUMBER() OVER (
  3120. ORDER BY
  3121. CollectionDays
  3122. ) AS RowNumber,
  3123. *
  3124. FROM
  3125. (
  3126. SELECT
  3127. di.Id,
  3128. di.TeamName,
  3129. di.ClientUnit,
  3130. di.ClientName,
  3131. di.VisitDate,
  3132. di.VisitPNumber,
  3133. di.JietuanOperator,
  3134. di.VisitEndDate,
  3135. (
  3136. SELECT
  3137. CAST(
  3138. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3139. ) AS GroupSales
  3140. FROM
  3141. Fin_ForeignReceivables
  3142. WHERE
  3143. IsDel = 0
  3144. AND di.Id = Diid
  3145. AND AddingWay IN (0, 1, 2)
  3146. ) AS GroupSales,
  3147. u.CnName AS GroupPickupUser,
  3148. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3149. FROM
  3150. Grp_DelegationInfo di
  3151. WITH
  3152. (NoLock)
  3153. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3154. WHERE
  3155. di.Isdel = 0
  3156. AND (
  3157. SELECT
  3158. CAST(
  3159. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3160. ) AS GroupSales
  3161. FROM
  3162. Fin_ForeignReceivables
  3163. WHERE
  3164. IsDel = 0
  3165. AND di.Id = Diid
  3166. AND AddingWay IN (0, 1, 2)
  3167. ) > 0
  3168. {userSql}
  3169. AND di.IsBid = 0
  3170. AND di.TeamName Not Like '%投标%'
  3171. AND VisitDate Between '{beginDt}' And '{endDt}'
  3172. ) Temp ");
  3173. var view = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToListAsync();
  3174. if (view.Count < 1 ) return Ok(JsonView(false, "暂无数据!"));
  3175. //DataTable dt = GeneralMethod.
  3176. DataTable dt = CommonFun.GetDataTableFromIList(view);
  3177. dt.TableName = $"_view";
  3178. WorkbookDesigner designer = new WorkbookDesigner();
  3179. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/营业额团组报表模板.xls");
  3180. designer.SetDataSource(dt);
  3181. designer.SetDataSource("Total", view.Sum(x => x.GroupSales));
  3182. designer.Workbook.Worksheets[0].Name = "营业额团组报表";
  3183. designer.Process();
  3184. string fileName = $"MarketingSales/{_dto.BeginDt}~{_dto.EndDt}营业额团组报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3185. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3186. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3187. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3188. }
  3189. /// <summary>
  3190. /// 市场部销售额
  3191. /// 客户类型、客户等级 统计
  3192. /// </summary>
  3193. /// <param name="_dto">市场部销售额请求dto</param>
  3194. /// <returns></returns>
  3195. [HttpPost("PostMarketingSalesGroupStatistics")]
  3196. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3197. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  3198. {
  3199. #region 参数验证
  3200. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3201. var validResult = await validationRules.ValidateAsync(_dto);
  3202. if (!validResult.IsValid)
  3203. {
  3204. var errors = new StringBuilder();
  3205. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3206. return Ok(JsonView(false, errors.ToString()));
  3207. }
  3208. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3209. #region 页面操作权限验证
  3210. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3211. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3212. #endregion
  3213. #endregion
  3214. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3215. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3216. string userSql = "";
  3217. if (userIds.Count > 0)
  3218. {
  3219. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3220. }
  3221. else
  3222. {
  3223. if (_dto.PortType == 2 || _dto.PortType == 3)
  3224. {
  3225. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  3226. }
  3227. else
  3228. {
  3229. return Ok(JsonView(true, "操作成功!", new
  3230. {
  3231. customerTypeData = new List<object> { },
  3232. clientGradeData = new List<object> { }
  3233. }));
  3234. }
  3235. }
  3236. string sql = "";
  3237. if (_dto.StatisticsType == 1)
  3238. {
  3239. sql = string.Format(@$"Select
  3240. sd.[Name],
  3241. Count(*) As [Count]
  3242. From Grp_DelegationInfo di
  3243. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3244. Where di.Isdel = 0
  3245. And (
  3246. SELECT
  3247. CAST(
  3248. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3249. ) AS GroupSales
  3250. FROM
  3251. Fin_ForeignReceivables fr
  3252. WHERE
  3253. fr.IsDel = 0
  3254. AND di.Id = fr.Diid
  3255. AND AddingWay IN (0, 1, 2)
  3256. ) > 0
  3257. {userSql}
  3258. AND di.IsBid = 0
  3259. AND di.TeamName Not Like '%投标%'
  3260. And VisitDate Between '{beginDt}' And '{endDt}'
  3261. Group By [Name]
  3262. Order By Count Desc");
  3263. }
  3264. else if (_dto.StatisticsType == 2)
  3265. {
  3266. sql = string.Format(@$"Select
  3267. sd.[Name],
  3268. Count(*) As [Count]
  3269. From Grp_DelegationInfo di
  3270. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3271. Where di.Isdel = 0
  3272. And (
  3273. SELECT
  3274. CAST(
  3275. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3276. ) AS GroupSales
  3277. FROM
  3278. Fin_ForeignReceivables fr
  3279. WHERE
  3280. fr.IsDel = 0
  3281. AND di.Id = fr.Diid
  3282. AND AddingWay IN (0, 1, 2)
  3283. ) > 0
  3284. {userSql}
  3285. AND di.IsBid = 0
  3286. AND di.TeamName Not Like '%投标%'
  3287. And VisitDate Between '{beginDt}' And '{endDt}'
  3288. Group By [Name]
  3289. Order By Count Desc");
  3290. }
  3291. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  3292. if (_dto.PortType == 1)
  3293. {
  3294. string sql1 = string.Format(@$"Select
  3295. sd.[Name],
  3296. Count(*) As [Count]
  3297. From Grp_DelegationInfo di
  3298. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3299. Where di.Isdel = 0
  3300. And (
  3301. SELECT
  3302. CAST(
  3303. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3304. ) AS GroupSales
  3305. FROM
  3306. Fin_ForeignReceivables fr
  3307. WHERE
  3308. fr.IsDel = 0
  3309. AND di.Id = fr.Diid
  3310. AND AddingWay IN (0, 1, 2)
  3311. ) > 0
  3312. {userSql}
  3313. AND di.IsBid = 0
  3314. AND di.TeamName Not Like '%投标%'
  3315. And VisitDate Between '{beginDt}' And '{endDt}'
  3316. Group By [Name]
  3317. Order By Count Desc");
  3318. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3319. string sql2 = string.Format(@$"Select
  3320. sd.[Name],
  3321. Count(*) As [Count]
  3322. From Grp_DelegationInfo di
  3323. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3324. Where di.Isdel = 0
  3325. And (
  3326. SELECT
  3327. CAST(
  3328. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3329. ) AS GroupSales
  3330. FROM
  3331. Fin_ForeignReceivables fr
  3332. WHERE
  3333. fr.IsDel = 0
  3334. AND di.Id = fr.Diid
  3335. AND AddingWay IN (0, 1, 2)
  3336. ) > 0
  3337. {userSql}
  3338. AND di.IsBid = 0
  3339. AND di.TeamName Not Like '%投标%'
  3340. And VisitDate Between '{beginDt}' And '{endDt}'
  3341. Group By [Name]
  3342. Order By Count Desc");
  3343. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3344. return Ok(JsonView(true, "操作成功!", new
  3345. {
  3346. customerTypeData = customerTypeData,
  3347. clientGradeData = clientGradeData
  3348. }));
  3349. }
  3350. else if (_dto.PortType == 2 || _dto.PortType == 3)
  3351. {
  3352. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  3353. return Ok(JsonView(true, "操作成功!", data, data.Count));
  3354. }
  3355. else return Ok(JsonView(false, MsgTips.Port));
  3356. }
  3357. /// <summary>
  3358. /// 市场部销售额
  3359. /// 接单排名
  3360. /// </summary>
  3361. /// <param name="_dto">市场部销售额请求dto</param>
  3362. /// <returns></returns>
  3363. [HttpPost("PostMarketingSalesOrderRanking")]
  3364. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3365. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  3366. {
  3367. #region 参数验证
  3368. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3369. var validResult = await validationRules.ValidateAsync(_dto);
  3370. if (!validResult.IsValid)
  3371. {
  3372. var errors = new StringBuilder();
  3373. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3374. return Ok(JsonView(false, errors.ToString()));
  3375. }
  3376. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3377. #region 页面操作权限验证
  3378. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3379. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3380. #endregion
  3381. #endregion
  3382. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3383. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3384. string userSql = "";
  3385. if (userIds.Count > 0)
  3386. {
  3387. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  3388. }
  3389. else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3390. string sql = string.Format(@$"Select
  3391. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3392. u.CnName As UserName,
  3393. Count(*) As [Count]
  3394. From Grp_DelegationInfo di
  3395. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3396. Where di.Isdel = 0
  3397. AND (
  3398. SELECT
  3399. CAST(
  3400. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3401. ) AS GroupSales
  3402. FROM
  3403. Fin_ForeignReceivables fr
  3404. WHERE
  3405. fr.IsDel = 0
  3406. AND di.Id = fr.Diid
  3407. AND AddingWay IN (0, 1, 2)
  3408. ) > 0
  3409. {userSql}
  3410. AND di.IsBid = 0
  3411. AND di.TeamName Not Like '%投标%'
  3412. AND VisitDate Between '{beginDt}' AND '{endDt}'
  3413. Group By CnName");
  3414. RefAsync<int> total = 0;
  3415. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3416. return Ok(JsonView(true, "操作成功!", rankingData, total));
  3417. }
  3418. /// <summary>
  3419. /// 市场部销售额
  3420. /// 团组列表、客户类型、客户等级、接单排名
  3421. /// </summary>
  3422. /// <param name="_dto">市场部销售额请求dto</param>
  3423. /// <returns></returns>
  3424. [HttpPost("PostMarketingSalesGroupItem")]
  3425. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3426. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  3427. {
  3428. #region 参数验证
  3429. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  3430. var validResult = await validationRules.ValidateAsync(_dto);
  3431. if (!validResult.IsValid)
  3432. {
  3433. var errors = new StringBuilder();
  3434. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3435. return Ok(JsonView(false, errors.ToString()));
  3436. }
  3437. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3438. #region 页面操作权限验证
  3439. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3440. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3441. #endregion
  3442. #endregion
  3443. string userSql = "";
  3444. List<int> userIds = new List<int>();
  3445. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  3446. if (userIds.Count <= 0)
  3447. {
  3448. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  3449. }
  3450. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  3451. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  3452. {
  3453. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  3454. }
  3455. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  3456. #region 团组List
  3457. string sql = string.Format(@$"SELECT
  3458. ROW_NUMBER() OVER (
  3459. ORDER BY
  3460. CollectionDays
  3461. ) AS RowNumber,
  3462. *
  3463. FROM
  3464. (
  3465. SELECT
  3466. di.Id,
  3467. di.TeamName,
  3468. di.ClientUnit,
  3469. di.ClientName,
  3470. di.VisitDate,
  3471. di.VisitPNumber,
  3472. di.JietuanOperator,
  3473. di.VisitEndDate,
  3474. (
  3475. SELECT
  3476. CAST(
  3477. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3478. ) AS GroupSales
  3479. FROM
  3480. Fin_ForeignReceivables
  3481. WHERE
  3482. IsDel = 0
  3483. AND di.Id = Diid
  3484. AND AddingWay IN (0, 1, 2)
  3485. ) AS GroupSales,
  3486. u.CnName AS GroupPickupUser,
  3487. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  3488. FROM
  3489. Grp_DelegationInfo di
  3490. WITH
  3491. (NoLock)
  3492. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  3493. WHERE
  3494. di.Isdel = 0
  3495. AND (
  3496. SELECT
  3497. CAST(
  3498. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3499. ) AS GroupSales
  3500. FROM
  3501. Fin_ForeignReceivables fr
  3502. WHERE
  3503. fr.IsDel = 0
  3504. AND di.Id = fr.Diid
  3505. AND AddingWay IN (0, 1, 2)
  3506. ) > 0
  3507. {userSql}
  3508. AND di.IsBid = 0
  3509. AND di.TeamName Not Like '%投标%'
  3510. AND VisitDate Between '{beginDt}' And '{endDt}'
  3511. ) Temp ");
  3512. RefAsync<int> total = 0;
  3513. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  3514. #endregion
  3515. #region 客户类型、客户等级 统计
  3516. string sql1 = string.Format(@$"Select
  3517. sd.[Name],
  3518. Count(*) As [Count]
  3519. From Grp_DelegationInfo di
  3520. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  3521. Where di.Isdel = 0
  3522. And (
  3523. SELECT
  3524. CAST(
  3525. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3526. ) AS GroupSales
  3527. FROM
  3528. Fin_ForeignReceivables fr
  3529. WHERE
  3530. fr.IsDel = 0
  3531. AND di.Id = fr.Diid
  3532. AND AddingWay IN (0, 1, 2)
  3533. ) > 0
  3534. {userSql}
  3535. AND di.IsBid = 0
  3536. AND di.TeamName Not Like '%投标%'
  3537. And VisitDate Between '{beginDt}' And '{endDt}'
  3538. Group By [Name]
  3539. Order By Count Desc");
  3540. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  3541. string sql2 = string.Format(@$"Select
  3542. sd.[Name],
  3543. Count(*) As [Count]
  3544. From Grp_DelegationInfo di
  3545. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  3546. Where di.Isdel = 0
  3547. And (
  3548. SELECT
  3549. CAST(
  3550. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3551. ) AS GroupSales
  3552. FROM
  3553. Fin_ForeignReceivables fr
  3554. WHERE
  3555. fr.IsDel = 0
  3556. AND di.Id = fr.Diid
  3557. AND AddingWay IN (0, 1, 2)
  3558. ) > 0
  3559. {userSql}
  3560. AND di.IsBid = 0
  3561. AND di.TeamName Not Like '%投标%'
  3562. And VisitDate Between '{beginDt}' And '{endDt}'
  3563. Group By [Name]
  3564. Order By Count Desc");
  3565. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  3566. #endregion
  3567. #region 接单排名
  3568. string sql4 = string.Format(@$"Select
  3569. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  3570. u.CnName As UserName,
  3571. Count(*) As [Count]
  3572. From Grp_DelegationInfo di
  3573. Left Join Sys_Users u On di.JietuanOperator = u.Id
  3574. Where di.Isdel = 0
  3575. And (
  3576. SELECT
  3577. CAST(
  3578. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  3579. ) AS GroupSales
  3580. FROM
  3581. Fin_ForeignReceivables fr
  3582. WHERE
  3583. fr.IsDel = 0
  3584. AND di.Id = fr.Diid
  3585. AND AddingWay IN (0, 1, 2)
  3586. ) > 0
  3587. {userSql}
  3588. AND di.IsBid = 0
  3589. AND di.TeamName Not Like '%投标%'
  3590. And VisitDate Between '{beginDt}' And '{endDt}'
  3591. Group By CnName");
  3592. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  3593. #endregion
  3594. var viewData = new
  3595. {
  3596. groupData = groupData,
  3597. groupTotal = total,
  3598. customerTypeData = customerTypeData,
  3599. clientGradeData = clientGradeData,
  3600. rankingData = rankingData
  3601. };
  3602. return Ok(JsonView(true, "操作成功!", viewData, total));
  3603. }
  3604. /// <summary>
  3605. /// 市场部销售额
  3606. /// 客户拜访列表
  3607. /// </summary>
  3608. /// <param name="_dto">市场部销售额请求dto</param>
  3609. /// <returns></returns>
  3610. [HttpPost("PostMarketingSalesVCList")]
  3611. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3612. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  3613. {
  3614. #region 参数验证
  3615. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3616. var validResult = await validationRules.ValidateAsync(_dto);
  3617. if (!validResult.IsValid)
  3618. {
  3619. var errors = new StringBuilder();
  3620. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3621. return Ok(JsonView(false, errors.ToString()));
  3622. }
  3623. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3624. #region 页面操作权限验证
  3625. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3626. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3627. #endregion
  3628. #endregion
  3629. return Ok(await _visitingClientsRep._List(_dto.PortType, _dto.PageIndex, _dto.PageSize, _dto.DiId, _dto.Search));
  3630. }
  3631. /// <summary>
  3632. /// 市场部销售额
  3633. /// 客户拜访 操作(添加 Or 编辑)
  3634. /// </summary>
  3635. /// <param name="_dto">市场部销售额请求dto</param>
  3636. /// <returns></returns>
  3637. [HttpPost("PostMarketingSalesVCOperate")]
  3638. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3639. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  3640. {
  3641. #region 参数验证
  3642. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3643. var validResult = await validationRules.ValidateAsync(_dto);
  3644. if (!validResult.IsValid)
  3645. {
  3646. var errors = new StringBuilder();
  3647. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3648. return Ok(JsonView(false, errors.ToString()));
  3649. }
  3650. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3651. #region 页面操作权限验证
  3652. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3653. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3654. #endregion
  3655. #endregion
  3656. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  3657. }
  3658. /// <summary>
  3659. /// 市场部销售额
  3660. /// 客户拜访 Del
  3661. /// </summary>
  3662. /// <param name="_dto">市场部销售额请求dto</param>
  3663. /// <returns></returns>
  3664. [HttpPost("PostMarketingSalesVCDel")]
  3665. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3666. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  3667. {
  3668. return Ok(await _visitingClientsRep._Del(_dto.Id, _dto.UserId));
  3669. }
  3670. /// <summary>
  3671. /// 市场部销售额
  3672. /// 客户拜访 操作 save
  3673. /// </summary>
  3674. /// <param name="_dto">市场部销售额请求dto</param>
  3675. /// <returns></returns>
  3676. [HttpPost("PostMarketingSalesVCSave")]
  3677. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3678. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  3679. {
  3680. #region 参数验证
  3681. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  3682. var validResult = await validationRules.ValidateAsync(_dto);
  3683. if (!validResult.IsValid)
  3684. {
  3685. var errors = new StringBuilder();
  3686. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  3687. return Ok(JsonView(false, errors.ToString()));
  3688. }
  3689. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3690. #region 页面操作权限验证
  3691. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3692. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  3693. #endregion
  3694. #endregion
  3695. return Ok(await _visitingClientsRep._Save(_dto));
  3696. }
  3697. #endregion
  3698. #region 日付报表
  3699. /// <summary>
  3700. /// 日付类型数据
  3701. /// </summary>
  3702. /// <param name="_dto"></param>
  3703. /// <returns></returns>
  3704. [HttpPost("DailypaymentTypeInit")]
  3705. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3706. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  3707. {
  3708. #region 参数验证
  3709. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3710. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3711. #region 页面操作权限验证
  3712. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3713. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3714. #endregion
  3715. #endregion
  3716. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3717. {
  3718. var defaultParentIds = new List<int>() {
  3719. 48,// 人员费用
  3720. 49,// 办公费用
  3721. 50,// 销售费用
  3722. 51,// 其他费用
  3723. 55,// 大运会
  3724. };
  3725. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3726. .CreateRedisRepository()
  3727. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3728. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  3729. .Includes(x => x.SubData)
  3730. .Where(x => defaultParentIds.Contains(x.Id))
  3731. .ToListAsync();
  3732. dailyTypeData.ForEach(x =>
  3733. {
  3734. x.SubData.ForEach(y =>
  3735. {
  3736. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  3737. y.IsChecked = currId == 0 ? false : true;
  3738. });
  3739. });
  3740. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  3741. .Where(x => x.IsDel == 0)
  3742. .Select(x => new { id = x.Id, name = x.CompanyName })
  3743. .ToListAsync();
  3744. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  3745. }
  3746. else
  3747. {
  3748. return Ok(JsonView(false, "查询失败"));
  3749. }
  3750. }
  3751. /// <summary>
  3752. /// 日付类型数据 Save
  3753. /// </summary>
  3754. /// <param name="_dto"></param>
  3755. /// <returns></returns>
  3756. [HttpPost("DailypaymentTypeDataSave")]
  3757. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3758. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  3759. {
  3760. #region 参数验证
  3761. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  3762. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3763. #region 页面操作权限验证
  3764. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3765. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3766. #endregion
  3767. #endregion
  3768. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3769. {
  3770. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  3771. var res = await RedisRepository.RedisFactory
  3772. .CreateRedisRepository()
  3773. .StringSetAsync(
  3774. key: "DailypaymentTypeData",
  3775. _dto.TypeIds,
  3776. timeout: null);
  3777. if (!res) return Ok(JsonView(false, "操作失败"));
  3778. return Ok(JsonView(true, "操作成功!"));
  3779. }
  3780. else return Ok(JsonView(false, "操作失败"));
  3781. }
  3782. /// <summary>
  3783. /// 日付数据列表
  3784. /// </summary>
  3785. /// <param name="_dto"></param>
  3786. /// <returns></returns>
  3787. [HttpPost("DailypaymentRange")]
  3788. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3789. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  3790. {
  3791. #region 参数验证
  3792. var validator = new DailypaymentRangeDtoValidator();
  3793. var validationRes = validator.Validate(_dto);
  3794. if (!validationRes.IsValid)
  3795. {
  3796. StringBuilder sb = new StringBuilder();
  3797. foreach (var item in validationRes.Errors)
  3798. {
  3799. sb.AppendLine(item.ErrorMessage);
  3800. }
  3801. return Ok(JsonView(false, sb.ToString()));
  3802. }
  3803. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  3804. #region 页面操作权限验证
  3805. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  3806. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  3807. #endregion
  3808. #endregion
  3809. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  3810. {
  3811. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  3812. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  3813. var sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'", _beginDt, _endDt);
  3814. var dailypaymentTypeData = await RedisRepository.RedisFactory
  3815. .CreateRedisRepository()
  3816. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  3817. var sql = string.Format(@"
  3818. Select
  3819. dfp.Id,
  3820. dfp.Instructions,
  3821. dfp.PriceTypeId,
  3822. sd1.Name As FeeType,
  3823. dfp.TransferTypeId,
  3824. sd2.Name As TransferType,
  3825. dfp.SumPrice,
  3826. dfp.FAuditDate,
  3827. dfp.MAuditDate,
  3828. dfp.CompanyId,
  3829. c.CompanyName,
  3830. dfp.CreateUserId As ApplicantId,
  3831. u.CnName As Applicant,
  3832. dfp.CreateTime As ApplicantDt,
  3833. dfp.Instructions+u.CnName As ViewStr
  3834. From Fin_DailyFeePayment dfp
  3835. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  3836. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  3837. Left Join Sys_Company c On dfp.CompanyId = c.Id
  3838. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  3839. Where dfp.IsDel = 0 And dfp.IsPay = 1
  3840. ");//--Order By dfp.CreateTime Desc
  3841. if (_dto.Type == 1) //data
  3842. {
  3843. RefAsync<int> total = 0;
  3844. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  3845. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3846. .WhereIF(dailypaymentTypeData.Count > 0,
  3847. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3848. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3849. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3850. .OrderByDescending(x => x.ApplicantDt)
  3851. .ToPageListAsync(
  3852. pageNumber: _dto.PageIndex,
  3853. pageSize: _dto.PageSize,
  3854. totalNumber: total
  3855. );
  3856. _sqlSugar.ThenMapper(_view, x =>
  3857. {
  3858. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3859. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3860. .ToList();
  3861. });
  3862. //单独处理
  3863. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  3864. }
  3865. else if (_dto.Type == 2) //view
  3866. {
  3867. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  3868. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  3869. .WhereIF(dailypaymentTypeData.Count > 0,
  3870. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  3871. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  3872. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  3873. .OrderByDescending(x => x.ApplicantDt)
  3874. .ToPageListAsync(
  3875. pageNumber: 1,
  3876. pageSize: 99999
  3877. );
  3878. _sqlSugar.ThenMapper(_view, x =>
  3879. {
  3880. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  3881. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  3882. .ToList();
  3883. string str = "";
  3884. int index = 1;
  3885. foreach (var item in x.Contents)
  3886. {
  3887. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price:#0.00}] 数量:[{item.Quantity:#0.00}] 小计:[{item.ItemTotal:#0.00}] 备注:[{item.Remark}]";
  3888. if (index == x.Contents.Count) str += str1;
  3889. else str += str1 + "\r\n";
  3890. index++;
  3891. }
  3892. x.ContentStr = str;
  3893. });
  3894. if (_view.Count > 0)
  3895. {
  3896. //DataTable dt = GeneralMethod.
  3897. DataTable dt = CommonFun.GetDataTableFromIList(_view);
  3898. dt.TableName = $"_view";
  3899. decimal total = _view.Sum(x => x.SumPrice);
  3900. WorkbookDesigner designer = new WorkbookDesigner();
  3901. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  3902. designer.SetDataSource(dt);
  3903. designer.SetDataSource("Total", total);
  3904. designer.Workbook.Worksheets[0].Name = "日付报表";
  3905. designer.Process();
  3906. string fileName = $"DailyPayment/日付报表{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  3907. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  3908. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  3909. return Ok(JsonView(true, "操作成功", new { url = rst }));
  3910. }
  3911. return Ok(JsonView(true, ",暂无数据"));
  3912. }
  3913. return Ok(JsonView(false, "操作失败"));
  3914. }
  3915. else return Ok(JsonView(false, "操作失败"));
  3916. }
  3917. #endregion
  3918. #region 统计模块
  3919. /// <summary>
  3920. /// 同比
  3921. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  3922. /// </summary>
  3923. /// <param name="_dto">市场部销售额请求dto</param>
  3924. /// <returns></returns>
  3925. [HttpPost("StatisticsYOY")]
  3926. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  3927. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  3928. {
  3929. //同比增长率 = (本期 - 同期) / 同期 * 100%;
  3930. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  3931. string beginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  3932. endDt = $"{_dto.Year}-12-31 23:59:59";
  3933. string sql = string.Format(@"
  3934. SELECT
  3935. di.Id,
  3936. di.TeamName,
  3937. di.VisitDate,
  3938. YEAR(di.VisitDate) AS YEAR,
  3939. MONTH(di.VisitDate) AS MONTH,
  3940. (
  3941. SELECT
  3942. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  3943. FROM
  3944. Fin_ForeignReceivables
  3945. WHERE
  3946. IsDel = 0
  3947. AND AddingWay IN (0, 1, 2)
  3948. AND di.Id = Diid
  3949. ) AS SaleAmount,
  3950. (
  3951. SELECT
  3952. CAST(
  3953. SUM(
  3954. (
  3955. ((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100
  3956. )
  3957. ) AS DECIMAL(12, 2)
  3958. )
  3959. FROM
  3960. Grp_AirTicketReservations atr
  3961. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3962. AND ccp.CTable = 85
  3963. AND atr.Id = ccp.CId
  3964. WHERE
  3965. atr.IsDel = 0
  3966. AND ccp.IsAuditGM = 1
  3967. AND ccp.IsPay = 1
  3968. AND di.Id = atr.DiId
  3969. ) AirTicketAmount,
  3970. (
  3971. SELECT
  3972. CAST(
  3973. SUM(
  3974. (
  3975. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  3976. )
  3977. ) AS DECIMAL(12, 2)
  3978. )
  3979. FROM
  3980. Grp_CarTouristGuideGroundReservations ctggr
  3981. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  3982. AND ccp.CTable = 79
  3983. AND ctggr.Id = ccp.CId
  3984. WHERE
  3985. ctggr.IsDel = 0
  3986. AND ccp.IsAuditGM = 1
  3987. AND ccp.IsPay = 1
  3988. AND di.Id = ctggr.DiId
  3989. ) AS OPAmount,
  3990. (
  3991. SELECT
  3992. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  3993. FROM
  3994. Grp_DecreasePayments dp
  3995. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  3996. AND ccp.CTable = 98
  3997. AND dp.Id = ccp.CId
  3998. WHERE
  3999. dp.IsDel = 0
  4000. AND ccp.Ctable = 98
  4001. AND ccp.IsAuditGM = 1
  4002. AND ccp.IsPay = 1
  4003. AND di.Id = dp.Diid
  4004. ) AS OtherCostAmount,
  4005. (
  4006. SELECT
  4007. CAST(
  4008. SUM(
  4009. (
  4010. (ccp.PayMoney * ccp.DayRate)
  4011. )
  4012. ) AS DECIMAL(12, 2)
  4013. )
  4014. FROM
  4015. Grp_VisaInfo vi
  4016. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4017. AND ccp.CTable = 80
  4018. AND vi.Id = ccp.CId
  4019. WHERE
  4020. vi.IsDel = 0
  4021. AND ccp.IsAuditGM = 1
  4022. AND ccp.IsPay = 1
  4023. AND di.Id = vi.DIId
  4024. ) AS VisaAmount,
  4025. (
  4026. SELECT
  4027. CAST(
  4028. SUM(
  4029. (ccp.PayMoney * ccp.DayRate)
  4030. ) AS DECIMAL(12, 2)
  4031. )
  4032. FROM
  4033. Grp_InvitationOfficialActivities ioa
  4034. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4035. AND ccp.CTable = 81
  4036. AND ioa.Id = ccp.CId
  4037. WHERE
  4038. ioa.IsDel = 0
  4039. AND ccp.IsAuditGM = 1
  4040. AND ccp.IsPay = 1
  4041. AND di.Id = ioa.Diid
  4042. ) AS OAAmount,
  4043. (
  4044. SELECT
  4045. CAST(
  4046. SUM(
  4047. (ccp.PayMoney * ccp.DayRate)
  4048. ) AS DECIMAL(12, 2)
  4049. )
  4050. FROM
  4051. Grp_Customers ic
  4052. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  4053. AND ccp.CTable = 82
  4054. AND ic.Id = ccp.CId
  4055. WHERE
  4056. ic.IsDel = 0
  4057. AND ccp.IsAuditGM = 1
  4058. AND ccp.IsPay = 1
  4059. AND di.Id = ic.DiId
  4060. ) AS InsureAmount,
  4061. (
  4062. SELECT
  4063. CAST(
  4064. SUM(
  4065. (ccp.PayMoney * ccp.DayRate)
  4066. ) AS DECIMAL(12, 2)
  4067. )
  4068. FROM
  4069. Grp_HotelReservations hr
  4070. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4071. WHERE
  4072. hr.IsDel = 0
  4073. AND ccp.IsDel = 0
  4074. AND ccp.CTable = 76
  4075. AND ccp.IsAuditGM = 1
  4076. AND ccp.PayMoney <> 0
  4077. AND ccp.IsPay = 1
  4078. AND di.Id = hr.DiId
  4079. ) AS HotelAmount,
  4080. (
  4081. SELECT
  4082. CAST(
  4083. SUM((gec.PriceSum * gec.Coefficient * ccp.DayRate)) AS DECIMAL(12, 2)
  4084. )
  4085. FROM
  4086. OA2023DB.dbo.Fin_GroupExtraCost gec
  4087. INNER JOIN Grp_CreditCardPayment ccp ON gec.Id = ccp.CId
  4088. WHERE
  4089. ccp.IsDel = 0
  4090. AND ccp.CTable = 1015
  4091. AND ccp.IsAuditGM = 1
  4092. AND ccp.IsPay = 1
  4093. AND di.Id = gec.DiId
  4094. ) AS ExcessAmount,
  4095. (
  4096. SELECT
  4097. CAST(
  4098. SUM(
  4099. (ccp.PayMoney * ccp.DayRate)
  4100. ) AS DECIMAL(12, 2)
  4101. )
  4102. FROM
  4103. Fin_PaymentRefundAndOtherMoney prom
  4104. INNER JOIN Grp_CreditCardPayment ccp ON prom.DiId = ccp.DIId
  4105. AND prom.Id = ccp.CId
  4106. WHERE
  4107. prom.IsDel = 0
  4108. AND prom.PayType = 1
  4109. AND ccp.CTable = 285
  4110. AND ccp.IsAuditGM = 1
  4111. AND ccp.IsPay = 1
  4112. AND di.Id = prom.DiId
  4113. ) AS SKTHAmount
  4114. FROM
  4115. Grp_DelegationInfo di
  4116. WHERE
  4117. di.IsDel = 0
  4118. AND di.TeamDid IN (38,39,40,1048)
  4119. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  4120. ORDER BY
  4121. di.VisitDate
  4122. ", beginDt, endDt);
  4123. var data = await _sqlSugar.SqlQueryable<StatisticsYOYView>(sql).ToListAsync();
  4124. var thisYearData = data.Where(x => x.Year == _dto.Year).ToList();
  4125. var lastYearData = data.Where(x => x.Year == (_dto.Year - 1)).ToList();
  4126. List<YOYReturnView> salesYOYData = new List<YOYReturnView>();
  4127. List<YOYReturnView> costYOYData = new List<YOYReturnView>();
  4128. List<YOYReturnView> grossProfitYOYData = new List<YOYReturnView>();
  4129. int monthIndex = 1;
  4130. while (monthIndex < 13)
  4131. {
  4132. var thisMonthData = thisYearData.Where(x => x.Month == monthIndex).ToList();
  4133. var lastMonthData = lastYearData.Where(x => x.Month == monthIndex).ToList();
  4134. var thisGroupIds = thisMonthData.Select(x => x.Id).ToList();
  4135. var lastGroupIds = lastMonthData.Select(x => x.Id).ToList();
  4136. decimal thisSalesAmount = thisMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4137. lastSalesAmount = lastMonthData.Sum(x => x?.SaleAmount ?? 0.00M),
  4138. thisCostAmount = thisMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4139. lastCostAmount = lastMonthData.Sum(x => x?.CostAmount ?? 0.00M),
  4140. thisgrossProfitAmount = thisMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M),
  4141. lastgrossProfitAmount = lastMonthData.Sum(x => x?.GrossProfitAmount ?? 0.00M);
  4142. salesYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisSalesAmount, lastSalesAmount, thisGroupIds, lastGroupIds));
  4143. costYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisCostAmount, lastCostAmount, thisGroupIds, lastGroupIds));
  4144. grossProfitYOYData.Add(new YOYReturnView(_dto.Year, monthIndex, thisgrossProfitAmount, lastgrossProfitAmount, thisGroupIds, lastGroupIds));
  4145. monthIndex++;
  4146. }
  4147. salesYOYData = salesYOYData.OrderBy(x => x.Month).ToList();
  4148. costYOYData = costYOYData.OrderBy(x => x.Month).ToList();
  4149. grossProfitYOYData = grossProfitYOYData.OrderBy(x => x.Month).ToList();
  4150. return Ok(JsonView(true, "操作成功!", new { salesYOYData = salesYOYData, costYOYData = costYOYData, grossProfitYOYData = grossProfitYOYData }));
  4151. }
  4152. /// <summary>
  4153. /// 国交数据统计-机票相关
  4154. /// 机票票数、机票到达地、预订平台
  4155. /// </summary>
  4156. /// <param name="_dto"></param>
  4157. /// <returns></returns>
  4158. [HttpPost("StatisticsAirTicket")]
  4159. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4160. public async Task<IActionResult> StatisticsAirTicket(YOYDto _dto)
  4161. {
  4162. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4163. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4164. endDt = $"{_dto.Year}-12-31 23:59:59";
  4165. string sql = string.Format(@"
  4166. SELECT
  4167. atr.DIId,
  4168. atr.FlightsDate,
  4169. YEAR(atr.FlightsDate) AS YEAR,
  4170. MONTH(atr.FlightsDate) AS MONTH,
  4171. atr.CType,
  4172. sd.Name As CTypeName,
  4173. atr.FlightsCity,
  4174. atr.ClientNum,
  4175. atr.ClientName,
  4176. di.TeamName As 'GroupName',
  4177. CASE
  4178. WHEN ccp.Payee = '' OR ccp.Payee IS NULL THEN '未知'
  4179. ELSE ccp.Payee
  4180. END AS 'Platform'
  4181. FROM
  4182. Grp_AirTicketReservations atr
  4183. INNER JOIN Grp_CreditCardPayment ccp ON atr.Id = ccp.CId
  4184. AND ccp.IsDel = 0
  4185. AND CTable = 85
  4186. INNER JOIN Grp_DelegationInfo di ON atr.DIId = di.Id
  4187. LEFT JOIN Sys_SetData sd On atr.CType = sd.Id
  4188. WHERE
  4189. atr.IsDel = 0
  4190. AND di.TeamDid IN (38,39,40,1048)
  4191. AND atr.CType IN(457,458,459,460,574,575)
  4192. AND CHARINDEX('行程单',atr.ClientName) = 0
  4193. AND CHARINDEX('返点',atr.ClientName) = 0
  4194. AND CHARINDEX('-1',atr.ClientName) = 0
  4195. AND ccp.IsPay = 1
  4196. AND atr.FlightsDate BETWEEN '{0}' AND '{1}'
  4197. ORDER BY atr.FlightsDate
  4198. ", beginDt, endDt);
  4199. var data = await _sqlSugar.SqlQueryable<StatisticsAirTicketView>(sql).ToListAsync();
  4200. var groupIds = data.Select(x => x.DIId).ToList();
  4201. //处理城市数据
  4202. var threeCodeData = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  4203. //处理团组名称
  4204. var groupNames = await _sqlSugar.Queryable<Grp_DelegationInfo>().Where(x => groupIds.Contains(x.Id)).Select(x => new { Id = x.Id, GroupName = x.TeamName }).ToListAsync();
  4205. data.ForEach(x =>
  4206. {
  4207. string cityName = "";
  4208. if (!string.IsNullOrEmpty(x.FlightsCity))
  4209. {
  4210. string cityCode = x.FlightsCity.Replace("-", "").Replace("/", "");
  4211. int cityNum = cityCode.Length / 3;
  4212. if (cityCode.Length % 3 == 0)
  4213. {
  4214. for (int i = 0; i < cityNum; i++)
  4215. {
  4216. string code = "";
  4217. if (i == 0) code = cityCode.Substring(0, 3);
  4218. else code = cityCode.Substring(i * 3, 3);
  4219. if (!string.IsNullOrEmpty(code))
  4220. {
  4221. if (i == cityNum - 1)
  4222. {
  4223. cityName += threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4224. }
  4225. else
  4226. {
  4227. var str1 = threeCodeData.Find(x1 => x1.Three.Equals(code))?.City ?? "";
  4228. cityName += str1 + "、";
  4229. }
  4230. }
  4231. }
  4232. }
  4233. }
  4234. x.FlightsCityName = cityName;
  4235. });
  4236. var airTicketNumData = new List<AirTicketReturnView>();
  4237. var airTicketAreaData = new List<AirTicketCityReturnView>();
  4238. int monthIndex = 1;
  4239. while (monthIndex < 13)
  4240. {
  4241. var monthData = data.Where(x => x.Month == monthIndex).ToList();
  4242. //机票票数处理
  4243. int airticket_quantity = monthData.Sum(x => x.ClientNum);
  4244. var linkGroupIds = monthData.Select(x => x.DIId).ToList();
  4245. List<AitTicketInfo> aitTicketInfos = new List<AitTicketInfo>();
  4246. foreach (var item in monthData)
  4247. {
  4248. string groupName = groupNames.Find(x => item.DIId == x.Id)?.GroupName ?? "";
  4249. aitTicketInfos.Add(new AitTicketInfo(item.DIId, groupName, item.ClientNum));
  4250. }
  4251. var aitTicketInfosGroupBy = aitTicketInfos.GroupBy(x => x.Id);
  4252. List<AitTicketInfo> aitTicketInfos1 = new List<AitTicketInfo>();
  4253. foreach (var item in aitTicketInfosGroupBy)
  4254. {
  4255. aitTicketInfos1.Add(new AitTicketInfo(item.Key, item.First().GroupName, item.Sum(x => x.Quantity)));
  4256. }
  4257. aitTicketInfos1 = aitTicketInfos1.OrderBy(x => x.Quantity).ToList();
  4258. linkGroupIds = linkGroupIds.Distinct().ToList();
  4259. airTicketNumData.Add(new AirTicketReturnView(_dto.Year, monthIndex, airticket_quantity, aitTicketInfos1, linkGroupIds));
  4260. //机票城市处理
  4261. //城市处理
  4262. var airTicketCityInfos = new List<string>();
  4263. foreach (var item in monthData)
  4264. {
  4265. if (!string.IsNullOrEmpty(item.FlightsCityName))
  4266. {
  4267. if (item.FlightsCityName.Contains("、"))
  4268. {
  4269. var cityArray = item.FlightsCityName.Split("、").ToList();
  4270. foreach (var item1 in cityArray)
  4271. {
  4272. if (!string.IsNullOrEmpty(item1))
  4273. {
  4274. airTicketCityInfos.Add(item1);
  4275. }
  4276. }
  4277. }
  4278. else
  4279. {
  4280. airTicketCityInfos.Add(item.FlightsCityName);
  4281. }
  4282. }
  4283. }
  4284. //int quantity1 = airTicketCityInfos.Count;
  4285. int city_totalquantity = 0;
  4286. var airTicketCityInfosGroupby = airTicketCityInfos.GroupBy(x => x);
  4287. var airTicketCityInfos1 = new List<AirTicketCityInfo>();
  4288. foreach (var item in airTicketCityInfosGroupby)
  4289. {
  4290. var city_quantity = item.ToList().Count;
  4291. city_totalquantity += city_quantity;
  4292. airTicketCityInfos1.Add(new AirTicketCityInfo(item.Key, city_quantity));
  4293. }
  4294. airTicketCityInfos1 = airTicketCityInfos1.OrderByDescending(x => x.Quantity).ToList();
  4295. airTicketAreaData.Add(new AirTicketCityReturnView(_dto.Year, monthIndex, city_totalquantity, airTicketCityInfos1, linkGroupIds));
  4296. monthIndex++;
  4297. }
  4298. var airTicketPlatformData = data.GroupBy(g => g.Platform)
  4299. .Select(g => new
  4300. {
  4301. platform = g.Key,
  4302. total = g.Sum(x => x.ClientNum),
  4303. children = g.GroupBy(g1 => g1.DIId)
  4304. .Select(g1 => new {
  4305. diId = g1.Key,
  4306. groupName = g1.FirstOrDefault()?.GroupName ?? "-",
  4307. total = g1.Sum(x1 => x1.ClientNum),
  4308. children = g1.Select(x1 => new {
  4309. //diId = x1.DIId,
  4310. //groupName = x1.GroupName,
  4311. flightsCityName=x1.FlightsCityName,
  4312. total = x1.ClientNum
  4313. })
  4314. .ToList()
  4315. })
  4316. .OrderByDescending(x1 => x1.total)
  4317. .ToList()
  4318. })
  4319. .OrderByDescending(x => x.total)
  4320. .ToList();
  4321. return Ok(JsonView(true, "操作成功!", new
  4322. {
  4323. airTicketNumData = airTicketNumData,
  4324. airTicketAreaData = airTicketAreaData,
  4325. airTicketPlatformData = airTicketPlatformData
  4326. }));
  4327. }
  4328. /// <summary>
  4329. /// 国交数据统计-酒店
  4330. /// 国家TOP10、地区TOP10、预订平台
  4331. /// </summary>
  4332. /// <param name="_dto"></param>
  4333. /// <returns></returns>
  4334. [HttpPost("StatisticsHotel")]
  4335. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4336. public async Task<IActionResult> StatisticsHotel(YOYDto _dto)
  4337. {
  4338. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4339. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4340. endDt = $"{_dto.Year}-12-31 23:59:59";
  4341. string sql = string.Format(@"
  4342. SELECT
  4343. hr.DIId,
  4344. CASE
  4345. WHEN ntf.Country IS NULL THEN '未选择'
  4346. ELSE ntf.Country
  4347. END AS 'Country',
  4348. hr.City,
  4349. hr.HotelName,
  4350. sd.Name AS BookinSite,
  4351. hr.CheckInDate,
  4352. YEAR(hr.CheckInDate) AS YEAR,
  4353. MONTH(hr.CheckInDate) AS MONTH,
  4354. hr.CheckOutDate,
  4355. hr.SingleRoomCount,
  4356. hr.DoubleRoomCount,
  4357. hr.SuiteRoomCount,
  4358. hr.OtherRoomCount
  4359. FROM
  4360. Grp_HotelReservations hr
  4361. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  4362. AND ccp.IsDel = 0
  4363. AND CTable = 76
  4364. INNER JOIN Grp_DelegationInfo di ON hr.DiId = di.Id
  4365. LEFT JOIN Sys_SetData sd ON hr.ReservationsWebsite = sd.Id
  4366. LEFT JOIN Grp_NationalTravelFee ntf ON hr.AreaId = ntf.Id
  4367. WHERE
  4368. hr.IsDel = 0
  4369. AND di.TeamDid IN (38,39,40,1048)
  4370. AND ccp.IsPay = 1
  4371. AND (
  4372. hr.SingleRoomCount > 0
  4373. OR hr.DoubleRoomCount > 0
  4374. OR hr.SuiteRoomCount > 0
  4375. OR hr.OtherRoomCount > 0
  4376. )
  4377. AND CHARINDEX('早餐',hr.HotelName) = 0
  4378. AND CHARINDEX('晚餐',hr.HotelName) = 0
  4379. AND CHARINDEX('升级',hr.HotelName) = 0
  4380. AND CHARINDEX('饮料茶水费',hr.HotelName) = 0
  4381. AND CHARINDEX('城市税',hr.HotelName) = 0
  4382. AND CHARINDEX('退款',hr.HotelName) = 0
  4383. AND CHARINDEX('返现',hr.HotelName) = 0
  4384. AND CHARINDEX('会议室',hr.HotelName) = 0
  4385. AND CHARINDEX('迷你吧消费',hr.HotelName) = 0
  4386. AND CHARINDEX('运费',hr.HotelName) = 0
  4387. AND CHARINDEX('地接',hr.HotelName) = 0
  4388. AND CHARINDEX('损失',hr.HotelName) = 0
  4389. AND CHARINDEX('补差',hr.HotelName) = 0
  4390. AND hr.CheckInDate BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4391. ORDER BY
  4392. hr.CheckInDate
  4393. ", beginDt, endDt);
  4394. var data = await _sqlSugar.SqlQueryable<StatisticsHotelView>(sql).ToListAsync();
  4395. var hotelCountryGroupByData = data.GroupBy(x => x.Country)
  4396. .Select(g => new
  4397. {
  4398. Country = g.Key,
  4399. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4400. hotelData = g.GroupBy(x => x.HotelName)
  4401. .Select(g1 => new
  4402. {
  4403. hotelName = g1.Key,
  4404. roomNights = g1.Sum(x => x.RoomNights),
  4405. roomTotal = g1.Sum(x => x.RoomTotal),
  4406. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4407. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4408. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4409. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4410. })
  4411. .ToList(),
  4412. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4413. })
  4414. .OrderByDescending(x => x.BookingRoomNum)
  4415. .Take(10)
  4416. .ToList();
  4417. var hotelData = data.OrderBy(x => x.CityStr).ToList();
  4418. var hotelCityGroupByData = data.GroupBy(x => x.CityStr)
  4419. .Select(g => new
  4420. {
  4421. city = g.Key,
  4422. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4423. hotelData = g.GroupBy(x => x.HotelName)
  4424. .Select(g1 => new
  4425. {
  4426. hotelName = g1.Key,
  4427. roomNights = g1.Sum(x => x.RoomNights),
  4428. roomTotal = g1.Sum(x => x.RoomTotal),
  4429. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4430. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4431. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4432. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4433. })
  4434. .ToList(),
  4435. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4436. })
  4437. .OrderByDescending(x => x.BookingRoomNum)
  4438. .Take(10)
  4439. .ToList();
  4440. var hotelPlatformGroupByData = data.GroupBy(x => x.BookinSite)
  4441. .Select(g => new
  4442. {
  4443. Platform = g.Key,
  4444. BookingRoomNum = g.Sum(x => x.RoomTotal),
  4445. hotelData = g.GroupBy(x => x.HotelName)
  4446. .Select(g1 => new
  4447. {
  4448. hotelName = g1.Key,
  4449. roomNights = g1.Sum(x => x.RoomNights),
  4450. roomTotal = g1.Sum(x => x.RoomTotal),
  4451. singleRoomCount = g1.Sum(x => x.SingleRoomCount),
  4452. doubleRoomCount = g1.Sum(x => x.DoubleRoomCount),
  4453. suiteRoomCount = g1.Sum(x => x.SuiteRoomCount),
  4454. otherRoomCount = g1.Sum(x => x.OtherRoomCount),
  4455. })
  4456. .ToList(),
  4457. linkGroupIds = g.Select(x => x.DIId).Distinct().ToList()
  4458. })
  4459. .OrderByDescending(x => x.BookingRoomNum)
  4460. .ToList();
  4461. return Ok(JsonView(true, "操作成功!", new { hotelCountryGroupByData = hotelCountryGroupByData, hotelCityData = hotelCityGroupByData, hotelPlatformData = hotelPlatformGroupByData }));
  4462. }
  4463. /// <summary>
  4464. /// 国交数据统计
  4465. /// 商邀邀请国家数量TOP10
  4466. /// </summary>
  4467. /// <param name="_dto"></param>
  4468. /// <returns></returns>
  4469. [HttpPost("StatisticsInvitation")]
  4470. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4471. public async Task<IActionResult> StatisticsInvitation(YOYDto _dto)
  4472. {
  4473. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4474. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4475. endDt = $"{_dto.Year}-12-31 23:59:59";
  4476. string sql = string.Format(@"
  4477. SELECT
  4478. oa.DiId,
  4479. di.TeamName AS GroupName,
  4480. oa.Country,
  4481. oa.Area AS City,
  4482. oa.Client,
  4483. oa.Date
  4484. FROM
  4485. Res_OfficialActivities oa
  4486. LEFT JOIN Grp_DelegationInfo di ON oa.DiId = di.Id
  4487. WHERE
  4488. oa.IsDel = 0
  4489. AND oa.Date BETWEEN '{0}' AND '{1}'
  4490. ", beginDt, endDt);
  4491. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation_HW>(sql).ToListAsync();
  4492. var groupByCountry = data.GroupBy(x => x.Country)
  4493. .Select(g => new
  4494. {
  4495. Country = g.Key,
  4496. TimeNum = g.Count(),
  4497. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4498. })
  4499. .OrderByDescending(x => x.TimeNum)
  4500. .Take(10)
  4501. .ToList();
  4502. var groupByClient = data.GroupBy(x => x.Client)
  4503. .Select(g => new
  4504. {
  4505. Country = g.Key,
  4506. TimeNum = g.Count(),
  4507. LinkGroupIds = g.Select(x => x.GroupName).Distinct().ToList()
  4508. })
  4509. .OrderByDescending(x => x.TimeNum)
  4510. .Take(10)
  4511. .ToList();
  4512. return Ok(JsonView(true, "操作成功!", new { groupByCountry= groupByCountry, groupByClient = groupByClient }));
  4513. }
  4514. /// <summary>
  4515. /// 会务数据统计
  4516. /// 会务城市TOP10排序
  4517. /// </summary>
  4518. /// <param name="_dto"></param>
  4519. /// <returns></returns>
  4520. [HttpPost("StatisticsConferenceCity")]
  4521. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4522. public async Task<IActionResult> StatisticsConferenceCity(YOYDto _dto)
  4523. {
  4524. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4525. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4526. endDt = $"{_dto.Year}-12-31 23:59:59";
  4527. string sql = string.Format(@"
  4528. SELECT
  4529. ioa.DiId,
  4530. ioa.InviterArea AS Country
  4531. FROM
  4532. Grp_InvitationOfficialActivities ioa
  4533. INNER JOIN Grp_CreditCardPayment ccp ON ioa.Id = ccp.CId
  4534. AND ccp.IsDel = 0
  4535. AND ccp.CTable = 81
  4536. INNER JOIN Grp_DelegationInfo di ON ioa.DiId = di.Id
  4537. WHERE
  4538. ioa.IsDel = 0
  4539. AND di.TeamDid IN (102,248,302,691,762,1047)
  4540. AND ccp.IsPay = 1
  4541. AND ioa.CreateTime BETWEEN '{0}' AND '{1}'
  4542. ", beginDt, endDt);
  4543. var data = await _sqlSugar.SqlQueryable<StatisticsInvitation>(sql).ToListAsync();
  4544. var groupByData = data.GroupBy(x => x.Country)
  4545. .Select(g => new
  4546. {
  4547. Country = g.Key,
  4548. TimeNum = g.Count(),
  4549. LinkGroupIds = g.Select(x => x.DIId).ToList()
  4550. })
  4551. .OrderByDescending(x => x.TimeNum)
  4552. .Take(10)
  4553. .ToList();
  4554. return Ok(JsonView(true, "操作成功!", groupByData));
  4555. }
  4556. /// <summary>
  4557. /// 团组数据统计
  4558. /// 团组合作前十的客户TOP10排序
  4559. /// </summary>
  4560. /// <param name="_dto"></param>
  4561. /// <returns></returns>
  4562. [HttpPost("StatisticsCooperativeCustomer")]
  4563. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4564. public async Task<IActionResult> StatisticsCooperativeCustomer(YOYDto _dto)
  4565. {
  4566. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4567. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4568. endDt = $"{_dto.Year}-12-31 23:59:59";
  4569. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4570. _endDt = Convert.ToDateTime(endDt);
  4571. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4572. .Where(x => x.IsDel == 0)
  4573. //.Where(x => x.IsSure == 1)
  4574. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4575. .ToListAsync();
  4576. var groupInfos1 = groupInfos.GroupBy(x => x.ClientName);
  4577. var view = groupInfos1.Select(x =>
  4578. new
  4579. {
  4580. clienName = x.Key,
  4581. clientUnit = x.FirstOrDefault()?.ClientUnit ?? "",
  4582. visitsNum = x.Count()
  4583. }
  4584. )
  4585. .OrderByDescending(x => x.visitsNum)
  4586. .Take(10)
  4587. .ToList();
  4588. return Ok(JsonView(true, "操作成功!", view));
  4589. }
  4590. /// <summary>
  4591. /// 团组数据统计
  4592. /// 已出团客户单位的类型比例图(饼状图-政府团、企业团等)
  4593. /// </summary>
  4594. /// <param name="_dto"></param>
  4595. /// <returns></returns>
  4596. [HttpPost("StatisticsCooperativeCustomerType")]
  4597. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4598. public async Task<IActionResult> StatisticsCooperativeCustomerType(YOYDto _dto)
  4599. {
  4600. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4601. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4602. endDt = $"{_dto.Year}-12-31 23:59:59";
  4603. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4604. _endDt = Convert.ToDateTime(endDt);
  4605. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4606. .LeftJoin<Sys_SetData>((di, sd) => di.TeamDid == sd.Id)
  4607. .Where((di, sd) => di.IsDel == 0)
  4608. .Where((di, sd) => di.VisitDate >= _beginDt && di.VisitDate <= _endDt)
  4609. .Select((di, sd) => new
  4610. {
  4611. Id = di.Id,
  4612. GroupTypeId = di.TeamDid,
  4613. GroupTypeName = sd.Name,
  4614. })
  4615. .ToListAsync();
  4616. var groupInfos1 = groupInfos.GroupBy(x => x.GroupTypeName);
  4617. var view = groupInfos1.Select(x =>
  4618. new
  4619. {
  4620. groupTypeName = x.Key,
  4621. groupNum = x.Count(),
  4622. linkGroupId = x.Select(x1 => x1.Id).ToList()
  4623. }
  4624. )
  4625. .OrderByDescending(x => x.groupNum)
  4626. .ToList();
  4627. return Ok(JsonView(true, "操作成功!", view));
  4628. }
  4629. /// <summary>
  4630. /// 团组数据统计
  4631. /// 团组数量
  4632. /// </summary>
  4633. /// <param name="_dto"></param>
  4634. /// <returns></returns>
  4635. [HttpPost("StatisticsGroupNum")]
  4636. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4637. public async Task<IActionResult> StatisticsGroupNum(YOYDto _dto)
  4638. {
  4639. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4640. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4641. endDt = $"{_dto.Year}-12-31 23:59:59";
  4642. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4643. _endDt = Convert.ToDateTime(endDt);
  4644. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4645. .Where(x => x.IsDel == 0)
  4646. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4647. .Select(x => new StatisticsGroupInfoEntity
  4648. {
  4649. Id = x.Id,
  4650. VisitDate = x.VisitDate,
  4651. Month = x.VisitDate.Month,
  4652. //MonthName = x.VisitDate.ToString("MMM", CultureInfo.GetCultureInfo("zh-CN")),
  4653. VisitPNumber = x.VisitPNumber
  4654. })
  4655. .MergeTable()
  4656. .OrderBy(x => new { x.Month })
  4657. .ToListAsync();
  4658. string groupNumStr = $"年度出访量:{groupInfos.Count}\r\n";
  4659. var groupNumYearData = new
  4660. {
  4661. year = _dto.Year,
  4662. yearName = _dto.Year + "年",
  4663. num = groupInfos.Count,
  4664. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4665. };
  4666. var groupNumData = groupInfos.GroupBy(x => x.Quarter)
  4667. .Select(x => new
  4668. {
  4669. Quarter = x.Key,
  4670. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4671. Num = x.Count(),
  4672. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4673. })
  4674. .OrderBy(x => x.Quarter)
  4675. .ToList();
  4676. groupNumData.ForEach(x =>
  4677. {
  4678. groupNumStr += $"{x.QuarterName}出访量:{x.Num};";
  4679. });
  4680. var groupNumMonthData = groupInfos.GroupBy(x => x.Month)
  4681. .Select(x => new
  4682. {
  4683. Month = x.Key,
  4684. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4685. Num = x.Count(),
  4686. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4687. })
  4688. .OrderBy(x => x.Month)
  4689. .ToList();
  4690. return Ok(JsonView(true, "操作成功!", new
  4691. {
  4692. yearData = groupNumYearData,
  4693. quarterData = groupNumData,
  4694. monthData = groupNumMonthData,
  4695. remark = groupNumStr
  4696. }));
  4697. }
  4698. /// <summary>
  4699. /// 团组数据统计
  4700. /// 团组人数
  4701. /// </summary>
  4702. /// <param name="_dto"></param>
  4703. /// <returns></returns>
  4704. [HttpPost("StatisticsGroupPeopleNum")]
  4705. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4706. public async Task<IActionResult> StatisticsGroupPeopleNum(YOYDto _dto)
  4707. {
  4708. if (_dto.Year < 1) return Ok(JsonView(false, "操作失败"));
  4709. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  4710. endDt = $"{_dto.Year}-12-31 23:59:59";
  4711. DateTime _beginDt = Convert.ToDateTime(beginDt),
  4712. _endDt = Convert.ToDateTime(endDt);
  4713. var groupInfos = await _sqlSugar.Queryable<Grp_DelegationInfo>()
  4714. .Where(x => x.IsDel == 0)
  4715. .Where(x => x.VisitDate >= _beginDt && x.VisitDate <= _endDt)
  4716. .Select(x => new StatisticsGroupInfoEntity
  4717. {
  4718. Id = x.Id,
  4719. VisitDate = x.VisitDate,
  4720. Month = x.VisitDate.Month,
  4721. VisitPNumber = x.VisitPNumber
  4722. })
  4723. .MergeTable()
  4724. .OrderBy(x => new { x.Month })
  4725. .ToListAsync();
  4726. string groupPeopleNumStr = $"年度出访人数:{groupInfos.Sum(x => x.VisitPNumber)}\r\n";
  4727. var groupPeopleNumYearData = new
  4728. {
  4729. year = _dto.Year,
  4730. yearName = _dto.Year + "年",
  4731. num = groupInfos.Sum(x => x.VisitPNumber),
  4732. linkGroupIds = groupInfos.Select(x => x.Id).ToList()
  4733. };
  4734. var groupPeopleNumData = groupInfos.GroupBy(x => x.Quarter)
  4735. .Select(x => new
  4736. {
  4737. Quarter = x.Key,
  4738. QuarterName = x.FirstOrDefault()?.QuarterName ?? "-",
  4739. Num = x.Sum(x1 => x1.VisitPNumber),
  4740. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4741. })
  4742. .OrderBy(x => x.Quarter)
  4743. .ToList();
  4744. groupPeopleNumData.ForEach(x =>
  4745. {
  4746. groupPeopleNumStr += $"{x.QuarterName}出访人数:{x.Num};";
  4747. });
  4748. var groupPeopleNumMonthData = groupInfos.GroupBy(x => x.Month)
  4749. .Select(x => new
  4750. {
  4751. Month = x.Key,
  4752. MonthName = x.FirstOrDefault()?.MonthName ?? "-",
  4753. Num = x.Sum(x1 => x1.VisitPNumber),
  4754. LinkGroupIds = x.Select(x1 => x1.Id).ToList()
  4755. })
  4756. .OrderBy(x => x.Month)
  4757. .ToList();
  4758. return Ok(JsonView(true, "操作成功!", new
  4759. {
  4760. yearData = groupPeopleNumYearData,
  4761. quarterData = groupPeopleNumData,
  4762. monthData = groupPeopleNumMonthData,
  4763. remark = groupPeopleNumStr
  4764. }));
  4765. }
  4766. /// <summary>
  4767. /// 团组数据统计
  4768. /// OP 成本
  4769. /// </summary>
  4770. /// <param name="_dto"></param>
  4771. /// <returns></returns>
  4772. [HttpPost("StatisticsOP")]
  4773. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  4774. public async Task<IActionResult> StatisticsOP(StatisticsOPDto _dto)
  4775. {
  4776. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  4777. if (_dto.Type < 1 || _dto.Type > 2) return Ok(JsonView(false, "Type参数错误!"));
  4778. int thisYear = _dto.Year, lastYear = _dto.Year - 1;
  4779. string beginDt = $"{lastYear}-01-01 00:00:00",
  4780. endDt = $"{thisYear}-12-31 23:59:59";
  4781. string sql = string.Format(@"
  4782. SELECT
  4783. temp.Id,
  4784. DiId,
  4785. PaymentTime,
  4786. [Year],
  4787. [Quarter],
  4788. [Month],
  4789. Area,
  4790. FeeType,
  4791. sd1.Name AS FeeTypeName,
  4792. FeeSubType,
  4793. sd2.Name AS FeeSubTypeName,
  4794. CONVERT(DECIMAL(12, 2), Price * Qauntity * ExchangeRate) AS Price
  4795. FROM
  4796. (
  4797. SELECT
  4798. ctggr.Id,
  4799. ctggr.DiId,
  4800. ctggr.Area,
  4801. CASE
  4802. WHEN ctggr.PriceType IS NULL THEN 1069
  4803. ELSE ctggr.PriceType
  4804. END AS FeeType,
  4805. ctggrc.SId AS FeeSubType,
  4806. ctggrc.Price,
  4807. CASE
  4808. WHEN ctggrc.Count IS NULL THEN 1
  4809. ELSE ctggrc.Count
  4810. END AS Qauntity,
  4811. ccp.DayRate AS ExchangeRate,
  4812. ctggrc.CreateTime AS PaymentTime,
  4813. YEAR(ctggrc.CreateTime) AS [Year],
  4814. CONVERT(INT,DATENAME(QUARTER, ctggrc.CreateTime)) AS [Quarter],
  4815. MONTH(ctggrc.CreateTime) AS [Month]
  4816. FROM
  4817. Grp_CarTouristGuideGroundReservations ctggr
  4818. INNER JOIN Grp_CarTouristGuideGroundReservationsContent ctggrc ON ctggr.Id = ctggrc.CTGGRId
  4819. AND ctggrc.IsDel = 0
  4820. INNER JOIN Grp_CreditCardPayment ccp ON ctggr.Id = ccp.CId
  4821. AND ccp.CTable = 79
  4822. AND ccp.IsDel = 0
  4823. WHERE
  4824. ctggr.IsDel = 0
  4825. AND ctggrc.SId != 1070 --费用子项筛掉尾款
  4826. AND ctggrc.Price > 0 --筛选真实存在的数据
  4827. AND ccp.IsPay = 1
  4828. ) temp
  4829. LEFT JOIN Sys_SetData sd1 ON FeeType = sd1.Id
  4830. LEFT JOIN Sys_SetData sd2 ON FeeSubType = sd2.Id
  4831. WHERE
  4832. temp.Area NOT LIKE '%尾款%' -- 筛选掉尾款相关信息
  4833. AND temp.FeeType != 1062 --费用类型筛选掉全款和首付款数据
  4834. AND temp.PaymentTime BETWEEN CONVERT(datetime,'{0}') AND CONVERT(datetime,'{1}')
  4835. ORDER BY
  4836. temp.[Year],
  4837. temp.[Quarter],
  4838. temp.[Month]
  4839. ", beginDt, endDt);
  4840. var opInfos = await _sqlSugar.SqlQueryable<StatisticsOP>(sql).ToListAsync();
  4841. //处理地区相关信息
  4842. var countrys = await _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x => x.IsDel == 0).ToListAsync();
  4843. for (int i = 0; i < opInfos.Count; i++)
  4844. {
  4845. string country = string.Empty, city = string.Empty;
  4846. int dataId = 0;
  4847. bool isCountryId = int.TryParse(opInfos[i].Area, out dataId);
  4848. string[] citySelecter = new string[] { "其他城市", "所有城市" };
  4849. if (isCountryId)
  4850. {
  4851. var countryInfo = countrys.Find(x => x.Id == dataId);
  4852. country = countryInfo?.Country ?? "";
  4853. if (citySelecter.Contains(countryInfo?.City)) city = country;
  4854. else city = countryInfo?.City ?? "";
  4855. }
  4856. else
  4857. {
  4858. var countryInfo1 = countrys.Find(x => opInfos[i].Area.Contains(x.Country));
  4859. if (countryInfo1 != null)
  4860. {
  4861. country = countryInfo1?.Country ?? "";
  4862. city = countryInfo1?.City ?? country;
  4863. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4864. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4865. else city = countryInfo2?.City ?? country;
  4866. }
  4867. else
  4868. {
  4869. var countryInfo2 = countrys.Find(x => opInfos[i].Area.Contains(x.City));
  4870. if (countryInfo2 != null)
  4871. {
  4872. country = countryInfo2?.Country ?? "";
  4873. city = countryInfo2?.City ?? "";
  4874. if (citySelecter.Contains(countryInfo2?.City)) city = country;
  4875. }
  4876. }
  4877. }
  4878. opInfos[i].Country = country;
  4879. opInfos[i].City = city;
  4880. }
  4881. var opParentFeeData = new StatisticsOP()._OPParentFeeInfo;
  4882. if (_dto.Type == 1)
  4883. {
  4884. //同比增长率=(本期数-同期数)/ 同期数
  4885. var yearData = opInfos.GroupBy(x => x.ParentFeeName)
  4886. .Select(x => new StatisticsOPYOY(
  4887. feeId: x.FirstOrDefault()?.ParentFeeId ?? 0,
  4888. feeName: x.Key,
  4889. currPeriodFee: x.Where(x => x.Year == thisYear).Sum(x => x.Price),
  4890. samePeriodFee: x.Where(x => x.Year == lastYear).Sum(x => x.Price),
  4891. currPeriodGroupTotal: x.Where(x => x.Year == thisYear).Select(x => x.DiId).Distinct().Count(),
  4892. samePeriodGroupTotal: x.Where(x => x.Year == lastYear).Select(x => x.DiId).Distinct().Count(),
  4893. subFeeData: x.GroupBy(x1 => x1.FeeSubType)
  4894. .Select(x1 => new StatisticsOPSubFeeYOY(
  4895. feeId: x1.Key,
  4896. feeName: x1.FirstOrDefault()?.FeeSubTypeName ?? "",
  4897. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  4898. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  4899. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  4900. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  4901. cityData: x1.GroupBy(x2 => x2.City)
  4902. .Select(x2 => new StatisticsOPCityYOY(
  4903. cityName: x2.Key,
  4904. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  4905. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  4906. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  4907. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price)
  4908. ))
  4909. .ToArray()
  4910. ))
  4911. .ToArray()
  4912. ))
  4913. .OrderBy(x => x.FeeId)
  4914. .ToList();
  4915. var opParentYearIds = yearData.Select(x => x.FeeId).ToList();
  4916. var opParentYearDataSelector = opParentFeeData.Where(x => !opParentYearIds.Contains(x.Id)).ToList();
  4917. if (opParentYearDataSelector.Count > 0)
  4918. {
  4919. foreach (var item in opParentYearDataSelector)
  4920. {
  4921. yearData.Add(
  4922. new StatisticsOPYOY(feeId: item.Id,
  4923. feeName: item.Name,
  4924. currPeriodFee: 0.00M,
  4925. samePeriodFee: 0.00M,
  4926. currPeriodGroupTotal: 0,
  4927. samePeriodGroupTotal: 0,
  4928. subFeeData: new StatisticsOPSubFeeYOY[] { }
  4929. ));
  4930. }
  4931. yearData = yearData.OrderBy(x => x.FeeId).ToList();
  4932. }
  4933. return Ok(JsonView(true, "操作成功!", yearData));
  4934. }
  4935. else if (_dto.Type == 2)
  4936. {
  4937. var monthData = opInfos.GroupBy(x => x.Month)
  4938. .Select(x => new StatisticsOPMonthYOY(
  4939. monthId: x.Key,
  4940. monthName: Enum.IsDefined(typeof(MonthEnum), (int)x.Key) ? ((MonthEnum)(int)x.Key).GetEnumDescription() : "",
  4941. feeDatas: x.GroupBy(x1 => x1.ParentFeeId)
  4942. .Select(x1 => new StatisticsOPYOY(
  4943. feeId: x1.Key,
  4944. feeName: x1.FirstOrDefault()?.ParentFeeName ?? "",
  4945. currPeriodFee: x1.Where(x1 => x1.Year == thisYear).Sum(x1 => x1.Price),
  4946. samePeriodFee: x1.Where(x1 => x1.Year == lastYear).Sum(x1 => x1.Price),
  4947. currPeriodGroupTotal: x1.Where(x1 => x1.Year == thisYear).Select(x1 => x1.DiId).Distinct().Count(),
  4948. samePeriodGroupTotal: x1.Where(x1 => x1.Year == lastYear).Select(x1 => x1.DiId).Distinct().Count(),
  4949. subFeeData: x1.GroupBy(x2 => x2.FeeSubType)
  4950. .Select(x2 => new StatisticsOPSubFeeYOY(
  4951. feeId: x2.Key,
  4952. feeName: x2.FirstOrDefault()?.FeeSubTypeName ?? "",
  4953. currPeriodFee: x2.Where(x2 => x2.Year == thisYear).Sum(x2 => x2.Price),
  4954. samePeriodFee: x2.Where(x2 => x2.Year == lastYear).Sum(x2 => x2.Price),
  4955. currPeriodGroupTotal: x2.Where(x2 => x2.Year == thisYear).Select(x2 => x2.DiId).Distinct().Count(),
  4956. samePeriodGroupTotal: x2.Where(x2 => x2.Year == lastYear).Select(x2 => x2.DiId).Distinct().Count(),
  4957. cityData: x2.GroupBy(x3 => x3.City)
  4958. .Select(x3 => new StatisticsOPCityYOY(
  4959. cityName: x3.Key,
  4960. currPeriodFee: x3.Where(x3 => x3.Year == thisYear).Sum(x3 => x3.Price),
  4961. samePeriodFee: x3.Where(x3 => x3.Year == lastYear).Sum(x3 => x3.Price),
  4962. currPeriodGroupTotal: x3.Where(x3 => x3.Year == thisYear).Select(x3 => x3.DiId).Distinct().Count(),
  4963. samePeriodGroupTotal: x3.Where(x3 => x3.Year == lastYear).Select(x3 => x3.DiId).Distinct().Count()
  4964. ))
  4965. .ToArray()
  4966. ))
  4967. .ToArray()
  4968. ))
  4969. .ToArray()
  4970. ))
  4971. //.OrderBy(x => x.MonthId)
  4972. .ToList();
  4973. //1、月份是否足够十二月
  4974. var monthIds = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
  4975. var monthDataIds = monthData.Select(x => x.MonthId).ToArray();
  4976. var newMonthIds = monthIds.Where(x => !monthDataIds.Contains(x)).ToList();
  4977. if (newMonthIds.Count > 0)
  4978. {
  4979. foreach (var item in newMonthIds)
  4980. {
  4981. monthData.Add(new StatisticsOPMonthYOY(
  4982. monthId: item,
  4983. monthName: Enum.IsDefined(typeof(MonthEnum), (int)item) ? ((MonthEnum)(int)item).GetEnumDescription() : "",
  4984. feeDatas: Array.Empty<StatisticsOPYOY>()
  4985. ));
  4986. }
  4987. monthData = monthData.OrderBy(x => x.MonthId).ToList();
  4988. }
  4989. //2、费用父类是否足够
  4990. for (int i = 0; i < monthData.Count; i++)
  4991. {
  4992. var month = monthData[i];
  4993. var opParentFeeIds = month.FeeDatas.Select(x => x.FeeId).ToList();
  4994. var opParentFeeDataSelector = opParentFeeData.Where(x => !opParentFeeIds.Contains(x.Id)).ToList();
  4995. if (opParentFeeDataSelector.Count > 0)
  4996. {
  4997. var feeDatas = month.FeeDatas.ToList();
  4998. foreach (var item in opParentFeeDataSelector)
  4999. {
  5000. feeDatas.Add(new StatisticsOPYOY(
  5001. feeId: item.Id,
  5002. feeName: item.Name,
  5003. currPeriodFee: 0.00M,
  5004. samePeriodFee: 0.00M,
  5005. currPeriodGroupTotal: 0,
  5006. samePeriodGroupTotal: 0,
  5007. subFeeData: Array.Empty<StatisticsOPSubFeeYOY>()
  5008. ));
  5009. }
  5010. feeDatas = feeDatas.OrderBy(x => x.FeeId).ToList();
  5011. monthData[i].FeeDatas = feeDatas.ToArray();
  5012. }
  5013. }
  5014. //3、费用子类是否足够
  5015. return Ok(JsonView(true, "操作成功!", monthData));
  5016. }
  5017. return Ok(JsonView(false, "操作失败!"));
  5018. }
  5019. /// <summary>
  5020. /// 团组数据统计
  5021. /// 团组预算/实际成本
  5022. /// </summary>
  5023. /// <param name="_dto"></param>
  5024. /// <returns></returns>
  5025. [HttpPost("StatisticsGroupCost")]
  5026. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5027. public async Task<IActionResult> StatisticsBRCost(StatisticsBRCostDto _dto)
  5028. {
  5029. if (_dto.Year < 1) return Ok(JsonView(false, "Year参数错误!"));
  5030. string beginDt = $"{_dto.Year}-01-01 00:00:00",
  5031. endDt = $"{_dto.Year}-12-31 23:59:59";
  5032. var sql = string.Format(@"
  5033. SELECT
  5034. ROW_NUMBER() OVER(
  5035. ORDER BY
  5036. di.VisitDate DESC
  5037. ) AS 'RowNumber',
  5038. di.Id,
  5039. di.TeamName AS 'GroupName',
  5040. di.ClientUnit,
  5041. di.VisitDate,
  5042. di.VisitDays,
  5043. di.VisitPNumber,
  5044. (
  5045. SELECT
  5046. TOP 1 CASE
  5047. ISNUMERIC (gcp.Currency)
  5048. WHEN 1 THEN (
  5049. SELECT
  5050. Name
  5051. FROM
  5052. Sys_SetData sd
  5053. WHERE
  5054. CAST(gcp.Currency AS INT) = sd.Id
  5055. )
  5056. ELSE gcp.Currency
  5057. END AS 'CurrencyCode'
  5058. FROM
  5059. Grp_GroupCostParameter gcp
  5060. WHERE
  5061. gcp.IsDel = 0
  5062. AND gcp.DiId = di.Id
  5063. ) Budget_CurrencyCode,
  5064. --预算币种
  5065. (
  5066. SELECT
  5067. TOP 1 CAST(COALESCE(gcp.Rate, 0.0000) AS DECIMAL(12, 4))
  5068. FROM
  5069. Grp_GroupCostParameter gcp
  5070. WHERE
  5071. gcp.IsDel = 0
  5072. AND gcp.DiId = di.Id
  5073. ) Budget_Rate,
  5074. --预算汇率
  5075. (
  5076. SELECT
  5077. CAST(
  5078. SUM(COALESCE(gcp.VisaCB, 0) * COALESCE(gcp.VisaRS, 0)) AS DECIMAL(12, 2)
  5079. )
  5080. FROM
  5081. Grp_GroupCostParameter gcp
  5082. WHERE
  5083. gcp.IsDel = 0
  5084. AND gcp.DiId = di.id
  5085. ) Budget_VisaAmount,
  5086. -- 预算签证成本
  5087. (
  5088. SELECT
  5089. CAST(
  5090. SUM(
  5091. (
  5092. (ccp.PayMoney * ccp.DayRate)
  5093. )
  5094. ) AS DECIMAL(12, 2)
  5095. )
  5096. FROM
  5097. Grp_VisaInfo vi
  5098. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5099. AND ccp.CTable = 80
  5100. AND vi.Id = ccp.CId
  5101. WHERE
  5102. vi.IsDel = 0
  5103. AND ccp.IsAuditGM = 1
  5104. AND ccp.IsPay = 1
  5105. AND di.Id = vi.DIId
  5106. ) AS Reality_VisaAmount,
  5107. -- 实际签证成本
  5108. (
  5109. SELECT
  5110. CAST(
  5111. SUM(
  5112. COALESCE(gcp.JJCCB, 0) * COALESCE(gcp.JJCRS, 0) + COALESCE(gcp.GWCCB, 0) * COALESCE(gcp.GWCRS, 0) + COALESCE(gcp.TDCCB, 0) * COALESCE(gcp.TDCRS, 0)
  5113. ) AS DECIMAL(12, 2)
  5114. )
  5115. FROM
  5116. Grp_GroupCostParameter gcp
  5117. WHERE
  5118. gcp.IsDel = 0
  5119. AND gcp.DiId = di.id
  5120. ) Budget_AirTicketAmount,
  5121. -- 预算机票成本
  5122. (
  5123. SELECT
  5124. CAST(
  5125. SUM(
  5126. (
  5127. (ccp.PayMoney * ccp.DayRate)
  5128. )
  5129. ) AS DECIMAL(12, 2)
  5130. )
  5131. FROM
  5132. Grp_AirTicketReservations atr
  5133. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5134. AND ccp.CTable = 85
  5135. AND atr.Id = ccp.CId
  5136. WHERE
  5137. atr.IsDel = 0
  5138. AND ccp.IsAuditGM = 1
  5139. AND ccp.IsPay = 1
  5140. AND di.Id = atr.DiId
  5141. ) Reality_AirTicketAmount,
  5142. --实际机票
  5143. (
  5144. SELECT
  5145. CAST(
  5146. SUM(
  5147. 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)
  5148. ) AS DECIMAL(12, 2)
  5149. )
  5150. FROM
  5151. Grp_GroupCostParameter gcp
  5152. WHERE
  5153. gcp.IsDel = 0
  5154. AND gcp.DiId = di.id
  5155. ) Budget_HotelAmount,
  5156. -- 预算酒店成本
  5157. (
  5158. SELECT
  5159. CAST(
  5160. SUM(
  5161. (ccp.PayMoney * ccp.DayRate)
  5162. ) AS DECIMAL(12, 2)
  5163. )
  5164. FROM
  5165. Grp_HotelReservations hr
  5166. INNER JOIN Grp_CreditCardPayment ccp ON hr.Id = ccp.CId
  5167. WHERE
  5168. hr.IsDel = 0
  5169. AND ccp.IsDel = 0
  5170. AND ccp.CTable = 76
  5171. AND ccp.IsAuditGM = 1
  5172. AND ccp.PayMoney <> 0
  5173. AND ccp.IsPay = 1
  5174. AND di.Id = hr.DiId
  5175. ) AS Reality_HotelAmount,
  5176. -- 实际酒店成本
  5177. (
  5178. SELECT
  5179. CAST(
  5180. SUM(COALESCE(gcp.DJCB, 0) * COALESCE(gcp.DJRS, 0)) AS DECIMAL(12, 2)
  5181. )
  5182. FROM
  5183. Grp_GroupCostParameter gcp
  5184. WHERE
  5185. gcp.IsDel = 0
  5186. AND gcp.DiId = di.id
  5187. ) Budget_OPAmount,
  5188. -- 预算 OP
  5189. (
  5190. SELECT
  5191. CAST(
  5192. SUM(
  5193. (
  5194. ctggr.ServiceQuotedPrice * (ccp.PayPercentage / 100) * ccp.DayRate
  5195. )
  5196. ) AS DECIMAL(12, 2)
  5197. )
  5198. FROM
  5199. Grp_CarTouristGuideGroundReservations ctggr
  5200. INNER JOIN Grp_CreditCardPayment ccp ON ccp.IsDel = 0
  5201. AND ccp.CTable = 79
  5202. AND ctggr.Id = ccp.CId
  5203. WHERE
  5204. ctggr.IsDel = 0
  5205. AND ccp.IsAuditGM = 1
  5206. AND ccp.IsPay = 1
  5207. AND di.Id = ctggr.DiId
  5208. ) AS Reality_OPAmount,
  5209. -- 实际 OP
  5210. (
  5211. SELECT
  5212. CAST(
  5213. SUM(COALESCE(gcp.GWCB, 0) * COALESCE(gcp.GWRS, 0)) AS DECIMAL(12, 2)
  5214. )
  5215. FROM
  5216. Grp_GroupCostParameter gcp
  5217. WHERE
  5218. gcp.IsDel = 0
  5219. AND gcp.DiId = di.id
  5220. ) Budget_OAAmount,
  5221. -- 预算 商邀
  5222. (
  5223. SELECT
  5224. CAST(
  5225. SUM(
  5226. (ccp.PayMoney * ccp.DayRate)
  5227. ) AS DECIMAL(12, 2)
  5228. )
  5229. FROM
  5230. Grp_InvitationOfficialActivities ioa
  5231. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5232. AND ccp.CTable = 81
  5233. AND ioa.Id = ccp.CId
  5234. WHERE
  5235. ioa.IsDel = 0
  5236. AND ccp.IsAuditGM = 1
  5237. AND ccp.IsPay = 1
  5238. AND di.Id = ioa.Diid
  5239. ) AS Reality_OAAmount,
  5240. -- 实际 商邀
  5241. (
  5242. SELECT
  5243. CAST(
  5244. SUM(
  5245. 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)
  5246. ) AS DECIMAL(12, 2)
  5247. )
  5248. FROM
  5249. Grp_GroupCostParameter gcp
  5250. WHERE
  5251. gcp.IsDel = 0
  5252. AND gcp.DiId = di.id
  5253. ) Budget_OtherAmount,
  5254. -- 预算其他成本
  5255. (
  5256. SELECT
  5257. CAST(
  5258. SUM(
  5259. (ccp.PayMoney * ccp.DayRate)
  5260. ) AS DECIMAL(12, 2)
  5261. )
  5262. FROM
  5263. Grp_Customers ic
  5264. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5265. AND ccp.CTable = 82
  5266. AND ic.Id = ccp.CId
  5267. WHERE
  5268. ic.IsDel = 0
  5269. AND ccp.IsAuditGM = 1And ccp.IsPay = 1
  5270. AND di.Id = ic.DiId
  5271. ) AS Reality_InsureAmount,
  5272. -- 实际保险成本
  5273. (
  5274. SELECT
  5275. CAST(SUM((ccp.PayMoney * ccp.DayRate)) AS DECIMAL(12, 2))
  5276. FROM
  5277. Grp_DecreasePayments dp
  5278. INNER JOIN Grp_CreditCardPayment ccp ON ccp.isdel = 0
  5279. AND ccp.CTable = 98
  5280. AND dp.Id = ccp.CId
  5281. WHERE
  5282. dp.IsDel = 0
  5283. AND ccp.Ctable = 98
  5284. AND ccp.IsAuditGM = 1
  5285. AND ccp.IsPay = 1
  5286. AND di.Id = dp.Diid
  5287. ) AS Reality_OtherCostAmount -- 实际其他款项
  5288. FROM
  5289. Grp_DelegationInfo di
  5290. WHERE
  5291. di.IsDel = 0
  5292. AND di.IsBid = 0
  5293. --AND di.TeamDid IN (38, 39, 40, 1048)
  5294. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  5295. ", beginDt, endDt);
  5296. if (!string.IsNullOrEmpty(_dto.Search))
  5297. {
  5298. sql += $"AND di.TeamName Like '%{_dto.Search}%'";
  5299. }
  5300. var view = await _sqlSugar.SqlQueryable<StatisticsBRCostView>(sql).ToListAsync();
  5301. view = view.Where(x => !x.GroupName.Contains("投标") && x.RealityAmount > 0).OrderByDescending(x => x.Id).ToList();
  5302. var total = view.Count;
  5303. var toSkip = (_dto.PageIndex - 1) * _dto.PageSize;
  5304. var data = view.Skip(toSkip).Take(_dto.PageSize).ToList();
  5305. if (data.Count > 0)
  5306. {
  5307. var diIds = data.Select(x => x.Id).ToList();
  5308. var currencyData = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 66).ToListAsync();
  5309. var ccpData = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
  5310. .Where(x => x.IsDel == 0 &&
  5311. diIds.Contains(x.DIId) &&
  5312. x.IsPay == 1 &&
  5313. x.IsAuditGM == 1
  5314. )
  5315. .ToListAsync();
  5316. for (int i = 0; i < data.Count; i++)
  5317. {
  5318. var info = data[i];
  5319. info.RowNumber = i + 1;
  5320. #region 1:签证 80
  5321. var visaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 80).ToList();
  5322. var visaDesc = "-";
  5323. if (visaDatas.Count > 0)
  5324. {
  5325. visaDesc = $"实际币种金额:";
  5326. foreach (var visa in visaDatas)
  5327. {
  5328. var currencyCode = currencyData.Find(x => x.Id == visa.PaymentCurrency)?.Name;
  5329. visaDesc += $"{visa.PayMoney} {currencyCode} 汇率:{visa.DayRate.ToString("#0.0000")};";
  5330. }
  5331. }
  5332. info.Reality_VisaAmountDesc = visaDesc;
  5333. #endregion
  5334. #region 2:机票 85
  5335. var airDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 85).ToList();
  5336. var airDesc = "-";
  5337. if (airDatas.Count > 0)
  5338. {
  5339. airDesc = $"实际币种金额:";
  5340. foreach (var air in airDatas)
  5341. {
  5342. var currencyCode = currencyData.Find(x => x.Id == air.PaymentCurrency)?.Name;
  5343. airDesc += $"{air.PayMoney} {currencyCode} 汇率:{air.DayRate.ToString("#0.0000")};";
  5344. }
  5345. }
  5346. info.Reality_AirTicketAmountDesc = airDesc;
  5347. #endregion
  5348. #region 3:酒店 76
  5349. var hotelDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 76 && x.PayMoney != 0 ).ToList();
  5350. var hotelDesc = "-";
  5351. if (hotelDatas.Count > 0)
  5352. {
  5353. hotelDesc = $"实际币种金额:";
  5354. foreach (var hotel in hotelDatas)
  5355. {
  5356. var currencyCode = currencyData.Find(x => x.Id == hotel.PaymentCurrency)?.Name;
  5357. hotelDesc += $"{hotel.PayMoney} {currencyCode} 汇率:{hotel.DayRate.ToString("#0.0000")};";
  5358. }
  5359. }
  5360. info.Reality_HotelAmountDesc = hotelDesc;
  5361. #endregion
  5362. #region 4:OP 79
  5363. var opDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 79 && x.PayMoney != 0).ToList();
  5364. var opDesc = "-";
  5365. if (opDatas.Count > 0)
  5366. {
  5367. opDesc = $"实际币种金额;";
  5368. foreach (var op in opDatas)
  5369. {
  5370. var currencyCode = currencyData.Find(x => x.Id == op.PaymentCurrency)?.Name;
  5371. opDesc += $"{op.PayMoney} {currencyCode} 汇率:{op.DayRate.ToString("#0.0000")};";
  5372. }
  5373. }
  5374. info.Reality_OPAmountDesc = opDesc;
  5375. #endregion
  5376. #region 5:商邀 81
  5377. var oaDatas = ccpData.Where(x => x.DIId == info.Id && x.CTable == 81 && x.PayMoney != 0).ToList();
  5378. var oaDesc = "-";
  5379. if (oaDatas.Count > 0)
  5380. {
  5381. oaDesc = $"实际币种金额:";
  5382. foreach (var oa in oaDatas)
  5383. {
  5384. var currencyCode = currencyData.Find(x => x.Id == oa.PaymentCurrency)?.Name;
  5385. oaDesc += $"{oa.PayMoney} {currencyCode} 汇率:{oa.DayRate.ToString("#0.0000")};";
  5386. }
  5387. }
  5388. info.Reality_OAAmountDesc = oaDesc;
  5389. #endregion
  5390. #region 6:其他款项(保险 82、其他款项 98)
  5391. var cTables = new List<int>() { 82, 98 };
  5392. var otherDatas = ccpData.Where(x => x.DIId == info.Id && cTables.Contains(x.CTable) && x.PayMoney != 0).ToList();
  5393. var otherDesc = "-";
  5394. if (otherDatas.Count > 0)
  5395. {
  5396. otherDesc = $"实际币种金额:";
  5397. foreach (var other in otherDatas)
  5398. {
  5399. var currencyCode = currencyData.Find(x => x.Id == other.PaymentCurrency)?.Name;
  5400. otherDesc += $"{other.PayMoney} {currencyCode} 汇率:{other.DayRate.ToString("#0.0000")};";
  5401. }
  5402. }
  5403. info.Reality_OtherCostAmountDesc = otherDesc;
  5404. #endregion
  5405. }
  5406. }
  5407. var briefData = _mapper.Map<List<StatisticsBRCostBriefView>>(data);
  5408. return Ok(JsonView(briefData, total));
  5409. }
  5410. /// <summary>
  5411. /// 团组数据统计
  5412. /// 当前时间团组所在城市
  5413. /// </summary>
  5414. /// <param name="_dto"></param>
  5415. /// <returns></returns>
  5416. [HttpPost("StatisticsNowCityOfGroup")]
  5417. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  5418. public async Task<IActionResult> StatisticsNowCityOfGroup(StatisticsNowCityOfGroupDto dto)
  5419. {
  5420. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  5421. var nowLable = dto.Now;
  5422. var nowBool = DateTime.TryParse(nowLable, out DateTime now);
  5423. if (!nowBool) return Ok(JsonView(false, $"请传入有效的当前时间(2024-11-27)!"));
  5424. var sql = string.Format(@"SELECT * FROM Grp_DelegationInfo WHERE ISdel = 0 AND '{0}' BETWEEN VisitStartDate AND VisitEndDate", nowLable);
  5425. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Select(x => new { x.Id, x.VisitCountry, x.TeamName, x.VisitStartDate, x.VisitEndDate }).ToListAsync();
  5426. var groupIds = groupInfos.Select(x => x.Id).ToList();
  5427. #region 舱位类型
  5428. //457 头等舱
  5429. //458 公务舱
  5430. //459 超经舱
  5431. //460 经济舱
  5432. //461 退票
  5433. //565 其他
  5434. //574 长段公务舱
  5435. //575 短途经济舱
  5436. //1023 行程单打印费
  5437. //1024 选座费
  5438. var classTypes = new int[] { 457, 458, 459, 460, 574, 575 };
  5439. #endregion
  5440. var throughCities = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  5441. .LeftJoin<Grp_DelegationInfo>((atr, di) => atr.DIId == di.Id)
  5442. .Where((atr, di) => atr.IsDel == 0 &&
  5443. groupIds.Contains(atr.DIId) &&
  5444. atr.FlightsDate.Trim().Equals(nowLable) &&
  5445. classTypes.Contains(atr.CType))
  5446. .Select((atr, di) => new
  5447. {
  5448. atr.DIId,
  5449. di.TeamName,
  5450. atr.FlightsDate,
  5451. atr.FlightsCode,
  5452. atr.FlightsCity,
  5453. atr.FlightsDescription
  5454. })
  5455. .ToListAsync();
  5456. if (!throughCities.Any()) return Ok(JsonView(false,"今日暂无团组出行!"));
  5457. foreach (var item in throughCities)
  5458. {
  5459. var dt = GeneralMethod.GetTableByBlackCode(item.DIId);
  5460. foreach (var row in dt.Rows)
  5461. {
  5462. }
  5463. }
  5464. throughCities = throughCities.Distinct().ToList(); // 去重
  5465. var cities = await _sqlSugar.Queryable<Res_ThreeCode>().Where(x => x.IsDel == 0).ToListAsync();
  5466. var view = new List<StatisticsNowCityOfGroupView>();
  5467. foreach (var item in throughCities)
  5468. {
  5469. var viewInfo = new StatisticsNowCityOfGroupView();
  5470. string flightCityLable = item.FlightsCity,
  5471. flightNoLable = item.FlightsCode;
  5472. if (flightCityLable.Contains(@"/") && flightNoLable.Contains(@"/"))
  5473. {
  5474. var flightCityArray = flightCityLable.Split(@"/");
  5475. var flightNoArray = flightNoLable.Split(@"/");
  5476. int index = 0;
  5477. foreach (var citys in flightCityArray)
  5478. {
  5479. viewInfo = CitySplit(citys, cities);
  5480. viewInfo.CurrDate = nowLable;
  5481. viewInfo.GroupName = item.TeamName;
  5482. viewInfo.FlightNo = flightNoArray[index];
  5483. view.Add(viewInfo);
  5484. index++;
  5485. }
  5486. }
  5487. else
  5488. {
  5489. viewInfo = CitySplit(flightCityLable, cities);
  5490. viewInfo.CurrDate = nowLable;
  5491. viewInfo.GroupName = item.TeamName;
  5492. viewInfo.FlightNo = flightNoLable;
  5493. view.Add(viewInfo);
  5494. }
  5495. }
  5496. if (!view.Any()) return Ok(JsonView(false, "今日暂无团组出行!"));
  5497. return Ok(JsonView(view));
  5498. }
  5499. private StatisticsNowCityOfGroupView CitySplit(string cityLable,List<Res_ThreeCode> cities)
  5500. {
  5501. var info = new StatisticsNowCityOfGroupView();
  5502. if (string.IsNullOrEmpty(cityLable)) return info;
  5503. var cityArray = cityLable.Split("-");
  5504. var departCityCode = cityArray[0];
  5505. var arriveCityCode = cityArray[1];
  5506. var departAirportInfo = cities.Find(x => x.Three.Equals(departCityCode.ToUpper()));
  5507. info.DepartAirportCode = departCityCode;
  5508. info.DepartCountryName = departAirportInfo?.Country ?? "-";
  5509. info.DepartCityName = departAirportInfo?.City ?? "-";
  5510. var arriveAirportInfo = cities.Find(x => x.Three.Equals(arriveCityCode.ToUpper()));
  5511. info.ArriveAirportCode = arriveCityCode;
  5512. info.ArriveCountryName = arriveAirportInfo?.Country ?? "-";
  5513. info.ArriveCityName = arriveAirportInfo?.City ?? "-";
  5514. return info;
  5515. }
  5516. #endregion
  5517. }
  5518. }