StatisticsController.cs 153 KB

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