12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043 |
- 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<IBaseApi> _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<UploadResult> _dataUpdateLogger;
- private IEnumerable<IManifestApi> _manifestApis;
- public OrderController(IOrderService orderService, IMQManager mQManager, IUnitOfWork unitOfWork
- //, FiddlerClient fiddlerClient
- , IEnumerable<IBaseApi> 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<UploadResult> dataUpdateLogger, IUser_CustomerDeclarationsRepository customerDeclarationsRepository, IEnumerable<IManifestApi> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> 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<IActionResult> GetStreeReplate(List<String> souces)
- {
- List<StreeReplate> streeReplates = new List<StreeReplate>();
- 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<string> Details
- {
- get; set;
- }
- public string Port
- {
- get; set;
- }
- }
- public async Task<IActionResult> 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<XYY.Model.Standard.MpsOrder.Order_MpsOrderBox>
- {
- }
- }
- };
- 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<XYY.Model.Standard.MpsOrder.Order_MpsOrderGoods>
- {
- 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<SMPCP> cp = new List<SMPCP>();
- 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<SMPCR>(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<IActionResult> 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<IActionResult> AsyncCustomerLastTrackingNumber()
- {
- var s = await customerLazyService.AsyncLastTrackingNumber();
- return Ok(s);
- }
- public async Task<IActionResult> AsyncCustomerFirstESBTracking()
- {
- var e = await customerLazyService.AsyncFirstESBTracking();
- return Ok(e);
- }
- [AllowAnonymous]
- [HttpGet]
- public async Task<IActionResult> 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<IActionResult> TestOrderOperation()
- {
- var channel = await _unitOfWork.QueryBySqlAsync<Logistics_Channel>(" select top 100 * from Logistics_Channel(nolock) where Id=611 ");
- var order = await _unitOfWork.QueryBySqlAsync<Order_Order>(" select top 100 * from Order_Order(nolock) where Id=222712850 ");
- var goods = await _unitOfWork.QueryBySqlAsync<Order_OrderGoods>(" select * from Order_OrderGoods(nolock) where OrderId=222712850 ");
- var box = await _unitOfWork.QueryBySqlAsync<Logistics_Box>(" 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<IActionResult> testDeAddress()
- {
- var channel = (await _unitOfWork.QueryBySqlAsync<Logistics_Channel>(" select top 100 * from Logistics_Channel(nolock) where Id=683 ")).FirstOrDefault();
- var order = (await _unitOfWork.QueryBySqlAsync<Order_Order>(" select top 100 * from Order_Order(nolock) where Id=223713094 ")).FirstOrDefault();
- var goods = await _unitOfWork.QueryBySqlAsync<Order_OrderGoods>(" select * from Order_OrderGoods(nolock) where OrderId=223713094 ");
- //需要测试的地址
- var deAddres = await _unitOfWork.QueryBySqlAsync<dynamic>(" 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();
- }
- /// <summary>
- /// wms头程转运,推送ams箱子信息按钮,调用此方法
- /// </summary>
- /// <param name="boxId"></param>
- /// <returns></returns>
- public async Task<IActionResult> PushAMSBoxData(IEnumerable<int> boxId)
- {
- //渠道写死
- var channel = await _unitOfWork.QueryBySqlAsync<Logistics_Channel>(" select * from Logistics_Channel(nolock) where ServiceCode='VE' ");
- var box = await _unitOfWork.QueryBySqlAsync<AMSBox>($" 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<bool, string>(false, "箱子均不属于ams,或均已推送!请确认后提交!")); }
- var orders = await _unitOfWork.QueryBySqlAsync<Order_Order>(@" 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<BagDeclareErrosResult> results = new List<BagDeclareErrosResult>();
- Tuple<bool, string> tuple = new Tuple<bool, string>(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<bool, string>(false, string.Join(",\r\n", results.Select(x => x.ErrorMessage)));
- }
- return Ok(tuple);
- }
- public async Task<IActionResult> DataUpload([FromBody] DataUploadRequest request)
- {
- return Ok(await _orderService.DataUpload(request.order, request.goods, request.channel, request.arg));
- }
- // #region Api调试代码
- // // 测试 DataUpload 接口后续
- // public async Task<IActionResult> TestDataUpload()
- // {
- // DataUploadRequest dataUploadRequest = new DataUploadRequest();
- // int order_orderId = 208273236;
- // dataUploadRequest.order = (_unitOfWork.QueryBySqlAsync<Order_Order>($"select *from Order_Order where Id={order_orderId}")).Result.FirstOrDefault();
- // dataUploadRequest.goods = (_unitOfWork.QueryBySqlAsync<Order_OrderGoods>($"select *from Order_OrderGoods where OrderId={order_orderId}")).Result.ToList();
- // dataUploadRequest.channel = (_unitOfWork.QueryBySqlAsync<Logistics_Channel>("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<IActionResult> 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_ChannelCancel> logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync<logistics_ChannelCancel>(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<IActionResult> 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<IActionResult> TestCannelOrdersByModel(List<string> 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_ChannelCancel> logistics_ChannelCancels = (await _unitOfWork.QueryBySqlAsync<logistics_ChannelCancel>(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<IActionResult> DrawPdfLabel(DrawPdfLabelRequest request)
- {
- return Ok(await _orderService.DrawPdfLabel(request.result, request.channel, request.order, request.goods));
- }
- public async Task<IActionResult> AsyncServiceTrackingNumber(int qty)
- {
- return Ok(await _orderService.AsyncServiceTrackingNumber(qty));
- }
- public class CancenOrderDto
- {
- public List<string> SysmteNos
- {
- get; set;
- }
- }
- public async Task<IActionResult> CancelOrders(CancenOrderDto cancenOrderDto)
- {
- var c = await _ChannelRepository.GetAsync(398);
- await _orderService.CancelOrders(cancenOrderDto.SysmteNos, c);
- return Ok();
- }
- public async Task<IActionResult> CancelOrdersByNoStr(CancenOrderDto cancenOrderDto)
- {
- cancenOrderDto.SysmteNos.RemoveAll(x => string.IsNullOrEmpty(x));
- await _mQManager.Publish<CancelOrderJobMessage>(
- 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<IActionResult> AddZZEUBOrder(string ladingNumber)
- {
- await _mQManager.Publish(new AddHNJobMessage { LadingNumber = ladingNumber }, null);
- return Ok();
- }
- public async Task<IActionResult> GetZZEUBOrder(string ladingNumber)
- {
- var data = await _orderService.GetZZESBUpdateData(ladingNumber);
- return Ok(data);
- }
- public async Task<IActionResult> OrderDeclare(List<Order_Order> 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<BagDeclareErrosResult> bagDeclareErros = new List<BagDeclareErrosResult>();
- 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);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="channelId"></param>
- /// <returns></returns>
- [ActionName("ConfimOrders")]
- public async Task<IActionResult> ConfimOrders(int qty = 100)
- {
- List<OrderConfimResult> cq = new List<OrderConfimResult>();
- await _orderService.OrderConfim(qty);
- return Ok();
- }
- [HttpPost]
- [AllowAnonymous]
- public async Task<IActionResult> ConfimChannelOrders(ConfimChannelOrderParam param)
- {
- List<string> numbers = param.TrackingNumbers;
- string channelServiceCode = param.ChannelServiceCode;
- await _orderService.ConfimChannelOrders(numbers, channelServiceCode);
- return Ok();
- }
- [HttpPost]
- [AllowAnonymous]
- public async Task<IActionResult> ConfimChannelOrdersByBox(ConfimChannelOrderParamByBox param)
- {
- List<int> boxIds = param.BoxIds;
- await _orderService.ConfimChannelOrdersByBox(boxIds);
- return Ok();
- }
- [ActionName("BagConfim")]
- public async Task<IActionResult> BagConfim()
- {
- await _orderService.BagConfim();
- return Ok();
- }
- [ActionName("BagConfimWithAwb")]
- [HttpGet]
- public async Task<IActionResult> BagConfimWithAwb(string awb)
- {
- await _orderService.BagConfimWithAwb(awb);
- return Ok();
- }
- [HttpGet]
- [ActionName("BagConfimWithBoxNumber")]
- public async Task<IActionResult> BagConfimWithBoxNumber(string boxNumber)
- {
- await _orderService.BagConfimWithBoxNumber(boxNumber);
- return Ok();
- }
-
- [ActionName("CannelOrderByNumber")]
- public async Task<IActionResult> CannelOrderByNumber(string systemNo)
- {
- List<string> orders = new List<string> { systemNo };
- var data = await _orderService.CancelOrdersByNoStr(orders);
- return Ok(data);
- }
- public async Task<IActionResult> TestConfimOrder()
- {
- XYY.Service.Standard.ChannelApi.IMG.Api api = new Service.Standard.ChannelApi.IMG.Api();
- //await api.Confims(new List<string>(), await _ChannelRepository.GetAsync(500));
- return Ok();
- }
- [ActionName("CustomerConfim")]
- public async Task<IActionResult> CustomerConfim(int qty = 100)
- {
- await _orderService.CustomerConfim(qty);
- return Ok();
- }
- /// <summary>
- /// 获取预报日志
- /// </summary>
- /// <param name="queryModel"></param>
- /// <returns></returns>
- public async Task<IActionResult> 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]
- /// <summary>
- /// 获取预报日志
- /// </summary>
- /// <param name="queryModel"></param>
- /// <returns></returns>
- public async Task<IActionResult> GetBagDeclareError(BagApiRequset bagApiRequset)
- {
- var result = await _orderService.GetBagDeclareError(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode);
- return Ok(result);
- }
- [HttpPost]
- public async Task<IActionResult> 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]
- /// <summary>
- /// 提单号重新申报
- /// </summary>
- /// <param name="laddingBillNumber"></param>
- /// <returns></returns>
- public async Task<IActionResult> ReBagDeclare(BagApiRequset bagApiRequset)
- {
- await _orderService.ReBagDeclare(bagApiRequset.laddingBillNumber, bagApiRequset.serviceCode);
- return Ok();
- }
- public async Task<IActionResult> 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<IActionResult> 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<IActionResult> QueryOverCancelOrders(QueryModel queryModel)
- {
- return Ok(await _orderService.QueryOverCancelOrders(queryModel));
- }
- [HttpPost]
- public async Task<IActionResult> GetIBBagLabels(GetIBBagLabelParam param)
- {
- List<int> 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<IActionResult> CancelIBBagLabel(CancelIBBagLabelParam param)
- {
- await _orderService.CancelIBBagLabel(param.BoxIds);
- return Ok();
- }
- [HttpPost]
- public async Task<IActionResult> GetOrderPager(QueryModel queryModel)
- {
- var result = await _orderService.GetOrderPager(queryModel);
- return Ok(result);
- }
- [HttpPost]
- public async Task<IActionResult> 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<IActionResult> Get(int Id)
- {
- var result = await _orderService.Get(Id);
- return Ok(result);
- }
- public async Task<IActionResult> GetCustomerDraftOrder(int id)
- {
- var order = await _orderService.GetCustomerDraftOrder(id);
- return Ok(order);
- }
- [AllowAnonymous]
- public async Task<IActionResult> OutData(QueryModel queryModel)
- {
- var u = User.GetUserContent();
- var list = await _orderService.GetCustomerOrderList(queryModel);
- var ms = new MSExcelHelper();
- var data = ms.OutDataAsByte<OutDataInfo, CustomerOrder>(list);
- var utc = DateTime.Now.ToFileTimeUtc();
- return File($"{utc}.xlsx", data);
- }
- public class OutDataInfo : MSExcelClassMapping<CustomerOrder>
- {
- 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<IActionResult> 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<IActionResult> 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<string, List<XYY.Model.Standard.Order.BoxDetailItem>>
- {
- { "test",new List<XYY.Model.Standard.Order.BoxDetailItem>{
- new XYY.Model.Standard.Order.BoxDetailItem{ ServiceNo = serviceNumber, ActualWeight = weight
- } }
- }
- }
- });
- return Ok(result);
- }
- /// <summary>
- /// 订单确认 推送
- /// </summary>
- /// <remarks>目前仅万邑通和派送翼有此服务</remarks>
- /// <returns></returns>
- public async Task<IActionResult> 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);
- }
- }
- }
|