StatisticsController.cs 214 KB

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