| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669 |
- using AutoMapper;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Linq;
- using OASystem.Domain;
- using OASystem.Domain.AesEncryption;
- using OASystem.Domain.Dtos.Groups;
- using OASystem.Domain.Entities.Customer;
- using OASystem.Domain.Entities.Financial;
- using OASystem.Domain.Entities.Groups;
- using OASystem.Domain.Entities.Resource;
- using OASystem.Domain.ViewModels.Groups;
- using System.Security.Cryptography;
- namespace OASystem.Infrastructure.Repositories.Groups;
- public class AirTicketResRepository : BaseRepository<Grp_AirTicketReservations, Grp_AirTicketReservations>
- {
- private readonly IMapper _mapper;
- private readonly DelegationInfoRepository _groupInfoRep;
- private readonly TeamRateRepository _groupRateRep;
- public AirTicketResRepository(SqlSugarClient sqlSugar, DelegationInfoRepository groupInfoRep, TeamRateRepository groupRateRep, IMapper mapper) : base(sqlSugar)
- {
- _mapper = mapper;
- _groupInfoRep = groupInfoRep;
- _groupRateRep = groupRateRep;
- }
-
- #region 旧版
- public async Task<Result> AirTicketResById(AirTicketResByIdDto dto)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- try
- {
- Grp_AirTicketReservations grp_AirTicket = _sqlSugar.Queryable<Grp_AirTicketReservations>().First(a => a.Id == dto.Id && a.IsDel == 0);
- if (grp_AirTicket == null)
- {
- return result = new Result() { Code = -1, Msg = "暂无数据" };
- }
- else
- {
- Grp_CreditCardPayment grp_CreditCard = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a => a.CId == grp_AirTicket.Id && a.IsDel == 0 && a.CTable == 85);
- if (grp_CreditCard == null) { return result = new Result() { Code = -1, Msg = "暂无数据" }; }
- return result = new Result()
- {
- Code = 0,
- Msg = "查询成功!",
- Data = new
- {
- AirTicket = grp_AirTicket,
- CreditCard = grp_CreditCard,
- }
- };
- }
- }
- catch (Exception)
- {
- return result = new Result() { Code = -2, Msg = "未知错误" };
- }
- }
- public async Task<Result> AirTicketResList(AirTicketResDto dto)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- Grp_DelegationInfo _DelegationInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().First(it => it.Id == dto.DiId);
- if (_DelegationInfo != null)
- {
- string UserId = "";
- List<Grp_GroupsTaskAssignment> gtaUIdList = _sqlSugar.Queryable<Grp_GroupsTaskAssignment>().Where(a => a.DIId == dto.DiId && a.IsDel == 0 && a.CTId == 85).ToList();
- foreach (Grp_GroupsTaskAssignment gta in gtaUIdList)
- UserId += gta.UId + ",";
- if (!string.IsNullOrWhiteSpace(UserId))
- {
- UserId = UserId[..^1];
- }
- else
- {
- UserId = "0";
- }
- string sqlWhere = "";
- if (dto.IsPaySign != -1)
- {
- sqlWhere += string.Format(@" And ccp.IsPay = {0} ", dto.IsPaySign);
- }
- string sql = string.Format(@"Select atr.*,ccp.IsAuditGM,sd1.Name As CTypeName,sd2.Name As PreCurrencyStr,sd3.Name As CurrencyStr,ccp.IsPay
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On atr.Id = ccp.CId And atr.DIId = ccp.DIId And ccp.IsDel = 0
- Left Join Sys_SetData sd1 On sd1.Id = atr.ctype
- Left Join Sys_SetData sd2 On sd2.Id = atr.PreCurrency
- Left Join Sys_SetData sd3 On sd3.Id = atr.Currency
- Where atr.IsDel = 0 And atr.DIId={0} {1}
- Order By atr.FlightsDate Asc", dto.DiId, sqlWhere);
- List<AirTicketReservationsView> _AirTicketReservations = _sqlSugar.SqlQueryable<AirTicketReservationsView>(sql).ToList();
- foreach (var item in _AirTicketReservations)
- {
- if (item.FlightsDescription.Contains("\n"))
- {
- var spilitArr = Regex.Split(item.FlightsDescription, "\n");
- int rowindex = 1;
- foreach (var spilitItem in spilitArr)
- {
- try
- {
- var spDotandEmpty = spilitItem.Split('.')[1].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
- var depCode = spDotandEmpty[3].Substring(0, 3);
- var arrCode = spDotandEmpty[3].Substring(3, 3);
- Res_ThreeCode depData = _sqlSugar.Queryable<Res_ThreeCode>().First(it => it.IsDel == 0 && it.Three == depCode);
- Res_ThreeCode arrData = _sqlSugar.Queryable<Res_ThreeCode>().First(it => it.IsDel == 0 && it.Three == arrCode);
- string day = spDotandEmpty[2].Substring(2, 2);//日
- string monthAbbreviations = spDotandEmpty[2].Substring(4, 3).ToUpper();//月份
- switch (monthAbbreviations)
- {
- case "JAN":
- monthAbbreviations = "1";
- break;
- case "FEB":
- monthAbbreviations = "2";
- break;
- case "MAR":
- monthAbbreviations = "3";
- break;
- case "APR":
- monthAbbreviations = "4";
- break;
- case "MAY":
- monthAbbreviations = "5";
- break;
- case "JUN":
- monthAbbreviations = "6";
- break;
- case "JUL":
- monthAbbreviations = "7";
- break;
- case "AUG":
- monthAbbreviations = "8";
- break;
- case "SEP":
- monthAbbreviations = "9";
- break;
- case "OCT":
- monthAbbreviations = "10";
- break;
- case "NOV":
- monthAbbreviations = "11";
- break;
- case "DEC":
- monthAbbreviations = "12";
- break;
- }
- string tate = $"{monthAbbreviations}月{day}日";
- item.FlightDescription += rowindex + ". " + depData.AirPort + " " + arrData.AirPort + " (" + tate + ")\r\n";
- }
- catch (Exception ex)
- {
- item.FlightDescription = "录入数据不规范!请检查";
- break;
- }
- rowindex++;
- }
- }
- else
- {
- try
- {
- var spDotandEmpty = item.FlightsDescription.Split('.')[1].Split(' ').Where(x => !string.IsNullOrEmpty(x)).ToList();
- var depCode = spDotandEmpty[3].Substring(0, 3);
- var arrCode = spDotandEmpty[3].Substring(3, 3);
- Res_ThreeCode depData = _sqlSugar.Queryable<Res_ThreeCode>().First(it => it.IsDel == 0 && it.Three == depCode);
- Res_ThreeCode arrData = _sqlSugar.Queryable<Res_ThreeCode>().First(it => it.IsDel == 0 && it.Three == arrCode);
- string day = spDotandEmpty[2].Substring(2, 2);//日
- string monthAbbreviations = spDotandEmpty[2].Substring(4, 3).ToUpper();//月份
- switch (monthAbbreviations)
- {
- case "JAN":
- monthAbbreviations = "1";
- break;
- case "FEB":
- monthAbbreviations = "2";
- break;
- case "MAR":
- monthAbbreviations = "3";
- break;
- case "APR":
- monthAbbreviations = "4";
- break;
- case "MAY":
- monthAbbreviations = "5";
- break;
- case "JUN":
- monthAbbreviations = "6";
- break;
- case "JUL":
- monthAbbreviations = "7";
- break;
- case "AUG":
- monthAbbreviations = "8";
- break;
- case "SEP":
- monthAbbreviations = "9";
- break;
- case "OCT":
- monthAbbreviations = "10";
- break;
- case "NOV":
- monthAbbreviations = "11";
- break;
- case "DEC":
- monthAbbreviations = "12";
- break;
- }
- string tate = $"{monthAbbreviations}月{day}日";
- item.FlightDescription += depData.AirPort + " " + arrData.AirPort + " (" + tate + ")\r\n";
- }
- catch (Exception)
- {
- item.FlightDescription = "录入数据不规范!请检查";
- }
- }
- }
- //团组成本预算表查询
- Grp_GroupCostParameter _GroupCostParameter = _sqlSugar.Queryable<Grp_GroupCostParameter>().First(a => a.DiId == dto.DiId && a.IsDel == 0 && a.CostType == "A" && a.IsShare == 1);
- AirGroupCostParameterView _AirgroupCostParameter = _mapper.Map<AirGroupCostParameterView>(_GroupCostParameter);
- for (int i = 0; i < _AirTicketReservations.Count; i++)
- {
- string[] ClientArr = _AirTicketReservations[i].ClientName.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
- foreach (var item in ClientArr)
- {
- bool isNumeric = int.TryParse(item, out _);
- if (isNumeric)
- {
- if (item == "-1")
- {
- _AirTicketReservations[i].ClientNameStr += "行程单,";
- }
- else
- {
- Crm_DeleClient DeleClient = _sqlSugar.Queryable<Crm_DeleClient>().Where(a => a.IsDel == 0 && a.Id == int.Parse(item)).First();
- EncryptionProcessor.DecryptProperties(DeleClient);
- _AirTicketReservations[i].ClientNameStr += DeleClient.Pinyin + ',';
- }
- }
- else
- {
- _AirTicketReservations[i].ClientNameStr += item;
- }
- }
- if (_AirTicketReservations[i].ClientNameStr is not null)
- {
- _AirTicketReservations[i].ClientNameStr = _AirTicketReservations[i].ClientNameStr.Substring(0, _AirTicketReservations[i].ClientNameStr.Length - 1);
- }
- }
- if (dto.PortType == 1)
- {
- var data = new
- {
- DelegationInfo = _DelegationInfo,
- AirTicketReservations = _AirTicketReservations,
- AirGroupCostParameter = _AirgroupCostParameter
- };
- return result = new Result() { Code = 0, Msg = "查询成功!", Data = data };
- }
- else if (dto.PortType == 2 || dto.PortType == 3)
- {
- int count = _AirTicketReservations.Count;
- float totalPage = (float)count / dto.PageSize;//总页数
- if (totalPage == 0) totalPage = 1;
- else totalPage = (int)Math.Ceiling((double)totalPage);
- var grp_AirTickets = new List<AirTicketReservationsView>();
- for (int i = 0; i < dto.PageSize; i++)
- {
- var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
- if (RowIndex < _AirTicketReservations.Count)
- {
- grp_AirTickets.Add(_AirTicketReservations[RowIndex]);
- }
- else
- {
- break;
- }
- }
- var rst = new ListViewBase<AirTicketReservationsView>
- {
- DataList = grp_AirTickets,
- DataCount = count,
- CurrPageIndex = dto.PageIndex,
- CurrPageSize = dto.PageSize
- };
- var data = new
- {
- AirData = rst,
- AirGroupCostParameter = _AirgroupCostParameter
- };
- return new Result() { Code = 0, Msg = "查询成功!", Data = data };
- }
- else
- {
- return new Result() { Code = -1, Msg = "请传入PortType参数!1:Web,2:Android,3:IOS!" };
- }
- }
- else
- {
- return new Result() { Code = -1, Msg = "暂无团组数据!" };
- }
- }
- public async Task<Result> AirTicketResSelect(AirTicketResDto dto)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- try
- {
- if (dto.DiId < 1)
- {
- dto.DiId = -1;
- }
- #region 团组下拉框
- List<Grp_GroupsTaskAssignment> grp_GroupsTaskAssignment = Query<Grp_GroupsTaskAssignment>(a => a.IsDel == 0 && a.UId == dto.UserId && a.CTId == 85).ToList();
- var grp_NameView = new List<dynamic>();
- string DiId = "";
- foreach (var item in grp_GroupsTaskAssignment)
- {
- DiId += item.DIId + ",";
- }
- if (DiId.Length > 1)
- {
- DiId = DiId.Substring(0, DiId.Length - 1);
- string sql = string.Format(@"select * from Grp_DelegationInfo where Id in({0}) and IsDel={1} Order By VisitStartDate Desc", DiId, 0);
- List<Grp_DelegationInfo> grp_Delegations = _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToList();
- if (grp_Delegations.Count == 0)
- {
- return result = new Result() { Code = -1, Msg = "查询失败!" };
- }
- foreach (var item in grp_Delegations)
- {
- var groupNameView = new
- {
- item.Id,
- item.TeamName
- };
- grp_NameView.Add(groupNameView);
- }
- }
- #endregion
- #region 其他下拉框查询
- //舱位类型
- List<Sys_SetData> TicketClass = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 44 && a.IsDel == 0).ToList();
- List<SetDataInfoView> _TicketClassa = _mapper.Map<List<SetDataInfoView>>(TicketClass);
- //支付方式
- List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
- List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);
- //卡类型
- List<Sys_SetData> CardType = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 15 && a.IsDel == 0).ToList();
- List<SetDataInfoView> _CardType = _mapper.Map<List<SetDataInfoView>>(CardType);
- //合作方资料
- List<Res_AirTicketAgent> _AirTicketAgents = _sqlSugar.Queryable<Res_AirTicketAgent>().Where(a => a.IsDel == 0).ToList();
- foreach (var item in _AirTicketAgents)
- {
- EncryptionProcessor.DecryptProperties(item);
- }
- #endregion
- #region 客人名单下拉框
- if (dto.DiId == -1)
- {
- var dele = _AirTicketAgents.FirstOrDefault();
- dto.DiId = dele != null ? dele.Id : dto.DiId;
- }
- string sqlClient = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", dto.DiId);
- var clientArr = _sqlSugar.SqlQueryable<SimplClientInfo>(sqlClient).ToList();
- foreach (var item in clientArr) { EncryptionProcessor.DecryptProperties(item); }
- #endregion
- var data = new
- {
- TicketClass = _TicketClassa,
- Payment = _Payment,
- CardType = _CardType,
- GroupName = grp_NameView,
- AirTicketAgents = _AirTicketAgents,
- clientArr
- };
- return result = new Result() { Code = 0, Msg = "查询成功!", Data = data };
- }
- catch (Exception ex)
- {
- return result = new Result() { Code = -2, Msg = "程序错误" };
- }
- }
- public async Task<Result> OpAirTicketRes(AirTicketResOpDto dto, Func<int, int, int, Task<Result>> fn)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- try
- {
- BeginTran();
- int id = 0;
- var grp_AirTicket = _mapper.Map<Grp_AirTicketReservations>(dto.AirTicketResOpData);
- var clientName = string.Join(",", dto.AirTicketResOpData.ClientName);
- if (dto.Status == 1)
- {
- grp_AirTicket.FlightsDate = DateTime.Parse(grp_AirTicket.FlightsDate).ToString("yyyy-MM-dd");
- grp_AirTicket.ClientName = clientName;
- id = await AddAsyncReturnId(grp_AirTicket);
- if (id == 0)
- {
- result = new Result() { Code = -1, Msg = "添加失败!" };
- }
- else
- {
- result = new Result() { Code = 0, Msg = "添加成功!" };
- }
- // }
- if (result.Code == 0)
- {
- Grp_CreditCardPayment grp_CreditCard = _mapper.Map<Grp_CreditCardPayment>(dto.CardPaymentOpData);
- // 2025-04-07 第四次更改 PayDId == 72(刷卡) IsPay == 1
- if (grp_CreditCard.PayDId == 72) grp_CreditCard.IsPay = 1;
- else grp_CreditCard.IsPay = 0;
- //获取新汇率 int diId,int CId, int currencyId
- var rate = await fn(dto.AirTicketResOpData.DiId, 85, dto.AirTicketResOpData.Currency);
- if (rate.Code == 0)
- {
- var rateInfo = (rate.Data as CurrencyInfo);
- if (rateInfo is not null)
- {
- grp_CreditCard.DayRate = rateInfo.Rate;
- grp_CreditCard.RMBPrice = rateInfo.Rate * grp_CreditCard.PayMoney;
- }
- else
- {
- grp_CreditCard.DayRate = 1;
- grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- }
- }
- //换算
- #region 老汇率处理方式
- //Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == grp_AirTicket.DIId && a.IsDel == 0 && a.CTable == 85);
- //if (_TeamRate != null)
- //{
- // if (grp_CreditCard.PaymentCurrency == 49)
- // {
- // grp_CreditCard.DayRate = _TeamRate.RateU;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney * Convert.ToDecimal(_TeamRate.RateU);
- // //ccp.PayMoney = ccp.PayMoney * float.Parse(tr.RateU);
- // }
- // else if (grp_CreditCard.PaymentCurrency == 51)
- // {
- // grp_CreditCard.DayRate = _TeamRate.RateE;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney * Convert.ToDecimal(_TeamRate.RateE);
- // //ccp.PayMoney = ccp.PayMoney * float.Parse(tr.RateE);
- // }
- // else
- // {
- // grp_CreditCard.DayRate = 1M;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- // }
- //}
- //else
- //{
- // grp_CreditCard.DayRate = 1M;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- //}
- #endregion
- //判断是否超出成本
- #region 自动审核(暂时屏蔽)
- //Grp_GroupCostParameter _GroupCostParameter = _sqlSugar.Queryable<Grp_GroupCostParameter>().First(a => a.DiId == grp_AirTicket.DIId && a.IsDel == 0);
- //if (grp_AirTicket.CType == 460)//经济舱
- //{
- // if (_GroupCostParameter != null)
- // {
- // if (Convert.ToDecimal(_GroupCostParameter.JJCCB) * Convert.ToDecimal(grp_AirTicket.ClientNum) > grp_CreditCard.RMBPrice)
- // {
- // grp_CreditCard.ExceedBudget = 0;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 3;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 0;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- // else
- // {
- // var a = grp_CreditCard.RMBPrice - Convert.ToDecimal(_GroupCostParameter.JJCCB);
- // var b = a / Convert.ToDecimal(_GroupCostParameter.JJCCB) * Convert.ToDecimal(grp_AirTicket.ClientNum);
- // grp_CreditCard.ExceedBudget = b;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- // }
- // else
- // {
- // grp_CreditCard.ExceedBudget = 0.00M;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 0;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- //}
- //else if (grp_AirTicket.CType == 458)
- //{
- // if (_GroupCostParameter != null)
- // {
- // if (Convert.ToDecimal(_GroupCostParameter.GWCB) * Convert.ToDecimal(grp_AirTicket.ClientNum) > grp_CreditCard.RMBPrice)
- // {
- // grp_CreditCard.ExceedBudget = 0;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 3;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- // else
- // {
- // var a = grp_CreditCard.RMBPrice - Convert.ToDecimal(_GroupCostParameter.GWCB);
- // var b = a / Convert.ToDecimal(_GroupCostParameter.GWCB) * Convert.ToDecimal(grp_AirTicket.ClientNum);
- // grp_CreditCard.ExceedBudget = b;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- // }
- // else
- // {
- // grp_CreditCard.ExceedBudget = 0.00M;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- //}
- //else
- //{
- // grp_CreditCard.ExceedBudget = 0.00M;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 0;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- //}
- #endregion
- grp_CreditCard.CId = id;
- grp_CreditCard.CTable = 85;
- grp_CreditCard.PayPercentage = 100;
- #region 查询上一次付款(注释)
- ////查询上一次付款信息
- //Grp_CreditCardPayment _CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment>().OrderByDescending(x => x.CreateUserId).First(a => a.DIId == grp_AirTicket.DIId && a.IsDel == 0 && a.IsPay == 1);
- //if (_CreditCardPayment != null)
- //{
- // grp_CreditCard.PayPercentageOld = _CreditCardPayment.PayPercentageOld;// 上次付款百分比 查询并计算最近一次
- // grp_CreditCard.PayThenMoneyOld = _CreditCardPayment.PayMoney;// 上次付款金额 查询上一次
- // grp_CreditCard.UpdateDate = _CreditCardPayment.UpdateDate;// 上次付款时间 查询上一次
- //}
- //else
- //{
- // grp_CreditCard.PayPercentageOld = 0;// 上次付款百分比 查询并计算最近一次
- // grp_CreditCard.PayThenMoneyOld = 0;// 上次付款金额 查询上一次
- // grp_CreditCard.UpdateDate = "";// 上次付款时间 查询上一次
- //}
- #endregion
- id = await _sqlSugar.Insertable(grp_CreditCard).ExecuteReturnIdentityAsync();
- if (id == 0)
- {
- RollbackTran();
- return result = new Result() { Code = -1, Msg = "添加失败!" };
- }
- await UpdateAsync(a => a.Id == id, a => new Grp_AirTicketReservations
- {
- FlightsDescription = dto.AirTicketResOpData.FlightsDescription,
- });
- CommitTran();
- var data = new { ccpId = id, sign = 1, dataId = grp_CreditCard.CId };
- return result = new Result() { Code = 0, Msg = "添加成功!", Data = data };
- }
- else
- {
- RollbackTran();
- return result = new Result() { Code = -1, Msg = "添加失败!" };
- }
- }
- else if (dto.Status == 2)
- {
- id = dto.AirTicketResOpData.Id;
- bool res = await UpdateAsync(a => a.Id == dto.AirTicketResOpData.Id, a => new Grp_AirTicketReservations
- {
- CType = dto.AirTicketResOpData.CType,
- PrePrice = dto.AirTicketResOpData.PrePrice,
- PreCurrency = dto.AirTicketResOpData.PreCurrency,
- Price = dto.AirTicketResOpData.Price,
- Currency = dto.AirTicketResOpData.Currency,
- ClientNum = dto.AirTicketResOpData.ClientNum,
- ClientName = clientName,
- IsCheckIn = dto.AirTicketResOpData.IsCheckIn,
- IsSetSeat = dto.AirTicketResOpData.IsSetSeat,
- IsPackage = dto.AirTicketResOpData.IsPackage,
- IsBagHandle = dto.AirTicketResOpData.IsBagHandle,
- IsTrain = dto.AirTicketResOpData.IsTrain,
- FlightsCode = dto.AirTicketResOpData.FlightsCode,
- FlightsCity = dto.AirTicketResOpData.FlightsCity,
- FlightsDescription = dto.AirTicketResOpData.FlightsDescription,
- PriceDescription = dto.AirTicketResOpData.PriceDescription,
- TicketNumber = dto.AirTicketResOpData.TicketNumber,
- TicketCode = dto.AirTicketResOpData.TicketCode,
- Remark = dto.AirTicketResOpData.Remark,
- });
- if (!res) { result = new Result() { Code = -1, Msg = "修改失败!" }; }
- else { result = new Result() { Code = 0, Msg = "修改成功!" }; }
- if (result.Code == 0)
- {
- //C表操作
- Grp_CreditCardPayment grp_CreditCard = _mapper.Map<Grp_CreditCardPayment>(dto.CardPaymentOpData);
- //2025-04-07 第四次更改 PayDId == 72(刷卡) IsPay == 1
- if (grp_CreditCard.PayDId == 72) grp_CreditCard.IsPay = 1;
- else grp_CreditCard.IsPay = 0;
- //获取新汇率 int diId,int CId, int currencyId
- var rate = await fn(dto.AirTicketResOpData.DiId, 85, dto.AirTicketResOpData.Currency);
- if (rate.Code == 0)
- {
- var rateInfo = (rate.Data as CurrencyInfo);
- if (rateInfo is not null)
- {
- grp_CreditCard.DayRate = rateInfo.Rate;
- grp_CreditCard.RMBPrice = rateInfo.Rate * grp_CreditCard.PayMoney;
- }
- else
- {
- grp_CreditCard.DayRate = 1;
- grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- }
- }
- #region 老汇率修改(注释)
- //换算
- Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == grp_AirTicket.DIId && a.IsDel == 0 && a.CTable == 85);
- //if (_TeamRate != null)
- //{
- // if (grp_CreditCard.PaymentCurrency == 49)
- // {
- // grp_CreditCard.DayRate = _TeamRate.RateU;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney * Convert.ToDecimal(_TeamRate.RateU);
- // //ccp.PayMoney = ccp.PayMoney * float.Parse(tr.RateU);
- // }
- // else if (grp_CreditCard.PaymentCurrency == 51)
- // {
- // grp_CreditCard.DayRate = _TeamRate.RateE;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney * Convert.ToDecimal(_TeamRate.RateE);
- // //ccp.PayMoney = ccp.PayMoney * float.Parse(tr.RateE);
- // }
- // else
- // {
- // grp_CreditCard.DayRate = 1M;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- // }
- //}
- //else
- //{
- // grp_CreditCard.DayRate = 1M;
- // grp_CreditCard.RMBPrice = grp_CreditCard.PayMoney;
- //}
- #endregion
- #region 自动审核(注释)
- //Grp_GroupCostParameter _GroupCostParameter = _sqlSugar.Queryable<Grp_GroupCostParameter>().First(a => a.DiId == grp_AirTicket.DIId && a.IsDel == 0);
- //if (grp_AirTicket.CType == 460)//经济舱
- //{
- // if (_GroupCostParameter != null)
- // {
- // if (Convert.ToDecimal(_GroupCostParameter.JJCCB) * Convert.ToDecimal(grp_AirTicket.ClientNum) > grp_CreditCard.RMBPrice)
- // {
- // grp_CreditCard.ExceedBudget = 0;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 3;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 0;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 1;
- // }
- // else
- // {
- // var a = grp_CreditCard.RMBPrice - Convert.ToDecimal(_GroupCostParameter.JJCCB);
- // var b = a / Convert.ToDecimal(_GroupCostParameter.JJCCB) * Convert.ToDecimal(grp_AirTicket.ClientNum);
- // grp_CreditCard.ExceedBudget = b;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 1;
- // }
- // }
- // else
- // {
- // grp_CreditCard.ExceedBudget = 0.00M;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- //}
- //else if (grp_AirTicket.CType == 458)
- //{
- // if (_GroupCostParameter != null)
- // {
- // if ((_GroupCostParameter != null ? _GroupCostParameter.GWCB : 0) * Convert.ToDecimal(grp_AirTicket.ClientNum) > grp_CreditCard.RMBPrice)
- // {
- // grp_CreditCard.ExceedBudget = 0;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 3;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 1;
- // }
- // else
- // {
- // var a = grp_CreditCard.RMBPrice - Convert.ToDecimal(_GroupCostParameter.GWCB);
- // var b = a / Convert.ToDecimal(_GroupCostParameter.GWCB) * Convert.ToDecimal(grp_AirTicket.ClientNum);
- // grp_CreditCard.ExceedBudget = b;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 1;
- // }
- // }
- // else
- // {
- // grp_CreditCard.ExceedBudget = 0.00M;// 超出预算比例 换算
- // grp_CreditCard.IsAuditGM = 0;//3 为自动审核
- // grp_CreditCard.AuditGMOperate = 21;
- // grp_CreditCard.AuditGMDate = "";
- // grp_CreditCard.IsPay = 0;
- // }
- //}
- #endregion
- grp_CreditCard.CId = id;
- grp_CreditCard.CTable = 85;
- grp_CreditCard.PayPercentage = 100;
- #region 查询上一次付款信息(注释)
- ////查询上一次付款信息
- //Grp_CreditCardPayment _CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment>().OrderByDescending(x => x.CreateUserId).First(a => a.DIId == grp_AirTicket.DIId && a.IsDel == 0 && a.IsPay == 1);
- //if (_CreditCardPayment != null)
- //{
- // grp_CreditCard.PayPercentageOld = _CreditCardPayment.PayPercentageOld;// 上次付款百分比 查询并计算最近一次
- // grp_CreditCard.PayThenMoneyOld = _CreditCardPayment.PayMoney;// 上次付款金额 查询上一次
- // grp_CreditCard.UpdateDate = _CreditCardPayment.UpdateDate;// 上次付款时间 查询上一次
- //}
- //else
- //{
- // grp_CreditCard.PayPercentageOld = 0;// 上次付款百分比 查询并计算最近一次
- // grp_CreditCard.PayThenMoneyOld = 0;// 上次付款金额 查询上一次
- // grp_CreditCard.UpdateDate = "";// 上次付款时间 查询上一次
- //}
- #endregion
- int CTable = await _sqlSugar.Updateable<Grp_CreditCardPayment>().Where(a => a.Id == dto.CardPaymentOpData.Id).SetColumns(a => new Grp_CreditCardPayment
- {
- PayDId = grp_CreditCard.PayDId,
- ConsumptionPatterns = grp_CreditCard.ConsumptionPatterns,
- ConsumptionDate = grp_CreditCard.ConsumptionDate,
- CTDId = grp_CreditCard.CTDId,
- BankNo = grp_CreditCard.BankNo,
- CardholderName = grp_CreditCard.CardholderName,
- PayMoney = grp_CreditCard.PayMoney,
- PaymentCurrency = grp_CreditCard.PaymentCurrency,
- DayRate = grp_CreditCard.DayRate,
- CompanyBankNo = grp_CreditCard.CompanyBankNo,
- OtherBankName = grp_CreditCard.OtherBankName,
- OtherSideNo = grp_CreditCard.OtherSideNo,
- OtherSideName = grp_CreditCard.OtherSideName,
- IsAuditGM = grp_CreditCard.IsAuditGM,
- AuditGMOperate = grp_CreditCard.AuditGMOperate,
- AuditGMDate = grp_CreditCard.AuditGMDate,
- IsPay = grp_CreditCard.IsPay,
- PayPercentage = grp_CreditCard.PayPercentage,
- PayThenMoney = grp_CreditCard.PayThenMoney,
- PayPercentageOld = grp_CreditCard.PayPercentageOld,
- PayThenMoneyOld = grp_CreditCard.PayThenMoneyOld,
- UpdateDate = grp_CreditCard.UpdateDate,
- Payee = grp_CreditCard.Payee,
- RMBPrice = grp_CreditCard.RMBPrice,
- OrbitalPrivateTransfer = grp_CreditCard.OrbitalPrivateTransfer,
- ExceedBudget = grp_CreditCard.ExceedBudget,
- Remark = grp_CreditCard.Remark,
- }).ExecuteCommandAsync();
- if (CTable == 0)
- {
- RollbackTran();
- return result = new Result() { Code = -1, Msg = "修改失败!" };
- }
- else
- {
- Grp_CreditCardPayment ccp = Query<Grp_CreditCardPayment>(a => a.Id == dto.CardPaymentOpData.Id).First();
- var data = new { ccpId = ccp.Id, sign = 2, dataId = grp_CreditCard.CId };
- result = new Result() { Code = 0, Msg = "修改成功!", Data = data };
- }
- }
- else
- {
- result = new Result() { Code = -1, Msg = "修改失败!" };
- RollbackTran();
- }
- }
- CommitTran();
- }
- catch (Exception ex)
- {
- RollbackTran();
- return result = new Result() { Code = -2, Msg = "程序错误" };
- throw;
- }
- return result;
- }
- /// <summary>
- /// 导出机票费用报表
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public async Task<Result> DeriveAirTicketRes(AirTicketResDto dto)
- {
- var result = new Result() { Code = -2, Msg = "未知错误" };
- try
- {
- string sql = string.Format(@"Select atr.*,ccp.Payee,ccp.BankNo, sd4.Name as PayType ,ccp.IsAuditGM,sd1.Name As 'CTypeName',sd2.Name As 'PreCurrencyStr',sd3.Name As CurrencyStr
- From Grp_AirTicketReservations atr
- Left Join Grp_CreditCardPayment ccp On atr.Id = ccp.CId And atr.DIId = ccp.DIId And ccp.IsDel = 0
- Left Join Sys_SetData sd1 On sd1.Id = atr.ctype
- Left Join Sys_SetData sd2 On sd2.Id = atr.PreCurrency
- Left Join Sys_SetData sd3 On sd3.Id = atr.Currency
- left join Sys_SetData sd4 On sd4.Id = ccp.PayDId
- Where atr.IsDel = 0 And atr.DIId={0}
- Order By atr.FlightsDate Asc", dto.DiId);
- List<AirTicketReservationsPayView> _AirTicketReservations = _sqlSugar.SqlQueryable<AirTicketReservationsPayView>(sql).ToList();
- if (_AirTicketReservations.Count != 0)
- {
- Grp_DelegationInfo grp_Delegation = _sqlSugar.Queryable<Grp_DelegationInfo>().First(a => a.Id == dto.DiId && a.IsDel == 0);
- Sys_Users _Users = _sqlSugar.Queryable<Sys_Users>().First(a => a.Id == dto.UserId && a.IsDel == 0);
- return result = new Result() { Code = 0, Msg = "成功", Data = new { Delegation = grp_Delegation, AirTicketRes = _AirTicketReservations, Users = _Users } };
- }
- else
- {
- return result = new Result() { Code = -1, Msg = "暂无数据", Data = null };
- }
- }
- catch (Exception)
- {
- return result = new Result() { Code = -2, Msg = "未知错误" };
- }
- }
- public async Task<Result> ItineraryAirTicketRes(ItineraryAirTicketResDto dto)
- {
- try
- {
- string sql = string.Format(@"select a.*,c.IsAuditGM,(select Name from Sys_SetData where Id=a.cType) as 'CTypeName',(select Name from
- Sys_SetData where Id=a.PreCurrency) as 'PreCurrencyStr',(select Name from Sys_SetData where Id=a.Currency)
- as 'CurrencyStr' from Grp_AirTicketReservations a,Grp_CreditCardPayment c where a.id=c.CId and a.isdel={1}
- and a.DIId={0} Order By a.CreateTime desc", dto.DiId, 0);
- List<AirTicketReservationsView> _AirTicketReservations = _sqlSugar.SqlQueryable<AirTicketReservationsView>(sql).ToList();
- if (_AirTicketReservations.Count == 0)
- {
- return new Result() { Code = -1, Msg = "暂无数据", Data = null };
- }
- else
- {
- return new Result() { Code = 0, Msg = "查询成功", Data = _AirTicketReservations };
- }
- }
- catch (Exception)
- {
- return new Result() { Code = -2, Msg = "未知错误" };
- }
- }
- public async Task<List<TranslateResult>> ReTransBatch(List<string> list, string aimlanguage)
- {
- var reultStr = new List<TranslateResult>();
- if (list.Count < 0)
- {
- return reultStr;
- }
- //待翻译内容,必须是UTF-8编码
- string q = "";
- string Qtext = "";
- foreach (var item in list)
- {
- q += item;
- Qtext += "q=" + item + "&";
- }
- if (Qtext.Length > 0)
- {
- Qtext = Qtext[..^1];
- }
- var dic = new Dictionary<string, string>();
- string url = "https://openapi.youdao.com/v2/api";
- //应用ID
- string appKey = "0fe3bc01e109ed36";
- //应用应用密钥
- string appSecret = "1f2x9TrqJfSBEJ8iH9GEFGgTyaYGjEry";
- //UUID
- string salt = DateTime.Now.Millisecond.ToString();
- //源语言
- dic.Add("from", "zh-CHS");
- //目标语言
- dic.Add("to", aimlanguage);
- //签名类型
- dic.Add("signType", "v3");
- //时间戳
- string curtime = ((GetBeijingTime().ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
- dic.Add("curtime", curtime);
- string signStr = appKey + Truncate(q) + salt + curtime + appSecret; ;
- string sign = ComputeHash(signStr, SHA256.Create());
- dic.Add("q", Qtext);
- dic.Add("appKey", appKey);
- dic.Add("salt", salt);
- dic.Add("sign", sign);
- try
- {
- //Thread.Sleep(500);
- string jsonStr = await TransSync(url, dic);
- JObject trans = (JObject)JsonConvert.DeserializeObject(jsonStr);
- string errorCode = trans["errorCode"].ToString();
- if (errorCode == "0")
- {
- reultStr = JsonConvert.DeserializeObject<List<TranslateResult>>(trans["translateResults"].ToString());
- }
- return reultStr;
- }
- catch (Exception)
- {
- return reultStr;
- }
- }
- public string Processing(string str)//处理这段英文的方法
- {
- if (string.IsNullOrEmpty(str)) { return ""; }
- string[] strArray;
- if (str.Contains(" ")) strArray = str.Split(" ".ToCharArray());
- else if (str.Contains(",")) strArray = str.Split(",".ToCharArray());
- else if (str.Contains(" ") && str.Contains(",")) strArray = str.Split(",".ToCharArray());
- else strArray = new string[] { str };
- string result = string.Empty;//定义一个空字符串
- foreach (string s in strArray)//循环处理数组里面每一个字符串
- {
- //result += System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s) + " ";
- result += string.Concat(s[..1].ToUpper(), s.AsSpan(1), " ");
- //.Substring(0, 1).ToUpper()把循环到的字符串第一个字母截取并转换为大写,并用s.Substring(1)得到循环到的字符串除第一个字符后的所有字符拼装到首字母后面。
- }
- return result;
- }
- protected static async Task<string> TransSync(string url, Dictionary<string, string> dic)
- {
- string result = "";
- using (var client = new HttpClient())
- {
- var content = new FormUrlEncodedContent(dic);
- HttpResponseMessage response = await client.PostAsync(url, content);
- response.EnsureSuccessStatusCode();
- if (response.Content.Headers.ContentType.MediaType.ToLower().Equals("audio/mp3"))
- {
- await SaveBinaryFile(response, "合成的音频存储路径");
- }
- else
- {
- result = await response.Content.ReadAsStringAsync();
- }
- }
- return result;
- }
- private static async Task<bool> SaveBinaryFile(HttpResponseMessage response, string FileName)
- {
- string FilePath = FileName + DateTime.Now.Millisecond.ToString() + ".mp3";
- bool Value = true;
- byte[] buffer = new byte[1024];
- try
- {
- if (File.Exists(FilePath))
- File.Delete(FilePath);
- using Stream outStream = File.Create(FilePath);
- using Stream inStream = await response.Content.ReadAsStreamAsync();
- int l;
- do
- {
- l = await inStream.ReadAsync(buffer);
- if (l > 0)
- await outStream.WriteAsync(buffer.AsMemory(0, l));
- }
- while (l > 0);
- }
- catch
- {
- Value = false;
- }
- return Value;
- }
- protected static string ComputeHash(string input, HashAlgorithm algorithm)
- {
- byte[] inputBytes = Encoding.UTF8.GetBytes(input);
- byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
- return BitConverter.ToString(hashedBytes).Replace("-", "");
- }
- protected static string Truncate(string q)
- {
- if (q == null)
- {
- return null;
- }
- int len = q.Length;
- return len <= 20 ? q : q.Substring(0, 10) + len + q.Substring(len - 10, 10);
- }
- public static DateTime GetBeijingTime()
- {
- string datetime = string.Empty;
- try
- {
- using (var client = new HttpClient())
- {
- client.Timeout = TimeSpan.FromSeconds(3);
- HttpResponseMessage response = client.GetAsync("https://www.baidu.com").Result;
- response.EnsureSuccessStatusCode();
- datetime = response.Headers.Date?.ToString() ?? DateTime.Now.ToString();
- }
- return Convert.ToDateTime(datetime);
- }
- catch (Exception)
- {
- return DateTime.Now;
- }
- }
- public class TranslateResult
- {
- public string Query { get; set; }
- public string Translation { get; set; }
- public string Type { get; set; }
- public string VerifyResult { get; set; }
- }
- #endregion
- #region 2026版
- /// <summary>
- /// list 2026版
- /// </summary>
- /// <param name="dto">查询参数</param>
- /// <returns>机票费用列表</returns>
- public async Task<JsonView> ListAsync(AirTicketFeeListDto dto)
- {
- // 1. 参数校验
- if (!SharingStaticData.PortTypes.Contains(dto.PortType))
- return JsonView.Fail(MsgTips.Port);
- if (dto.DiId <= 0)
- return JsonView.Fail("团组ID无效");
- // 2. 获取团组信息
- var groupInfo = await _groupInfoRep.GetGroupAirInfo(dto.DiId);
- if (groupInfo == null)
- return JsonView.Fail("暂无团组数据!");
- // 3. 查询机票费用列表
- var airTicketFeeList = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .InnerJoin<Grp_CreditCardPayment>((x, y) => x.Id == y.CId && x.DIId == y.DIId)
- .LeftJoin<Sys_SetData>((x, y, z) => x.CType == z.Id)
- .LeftJoin<Sys_SetData>((x, y, z, z1) => x.Currency == z1.Id)
- .LeftJoin<Sys_Users>((x, y, z, z1, u) => x.CreateUserId == u.Id)
- .Where((x, y, z, z1, u) => x.IsDel == 0 && y.IsDel == 0 && x.DIId == dto.DiId)
- .WhereIF(dto.IsPaySign != -1, (x, y, z, z1, u) => y.IsPay == dto.IsPaySign)
- .Select((x, y, z, z1, u) => new AirTicketFeeListView()
- {
- Id = x.Id,
- No = x.RecordType,
- CabinName = z.Name,
- FlightDesc = x.FlightsDescription,
- ClientNameList = x.ClientName,
- ClientCount = x.ClientNum,
- TotalTicketPrice = x.Price,
- Currency = z1.Name,
- AuditStatus = y.IsAuditGM.ToString(),
- Remark = y.Remark,
- Applicant = u.CnName,
- ApplyTime = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
- })
- .ToListAsync();
- // 4. 获取黑屏代码(三字码映射)
- var threeCodeList = await _sqlSugar.Queryable<Res_ThreeCode>()
- .Where(x => x.IsDel == 0)
- .Select(x => new { x.Three, x.AirPort })
- .ToListAsync();
- // 保留第一个遇到的
- var threeCodes = threeCodeList
- .GroupBy(x => x.Three)
- .ToDictionary(g => g.Key, g => g.First().AirPort);
- // 5. 获取团组成本预算
- var groupCostParameter = await _sqlSugar.Queryable<Grp_GroupCostParameter>()
- .FirstAsync(a => a.DiId == dto.DiId && a.IsDel == 0 && a.CostType == "A" && a.IsShare == 1);
- var airgroupCostParameter = _mapper.Map<AirGroupCostParameterView>(groupCostParameter);
- // 6. 获取客户信息映射
- var groupClientIds = await _sqlSugar.Queryable<Grp_TourClientList>()
- .Where(a => a.DiId == dto.DiId && a.IsDel == 0)
- .Select(x => x.ClientId)
- .ToListAsync();
- var clientInfoMap = new Dictionary<int, (string FirstName, string LastName, string Pinyin)>();
- if (groupClientIds.Any())
- {
- var encryptedClients = await _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(a => a.IsDel == 0 && groupClientIds.Contains(a.Id))
- .Select(x => new { x.Id, x.FirstName, x.LastName, x.Pinyin })
- .ToListAsync();
- foreach (var client in encryptedClients)
- {
- clientInfoMap[client.Id] = (
- AesEncryptionHelper.Decrypt(client.FirstName),
- AesEncryptionHelper.Decrypt(client.LastName),
- AesEncryptionHelper.Decrypt(client.Pinyin)
- );
- }
- }
- // 7. 处理航班描述和客户名称
- foreach (var item in airTicketFeeList)
- {
- // 退票退票标识
- if (item.No == 1)
- {
- item.CabinName += "(退票)";
- }
- // 7.1 处理航班描述
- if (!string.IsNullOrWhiteSpace(item.FlightDesc))
- {
- var flightInfos = FlightParser.ParseFlights(item.FlightDesc);
- var flightDescBuilder = new StringBuilder();
- foreach (var flightInfo in flightInfos)
- {
- string departAirport = threeCodes.ContainsKey(flightInfo.DepartureAirport)
- ? threeCodes[flightInfo.DepartureAirport]?.ToString() ?? flightInfo.DepartureAirport
- : flightInfo.DepartureAirport;
- string arrivalAirport = threeCodes.ContainsKey(flightInfo.ArrivalAirport)
- ? threeCodes[flightInfo.ArrivalAirport]?.ToString() ?? flightInfo.ArrivalAirport
- : flightInfo.ArrivalAirport;
- string desc = $"{flightInfo.SequenceNo}.{departAirport} → {arrivalAirport}({flightInfo.DepartureDate:yyyy-MM-dd})";
- flightDescBuilder.AppendLine(desc);
- }
- item.FlightDesc = flightDescBuilder.ToString().TrimEnd();
- }
- else item.FlightDesc = "录入数据不规范!请检查";
- // 7.2 处理客户名称
- if (!string.IsNullOrWhiteSpace(item.ClientNameList))
- {
- var clientArr = item.ClientNameList.Split(',')
- .Where(x => !string.IsNullOrWhiteSpace(x))
- .ToArray();
- var clientNames = new List<string>();
- foreach (var clientItem in clientArr)
- {
- if (int.TryParse(clientItem, out int clientId))
- {
- if (clientId == -1)
- {
- clientNames.Add("行程单");
- }
- else if (clientInfoMap.TryGetValue(clientId, out var clientInfo))
- {
- clientNames.Add(clientInfo.Pinyin);
- }
- }
- else
- {
- clientNames.Add(clientItem);
- }
- }
- item.ClientNameList = clientNames.Any() ? string.Join(",", clientNames) : string.Empty;
- }
- }
- // 8. 根据端口类型返回数据
- if (dto.PortType == 1)
- {
- var data = new
- {
- DelegationInfo = groupInfo,
- AirTicketReservations = airTicketFeeList,
- AirGroupCostParameter = airgroupCostParameter
- };
- return JsonView.Success(data);
- }
- else if (dto.PortType == 2 || dto.PortType == 3)
- {
- int totalCount = airTicketFeeList.Count;
- int totalPages = (int)Math.Ceiling((double)totalCount / dto.PageSize);
- if (totalPages == 0) totalPages = 1;
- // 分页数据
- var pagedData = airTicketFeeList
- .Skip((dto.PageIndex - 1) * dto.PageSize)
- .Take(dto.PageSize)
- .ToList();
- var rst = new ListViewBase<AirTicketFeeListView>
- {
- DataList = pagedData,
- DataCount = totalCount,
- CurrPageIndex = dto.PageIndex,
- CurrPageSize = dto.PageSize
- };
- var data = new
- {
- AirData = rst,
- AirGroupCostParameter = airgroupCostParameter
- };
- return JsonView.Success(data);
- }
- return JsonView.Fail("暂无团组数据!");
- }
- /// <summary>
- /// 机票费用基础数据 2026版
- /// </summary>
- /// <returns></returns>
- public async Task<JsonView> BasicDataAsync(int userId)
- {
- var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.IsDel == 0).ToList();
- // 附加服务类型
- var additionalServiceTypes = setDatas
- .Where(a => a.STid == 139 && a.IsDel == 0)
- .Select(a => _mapper.Map<SetDataInfoView>(a))
- .OrderBy(x => x.RemarkSort)
- .ToList();
- // 舱位类型
- var ticketClass = setDatas
- .Where(a => a.STid == 44 && a.IsDel == 0)
- .Select(a => _mapper.Map<SetDataInfoView>(a))
- .ToList();
- // 支付方式
- var payments = setDatas
- .Where(a => a.STid == 14 && a.IsDel == 0)
- .Select(a => _mapper.Map<SetDataInfoView>(a))
- .ToList();
- // 卡类型
- var cardTypes = setDatas
- .Where(a => a.STid == 15 && a.IsDel == 0)
- .Select(a => _mapper.Map<SetDataInfoView>(a))
- .ToList();
- // 合作方资料
- var airTicketAgents = _sqlSugar.Queryable<Res_AirTicketAgent>().Where(a => a.IsDel == 0).ToList();
- foreach (var item in airTicketAgents)
- {
- EncryptionProcessor.DecryptProperties(item);
- }
- var airTicketAgentsView = airTicketAgents.Select(x => new
- {
- x.Id,
- x.Name,
- x.Account,
- x.Bank
- }).ToList();
- #region 团组下拉框
- var permGroupIds = Query<Grp_GroupsTaskAssignment>(a => a.IsDel == 0 && a.UId == userId && a.CTId == 85).Select(a => a.DIId).ToList();
- var teamNames = _sqlSugar.Queryable<Grp_DelegationInfo>()
- .Where(x => x.IsDel == 0 && permGroupIds.Contains(x.Id))
- .OrderByDescending(x => x.VisitDate)
- .Select(x => new
- {
- x.Id,
- x.TeamName
- })
- .ToList();
- #endregion
- // 获取第一个团组的基本信息
- var firstGroupInfo = await _groupInfoRep.GetGroupAirInfo(teamNames.FirstOrDefault()?.Id ?? 0);
- return JsonView.Success(new
- {
- additionalServiceTypes,
- ticketClass,
- payment = payments,
- cardType = cardTypes,
- airTicketAgents = airTicketAgentsView,
- firstGroupInfo,
- groupName = teamNames
- });
- }
- /// <summary>
- /// 详情 2026版
- /// </summary>
- /// <returns></returns>
- public async Task<JsonView> InfoAsync(int userId, int groupId)
- {
- var view = new AirTicketFeeInfoView()
- {
- CurrUserId = userId,
- GroupAirInfo = new GroupAirTicketInfo(),
- AirTicketFeeInfos = new List<AirTicketFeeInfo>()
- };
- if (userId < 1) return JsonView.Fail<AirTicketFeeInfoView>("用户ID无效");
- if (groupId < 1) return JsonView.Fail<AirTicketFeeInfoView>("团组ID无效");
- var groupVaild = Query<Grp_GroupsTaskAssignment>(a => a.IsDel == 0 && a.UId == userId && a.CTId == 85 && a.DIId == groupId).Any();
- if (!groupVaild) return JsonView.Fail<AirTicketFeeInfoView>("没有查看权限");
- // 获取第一个团组的基本信息
- var firstGroupInfo = await _groupInfoRep.GetGroupAirInfo(groupId);
- if (firstGroupInfo == null)
- return JsonView.Fail<AirTicketFeeInfoView>("团组信息不存在");
- // 团组公共信息
- var groupInfo = _mapper.Map<GroupAirTicketInfo>(firstGroupInfo);
- // 机票信息集合
- var airTicketFeeInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .InnerJoin<Grp_CreditCardPayment>((x, y) => x.Id == y.CId && x.DIId == y.DIId && y.CTable == 85)
- .Where((x, y) => x.IsDel == 0 && y.IsDel == 0 && x.DIId == groupId && x.RecordType == 0)
- .Select((x, y) => new AirTicketFeeInfo
- {
- // 机票信息
- Id = x.Id,
- FlightsDescription = x.FlightsDescription,
- AirTicketBasicInfos = x.AirTicketBasicInfos,
- ClientName = x.ClientName,
- CustTicketInfos = x.CustTicketInfos,
- PriceDescription = x.PriceDescription,
- // 支付信息
- PayDId = y.PayDId,
- ConsumptionPatterns = y.ConsumptionPatterns,
- ConsumptionDate = y.ConsumptionDate,
- PayMoney = y.PayMoney,
- PaymentCurrency = y.PaymentCurrency,
- CTDId = y.CTDId,
- BankNo = y.BankNo,
- CardholderName = y.CardholderName,
- DayRate = y.DayRate,
- CompanyBankNo = y.CompanyBankNo,
- OtherSideNo = y.OtherSideNo,
- OtherSideName = y.OtherSideName,
- Payee = y.Payee,
- OrbitalPrivateTransfer = y.OrbitalPrivateTransfer,
- Remark = y.Remark,
- IsAuditGM = y.IsAuditGM,
- AuditGMOperate = y.AuditGMOperate,
- AuditGMDate = y.AuditGMDate
- })
- .ToListAsync();
- // 如果没有数据,返回空结果
- if (!airTicketFeeInfos.Any())
- {
- groupInfo.FlightsDescription = string.Empty;
- return JsonView.Success(new AirTicketFeeInfoView()
- {
- CurrUserId = userId,
- GroupAirInfo = groupInfo,
- AirTicketFeeInfos = new List<AirTicketFeeInfo>()
- });
- }
- // 航班舱位类型
- var cabinTypes = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 44).ToListAsync();
- // 分组统计一个航班行程的信息
- var groupedByFlights = airTicketFeeInfos
- .GroupBy(x => x.FlightsDescription)
- .Select(g =>
- {
- var first = g.First();
- // 合并客户名称(去重)
- var clientNames = string.Join(",", g.Select(x => x.ClientName).ToList());
- var clientNameIds = ParseToIntListSafe(clientNames);
- // 处理审核状态
- var auditsStr = new StringBuilder();
- foreach (var item in g)
- {
- var auditStatus = item.IsAuditGM switch
- {
- 0 => "未审核",
- 1 => "审核通过",
- 2 => "审核驳回",
- 3 => "自动审核",
- _ => "未知状态"
- };
- var cabinTypeName = cabinTypes.FirstOrDefault(c => c.Id == item.CustTicketInfos.FirstOrDefault()?.CType)?.Name ?? "未知舱位";
- auditsStr.Append($"{cabinTypeName}:{auditStatus};");
- }
- // 合并所有客户的机票信息
- var custTicketInfos = g.SelectMany(x => x.CustTicketInfos ?? new List<CustTicketInfo>()).ToList();
- // 累计退票金额
- decimal refundAmount = custTicketInfos.Where(x => x.IsRefund).Sum(x => (x.RefundRecord?.RefundAmount ?? 0m) + (x.RefundRecord?.NonRefundableTax ?? 0m));
- // 付款金额
- decimal payMoney = g.Sum(x => x.PayMoney) + refundAmount;
- // 处理多舱位审核描述
- var newFlight = new AirTicketFeeInfo
- {
- Id = first.Id,
- FlightsDescription = g.Key,
- AirTicketBasicInfos = g.FirstOrDefault()?.AirTicketBasicInfos ?? new List<AirTicketBasicInfo>(),
- // 合并客户人员
- ClientName = clientNames,
- ClientNameIds = clientNameIds,
- // 合并所有客户的机票信息
- CustTicketInfos = custTicketInfos,
- PriceDescription = first.PriceDescription,
- // 付款信息
- PayDId = first.PayDId,
- ConsumptionPatterns = first.ConsumptionPatterns,
- ConsumptionDate = first.ConsumptionDate,
- PayMoney = payMoney,
- PaymentCurrency = first.PaymentCurrency,
- CTDId = first.CTDId,
- BankNo = first.BankNo,
- CardholderName = first.CardholderName,
- DayRate = first.DayRate,
- CompanyBankNo = first.CompanyBankNo,
- OtherSideNo = first.OtherSideNo,
- OtherSideName = first.OtherSideName,
- Payee = first.Payee,
- OrbitalPrivateTransfer = first.OrbitalPrivateTransfer,
- Remark = first.Remark,
- IsAuditGM = first.IsAuditGM,
- AuditGMOperate = first.AuditGMOperate,
- AuditGMDate = first.AuditGMDate,
- AuditStr = auditsStr.ToString().Trim()
- };
-
- return newFlight;
- })
- .ToList();
- // 按序号排序
- groupedByFlights = groupedByFlights
- .OrderBy(x => ExtractSequenceNo(x.FlightsDescription))
- .ToList();
- // 提取完整的航班行程信息
- var flightsDescAll = new StringBuilder();
- foreach (var item in groupedByFlights)
- {
- flightsDescAll.Append(item.FlightsDescription);
- }
- groupInfo.FlightsDescription = flightsDescAll.ToString();
- return JsonView.Success(new AirTicketFeeInfoView()
- {
- CurrUserId = userId,
- GroupAirInfo = groupInfo,
- AirTicketFeeInfos = groupedByFlights
- });
- }
- #region info 辅助方法
- /// <summary>
- /// 将逗号分隔的字符串解析为 List<int>(带错误处理)
- /// </summary>
- public static List<int> ParseToIntListSafe(string input)
- {
- if (string.IsNullOrWhiteSpace(input))
- return new List<int>();
- var result = new List<int>();
- var parts = input.Split(',');
- foreach (var part in parts)
- {
- if (int.TryParse(part.Trim(), out int value))
- {
- result.Add(value);
- }
- // 可选:记录解析失败的值
- }
- return result;
- }
- /// <summary>
- /// 提取序号辅助方法
- /// </summary>
- private static int ExtractSequenceNo(string flightsDescription)
- {
- if (string.IsNullOrWhiteSpace(flightsDescription))
- return int.MaxValue;
- var match = Regex.Match(flightsDescription, @"^(\d+)\.");
- return match.Success ? int.Parse(match.Groups[1].Value) : int.MaxValue;
- }
- /// <summary>
- /// 获取测试数据
- /// </summary>
- private static List<CustTicketInfo> GetTestCustomerData()
- {
- var testData = new CustTicketInfo()
- {
- ClientId = 1081,
- CType = 460,
- ActualPrice = 1000,
- TicketCode = "9991234567890",
- TicketNumber = "ABC123",
- SelectedServiceIds = new List<int> { 1561, 1563 },
- AdditionalServices = new List<AdditionalService>()
- {
- new AdditionalService() { ServiceTypeId = 1561, Amount = 100 },
- new AdditionalService() { ServiceTypeId = 1563, Amount = 50 }
- },
- TotalTicketPrice = 1150,
- IsRefund = true,
- RefundRecord = new RefundRecord()
- {
- RefundAmount = -200,
- NonRefundableTax = -100,
- RefundReason = "航班取消",
- RefundTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
- RefundAccount = 0,
- }
- };
- return new List<CustTicketInfo>
- {
- testData,
- new CustTicketInfo
- {
- ClientId = 1720,
- CType = 460,
- ActualPrice = 1000,
- TicketCode = "9991234567890",
- TicketNumber = "ABC123"
- },
- new CustTicketInfo
- {
- ClientId = 163,
- CType = 460,
- ActualPrice = 1000,
- TicketCode = "9991234567890",
- TicketNumber = "ABC123"
- }
- };
- }
- #endregion
- /// <summary>
- /// 保存 2026版
- /// </summary>
- /// <returns></returns>
- /// <summary>
- /// 保存 2026版(无ID,通过业务字段定位)
- /// </summary>
- public async Task<JsonView<AppPushBodyView>> SaveAsync(AirTicketFeeSaveDto dto)
- {
- // 1. 基础字段设置
- var currUserId = dto.CurrUserId;
- var groupId = dto.GroupAirInfo?.Id ?? 0;
- var appPushBodyInfos = new List<AppPushBodyInfo>();
- var index = 1;
- // 2. 整理数据
- var airFeeRecords = await OrganizeAirTicketDataAsync(dto.AirTicketFeeInfos, groupId);
- if (airFeeRecords == null || !airFeeRecords.Any())
- {
- return JsonView<AppPushBodyView>.Success("没有需要保存的数据");
- }
- // 3. 开启事务
- BeginTran();
- try
- {
- foreach (var airInfo in airFeeRecords)
- {
- var airFeeInfo = _mapper.Map<Grp_AirTicketReservations>(airInfo);
- var cardPaymentInfo = _mapper.Map<Grp_CreditCardPayment>(airInfo);
- // 设置公共字段
- airFeeInfo.CreateUserId = currUserId;
- airFeeInfo.IsDel = 0;
- cardPaymentInfo.DIId = groupId;
- cardPaymentInfo.CTable = 85;
- cardPaymentInfo.AuditGMDate = string.Empty;
- cardPaymentInfo.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- cardPaymentInfo.IsPay = cardPaymentInfo.PayDId == 72 ? 1 : 0;
- cardPaymentInfo.PayThenMoney = cardPaymentInfo.PayMoney;
- cardPaymentInfo.RMBPrice = cardPaymentInfo.PayMoney * cardPaymentInfo.DayRate;
- cardPaymentInfo.CreateUserId = currUserId;
- cardPaymentInfo.IsDel = 0;
- // ========== 通过业务字段查找现有记录 ==========
- var existingAir = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .FirstAsync(x => x.DIId == groupId
- && x.FlightsDescription == airFeeInfo.FlightsDescription
- && x.CType == airFeeInfo.CType
- && x.RecordType == airFeeInfo.RecordType
- && x.IsDel == 0);
- int airId = 0;
- int cardId = 0;
- if (existingAir == null)
- {
- // ========== 新增 ==========
- var (Success, ErrorMessage, AirId, CardId) = await InsertNewRecord(airFeeInfo, cardPaymentInfo, index);
- if (!Success)
- {
- RollbackTran();
- return JsonView<AppPushBodyView>.Fail(ErrorMessage);
- }
- airId = AirId;
- cardId = CardId;
- appPushBodyInfos.Add(new AppPushBodyInfo()
- {
- OperationType = 1,
- AirTicketId = airId,
- CardId = cardId,
- CardCNYAmount = cardPaymentInfo.RMBPrice
- });
- }
- else
- {
- // ========== 修改 ==========
- var result = await UpdateExistingRecord(airFeeInfo, cardPaymentInfo, existingAir, groupId, index);
- if (!result.Success)
- {
- RollbackTran();
- return JsonView<AppPushBodyView>.Fail(result.ErrorMessage);
- }
- airId = result.AirId;
- cardId = result.CardId;
- appPushBodyInfos.Add(new AppPushBodyInfo()
- {
- OperationType = 2,
- AirTicketId = airId,
- CardId = cardId,
- CardCNYAmount = cardPaymentInfo.RMBPrice
- });
- }
- index++;
- }
- CommitTran();
- var view = new AppPushBodyView()
- {
- GroupName = dto.GroupAirInfo.TeamName,
- AppPushBodyInfos = appPushBodyInfos
- };
- return JsonView<AppPushBodyView>.Success("保存成功", view);
- }
- catch (Exception ex)
- {
- RollbackTran();
- return JsonView<AppPushBodyView>.Fail($"保存失败:{ex.Message}");
- }
- }
- #region 保存 辅助方法
- /// <summary>
- /// 整理数据(按舱位类型分组,分离退票和正常记录)
- /// </summary>
- /// <param name="airTicketFeeInfos"></param>
- /// <param name="groupId"></param>
- /// <returns></returns>
- private Task<List<AirTicketFeeOpInfo>> OrganizeAirTicketDataAsync(List<AirTicketFeeInfo> airTicketFeeInfos, int groupId)
- {
- var result = new List<AirTicketFeeOpInfo>();
- foreach (var airInfo in airTicketFeeInfos)
- {
- if (airInfo.CustTicketInfos == null || !airInfo.CustTicketInfos.Any())
- continue;
- // 按舱位类型分组
- var groupByCabinType = airInfo.CustTicketInfos
- .GroupBy(x => x.CType)
- .ToList();
- foreach (var cabinGroup in groupByCabinType)
- {
- var customers = cabinGroup.ToList();
- // 1. 正常记录(非退票客户)- 按舱位类型合并成一条数据
- var normalCustomers = customers.ToList();
- if (normalCustomers.Any())
- {
- var custRecord = _mapper.Map<AirTicketFeeOpInfo>(airInfo);
- custRecord.ClientNum = normalCustomers.Count;
- custRecord.ClientName = string.Join(",", normalCustomers.Select(x => x.ClientId));
- custRecord.CustTicketInfos = normalCustomers;
- var totalTicketPrice = normalCustomers.Sum(x => x.ActualPrice + x.AdditionalServices?.Sum(x1 => x1.Amount) ?? 0.00m);
- custRecord.Price = totalTicketPrice;
- custRecord.Currency = airInfo.PaymentCurrency;
- custRecord.PayMoney = totalTicketPrice;
- custRecord.RecordType = 0; // 正常记录
- custRecord.DIId = groupId;
- custRecord.CType = normalCustomers.FirstOrDefault()?.CType ?? 0;
- result.Add(custRecord);
- }
- // 2. 退票记录 - 按舱位类型 + 退款卡类型 分组
- var refundCustomers = customers.Where(x => x.IsRefund).ToList();
- if (refundCustomers.Any())
- {
- // 按退款卡类型分组
- var groupByRefundAccount = refundCustomers
- .GroupBy(x => x.RefundRecord?.RefundAccount ?? 0)
- .ToList();
- foreach (var refundGroup in groupByRefundAccount)
- {
- var refundCustomersInGroup = refundGroup.ToList();
- var refundAccount = refundGroup.Key;
- var custRecord = _mapper.Map<AirTicketFeeOpInfo>(airInfo);
- custRecord.DIId = groupId;
- custRecord.RecordType = 1; // 退票记录
- custRecord.CType = normalCustomers.FirstOrDefault()?.CType ?? 0;
- custRecord.OriginalReservationId = custRecord.Id; // 关联原始记录
- custRecord.ClientNum = refundCustomersInGroup.Count;
- custRecord.ClientName = string.Join(",", refundCustomersInGroup.Select(x => x.ClientId));
- custRecord.CustTicketInfos = refundCustomersInGroup;
- // 计算退款金额(负数)
- decimal totalRefundAmount = refundCustomersInGroup.Sum(x =>
- (x.RefundRecord?.RefundAmount ?? 0) + (x.RefundRecord?.NonRefundableTax ?? 0));
- custRecord.Price = totalRefundAmount;
- custRecord.Currency = airInfo.PaymentCurrency;
- custRecord.PayMoney = totalRefundAmount;
- custRecord.CTDId = refundAccount; // 退款账户
- result.Add(custRecord);
- }
- }
- }
- }
- return Task.FromResult(result.OrderBy(x => x.RecordType).ToList());
- }
- /// <summary>
- /// 新增记录
- /// </summary>
- /// <param name="airFeeInfo"></param>
- /// <param name="cardPaymentInfo"></param>
- /// <param name="index"></param>
- /// <returns></returns>
- private async Task<(bool Success, string ErrorMessage, int AirId, int CardId)> InsertNewRecord(
- Grp_AirTicketReservations airFeeInfo,
- Grp_CreditCardPayment cardPaymentInfo,
- int index)
- {
- // 如果是退票记录,需要先获取关联的正常机票ID
- if (airFeeInfo.RecordType == 1)
- {
- // 根据唯一键查找关联的正常机票记录
- var normalAir = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .FirstAsync(x => x.DIId == airFeeInfo.DIId
- && x.FlightsDescription == airFeeInfo.FlightsDescription
- && x.CType == airFeeInfo.CType
- && x.RecordType == 0
- && x.IsDel == 0);
- // 设置关联的正常机票ID
- airFeeInfo.OriginalReservationId = normalAir?.Id ?? 0;
- }
- // 插入机票信息
- var airIdLong = await _sqlSugar.Insertable(airFeeInfo).ExecuteReturnIdentityAsync();
- var airId = (int)airIdLong;
- if (airId < 1)
- {
- return (false, $"第{index}条,机票信息添加失败", 0, 0);
- }
- // 插入付款信息
- cardPaymentInfo.CId = airId;
- var cardIdLong = await _sqlSugar.Insertable(cardPaymentInfo).ExecuteReturnIdentityAsync();
- var cardId = (int)cardIdLong;
- if (cardId < 1)
- {
- return (false, $"第{index}条,机票付款信息添加失败", 0, 0);
- }
- return (true, string.Empty, airId, cardId);
- }
- /// <summary>
- /// 更新记录
- /// </summary>
- /// <param name="airFeeInfo"></param>
- /// <param name="cardPaymentInfo"></param>
- /// <param name="existingAir"></param>
- /// <param name="groupId"></param>
- /// <param name="index"></param>
- /// <returns></returns>
- /// <summary>
- /// 更新记录(支持舱位变更:当前舱位无人员时删除,新舱位新增或合并)
- /// </summary>
- /// <summary>
- /// 更新记录(在修改时处理舱位变更)
- /// </summary>
- private async Task<(bool Success, bool IsSkip, string ErrorMessage, int AirId, int CardId)> UpdateExistingRecord(
- Grp_AirTicketReservations airFeeInfo,
- Grp_CreditCardPayment cardPaymentInfo,
- Grp_AirTicketReservations existingAir,
- int groupId,
- int index)
- {
- var existingAirId = existingAir.Id;
- var oldCabinType = existingAir.CType;
- var newCabinType = airFeeInfo.CType;
- // 1. 验证费用状态
- var existingCard = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .FirstAsync(x => x.DIId == groupId && x.CTable == 85 && x.CId == existingAirId && x.IsDel == 0);
- if (existingCard != null)
- {
- if (existingCard.IsAuditGM == 1 || existingCard.IsAuditGM == 3)
- {
- return (false, true, $"第{index}条,机票费用已审核,不可操作!", 0, 0);
- }
- if (existingCard.IsPay == 1)
- {
- return (false, true, $"第{index}条,机票费用已付款,不可操作!", 0, 0);
- }
- }
- // 2. 如果是退票记录,处理关联
- if (airFeeInfo.RecordType == 1 && airFeeInfo.OriginalReservationId <= 0)
- {
- var normalAir = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .FirstAsync(x => x.DIId == groupId
- && x.FlightsDescription == airFeeInfo.FlightsDescription
- && x.CType == airFeeInfo.CType
- && x.RecordType == 0
- && x.IsDel == 0);
- if (normalAir == null)
- {
- return (false, true, $"第{index}条,退票记录关联的正常机票不存在,请先添加正常机票", 0, 0);
- }
- airFeeInfo.OriginalReservationId = normalAir.Id;
- }
- // ========== 3. 处理舱位变更 ==========
- if (oldCabinType != newCabinType)
- {
- // 3.1 检查原舱位是否有退票记录
- var hasRefund = existingAir.CustTicketInfos?.Any(x => x.IsRefund) == true;
- if (hasRefund)
- {
- return (false, true, $"第{index}条,原舱位下存在退票记录,不可变更舱位!请先处理退票", 0, 0);
- }
- // 3.2 获取原舱位的人员列表
- var movingClients = existingAir.CustTicketInfos ?? new List<CustTicketInfo>();
- if (!movingClients.Any())
- {
- // 没有人员,直接更新舱位类型
- airFeeInfo.Id = existingAirId;
- var airUpdateCount = await _sqlSugar.Updateable(airFeeInfo)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == existingAirId)
- .ExecuteCommandAsync();
- if (airUpdateCount < 1)
- {
- return (false, false, $"第{index}条,更新舱位类型失败", 0, 0);
- }
- return (true, false, string.Empty, existingAirId, existingCard?.Id ?? 0);
- }
- // 3.3 查找目标舱位是否已存在记录
- var targetRecord = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .FirstAsync(x => x.DIId == groupId
- && x.FlightsDescription == airFeeInfo.FlightsDescription
- && x.CType == newCabinType
- && x.RecordType == airFeeInfo.RecordType
- && x.IsDel == 0);
- if (targetRecord != null)
- {
- // ========== 目标舱位已存在:合并人员 ==========
- // 3.3.1 获取目标舱位的人员列表
- var targetClients = targetRecord.CustTicketInfos ?? new List<CustTicketInfo>();
- var existingClientIds = targetClients.Select(x => x.ClientId).ToHashSet();
- // 3.3.2 合并人员(去重,保留原舱位的人员信息)
- foreach (var movingClient in movingClients)
- {
- if (!existingClientIds.Contains(movingClient.ClientId))
- {
- targetClients.Add(movingClient);
- }
- }
- // 3.3.3 重新计算目标舱位的总金额
- var totalTicketPrice = targetClients.Sum(x =>
- x.ActualPrice + (x.AdditionalServices?.Sum(x1 => x1.Amount) ?? 0.00m));
- // 3.3.4 更新目标舱位记录
- targetRecord.CustTicketInfos = targetClients;
- targetRecord.ClientNum = targetClients.Count;
- targetRecord.ClientName = string.Join(",", targetClients.Select(x => x.ClientId));
- targetRecord.Price = totalTicketPrice;
- var targetUpdateCount = await _sqlSugar.Updateable(targetRecord)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == targetRecord.Id)
- .ExecuteCommandAsync();
- if (targetUpdateCount < 1)
- {
- return (false, false, $"第{index}条,合并到目标舱位失败", 0, 0);
- }
- // 3.3.5 更新目标舱位的费用记录
- var targetCard = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .FirstAsync(x => x.DIId == groupId && x.CTable == 85 && x.CId == targetRecord.Id && x.IsDel == 0);
- if (targetCard != null)
- {
- targetCard.PayMoney = totalTicketPrice;
- targetCard.RMBPrice = totalTicketPrice * (targetCard?.DayRate ?? 1);
- targetCard.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- await _sqlSugar.Updateable(targetCard)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == targetCard.Id)
- .ExecuteCommandAsync();
- }
- // 3.3.6 删除原舱位记录(软删除)
- existingAir.IsDel = 1;
- existingAir.DeleteUserId = airFeeInfo.CreateUserId;
- existingAir.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- await _sqlSugar.Updateable(existingAir)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == existingAirId)
- .ExecuteCommandAsync();
- // 3.3.7 删除原舱位费用记录
- if (existingCard != null)
- {
- existingCard.IsDel = 1;
- existingCard.DeleteUserId = airFeeInfo.CreateUserId;
- existingCard.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- await _sqlSugar.Updateable(existingCard)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == existingCard.Id)
- .ExecuteCommandAsync();
- }
- return (true, false, string.Empty, targetRecord.Id, targetCard?.Id ?? 0);
- }
- else
- {
- // ========== 目标舱位不存在:直接修改原记录的舱位类型 ==========
- airFeeInfo.Id = existingAirId;
- airFeeInfo.CreateUserId = existingAir.CreateUserId;
- airFeeInfo.CreateTime = existingAir.CreateTime;
- var airUpdateCount = await _sqlSugar.Updateable(airFeeInfo)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == existingAirId)
- .ExecuteCommandAsync();
- if (airUpdateCount < 1)
- {
- return (false, false, $"第{index}条,更新舱位类型失败", 0, 0);
- }
- return (true, false, string.Empty, existingAirId, existingCard?.Id ?? 0);
- }
- }
- // ========== 4. 舱位未变,正常更新 ==========
- // 4.1 保留创建信息
- airFeeInfo.Id = existingAirId;
- airFeeInfo.CreateUserId = existingAir.CreateUserId;
- airFeeInfo.CreateTime = existingAir.CreateTime;
- airFeeInfo.IsDel = 0;
- // 4.2 更新机票信息
- var updateCount = await _sqlSugar.Updateable(airFeeInfo)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == existingAirId)
- .ExecuteCommandAsync();
- if (updateCount < 1)
- {
- return (false, false, $"第{index}条,机票信息保存失败", 0, 0);
- }
- // 4.3 更新或新增付款信息
- int cardId = 0;
- cardPaymentInfo.CId = existingAirId;
- if (existingCard != null)
- {
- cardPaymentInfo.Id = existingCard.Id;
- cardPaymentInfo.CreateUserId = existingCard.CreateUserId;
- cardPaymentInfo.CreateTime = existingCard.CreateTime;
- var cardUpdateCount = await _sqlSugar.Updateable(cardPaymentInfo)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == existingCard.Id)
- .ExecuteCommandAsync();
- if (cardUpdateCount < 1)
- {
- return (false, false, $"第{index}条,机票费用信息保存失败", 0, 0);
- }
- cardId = existingCard.Id;
- }
- else
- {
- var cardIdLong = await _sqlSugar.Insertable(cardPaymentInfo).ExecuteReturnIdentityAsync();
- if (cardIdLong < 1)
- {
- return (false, false, $"第{index}条,机票费用信息保存失败", 0, 0);
- }
- cardId = (int)cardIdLong;
- }
- return (true, false, string.Empty, existingAirId, cardId);
- }
- #endregion
- /// <summary>
- /// 行程内删除用户信息
- /// </summary>
- /// <param name="dto"></param>
- /// <returns></returns>
- public async Task<JsonView> TripUserDeleteAsync(AirTicketCostTripUserDelDto dto)
- {
- // 基础数据查询(舱位类型)
- var cabinDatas = await _sqlSugar
- .Queryable<Sys_SetData>()
- .Where(x => x.IsDel == 0 && x.STid == 44)
- .Select(x => new { x.Id, x.Name })
- .ToListAsync();
- // 人员信息查询
- var clientInfo = await _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(x => x.IsDel == 0 && x.Id == dto.ClientId)
- .Select(x => new { x.Id, x.FirstName, x.LastName, x.Pinyin })
- .FirstAsync();
- // 客户名称
- var clientName = clientInfo != null
- ? $"{AesEncryptionHelper.Decrypt(clientInfo.FirstName)}{AesEncryptionHelper.Decrypt(clientInfo.LastName)}"
- : $"ID:{dto.ClientId}";
- BeginTran();
- try
- {
- // 1. 查询对应的机票记录(按团组+航段+舱位+正常记录)
- var airTicket = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.DIId == dto.GroupId
- && x.FlightsDescription == dto.FlightsDescription
- && x.CType == dto.CType
- && x.RecordType == 0 // 正常记录
- && x.IsDel == 0)
- .FirstAsync();
- var cabinName = cabinDatas.FirstOrDefault(x => x.Id == dto.CType)?.Name ?? "未知舱位";
- if (airTicket == null)
- {
- RollbackTran();
- return JsonView.Fail($"未找到对应记录!(航段:{dto.FlightsDescription}, 舱位:{cabinName})");
- }
- // 1.1 检查人员是否在记录中
- var hasClient = airTicket.CustTicketInfos?.Any(ct => ct.ClientId == dto.ClientId) == true;
- if (!hasClient)
- {
- RollbackTran();
- return JsonView.Fail($"人员【{clientName}(ID:{dto.ClientId})】不存在于该记录中!(航段:{dto.FlightsDescription}, 舱位:{cabinName})");
- }
- // 2. 查询对应的费用记录并验证状态
- var cardPayment = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .Where(x => x.DIId == dto.GroupId && x.CId == airTicket.Id && x.CTable == 85 && x.IsDel == 0)
- .FirstAsync();
- if (cardPayment != null)
- {
- // 费用状态验证
- if (cardPayment.IsAuditGM == 1)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已审核,不可删除人员!(航段:{dto.FlightsDescription}, 舱位:{cabinName}, 客户:{clientName})");
- }
- if (cardPayment.IsAuditGM == 3)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已自动审核,不可删除人员!(航段:{dto.FlightsDescription}, 舱位:{cabinName}, 客户:{clientName})");
- }
- if (cardPayment.IsPay == 1)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已付款,不可删除人员!(航段:{dto.FlightsDescription}, 舱位:{cabinName}, 客户:{clientName})");
- }
- }
- // 3. 检查该人员是否有退票记录
- var targetClientInfo = airTicket.CustTicketInfos?.FirstOrDefault(x => x.ClientId == dto.ClientId);
- var hasRefund = targetClientInfo?.IsRefund == true;
- if (hasRefund)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:人员【{clientName}(ID:{dto.ClientId})】存在退票记录,不可删除!请先处理退票信息。");
- }
- // 4. 获取剩余人员列表
- var remainingClients = airTicket.CustTicketInfos?
- .Where(ct => ct.ClientId != dto.ClientId)
- .ToList() ?? new List<CustTicketInfo>();
- // 5. 计算总金额(包含机票价格 + 附加服务费用)
- decimal totalPrice = remainingClients.Sum(x =>
- (x?.ActualPrice ?? 0) + (x.AdditionalServices?.Sum(x1 => x1.Amount) ?? 0));
- // 6. 更新或删除记录
- if (remainingClients.Any())
- {
- // 6.1 更新机票记录
- airTicket.Price = totalPrice;
- airTicket.ClientNum = remainingClients.Count;
- airTicket.ClientName = string.Join(",", remainingClients.Select(x => x.ClientId));
- airTicket.CustTicketInfos = remainingClients;
- var airUpdateCount = await _sqlSugar.Updateable(airTicket)
- .UpdateColumns(x => new { x.ClientNum, x.ClientName, x.Price, x.CustTicketInfos })
- .Where(x => x.Id == airTicket.Id)
- .ExecuteCommandAsync();
- if (airUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:更新机票记录失败!");
- }
- // 6.2 更新费用记录
- if (cardPayment != null)
- {
- cardPayment.PayMoney = totalPrice;
- cardPayment.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- cardPayment.PayThenMoney = totalPrice;
- cardPayment.RMBPrice = totalPrice * (cardPayment?.DayRate ?? 1);
- var cardUpdateCount = await _sqlSugar.Updateable(cardPayment)
- .IgnoreColumns(ignoreAllNullColumns: true)
- .Where(x => x.Id == cardPayment.Id)
- .ExecuteCommandAsync();
- if (cardUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:更新费用记录失败!");
- }
- }
- }
- else
- {
- // 7. 没有剩余人员,删除整条记录
- var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- // 7.1 软删除机票记录
- airTicket.IsDel = 1;
- airTicket.DeleteUserId = dto.CurrUserId;
- airTicket.DeleteTime = now;
- var airUpdateCount = await _sqlSugar.Updateable(airTicket)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == airTicket.Id)
- .ExecuteCommandAsync();
- if (airUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:删除机票记录失败!");
- }
- // 7.2 软删除费用记录
- if (cardPayment != null)
- {
- cardPayment.IsDel = 1;
- cardPayment.DeleteUserId = dto.CurrUserId;
- cardPayment.DeleteTime = now;
- var cardUpdateCount = await _sqlSugar.Updateable(cardPayment)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == cardPayment.Id)
- .ExecuteCommandAsync();
- if (cardUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:删除费用记录失败!");
- }
- }
- }
- CommitTran();
- return JsonView.Success($"删除成功!已从航段【{dto.FlightsDescription}】舱位【{cabinName}】中移除人员【{clientName}(ID:{dto.ClientId})】");
- }
- catch (Exception ex)
- {
- RollbackTran();
- // 记录异常日志
- // _logger.LogError(ex, "行程内删除用户信息失败,参数:{@dto}", dto);
- return JsonView.Fail($"删除失败:{ex.Message}");
- }
- }
- /// <summary>
- /// 取消指定客户的退票
- /// </summary>
- /// <param name="dto">取消退票参数</param>
- /// <returns></returns>
- public async Task<JsonView> CancelClientRefundAsync(CancelClientRefundDto dto)
- {
- // 人员信息查询
- var clientInfo = await _sqlSugar.Queryable<Crm_DeleClient>()
- .Where(x => x.IsDel == 0 && x.Id == dto.ClientId)
- .Select(x => new { x.Id, x.FirstName, x.LastName, x.Pinyin })
- .FirstAsync();
- // 客户名称
- var clientName = clientInfo != null
- ? $"{AesEncryptionHelper.Decrypt(clientInfo.FirstName)}{AesEncryptionHelper.Decrypt(clientInfo.LastName)}"
- : $"ID:{dto.ClientId}";
- BeginTran();
- try
- {
- // 1. 查询退票记录
- var refundRecord = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.DIId == dto.GroupId
- && x.FlightsDescription == dto.FlightsDescription
- && x.CType == dto.CType
- && x.RecordType == 1 // 退票记录
- && x.IsDel == 0)
- .FirstAsync();
- if (refundRecord == null)
- {
- RollbackTran();
- return JsonView.Fail("未找到退票记录!");
- }
- // 2. 查询退票费用记录并验证状态
- var refundPayment = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .Where(x => x.DIId == dto.GroupId
- && x.CId == refundRecord.Id
- && x.CTable == 85
- && x.IsDel == 0)
- .FirstAsync();
- if (refundPayment != null)
- {
- if (refundPayment.IsAuditGM == 1 || refundPayment.IsAuditGM == 3)
- {
- RollbackTran();
- return JsonView.Fail("取消失败:退票费用已审核,不可取消!");
- }
- if (refundPayment.IsPay == 1)
- {
- RollbackTran();
- return JsonView.Fail("取消失败:退票费用已付款,不可取消!");
- }
- }
- // 3. 解析退票人员列表
- var refundClientIds = refundRecord.CustTicketInfos?
- .Where(x => x.IsRefund)
- .Select(x => x.ClientId)
- .ToList() ?? new List<int>();
- if (!refundClientIds.Contains(dto.ClientId))
- {
- RollbackTran();
- return JsonView.Fail($"人员【{clientName}】不存在于该退票记录中!");
- }
- // 4. 查询关联的正常机票记录
- var normalTicket = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.Id == refundRecord.OriginalReservationId
- && x.RecordType == 0
- && x.IsDel == 0)
- .FirstAsync();
- if (normalTicket == null)
- {
- RollbackTran();
- return JsonView.Fail("取消失败:关联的正常机票记录不存在!");
- }
- // 5. 更新正常机票中该客户的 IsRefund 标志
- var normalTicketClients = normalTicket.CustTicketInfos ?? new List<CustTicketInfo>();
- var targetClient = normalTicketClients.FirstOrDefault(x => x.ClientId == dto.ClientId);
- if (targetClient != null)
- {
- targetClient.IsRefund = false;
- targetClient.RefundRecord = new RefundRecord();
- }
- // 6. 保存正常机票记录
- normalTicket.CustTicketInfos = normalTicketClients;
- var airNormalCount = await _sqlSugar.Updateable(normalTicket)
- .UpdateColumns(x => new { x.CustTicketInfos })
- .Where(x => x.Id == normalTicket.Id)
- .ExecuteCommandAsync();
- if (airNormalCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("取消失败:更新正常机票记录失败!");
- }
- // 7. 从退票记录中移除该客户(同时更新 CustTicketInfos)
- var remainingRefundClients = refundRecord.CustTicketInfos?
- .Where(x => x.ClientId != dto.ClientId)
- .ToList() ?? new List<CustTicketInfo>();
- if (remainingRefundClients.Any())
- {
- // 7.1 更新退票记录中的 CustTicketInfos
- refundRecord.CustTicketInfos = remainingRefundClients;
- refundRecord.ClientNum = remainingRefundClients.Count;
- refundRecord.ClientName = string.Join(",", remainingRefundClients.Select(x => x.ClientId));
- // 重新计算退款金额
- decimal totalRefundAmount = remainingRefundClients.Sum(x =>
- (x.RefundRecord?.RefundAmount ?? 0) + (x.RefundRecord?.NonRefundableTax ?? 0));
- refundRecord.Price = totalRefundAmount;
- var refundRecordCount = await _sqlSugar.Updateable(refundRecord)
- .UpdateColumns(x => new { x.CustTicketInfos, x.ClientNum, x.ClientName, x.Price })
- .Where(x => x.Id == refundRecord.Id)
- .ExecuteCommandAsync();
- if (refundRecordCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("取消退票失败:退票信息更新失败!");
- }
- // 7.2 更新退票费用记录
- if (refundPayment != null)
- {
- refundPayment.PayMoney = totalRefundAmount;
- refundPayment.RMBPrice = totalRefundAmount * (refundPayment?.DayRate ?? 1);
- refundPayment.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- var refundPaymentCount = await _sqlSugar.Updateable(refundPayment)
- .UpdateColumns(x => new { x.PayMoney, x.RMBPrice, x.UpdateDate })
- .Where(x => x.Id == refundPayment.Id)
- .ExecuteCommandAsync();
- if (refundPaymentCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("取消退票失败:退票费用信息更新失败!");
- }
- }
- }
- else
- {
- // 8. 退票记录中没有客户了,删除整条退票记录
- var now = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- refundRecord.IsDel = 1;
- refundRecord.DeleteUserId = dto.CurrUserId;
- refundRecord.DeleteTime = now;
- var refundRecordCount = await _sqlSugar.Updateable(refundRecord)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == refundRecord.Id)
- .ExecuteCommandAsync();
- if (refundRecordCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("取消退票失败:删除退票记录失败!");
- }
- if (refundPayment != null)
- {
- refundPayment.IsDel = 1;
- refundPayment.DeleteUserId = dto.CurrUserId;
- refundPayment.DeleteTime = now;
- var refundPaymentCount = await _sqlSugar.Updateable(refundPayment)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == refundPayment.Id)
- .ExecuteCommandAsync();
- if (refundPaymentCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("取消退票失败:删除退票费用记录失败!");
- }
- }
- }
- CommitTran();
- return JsonView.Success($"取消退票成功!已将客户【{clientName}】的退票状态恢复正常");
- }
- catch (Exception ex)
- {
- RollbackTran();
- return JsonView.Fail($"取消退票失败:{ex.Message}");
- }
- }
- /// <summary>
- /// 按ID删除机票记录 2026版
- /// 验证费用状态和退票记录
- /// </summary>
- /// <param name="userId">操作用户ID</param>
- /// <param name="airTicketId">机票记录ID</param>
- /// <returns></returns>
- public async Task<JsonView> DeleteByIdAsync(int userId, int airTicketId)
- {
- BeginTran();
- try
- {
- // 1. 查询机票记录
- var airTicket = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.Id == airTicketId && x.IsDel == 0)
- .FirstAsync();
- if (airTicket == null)
- {
- RollbackTran();
- return JsonView.Fail("机票费用记录不存在或已被删除!");
- }
- // 2. 验证费用状态
- var cardPayment = await _sqlSugar.Queryable<Grp_CreditCardPayment>()
- .Where(x => x.CId == airTicketId && x.CTable == 85 && x.IsDel == 0)
- .FirstAsync();
- if (cardPayment != null)
- {
- if (cardPayment.IsAuditGM == 1)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已审核,不可删除!(记录ID:{airTicketId})");
- }
- if (cardPayment.IsAuditGM == 3)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已自动审核,不可删除!(记录ID:{airTicketId})");
- }
- if (cardPayment.IsPay == 1)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:当前费用已付款,不可删除!(记录ID:{airTicketId})");
- }
- }
- // 3. 验证退票记录关联
- if (airTicket.RecordType == 0) // 正常记录
- {
- // 检查是否有退票记录关联
- var refundRecords = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.OriginalReservationId == airTicketId
- && x.RecordType == 1
- && x.IsDel == 0)
- .ToListAsync();
- if (refundRecords.Any())
- {
- var refundIds = string.Join(",", refundRecords.Select(x => x.Id));
- var refundNames = string.Join(",", refundRecords.Select(x => x.ClientName));
- RollbackTran();
- return JsonView.Fail($"删除失败:该记录存在关联的退票记录!请先删除以下退票记录ID:[{refundIds}],关联人员:[{refundNames}]");
- }
- }
- else if (airTicket.RecordType == 1) // 退票记录
- {
- // 检查关联的正常机票是否存在
- if (airTicket.OriginalReservationId > 0)
- {
- var normalTicket = await _sqlSugar.Queryable<Grp_AirTicketReservations>()
- .Where(x => x.Id == airTicket.OriginalReservationId && x.IsDel == 0)
- .FirstAsync();
- if (normalTicket == null)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:退票记录关联的正常机票不存在或已被删除!(关联ID:{airTicket.OriginalReservationId})");
- }
- }
- }
- // 4. 执行软删除
- // 4.1 软删除机票记录
- airTicket.IsDel = 1;
- airTicket.DeleteUserId = userId;
- airTicket.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- var airUpdateCount = await _sqlSugar.Updateable(airTicket)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == airTicketId)
- .ExecuteCommandAsync();
- if (airUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:机票记录删除失败!");
- }
- // 4.2 软删除对应的费用记录
- if (cardPayment != null)
- {
- cardPayment.IsDel = 1;
- cardPayment.DeleteUserId = userId;
- cardPayment.DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- var cardUpdateCount = await _sqlSugar.Updateable(cardPayment)
- .UpdateColumns(x => new { x.IsDel, x.DeleteUserId, x.DeleteTime })
- .Where(x => x.Id == cardPayment.Id)
- .ExecuteCommandAsync();
- if (cardUpdateCount < 1)
- {
- RollbackTran();
- return JsonView.Fail("删除失败:费用记录删除失败!");
- }
- }
- CommitTran();
- var recordTypeName = airTicket.RecordType == 0 ? "正常记录" : "退票记录";
- return JsonView.Success($"删除成功!已删除{recordTypeName},ID:{airTicketId}");
- }
- catch (Exception ex)
- {
- RollbackTran();
- return JsonView.Fail($"删除失败:{ex.Message}");
- }
- }
- #endregion
- }
|