StatisticsController.cs 219 KB

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