StatisticsController.cs 147 KB

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