StatisticsController.cs 150 KB

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