using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using XYY.Api.Order.Model.Order; using XYY.Common.Standard; using XYY.Core.Standard.Data.Infrastructure; using XYY.Core.Standard.Mvc; using XYY.Service.Standard.Order; using XYY.TaskTrack.Standard; using XYY.Model.Standard.Channel; using XYY.Service.Standard.ChannelApi.Base; using Dapper; using XYY.Authentication.Standard; using Microsoft.AspNetCore.Authorization; using XYY.Core.Standard.ExcelHelper.MSExcelHelper; using XYY.Model.Standard.Dto.order; using XYY.Service.Standard.ChannelApi.Itdida; using XYY.Data.Standard.Order; using XYY.Service.Standard.Channel; using static XYY.Service.Standard.Finance.Charging.Express.ExpressFeeChargesService; using XYY.Data.Standard.Channel; using System.IO; using XYY.Service.Standard.ChannelApi.Winit.LMAApi; using XYY.Model.Standard.Order; using static XYY.Service.Standard.ChannelApi.HangLe.Api; using System.Threading.Channels; using XYY.Model.Standard.Dto.Channel; using Antlr.Runtime.Misc; using Nest; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Microsoft.Extensions.Caching.Memory; using static Aliyun.OSS.Model.CreateSelectObjectMetaInputFormatModel; namespace XYY.Api.Order.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class OrderController : ApiControllerBase { private IOrderService _orderService; private IMQManager _mQManager; private IUnitOfWork _unitOfWork; //private FiddlerClient _fiddlerClient; private IEnumerable _baseApis; private IOrderRepository _orderRepository; private IChannelService _channelService; ICustomerLazyService customerLazyService; private IMoreThanOneTicketService _mpsService; private IOrderGoodsRepository _orderGoodsRepository; private ILogistics_ChannelRepository _ChannelRepository; IOrder_OrderPrintQtyRepository _order_OrderPrintQtyRepository; Microsoft.Extensions.Caching.Distributed.IDistributedCache _distributed; IUser_CustomerDeclarationsRepository _CustomerDeclarationsRepository; private ILogger _dataUpdateLogger; private IEnumerable _manifestApis; public OrderController(IOrderService orderService, IMQManager mQManager, IUnitOfWork unitOfWork //, FiddlerClient fiddlerClient , IEnumerable baseApis , IOrderRepository orderRepository, Microsoft.Extensions.Caching.Distributed.IDistributedCache distributed, IChannelService channelService, IMoreThanOneTicketService mpsService, IOrderGoodsRepository orderGoodsRepository, ILogistics_ChannelRepository channelRepository, IOrder_OrderPrintQtyRepository order_OrderPrintQtyRepository, ICustomerLazyService customerLazyService, ILogger dataUpdateLogger, IUser_CustomerDeclarationsRepository customerDeclarationsRepository, IEnumerable manifestApis) { _orderService = orderService; _mQManager = mQManager; _unitOfWork = unitOfWork; //_fiddlerClient = fiddlerClient; _baseApis = baseApis; _orderRepository = orderRepository; _distributed = distributed; _channelService = channelService; _mpsService = mpsService; _orderGoodsRepository = orderGoodsRepository; _ChannelRepository = channelRepository; _order_OrderPrintQtyRepository = order_OrderPrintQtyRepository; this.customerLazyService = customerLazyService; _dataUpdateLogger = dataUpdateLogger; _CustomerDeclarationsRepository = customerDeclarationsRepository; _manifestApis = manifestApis; } public async Task GetFP(FBRequest request) { ItdidaApi itdidaApi = new ItdidaApi(_orderRepository, _distributed); byte[] data = await itdidaApi.GetFP(request.Channel, request.TrackingNumber); string base64 = Convert.ToBase64String(data); return Ok(base64); } public async Task GetK5FP(FPRequest request) { Service.Standard.ChannelApi.K5.Api k5 = new Service.Standard.ChannelApi.K5.Api(_order_OrderPrintQtyRepository); byte[] data = await k5.GetFP(request.Channel, request.order); string base64 = Convert.ToBase64String(data); return Ok(base64); } public async Task GetDGFedexFP(FPRequest request) { Service.Standard.ChannelApi.ChinaPost.GatewayApi api = new Service.Standard.ChannelApi.ChinaPost.GatewayApi(_order_OrderPrintQtyRepository, _CustomerDeclarationsRepository); byte[] data = await api.GetFP(request.Channel, request.order); string base64 = Convert.ToBase64String(data); return Ok(base64); } public async Task PostManifest() { var channels = await _channelService.CacheGetAllChannel(); var pbchannels = channels.Where(x => x.ServiceCode == "PitneyBowes"); foreach (var channel in pbchannels) { XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api(); var result = await api.Manifest(channel); } return Ok(); } public async Task GetPBTracking(PBTrackingRequest request) { XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api(); var response = await api.GetTracking(request.TrackingNumber, new Logistics_Channel()); return Ok(response); } public async Task ContainerManifest(ContainerManifestRequest request) { if (request.Details.Count == 0) throw new Exception("必须传入明细"); XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api(); var result = await api.ContainerManifest(request.BoxNumber, request.Port, request.Channel, request.Details); var data = Convert.FromBase64String(result.labelData); return File(data, "application/pdf"); } public async Task GetRemote() { Order_Order order = new Order_Order(); order.ReceiverCity = "NORTH POLE"; order.ReceiverState = "AK"; order.ReceiverCountryCode = "US"; order.ReceiverStreet = "3051 Victoria Circle"; order.ReceiverPhone = "+19073478300"; order.ReceiverZipCode = "99705"; Logistics_Channel channel = await _ChannelRepository.GetAsync(583); ItdidaApi itdidaApi = new ItdidaApi(_orderRepository, _distributed); var c = await itdidaApi.GetRemote(channel, order); return Ok(); } public async Task GetTracking(TrackingRequest request) { XYY.Service.Standard.ChannelApi.PitneyBowes.Api api = new Service.Standard.ChannelApi.PitneyBowes.Api(); var result = await api.GetTracking(request.TrackingNumber, request.Channel); return Ok(result); } public class StreeReplate { public string Ori { get; set; } public string Replete { get; set; } public string Stree1 { get; set; } public string Stree2 { get; set; } } public async Task GetStreeReplate(List souces) { List streeReplates = new List(); foreach (var s in souces) { StreeReplate replate = new StreeReplate(); replate.Ori = s; string r2 = s .ReplateExp("Road", "Rd") .ReplateExp("Street", "St") .ReplateExp("Drive", "Dr") .ReplateExp("Avenue", "Ave") .ReplateExp("Freeway", "Fwy") .ReplateExp("Alley", "Aly") .ReplateExp("apartment", "apt") .ReplateExp("Boulevard", "BLVD") .ReplateExp("north", "N") .ReplateExp("South", "S") .ReplateExp("west", "W") .ReplateExp("east", "E"); replate.Replete = r2; replate.Stree1 = r2; if (r2.Length > 32) { if (r2.Split(' ').Count(x => string.Equals(x, "apt", StringComparison.OrdinalIgnoreCase)) >= 1) { replate.Stree1 = (r2.Substring(0, r2.IndexOf("apt", StringComparison.OrdinalIgnoreCase))).Trim(); replate.Stree2 = (r2.Substring(r2.IndexOf("apt", StringComparison.OrdinalIgnoreCase))).Trim(); } if (replate.Stree1.Length > 32 || replate.Stree2.Length > 32) { string[] addressList = XYY.Core.Standard.ExtendMethods.StringExtendMethods.ToArray2(r2, 32); replate.Stree1 = addressList[0].Trim(); replate.Stree2 = addressList.Length > 1 ? addressList[1].Trim() : ""; } } streeReplates.Add(replate); } System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter stringWriter = new System.IO.StringWriter(sb); CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(stringWriter, System.Globalization.CultureInfo.InvariantCulture); csvWriter.WriteRecords(streeReplates); csvWriter.Dispose(); System.IO.File.WriteAllText(@"d:\stree.csv", sb.ToString()); return Ok(); } public class TrackingRequest { public string TrackingNumber { get; set; } public Logistics_Channel? Channel { get; set; } } public class ContainerManifestRequest { public string BoxNumber { get; set; } public Logistics_Channel? Channel { get; set; } public List Details { get; set; } public string Port { get; set; } } public async Task GetUPSFee([FromBody] DataUploadRequest request) { var chanel = (await _channelService.CacheGetAllChannel()).Where(x => x.Id == 460).First(); request.arg = new ExtendArg { Order = new XYY.Model.Standard.MpsOrder.Order_MpsOrder { Boxs = new List { } } }; int vweight = (int)Math.Round(request.order.Width * request.order.Length * request.order.Height / 9.0m, MidpointRounding.AwayFromZero); request.order.CustomerWeight = vweight > request.order.CustomerWeight ? vweight : request.order.CustomerWeight; request.arg.Order.Boxs.Add(new XYY.Model.Standard.MpsOrder.Order_MpsOrderBox { OpInputWeight = request.order.CustomerWeight / 1000.0m, OpLength = request.order.Length, OpHeight = request.order.Height, OpWidth = request.order.Width, Goods = new List { new XYY.Model.Standard.MpsOrder.Order_MpsOrderGoods { CnName = "试算", EnName="test", HsCode="000000000", Quantity=1 } } }); request.order.CustomerId = 698; XYY.Service.Standard.ChannelApi.dorje56.Api api = new Service.Standard.ChannelApi.dorje56.Api(); var price = await api.SS(request.order, request.goods, chanel, request.arg); if (!string.IsNullOrEmpty(price.message)) { throw new Exception(price.message); } bool IsResidential = price.warnings.Any(x => x.message.Contains("Ship To Address Classification is changed from Commercial to Residential")); string url = "http://api.smp.xingyunyi.cn/Compute"; List cp = new List(); cp.Add(new SMPCP { ZipCode = request.order.ReceiverZipCode, City = String.Empty, State = String.Empty, Stree = String.Empty, ComputeDate = DateTime.Now.ToString_yyyyMMdd(), CountryCode = request.order.ReceiverCountryCode, ExpenseItemId = 224, Length = request.order.Length.ToString(), Width = request.order.Width.ToString(), Height = request.order.Height.ToString(), GoodsDeclareValue = 0.ToString(), M3 = 0.ToString(), Port = "LAX", TrackingNumber = String.Empty, Weight = (request.order.CustomerWeight).ToString(), OrderQty = 1.ToString(), IsResidential = IsResidential, Zone = "" }); RestSharp.RestClient client = new RestSharp.RestClient(url); RestSharp.RestRequest restRequest = new RestSharp.RestRequest(RestSharp.Method.POST); restRequest.AddJsonBody(cp.ToArray()); var response = client.Execute(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var model = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content); if (model.success) { var shopFee = model.data.FirstOrDefault(x => x.ExpenseName == "UPS运费"); if (shopFee == null) return Error("未返回UPS运费"); if (!shopFee.IsSuccess) return Error("运费计算失败:" + shopFee.Message); //原币种结算 var fee = new { Fee = model.data.Sum(x => x.AmountinOriginalCurrency), FeeCurrency = model.data.FirstOrDefault().BillCurrency, Weight = Math.Ceiling(request.order.CustomerWeight / 453.59237m), WeightUnit = "磅", FeeDetail = model.data.Where(x => x.IsSuccess && x.AmountinOriginalCurrency > 0) .Select(x => new { x.ExpenseName, x.BillCurrency, Amountin = (decimal)Math.Round(x.AmountinOriginalCurrency, 4, MidpointRounding.AwayFromZero) }) }; return Ok(fee); } else { return Error(model.message); } } return Ok(); } public async Task GetUPSAddreeIsResidential([FromBody] DataUploadRequest request) { //州名处理 XYY.Service.Standard.ChannelApi.dorje56.Api api = new Service.Standard.ChannelApi.dorje56.Api(); var price = await api.SS(request.order, request.goods, request.channel, request.arg); if (price.success) { return Ok(price.warnings.Any(x => x.message.Contains("Ship To Address Classification is changed from Commercial to Residential"))); } else { if (price.message == "无效的产品代码") { return Ok(true); } return Error("获取计费信息失败:" + price.message); } } public async Task AsyncCustomerLastTrackingNumber() { var s = await customerLazyService.AsyncLastTrackingNumber(); return Ok(s); } public async Task AsyncCustomerFirstESBTracking() { var e = await customerLazyService.AsyncFirstESBTracking(); return Ok(e); } [AllowAnonymous] [HttpGet] public async Task TestOrderAddress() { string textRegext = @"^[A-Za-z0-9/\-,.&'<>() ]+$"; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(textRegext); string s = "asdfsadfasdf.,112312 -/&<>()"; return Ok(new { soure = s, isok = r.IsMatch(s) }); } [AllowAnonymous] [HttpGet] public async Task TestOrderOperation() { var channel = await _unitOfWork.QueryBySqlAsync(" select top 100 * from Logistics_Channel(nolock) where Id=611 "); var order = await _unitOfWork.QueryBySqlAsync(" select top 100 * from Order_Order(nolock) where Id=222712850 "); var goods = await _unitOfWork.QueryBySqlAsync(" select * from Order_OrderGoods(nolock) where OrderId=222712850 "); var box = await _unitOfWork.QueryBySqlAsync(" select * from Logistics_Box(nolock) where boxnumber='B231101007702' "); #region AMS Service.Standard.ChannelApi.VE.Api api = new Service.Standard.ChannelApi.VE.Api(_order_OrderPrintQtyRepository); //await api.CreateDeclaration(order.First(), goods.ToList(), channel.First()); //await api.CancelDeclaration(channel.First().ApiHost,channel.First().ApiSecret, "XYYEX0030976426YQ"); //await api.NewDeclaration(order.First(), goods.ToList(), channel.First()); await api.PushBoxInfo(channel.First(), box.First(), 819); //await api.Association_BoxAndOrder(channel.First(), "B231030019402", "XYYEX0030976426YQ"); //await api.GetChannelOrderInfo(channel.First(), "XYYEX0030976426YQ"); #endregion //var baseApi = _baseApis.Where(x => x.ServiceName == channel.First().ServiceCode).FirstOrDefault(); //await _orderService.DataUpload(order.First(), goods.ToList(), channel.First(), new ExtendArg() { }); return Ok(); } [AllowAnonymous] [HttpGet] public async Task testDeAddress() { var channel = (await _unitOfWork.QueryBySqlAsync(" select top 100 * from Logistics_Channel(nolock) where Id=683 ")).FirstOrDefault(); var order = (await _unitOfWork.QueryBySqlAsync(" select top 100 * from Order_Order(nolock) where Id=223713094 ")).FirstOrDefault(); var goods = await _unitOfWork.QueryBySqlAsync(" select * from Order_OrderGoods(nolock) where OrderId=223713094 "); //需要测试的地址 var deAddres = await _unitOfWork.QueryBySqlAsync(" select * from lzktemp_Veaddr20240102(nolock) where ''=isnull(是否成功,'') "); //强制使用测试环境 channel.ApiHost = "https://app-sandbox.viaeurope.com"; channel.ApiSecret = "2a6c33e154f5ca571ac29584bbb248c4"; Service.Standard.ChannelApi.VE.Api api = new Service.Standard.ChannelApi.VE.Api(_order_OrderPrintQtyRepository); foreach (var item in deAddres) { string result = "是"; string resultJson = string.Empty; try { order.ReceiverName = item.收件人; order.ReceiverPhone = ((string)item.收件人电话).Replace("'", ""); order.ReceiverEmail = item.收件人邮箱; order.ReceiverState = item.收件人州; order.ReceiverCity = item.收件人城市; order.ReceiverStreet = item.收件人地址; order.CustomerWeight = Convert.ToInt32(item.客户重量); order.ReceiverZipCode = ((string)item.收件人邮编).PadLeft(5, '0'); var resultInfo = await api.DataUpload(order, goods.ToList(), channel, new ExtendArg()); resultJson = JsonConvert.SerializeObject(resultInfo); } catch (Exception ex) { result = "否"; resultJson = ex.Message; } await _unitOfWork.ExecuteAsync($" update lzktemp_Veaddr20240102 set 是否成功='{result}',执行结果=@resultJson where 客单号='{item.客单号}' ", new { resultJson = resultJson }); } return Ok(); } /// /// wms头程转运,推送ams箱子信息按钮,调用此方法 /// /// /// public async Task PushAMSBoxData(IEnumerable boxId) { //渠道写死 var channel = await _unitOfWork.QueryBySqlAsync(" select * from Logistics_Channel(nolock) where ServiceCode='VE' "); var box = await _unitOfWork.QueryBySqlAsync($" select * from Logistics_Box(nolock) where Id in @boxId and ChannelId in @ChannelId and 0=ISNULL(IsAMSPost,0) ", null, new { boxId = boxId, ChannelId = channel.Select(x => x.Id) }); if (box == null || box.Count() == 0) { return Ok(Tuple.Create(false, "箱子均不属于ams,或均已推送!请确认后提交!")); } var orders = await _unitOfWork.QueryBySqlAsync(@" select distinct a.BoxNumber,c.* from Logistics_Box(nolock) a left join Logistics_BoxDetail(nolock) b on b.BoxId=a.Id left join Order_Order(nolock)c on c.id=b.orderId where a.Id in @boxId ", null, new { boxId = boxId }); foreach (var item in box) { item.orders.AddRange(orders.Where(x => x.BoxNumber == item.BoxNumber)); } var boxGroupChannelId = box.GroupBy(x => x.ChannelId); List results = new List(); Tuple tuple = new Tuple(true, "推送成功"); Service.Standard.ChannelApi.VE.Api api = new Service.Standard.ChannelApi.VE.Api(_order_OrderPrintQtyRepository); foreach (var item in boxGroupChannelId) { var tempBox = item.ToList(); var result = await api.XYYPushBoxInfo(channel.Where(x => x.Id == item.Key).FirstOrDefault(), tempBox); if (result != null && result.Count > 0) { results.AddRange(result); //有失败的数据 tempBox.RemoveAll(x => result.Select(y => y.BoxNumber).Contains(x.BoxNumber)); } if (tempBox != null && tempBox.Count() > 0) { //更新推送成功标识 await _unitOfWork.ExecuteAsync("update Logistics_Box set IsAMSPost=1 where Id in @id", new { id = tempBox.Select(x => x.Id) }); } } if (results != null && results.Count > 0) { tuple = Tuple.Create(false, string.Join(",\r\n", results.Select(x => x.ErrorMessage))); } return Ok(tuple); } public async Task DataUpload([FromBody] DataUploadRequest request) { return Ok(await _orderService.DataUpload(request.order, request.goods, request.channel, request.arg)); } // #region Api调试代码 // // 测试 DataUpload 接口后续 // public async Task TestDataUpload() // { // DataUploadRequest dataUploadRequest = new DataUploadRequest(); // int order_orderId = 208273236; // dataUploadRequest.order = (_unitOfWork.QueryBySqlAsync($"select *from Order_Order where Id={order_orderId}")).Result.FirstOrDefault(); // dataUploadRequest.goods = (_unitOfWork.QueryBySqlAsync($"select *from Order_OrderGoods where OrderId={order_orderId}")).Result.ToList(); // dataUploadRequest.channel = (_unitOfWork.QueryBySqlAsync("select *from Logistics_Channel where Id=122")).Result.FirstOrDefault(); // dataUploadRequest.arg = new ExtendArg(); // UploadResult data1 = new UploadResult(); // try // { // data1 = await _orderService.DataUpload(dataUploadRequest.order, dataUploadRequest.goods, dataUploadRequest.channel, dataUploadRequest.arg); // } // catch (Exception ex) // { // } // //测试 DrawPdfLabel 接口后续 // var baseApi = _baseApis.Where(x => x.ServiceName == dataUploadRequest.channel.ServiceCode).FirstOrDefault(); // try // { // var data2 = baseApi.DrawPdfLabel(data1, dataUploadRequest.channel, dataUploadRequest.order, dataUploadRequest.goods); // return Ok(data2); // } // catch (Exception ex) // { // throw ex; // } // } public async Task AutoCancelOrder() { string sql = @"select a.Id,a.OrderId Order_OrderId,a.TrackingNumber,a.SystemNo,b.ServiceCode,b.PublicName,b.ApiHost,b.ApiKey,b.ApiSecret,a.ServicesOrderNo,a.ServiceOrderNumber3 from Logistics_RepleatChannelRecord a join Logistics_Channel b on b.Id=a.ChannelId where a.CancelState=0 union select a.Id,a.OrderId Order_OrderId,a.TrackingNumber,a.SystemNo,b.ServiceCode,b.PublicName,b.ApiHost,b.ApiKey,b.ApiSecret,a.ServicesOrderNo,a.ServiceOrderNumber3 from Logistics_RepleatChannelRecord a join Logistics_Channel b on b.Id=a.ChannelId where a.CancelState=500 and ExecutionCount<3 "; List logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync(sql)).ToList(); foreach (var item in logistics_ChannelCancels) { try { var baseApi = _baseApis.Where(x => x.ServiceName == item.ServiceCode).FirstOrDefault(); await baseApi.CannelOrdersByModel(item); item.UpdateTime = DateTime.Now; item.ResultState = ResultStateEnum.成功.GetValue(); item.ResultMessage = "成功"; } catch (Exception ex) { if (ex is NotImplementedException) { item.ResultState = ResultStateEnum.成功.GetValue(); item.ResultMessage = ex.Message; } else { item.ResultState = ResultStateEnum.异常.GetValue(); item.ResultMessage = ex.Message; } continue;//异常进行下一个,记录以数据表为准 } } //对数据做批量更新 string updateSql = " Update Logistics_RepleatChannelRecord set CancelState=@ResultState,ExecutionCount=ExecutionCount+1,ResultMessage=@ResultMessage where Id =@Id "; await _unitOfWork.ExecuteAsync(updateSql, logistics_ChannelCancels); return Ok(); } public async Task TestGetLabel() { //XYY.Service.Standard.ChannelApi.WeaShip.Api api = new Service.Standard.ChannelApi.WeaShip.Api(null); //byte[] data = await api.DrawPdfLabel(new UploadResult { ServiceOrderNumber = "WEAIT1092000002YQ" }, // _channelService.CacheGetAllChannel().Result.ToList().First(x => x.Id == 637), null, null); //System.IO.File.WriteAllBytes(@"E:\1.pdf", data); return Ok(); } //测试 CannelOrdersByModel public async Task TestCannelOrdersByModel(List SysmteNos) { string sql = @$"select a.Id Order_OrderId,a.TrackingNumber,a.SystemNo,b.ServiceCode,b.PublicName,b.ApiHost,b.ApiKey,b.ApiSecret,28256 OperationUserId,'{DateTime.Now}' CreateTime,'刘正凯' CreateUserName,'刘正凯' UpdateUserName,a.ServicesOrderNo,a.ServiceOrderNumber3 from Order_Order a join Logistics_Channel b on b.Id=a.ChannelId where a.SystemNo in @SystemNo or a.TrackingNumber in @SystemNo or a.TransferNumber in @SystemNo ";//小于三或者等于四,才可以取消 List logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync(sql, null, new { SystemNo = SysmteNos })).ToList(); foreach (var item in logistics_ChannelCancels) { try { var baseApi = _baseApis.Where(x => x.ServiceName == item.ServiceCode).FirstOrDefault(); await baseApi.CannelOrdersByModel(item); item.UpdateTime = DateTime.Now; } catch (Exception ex) { item.ResultState = ResultStateEnum.异常.GetValue(); item.ResultMessage = ex.Message; continue;//异常进行下一个,记录以数据表为准 } } return Ok(); } // #endregion public async Task DrawPdfLabel(DrawPdfLabelRequest request) { return Ok(await _orderService.DrawPdfLabel(request.result, request.channel, request.order, request.goods)); } public async Task AsyncServiceTrackingNumber(int qty) { return Ok(await _orderService.AsyncServiceTrackingNumber(qty)); } public class CancenOrderDto { public List SysmteNos { get; set; } } public async Task CancelOrders(CancenOrderDto cancenOrderDto) { var c = await _ChannelRepository.GetAsync(398); await _orderService.CancelOrders(cancenOrderDto.SysmteNos, c); return Ok(); } public async Task CancelOrdersByNoStr(CancenOrderDto cancenOrderDto) { cancenOrderDto.SysmteNos.RemoveAll(x => string.IsNullOrEmpty(x)); await _mQManager.Publish( new CancelOrderJobMessage { SysmteNos = cancenOrderDto.SysmteNos, UserId = _unitOfWork.CurrentId ?? 0, UserName = _unitOfWork.CurrentName, CreateTime = DateTime.Now }, null); //await _orderService.CancelOrdersByNoStr(cancenOrderDto.SysmteNos); var returnList = await _orderService.GetPackingOrderId(cancenOrderDto.SysmteNos); return Ok(returnList); } public async Task AddZZEUBOrder(string ladingNumber) { await _mQManager.Publish(new AddHNJobMessage { LadingNumber = ladingNumber }, null); return Ok(); } public async Task GetZZEUBOrder(string ladingNumber) { var data = await _orderService.GetZZESBUpdateData(ladingNumber); return Ok(data); } public async Task OrderDeclare(List orders) { string batchNo = DateTime.Now.ToString("CAyyyyMMddHHmmss"); XYY.Service.Standard.ChannelApi.UBI.Api api = new Service.Standard.ChannelApi.UBI.Api(null); int batchQty = 40; int qty = (int)Math.Ceiling(orders.Count() / 40.0); var channel = await _ChannelRepository.GetAsync(581); int start = 5; List bagDeclareErros = new List(); for (int i = 0; i < qty; i++) { string boxNumber = "Box" + batchNo + (start + i + 1); var declareList = orders.Skip(i * 40).Take(40).ToList(); var err = await api.Declare(declareList.Select(x => x.TrackingNumber).ToList(), declareList.Sum(y => y.ActualWeight.Value) / 1000.0m, batchNo, boxNumber, channel.ServiceChannelCode, channel); bagDeclareErros.AddRange(err); } return Ok(bagDeclareErros); } /// /// /// /// /// [ActionName("ConfimOrders")] public async Task ConfimOrders(int qty = 100) { List cq = new List(); await _orderService.OrderConfim(qty); return Ok(); } [HttpPost] [AllowAnonymous] public async Task ConfimChannelOrders(ConfimChannelOrderParam param) { List numbers = param.TrackingNumbers; string channelServiceCode = param.ChannelServiceCode; await _orderService.ConfimChannelOrders(numbers, channelServiceCode); return Ok(); } [HttpPost] [AllowAnonymous] public async Task ConfimChannelOrdersByBox(ConfimChannelOrderParamByBox param) { List boxIds = param.BoxIds; await _orderService.ConfimChannelOrdersByBox(boxIds); return Ok(); } [ActionName("BagConfim")] public async Task BagConfim() { await _orderService.BagConfim(); return Ok(); } [ActionName("BagConfimWithAwb")] [HttpGet] public async Task BagConfimWithAwb(string awb) { await _orderService.BagConfimWithAwb(awb); return Ok(); } [HttpGet] [ActionName("BagConfimWithBoxNumber")] public async Task BagConfimWithBoxNumber(string boxNumber) { await _orderService.BagConfimWithBoxNumber(boxNumber); return Ok(); } [ActionName("CannelOrderByNumber")] public async Task CannelOrderByNumber(string systemNo) { List orders = new List { systemNo }; var data = await _orderService.CancelOrdersByNoStr(orders); return Ok(data); } public async Task TestConfimOrder() { XYY.Service.Standard.ChannelApi.IMG.Api api = new Service.Standard.ChannelApi.IMG.Api(); //await api.Confims(new List(), await _ChannelRepository.GetAsync(500)); return Ok(); } [ActionName("CustomerConfim")] public async Task CustomerConfim(int qty = 100) { await _orderService.CustomerConfim(qty); return Ok(); } /// /// 获取预报日志 /// /// /// public async Task GetBagDeclareLogs(QueryModel queryModel) { var result = await _orderService.GetBagDeclareLogs(queryModel); return Ok(result); } public class BagApiRequset { public string laddingBillNumber { get; set; } public string serviceCode { get; set; } } [HttpPost] /// /// 获取预报日志 /// /// /// public async Task GetBagDeclareError(BagApiRequset bagApiRequset) { var result = await _orderService.GetBagDeclareError(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode); return Ok(result); } [HttpPost] public async Task JTTest() { var api = new XYY.Service.Standard.ChannelApi.JiTu.Api(); var obj = new { customerid = "SJ00021560", country = "US" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj); var msg = api.Send("9e3e3ff4f1193880f3dc3527c6c68e19", "LangTian", json, "OBTAINTRANSPORT", "https://api.yl-scm.com/yunlu-order-web/baseData/baseDataAction!findTransportList.action"); return Ok(msg); } [HttpPost] /// /// 提单号重新申报 /// /// /// public async Task ReBagDeclare(BagApiRequset bagApiRequset) { await _orderService.ReBagDeclare(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode); return Ok(); } public async Task UpdateLoadOrder() { var filelist = (await Request.ReadFormAsync()).Files; if (filelist != null && filelist.Count > 0) { var file = filelist[0]; await _orderService.THInputOrder(file.OpenReadStream()); return Ok(); } else { return Error("请上传一个文件"); } } public async Task ImportPPXFba() { var filelist = (await Request.ReadFormAsync()).Files; if (filelist != null && filelist.Count > 0) { var file = filelist[0]; await _orderService.ImportPPXFba(file.OpenReadStream()); return Ok(); } else { return Error("请上传一个文件"); } } public async Task QueryOverCancelOrders(QueryModel queryModel) { return Ok(await _orderService.QueryOverCancelOrders(queryModel)); } [HttpPost] public async Task GetIBBagLabels(GetIBBagLabelParam param) { List boxIds = param.BoxIds; try { var labelDatas = await _orderService.GetIBBagLabel(boxIds); if (labelDatas == null) { return Error("获取大包面单失败,无面单数据,请查看记录"); } else if (labelDatas.Any(i => i.Success)) { var successLabels = labelDatas.Where(i => i.Success).Select(i => i.LabelContent); return Ok(successLabels); } else { string msg = string.Join(",", labelDatas.Select(i => i.Message)); return Ok($"获取大包面单全部失败,请查看记录:{msg}"); } } catch (Exception ex) { return Error($"获取大包面单失败:{ex.Message}"); } } public async Task CancelIBBagLabel(CancelIBBagLabelParam param) { await _orderService.CancelIBBagLabel(param.BoxIds); return Ok(); } [HttpPost] public async Task GetOrderPager(QueryModel queryModel) { var result = await _orderService.GetOrderPager(queryModel); return Ok(result); } [HttpPost] public async Task GetOrderQty(QueryModel qm) { var u = User.GetUserContent(); var first = qm.QueryParamer.Where(x => x.Filed == "OrderStatus").FirstOrDefault(); if (first != null) { qm.QueryParamer.Remove(first); } var list = await _orderService.GetOrderQty(qm); return Ok(list); } public async Task Get(int Id) { var result = await _orderService.Get(Id); return Ok(result); } public async Task GetCustomerDraftOrder(int id) { var order = await _orderService.GetCustomerDraftOrder(id); return Ok(order); } [AllowAnonymous] public async Task OutData(QueryModel queryModel) { var u = User.GetUserContent(); var list = await _orderService.GetCustomerOrderList(queryModel); var ms = new MSExcelHelper(); var data = ms.OutDataAsByte(list); var utc = DateTime.Now.ToFileTimeUtc(); return File($"{utc}.xlsx", data); } public class OutDataInfo : MSExcelClassMapping { public OutDataInfo() { Map(x => x.CustomerOrderNo).Name("客户单号"); Map(x => x.SaelOrderNo).Name("平台订单号"); Map(x => x.TrackingNumber).Name("服务商单号"); Map(x => x.TransferNumber).Name("行运易单号"); Map(x => x.ReceiverCountryCode).Name("国家/地区"); Map(x => x.CreateTime).Name("下单时间"); Map(x => x.ReceiveTime).Name("称重时间"); Map(x => x.CustomerWeight).Name("下单重"); Map(x => x.OPWeight).Name("计费重"); Map(x => x.Quantity).Name("件数"); Map(x => x.CFright).Name("预计费用"); Map(x => x.ChannelName).Name("产品名称"); Map(x => x.ReceiverName).Name("收件人"); Map(x => x.ReceiverState).Name("收件人省份"); Map(x => x.ReceiverCity).Name("收件人城市"); Map(x => x.ReceiverStreet).Name("收件人地址"); Map(x => x.House).Name("收件人门牌号"); Map(x => x.ReceiverZipCode).Name("收件人邮编"); Map(x => x.ReceiverPhone).Name("收件人电话"); Map(x => x.ioss).Name("含IOSS"); Map(x => x.LatestLogisticsStatus).Name("最新物流状态"); Map(x => x.LastMessage).Name("最新物流信息"); Map(x => x.LatestLogisticsTime).Name("最新物流时间"); } } [AllowAnonymous] [HttpPost] public async Task TestMps() { var mpsOrder = await _mpsService.Get(220222937, 0); if (mpsOrder == null) { return Ok(); } var orders = await _orderRepository.QueryAsync(i => i.CustomerOrderNo == mpsOrder.CustomerOrderNumber); var order = orders.FirstOrDefault(); var orderGoods = await _orderGoodsRepository.QueryAsync(i => i.OrderId == order.Id); var channel = await _ChannelRepository.GetAsync(493); ExtendArg arg = new ExtendArg { Order = mpsOrder }; var result = await _orderService.DataUpload(order, orderGoods.ToList(), channel, arg); return Ok(result); } [AllowAnonymous] [HttpPost] [HttpGet] public async Task TestWinitChangeWeight(string serviceNumber, int weight) { LMAApi lma = new LMAApi(_orderRepository); //throw new Exception(""); var result = lma.BagDeclare(new XYY.Model.Standard.Order.BagDeclareRequest { BatchDeclare = new Dictionary> { { "test",new List{ new XYY.Model.Standard.Order.BoxDetailItem{ ServiceNo = serviceNumber, ActualWeight = weight } } } } }); return Ok(result); } /// /// 订单确认 推送 /// /// 目前仅万邑通和派送翼有此服务 /// public async Task ChannelManifest([FromBody] DataUploadRequest request) { ApiJsonModel apiJsonModel = new ApiJsonModel(); var baseApi = _manifestApis.Where(x => x.ServiceName == request.channel.ServiceCode).FirstOrDefault(); if (baseApi == null) { apiJsonModel.code = System.Net.HttpStatusCode.InternalServerError; apiJsonModel.success = false; apiJsonModel.message = "订单对应的产品,未找到相关的API服务"; } else { try { string result = await baseApi.ManifestPush(new ManifestParam() { Order = request.order, Channel = request.channel }); apiJsonModel.code = System.Net.HttpStatusCode.OK; apiJsonModel.success = true; apiJsonModel.message = result; } catch (Exception ex) { apiJsonModel.code = System.Net.HttpStatusCode.InternalServerError; apiJsonModel.success = false; apiJsonModel.message = ex.Message; } } return Ok(apiJsonModel); } } }