StatisticsController.cs 239 KB

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