You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

360 lines
22 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DSWeb.Common.DB;
using DSWeb.Common.Helper;
using DSWeb.Common.Model;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Quartz;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSWeb.Job.Common
{
public class TaskFangCangJob : IJob
{
private CommonDataContext commonData = new CommonDataContext();
private BookingDB bookingData = new BookingDB();
private OpTaskDataContext taskData = new OpTaskDataContext();
private ILog logger = LogManager.GetLogger("TaskFangCangJob");
private const string MqActionExchangeName = "djy.action";
private const string MqActionQueueName = "djy.action";
public void Execute(IJobExecutionContext context)
{
var todoList = commonData.BackgroundTaskCommon
.Where(t => t.Status == BackgroundTaskCommon.StatusCreate && t.Type == BackgroundTaskCommon.TypeBookingFangCang)
.OrderBy(t => t.CreateTime)
.Take(10)
.ToList();
if (todoList.Count > 0)
{
logger.Debug($"发现{todoList.Count}条待自动放舱的任务");
todoList.ForEach(t =>
{
t.Status = BackgroundTaskCommon.StatusDoing;
t.ExecuteCount++;
t.ExecuteTime = DateTime.Now;
});
commonData.SaveChanges();
foreach (var item in todoList)
{
var ordno = item.ParamData.ToString();
var order = bookingData.Orders.AsNoTracking().FirstOrDefault(o => o.ORDNO == ordno);
var typeBC = OpTaskType.BC.ToString();
var task = taskData.OpTasks.FirstOrDefault(t => t.RelativeId == ordno && t.TASKTYPE == typeBC);
if (order == null)
{
var msg = $"订舱信息未找到:{ordno}";
logger.Error(msg);
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = msg;
commonData.SaveChanges();
continue;
}
if (task == null)
{
var msg = $"BC任务信息未找到{order.MBLNO}";
logger.Error(msg);
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = msg;
commonData.SaveChanges();
continue;
}
var paraFC = commonData.ParamValues.AsNoTracking().FirstOrDefault(x => x.CompId == order.CORPID && x.ParaCode == "AUTO_FANGCANG");
if (paraFC == null || paraFC.ItemCode != "YES")
{
var msg = $"所属公司配置为非自动放舱,不执行自动放舱:{order.MBLNO}";
logger.Error(msg);
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = msg;
commonData.SaveChanges();
continue;
}
var ctns = bookingData.Ctns.AsNoTracking().Where(c => c.ORDNO == ordno).ToList();
//尝试自动放舱
var letter = bookingData.LetterYard.AsNoTracking().FirstOrDefault(l => l.ORDNO == order.ORDNO);
if (letter == null)
{
var user = commonData.Users.AsNoTracking().First(u => u.GID == order.USERID);
var userbase = commonData.UserBases.AsNoTracking().First(ub => ub.USERID == user.GID);
var userCompany = commonData.CompanyNew.AsNoTracking().FirstOrDefault(c => c.CompId == user.CompId);
if (userCompany != null)
{
letter = new OP_SEAE_ORDER_LETTER_YARD();
List<string> emailList = null;
var paraFangCangRec = commonData.ParamValues.AsNoTracking().FirstOrDefault(x => x.ParaCode == "FANGCANG_REC_MAIL_USER" && x.CompId == user.CompId);
if (paraFangCangRec != null && paraFangCangRec.ItemCode == "OP")
{
logger.Debug($"{userCompany.CompName}自动放舱发送给操作,提单号:{order.MBLNO}");
emailList = new List<string>();
emailList.Add(userbase.EMAIL1);
}
else
{
logger.Debug($"{userCompany.CompName}自动放舱发送给客户,提单号:{order.MBLNO}");
//带入联系人客户
emailList = bookingData.Persons.AsNoTracking().Where(p => p.TYPE == "客户" && p.ORDNO == ordno && p.EMAIL != null && p.EMAIL.Length > 0 && p.IS_BC).Select(p => p.EMAIL).ToList();
emailList = MailAddrSplitDistinctHelper.SplitDistinct(emailList);
}
if (emailList.Count > 0)
{
letter.TO = string.Empty;
letter.ATTN = string.Empty;
letter.ATTN_TEL = string.Empty;
letter.ATTN_MAIL = string.Join(";", emailList);
//当前人带入到from
letter.FROM = user.SHOWNAME;
letter.FROM_TEL = userbase.OFFICEPHONE;
letter.FROM_MAIL = userbase.EMAIL1;
//货描
letter.DESCRIPTION = order.DESCRIPTION;
letter.ORDNO = order.ORDNO;
letter.GID = Guid.NewGuid().ToString();
letter.CREATE_TIME = DateTime.Now;
letter.CREATE_USER = user.GID;
bookingData.LetterYard.Add(letter);
//检查亿通账号
var accType = AccountConfigType.YitongWeb.ToString();
var accCfg = commonData.AccountConfigs.AsNoTracking().FirstOrDefault(x => x.Type == accType && x.UserId == order.USERID);
if (accCfg == null)
{
task.ExtData = "亿通账号未正确配置";
logger.Error($"自动放舱失败:{order.MBLNO},亿通账号未正确配置");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
//场站转换
CodeYardDataSet yardset = commonData.YardDataSet.AsNoTracking().FirstOrDefault(y => y.YARD == order.YARD);
if (yardset == null)
{
task.ExtData = "场站代号未找到";
logger.Error($"自动放舱失败:{order.MBLNO},场站代号未找到");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
//校验箱子数据录入
if (ctns.Where(c => string.IsNullOrEmpty(c.CTNALL) || !c.CTNNUM.HasValue).Count() > 0)
{
task.ExtData = "所有箱型箱量信息必须录入完整";
logger.Error($"自动放舱失败:{order.MBLNO},所有箱型箱量信息必须录入完整");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
//生成提箱小票链接
var paraTxCall = commonData.ParamSets.AsNoTracking().First(x => x.PARAMNAME == "bookingTixiangUrl"); //提箱小票的调用服务地址
var postObj = new
{
SystemCode = "djy",
CarrierCode = order.CARRIERID,
billOrderId = order.ORDNO,
sendOrderCode = order.MBLNO,
userId = order.USERID,
customerId = order.CUSTOMERID,
// userName = currUser.CODENAME,
//userPassword = currUser.PASSWORD,
operatorName = user.SHOWNAME,
depotCode = yardset.YitongCode,
depotName = yardset.YitongName,
AgentName = userCompany.CompName,
linkName = user.SHOWNAME,
linkMobile = userbase.OFFICEPHONE,
CustomerName = $"{user.COMNAME}+{user.SHOWNAME}", //公司名称+用户姓名
memo = string.Empty,
boxInfo = ctns.Select(c => new
{
boxType = c.CTNALL == "20GP" ? "20ST" : c.CTNALL == "40GP" ? "40ST" : c.CTNALL,
boxCount = c.CTNNUM.Value
}),
sysLoginName = accCfg.Account,
sysPsssword = accCfg.Password
};
string strPostObj = JsonConvert.SerializeObject(postObj);
logger.Debug($"调用提箱小票接口传递数据:{strPostObj}");
var strResp = WebRequestHelper.DoPost(paraTxCall.PARAMVALUE, strPostObj);
logger.Debug($"调用提箱小票接口返回:{strResp}");
var jobjResp = JObject.Parse(strResp);
int respCode = Convert.ToInt32(jobjResp.GetValue("code"));
if (respCode != 200)
{
var msg = jobjResp.GetValue("message").ToString();
task.ExtData = msg;
logger.Error($"自动放舱失败:{order.MBLNO},调用提箱小票接口返回:{msg}");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
letter.TixiangUrl = jobjResp.GetValue("data").ToString();
logger.Debug($"自动放舱调用提箱小票成功:{order.MBLNO}");
bookingData.SaveChanges(); //保存数据随后调用大简云进行pdf生成和放舱操作
#region 记录动作
var mqSendObj = new DjyActionLog()
{
ModuleName = EActionModule.Booking.ToString(),
ActionType = EActionType.GenTxxpLink.ToString(),
ActionCate = string.Empty,
SourceOp = "自动放舱生成提箱小票链接",
ActionTime = DateTime.Now,
Carrier = "CMA",
IsAuto = true,
UserId = order.USERID,
UserName = order.INPUTBY,
CompId = order.CORPID,
CompName = order.CompName,
MBLNO = order.MBLNO,
RelativeId = order.ORDNO,
CtrnNO = string.Empty,
Remark = string.Empty,
ExtData = string.Empty
};
var strSendObj = JsonConvert.SerializeObject(mqSendObj);
try
{
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(ConfigurationManager.AppSettings["ActionLogMQUri"]);
using (IConnection conn = factory.CreateConnection())
{
IModel mqModel = conn.CreateModel();
mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct);
mqModel.QueueDeclare(MqActionQueueName, false, false, false, null);
mqModel.QueueBind(MqActionQueueName, MqActionExchangeName, MqActionQueueName, null);
byte[] messageBodyBytes = Encoding.UTF8.GetBytes(strSendObj);
IBasicProperties props = mqModel.CreateBasicProperties();
props.DeliveryMode = 2;
mqModel.BasicPublish(MqActionExchangeName,
MqActionQueueName, props,
messageBodyBytes);
}
}
catch (Exception ex)
{
logger.Error($"发送动作日志出错,参数对象:{strSendObj}");
logger.Error(ex.Message);
logger.Error(ex.StackTrace);
}
#endregion
var paraMyshippingUrlService = commonData.ParamSets.AsNoTracking().FirstOrDefault(p => p.PARAMNAME == "bookingWebUrlCMA");
if (paraMyshippingUrlService == null || string.IsNullOrEmpty(paraMyshippingUrlService.PARAMVALUE))
{
task.ExtData = "大简云地址未正确配置";
logger.Error($"自动放舱失败:{order.MBLNO},大简云地址未正确配置");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
var myshippingUrl = paraMyshippingUrlService.PARAMVALUE.Trim();
if (!myshippingUrl.EndsWith("/"))
{
myshippingUrl += "/";
}
try
{
var rtn = WebRequestHelper.DoPost($"{myshippingUrl}booking/SendYard?lid=" + letter.GID, "");
logger.Debug($"调用大简云放舱返回:{rtn}");
var rtnObj = JsonConvert.DeserializeAnonymousType(rtn, new { Success = false, Message = "" });
if (!rtnObj.Success)
{
task.ExtData = rtnObj.Message;
logger.Error($"自动放舱失败:{order.MBLNO},调用大简云放舱返回:{rtnObj.Message}");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
else
{
logger.Debug($"自动放舱全部成功:{order.MBLNO}");
task.TASKSTATUS = OpTaskStatus.Complete.ToString(); //任务状态完成
task.COMPLETETYPE = "自动";
task.COMPLETETIME = DateTime.Now;
item.Status = BackgroundTaskCommon.StatusSuccess;
}
}
catch (Exception ex)
{
task.ExtData = "放舱失败";
logger.Error(ex.Message);
logger.Error(ex.StackTrace);
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
}
}
}
}
}
}
else
{
task.ExtData = "无客户联系人邮箱,无法自动放舱!";
logger.Error($"自动放舱失败:{order.MBLNO},找不到客户联系人邮箱");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
}
else
{
task.ExtData = "找不到订舱所属公司";
logger.Error($"自动放舱失败:{order.MBLNO},找不到订舱所属公司");
item.Status = BackgroundTaskCommon.StatusFail;
item.ResultData = task.ExtData;
}
}
else
{
logger.Debug($"已有放舱信息,不进行自动放舱操作:{order.MBLNO}");
item.Status = BackgroundTaskCommon.StatusSuccess;
}
commonData.SaveChanges();
taskData.SaveChanges();
}
}
}
}
}