StatisticsController.cs 156 KB

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