StatisticsController.cs 280 KB

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