StatisticsController.cs 129 KB

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