StatisticsController.cs 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433
  1. using Microsoft.AspNetCore.Mvc;
  2. using NPOI.POIFS.Properties;
  3. using NPOI.SS.Formula.Functions;
  4. using OASystem.API.OAMethodLib;
  5. using OASystem.Domain.Dtos.Groups;
  6. using OASystem.Domain.Dtos.Statistics;
  7. using OASystem.Domain.Entities.Financial;
  8. using OASystem.Domain.ViewModels.Financial;
  9. using OASystem.Domain.ViewModels.Groups;
  10. using OASystem.Domain.ViewModels.Statistics;
  11. using OASystem.Infrastructure.Repositories.Groups;
  12. using static OpenAI.GPT3.ObjectModels.SharedModels.IOpenAiModels;
  13. using System;
  14. using OASystem.Domain.Entities.Customer;
  15. using System.Collections.Generic;
  16. using Microsoft.AspNetCore.Mvc.RazorPages;
  17. using Microsoft.VisualBasic;
  18. using OASystem.Domain.Entities.Groups;
  19. using Microsoft.Extensions.DependencyInjection;
  20. using Aspose.Words.Lists;
  21. using static OASystem.API.OAMethodLib.GeneralMethod;
  22. using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;
  23. using System.Net.NetworkInformation;
  24. using System.ComponentModel.Design;
  25. using NetTaste;
  26. using OASystem.Domain.ViewModels.QiYeWeChat;
  27. using NPOI.POIFS.Crypt.Dsig;
  28. using EyeSoft.SequentialIdentity;
  29. using Microsoft.Extensions.Configuration;
  30. using System.Text.Json;
  31. using OASystem.RedisRepository;
  32. using OASystem.RedisRepository.RedisAsyncHelper;
  33. using System.Data;
  34. using OfficeOpenXml.Export.ToDataTable;
  35. using Aspose.Cells;
  36. namespace OASystem.API.Controllers
  37. {
  38. /// <summary>
  39. /// 统计模块
  40. /// </summary>
  41. [Route("api/[controller]")]
  42. [ApiController]
  43. public class StatisticsController : ControllerBase
  44. {
  45. private readonly int _decimalPlaces;
  46. private readonly IConfiguration _config;
  47. private readonly IMapper _mapper;
  48. private readonly SqlSugarClient _sqlSugar;
  49. private readonly DelegationInfoRepository _groupRep;
  50. private readonly SetDataRepository _setDataRep;
  51. private readonly TeamRateRepository _teamRateRep;
  52. private readonly VisitingClientsRepository _visitingClientsRep;
  53. /// <summary>
  54. /// Init
  55. /// </summary>
  56. /// <param name="mapper"></param>
  57. /// <param name="sqlSugar"></param>
  58. /// <param name="groupRep"></param>
  59. /// <param name="setDataRep"></param>
  60. public StatisticsController(IMapper mapper, IConfiguration config, SqlSugarClient sqlSugar, DelegationInfoRepository groupRep, SetDataRepository setDataRep, TeamRateRepository teamRate, VisitingClientsRepository visitingClientsRep)
  61. {
  62. _mapper = mapper;
  63. _config = config;
  64. _groupRep = groupRep;
  65. _setDataRep = setDataRep;
  66. _sqlSugar = sqlSugar;
  67. _teamRateRep = teamRate;
  68. _visitingClientsRep = visitingClientsRep;
  69. }
  70. #region 团组报表
  71. /// <summary>
  72. /// 团组报表
  73. /// Items
  74. /// </summary>
  75. /// <param name="_dto">团组列表请求dto</param>
  76. /// <returns></returns>
  77. [HttpPost("PostGroupStatementItems")]
  78. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  79. public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)
  80. {
  81. #region 参数验证
  82. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  83. if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));
  84. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  85. #region 页面操作权限验证
  86. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  87. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  88. #endregion
  89. #endregion
  90. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  91. {
  92. string sqlWhere = string.Empty;
  93. if (_dto.IsSure == 0) //未完成
  94. {
  95. sqlWhere += string.Format(@" And IsSure = 0");
  96. }
  97. else if (_dto.IsSure == 1) //已完成
  98. {
  99. sqlWhere += string.Format(@" And IsSure = 1");
  100. }
  101. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  102. {
  103. string tj = _dto.SearchCriteria;
  104. 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}%')",
  105. tj, tj, tj, tj, tj);
  106. }
  107. string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number,
  108. gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,
  109. ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,
  110. VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,
  111. pr.LastCollectionTime
  112. From Grp_DelegationInfo gdi
  113. Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id
  114. Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id
  115. Left Join Sys_Users su On gdi.JietuanOperator = su.Id
  116. Left Join (
  117. SELECT Diid, MAX(CreateTime) LastCollectionTime
  118. FROM Fin_ProceedsReceived
  119. Where IsDel = 0
  120. GROUP BY Diid
  121. ) pr On gdi.Id = pr.Diid
  122. Where gdi.IsDel = 0 {0} ", sqlWhere);
  123. RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
  124. var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync
  125. var _view = new
  126. {
  127. PageFuncAuth = pageFunAuthView,
  128. Data = _DelegationList
  129. };
  130. return Ok(JsonView(true, "查询成功!", _view, total));
  131. }
  132. else
  133. {
  134. return Ok(JsonView(false, "查询失败"));
  135. }
  136. }
  137. /// <summary>
  138. /// 团组报表
  139. /// Details
  140. /// </summary>
  141. /// <param name="_dto">团组列表请求dto</param>
  142. /// <returns></returns>
  143. [HttpPost("PostGroupStatementDetails")]
  144. //[JsonConverter(typeof(DecimalConverter), 2)]
  145. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  146. public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)
  147. {
  148. /*
  149. * 团组报表计算方式
  150. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  151. * 应收金额 = 应收表.Sum()
  152. * 已收金额 = 已收表.Sum()
  153. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  154. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  155. *
  156. */
  157. #region 参数验证
  158. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  159. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  160. if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));
  161. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  162. #region 页面操作权限验证
  163. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  164. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  165. #endregion
  166. #endregion
  167. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  168. {
  169. GroupStatementDetailsView _view = new GroupStatementDetailsView();
  170. #region 费用类型 币种,转账,客户信息
  171. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  172. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  173. #endregion
  174. #region 团组收入
  175. GroupIncomeView _giView = new GroupIncomeView();
  176. /*
  177. * 应收报表
  178. * 增加方式=实际报价时 费用必须审核才能进入团组报表
  179. */
  180. decimal frTotalAmount = 0.00M;//应收总金额
  181. string _frSql = string.Format(@"Select fr.Id,fr.AddingWay,fr.Status,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  182. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  183. From Fin_ForeignReceivables fr
  184. Left Join Sys_SetData sd On fr.Currency = sd.Id
  185. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);
  186. List<Gsd_ForeignReceivablesView> _frViews1 = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  187. List<Gsd_ForeignReceivablesView> _frViews = new List<Gsd_ForeignReceivablesView>();
  188. if (_frViews1.Count > 0)
  189. {
  190. _frViews.AddRange(_frViews1.Where(x => x.AddingWay != 2).ToList());
  191. _frViews.AddRange(_frViews1.Where(x => x.AddingWay == 2 && x.Status == 1).ToList());
  192. }
  193. _frViews.ForEach(x =>
  194. {
  195. string namePrefix = string.Empty;
  196. if (x.AddingWay == 0) namePrefix = $"账单模块-";
  197. else if (x.AddingWay == 1) namePrefix = $"成本预算模块-";
  198. else if (x.AddingWay == 2) namePrefix = $"实际报价-";
  199. x.PriceName = $"{namePrefix}{x.PriceName}";
  200. });
  201. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  202. _giView.Receivables = _frViews;
  203. _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  204. /*
  205. * 已收报表
  206. */
  207. decimal prTotalAmount = 0.00M;//已收总金额
  208. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  209. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  210. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  211. From Fin_ProceedsReceived pr
  212. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  213. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  214. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);
  215. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  216. prTotalAmount = _prViews.Sum(it => it.Price);
  217. _giView.ProceedsReceivedViews = _prViews;
  218. _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount.ToString("#0.00")} CNY 已收款合计:{prTotalAmount.ConvertToDecimal1().ToString("#0.00")} CNY");
  219. /*
  220. * 超支费用
  221. */
  222. decimal exTotalAmount = 0.00M;
  223. 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,
  224. (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  225. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  226. From OA2023DB.dbo.Fin_GroupExtraCost gec
  227. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  228. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  229. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  230. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  231. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  232. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _dto.DiId);
  233. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  234. #region 超支费用 - 模拟数据
  235. //if (_ExtraCostsViews.Count < 1)
  236. //{
  237. // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  238. // {
  239. // GECId = 0,
  240. // GECDiId = 2334,
  241. // PriceName = "模拟数据-超支费用名称",
  242. // PayMoney = 1000.00M,
  243. // PaymentCurrency = "CNY",
  244. // DayRate = 1.0000M,
  245. // CNYPrice = 1000.00M,
  246. // Payee = "模拟数据-超支费用收款方",
  247. // OrbitalPrivateTransfer = 1,
  248. // PayWay = "刷卡",
  249. // CardType = "招行卡",
  250. // IsPay = 1,
  251. // Applicant = "刘华举"
  252. // });
  253. // _ExtraCostsViews.Add(new Gsd_ExtraCostsView()
  254. // {
  255. // GECId = 0,
  256. // GECDiId = 2334,
  257. // PriceName = "模拟数据-超支费用名称",
  258. // PayMoney = 1000.00M,
  259. // PaymentCurrency = "CNY",
  260. // DayRate = 1.0000M,
  261. // CNYPrice = 1000.00M,
  262. // Payee = "模拟数据-超支费用收款方",
  263. // OrbitalPrivateTransfer = 1,
  264. // PayWay = "刷卡",
  265. // CardType = "招行卡",
  266. // IsPay = 1,
  267. // Applicant = "刘华举"
  268. // });
  269. //}
  270. #endregion
  271. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  272. _giView.ExtraCostsViews = _ExtraCostsViews;
  273. _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  274. /*
  275. * 收款退还
  276. */
  277. decimal promTotalAmount = 0.00M;// 收款退还总金额
  278. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  279. //删除了 And prom.PriceType = 1
  280. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  281. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  282. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  283. From Fin_PaymentRefundAndOtherMoney prom
  284. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  285. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  286. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  287. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  288. And prom.DiId = {0} Order By PrCreateTime", _dto.DiId);
  289. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  290. foreach (var ropItem in _promDatas)
  291. {
  292. string thisCueencyCode = "Unknown";
  293. string thisCueencyName = "Unknown";
  294. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  295. if (currency != null)
  296. {
  297. thisCueencyCode = currency.Name;
  298. thisCueencyName = currency.Remark;
  299. }
  300. string orbitalPrivateTransferStr = "Unknown";
  301. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  302. if (orbitalPrivateTransfer != null)
  303. {
  304. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  305. }
  306. string payStr = "Unknown";
  307. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  308. if (pay != null)
  309. {
  310. payStr = pay.Name;
  311. }
  312. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  313. {
  314. Id = ropItem.Id,
  315. DiId = ropItem.DIId,
  316. PriceName = ropItem.PrPriceName,
  317. PayCurrencyCode = thisCueencyCode,
  318. PayCurrencyName = thisCueencyName,
  319. Price = ropItem.PrPrice,
  320. CNYPrice = ropItem.RMBPrice,
  321. ThisRate = ropItem.DayRate,
  322. Payee = ropItem.Payee,
  323. PayTime = ropItem.AuditGMDate,
  324. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  325. PayType = payStr,
  326. IsPay = ropItem.IsPay,
  327. Applicant = ropItem.Appliction
  328. };
  329. _promView.Add(gsd_PaymentRefund);
  330. }
  331. #region 收款退还 - 模拟数据
  332. //if (_promView.Count < 1)
  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. // _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()
  352. // {
  353. // Id = 0,
  354. // DiId = 2334,
  355. // PriceName = "模拟数据-费用名称",
  356. // PayCurrencyCode = "CNY",
  357. // PayCurrencyName = "人民币",
  358. // Price = 1000.00M,
  359. // CNYPrice = 1000.00M,
  360. // ThisRate = 1.00M,
  361. // Payee = "模拟数据-收款方",
  362. // PayTime = "2023-01-01 15:20:01",
  363. // OrbitalPrivateTransfer = 1,
  364. // PayType = "刷卡",
  365. // IsPay = 1,
  366. // Applicant = "刘华举"
  367. // });
  368. //}
  369. #endregion
  370. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  371. _giView.PaymentRefundAndOtherMoneyViews = _promView;
  372. _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));
  373. decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;
  374. _view.GroupIncome = _giView;
  375. _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));
  376. #endregion
  377. #region 团组支出
  378. GroupExpenditureView _geView = new GroupExpenditureView();
  379. #region 酒店预定费用
  380. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  381. //ccp.RMBPrice As CNYPrice
  382. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  383. 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,
  384. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  385. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  386. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  387. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  388. ccp.PayMoney,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  389. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  390. From Grp_HotelReservations hr
  391. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  392. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  393. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  394. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  395. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  396. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  397. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  398. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  399. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.PayMoney<> 0 And hr.DiId = {0}
  400. Order By CheckInDate Asc", _dto.DiId);
  401. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  402. List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();
  403. List<Grp_HotelReservationsContent> groupHotelContentFeeViews = new List<Grp_HotelReservationsContent>();
  404. groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();
  405. decimal HotelCNYTotalPrice = 0.00M;
  406. var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);
  407. foreach (var item in groupHotelFeeViews)
  408. {
  409. if (groupHotelContentFeeViews.Count > 0)
  410. {
  411. string paymentStr = string.Empty;
  412. var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费
  413. item.RoomPrice = roomData?.Price ?? 0.00M;
  414. if (item.RoomPrice != 0)
  415. {
  416. if (roomData.IsPay == 0) paymentStr += $"房费:未付款<br/>";
  417. item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;
  418. string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  419. string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";
  420. item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>
  421. 收款方:{roomData?.Payee}<br/>
  422. 费用标识:{feeMark1} <br/>
  423. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  424. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}<br/>
  425. 是否由地接支付:{isFeeMark1} <br/>";
  426. }
  427. var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐
  428. item.BreakfastPrice = breakfastData?.Price ?? 0.00M;
  429. if (item.BreakfastPrice != 0)
  430. {
  431. if (breakfastData.IsPay == 0) paymentStr += $"早餐:未付款<br/>";
  432. item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;
  433. string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  434. string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";
  435. item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>
  436. 收款方:{breakfastData?.Payee}<br/>
  437. 费用标识:{feeMark2} <br/>
  438. 支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>
  439. 卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>
  440. 是否由地接支付:{isFeeMark2} <br/>";
  441. }
  442. var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税
  443. item.GovernmentRent = landTaxData?.Price ?? 0.00M;
  444. if (item.GovernmentRent != 0)
  445. {
  446. if (landTaxData.IsPay == 0) paymentStr += $"地税:未付款<br/>";
  447. item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;
  448. string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  449. string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";
  450. item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>
  451. 收款方:{landTaxData?.Payee}<br/>
  452. 费用标识:{feeMark3} <br/>
  453. 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>
  454. 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>
  455. 是否由地接支付:{isFeeMark3} <br/>";
  456. }
  457. var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税
  458. item.CityTax = cityTaxData?.Price ?? 0.00M;
  459. if (item.CityTax != 0)
  460. {
  461. if (cityTaxData.IsPay == 0) paymentStr += $"城市税:未付款<br/>";
  462. item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;
  463. string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";
  464. string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";
  465. item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>
  466. 收款方:{cityTaxData?.Payee}<br/>
  467. 费用标识:{feeMark4} <br/>
  468. 支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>
  469. 卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>
  470. 是否由地接支付:{isFeeMark4} <br/>";
  471. }
  472. if (!string.IsNullOrEmpty(paymentStr))
  473. {
  474. item.IsPay = 2;
  475. item.PayTips = paymentStr;
  476. }
  477. }
  478. else
  479. {
  480. decimal roomPrice = (item.SingleRoomCount * item.SingleRoomPrice) +
  481. (item.DoubleRoomCount * item.DoubleRoomPrice) +
  482. (item.SuiteRoomCount * item.SuiteRoomPrice) +
  483. (item.OtherRoomCount * item.OtherRoomPrice);
  484. //item.RoomPrice = item.CardPrice;
  485. item.RoomPriceCurrency = item.PaymentCurrency;
  486. }
  487. HotelCNYTotalPrice += item.CNYPrice;
  488. item.PayMoney = item.PayMoney.ConvertToDecimal1();
  489. item.CNYPrice = item.CNYPrice.ConvertToDecimal1();
  490. }
  491. _geView.GroupHotelFeeViews = groupHotelFeeViews;
  492. _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));
  493. #endregion
  494. #region 地接费用
  495. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  496. //string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  497. // sd2.name As PaymentCurrency,ccp.PayPercentage,
  498. // (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  499. // (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  500. // ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  501. // ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  502. // From Grp_CarTouristGuideGroundReservations ctggr
  503. // Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  504. // cggrc.DatePrice,cggrc.PriceContent
  505. // From Grp_CarTouristGuideGroundReservationsContent cggrc
  506. // Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  507. // Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  508. // Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  509. // ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  510. // Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  511. // Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  512. // Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  513. // Left Join Sys_Users u On ccp.CreateUserId = u.Id
  514. // Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ctggr.DiId = {0}
  515. // Order By CreateTime", _dto.DiId);
  516. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,
  517. sd2.name As PaymentCurrency,ccp.PayPercentage,
  518. (ctggrc.Price * (ccp.PayPercentage / 100)) As AmountPaid,
  519. (ctggrc.Price - ctggrc.Price * (ccp.PayPercentage / 100)) As BalancePayment,
  520. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  521. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  522. From Grp_CarTouristGuideGroundReservations ctggr
  523. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price*cggrc.Count As Price,sd2.Name As PriceCurrency,
  524. cggrc.DatePrice,cggrc.PriceContent
  525. From Grp_CarTouristGuideGroundReservationsContent cggrc
  526. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  527. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  528. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  529. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  530. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  531. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  532. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  533. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  534. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ctggr.DiId = {0}
  535. Order By CreateTime", _dto.DiId);
  536. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  537. string CTGGRFeeStr = "";
  538. decimal CTGGRCNYTotalPrice = 0.00M;
  539. //按1 地区,2 币种,3 汇率 分组计算
  540. var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);
  541. foreach (var ctggfr in groupCTGGRFeeDatas)
  542. {
  543. var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);
  544. if (ctggfr_curr.Count() > 0)
  545. {
  546. foreach (var curr in ctggfr_curr)
  547. {
  548. var ctggfr_rate = curr.GroupBy(it => it.DayRate);
  549. if (ctggfr_rate.Count() > 0)
  550. {
  551. foreach (var rate in ctggfr_rate)
  552. {
  553. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}
  554. {rate.FirstOrDefault()?.PaymentCurrency}(人民币:
  555. {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  556. {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  557. CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  558. }
  559. }
  560. else
  561. {
  562. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}
  563. {curr.FirstOrDefault()?.PaymentCurrency}(人民币:
  564. {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  565. {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  566. CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  567. }
  568. }
  569. }
  570. else
  571. {
  572. CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}
  573. {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:
  574. {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:
  575. {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");
  576. CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  577. }
  578. }
  579. foreach (var item in groupCTGGRFeeViews)
  580. {
  581. if (!string.IsNullOrEmpty(item.AuditGMDate))
  582. {
  583. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  584. }
  585. if (item.DatePrice != null)
  586. {
  587. item.PriceName = $"{item.PriceName}({Convert.ToDateTime(item.DatePrice).ToString("yyyy-MM-dd")})";
  588. }
  589. //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",
  590. // item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));
  591. //CTGGRCNYTotalPrice += item.CNYPrice;
  592. }
  593. _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;
  594. _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));
  595. #endregion
  596. #region 机票预订费用
  597. //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  598. //ccp.RMBPrice As CNYPrice
  599. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  600. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  601. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  602. sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  603. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,
  604. atr.CType
  605. From Grp_AirTicketReservations atr
  606. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId
  607. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  608. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  609. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  610. Left Join Sys_SetData sd4 On atr.CType = sd4.Id
  611. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  612. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And atr.DiId = {0} Order By CreateTime", _dto.DiId);
  613. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  614. string str = "";
  615. List<dynamic> airClientPris = new List<dynamic>();
  616. decimal AirCNYTotalPrice = 0.00M;
  617. decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;
  618. decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;
  619. //if (groupAirFeeViews.Count > 0)
  620. //{
  621. // JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);
  622. // JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);
  623. // JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();
  624. // GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);
  625. // GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);
  626. // GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();
  627. //}
  628. int Index = 0;
  629. foreach (var item in groupAirFeeViews)
  630. {
  631. if (item.AirId > 2924)
  632. {
  633. string itemClientName = "";
  634. if (!string.IsNullOrEmpty(item.ClientName))
  635. {
  636. System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  637. System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  638. if (m_EnName.Success || m_ZHName.Success)
  639. {
  640. itemClientName = item.ClientName;
  641. decimal unitCost = 0.00M;
  642. AirCNYTotalPrice += item.CNYPrice;
  643. continue;
  644. }
  645. string[] clientIds = new string[] { };
  646. if (item.ClientName.Contains(','))
  647. {
  648. clientIds = item.ClientName.Split(',');
  649. }
  650. else
  651. {
  652. clientIds = new string[] { item.ClientName };
  653. }
  654. if (clientIds.Length > 0)
  655. {
  656. int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });
  657. if (output.Contains(-1))
  658. {
  659. itemClientName += $@"行程单";
  660. output = output.Where(val => val != -1).ToArray();
  661. }
  662. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  663. decimal unitCost = 0.00M;
  664. unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();
  665. int clienIndex = 1;
  666. foreach (var client in clients)
  667. {
  668. airClientPris.Add(new
  669. {
  670. CnName = client.LastName + client.FirstName,
  671. EnName = client.Pinyin,
  672. Price = unitCost,
  673. AirType = item.AirTypeName
  674. });
  675. string six = "";
  676. if (client.Sex == 0) six = "Mr";
  677. else if (client.Sex == 1) six = "Ms";
  678. itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);
  679. clienIndex++;
  680. }
  681. }
  682. }
  683. item.ClientName = itemClientName;
  684. }
  685. else
  686. {
  687. string clientPinYinName = "";
  688. decimal unitCost = 0.00M;
  689. int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;
  690. unitCost = (item.PayMoney / cNum).ConvertToDecimal1();
  691. Regex r = new Regex("[0-9]");
  692. string name1 = item.ClientName;
  693. name1 = r.Replace(name1, "");
  694. string[] clientNames = name1.Split('.');
  695. for (int i = 0; i < item.ClientNum; i++)
  696. {
  697. string name = "";
  698. if (clientNames.Length > 0)
  699. {
  700. int index = i + 1;
  701. if (index < clientNames.Length)
  702. {
  703. name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();
  704. if (!string.IsNullOrEmpty(name))
  705. {
  706. airClientPris.Add(new
  707. {
  708. CnName = name,
  709. EnName = name,
  710. Price = unitCost,
  711. AirType = item.AirTypeName
  712. });
  713. }
  714. //if (name.Length > 0)
  715. //{
  716. // string nameLastStr = name[name.Length - 1].ToString();
  717. // if (nameLastStr.IsNumeric())
  718. // {
  719. // name = name.Substring(0, name.Length - 1).Trim();
  720. // }
  721. //}
  722. }
  723. }
  724. clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));
  725. }
  726. }
  727. if (!string.IsNullOrEmpty(item.AuditGMDate))
  728. {
  729. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  730. }
  731. AirCNYTotalPrice += item.CNYPrice;
  732. }
  733. _geView.GroupAirFeeViews = groupAirFeeViews;
  734. if (airClientPris.Count > 0)
  735. {
  736. var peoplePriStr = "";
  737. var airClientPris1 = airClientPris.GroupBy(item => item.CnName)
  738. .Select(group => group.First())
  739. .ToList();
  740. int airClientPrisIndex = 1;
  741. foreach (var item in airClientPris1)
  742. {
  743. decimal price = 0.00M;
  744. var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();
  745. foreach (var pri in prices)
  746. {
  747. price += pri.Price;
  748. }
  749. peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";
  750. airClientPrisIndex++;
  751. }
  752. if (!string.IsNullOrEmpty(peoplePriStr))
  753. {
  754. str = $@"其中:{peoplePriStr}";
  755. }
  756. //经济舱均价
  757. var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();
  758. if (airJJCPris.Count > 0)
  759. {
  760. decimal jjcTotalPrice = 0.00M;
  761. foreach (var item in airJJCPris)
  762. {
  763. jjcTotalPrice += item.Price;
  764. }
  765. decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)
  766. .Select(group => group.First())
  767. .ToList().Count(); ;
  768. JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;
  769. }
  770. //公务舱均价
  771. var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();
  772. if (airGWCPris.Count > 0)
  773. {
  774. decimal gwcTotalPrice = 0.00M;
  775. foreach (var item in airGWCPris)
  776. {
  777. gwcTotalPrice += item.Price;
  778. }
  779. decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)
  780. .Select(group => group.First())
  781. .ToList().Count();
  782. GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;
  783. }
  784. }
  785. _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";
  786. #endregion
  787. #region 签证费用
  788. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  789. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  790. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  791. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,
  792. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice
  793. From Grp_VisaInfo vi
  794. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  795. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  796. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  797. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  798. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  799. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And vi.DIId = {0} Order By CreateTime", _dto.DiId);
  800. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  801. decimal VisaCNYTotalPirce = 0.00M;
  802. foreach (var item in groupVisaFeeViews)
  803. {
  804. string itemClientName = "";
  805. string visaClients = item.VisaClient;
  806. if (!string.IsNullOrEmpty(visaClients))
  807. {
  808. string[] clientIds = new string[] { };
  809. if (visaClients.Contains(','))
  810. {
  811. clientIds = visaClients.Split(',');
  812. }
  813. else
  814. {
  815. clientIds = new string[] { visaClients };
  816. }
  817. if (clientIds.Length > 0)
  818. {
  819. List<int> clientIds1 = new List<int>() { };
  820. foreach (var clientIdStr in clientIds)
  821. {
  822. if (clientIdStr.IsNumeric())
  823. {
  824. clientIds1.Add(int.Parse(clientIdStr));
  825. }
  826. }
  827. if (clientIds1.Count > 0)
  828. {
  829. var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();
  830. foreach (var client in clients)
  831. {
  832. itemClientName += $"{client.LastName + client.FirstName},";
  833. }
  834. }
  835. else
  836. {
  837. itemClientName = visaClients;
  838. }
  839. }
  840. }
  841. if (itemClientName.Length > 0)
  842. {
  843. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  844. }
  845. item.VisaClient = itemClientName;
  846. VisaCNYTotalPirce += item.CNYPrice;
  847. if (!string.IsNullOrEmpty(item.AuditGMDate))
  848. {
  849. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  850. }
  851. }
  852. _geView.GroupVisaFeeViews = groupVisaFeeViews;
  853. _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));
  854. #endregion
  855. #region 邀请/公务活动 CTable = 81
  856. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  857. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  858. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  859. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  860. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,
  861. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  862. From Grp_InvitationOfficialActivities ioa
  863. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  864. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  865. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  866. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  867. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  868. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  869. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  870. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  871. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  872. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ioa.Diid = {0} Order By CreateTime", _dto.DiId);
  873. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  874. #region 邀请/公务活动 - 模拟数据
  875. //if (groupInvitationalFeeViews.Count < 1)
  876. //{
  877. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  878. // {
  879. // IOAId = 0,
  880. // IOADiId = 2334,
  881. // InviterArea = "模拟数据-邀请方地区",
  882. // Inviter = "模拟数据-邀请方",
  883. // InviteTime = "2023-10-10",
  884. // InviteCost = 100.00M,
  885. // InviteCurrency = "EUR",
  886. // SendCost = 100.00M,
  887. // SendCurrency = "EUR",
  888. // EventsCost = 10000.00M,
  889. // EventsCurrency = "EUR",
  890. // TranslateCost = 300.00M,
  891. // TranslateCurrency = "EUR",
  892. // PayMoney = 10500.00M,
  893. // PaymentCurrency = "EUR",
  894. // CNYPrice = 76765.50M,
  895. // Payee = "模拟数据-收款方",
  896. // AuditGMDate = "2023-12-05",
  897. // OrbitalPrivateTransfer = 1,
  898. // PayWay = "刷卡",
  899. // IsPay = 1,
  900. // Applicant = "刘华举"
  901. // });
  902. // groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()
  903. // {
  904. // IOAId = 0,
  905. // IOADiId = 2334,
  906. // InviterArea = "模拟数据-邀请方地区",
  907. // Inviter = "模拟数据-邀请方",
  908. // InviteTime = "2023-10-10",
  909. // InviteCost = 100.00M,
  910. // InviteCurrency = "EUR",
  911. // SendCost = 100.00M,
  912. // SendCurrency = "EUR",
  913. // EventsCost = 10000.00M,
  914. // EventsCurrency = "EUR",
  915. // TranslateCost = 300.00M,
  916. // TranslateCurrency = "EUR",
  917. // PayMoney = 10500.00M,
  918. // PaymentCurrency = "EUR",
  919. // CNYPrice = 76765.50M,
  920. // Payee = "模拟数据-收款方",
  921. // AuditGMDate = "2023-12-05",
  922. // OrbitalPrivateTransfer = 1,
  923. // PayWay = "刷卡",
  924. // IsPay = 1,
  925. // Applicant = "刘华举"
  926. // });
  927. //}
  928. #endregion
  929. decimal InvitationalCNYTotalPrice = 0.00M;
  930. foreach (var item in groupInvitationalFeeViews)
  931. {
  932. InvitationalCNYTotalPrice += item.CNYPrice2;
  933. if (!string.IsNullOrEmpty(item.AuditGMDate))
  934. {
  935. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  936. }
  937. string currencyRateStr = "";
  938. List<string> currencys = new List<string>();
  939. if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);
  940. if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);
  941. if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);
  942. if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);
  943. if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);
  944. currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);
  945. item.CurrencyRateStr = currencyRateStr;
  946. }
  947. _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;
  948. _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));
  949. #endregion
  950. #region 保险费用
  951. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  952. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  953. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  954. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  955. From Grp_Customers ic
  956. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  957. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  958. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  959. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  960. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ic.DiId = {0} Order By CreateTime", _dto.DiId);
  961. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  962. decimal InsuranceCNYTotalPrice = 0.00M;
  963. foreach (var item in groupInsuranceFeeViews)
  964. {
  965. InsuranceCNYTotalPrice += item.CNYPrice;
  966. string itemClientName = "";
  967. string insClients = item.ClientName;
  968. if (!string.IsNullOrEmpty(insClients))
  969. {
  970. //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");
  971. //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");
  972. //if (m_EnName.Success || m_ZHName.Success)
  973. //{
  974. // itemClientName = insClients;
  975. // continue;
  976. //}
  977. string[] clientIds = new string[] { };
  978. if (insClients.Contains(','))
  979. {
  980. clientIds = insClients.Split(',');
  981. }
  982. else
  983. {
  984. clientIds = new string[] { insClients };
  985. }
  986. if (clientIds.Length > 0)
  987. {
  988. List<int> output = new List<int>();
  989. foreach (var clientId in clientIds)
  990. {
  991. if (clientId.IsNumeric())
  992. {
  993. output.Add(int.Parse(clientId));
  994. }
  995. }
  996. if (output.Count > 0)
  997. {
  998. var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();
  999. foreach (var client in clients)
  1000. {
  1001. itemClientName += $"{client.LastName + client.FirstName},";
  1002. }
  1003. if (itemClientName.Length > 0)
  1004. {
  1005. itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);
  1006. }
  1007. }
  1008. else
  1009. {
  1010. itemClientName = insClients;
  1011. }
  1012. }
  1013. }
  1014. item.ClientName = itemClientName;
  1015. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1016. {
  1017. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1018. }
  1019. }
  1020. _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;
  1021. _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));
  1022. #endregion
  1023. #region 其他款项费用 98
  1024. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1025. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1026. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1027. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1028. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1029. From Grp_DecreasePayments dp
  1030. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1031. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1032. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1033. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1034. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And dp.Diid = {0}
  1035. Order By CreateTime", _dto.DiId);
  1036. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1037. #region 保险费用 - 模拟数据
  1038. //if (groupDecreaseFeeViews.Count < 1)
  1039. //{
  1040. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1041. // {
  1042. // DPId = 0,
  1043. // DPDiId = 2334,
  1044. // PriceName = "模拟数据-费用名称",
  1045. // PayMoney = 1000.00M,
  1046. // PayMoneyCurrency = "CNY",
  1047. // DayRate = 1.0000M,
  1048. // CNYPrice = 1.0000M,
  1049. // AuditGMDate = "2023-12-10 12:13:00",
  1050. // Payee = "模拟数据-付款方",
  1051. // OrbitalPrivateTransfer = 1,
  1052. // PayWay = "现金",
  1053. // IsPay = 1,
  1054. // Applicant = "刘华举"
  1055. // });
  1056. // groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()
  1057. // {
  1058. // DPId = 0,
  1059. // DPDiId = 2334,
  1060. // PriceName = "模拟数据-费用名称",
  1061. // PayMoney = 1000.00M,
  1062. // PayMoneyCurrency = "CNY",
  1063. // DayRate = 1.0000M,
  1064. // CNYPrice = 1.0000M,
  1065. // AuditGMDate = "2023-12-10 12:13:00",
  1066. // Payee = "模拟数据-付款方",
  1067. // OrbitalPrivateTransfer = 1,
  1068. // PayWay = "现金",
  1069. // IsPay = 1,
  1070. // Applicant = "刘华举"
  1071. // });
  1072. //}
  1073. #endregion
  1074. decimal DecreaseCNYTotalPrice = 0.00M;
  1075. foreach (var item in groupDecreaseFeeViews)
  1076. {
  1077. item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));
  1078. DecreaseCNYTotalPrice += item.CNYPrice;
  1079. if (!string.IsNullOrEmpty(item.AuditGMDate))
  1080. {
  1081. item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");
  1082. }
  1083. }
  1084. _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;
  1085. _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));
  1086. #endregion
  1087. _view.GroupExpenditure = _geView;
  1088. #endregion
  1089. /*
  1090. * 团组报表计算方式
  1091. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1092. * 应收金额 = 应收表.Sum()
  1093. * 已收金额 = 已收表.Sum()
  1094. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1095. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1096. *
  1097. */
  1098. decimal _totalExpenditure = 0.00M; //总支出
  1099. decimal _amountReceivable = 0.00M; //应收金额
  1100. decimal _amountReceived = 0.00M; //已收金额
  1101. decimal _receivableProfit = 0.00M; //应收利润
  1102. decimal _receivedProfit = 0.00M; //已收利润
  1103. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1104. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1105. _amountReceivable = frTotalAmount;
  1106. _amountReceived = prTotalAmount;
  1107. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1108. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1109. _view.FeeTotalStr = string.Format(@$"<span>
  1110. <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>
  1111. <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>
  1112. <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>
  1113. <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>
  1114. <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>
  1115. </span>");
  1116. return Ok(JsonView(true, "查询成功!", _view));
  1117. }
  1118. else
  1119. {
  1120. return Ok(JsonView(false, "查询成功"));
  1121. }
  1122. }
  1123. #endregion
  1124. #region 报表/折线图统计
  1125. //企业利润-团组利润
  1126. //企业利润-会务利润
  1127. /// <summary>
  1128. /// 企业利润
  1129. /// Details
  1130. /// 待添加权限验证
  1131. /// </summary>
  1132. /// <param name="_dto">团组列表请求dto</param>
  1133. /// <returns></returns>
  1134. [HttpPost("PostCorporateProfit")]
  1135. //[JsonConverter(typeof(DecimalConverter), 2)]
  1136. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1137. public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)
  1138. {
  1139. #region 参数验证
  1140. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1141. if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1142. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1143. if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));
  1144. if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));
  1145. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1146. #region 页面操作权限验证
  1147. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1148. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1149. #endregion
  1150. string sqlWhere = string.Empty;
  1151. //起止时间
  1152. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1153. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1154. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1155. //业务类型
  1156. List<int> groupTypeId = new List<int>();
  1157. if (_dto.BusinessType == 2) //团组
  1158. {
  1159. groupTypeId.AddRange(new List<int>() {
  1160. 38, // 政府团
  1161. 39, // 企业团
  1162. 40, // 散客团
  1163. 1048 // 高校团
  1164. });
  1165. }
  1166. else if (_dto.BusinessType == 3) //会务
  1167. {
  1168. groupTypeId.AddRange(new List<int>() {
  1169. 102, // 未知
  1170. 248, // 非团组
  1171. 302, // 成都-会务活动
  1172. 691, // 四川-会务活动
  1173. 762, // 四川-赛事项目收入
  1174. 1047 // 成都-赛事项目收入
  1175. });
  1176. }
  1177. if (groupTypeId.Count > 0)
  1178. {
  1179. sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");
  1180. }
  1181. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  1182. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  1183. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  1184. List<int> diIds = groupInfos.Select(it => it.Id).ToList();
  1185. List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);
  1186. List<MonthInfo> months = new List<MonthInfo>();
  1187. if (_dto.StatisticsType == 1) //月份
  1188. {
  1189. months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));
  1190. }
  1191. else if (_dto.StatisticsType == 1) //季度
  1192. {
  1193. months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));
  1194. }
  1195. List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();
  1196. foreach (var item in months)
  1197. {
  1198. DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");
  1199. DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");
  1200. var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();
  1201. _view.Add(new CorporateProfitMonthView()
  1202. {
  1203. Month = item.Month,
  1204. Profit = corporateProfit.Sum(it => it.ReceivedProfit),
  1205. GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()
  1206. });
  1207. }
  1208. return Ok(JsonView(true, "操作成功!", _view));
  1209. #endregion
  1210. }
  1211. /// <summary>
  1212. /// 计算团组利润
  1213. /// </summary>
  1214. /// <param name="diIds"></param>
  1215. /// <returns></returns>
  1216. private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)
  1217. {
  1218. List<CorporateProfit> corporateProfits = new List<CorporateProfit>();
  1219. if (diIds.Count < 1)
  1220. {
  1221. return corporateProfits;
  1222. }
  1223. #region 计算团组利润
  1224. /*
  1225. * 团组报表计算方式
  1226. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1227. * 应收金额 = 应收表.Sum()
  1228. * 已收金额 = 已收表.Sum()
  1229. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1230. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1231. *
  1232. */
  1233. string diIdStr = string.Join(",", diIds);
  1234. string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");
  1235. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();
  1236. #region 费用类型 币种,转账,客户信息
  1237. List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();
  1238. var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();
  1239. #endregion
  1240. foreach (var _diId in diIds)
  1241. {
  1242. List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();
  1243. #region 团组收入
  1244. /*
  1245. * 应收报表
  1246. */
  1247. decimal frTotalAmount = 0.00M;//应收总金额
  1248. string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,
  1249. sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime
  1250. From Fin_ForeignReceivables fr
  1251. Left Join Sys_SetData sd On fr.Currency = sd.Id
  1252. Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);
  1253. List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();
  1254. frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);
  1255. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });
  1256. /*
  1257. * 已收报表
  1258. */
  1259. decimal prTotalAmount = 0.00M;//已收总金额
  1260. string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,
  1261. sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,
  1262. pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime
  1263. From Fin_ProceedsReceived pr
  1264. Left Join Sys_SetData sd1 On pr.Currency = sd1.Id
  1265. Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id
  1266. Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);
  1267. List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();
  1268. prTotalAmount = _prViews.Sum(it => it.Price);
  1269. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });
  1270. /*
  1271. * 超支费用
  1272. */
  1273. decimal exTotalAmount = 0.00M;
  1274. string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,
  1275. ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  1276. sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime
  1277. From OA2023DB.dbo.Fin_GroupExtraCost gec
  1278. Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId
  1279. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1280. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1281. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1282. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1283. Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);
  1284. List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();
  1285. exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);
  1286. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });
  1287. /*
  1288. * 收款退还
  1289. */
  1290. decimal promTotalAmount = 0.00M;// 收款退还总金额
  1291. List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();
  1292. //删除了 And prom.PriceType = 1
  1293. string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,
  1294. prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,
  1295. prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime
  1296. From Fin_PaymentRefundAndOtherMoney prom
  1297. Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId
  1298. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1299. Where prom.IsDel = 0 And prom.PayType = 1 And ccp.CTable = 285
  1300. And ccp.IsAuditGM = 1 And ccp.IsPay = 1
  1301. And prom.DiId = {0} Order By PrCreateTime", _diId);
  1302. var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();
  1303. foreach (var ropItem in _promDatas)
  1304. {
  1305. string thisCueencyCode = "Unknown";
  1306. string thisCueencyName = "Unknown";
  1307. var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();
  1308. if (currency != null)
  1309. {
  1310. thisCueencyCode = currency.Name;
  1311. thisCueencyName = currency.Remark;
  1312. }
  1313. string orbitalPrivateTransferStr = "Unknown";
  1314. var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();
  1315. if (orbitalPrivateTransfer != null)
  1316. {
  1317. orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;
  1318. }
  1319. string payStr = "Unknown";
  1320. var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();
  1321. if (pay != null)
  1322. {
  1323. payStr = pay.Name;
  1324. }
  1325. Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()
  1326. {
  1327. Id = ropItem.Id,
  1328. DiId = ropItem.DIId,
  1329. PriceName = ropItem.PrPriceName,
  1330. PayCurrencyCode = thisCueencyCode,
  1331. PayCurrencyName = thisCueencyName,
  1332. Price = ropItem.PrPrice,
  1333. CNYPrice = ropItem.RMBPrice,
  1334. ThisRate = ropItem.DayRate,
  1335. Payee = ropItem.Payee,
  1336. PayTime = ropItem.AuditGMDate,
  1337. OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,
  1338. PayType = payStr,
  1339. IsPay = ropItem.IsPay,
  1340. Applicant = ropItem.Appliction
  1341. };
  1342. _promView.Add(gsd_PaymentRefund);
  1343. }
  1344. promTotalAmount = _promView.Sum(it => it.CNYPrice);
  1345. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });
  1346. #endregion
  1347. #region 团组支出
  1348. GroupExpenditureView _geView = new GroupExpenditureView();
  1349. #region 酒店预定费用
  1350. List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();
  1351. string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,
  1352. sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,
  1353. hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,
  1354. hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,
  1355. sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,
  1356. ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,
  1357. sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant
  1358. From Grp_HotelReservations hr
  1359. Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId
  1360. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1361. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1362. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1363. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1364. Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id
  1365. Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id
  1366. Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id
  1367. Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}
  1368. Order By CheckInDate Asc", _diId);
  1369. groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();
  1370. decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);
  1371. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });
  1372. #endregion
  1373. #region 地接费用
  1374. List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();
  1375. string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,
  1376. sd2.name As PaymentCurrency,ccp.PayPercentage,
  1377. (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,
  1378. (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,
  1379. ccp.DayRate,(ctggrc.Price * ccp.DayRate) As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1380. ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime
  1381. From Grp_CarTouristGuideGroundReservations ctggr
  1382. Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,
  1383. cggrc.PriceContent
  1384. From Grp_CarTouristGuideGroundReservationsContent cggrc
  1385. Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id
  1386. Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id
  1387. Where cggrc.ISdel = 0 And cggrc.Price != 0.00
  1388. ) ctggrc On ctggr.Id = ctggrc.CTGGRId
  1389. Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0 And ccp.CTable = 79 And ctggr.Id = ccp.CId
  1390. Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id
  1391. Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id
  1392. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1393. Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}
  1394. Order By CreateTime", _diId);
  1395. groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();
  1396. decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1397. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });
  1398. #endregion
  1399. #region 机票预订费用
  1400. List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();
  1401. string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,
  1402. atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,
  1403. sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,
  1404. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime
  1405. From Grp_AirTicketReservations atr
  1406. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.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_SetData sd4 On atr.CType = sd4.Id
  1411. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1412. Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);
  1413. groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();
  1414. decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);
  1415. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });
  1416. #endregion
  1417. #region 签证费用
  1418. List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();
  1419. string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1420. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,
  1421. sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime
  1422. From Grp_VisaInfo vi
  1423. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId
  1424. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1425. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1426. Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id
  1427. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1428. Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);
  1429. groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();
  1430. decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);
  1431. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });
  1432. #endregion
  1433. #region 邀请/公务活动 CTable = 81
  1434. List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();
  1435. string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,
  1436. ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,
  1437. sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,
  1438. sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,
  1439. ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime
  1440. From Grp_InvitationOfficialActivities ioa
  1441. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId
  1442. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1443. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1444. Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id
  1445. Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id
  1446. Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id
  1447. Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id
  1448. Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id
  1449. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1450. Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ioa.Diid = {0} Order By CreateTime", _diId);
  1451. groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();
  1452. decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);
  1453. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });
  1454. #endregion
  1455. #region 保险费用
  1456. List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();
  1457. string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,
  1458. sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1459. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime
  1460. From Grp_Customers ic
  1461. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId
  1462. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1463. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1464. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1465. Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);
  1466. groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();
  1467. decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);
  1468. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });
  1469. #endregion
  1470. #region 其他款项费用 98
  1471. List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();
  1472. string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,
  1473. (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,
  1474. ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,
  1475. sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime
  1476. From Grp_DecreasePayments dp
  1477. Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId
  1478. Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id
  1479. Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id
  1480. Left Join Sys_Users u On ccp.CreateUserId = u.Id
  1481. Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}
  1482. Order By CreateTime", _diId);
  1483. groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();
  1484. decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));
  1485. expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });
  1486. #endregion
  1487. #endregion
  1488. /*
  1489. * 团组报表计算方式
  1490. * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()
  1491. * 应收金额 = 应收表.Sum()
  1492. * 已收金额 = 已收表.Sum()
  1493. * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出
  1494. * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出
  1495. *
  1496. */
  1497. decimal _totalExpenditure = 0.00M; //总支出
  1498. decimal _amountReceivable = 0.00M; //应收金额
  1499. decimal _amountReceived = 0.00M; //已收金额
  1500. decimal _receivableProfit = 0.00M; //应收利润
  1501. decimal _receivedProfit = 0.00M; //已收利润
  1502. _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +
  1503. InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;
  1504. _amountReceivable = frTotalAmount;
  1505. _amountReceived = prTotalAmount;
  1506. _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;
  1507. _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;
  1508. var groupInfo = groupInfos.Find(it => it.Id == _diId);
  1509. corporateProfits.Add(new CorporateProfit()
  1510. {
  1511. DiId = _diId,
  1512. TeamName = groupInfo?.TeamName ?? "Unkwnon",
  1513. CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),
  1514. TotalExpenditure = _totalExpenditure,
  1515. ExpenditureItem = expenditureInfos,
  1516. AmountReceivable = _amountReceivable,
  1517. AmountReceived = _amountReceived,
  1518. ReceivableProfit = _receivableProfit,
  1519. ReceivedProfit = _receivedProfit,
  1520. });
  1521. }
  1522. #endregion
  1523. return corporateProfits;
  1524. }
  1525. //未来预测-地区接团/出团量
  1526. //未来预测-地区酒店预订量
  1527. //未来预测-地区机票预订量
  1528. //未来预测-地区车辆预订量
  1529. /// <summary>
  1530. /// (国家/城市)地区预订数量(团,酒店,机票,车辆)
  1531. /// Details
  1532. /// 待添加权限验证
  1533. /// </summary>
  1534. /// <param name="_dto">团组列表请求dto</param>
  1535. /// <returns></returns>
  1536. [HttpPost("PostRegionalBookingsNumber")]
  1537. //[JsonConverter(typeof(DecimalConverter), 2)]
  1538. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1539. public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)
  1540. {
  1541. #region 参数验证
  1542. if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));
  1543. //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id
  1544. if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));
  1545. if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));
  1546. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1547. #region 页面操作权限验证
  1548. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1549. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  1550. #endregion
  1551. string sqlWhere = string.Empty;
  1552. //起止时间
  1553. DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");
  1554. DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");
  1555. sqlWhere = string.Format(@$" Where Isdel = 0 ");
  1556. string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");
  1557. var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();
  1558. if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));
  1559. List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();
  1560. foreach (var item in groupInfos)
  1561. {
  1562. var data = await GroupBookingsNumber(_dto.Type, item);
  1563. if (data.TypeItem.Count > 0)
  1564. {
  1565. datas.Add(data);
  1566. }
  1567. }
  1568. //类型处理
  1569. if (_dto.Type == 1)//接团
  1570. {
  1571. List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();
  1572. dynamic groupData = null;
  1573. foreach (var item in datas)
  1574. {
  1575. if (item.TypeItem.Count > 0)
  1576. {
  1577. foreach (var item1 in item.TypeItem)
  1578. {
  1579. if (item1.RegionItem.Count > 0)
  1580. {
  1581. GroupInfo groupInfo = new GroupInfo()
  1582. {
  1583. DiId = item.DiId,
  1584. TeamName = item.GroupName,
  1585. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  1586. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  1587. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  1588. };
  1589. views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });
  1590. }
  1591. }
  1592. }
  1593. }
  1594. var viewsGroup = views.GroupBy(it => it.Name);
  1595. List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();
  1596. foreach (var item in viewsGroup)
  1597. {
  1598. List<GroupInfo> infos = new List<GroupInfo>();
  1599. foreach (var item1 in item)
  1600. {
  1601. infos.AddRange(item1.GroupItem);
  1602. }
  1603. infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //
  1604. _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });
  1605. }
  1606. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  1607. return Ok(JsonView(true, "操作成功!", _view, _view.Count));
  1608. }
  1609. else if (_dto.Type == 2)
  1610. {
  1611. List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();
  1612. foreach (var item in datas)
  1613. {
  1614. if (item.TypeItem.Count > 0)
  1615. {
  1616. foreach (var item1 in item.TypeItem)
  1617. {
  1618. if (item1.RegionItem.Count > 0)
  1619. {
  1620. foreach (var item2 in item1.RegionItem)
  1621. {
  1622. GroupInfo groupInfo = new GroupInfo()
  1623. {
  1624. DiId = item.DiId,
  1625. TeamName = item.GroupName,
  1626. CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",
  1627. ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",
  1628. Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",
  1629. };
  1630. List<HotelInfo> hotels = new List<HotelInfo>();
  1631. foreach (var item3 in item2.Data)
  1632. {
  1633. StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));
  1634. HotelInfo hotelInfo = new HotelInfo()
  1635. {
  1636. HotelName = statisticsHotelInfos.HotelName,
  1637. SingleRoomNum = statisticsHotelInfos.SingleRoomNum,
  1638. DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,
  1639. SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,
  1640. OtherRoomNum = statisticsHotelInfos.OtherRoomNum,
  1641. GroupInfo = groupInfo
  1642. };
  1643. hotels.Add(hotelInfo);
  1644. }
  1645. views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });
  1646. }
  1647. }
  1648. }
  1649. }
  1650. }
  1651. var viewsGroup = views.GroupBy(it => it.Name);
  1652. List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();
  1653. foreach (var item in viewsGroup)
  1654. {
  1655. List<HotelInfo> infos = new List<HotelInfo>();
  1656. foreach (var item1 in item)
  1657. {
  1658. infos.AddRange(item1.HotelItem);
  1659. }
  1660. _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });
  1661. }
  1662. _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();
  1663. return Ok(JsonView(true, "操作成功!", views, views.Count));
  1664. }
  1665. return Ok(JsonView(false, "操作失败!"));
  1666. #endregion
  1667. }
  1668. /// <summary>
  1669. /// 计算团组ALLType预订数量
  1670. /// </summary>
  1671. /// <param name="diIds"></param>
  1672. /// <returns></returns>
  1673. private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)
  1674. {
  1675. GroupTypeNumberInfo _view = new GroupTypeNumberInfo();
  1676. if (info == null)
  1677. {
  1678. return _view;
  1679. }
  1680. _view.DiId = info.Id;
  1681. _view.GroupName = info.TeamName;
  1682. List<TypeInfo> _types = new List<TypeInfo>();
  1683. #region 计算团组ALLType预订数量
  1684. if (type == 1)
  1685. {
  1686. //接团 客户集团所在地区
  1687. string group_region = string.Empty;
  1688. int group_number = 0;
  1689. if (!string.IsNullOrEmpty(info.ClientUnit))
  1690. {
  1691. var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>().Where(it => it.IsDel == 0 && it.Client.Equals(info.ClientUnit)).FirstAsync();
  1692. if (_NewClientData != null)
  1693. {
  1694. var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();
  1695. if (regionInfo != null)
  1696. {
  1697. group_region = regionInfo.Name.Replace("级", "");
  1698. group_number++;
  1699. }
  1700. }
  1701. }
  1702. if (group_number > 0)
  1703. {
  1704. _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });
  1705. }
  1706. }
  1707. else if (type == 2)
  1708. {
  1709. //酒店
  1710. var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1711. if (hotelInfos.Count > 0)
  1712. {
  1713. List<RegionInfo> hotelRegions = new List<RegionInfo>();
  1714. foreach (var item in hotelInfos)
  1715. {
  1716. var hotelNumberInfo = new StatisticsHotelInfo()
  1717. {
  1718. HotelName = item.HotelName,
  1719. SingleRoomNum = item.SingleRoomCount,
  1720. DoubleRoomNum = item.DoubleRoomCount,
  1721. SuiteRoomNum = item.SuiteRoomCount,
  1722. OtherRoomNum = item.OtherRoomCount,
  1723. };
  1724. int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;
  1725. if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))
  1726. {
  1727. RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));
  1728. if (hotelRegion != null)
  1729. {
  1730. hotelRegions.Remove(hotelRegion);
  1731. if (hotelRegion.Data.Count > 0)
  1732. {
  1733. hotelRegion.Data.Add(hotelNumberInfo);
  1734. }
  1735. hotelRegion.Number += hotelRoomTotal;
  1736. hotelRegions.Add(hotelRegion);
  1737. }
  1738. }
  1739. else
  1740. {
  1741. hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });
  1742. }
  1743. }
  1744. _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });
  1745. }
  1746. }
  1747. else if (type == 3)
  1748. {
  1749. //机票
  1750. var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
  1751. .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)
  1752. .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)
  1753. .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)
  1754. .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })
  1755. .ToListAsync();
  1756. if (airTicketInfos.Count > 0)
  1757. {
  1758. List<RegionInfo> airTicketRegions = new List<RegionInfo>();
  1759. foreach (var item in airTicketInfos)
  1760. {
  1761. var ticketClass = new
  1762. {
  1763. TiketClass = item.AirType,
  1764. Number = item.ClientNum
  1765. };
  1766. if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))
  1767. {
  1768. RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));
  1769. if (airTicketRegion != null)
  1770. {
  1771. airTicketRegions.Remove(airTicketRegion);
  1772. if (airTicketRegion.Data.Count > 0)
  1773. {
  1774. airTicketRegion.Data.Add(ticketClass);
  1775. }
  1776. airTicketRegion.Number += item.ClientNum;
  1777. airTicketRegions.Add(airTicketRegion);
  1778. }
  1779. }
  1780. else
  1781. {
  1782. airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });
  1783. }
  1784. }
  1785. _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });
  1786. }
  1787. }
  1788. else if (type == 4)
  1789. {
  1790. //车辆
  1791. var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1792. var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();
  1793. if (opInfos.Count > 0)
  1794. {
  1795. List<RegionInfo> opRegions = new List<RegionInfo>();
  1796. foreach (var item in opInfos)
  1797. {
  1798. int carNum = 0;
  1799. var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();
  1800. if (opContentInfo.Count > 0)
  1801. {
  1802. foreach (var item1 in opContentInfo)
  1803. {
  1804. if (item1.Price > 0 && item1.Count > 0)
  1805. {
  1806. carNum += item1.Count;
  1807. }
  1808. }
  1809. }
  1810. if (carNum > 0)
  1811. {
  1812. var opData = new
  1813. {
  1814. ServiceCompany = item.ServiceCompany,
  1815. BusName = item.BusName,
  1816. Numbuer = carNum
  1817. };
  1818. if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))
  1819. {
  1820. RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));
  1821. if (opRegion != null)
  1822. {
  1823. opRegions.Remove(opRegion);
  1824. if (opRegion.Data.Count > 0)
  1825. {
  1826. opRegion.Data.Add(opData);
  1827. }
  1828. opRegion.Number += carNum;
  1829. opRegions.Add(opRegion);
  1830. }
  1831. }
  1832. else
  1833. {
  1834. opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });
  1835. }
  1836. }
  1837. }
  1838. _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });
  1839. }
  1840. }
  1841. #endregion
  1842. _view.TypeItem = _types;
  1843. return _view;
  1844. }
  1845. #endregion
  1846. #region 市场部销售额
  1847. /// <summary>
  1848. /// 市场部销售额
  1849. /// Init 基础数据(公司/人员/年份/季度/月份)
  1850. /// </summary>
  1851. /// <param name="_dto">市场部销售额请求dto</param>
  1852. /// <returns></returns>
  1853. [HttpPost("PostMarketingSalesInitData")]
  1854. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1855. public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)
  1856. {
  1857. #region 参数验证
  1858. MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();
  1859. var validResult = await validationRules.ValidateAsync(_dto);
  1860. if (!validResult.IsValid)
  1861. {
  1862. var errors = new StringBuilder();
  1863. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  1864. return Ok(JsonView(false, errors.ToString()));
  1865. }
  1866. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1867. #region 页面操作权限验证
  1868. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1869. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  1870. #endregion
  1871. var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)
  1872. .Select(it => new { id = it.Id, name = it.CompanyName })
  1873. .ToList();
  1874. List<int> companyIds = companyData.Select(it => it.id).ToList();
  1875. List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)
  1876. .Select(it => it.JietuanOperator )
  1877. .ToList();
  1878. //var jobData = _sqlSugar.Queryable<Sys_JobPost>().Where(it => it.IsDel == 0 && companyIds.Contains(it.CompanyId) && (it.JobName.Contains("经理") || it.JobName.Contains("主管")))
  1879. // .Select(it => new { it.Id, it.CompanyId, it.DepId, it.JobName })
  1880. // .ToList();
  1881. //List<int> jobIds = jobData.Select(it => it.Id).ToList();
  1882. //(depIds.Contains(it.DepId) || jobIds.Contains(it.JobPostId)
  1883. //userId = 21
  1884. var userData = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))
  1885. .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })
  1886. .ToList();
  1887. companyData.Insert(0, new { id = -1, name = "全部" });
  1888. userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });
  1889. #region 年份
  1890. var dtData = new List<dynamic>();
  1891. int dt = DateTime.Now.Year;
  1892. for (int y = dt; y >= dt-4; y--)
  1893. {
  1894. //季度
  1895. var quarterDatas = new List<dynamic>();
  1896. quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });
  1897. for (int q = 0; q < 4; q++)
  1898. {
  1899. dynamic quarterData = null;
  1900. if (q == 0)
  1901. {
  1902. var monthDatas = new List<dynamic>();
  1903. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });
  1904. for (int m = 1; m < 4; m++)
  1905. {
  1906. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1907. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1908. }
  1909. //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };
  1910. quarterData = new { name = "第一季度", monthData = monthDatas };
  1911. }
  1912. else if (q == 1)
  1913. {
  1914. var monthDatas = new List<dynamic>();
  1915. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });
  1916. for (int m = 4; m < 7; m++)
  1917. {
  1918. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1919. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1920. }
  1921. //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };
  1922. quarterData = new { name = "第二季度", monthData = monthDatas };
  1923. }
  1924. else if (q == 2)
  1925. {
  1926. var monthDatas = new List<dynamic>();
  1927. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });
  1928. for (int m = 7; m < 10; m++)
  1929. {
  1930. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1931. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1932. }
  1933. //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };
  1934. quarterData = new { name = "第三季度", monthData = monthDatas };
  1935. }
  1936. else if (q == 3)
  1937. {
  1938. var monthDatas = new List<dynamic>();
  1939. monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });
  1940. for (int m = 10; m < 13; m++)
  1941. {
  1942. MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);
  1943. monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });
  1944. }
  1945. //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };
  1946. quarterData = new { name = "第四季度", monthData = monthDatas };
  1947. }
  1948. quarterDatas.Add(quarterData);
  1949. }
  1950. dtData.Add(new
  1951. {
  1952. year = y,
  1953. //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },
  1954. quarterData = quarterDatas,
  1955. });
  1956. }
  1957. #endregion
  1958. return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));
  1959. #endregion
  1960. }
  1961. private static string ConvertToChinese(int month)
  1962. {
  1963. if (month < 1 || month > 12)
  1964. throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");
  1965. var cultureInfo = new System.Globalization.CultureInfo("zh-CN");
  1966. var dateTimeFormat = cultureInfo.DateTimeFormat;
  1967. return dateTimeFormat.GetMonthName(month);
  1968. }
  1969. /// <summary>
  1970. /// 市场部销售额
  1971. /// 年度/季度/月度 报表(同比)
  1972. /// (增加团组查询条件 IsSure=1)
  1973. /// </summary>
  1974. /// <param name="_dto">市场部销售额请求dto</param>
  1975. /// <returns></returns>
  1976. [HttpPost("PostMarketingSalesStatistics")]
  1977. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  1978. public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)
  1979. {
  1980. #region 参数验证
  1981. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  1982. var validResult = await validationRules.ValidateAsync(_dto);
  1983. if (!validResult.IsValid)
  1984. {
  1985. var errors = new StringBuilder();
  1986. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  1987. return Ok(JsonView(false, errors.ToString()));
  1988. }
  1989. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  1990. #region 页面操作权限验证
  1991. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  1992. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  1993. #endregion
  1994. #endregion
  1995. string beginDt = $"{_dto.BeginDt} 00:00:00",endDt = $"{_dto.EndDt} 23:59:59";
  1996. return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));
  1997. }
  1998. private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)
  1999. {
  2000. //全部人员Id
  2001. //查询所有公司的市场部
  2002. List<int> pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();
  2003. List<int> userIds = new List<int>();
  2004. var userDatas = await _sqlSugar.Queryable<Sys_Users>()
  2005. .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)
  2006. .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains( u.Id))
  2007. .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })
  2008. .ToListAsync();
  2009. userIds = userDatas.Select(it => it.Id).ToList();
  2010. if (companyId > 0)
  2011. {
  2012. userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();
  2013. }
  2014. if (groupPickupUserId > 0)
  2015. {
  2016. userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();
  2017. }
  2018. return userIds;
  2019. }
  2020. /// <summary>
  2021. /// 计算团组销售额
  2022. /// </summary>
  2023. /// <param name="companyId"></param>
  2024. /// <param name="groupPickupUserId"></param>
  2025. /// <param name="beginDt"></param>
  2026. /// <param name="endDt"></param>
  2027. /// <returns></returns>
  2028. private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId,string beginDt, string endDt)
  2029. {
  2030. decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;
  2031. var _view = new SalesYOYView();
  2032. List<int> userIds = new List<int>();
  2033. userIds = await GetUserIds(companyId, groupPickupUserId);
  2034. string userSqlWhere = "";
  2035. if (userIds.Count > 0)
  2036. {
  2037. userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");
  2038. }
  2039. else
  2040. {
  2041. _view = new SalesYOYView
  2042. {
  2043. thisYearSales = "0.00",
  2044. lastYearSales = "0.00",
  2045. };
  2046. return _view;
  2047. }
  2048. string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),
  2049. lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");
  2050. string salesSql = string.Format(@"
  2051. SELECT
  2052. 'ThisSales' As [Name],
  2053. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2054. FROM
  2055. (
  2056. SELECT di.VisitDate,
  2057. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2058. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2059. ) AS Sales
  2060. FROM
  2061. Grp_DelegationInfo di
  2062. WHERE di.IsDel = 0 AND di.IsSure = 1
  2063. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {0})
  2064. AND di.VisitDate BETWEEN '{1}' AND '{2}'
  2065. ) temp
  2066. Union ALL
  2067. SELECT
  2068. 'LastSales' As [Name],
  2069. CAST(SUM(Sales) AS decimal(12,2)) As Sales
  2070. FROM
  2071. (
  2072. SELECT di.VisitDate,
  2073. (SELECT CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables
  2074. WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid
  2075. ) AS Sales
  2076. FROM
  2077. Grp_DelegationInfo di
  2078. WHERE di.IsDel = 0 AND di.IsSure = 1
  2079. AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})
  2080. AND di.VisitDate BETWEEN '{4}' AND '{5}'
  2081. ) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);
  2082. var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();
  2083. thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;
  2084. lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;
  2085. if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;
  2086. return new SalesYOYView() {
  2087. thisYearSales = thisSales.ToString("#0.00"),
  2088. lastYearSales = lastSales.ToString("#0.00"),
  2089. yoy = yoy.ToString("#0.00")
  2090. };
  2091. }
  2092. private class SalesView
  2093. {
  2094. public string Name { get; set; }
  2095. public decimal Sales { get; set; }
  2096. }
  2097. private class SalesYOYView
  2098. {
  2099. public string thisYearSales { get; set; }
  2100. public string lastYearSales { get; set; }
  2101. public string yoy { get; set; } = "1.00";
  2102. }
  2103. /// <summary>
  2104. /// 市场部销售额
  2105. /// 团组列表
  2106. /// (增加团组查询条件 IsSure=1)
  2107. /// </summary>
  2108. /// <param name="_dto">市场部销售额请求dto</param>
  2109. /// <returns></returns>
  2110. [HttpPost("PostMarketingSalesGroupList")]
  2111. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2112. public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)
  2113. {
  2114. #region 参数验证
  2115. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2116. var validResult = await validationRules.ValidateAsync(_dto);
  2117. if (!validResult.IsValid)
  2118. {
  2119. var errors = new StringBuilder();
  2120. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2121. return Ok(JsonView(false, errors.ToString()));
  2122. }
  2123. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2124. #region 页面操作权限验证
  2125. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2126. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2127. #endregion
  2128. #endregion
  2129. string userSql = "";
  2130. List<int> userIds = new List<int>();
  2131. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2132. if (userIds.Count <= 0)
  2133. {
  2134. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2135. }
  2136. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2137. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2138. {
  2139. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2140. }
  2141. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2142. string sql = string.Format(@$"SELECT
  2143. ROW_NUMBER() OVER (
  2144. ORDER BY
  2145. CollectionDays
  2146. ) AS RowNumber,
  2147. *
  2148. FROM
  2149. (
  2150. SELECT
  2151. di.Id,
  2152. di.TeamName,
  2153. di.ClientUnit,
  2154. di.ClientName,
  2155. di.VisitDate,
  2156. di.VisitPNumber,
  2157. di.JietuanOperator,
  2158. di.VisitEndDate,
  2159. (
  2160. SELECT
  2161. CAST(
  2162. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2163. ) AS GroupSales
  2164. FROM
  2165. Fin_ForeignReceivables
  2166. WHERE
  2167. IsDel = 0
  2168. AND di.Id = Diid
  2169. AND AddingWay IN (0, 1, 2)
  2170. ) AS GroupSales,
  2171. u.CnName AS GroupPickupUser,
  2172. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2173. FROM
  2174. Grp_DelegationInfo di
  2175. WITH
  2176. (NoLock)
  2177. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2178. WHERE
  2179. di.Isdel = 0
  2180. AND di.IsSure = 1 {userSql}
  2181. AND VisitDate Between '{beginDt}' And '{endDt}'
  2182. ) Temp ");
  2183. RefAsync<int> total = 0;
  2184. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2185. return Ok(JsonView(true, "操作成功!", groupData, total));
  2186. }
  2187. /// <summary>
  2188. /// 市场部销售额
  2189. /// 客户类型、客户等级 统计
  2190. /// </summary>
  2191. /// <param name="_dto">市场部销售额请求dto</param>
  2192. /// <returns></returns>
  2193. [HttpPost("PostMarketingSalesGroupStatistics")]
  2194. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2195. public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)
  2196. {
  2197. #region 参数验证
  2198. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2199. var validResult = await validationRules.ValidateAsync(_dto);
  2200. if (!validResult.IsValid)
  2201. {
  2202. var errors = new StringBuilder();
  2203. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2204. return Ok(JsonView(false, errors.ToString()));
  2205. }
  2206. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2207. #region 页面操作权限验证
  2208. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2209. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2210. #endregion
  2211. #endregion
  2212. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2213. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2214. string userSql = "";
  2215. if (userIds.Count > 0)
  2216. {
  2217. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",",userIds)})");
  2218. }
  2219. else
  2220. {
  2221. if (_dto.PortType == 2 || _dto.PortType == 3)
  2222. {
  2223. return Ok(JsonView(true, "操作成功!", new List<object> { }));
  2224. }
  2225. else
  2226. {
  2227. return Ok(JsonView(true, "操作成功!", new
  2228. {
  2229. customerTypeData = new List<object> { },
  2230. clientGradeData = new List<object> { }
  2231. }));
  2232. }
  2233. }
  2234. string sql = "";
  2235. if (_dto.StatisticsType == 1 )
  2236. {
  2237. sql = string.Format(@$"Select
  2238. sd.[Name],
  2239. Count(*) As [Count]
  2240. From Grp_DelegationInfo di
  2241. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2242. Where di.Isdel = 0
  2243. And IsSure = 1 {userSql}
  2244. And VisitDate Between '{beginDt}' And '{endDt}'
  2245. Group By [Name]
  2246. Order By Count Desc");
  2247. }
  2248. else if (_dto.StatisticsType == 2)
  2249. {
  2250. sql = string.Format(@$"Select
  2251. sd.[Name],
  2252. Count(*) As [Count]
  2253. From Grp_DelegationInfo di
  2254. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2255. Where di.Isdel = 0
  2256. And IsSure = 1 {userSql}
  2257. And VisitDate Between '{beginDt}' And '{endDt}'
  2258. Group By [Name]
  2259. Order By Count Desc");
  2260. }
  2261. else return Ok(JsonView(false, "StatisticsType不在可取范围!"));
  2262. if (_dto.PortType == 1)
  2263. {
  2264. string sql1 = string.Format(@$"Select
  2265. sd.[Name],
  2266. Count(*) As [Count]
  2267. From Grp_DelegationInfo di
  2268. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2269. Where di.Isdel = 0
  2270. And IsSure = 1 {userSql}
  2271. And VisitDate Between '{beginDt}' And '{endDt}'
  2272. Group By [Name]
  2273. Order By Count Desc");
  2274. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2275. string sql2 = string.Format(@$"Select
  2276. sd.[Name],
  2277. Count(*) As [Count]
  2278. From Grp_DelegationInfo di
  2279. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2280. Where di.Isdel = 0
  2281. And IsSure = 1 {userSql}
  2282. And VisitDate Between '{beginDt}' And '{endDt}'
  2283. Group By [Name]
  2284. Order By Count Desc");
  2285. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2286. return Ok(JsonView(true, "操作成功!", new {
  2287. customerTypeData= customerTypeData,
  2288. clientGradeData = clientGradeData
  2289. }));
  2290. }
  2291. else if (_dto.PortType == 2 || _dto.PortType == 3)
  2292. {
  2293. var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();
  2294. return Ok(JsonView(true, "操作成功!", data, data.Count));
  2295. }
  2296. else return Ok(JsonView(false, MsgTips.Port));
  2297. }
  2298. /// <summary>
  2299. /// 市场部销售额
  2300. /// 接单排名
  2301. /// </summary>
  2302. /// <param name="_dto">市场部销售额请求dto</param>
  2303. /// <returns></returns>
  2304. [HttpPost("PostMarketingSalesOrderRanking")]
  2305. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2306. public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)
  2307. {
  2308. #region 参数验证
  2309. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2310. var validResult = await validationRules.ValidateAsync(_dto);
  2311. if (!validResult.IsValid)
  2312. {
  2313. var errors = new StringBuilder();
  2314. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2315. return Ok(JsonView(false, errors.ToString()));
  2316. }
  2317. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2318. #region 页面操作权限验证
  2319. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2320. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2321. #endregion
  2322. #endregion
  2323. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2324. List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2325. string userSql = "";
  2326. if (userIds.Count > 0)
  2327. {
  2328. userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");
  2329. }else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2330. string sql = string.Format(@$"Select
  2331. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2332. u.CnName As UserName,
  2333. Count(*) As [Count]
  2334. From Grp_DelegationInfo di
  2335. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2336. Where di.Isdel = 0
  2337. AND IsSure = 1 {userSql}
  2338. And VisitDate Between '{beginDt}' And '{endDt}'
  2339. Group By CnName");
  2340. RefAsync<int> total = 0;
  2341. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2342. return Ok(JsonView(true, "操作成功!", rankingData, total));
  2343. }
  2344. /// <summary>
  2345. /// 市场部销售额
  2346. /// 团组列表、客户类型、客户等级、接单排名
  2347. /// (增加团组查询条件 IsSure=1)
  2348. /// </summary>
  2349. /// <param name="_dto">市场部销售额请求dto</param>
  2350. /// <returns></returns>
  2351. [HttpPost("PostMarketingSalesGroupItem")]
  2352. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2353. public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)
  2354. {
  2355. #region 参数验证
  2356. MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();
  2357. var validResult = await validationRules.ValidateAsync(_dto);
  2358. if (!validResult.IsValid)
  2359. {
  2360. var errors = new StringBuilder();
  2361. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2362. return Ok(JsonView(false, errors.ToString()));
  2363. }
  2364. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2365. #region 页面操作权限验证
  2366. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2367. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2368. #endregion
  2369. #endregion
  2370. string userSql = "";
  2371. List<int> userIds = new List<int>();
  2372. userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);
  2373. if (userIds.Count <= 0)
  2374. {
  2375. return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));
  2376. }
  2377. else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";
  2378. if (!string.IsNullOrEmpty(_dto.SearchCriteria))
  2379. {
  2380. userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");
  2381. }
  2382. string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";
  2383. #region 团组List
  2384. string sql = string.Format(@$"SELECT
  2385. ROW_NUMBER() OVER (
  2386. ORDER BY
  2387. CollectionDays
  2388. ) AS RowNumber,
  2389. *
  2390. FROM
  2391. (
  2392. SELECT
  2393. di.Id,
  2394. di.TeamName,
  2395. di.ClientUnit,
  2396. di.ClientName,
  2397. di.VisitDate,
  2398. di.VisitPNumber,
  2399. di.JietuanOperator,
  2400. di.VisitEndDate,
  2401. (
  2402. SELECT
  2403. CAST(
  2404. COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)
  2405. ) AS GroupSales
  2406. FROM
  2407. Fin_ForeignReceivables
  2408. WHERE
  2409. IsDel = 0
  2410. AND di.Id = Diid
  2411. AND AddingWay IN (0, 1, 2)
  2412. ) AS GroupSales,
  2413. u.CnName AS GroupPickupUser,
  2414. DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays
  2415. FROM
  2416. Grp_DelegationInfo di
  2417. WITH
  2418. (NoLock)
  2419. LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id
  2420. WHERE
  2421. di.Isdel = 0
  2422. AND di.IsSure = 1 {userSql}
  2423. AND VisitDate Between '{beginDt}' And '{endDt}'
  2424. ) Temp ");
  2425. RefAsync<int> total = 0;
  2426. var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);
  2427. #endregion
  2428. #region 客户类型、客户等级 统计
  2429. string sql1 = string.Format(@$"Select
  2430. sd.[Name],
  2431. Count(*) As [Count]
  2432. From Grp_DelegationInfo di
  2433. Left Join Sys_SetData sd On di.TeamDid = sd.Id
  2434. Where di.Isdel = 0
  2435. And IsSure = 1 {userSql}
  2436. And VisitDate Between '{beginDt}' And '{endDt}'
  2437. Group By [Name]
  2438. Order By Count Desc");
  2439. var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();
  2440. string sql2 = string.Format(@$"Select
  2441. sd.[Name],
  2442. Count(*) As [Count]
  2443. From Grp_DelegationInfo di
  2444. Left Join Sys_SetData sd On di.TeamLevSId = sd.Id
  2445. Where di.Isdel = 0
  2446. And IsSure = 1 {userSql}
  2447. And VisitDate Between '{beginDt}' And '{endDt}'
  2448. Group By [Name]
  2449. Order By Count Desc");
  2450. var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();
  2451. #endregion
  2452. #region 接单排名
  2453. string sql4 = string.Format(@$"Select
  2454. ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,
  2455. u.CnName As UserName,
  2456. Count(*) As [Count]
  2457. From Grp_DelegationInfo di
  2458. Left Join Sys_Users u On di.JietuanOperator = u.Id
  2459. Where di.Isdel = 0
  2460. AND IsSure = 1 {userSql}
  2461. And VisitDate Between '{beginDt}' And '{endDt}'
  2462. Group By CnName");
  2463. var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();
  2464. #endregion
  2465. var viewData = new {
  2466. groupData = groupData,
  2467. groupTotal = total,
  2468. customerTypeData = customerTypeData,
  2469. clientGradeData = clientGradeData,
  2470. rankingData = rankingData
  2471. };
  2472. return Ok(JsonView(true, "操作成功!", viewData, total));
  2473. }
  2474. /// <summary>
  2475. /// 市场部销售额
  2476. /// 客户拜访列表
  2477. /// </summary>
  2478. /// <param name="_dto">市场部销售额请求dto</param>
  2479. /// <returns></returns>
  2480. [HttpPost("PostMarketingSalesVCList")]
  2481. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2482. public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)
  2483. {
  2484. #region 参数验证
  2485. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2486. var validResult = await validationRules.ValidateAsync(_dto);
  2487. if (!validResult.IsValid)
  2488. {
  2489. var errors = new StringBuilder();
  2490. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2491. return Ok(JsonView(false, errors.ToString()));
  2492. }
  2493. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2494. #region 页面操作权限验证
  2495. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2496. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2497. #endregion
  2498. #endregion
  2499. return Ok(await _visitingClientsRep._List(_dto.PortType,_dto.PageIndex,_dto.PageSize,_dto.DiId,_dto.Search));
  2500. }
  2501. /// <summary>
  2502. /// 市场部销售额
  2503. /// 客户拜访 操作(添加 Or 编辑)
  2504. /// </summary>
  2505. /// <param name="_dto">市场部销售额请求dto</param>
  2506. /// <returns></returns>
  2507. [HttpPost("PostMarketingSalesVCOperate")]
  2508. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2509. public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)
  2510. {
  2511. #region 参数验证
  2512. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2513. var validResult = await validationRules.ValidateAsync(_dto);
  2514. if (!validResult.IsValid)
  2515. {
  2516. var errors = new StringBuilder();
  2517. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2518. return Ok(JsonView(false, errors.ToString()));
  2519. }
  2520. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2521. #region 页面操作权限验证
  2522. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2523. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2524. #endregion
  2525. #endregion
  2526. return Ok(await _visitingClientsRep._AddOrEdit(_dto));
  2527. }
  2528. /// <summary>
  2529. /// 市场部销售额
  2530. /// 客户拜访 Del
  2531. /// </summary>
  2532. /// <param name="_dto">市场部销售额请求dto</param>
  2533. /// <returns></returns>
  2534. [HttpPost("PostMarketingSalesVCDel")]
  2535. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2536. public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)
  2537. {
  2538. return Ok(await _visitingClientsRep._Del(_dto.Id,_dto.UserId));
  2539. }
  2540. /// <summary>
  2541. /// 市场部销售额
  2542. /// 客户拜访 操作 save
  2543. /// </summary>
  2544. /// <param name="_dto">市场部销售额请求dto</param>
  2545. /// <returns></returns>
  2546. [HttpPost("PostMarketingSalesVCSave")]
  2547. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2548. public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)
  2549. {
  2550. #region 参数验证
  2551. MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();
  2552. var validResult = await validationRules.ValidateAsync(_dto);
  2553. if (!validResult.IsValid)
  2554. {
  2555. var errors = new StringBuilder();
  2556. foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);
  2557. return Ok(JsonView(false, errors.ToString()));
  2558. }
  2559. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2560. #region 页面操作权限验证
  2561. pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2562. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));
  2563. #endregion
  2564. #endregion
  2565. return Ok(await _visitingClientsRep._Save(_dto));
  2566. }
  2567. #endregion
  2568. #region 日付报表
  2569. /// <summary>
  2570. /// 日付类型数据
  2571. /// </summary>
  2572. /// <param name="_dto"></param>
  2573. /// <returns></returns>
  2574. [HttpPost("DailypaymentTypeInit")]
  2575. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2576. public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)
  2577. {
  2578. #region 参数验证
  2579. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg:MsgTips.Port));
  2580. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2581. #region 页面操作权限验证
  2582. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2583. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2584. #endregion
  2585. #endregion
  2586. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2587. {
  2588. var defaultParentIds = new List<int>() {
  2589. 48,// 人员费用
  2590. 49,// 办公费用
  2591. 50,// 销售费用
  2592. 51,// 其他费用
  2593. 55,// 大运会
  2594. };
  2595. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2596. .CreateRedisRepository()
  2597. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2598. var dailyTypeData = await _sqlSugar.Queryable<DailypaymentParentTypeView>()
  2599. .Includes(x => x.SubData)
  2600. .Where(x => defaultParentIds.Contains(x.Id))
  2601. .ToListAsync();
  2602. dailyTypeData.ForEach(x =>
  2603. {
  2604. x.SubData.ForEach(y =>
  2605. {
  2606. int currId = dailypaymentTypeData.Find(z => z == y.Id);
  2607. y.IsChecked = currId == 0 ? false : true;
  2608. });
  2609. });
  2610. var companyData = await _sqlSugar.Queryable<Sys_Company>()
  2611. .Where(x => x.IsDel == 0)
  2612. .Select(x => new { id = x.Id, name = x.CompanyName })
  2613. .ToListAsync();
  2614. return Ok(JsonView(true, "查询成功!", new { dailyTypeData = dailyTypeData, companyData = companyData }));
  2615. }
  2616. else
  2617. {
  2618. return Ok(JsonView(false, "查询失败"));
  2619. }
  2620. }
  2621. /// <summary>
  2622. /// 日付类型数据 Save
  2623. /// </summary>
  2624. /// <param name="_dto"></param>
  2625. /// <returns></returns>
  2626. [HttpPost("DailypaymentTypeDataSave")]
  2627. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2628. public async Task<IActionResult> DailypaymentTypeDataSave(DailypaymentTypeDataSaveDto _dto)
  2629. {
  2630. #region 参数验证
  2631. if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg: MsgTips.Port));
  2632. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2633. #region 页面操作权限验证
  2634. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2635. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2636. #endregion
  2637. #endregion
  2638. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2639. {
  2640. if (_dto.TypeIds.Count < 1) return Ok(JsonView(false, "请传入需要保存的TypeIds"));
  2641. var res = await RedisRepository.RedisFactory
  2642. .CreateRedisRepository()
  2643. .StringSetAsync(
  2644. key:"DailypaymentTypeData",
  2645. _dto.TypeIds,
  2646. timeout:null );
  2647. if (!res) return Ok(JsonView(false, "操作失败"));
  2648. return Ok(JsonView(true, "操作成功!"));
  2649. }
  2650. else return Ok(JsonView(false, "操作失败"));
  2651. }
  2652. /// <summary>
  2653. /// 日付数据列表
  2654. /// </summary>
  2655. /// <param name="_dto"></param>
  2656. /// <returns></returns>
  2657. [HttpPost("DailypaymentRange")]
  2658. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2659. public async Task<IActionResult> DailypaymentRange(DailypaymentRangeDto _dto)
  2660. {
  2661. #region 参数验证
  2662. var validator = new DailypaymentRangeDtoValidator();
  2663. var validationRes = validator.Validate(_dto);
  2664. if (!validationRes.IsValid)
  2665. {
  2666. StringBuilder sb = new StringBuilder();
  2667. foreach (var item in validationRes.Errors)
  2668. {
  2669. sb.AppendLine(item.ErrorMessage);
  2670. }
  2671. return Ok(JsonView(false, sb.ToString()));
  2672. }
  2673. PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
  2674. #region 页面操作权限验证
  2675. //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);
  2676. //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));
  2677. #endregion
  2678. #endregion
  2679. if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS
  2680. {
  2681. DateTime _beginDt = Convert.ToDateTime($"{_dto.BeginDt} 00:00:00"),
  2682. _endDt = Convert.ToDateTime($"{_dto.EndDt} 23:59:59");
  2683. string sqlWhere = string.Format(@" And dfp.CreateTime Between '{0}' And '{1}'",_beginDt,_endDt);
  2684. var dailypaymentTypeData = await RedisRepository.RedisFactory
  2685. .CreateRedisRepository()
  2686. .StringGetAsync<List<int>>("DailypaymentTypeData") ?? new List<int>();
  2687. string sql = string.Format(@"
  2688. Select
  2689. dfp.Id,
  2690. dfp.Instructions,
  2691. dfp.PriceTypeId,
  2692. sd1.Name As FeeType,
  2693. dfp.TransferTypeId,
  2694. sd2.Name As TransferType,
  2695. dfp.SumPrice,
  2696. dfp.FAuditDate,
  2697. dfp.MAuditDate,
  2698. dfp.CompanyId,
  2699. c.CompanyName,
  2700. dfp.CreateUserId As ApplicantId,
  2701. u.CnName As Applicant,
  2702. dfp.CreateTime As ApplicantDt,
  2703. dfp.Instructions+u.CnName As ViewStr
  2704. From Fin_DailyFeePayment dfp
  2705. Left Join Sys_Users u On dfp.CreateUserId = u.Id
  2706. Left Join Sys_SetData sd1 On dfp.TransferTypeId = sd1.Id
  2707. Left Join Sys_Company c On dfp.CompanyId = c.Id
  2708. Left Join Sys_SetData sd2 On dfp.PriceTypeId = sd2.Id
  2709. Where dfp.IsDel = 0 And dfp.IsPay = 1
  2710. ", sqlWhere);//--Order By dfp.CreateTime Desc
  2711. if (_dto.Type == 1) //data
  2712. {
  2713. RefAsync<int> total = 0;
  2714. var _view = await _sqlSugar.SqlQueryable<DailyFeePaymentRangeView>(sql)
  2715. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2716. .WhereIF(dailypaymentTypeData.Count > 0,
  2717. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2718. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2719. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2720. .OrderByDescending(x => x.ApplicantDt)
  2721. .ToPageListAsync(
  2722. pageNumber: _dto.PageIndex,
  2723. pageSize: _dto.PageSize,
  2724. totalNumber: total
  2725. );
  2726. _sqlSugar.ThenMapper(_view, x =>
  2727. {
  2728. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2729. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2730. .ToList();
  2731. });
  2732. //单独处理
  2733. return Ok(JsonView(true, "操作成功!", new { data = _view, total = _view.Sum(x => x.SumPrice) }, total));
  2734. }
  2735. else if (_dto.Type == 2) //view
  2736. {
  2737. var _view = await _sqlSugar.SqlQueryable<ExcelView>(sql)
  2738. .Where(x => x.ApplicantDt >= _beginDt && x.ApplicantDt <= _endDt)
  2739. .WhereIF(dailypaymentTypeData.Count > 0,
  2740. x => dailypaymentTypeData.Contains(x.PriceTypeId))
  2741. .WhereIF(_dto.CompanyIds.Count > 0, x => _dto.CompanyIds.Contains(x.CompanyId))
  2742. .WhereIF(!string.IsNullOrEmpty(_dto.Filter), x => x.ViewStr.Contains(_dto.Filter))
  2743. .OrderByDescending(x => x.ApplicantDt)
  2744. .ToPageListAsync(
  2745. pageNumber: 1,
  2746. pageSize: 99999
  2747. ) ;
  2748. _sqlSugar.ThenMapper(_view, x =>
  2749. {
  2750. x.Contents = _sqlSugar.Queryable<DailyFeePaymentContentView>()
  2751. .SetContext(x1 => x1.DFPId, () => x.Id, x)
  2752. .ToList();
  2753. string str = "";
  2754. int index = 1;
  2755. foreach (var item in x.Contents)
  2756. {
  2757. string str1 = $"{index}、费用名称:[{item.PriceName}] 单价:[{item.Price.ToString("#0.00")}] 数量:[{item.Quantity.ToString("#0.00")}] 小计:[{item.ItemTotal.ToString("#0.00")}] 备注:[{item.Remark}]";
  2758. if (index == x.Contents.Count) str += str1;
  2759. else str += str1 + "\r\n";
  2760. index++;
  2761. }
  2762. x.ContentStr = str;
  2763. });
  2764. if (_view.Count > 0 )
  2765. {
  2766. //DataTable dt = GeneralMethod.
  2767. DataTable dt = CommonFun.GetDataTableFromIList(_view );
  2768. dt.TableName = $"_view";
  2769. decimal total = _view.Sum(x => x.SumPrice);
  2770. WorkbookDesigner designer = new WorkbookDesigner();
  2771. designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/日付报表模板.xls");
  2772. designer.SetDataSource(dt);
  2773. designer.SetDataSource("Total", total);
  2774. designer.Workbook.Worksheets[0].Name = "日付报表";
  2775. designer.Process();
  2776. string fileName = $"DailyPayment/日付报表{ DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
  2777. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
  2778. string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
  2779. return Ok(JsonView(true, "操作成功", new { url = rst })) ;
  2780. }
  2781. return Ok(JsonView(true, ",暂无数据"));
  2782. }
  2783. return Ok(JsonView(false, "操作失败"));
  2784. }
  2785. else return Ok(JsonView(false, "操作失败"));
  2786. }
  2787. #endregion
  2788. #region 统计模块
  2789. /// <summary>
  2790. /// 同比
  2791. /// 营业额(今年和去年的)、成本支出(今年和去年的)、毛利润(今年和去年的)
  2792. /// </summary>
  2793. /// <param name="_dto">市场部销售额请求dto</param>
  2794. /// <returns></returns>
  2795. [HttpPost("StatisticsYOY")]
  2796. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  2797. public async Task<IActionResult> StatisticsYOY(YOYDto _dto)
  2798. {
  2799. if (_dto.Year < 1) return Ok(JsonView(false,"操作失败"));
  2800. string thisBeginDt = $"{_dto.Year}-01-01 00:00:00",
  2801. thisEndDt = $"{_dto.Year}-12-31 23:59:59";
  2802. string lastBeginDt = $"{_dto.Year - 1}-01-01 00:00:00",
  2803. lastEndDt = $"{_dto.Year - 1}-12-31 23:59:59";
  2804. #region 营业额
  2805. string thisSql = string.Format(@"
  2806. SELECT
  2807. di.Id,
  2808. di.VisitDate,
  2809. YEAR(di.VisitDate) AS Year,
  2810. MONTH(di.VisitDate) AS Month,
  2811. (
  2812. SELECT
  2813. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  2814. FROM
  2815. Fin_ForeignReceivables
  2816. WHERE
  2817. IsDel = 0
  2818. AND AddingWay IN (0, 1, 2)
  2819. AND di.Id = Diid
  2820. ) AS Amount
  2821. FROM
  2822. Grp_DelegationInfo di
  2823. WHERE
  2824. di.IsDel = 0
  2825. AND di.IsSure = 1
  2826. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  2827. ", thisBeginDt,thisEndDt);
  2828. string lastSql = string.Format(@"
  2829. SELECT
  2830. di.Id,
  2831. di.VisitDate,
  2832. YEAR(di.VisitDate) AS YEAR,
  2833. MONTH(di.VisitDate) AS MONTH,
  2834. (
  2835. SELECT
  2836. CAST(SUM(ItemSumPrice * Rate) AS DECIMAL(12, 2))
  2837. FROM
  2838. Fin_ForeignReceivables
  2839. WHERE
  2840. IsDel = 0
  2841. AND AddingWay IN (0, 1, 2)
  2842. AND di.Id = Diid
  2843. ) AS Amount
  2844. FROM
  2845. Grp_DelegationInfo di
  2846. WHERE
  2847. di.IsDel = 0
  2848. AND di.IsSure = 1
  2849. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  2850. ", lastBeginDt, lastEndDt);
  2851. var thisSalesData = _sqlSugar.SqlQueryable<SalesSqlView>(thisSql).ToList();
  2852. var lastSalesData = _sqlSugar.SqlQueryable<SalesSqlView>(lastSql).ToList();
  2853. List<SalesReturnView> salesData = new List<SalesReturnView>();
  2854. int salesMonth = 1;
  2855. while (salesMonth < 13)
  2856. {
  2857. var thisMonthData = thisSalesData.Where(x => x.Month == salesMonth).ToList();
  2858. var lastMonthData = lastSalesData.Where(x => x.Month == salesMonth).ToList();
  2859. decimal thisMonthSales = thisMonthData.Sum(x => x?.Amount ?? 0);
  2860. var thisIds = thisMonthData.Select(x => x.Id).ToList();
  2861. decimal lastMonthSales = lastMonthData.Sum(x => x?.Amount ?? 0);
  2862. var lastIds = lastMonthData.Select(x => x.Id).ToList();
  2863. salesData.Add(new SalesReturnView( _dto.Year,salesMonth, thisMonthSales, lastMonthSales, thisIds, lastIds) );
  2864. salesMonth++;
  2865. }
  2866. #endregion
  2867. #region 团组成本
  2868. string thisCostSql = string.Format(@"
  2869. SELECT
  2870. di.Id,
  2871. di.VisitDate,
  2872. YEAR(di.VisitDate) AS YEAR,
  2873. MONTH(di.VisitDate) AS MONTH,
  2874. (
  2875. SELECT
  2876. CAST(SUM(PayMoney * DayRate) AS DECIMAL(12, 2))
  2877. FROM
  2878. Grp_CreditCardPayment
  2879. WHERE
  2880. IsDel = 0
  2881. AND di.Id = Diid
  2882. AND CTable IN(98, 81, 79, 85, 76, 80, 82)
  2883. AND IsPay = 1
  2884. ) AS Amount
  2885. FROM
  2886. Grp_DelegationInfo di
  2887. WHERE
  2888. di.IsDel = 0
  2889. AND di.IsSure = 1
  2890. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  2891. ", thisBeginDt, thisEndDt);
  2892. string lastCostSql = string.Format(@"
  2893. SELECT
  2894. di.Id,
  2895. di.VisitDate,
  2896. YEAR(di.VisitDate) AS YEAR,
  2897. MONTH(di.VisitDate) AS MONTH,
  2898. (
  2899. SELECT
  2900. CAST(SUM(PayMoney * DayRate) AS DECIMAL(12, 2))
  2901. FROM
  2902. Grp_CreditCardPayment
  2903. WHERE
  2904. IsDel = 0
  2905. AND di.Id = Diid
  2906. AND CTable IN(98, 81, 79, 85, 76, 80, 82)
  2907. AND IsPay = 1
  2908. ) AS Amount
  2909. FROM
  2910. Grp_DelegationInfo di
  2911. WHERE
  2912. di.IsDel = 0
  2913. AND di.IsSure = 1
  2914. AND di.VisitDate BETWEEN '{0}' AND '{1}'
  2915. ", lastBeginDt, lastEndDt);
  2916. var thisCostData = _sqlSugar.SqlQueryable<SalesSqlView>(thisCostSql).ToList();
  2917. var lastCostData = _sqlSugar.SqlQueryable<SalesSqlView>(lastCostSql).ToList();
  2918. List<SalesReturnView> costData = new List<SalesReturnView>();
  2919. int costMonth = 1;
  2920. while (costMonth < 13)
  2921. {
  2922. var thisMonthData = thisSalesData.Where(x => x.Month == costMonth).ToList();
  2923. var lastMonthData = lastSalesData.Where(x => x.Month == costMonth).ToList();
  2924. decimal thisMonthSales = thisMonthData.Sum(x => x?.Amount ?? 0);
  2925. var thisIds = thisMonthData.Select(x => x.Id).ToList();
  2926. decimal lastMonthSales = lastMonthData.Sum(x => x?.Amount ?? 0);
  2927. var lastIds = lastMonthData.Select(x => x.Id).ToList();
  2928. costData.Add(new SalesReturnView(_dto.Year, costMonth, thisMonthSales, lastMonthSales, thisIds, lastIds));
  2929. costMonth++;
  2930. }
  2931. #endregion
  2932. return Ok(JsonView(true,"操作成功!", new { SalesData = salesData,CostData = costData }));
  2933. }
  2934. #endregion
  2935. }
  2936. }