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.

2348 lines
117 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using djy.Paas.IService;
using Ys.Core.Common;
using djy.Model;
using djy.Paas.Model;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Text.Json;
using Hangfire;
using AutoMapper;
using djy.Paas.Model.Dto;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Drawing.Imaging;
using System.Threading;
namespace djy.Paas.Service
{
/// <summary>
///
/// </summary>
public class BaoguanService : ServBase<tb_BaoGuanOrderList, tb_BaoGuanOrderList>, IBaoguanService
{
/// <summary>
/// 字典数据
/// </summary>
private List<tb_sys_Dictionary> _dictlist = new List<tb_sys_Dictionary>();
public BaoguanService(string dbname = DbList.djypublicedb) : base(dbname)
{
_dictlist = DbBus.Get(DbList.djypublicedb).Select<tb_sys_Dictionary>().Where(w => w.DictType == "dict").ToList();
}
#region api接口
/// <summary>
/// 条件查询报关单数据
/// </summary>
/// <param name="Dto"></param>
/// <param name="apiFrom"></param>
/// <returns></returns>
public async Task<ReturnPagedResult<tb_BaoGuanOrderList>> GetBaoguanOrderList(tb_BaoGuanOrderList Dto, ApiFromDto apiFrom)
{
var rs = new ReturnPagedResult<tb_BaoGuanOrderList>();
apiFrom.EndTimeAddDay();
var sql = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.Status > 0)
.WhereIf(apiFrom.StartTime > 0, w => w.AddTime >= apiFrom.StartTime)
.WhereIf(apiFrom.EndTime > 0, w => w.AddTime <= apiFrom.EndTime)
.WhereIf(Dto.Gid != null, w => w.Gid == Dto.Gid)
.WhereIf(Dto.stateCode.IsNotNull(), w => w.stateCode != null && w.stateCode == Dto.stateCode)
.WhereIf(Dto.CompId != null, w => w.CompId == Dto.CompId)
.WhereIf(Dto.ClientName.IsNotNull(), w => w.ClientName.Contains(Dto.ClientName) || w.TradeName.Contains(Dto.ClientName))
.WhereIf(Dto.DeclareCustoms.IsNotNull(), w => w.DeclareCustoms.Contains(Dto.DeclareCustoms))
.WhereIf(Dto.TradeName.IsNotNull(), w => w.TradeName.Contains(Dto.TradeName))
.WhereIf(Dto.UniqueNumber.IsNotNull(), w => w.UniqueNumber.Length > 0 && Dto.UniqueNumber.Contains(w.UniqueNumber))
.WhereIf(Dto.IEFlag.IsNotNull(), w => w.IEFlag == Dto.IEFlag)
.WhereIf(Dto.CompName.IsNotNull(), w => w.CompName.Contains(Dto.CompName))
.WhereIf(Dto.ShipOrderNo.IsNotNull(), w => w.ShipOrderNo.Contains(Dto.ShipOrderNo) || w.ShipOrderNoMain.Contains(Dto.ShipOrderNo));
rs.Data = await sql.OrderByDescending(w => w.AddTime).Count(out var totalcount).Page(apiFrom.Page, apiFrom.Limit).ToListAsync();
rs.Pageset(apiFrom, totalcount);
rs.OK();
return rs;
}
/// <summary>
///报关审核保存
/// </summary>
/// <param name="Dto"></param>
/// <returns></returns>
public async Task<ReturnResult<string>> OrderCheck(tb_BaoGuanOrderList Dto)
{
var rs = new ReturnResult<string>();
var order = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.Gid == Dto.Gid).ToOne();
if (order == null)
{
rs.Not("非法操作没有此报关单");
return rs;
}
order.CustomersCheck = Dto.CustomersCheck;
await DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().SetSource(order).UpdateColumns(w => w.CustomersCheck).ExecuteAffrowsAsync();
rs.OK();
return rs;
}
/// <summary>
/// 绑定客户信息
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
public async Task<ReturnResult<int>> BindClient(ClientLinkInfoDto dto)
{
var rs = new ReturnResult<int>();
//if (!dto.Email.IsEmail())
//{
// rs.Not("要绑定的数据信息不正确");
// return rs;
//}
var order = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.Gid == dto.DataGid).ToOne();
//order.ClientName = dto.ClientName.IsNotNull() ? dto.ClientName : order.ClientName;
//order.ClientMain = dto.LinkName.IsNotNull() ? dto.LinkName : order.ClientMain;
//order.ClientEmail = dto.Email.IsNotNull() ? dto.Email : order.ClientEmail;
order.ClientName = dto.ClientName;
order.ClientMain = dto.LinkName;
order.ClientEmail = dto.Email;
_LogsAdd("报关客户绑定:" + order.UniqueNumber, "报关绑定", new { dto, order });
rs.Data = DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().SetSource(order).ExecuteAffrows();
if (dto.Email.IsNotNull() && dto.ClientName.IsNotNull())
{
//未绑定的一起绑定更新
var bangdinglist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.CompId == order.CompId && w.TradeName.Length > 0 && w.TradeName == order.TradeName && (w.ClientName == null || w.ClientName.Length == 0)).ToList(w => new { w.Id, w.Gid, w.UniqueNumber });
//var bangdinglist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.CompId == order.CompId && w.TradeName.Length > 0 && w.TradeName == order.TradeName && (w.ClientName!=dto.ClientName || w.ClientMain!=dto.LinkName || w.ClientEmail!=dto.Email)).ToList(w => new { w.Id, w.Gid, w.UniqueNumber });
var unidlist = "";
bangdinglist.ForEach(item =>
{
unidlist += $",{item.UniqueNumber}";
});
_LogsAdd("手动绑定触发更新:" + unidlist, "报关绑定", new { dto, order, bangdinglist });
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().Set(w => new tb_BaoGuanOrderList { ClientName = dto.ClientName, ClientMain = dto.LinkName, ClientEmail = dto.Email })
.Where(w => w.CompId == order.CompId && w.TradeName.Length > 0 && w.TradeName == order.TradeName && (w.ClientName == null || w.ClientName.Length == 0)).ExecuteAffrows();
//.Where(w =>w.CompId==order.CompId&& w.TradeName.Length > 0 && w.TradeName == order.TradeName && (w.ClientEmail.Length == 0 || w.ClientEmail == null)).ExecuteAffrows();
//.Where(w => w.CompId == order.CompId && w.TradeName.Length > 0 && w.TradeName == order.TradeName && (w.ClientName != dto.ClientName || w.ClientMain != dto.LinkName || w.ClientEmail != dto.Email)).ExecuteAffrows();
}
rs.OK();
return rs;
}
/// <summary>
/// 根据箱号获取报关箱体数据详情
/// </summary>
/// <param name="ContNoList"></param>
/// <returns></returns>
public async Task<ReturnResult<List<ContainerDto>>> GetContainerList(List<string> ContNoList)
{
var rs = new ReturnResult<List<ContainerDto>>();
if (ContNoList != null || ContNoList.Count > 0)
{
var contlist = await DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanContainer>().Where(w => w.Status == 1 && ContNoList.Contains(w.ContainerId)).ToListAsync<ContainerDto>();
var orderidlist = contlist.Select(w => w.BaoguanOrderGid).ToList();
var gidlist = contlist.Select(w => w.Gid).ToList();
var orderlist = await DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => orderidlist.Contains(w.Gid)).ToListAsync();
var goodslist = await DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanDecList>().Where(w => gidlist.Contains(w.ContainerGid)).ToListAsync();
contlist.ForEach(item =>
{
item.OrderInfo = orderlist.Where(w => w.Gid == item.BaoguanOrderGid).First();
item.GoodsList = goodslist.Where(w => w.ContainerGid == item.Gid).ToList();
});
rs.Data = contlist;
}
rs.OK();
return rs;
}
/// <summary>
/// 读取报关消息推送数据
/// </summary>
/// <returns></returns>
public ReturnResult<List<tb_BaoguanOrderCompanyPushMsg>> ReadCompanyPushMsg(Guid? CompanyGid)
{
var rs = new ReturnResult<List<tb_BaoguanOrderCompanyPushMsg>>();
rs.Data = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanOrderCompanyPushMsg>().Where(w => w.Status < 100 && w.CompanyGid == CompanyGid).OrderBy(w => w.Id).ToList();
//if (rs.Data.Count > 10) {
// rs.Data= rs.Data.Skip(0).Take(10).ToList();
//}
var idlist = rs.Data.Select(w => w.Id).ToList();
DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanOrderCompanyPushMsg>().Set(s => s.Status, 100).Where(s => idlist.Contains(s.Id)).ExecuteAffrows();
rs.OK();
return rs;
}
#endregion
#region 阿里云报关对接部分
/// <summary>
/// 阿里云apiHost
/// </summary>
private const string _aliapihost = @"http://gw.open.1688.com/openapi/";
///阿里云测试服务地址
//private const string _aliapihost = @"http://pre-gw.api.1688.com/openapi/";
/// <summary>
/// 生成的签名秘钥
/// </summary>
private const string _aliappsecretKey = @"YJwlNbSYPVe";
/// <summary>
/// 阿里用户数据回写请求 阿里请求我们
/// </summary>
/// <param name="Dto"></param>
/// <returns></returns>
public async Task<ReturnResult<string>> AliBack(ApiFromDto Dto)
{
var rs = new ReturnResult<string>();
//解析密文
var getjson = "";
var aliyunkey = DjyTools.GetConfigKey("bg_aliyunseckey");
try
{
getjson = Jose.JWT.Decode(Dto.Token, Encoding.UTF8.GetBytes(aliyunkey), Jose.JweAlgorithm.PBES2_HS512_A256KW, Jose.JweEncryption.A256CBC_HS512);
_LogsAdd("baoguan阿里报关用户数据回写", "报关", getjson);
long aliid = 0;
var jsondata = YsJson.DeserializeAnonymousType(getjson, new { openUserId = "", aliId = aliid, companyid = 0 });
var user = DbBus.Get(DbList.djyolddb).Select<User>().Where(w => w.GID == jsondata.openUserId).ToOne();
if (user != null)
{
//更新绑定到user
DbBus.Get(DbList.djyolddb).Update<User>().Set(w => w.BaoguanAliId, jsondata.aliId.ToString()).Where(w => w.GID == jsondata.openUserId).ExecuteAffrows();
//更新绑定到公司
DbBus.Get(DbList.djyolddb).Update<CompanyNew>().Set(w => w.AliCompanyId, jsondata.companyid).Where(w => w.CompId == user.CompId && w.AliCompanyId == 0).ExecuteAffrows();
}
}
catch (Exception ex)
{
}
_LogsAdd("报关阿里回馈", "baoguan", new { Dto.Token, getjson });
rs.OK("接收成功");
return rs;
}
#region 阿里云报关对接
/// <summary>
/// 报关自动接收数据生成同步报关单数据job
/// </summary>
/// <returns></returns>
public async Task<ReturnResult<int>> AutoAllibonBaoguanJob(ApiFromDto UserDto)
{
var rs = new ReturnResult<int>();
///接收数据 1 接收 2 标记告诉阿里接收状态
await AliBaoguanrationlist();
//生成与更新报关单数据到本地 解析报关数据 单一窗口数据 下载报关附件文件 触发发送不同状态的Email 更新绑定报关订单数据 tb-baoguanorderlist
await AutoRunBaoguanOrder();
//仅用于测试重新下载附件
//await TestRedown();
//重试发送
await AutoSendMail();
rs.MemoData = UserDto;
rs.OK();
_LogsAdd($"报关全局刷新请求{UserDto.Name} {UserDto.UserId}", "报关", rs);
return rs;
}
/// <summary>
/// 发送指定的文件给客户
/// </summary>
/// <param name="Dto"></param>
/// <returns></returns>
public ReturnResult<string> EmailSend(ApiFromDto Dto)
{
var rs = new ReturnResult<string>();
var order = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.Gid == Dto.Gid).ToOne();
if (order == null)
{
rs.Not("错误的请求");
return rs;
}
var _newfilelist = order.FileList.Where(w => w.Name.Contains(Dto.FileName)).ToList();
if (_newfilelist.Count == 0)
{
rs.Not(Dto.FileName + "文件不存在!");
return rs;
}
if (!order.ClientEmail.IsEmail())
{
rs.Not("客户Email地址不正确");
return rs;
}
if (_newfilelist.Count > 0)
{
var _newfile = _newfilelist[_newfilelist.Count - 1];
var _mailbody = @"<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>" + _newfile.Name.Split('.')[0] + @"</title>
</head>
<body>
<div style='padding:0 20px;'>
<p style='color:#333;'>尊敬的" + order.ClientName + @",您好:</p>
<p style='color:#333;'>请确认报关单草稿并回复我们OK确认请查看附件谢谢</p>
<p style='color:#333;'>提单号:" + order.ShipOrderNo + @"</p>
<div>
<p style='color:#333;'>" + order.CompName + @"</p>
</div> </div></body> </html>";
var _userlist = DbBus.Get(DbList.djyolddb).Select<UserBaseinfo, CompanyNew>().LeftJoin((u, c) => u.USERID == c.AdminUser).Where((u, c) => c.CompId == order.CompId.ToString()).ToOne((u, c) => new { u.USERID, c.CompId, u.EMAIL1 });
var _sendmail = "";
if (_userlist != null)
{
_sendmail = _userlist.EMAIL1;
var _mailhostconfig = DbBus.Get(DbList.djyolddb).Select<MailUserAccount>().Where(w => w.UserId == _userlist.USERID).ToList();
}
var sendmail = new MailSendDto { FileList = new List<FileListDto> { _newfile }, DataKey = order.Gid.ToString() + "_" + order.UniqueNumber, SendEmail = _sendmail, Email = order.ClientEmail, MailBody = _mailbody, Title = _newfile.Name.Split('.')[0] };
if (_userlist != null)
{
var _mailconfig = DbBus.Get(DbList.djyolddb).Select<MailUserAccount>().Where(w => w.UserId == _userlist.USERID).ToOne();
if (_mailconfig != null)
{
sendmail.SendMailConfig = new Ys.Core.Common.Email.SendServerConfigurationEntity
{
SmtpHost = _mailconfig.SmtpServer,
SmtpPort = _mailconfig.SmtpPort,
SenderAccount = _mailconfig.MailAccount,
SenderPassword = _mailconfig.Password,
IsSsl = _mailconfig.SmtpSSL
};
sendmail.SendEmail = _mailconfig.MailAccount;
}
else
{
sendmail.MailBody = sendmail.MailBody.Replace("<body>", "<h3> 因您的大简云邮箱配置错误无法直接发送Email给客户,错误原因: 未配置,请登录大简云->个人中心->个人信息进行配置 </h3> <br> <h3> 客户Email为: " + sendmail.Email + " </h3>");
}
}
return _SendEmail(sendmail);
}
rs.OK();
return rs;
}
public const string = "BaoguanEmailSend";
/// <summary>
/// 自动根据阿里海关数据解出报关订单数据
/// </summary>
/// <returns></returns>
public async Task<ReturnResult<int>> AutoRunBaoguanOrder()
{
var rs = new ReturnResult<int>();
var topiclist = new List<string>() { "DraftDecStatus", "DeclarationAttachments", "CusDecInfo" };
var dblist = await DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanAliActionList>().Where(w => w.Status < 100 && topiclist.Contains(w.topic)).OrderBy(w => w.Id).ToListAsync();
var orderlist = new List<tb_BaoGuanOrderList>();//报关订单
var SendMailList = new List<MailSendDto>();//Email发送
var companylist = DbBus.Get(DbList.djyolddb).Select<djy.Model.CompanyNew>().Where(w => w.AliCompanyId > 0).ToList();
foreach (var item in dblist)
{
try
{
if (item.topic == "DraftDecStatus" || item.topic == "CusDecInfo" || item.topic == "DeclarationAttachments")//报关草稿状态
{
var data = YsJson.JsonToObject<AliBaoGuanOnetouchDataDto>(item.data);
if (data != null)
{
var comp = companylist.Where(w => w.AliCompanyId == item.companyId).FirstOrDefault();
var compid = Guid.Empty;
var compname = "";
if (comp != null)
{
compid = Guid.Parse(comp.CompId);
compname = comp.CompName;
}
var order = new tb_BaoGuanOrderList
{
OrderType = "ali"
,
UniqueNumber = item.uniqueNumber
,
AlSActionGid = item.Gid
,
AliCompanyId = item.companyId
,
CompId = compid
,
CompName = compname
,
ShipOrderNo = data.BillNo
,
Topic = item.topic,
stateCode = item.StateCode,
stateName = item.StateName,
ClientName = ""
};
//获取最新客户联系方式
//绑定客户 仅在【提交到单一窗口】时触发一次
//其它时候不做此操作 以减少访问数据库的次数
//if (item.topic == "CusDecInfo" && data.StateCode == "22")
//{
// _LogsAdd("海关报文解析" + order.UniqueNumber, "绑定客户", new { data });
// var linkinfo = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w =>
// w.AliCompanyId == order.AliCompanyId
// && w.TradeName == order.TradeName
// //&& w.ClientEmail.Length > 0
// ).OrderByDescending(w => w.Id).ToOne();
// if (linkinfo != null)
// {
// order.ClientName = linkinfo.ClientName;
// order.ClientMain = linkinfo.ClientMain;
// order.ClientEmail = linkinfo.ClientEmail;
// _LogsAdd("海关报文解析" + order.UniqueNumber, "绑定客户", new { order });
// }
//}
if (data.StateCode == "13")
{//海关查验时间
order.CheckTime = data.Date.ToTimestamp();
//创建Email发送委托
var _mailbody = @"海关查验";
SendMailList.Add(new MailSendDto { DataKey = item.uniqueNumber, MailBody = _mailbody, Title = "海关查验", Type = "13" });
}
if (data.StateCode == "14")
{
//海关放行触发发送邮件
SendMailList.Add(new MailSendDto { Type = "14", DataKey = item.uniqueNumber, Title = "海关放行" });
}
//item.topic == "CusDecInfo" &&
//20220301 海关报文改为状态11 海关入库 时发送,此时内容包括报关单号
if ((item.topic == "CusDecInfo" || data.StateCode == "11") && data.MessageContent.IsNotNull())//海关报文
{
var jsonstr = YsJson.XmlToJson(data.MessageContent.Base64ToString());
if (jsonstr.IsNotNull())
{
jsonstr = jsonstr.Replace("?", "").Replace("@", "");
_LogsAdd("海关报文解析" + order.UniqueNumber, "海关报文", new { order, jsonstr });
var cusdata = JsonSerializer.Deserialize<JsonElement>(jsonstr);
var customerdec = YsJson.DeserializeAnonymousType(cusdata.GetProperty("DecMessage").ToString(), new { DecSign = new AliBaoGuanCustomesDecSignDto(), DecHead = new AliBaoGuanCustomesDecHeadDto() });
if (customerdec != null)
{
//_LogsAdd("海关报文解析" + order.UniqueNumber, "海关报文", new { order, customerdec });
order.IEFlag = customerdec.DecHead.IEFlag.IsNull() ? "E" : customerdec.DecHead.IEFlag;
order.DeclareCustoms = customerdec.DecHead.CustomMaster;
order.CustomsMessage = jsonstr;
order.TradeName = customerdec.DecHead.TradeName;
//报关单号
//20220301 海关报文改为状态11 海关入库 时发送,此时内容包括报关单号
//order.CustomsNo = customerdec.DecHead.SeqNo;
//如有海关入库时才解析报关单号
if (data.StateCode == "11")
order.CustomsNo = customerdec.DecHead.EntryId;
order.TrafName = customerdec.DecHead.TrafName;
////获取最新客户联系方式
///改为如果ClientName有值 就不修改
if (!string.IsNullOrWhiteSpace(order.TradeName) && (order.ClientName == null || order.ClientName.Length == 0))
{
var linkinfo = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.AliCompanyId == order.AliCompanyId && w.TradeName == order.TradeName
&& (w.ClientName != null && w.ClientName.Length > 0)
//&& w.ClientEmail.Length > 0
).OrderByDescending(w => w.Id).ToOne();
_LogsAdd("海关报文解析" + order.UniqueNumber, "绑定客户", new { linkinfo });
if (linkinfo != null)
{
order.ClientName = linkinfo.ClientName;
order.ClientMain = linkinfo.ClientMain;
order.ClientEmail = linkinfo.ClientEmail;
}
}
}
}
}
if (item.topic == "DeclarationAttachments")
{//接收回执文件
var url = HttpHelp.FileDown(data.docUrl, "userdata/alibaoguanfile", item.uniqueNumber + "_" + data.docName).Result;
var flist = order.FileList;
var _newfile = new FileListDto { Name = data.docName, Url = url };
flist.Add(_newfile);
order.FileList = flist;
_LogsAdd("接收文件" + order.UniqueNumber, "报关file", order);
}
if (orderlist.Where(w => w.UniqueNumber == order.UniqueNumber).Count() > 0)
{//如果已存在则更新
foreach (var o in orderlist)
if (o.UniqueNumber == order.UniqueNumber)
{
o.ShipOrderNo = order.ShipOrderNo;
o.stateCode = order.stateCode.IsNotNull() ? order.stateCode : o.stateCode;
o.stateName = order.stateName.IsNotNull() ? order.stateName : o.stateName;
o.IEFlag = order.IEFlag.IsNotNull() ? order.IEFlag : o.IEFlag;
o.DeclareCustoms = order.DeclareCustoms.IsNotNull() ? order.DeclareCustoms : o.DeclareCustoms;
o.CheckTime = order.CheckTime > 0 ? order.CheckTime : o.CheckTime;
o.CustomsMessage = order.CustomsMessage.IsNotNull() ? order.CustomsMessage : o.CustomsMessage;
o.TrafName = order.TrafName.IsNotNull() ? order.TrafName : o.TrafName;
o.CustomsNo = order.CustomsNo.IsNotNull() ? order.CustomsNo : o.CustomsNo;
o.TradeName = order.TradeName.IsNotNull() ? order.TradeName : o.TradeName;
if (string.IsNullOrWhiteSpace(o.ClientName))
{
//如果已绑定 则不做修改 //如未绑定 才判断是否记录绑定数据
o.ClientName = order.ClientName.IsNotNull() ? order.ClientName : o.ClientName;
o.ClientMain = order.ClientMain.IsNotNull() ? order.ClientMain : o.ClientMain;
o.ClientEmail = order.ClientEmail.IsNotNull() ? order.ClientEmail : o.ClientEmail;
}
if (order.FileList.Count > 0)
{
var flist = o.FileList;
var namelist = flist.Select(w => w.Name).ToList();
List<FileListDto> nlist = order.FileList.Where(w => !namelist.Contains(w.Name)).ToList();
flist.AddRange(nlist);
o.FileList = flist;
}
break;
}
}
else
{
orderlist.Add(order);
}
}
}
}
catch (Exception ex)
{
}
}
//更新或插入
var alinumberlist = orderlist.Select(w => w.UniqueNumber).ToList();
var _shoporderlist = orderlist.Where(w => w.ShipOrderNo.IsNotNull()).Select(w => w.ShipOrderNo).ToList();
var datalist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => _shoporderlist.Contains(w.ShipOrderNo) || alinumberlist.Contains(w.UniqueNumber)).ToList();
var uplist = new List<tb_BaoGuanOrderList>();
var newlist = new List<tb_BaoGuanOrderList>();
// orderlist.ForEach(item => {
foreach (var item in orderlist)
{
var order = datalist.Where(w => w.UniqueNumber == item.UniqueNumber || (w.UniqueNumber.Length == 0 && w.ShipOrderNo == item.ShipOrderNo && w.ShipOrderNo.Length > 0)).FirstOrDefault();
if (order == null)
{
item.Init();
newlist.Add(item);
}
else
{
order.UniqueNumber = item.UniqueNumber.IsNotNull() ? item.UniqueNumber : order.UniqueNumber;
order.ShipOrderNo = item.ShipOrderNo.IsNotNull() ? item.ShipOrderNo : order.ShipOrderNo;
order.stateCode = item.stateCode.IsNotNull() ? item.stateCode : order.stateCode;
order.stateName = item.stateName.IsNotNull() ? item.stateName : order.stateName;
order.IEFlag = item.IEFlag.IsNotNull() ? item.IEFlag : order.IEFlag;
order.DeclareCustoms = item.DeclareCustoms.IsNotNull() ? item.DeclareCustoms : order.DeclareCustoms;
order.CheckTime = item.CheckTime > 0 ? item.CheckTime : item.CheckTime;
order.CustomsMessage = item.CustomsMessage.IsNotNull() ? item.CustomsMessage : order.CustomsMessage;
order.CustomsNo = item.CustomsNo.IsNotNull() ? item.CustomsNo : order.CustomsNo;
order.TradeName = item.TradeName.IsNotNull() ? item.TradeName : order.TradeName;
order.TrafName = item.TrafName.IsNotNull() ? item.TrafName : order.TrafName;
//联系信息在绑定过后不更新
if (item.ClientName.IsNotNull() && order.ClientName.IsNull())//order.ClientEmail.IsNull() &&
{
order.ClientName = item.ClientName;
order.ClientMain = item.ClientMain;
order.ClientEmail = item.ClientEmail;
_LogsAdd("自动绑定报关客户:" + order.UniqueNumber, "报关绑定", new { item, order });
}
//order.ClientName = item.ClientName.IsNotNull() ? item.ClientName : order.ClientName;
//order.ClientMain = item.ClientMain.IsNotNull() ? item.ClientMain : order.ClientMain;
//order.ClientEmail = item.ClientEmail.IsNotNull() ? item.ClientEmail : order.ClientEmail;
if (item.FileList.Count > 0)
{
var filist = order.FileList;
filist.AddRange(item.FileList);
order.FileList = filist;
}
if (item.CustomsMessage.IsNotNull())
{//如果原始单一报文发生改变则重新解析数据
order.ParseStatus = 1;
}
uplist.Add(order);
}
}
// });
//事务提交数据
DbBus.Get(DbList.djypublicedb).Transaction(() =>
{
if (uplist.Count > 0)
{
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().SetSource(uplist).ExecuteAffrows();
}
if (newlist.Count > 0)
{
var bangdinglist = newlist.Where(w => w.ClientEmail.IsNotNull()).ToList();
var bandinggidlist = "";
bangdinglist.ForEach(item => { bandinggidlist += $",{item.UniqueNumber}"; });
_LogsAdd("新建时绑定:" + bandinggidlist, "报关绑定", bangdinglist);
DbBus.Get(DbList.djypublicedb).Insert(newlist).ExecuteAffrows();
}
//更新状态
var _gidlist = dblist.Select(w => w.Gid).ToList();
DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanAliActionList>().Set(w => w.Status, 100).Where(w => _gidlist.Contains(w.Gid)).ExecuteAffrows();
});
//Email发送处理
if (sysOptionConfig.YsWebconfig.IsDev)
{
SendMailList = new List<MailSendDto>();
}
if (SendMailList.Count > 0)
{
//创建Email发送委托
var keylist = SendMailList.GroupBy(w => w.DataKey).Select(w => w.Key).ToList();
var _getorder = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => keylist.Contains(w.UniqueNumber)).ToList();
var baoguanhanggid = _getorder.GroupBy(w => w.CompId).Select(w => w.Key.Value.ToString()).ToList();
var _userlist = DbBus.Get(DbList.djyolddb).Select<UserBaseinfo, CompanyNew>().LeftJoin((u, c) => u.USERID == c.AdminUser).Where((u, c) => baoguanhanggid.Contains(c.CompId)).ToList((u, c) => new { u.USERID, c.CompId, u.EMAIL1 });
var _useridlist = _userlist.Select(w => w.USERID).ToList();
var _mailhostconfig = DbBus.Get(DbList.djyolddb).Select<MailUserAccount>().Where(w => _useridlist.Contains(w.UserId)).ToList();
foreach (var item in SendMailList)
{
var border = _getorder.Where(w => w.UniqueNumber == item.DataKey).FirstOrDefault();
//20220323 如果该绑定客户没有邮箱 则跳过
if (string.IsNullOrWhiteSpace(border.ClientEmail))
{
continue;
}
if (border != null)
{//获取接收Email
if (item.Type == "13")
{ //查验Email完善处理
var Mailbody = @"<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>海关查验 " + border.ShipOrderNo + " " + border.CustomsNo + @" </title>
</head>
<body>
<div style='padding:0 20px;'>
<p style='color:#333;'>尊敬的" + border.ClientName + @",您好:</p>
<p style='color:#333;'>你单位申报的报关单号,经审核现决定实施口岸检查,请联系港务等相关部门做好准备,并派员配合海关实施口岸检查。特此通知!</p>
<div>
<div style='padding:0 20px;'>
<p style='color:#333;'>检查关区:" + border.DeclareCustoms + @"</p>
<p style='color:#333;'>报关单号:" + border.CustomsNo + @"</p>
<p style='color:#333;'>提单号:" + border.ShipOrderNo + @"</p>
<p style='color:#333;'>运输工具:" + border.TrafName + @"</p>
</div>
<p style='color:#333;'>" + border.CompName + @"</p></div>
</div>
</body>
</html>";
item.MailBody = Mailbody;
item.Title = "海关查验" + border.ShipOrderNo;
}
if (item.Type == "14")
{
//加入Email发送队列
var _mailbody = @"<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>海关放行通知 " + border.ShipOrderNo + @"</title>
</head>
<body>
<div style='padding:0 20px;'>
<p style='color:#333;'>尊敬的" + border.ClientName + @",您好:</p>
<p style='color:#333;'>您的提单号为" + border.ShipOrderNo + @"海关已放行,报关单及放行条请查看附件,谢谢!</p>
<div>
<p style='color:#333;'>" + border.CompName + @"</p> </div>
</div>
</body>
</html>";
item.Title = "海关放行通知 " + border.ShipOrderNo;
item.MailBody = _mailbody;
var _flist = border.FileList.Where(w => w.Name.Contains("报关单") || w.Name.Contains("放行条")).ToList();
//20220309 逐个判断文件是否存在,
//如不存在 select * from tb_BaoguanAliActionList where uniquenumber='6743-0-4923' and topic='DeclarationAttachments'
//寻找这个文件的docname ,找到它对应的url 重新下载。
//foreach (var filedto in _flist)
//{
// var retrycount = 0;
// 重新下载文件(border, filedto.Name, ref retrycount);
//}
item.FileList = _flist;
}
item.Email = border.ClientEmail;
var _sml = _userlist.Where(w => w.CompId == border.CompId.ToString()).FirstOrDefault();
if (_sml != null)
{
var _mailconfig = _mailhostconfig.Where(w => w.UserId == _sml.USERID).FirstOrDefault();
item.SendEmail = _sml.EMAIL1;
if (_mailconfig != null)
{
item.SendMailConfig = new Ys.Core.Common.Email.SendServerConfigurationEntity
{
SmtpHost = _mailconfig.SmtpServer,
SmtpPort = _mailconfig.SmtpPort,
SenderAccount = _mailconfig.MailAccount,
SenderPassword = _mailconfig.Password,
IsSsl = _mailconfig.SmtpSSL
};
item.SendEmail = _mailconfig.MailAccount;
//20220317 如果此时没接收到附件 则将此项任务丢到redis的BaoguanEmailSend队列
if (item.Type == "14")
{
if (!item.())
{
item.border = border;
item.SendTime = DateTime.Now.AddMinutes(2);
DbRedis.LPush(, YsJson.ToJson(item));
continue;
}
else
{
var cansend = true;
foreach (var fileDto in item.FileList)
{
if (!File.Exists(fileDto.Url))
{
item.border = border;
item.SendTime = DateTime.Now.AddMinutes(1);
DbRedis.LPush(, YsJson.ToJson(item));
cansend = false;
continue;
}
}
if (!cansend) continue;
}
}
}
else
{
item.MailBody = item.MailBody.Replace("<body>", "<h3> 因您的大简云邮箱配置错误无法直接发送Email给客户,错误原因: 未配置,请登录大简云->个人中心->个人信息进行配置 </h3> <br> <h3> 客户Email为: " + item.Email + " </h3>");
}
}
}
else
{
item.Status = 0;
}
if (item.Status == 1)
{
BackgroundJob.Enqueue(() => _SendEmail(item));
}
}
}
rs.OK("成功");
return rs;
}
/// <summary>
/// 仅用于测试发送邮件时重新下载文件的测试
/// </summary>
public async Task<ReturnResult<int>> TestRedown()
{
var rs = new ReturnResult<int>();
var topiclist = new List<string>() { "DraftDecStatus", "DeclarationAttachments", "CusDecInfo" };
var dblist = await DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanAliActionList>()
.Where(w => w.uniqueNumber == "6637-0-28698"
//&& (w.topic== "DeclarationAttachments"||w.StateCode=="14")
&& w.StateCode == "22"
).OrderBy(w => w.Id).ToListAsync();
var orderlist = new List<tb_BaoGuanOrderList>();//报关订单
var SendMailList = new List<MailSendDto>();//Email发送
var companylist = DbBus.Get(DbList.djyolddb).Select<djy.Model.CompanyNew>().Where(w => w.AliCompanyId > 0).ToList();
foreach (var item in dblist)
{
try
{
if (item.topic == "DraftDecStatus" || item.topic == "CusDecInfo" || item.topic == "DeclarationAttachments")//报关草稿状态
{
var data = YsJson.JsonToObject<AliBaoGuanOnetouchDataDto>(item.data);
if (data != null)
{
var comp = companylist.Where(w => w.AliCompanyId == item.companyId).FirstOrDefault();
var compid = Guid.Empty;
var compname = "";
if (comp != null)
{
compid = Guid.Parse(comp.CompId);
compname = comp.CompName;
}
var order = new tb_BaoGuanOrderList
{
OrderType = "ali"
,
UniqueNumber = item.uniqueNumber
,
AlSActionGid = item.Gid
,
AliCompanyId = item.companyId
,
CompId = compid
,
CompName = compname
,
ShipOrderNo = data.BillNo
,
Topic = item.topic,
stateCode = item.StateCode,
stateName = item.StateName,
ClientName = ""
};
//获取最新客户联系方式
//绑定客户 仅在【提交到单一窗口】时触发一次
//其它时候不做此操作 以减少访问数据库的次数
if (order.TradeName.IsNotNull() && data.StateCode == "22")
{
}
if (data.StateCode == "13")
{//海关查验时间
order.CheckTime = data.Date.ToTimestamp();
//创建Email发送委托
var _mailbody = @"海关查验";
SendMailList.Add(new MailSendDto { DataKey = item.uniqueNumber, MailBody = _mailbody, Title = "海关查验", Type = "13", SendTime = DateTime.Now });
}
if (data.StateCode == "14")
{
//海关放行触发发送邮件
SendMailList.Add(new MailSendDto { Type = "14", DataKey = item.uniqueNumber, Title = "海关放行", SendTime = DateTime.Now.AddMinutes(2) });
}
//item.topic == "CusDecInfo" &&
//20220301 海关报文改为状态11 海关入库 时发送,此时内容包括报关单号
if ((item.topic == "CusDecInfo" || data.StateCode == "11") && data.MessageContent.IsNotNull())//海关报文
{
var jsonstr = YsJson.XmlToJson(data.MessageContent.Base64ToString());
if (jsonstr.IsNotNull())
{
jsonstr = jsonstr.Replace("?", "").Replace("@", "");
_LogsAdd("海关报文解析" + order.UniqueNumber, "海关报文", new { order, jsonstr });
var cusdata = JsonSerializer.Deserialize<JsonElement>(jsonstr);
var customerdec = YsJson.DeserializeAnonymousType(cusdata.GetProperty("DecMessage").ToString(), new { DecSign = new AliBaoGuanCustomesDecSignDto(), DecHead = new AliBaoGuanCustomesDecHeadDto() });
if (customerdec != null)
{
//_LogsAdd("海关报文解析" + order.UniqueNumber, "海关报文", new { order, customerdec });
order.IEFlag = customerdec.DecHead.IEFlag.IsNull() ? "E" : customerdec.DecHead.IEFlag;
order.DeclareCustoms = customerdec.DecHead.CustomMaster;
order.CustomsMessage = jsonstr;
order.TradeName = customerdec.DecHead.TradeName;
//报关单号
//20220301 海关报文改为状态11 海关入库 时发送,此时内容包括报关单号
//order.CustomsNo = customerdec.DecHead.SeqNo;
//如有海关入库时才解析报关单号
if (data.StateCode == "11")
order.CustomsNo = customerdec.DecHead.EntryId;
order.TrafName = customerdec.DecHead.TrafName;
////获取最新客户联系方式
if (!string.IsNullOrWhiteSpace(order.TradeName) && (order.ClientName == null || order.ClientName.Length == 0))
{
var linkinfo = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.AliCompanyId == order.AliCompanyId && w.TradeName == order.TradeName
&& (w.ClientName != null && w.ClientName.Length > 0)
//&& w.ClientEmail.Length > 0
).OrderByDescending(w => w.Id).ToOne();
_LogsAdd("海关报文解析" + order.UniqueNumber, "绑定客户", new { linkinfo });
if (linkinfo != null)
{
order.ClientName = linkinfo.ClientName;
order.ClientMain = linkinfo.ClientMain;
order.ClientEmail = linkinfo.ClientEmail;
}
}
}
}
}
//if (item.topic == "DeclarationAttachments")
//{//接收回执文件
// var url = HttpHelp.FileDown(data.docUrl, "userdata/alibaoguanfile", item.uniqueNumber + "_" + data.docName).Result;
// var flist = order.FileList;
// var _newfile = new FileListDto { Name = data.docName, Url = url };
// flist.Add(_newfile);
// order.FileList = flist;
// _LogsAdd("接收文件" + order.UniqueNumber, "报关file", order);
//}
if (orderlist.Where(w => w.UniqueNumber == order.UniqueNumber).Count() > 0)
{//如果已存在则更新
foreach (var o in orderlist)
if (o.UniqueNumber == order.UniqueNumber)
{
o.ShipOrderNo = order.ShipOrderNo;
o.stateCode = order.stateCode.IsNotNull() ? order.stateCode : o.stateCode;
o.stateName = order.stateName.IsNotNull() ? order.stateName : o.stateName;
o.IEFlag = order.IEFlag.IsNotNull() ? order.IEFlag : o.IEFlag;
o.DeclareCustoms = order.DeclareCustoms.IsNotNull() ? order.DeclareCustoms : o.DeclareCustoms;
o.CheckTime = order.CheckTime > 0 ? order.CheckTime : o.CheckTime;
o.CustomsMessage = order.CustomsMessage.IsNotNull() ? order.CustomsMessage : o.CustomsMessage;
o.TrafName = order.TrafName.IsNotNull() ? order.TrafName : o.TrafName;
o.CustomsNo = order.CustomsNo.IsNotNull() ? order.CustomsNo : o.CustomsNo;
o.TradeName = order.TradeName.IsNotNull() ? order.TradeName : o.TradeName;
o.ClientName = order.ClientName.IsNotNull() ? order.ClientName : o.ClientName;
o.ClientMain = order.ClientMain.IsNotNull() ? order.ClientMain : o.ClientMain;
o.ClientEmail = order.ClientEmail.IsNotNull() ? order.ClientEmail : o.ClientEmail;
if (order.FileList.Count > 0)
{
var flist = o.FileList;
var namelist = flist.Select(w => w.Name).ToList();
List<FileListDto> nlist = order.FileList.Where(w => !namelist.Contains(w.Name)).ToList();
flist.AddRange(nlist);
o.FileList = flist;
}
break;
}
}
else
{
orderlist.Add(order);
}
}
}
}
catch (Exception ex)
{
}
}
//更新或插入
var alinumberlist = orderlist.Select(w => w.UniqueNumber).ToList();
var _shoporderlist = orderlist.Where(w => w.ShipOrderNo.IsNotNull()).Select(w => w.ShipOrderNo).ToList();
var datalist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => _shoporderlist.Contains(w.ShipOrderNo) || alinumberlist.Contains(w.UniqueNumber)).ToList();
var uplist = new List<tb_BaoGuanOrderList>();
var newlist = new List<tb_BaoGuanOrderList>();
// orderlist.ForEach(item => {
foreach (var item in orderlist)
{
var order = datalist.Where(w => w.UniqueNumber == item.UniqueNumber || (w.UniqueNumber.Length == 0 && w.ShipOrderNo == item.ShipOrderNo && w.ShipOrderNo.Length > 0)).FirstOrDefault();
if (order == null)
{
item.Init();
newlist.Add(item);
}
else
{
order.CompId = item.CompId;
order.CompName = item.CompName;
order.UniqueNumber = item.UniqueNumber.IsNotNull() ? item.UniqueNumber : order.UniqueNumber;
order.ShipOrderNo = item.ShipOrderNo.IsNotNull() ? item.ShipOrderNo : order.ShipOrderNo;
order.stateCode = item.stateCode.IsNotNull() ? item.stateCode : order.stateCode;
order.stateName = item.stateName.IsNotNull() ? item.stateName : order.stateName;
order.IEFlag = item.IEFlag.IsNotNull() ? item.IEFlag : order.IEFlag;
order.DeclareCustoms = item.DeclareCustoms.IsNotNull() ? item.DeclareCustoms : order.DeclareCustoms;
order.CheckTime = item.CheckTime > 0 ? item.CheckTime : item.CheckTime;
order.CustomsMessage = item.CustomsMessage.IsNotNull() ? item.CustomsMessage : order.CustomsMessage;
order.CustomsNo = item.CustomsNo.IsNotNull() ? item.CustomsNo : order.CustomsNo;
order.TradeName = item.TradeName.IsNotNull() ? item.TradeName : order.TradeName;
order.TrafName = item.TrafName.IsNotNull() ? item.TrafName : order.TrafName;
//联系信息在绑定过后不更新
if (item.ClientName.IsNotNull() && order.ClientName.IsNull())//order.ClientEmail.IsNull() &&
{
order.ClientName = item.ClientName;
order.ClientMain = item.ClientMain;
order.ClientEmail = item.ClientEmail;
_LogsAdd("自动绑定报关客户:" + order.UniqueNumber, "报关绑定", new { item, order });
}
if (item.FileList.Count > 0)
{
var filist = order.FileList;
filist.AddRange(item.FileList);
order.FileList = filist;
}
if (item.CustomsMessage.IsNotNull())
{//如果原始单一报文发生改变则重新解析数据
order.ParseStatus = 1;
}
uplist.Add(order);
}
}
// });
//事务提交数据
DbBus.Get(DbList.djypublicedb).Transaction(() =>
{
if (uplist.Count > 0)
{
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().SetSource(uplist).ExecuteAffrows();
}
if (newlist.Count > 0)
{
var bangdinglist = newlist.Where(w => w.ClientEmail.IsNotNull()).ToList();
var bandinggidlist = "";
bangdinglist.ForEach(item => { bandinggidlist += $",{item.UniqueNumber}"; });
_LogsAdd("新建时绑定:" + bandinggidlist, "报关绑定", bangdinglist);
DbBus.Get(DbList.djypublicedb).Insert(newlist).ExecuteAffrows();
}
//更新状态
var _gidlist = dblist.Select(w => w.Gid).ToList();
DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanAliActionList>().Set(w => w.Status, 100).Where(w => _gidlist.Contains(w.Gid)).ExecuteAffrows();
});
//Email发送处理
//if (sysOptionConfig.YsWebconfig.IsDev)
//{
// SendMailList = new List<MailSendDto>();
//}
if (SendMailList.Count > 0)
{
//创建Email发送委托
var keylist = SendMailList.GroupBy(w => w.DataKey).Select(w => w.Key).ToList();
var _getorder = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => keylist.Contains(w.UniqueNumber)).ToList();
var baoguanhanggid = _getorder.GroupBy(w => w.CompId).Select(w => w.Key.Value.ToString()).ToList();
var _userlist = DbBus.Get(DbList.djyolddb).Select<UserBaseinfo, CompanyNew>().LeftJoin((u, c) => u.USERID == c.AdminUser).Where((u, c) => baoguanhanggid.Contains(c.CompId)).ToList((u, c) => new { u.USERID, c.CompId, u.EMAIL1 });
var _useridlist = _userlist.Select(w => w.USERID).ToList();
var _mailhostconfig = DbBus.Get(DbList.djyolddb).Select<MailUserAccount>().Where(w => _useridlist.Contains(w.UserId)).ToList();
foreach (var item in SendMailList)
{
var border = _getorder.Where(w => w.UniqueNumber == item.DataKey).FirstOrDefault();
if (border != null)
{//获取接收Email
if (item.Type == "13")
{ //查验Email完善处理
var Mailbody = @"<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>海关查验 " + border.ShipOrderNo + " " + border.CustomsNo + @" </title>
</head>
<body>
<div style='padding:0 20px;'>
<p style='color:#333;'>尊敬的" + border.ClientName + @",您好:</p>
<p style='color:#333;'>你单位申报的报关单号,经审核现决定实施口岸检查,请联系港务等相关部门做好准备,并派员配合海关实施口岸检查。特此通知!</p>
<div>
<div style='padding:0 20px;'>
<p style='color:#333;'>检查关区:" + border.DeclareCustoms + @"</p>
<p style='color:#333;'>报关单号:" + border.CustomsNo + @"</p>
<p style='color:#333;'>提单号:" + border.ShipOrderNo + @"</p>
<p style='color:#333;'>运输工具:" + border.TrafName + @"</p>
</div>
<p style='color:#333;'>" + border.CompName + @"</p></div>
</div>
</body>
</html>";
item.MailBody = Mailbody;
item.Title = "海关查验" + border.ShipOrderNo;
}
if (item.Type == "14")
{
//加入Email发送队列
var _mailbody = @"<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>海关放行通知 " + border.ShipOrderNo + @"</title>
</head>
<body>
<div style='padding:0 20px;'>
<p style='color:#333;'>尊敬的" + border.ClientName + @",您好:</p>
<p style='color:#333;'>您的提单号为" + border.ShipOrderNo + @"海关已放行,报关单及放行条请查看附件,谢谢!</p>
<div>
<p style='color:#333;'>" + border.CompName + @"</p> </div>
</div>
</body>
</html>";
item.Title = "海关放行通知 " + border.ShipOrderNo;
item.MailBody = _mailbody;
var _flist = border.FileList.Where(w => w.Name.Contains("报关单") || w.Name.Contains("放行条")).ToList();
////20220309 逐个判断文件是否存在,
////如不存在 select * from tb_BaoguanAliActionList where uniquenumber='6743-0-4923' and topic='DeclarationAttachments'
////寻找这个文件的docname ,找到它对应的url 重新下载。
//foreach (var filedto in _flist)
//{
// var retrycount = 0;
// 重新下载文件(border, filedto.Name, ref retrycount);
//}
item.FileList = _flist;
}
item.Email = border.ClientEmail;
var _sml = _userlist.Where(w => w.CompId == border.CompId.ToString()).FirstOrDefault();
if (_sml != null)
{
var _mailconfig = _mailhostconfig.Where(w => w.UserId == _sml.USERID).FirstOrDefault();
item.SendEmail = _sml.EMAIL1;
if (_mailconfig != null)
{
item.SendMailConfig = new Ys.Core.Common.Email.SendServerConfigurationEntity
{
SmtpHost = _mailconfig.SmtpServer,
SmtpPort = _mailconfig.SmtpPort,
SenderAccount = _mailconfig.MailAccount,
SenderPassword = _mailconfig.Password,
IsSsl = _mailconfig.SmtpSSL
};
item.SendEmail = _mailconfig.MailAccount;
//20220317 如果此时没接收到附件 则将此项任务丢到redis的BaoguanEmailSend队列
if (item.Type == "14")
{
//用于测试
if (item.())
{
item.border = border;
item.SendTime = DateTime.Now.AddMinutes(1);
DbRedis.LPush(, YsJson.ToJson(item));
continue;
}
else
{
var cansend = true;
foreach (var fileDto in item.FileList)
{
if (!File.Exists(fileDto.Url))
{
item.border = border;
item.SendTime = DateTime.Now.AddMinutes(1);
DbRedis.LPush(, YsJson.ToJson(item));
cansend = false;
continue;
}
}
if (!cansend) continue;
}
}
}
else
{
item.MailBody = item.MailBody.Replace("<body>", "<h3> 因您的大简云邮箱配置错误无法直接发送Email给客户,错误原因: 未配置,请登录大简云->个人中心->个人信息进行配置 </h3> <br> <h3> 客户Email为: " + item.Email + " </h3>");
}
}
}
else
{
item.Status = 0;
}
if (item.Status == 1)
{
//BackgroundJob.Enqueue(() => _SendEmail(item));
}
}
}
rs.OK("成功");
return rs;
}
/// <summary>
/// 20220309 逐个判断文件是否存在,
/// 如不存在 select * from tb_BaoguanAliActionList where uniquenumber='6743-0-4923' and topic='DeclarationAttachments'
/// 寻找这个文件的docname ,找到它对应的url 重新下载。
/// </summary>
/// <param name="baoguanorder"></param>
/// <param name="docname"></param>
/// <param name="retrycount"></param>
private void (tb_BaoGuanOrderList baoguanorder, string docname, ref int retrycount)
{
//只允许递归2次
if (retrycount >= 2) return;
retrycount++;
try
{
//判断文件是否存在
foreach (var fileDto in baoguanorder.FileList)
{
if (!File.Exists(fileDto.Url))
//if (!File.Exists("userdata/alibaoguanfile/10000288-0-7339_报关单_QDWE251107.pdf"))
//10000288-0-7339_报关单_QDWE251107.pdf
{
var _getorderbaoguan = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanAliActionList>().Where(w => w.uniqueNumber == baoguanorder.UniqueNumber && w.topic == "DeclarationAttachments" && w.data.IndexOf(fileDto.Name) > 0).ToList();
var AlibaoguanDoc = _getorderbaoguan[0];
var data = YsJson.JsonToObject<AliBaoGuanOnetouchDataDto>(AlibaoguanDoc.data);
_LogsAdd("重新下载" + baoguanorder.UniqueNumber, "报关file", new { fileDto.Name, data.docUrl });
//重新下载
HttpHelp.FileDown(data.docUrl, "userdata/alibaoguanfile", fileDto.Name);
Thread.Sleep(500);
}
else
{
_LogsAdd("文件已存在" + baoguanorder.UniqueNumber, "报关file", new { fileDto.Name });
retrycount = 3;
return;
}
}
(baoguanorder, docname, ref retrycount);
}
catch (Exception e)
{
_LogsAdd("重新下载error:" + baoguanorder.UniqueNumber, "报关file", new { e.Message });
}
}
public async Task<ReturnResult<int>> AutoSendMail()
{
var rs = new ReturnResult<int>();
//从redis中获得数据
var = DbRedis.LLen();
if ( == 0)
{
rs.OK("成功");
return rs;
}
else
{
for (var _i = 0; _i < ; _i++)
{
var str = DbRedis.RPop();
MailSendDto Sendmail = YsJson.JsonToObject<MailSendDto>(str);
if (Sendmail.SendTime > DateTime.Now)
{
DbRedis.LPush(, YsJson.ToJson(Sendmail));
}
else
{
if (!Sendmail.())
{
tb_BaoGuanOrderList border = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(x => x.Gid == Sendmail.border.Gid).ToOne();
if (!Sendmail.())
{
//推迟2分钟
Sendmail.SendTime = DateTime.Now.AddMinutes(2);
DbRedis.LPush(, YsJson.ToJson(Sendmail));
continue;
}
}
var cansend = true;
foreach (var fileDto in Sendmail.FileList)
{
if (!File.Exists(fileDto.Url))
{
//推迟2分钟
Sendmail.SendTime = DateTime.Now.AddMinutes(2);
DbRedis.LPush(, YsJson.ToJson(Sendmail));
cansend = false;
continue;
}
}
if (!cansend) continue;
BackgroundJob.Enqueue(() => _SendEmail(Sendmail));
}
}
}
rs.OK("成功");
return rs;
}
/// <summary>
/// Email发送
/// </summary>
/// <param name="sendDto"></param>
public ReturnResult<string> _SendEmail(MailSendDto sendDto)
{
var rs = new ReturnResult<string>();
//创建发送委托任务
var sendflist = new List<Ys.Core.Common.Email.MailFile>();
sendDto.FileList.ForEach(im =>
{
sendflist.Add(new Ys.Core.Common.Email.MailFile { FileName = im.Name, MailFileType = "application/pdf", MailFileSubType = "pdf", MailFilePath = im.Url });
});
if (sendDto.Email.IsNull())
{
_LogsAdd("报关Email空" + sendDto.Title + sendDto.DataKey, "报关Email空", sendDto);
rs.Not("Email 未设置");
return rs;
}
//发送
var mlist = sendDto.Email.Split(',').ToList();
var send = DjyTools.EmailSendOnLogs(mlist, sendDto.Title, sendDto.MailBody, sendDto.SendEmail, sendDto.Title + sendDto.DataKey, sendflist, sendDto.SendMailConfig);
if (send.ResultStatus)
{
rs.OK();
}
if (sendDto.SendMailConfig != null && !send.ResultStatus && mlist.Where(w => w == sendDto.SendMailConfig.SenderAccount).Count() == 0)
{//通过自有邮件配置发送失败 则将邮件发送一份给配置客户
var _sendmail = YsJson.JsonToObject<MailSendDto>(YsJson.ToJson(sendDto));
_sendmail.SendMailConfig = null;
_sendmail.Email = sendDto.SendMailConfig.SenderAccount;
_sendmail.MailBody = _sendmail.MailBody.Replace("<body>", "<h3> 因您的大简云邮箱配置错误无法直接发送Email给客户,错误原因: " + send.ResultInformation + ",请登录大简云->个人中心->个人信息进行配置 </h3> <br> <h3> 客户Email为: " + sendDto.Email + " </h3>");
var _mlist = _sendmail.Email.Split(',').ToList();
_sendmail.SendEmail = null;
var rsend = DjyTools.EmailSendOnLogs(_mlist, _sendmail.Title, _sendmail.MailBody, _sendmail.SendEmail, _sendmail.Title + _sendmail.DataKey, sendflist);
if (rsend.ResultStatus)
{
rs.OK();
}
else
{
rs.Not(rsend.ResultInformation);
}
}
return rs;
}
/// <summary>
/// 1 生成阿里云报关跳转地址 同时建立关联用户流程或联合登录到一达通
/// </summary>
/// <returns></returns>
public async Task<ReturnResult<string>> AliyunBaoguanToken(User Dto)
{
var rs = new ReturnResult<string>();
var user = DbBus.Get(DbList.djyolddb).Select<User>().Where(w => w.GID == Dto.GID).ToOne();
if (user == null)
{
rs.Not("请求错误:账户不存在!");
return rs;
}
if (user.CompId.IsNull())
{
rs.Not("您所在企业未认证,请先做企业认证!");
return rs;
}
var company = DbBus.Get(DbList.djyolddb).Select<CompanyNew>().Where(w => w.CompId == user.CompId).ToOne();
if (company == null)
{
rs.Not("没有找到所属企业主体!");
return rs;
}
if (company.AuditStatus.ToLower() != "Success".ToLower())
{
rs.Not("企业主体未认证!");
return rs;
}
if (company.CustomsCode.IsNull())
{
rs.Not("海关号未完善,请先完善企业主体海关号!");
return rs;
}
if (company.AdminUser != user.GID)
{
var ccount = DbBus.Get(DbList.djyolddb).Select<User>().Where(w => w.CompId == company.CompId && w.BaoguanAliId != null).Count();
if (ccount == 0)
{
rs.Not("企业账户第一次使用,请使用企业管理员账户!");
return rs;
}
}
var userinfo = DbBus.Get(DbList.djyolddb).Select<UserBaseinfo>().Where(w => w.USERID == user.GID).ToOne();
if (userinfo.EMAIL1.IsNull() || userinfo.MOBILE.IsNull())
{
if (userinfo.EMAIL1.IsNull())
{
rs.Not("账户Email未维护请先维护");
}
if (userinfo.MOBILE.IsNull())
{
rs.Not("账户手机号未维护请先维护!");
}
return rs;
}
var aliyunkey = DjyTools.GetConfigKey("bg_aliyunseckey");
var jwtcreate = new TokenProvider();
jwtcreate.Jwtoptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(aliyunkey)), SecurityAlgorithms.HmacSha512);
var claimlist = new List<Claim>() {
new Claim("entName",company.CompName),//企业名称
new Claim("cusCode",company.CustomsCode),//10位海关登记号
new Claim("scCode",company.TaxCode),//18位企业信用代码
new Claim("userName",user.CODENAME),//该账户用户名
new Claim("userId",user.GID),//该账户大简云ID
new Claim("email",userinfo.EMAIL1),//Email
new Claim("mobile",userinfo.MOBILE)//手机号
};
var rstoken = await jwtcreate.CreateToken(user.GID, claimlist);
_LogsAdd("报关跳转登录注册", "baoguan", new { claimlist, rstoken });
if (!rstoken.Status)
{
rs.Not("token生成失败");
return rs;
}
rs.Data = rstoken.Token;
var url = @"https://onetouch-partner.alibaba.com/ptnProvider/customs/thirdParty.htm?token=" + rs.Data + "&platform=DaJianYun&targetUrl=%2F%2Fonetouch-partner.alibaba.com%2FptnProvider%2Fluyou%2Fcustoms%2Fexternal%2Fcustomer%2Flist.htm%3Fplatform%3DDaJianYun";
rs.MemoData = new { url, key = aliyunkey };
rs.OK();
return rs;
}
/// <summary>
/// 用户离职
/// </summary>
/// <returns></returns>
public async Task<ReturnResult<string>> AliUserQuit(string UserId)
{
var rs = new ReturnResult<string>();
var aliURl = @"https://onetouch-partner.alibaba.com/ptnProvider/customs/thirdParty/quitJob.json";
var user = DbBus.Get(DbList.djyolddb).Select<User>().Where(w => w.GID == UserId).ToOne();
if (user == null)
{
rs.Not("没有此账户!");
return rs;
}
var userinfo = DbBus.Get(DbList.djyolddb).Select<UserBaseinfo>().Where(w => w.USERID == user.GID).ToOne();
var aliyunkey = DjyTools.GetConfigKey("bg_aliyunseckey");
var jwtcreate = new TokenProvider();
jwtcreate.Jwtoptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(aliyunkey)), SecurityAlgorithms.HmacSha512);
var claimlist = new List<Claim>() {
new Claim("openUserId",user.GID),//大简云账户Id
new Claim("openUserEmail",userinfo.EMAIL1),//大简云账户email
new Claim("aliId",user.BaoguanAliId)// 阿里平台用户id
};
var rstoken = await jwtcreate.CreateToken(user.GID, claimlist);
await DjyTools.PostOnLogs(new { token = rstoken.Token }, aliURl, "alliuser");
DbBus.Get(DbList.djyolddb).Update<User>().Set(w => w.BaoguanAliId, null).Where(w => w.GID == user.GID).ExecuteAffrows();
rs.OK();
return rs;
}
/// <summary>
/// 阿里报关消息查询接口 接收了就标记自动消费掉
/// </summary>
/// <returns></returns>
public async Task<ReturnResult<string>> AliBaoguanrationlist()
{
var rs = new ReturnResult<string>();
var urlPath = @"param2/1/ali.intl.onetouch/customs.saas.declaration.message.list.get/855313";
var pdata = new Dictionary<string, string>();
pdata.Add("appKey", "855313");
var sinkey = Getalisign(urlPath, pdata, _aliappsecretKey);
var gethtml = await DjyTools.PostOnLogs(new { appKey = "855313", _aop_signature = sinkey }, _aliapihost + urlPath, "阿里报关消息查询", YsPsotType.Form);
var jsone = JsonSerializer.Deserialize<JsonElement>(gethtml);
var jsondata = YsJson.DeserializeAnonymousType(jsone.GetProperty("result").ToString(), new { isSuccess = false, resultMsg = "", resultCode = "", traceId = "", data = "" });
if (jsondata.data != null)
{
var data = Encoding.UTF8.GetString(Convert.FromBase64String(jsondata.data));
var datalist = JsonSerializer.Deserialize<List<tb_BaoguanAliActionList>>(data);
var idlist = datalist.Select(w => w.msgId).ToList();
var oldlist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanAliActionList>().Where(w => idlist.Contains(w.msgId)).ToList(w => w.msgId);
var newlist = datalist.Where(w => !oldlist.Contains(w.msgId)).ToList();
foreach (var item in newlist)
{
if (item.data.IsNotNull())
{
item.data = Encoding.UTF8.GetString(Convert.FromBase64String(item.data));
//尝试解析
var datainfo = YsJson.JsonToObject<AliBaoGuanOnetouchDataDto>(item.data);
if (datainfo != null)
{
item.AliTime = datainfo.Date.IsDateTime() ? datainfo.Date.ToTimestamp() : 0;
item.StateCode = datainfo.StateCode.IsNotNull() ? datainfo.StateCode : "";
item.StateName = datainfo.StateName.IsNotNull() ? datainfo.StateName : "";
}
}
item.Init();
}
if (newlist.Count > 0)
{
var dbcount = DbBus.Get(DbList.djypublicedb).Insert(newlist).ExecuteAffrows();
if (dbcount > 0)
{//数据保存成功标记消费掉
var msidlist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanAliActionList>().Where(w => w.Status == 1).ToList(w => w.msgId);
await AliBaodanActionConsume(msidlist);
//提交到阿里更新消费掉 标记status=2
await DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanAliActionList>().Set(w => w.Status, 2).Where(w => msidlist.Contains(w.msgId)).ExecuteAffrowsAsync();
}
}
rs.Data = datalist.Count().ToString();
}
rs.OK();
return rs;
}
/// <summary>
/// 阿里报关消息消费修改状态
/// </summary>
/// <param name="MsIdList"></param>
/// <returns></returns>
public async Task<ReturnResult<int>> AliBaodanActionConsume(List<string> MsIdList)
{
var rs = new ReturnResult<int>();
if (MsIdList == null || MsIdList.Count == 0)
{
rs.Not("消息id未指定");
}
var urlPath = @"param2/1/ali.intl.onetouch/customs.saas.declaration.message.list.consume/855313";
var pdata = new Dictionary<string, string>();
pdata.Add("appKey", "855313");//阿里分配的固定appkeyid
var idstr = "";
MsIdList.ForEach(item =>
{
if (idstr.IsNull())
{
idstr += ",";
}
idstr += "\"" + item + "\"";
});
var pidlist = "[" + idstr + "]";
pdata.Add("msgIdList", pidlist);
var sinkey = Getalisign(urlPath, pdata, _aliappsecretKey);
var gethtml = await DjyTools.PostOnLogs(new { appKey = "855313", msgIdList = pidlist, _aop_signature = sinkey }, _aliapihost + urlPath, "消费阿里报关消息", YsPsotType.Form);
rs.Data = DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanAliActionList>().Set(w => w.Status, 100).Where(w => MsIdList.Contains(w.msgId)).ExecuteAffrows();
rs.OK();
return rs;
}
/// <summary>
/// 计算阿里签名
/// </summary>
/// <param name="urlPath"></param>
/// <param name="paramDic"></param>
/// <param name="AppsecretKey"></param>
/// <returns></returns>
private string Getalisign(string urlPath, Dictionary<string, string> paramDic, string AppsecretKey)
{
byte[] signatureKey = Encoding.UTF8.GetBytes(AppsecretKey); //此处固定⽤⾃⼰ 的签名密钥
List<string> list = new List<string>();
foreach (KeyValuePair<string, string> kv in paramDic)
{
list.Add(kv.Key + kv.Value);
}
list.Sort();
string tmp = urlPath;
foreach (string kvstr in list)
{ tmp = tmp + kvstr; }
//HMAC-SHA1
HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey);
hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));
/*hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(urlPath));
foreach (string kvstr in list)
{
hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(kvstr));
}*/
byte[] hash = hmacsha1.Hash;
//TO HEX
return BitConverter.ToString(hash).Replace("-", string.Empty).ToUpper();
}
#endregion
#endregion
/// <summary>
/// 运行杂项
/// </summary>
/// <returns></returns>
public ReturnResult<string> Run()
{ //批量更新解析发货人
var rs = new ReturnResult<string>();
try
{
var getlist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => (w.TradeName.Length == 0 || w.TradeName == null) && w.CustomsMessage.Length > 0).ToList();
getlist.ForEach(item =>
{
var cusdata = JsonSerializer.Deserialize<JsonElement>(item.CustomsMessage);
var customerdec = YsJson.DeserializeAnonymousType(cusdata.GetProperty("DecMessage").ToString(), new { DecSign = new AliBaoGuanCustomesDecSignDto(), DecHead = new AliBaoGuanCustomesDecHeadDto() });
item.TradeName = customerdec.DecHead.TradeName;
});
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().SetSource(getlist).UpdateColumns(w => w.TradeName).ExecuteAffrows();
}
catch (Exception ex)
{
}
rs.OK();
return rs;
}
/// <summary>
///报关单详情数据数据解析 自动解析 1 将报关单的箱数据和商品明细数据解析出来 2 将报关订阅的公司数据生成订阅消息数据到baoguanmsg表
/// </summary>
/// <returns></returns>
public ReturnResult<string> RunOrderPsrse()
{
var rs = new ReturnResult<string>();
var codelist = new List<string> { "14", "15" };//,"22"
var datalist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => w.ParseStatus < 100 && w.CustomsMessage != null && w.CustomsMessage.Length > 0 && codelist.Contains(w.stateCode)).ToList();
var contlist = new List<tb_BaoguanContainer>();
var decList = new List<tb_BaoguanDecList>();
foreach (var item in datalist)
{
if (item.CustomsMessage.IsNull())
{ continue; }
var cusdata = JsonSerializer.Deserialize<JsonElement>(item.CustomsMessage);
var customerdec = YsJson.DeserializeAnonymousType(cusdata.GetProperty("DecMessage").ToString(), new { DecSign = new AliBaoGuanCustomesDecSignDto(), DecContainers = new JsonElement(), DecLists = new JsonElement(), DecHead = new AliBaoGuanCustomesDecHeadDto() });
var ncontlist = new List<tb_BaoguanContainer>();
if (customerdec.DecContainers.ToString().IsNotNull())
{ //箱型数据
if (customerdec.DecContainers.GetProperty("Container").ValueKind == JsonValueKind.Object)
{
ncontlist.Add(YsJson.JsonToObject<tb_BaoguanContainer>(customerdec.DecContainers.GetProperty("Container").ToString()));
}
else if (customerdec.DecContainers.GetProperty("Container").ValueKind == JsonValueKind.Array)
{
ncontlist.AddRange(YsJson.JsonToObject<List<tb_BaoguanContainer>>(customerdec.DecContainers.GetProperty("Container").ToString()));
}
}
ncontlist.ForEach(nc => { nc.BaoguanOrderGid = item.Gid; nc.Init(); });
contlist.AddRange(ncontlist);
var ndeclist = new List<BaoguanDecListDto>();
if (customerdec.DecLists.ToString().IsNotNull())
{ //商品数据解析
var jsonstr = customerdec.DecLists.GetProperty("DecList").ToString();
if (customerdec.DecLists.GetProperty("DecList").ValueKind == JsonValueKind.Object)
{
ndeclist.Add(JsonSerializer.Deserialize<BaoguanDecListDto>(jsonstr));
}
else if (customerdec.DecLists.GetProperty("DecList").ValueKind == JsonValueKind.Array)
{
ndeclist.AddRange(YsJson.JsonToObject<List<BaoguanDecListDto>>(jsonstr));
}
}
ndeclist.ForEach(decitem =>
{
var e = new tb_BaoguanDecList
{
BaoguanOrderGid = item.Gid
,
GNo = decitem.GNo
,
OriginCountry = decitem.OriginCountry
,
OriginCountryName = _GetDcitValue("原产地区", decitem.OriginCountry)//
,
CodeTS = decitem.CodeTS
,
GModel = decitem.GModel
,
GName = decitem.GName
,
FirstQty = decitem.FirstQty.IsDecimal() ? Math.Round(decimal.Parse(decitem.FirstQty), 4) : 0
,
FirstUnit = decitem.FirstUnit
,
FirstUnitName = _GetDcitValue("计量单位", decitem.FirstUnit)//
,
DutyMode = decitem.DutyMode
,
DutyModeName = _GetDcitValue("征减免税方式", decitem.DutyMode)//
,
DestinationCountry = decitem.DestinationCountry
,
DestinationCountryName = _GetDcitValue("原产地区", decitem.DestinationCountry)//
,
DistrictCode = decitem.DistrictCode
,
DistrictCodeName = _GetDcitValue("国内地区", decitem.DistrictCode)//
,
TradeCurr = decitem.TradeCurr
,
TradeCurrName = _GetDcitValue("货币代码", decitem.TradeCurr)//
,
GQty = decitem.GQty.IsDecimal() ? Math.Round(decimal.Parse(decitem.GQty), 4) : 0
,
DeclTotal = decitem.DeclTotal.IsDecimal() ? Math.Round(decimal.Parse(decitem.DeclTotal), 4) : 0
,
GUnit = decitem.GUnit
,
GUnitName = _GetDcitValue("计量单位", decitem.GUnit)//
,
DeclPrice = decitem.DeclPrice.IsDecimal() ? Math.Round(decimal.Parse(decitem.DeclPrice), 4) : 0
,
};
e.Init();
decList.Add(e);
});
}
//绑定箱柜和订单数据关系
contlist.ForEach(cnt =>
{
var goidlist = cnt.GoodsNo.Split(',').ToList();
foreach (var item in goidlist)
{
foreach (var dec in decList.Where(w => w.BaoguanOrderGid == cnt.BaoguanOrderGid))
{
if (dec.GNo == item)
{
dec.ContainerGid = cnt.Gid;
break;
}
}
}
cnt.Init();
});
decList.ForEach(cnt => { cnt.Init(); });
var idlist_cnt = contlist.Select(w => w.BaoguanOrderGid).ToList();
var idlist_dec = decList.Select(w => w.BaoguanOrderGid).ToList();
var orderidlist = new List<Guid?>();
orderidlist.AddRange(idlist_cnt);
orderidlist.AddRange(idlist_dec);
DbBus.Get(DbList.djypublicedb).Transaction(() =>
{
//删除历史
DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanContainer>().Set(w => w.Status, -1).Where(w => idlist_cnt.Contains(w.BaoguanOrderGid)).ExecuteAffrows();
DbBus.Get(DbList.djypublicedb).Update<tb_BaoguanDecList>().Set(w => w.Status, -1).Where(w => idlist_dec.Contains(w.BaoguanOrderGid)).ExecuteAffrows();
DbBus.Get(DbList.djypublicedb).Insert(contlist).ExecuteAffrows();
DbBus.Get(DbList.djypublicedb).Insert(decList).ExecuteAffrows();
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>().Set(w => w.ParseStatus, 100).Where(w => orderidlist.Contains(w.Gid)).ExecuteAffrows();
});
//生成公司订阅消息到消息表 更多的往参数表中增加逗号间隔
var msgcomlist = DjyTools.GetConfigKey("baoguan_msg_company").Split(',').ToList().ConvertAll<Guid?>(s => Guid.Parse(s));
if (msgcomlist.Count > 0)
{
var msgdatalist = datalist.Where(w => msgcomlist.Contains(w.CompId)).ToList();
var msg_pushlist = new List<tb_BaoguanOrderCompanyPushMsg>();
var msgorderidlist = msgdatalist.Select(w => w.Gid).ToList();
var Containerlist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanContainer>().Where(w => w.Status > 0 && msgorderidlist.Contains(w.BaoguanOrderGid)).ToList();
var conidlist = Containerlist.Select(w => w.Gid).ToList();
var declist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoguanDecList>().Where(w => w.Status > 0 && conidlist.Contains(w.ContainerGid)).ToList();
foreach (var con in Containerlist)
{
con.DecList = declist.Where(w => w.ContainerGid == con.Gid).ToList();
}
var pushmsglist = new List<tb_BaoguanOrderCompanyPushMsg>();
foreach (var order in msgdatalist)
{
var filelist = YsJson.JsonToObject<List<FileListDto>>(order.FileInfo);
if (filelist != null)
{
filelist.ForEach(f =>
{
f.Url = $"http://djypaas.myshipping.net/api/tools/download?name={f.Url}";
});
}
order.FileInfo = YsJson.ToJson(filelist);
var orderdata = new
{
Order = order,
ContainerList = Containerlist.Where(w => w.BaoguanOrderGid == order.Gid).ToList()
};
var newordermsg = new tb_BaoguanOrderCompanyPushMsg { CompanyGid = order.CompId, Data = YsJson.ToJson(orderdata), OrderGid = order.Gid };
newordermsg.Init();
pushmsglist.Add(newordermsg);
}
if (pushmsglist.Count > 0)
{
DbBus.Get(DbList.djypublicedb).Insert(pushmsglist).ExecuteAffrows();
}
}
rs.OK();
return rs;
}
/// <summary>
/// 将通过open提送上来的单一窗口数据解析到BaoguanOrder
/// </summary>
/// <returns></returns>
public ReturnResult<string> RunOpenDanyiParseToOrder()
{
var rs = new ReturnResult<string>();
var openlist = DbBus.Get(DbList.djypublicedb).Select<tb_OpenModuleServer>().Where(w => w.Status == 1 && w.Module == "报关单一窗口").ToList();
if (openlist.Count == 0)
{
rs.Data = "没有可解析数据!";
rs.OK("没有可解析数据!");
return rs;
}
var useridlist = openlist.Select(w => w.UserId).ToList();
var companylist = DbBus.Get(DbList.djyolddb).Select<CompanyNew, User>().LeftJoin((c, u) => c.CompId == u.CompId).Where((c, u) => useridlist.Contains(u.GID)).ToList((c, u) => new { UserGid = u.GID, c.CompId, c.CompName });
var new_orderlist = new List<tb_BaoGuanOrderList>();
foreach (var opendataitem in openlist)
{
try
{
var _company = companylist.Where(w => w.UserGid == opendataitem.UserId).FirstOrDefault();
if (_company == null)
{
_company = new { UserGid = "", CompId = "", CompName = "" };
}
var jsondata = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.Dto.OpenDanyi.BaoguanOpenModel>(opendataitem.ResultJson);
foreach (var _jsondata in jsondata.message)
{
var _data = _jsondata.data;
var _preDecHeadVo = _data.preDecHeadVo;
var _newDanyichuagkou = new DanyichuagkouDto();
_newDanyichuagkou.DecMessage.DecHead = new AliBaoGuanCustomesDecHeadDto
{
AgentCode = _preDecHeadVo.agentCode
,
AgentCodeScc = _preDecHeadVo.agentScc
,
AgentName = _preDecHeadVo.agentName
,
BillNo = _preDecHeadVo.billNo
,
ChkSurety = _preDecHeadVo.chktstFlag
,
ContrNo = _preDecHeadVo.contrNo
,
CopCode = _preDecHeadVo.contrNo//~
,
CopCodeScc = _preDecHeadVo.cnsnTradeScc//~
,
CopName = _preDecHeadVo.consignorCname//~
,
CustomMaster = _preDecHeadVo.customMaster
// ,CutMode=_preDecHeadVo.//~
,
DeclCiqCode = _preDecHeadVo.declCode
// ,DeclTrnRel=_preDecHeadVo.//~
,
DistinatePort = _preDecHeadVo.distinatePort
// ,EdiId=_preDecHeadVo.//~
//,EntryId = _preDecHeadVo.entryId
,
EntryType = _preDecHeadVo.entryType
,
EntyPortCode = _preDecHeadVo.despPortCode//~
,
GrossWet = _preDecHeadVo.grossWt
,
IEFlag = _preDecHeadVo.ciqIEFlag
,
IEPort = _preDecHeadVo.iEPort
,
MarkNo = _preDecHeadVo.markNo
,
NetWt = _preDecHeadVo.netWt
,
OverseasConsigneeEname = _preDecHeadVo.consigneeEname
,
OwnerCiqCode = _preDecHeadVo.ownerCiqCode
,
OwnerCode = _preDecHeadVo.ownerCode
,
OwnerCodeScc = _preDecHeadVo.ownerScc
,
OwnerName = _preDecHeadVo.ownerName
,
PackNo = _preDecHeadVo.packNo
//,PromiseItmes=_preDecHeadVo.//~
,
SeqNo = _preDecHeadVo.cusCiqNo
,
TradeAreaCode = _preDecHeadVo.ciqTradeCountryCode
,
TradeCiqCode = _preDecHeadVo.consignorCode
,
TradeCode = _preDecHeadVo.consigneeEname //_preDecHeadVo.cnsnTradeCode
,
TradeCoScc = _preDecHeadVo.cnsnTradeScc
,
TradeCountry = _preDecHeadVo.cusTradeCountry
,
TradeMode = _preDecHeadVo.supvModeCdde
,
TradeName = _preDecHeadVo.consignorCname
,
TrafMode = _preDecHeadVo.cusTrafMode
,
TrafName = _preDecHeadVo.trafName
,
TransMode = _preDecHeadVo.transMode
,
WrapType = _preDecHeadVo.wrapType
};
//商品数据解析
var _declist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BaoguanOpenDecListDto>>(_preDecHeadVo.decMergeListVo);
_declist.ForEach((row) =>
{
_newDanyichuagkou.DecMessage.DecLists.DecList.Add(row.ToBaoguanDecListDto());
});
//集装箱数据
var _containerlist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<BaoguanOpenContainerDto>>(_preDecHeadVo.preDecContainerVo);
_containerlist.ForEach(row => { _newDanyichuagkou.DecMessage.DecContainers.Container.Add(row.ToBaoguanContainer()); });
//文件文档
var _fileList = new List<FileListDto>();
foreach (var file in _jsondata.pdfFile)
{
var url = HttpHelp.FileDown(file.path, "userdata/alibaoguanfile", _preDecHeadVo.preEntryId + "_" + file.filename + ".pdf").Result;
_LogsAdd("open单一窗口文件下载", "opendanyi", new { file, newurl = url });
try
{
SignPdf(url);
}
catch (Exception e)
{
_LogsAdd("open签章错误", "opendanyi", e.Message);
}
_fileList.Add(new FileListDto { Name = file.filename, Url = url });
}
//创建报关订单
var _newbaoguanorder = new tb_BaoGuanOrderList()
{
AlSActionGid = opendataitem.Gid
// ,ClientName=_preDecHeadVo.ownerName
,
CompId = Guid.Parse(_company.CompId)
,
CompName = _company.CompName
,
CustomsMessage = YsJson.ToJson(_newDanyichuagkou)
,
CustomsNo = _preDecHeadVo.preEntryId
,
BillType = _preDecHeadVo.billType
,
Memo = _preDecHeadVo.billType + "," + _preDecHeadVo.billTypeName
,
DeclareCustoms = _newDanyichuagkou.DecMessage.DecHead.CustomMaster
,
DelegateMain = _newDanyichuagkou.DecMessage.DecHead.AgentName
,
FileInfo = YsJson.ToJson(_fileList)
,
IEFlag = _newDanyichuagkou.DecMessage.DecHead.IEFlag
,
ParseStatus = 1
,
ShipOrderNo = _preDecHeadVo.billNo
,
stateCode = "15"
,
stateName = "海关结关"
,
Status = 100
,
TradeName = _newDanyichuagkou.DecMessage.DecHead.TradeName
,
TrafName = _newDanyichuagkou.DecMessage.DecHead.TrafName
,
UniqueNumber = _preDecHeadVo.preEntryId
,
UpTime = DateTime.Now.ToTimeStamp()
,
OrderType = "open"
};
_newbaoguanorder.Init();
new_orderlist.Add(_newbaoguanorder);
}
}
catch { }
}
//保存报关单数据
if (new_orderlist.Count > 0)
{
var _orderid = new_orderlist.Select(w => w.UniqueNumber).ToList();
var _oldorderlist = DbBus.Get(DbList.djypublicedb).Select<tb_BaoGuanOrderList>().Where(w => _orderid.Contains(w.CustomsNo)).ToList();
var _oldnolist = _oldorderlist.Select(w => w.CustomsNo).ToList();
var addnew_orderlist = new_orderlist.Where(w => !_oldnolist.Contains(w.UniqueNumber)).ToList();//筛选最后的写入单号数据
var del_orderid = addnew_orderlist.Select(s => s.UniqueNumber).ToList();
DbBus.Get(DbList.djypublicedb).Transaction(() =>
{
//删除旧的
DbBus.Get(DbList.djypublicedb).Delete<tb_BaoGuanOrderList>().Where(w => w.OrderType == "open" && _orderid.Contains(w.UniqueNumber)).ExecuteAffrows();
//保存新的
DbBus.Get(DbList.djypublicedb).Insert(addnew_orderlist).ExecuteAffrows();
});
}
var opengidlist = openlist.Select(w => w.Gid).ToList();
DbBus.Get(DbList.djypublicedb).Update<tb_OpenModuleServer>().Set(w => w.Status, 100).Where(w => opengidlist.Contains(w.Gid)).ExecuteAffrows();
rs.Data = YsJson.ToJson(new_orderlist);
rs.OK();
return rs;
}
/// <summary>
/// 获取数据字典的title值
/// </summary>
/// <param name="GroupName"></param>
/// <param name="KeyValue"></param>
public string _GetDcitValue(string GroupName, string KeyValue, string Titletype = "title")
{
string val = "";
var dict = _dictlist.Where(w => w.GroupName == GroupName && w.Key == KeyValue).FirstOrDefault();
if (dict != null)
{ val = Titletype == "title" ? dict.Title : dict.Value; }
return val;
}
#region 图片插入PDF方法
/// <summary>
/// pdf添加图片
/// </summary>
/// <param name="imglist">图片的list</param>
public void SignPdf(string pdfPath)
{
var imgFile = "";
if (pdfPath.IndexOf("放行通知书") > 0 || pdfPath.IndexOf("报关单") > 0)
imgFile = @"userdata/alibaoguanfile/sign2.png";
else imgFile = @"userdata/alibaoguanfile/sign.png";
///分割list
//string[] imgs = imglist.Split(',');
//string pdfpath = Server.MapPath("pdf");
//string imagepath = Server.MapPath("Image");
//string pdfpath = @"G:\MyWeb\Web学习\Windows\LiveProject\LiveProject\Images\"; //文件路径
//string imagepath = @"G:\MyWeb\Web学习\Windows\LiveProject\LiveProject\Images\";
var imagePath = imgFile;
//load pdf file
var pdfBytes = File.ReadAllBytes(pdfPath);
var oldFile = new PdfReader(pdfBytes);
//load image
var preImage = System.Drawing.Image.FromFile(imagePath);
var imgSign = iTextSharp.text.Image.GetInstance(preImage, ImageFormat.Png);
preImage.Dispose();
if (pdfPath.IndexOf("放行通知书") > 0)
{
//imgSign.SetFixedPosition(430, 30); //左、上、右、下
//imgSign.SetWidth(120);
imgSign.SetAbsolutePosition(391, 20);
imgSign.ScalePercent(60);
}
else if (pdfPath.IndexOf("报关单") > 0)
{
//imgSign.SetFixedPosition(430, 520); //左、上、右、下
//imgSign.SetWidth(120);
imgSign.SetAbsolutePosition(445, 30);
imgSign.ScalePercent(60);
}
else
{
//imgSign.SetFixedPosition(480, 400);//左、上、右、下
//imgSign.SetWidth(100);
imgSign.SetAbsolutePosition(480, 400);
imgSign.ScalePercent(60);
}
//in production, I use MemoryStream
//I put FileStream here to test the code in console application
using (var newFileStream = new FileStream(pdfPath, FileMode.Create))
{
//setup PdfStamper
var stamper = new PdfStamper(oldFile, newFileStream);
//iterate through the pages in the original file
for (var i = 1; i <= oldFile.NumberOfPages; i++)
{
//get canvas for current page
var canvas = stamper.GetOverContent(i);
//add image with pre-set position and size
canvas.AddImage(imgSign);
}
stamper.Close();
}
}
#endregion
#region 自动扣费companeynew用户相关
/// <summary>
/// 处理自动扣费
/// </summary>
public void ProcCustFee()
{
var cfgAutoCompId = DjyTools.GetConfigKey("baoguanAutoBindCompanyFeeCompId");
var cfgDingtalk = DjyTools.GetConfigKey("baoguanDingtalkNotify");
_LogsAdd($"报关自动扣费,公司参数:{cfgAutoCompId}", "胜云航通客服消息", null);
_LogsAdd($"报关自动扣费,钉钉:{cfgDingtalk}", "胜云航通客服消息", null);
if (!string.IsNullOrEmpty(cfgAutoCompId))
{
try
{
var arr = cfgAutoCompId.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
_LogsAdd($"报关自动扣费,待处理公司:{arr.Length}", "胜云航通客服消息", null);
foreach (var compid in arr)
{
var guidComp = Guid.Parse(compid);
var orderList = DbBus.Get(DbList.djypublicedb)
.Select<tb_BaoGuanOrderList>()
.Where(x => x.CompId == guidComp
&& (x.StaCustFee == null || x.StaCustFee == "") //未扣费
&& x.ClientName != null && x.ClientName != "" //已绑定客户
&& (x.stateCode == "14" || x.stateCode == "15" || x.stateCode == "18"))//14海关放行15已结关18准予入港
.ToList();
_LogsAdd($"处理{compid}的报关自动扣费,共发现{orderList.Count}票", "胜云航通客服消息", null);
foreach (var ord in orderList)
{
var customerComp = DbBus.Get(DbList.djyolddb)
.Select<CompanyNew>()
.Where(x => x.CompName == ord.ClientName)
.ToOne();
if (customerComp == null)
{
//推送钉钉消息给客服
var content = $"公司{ord.ClientName}未找到";
_LogsAdd(content, "胜云航通客服消息", null);
var gethtml = DjyTools.PostOnLogs(new { text = new { content = $"【未扣费提醒】\r\n{content}\r\n----报关消息通知" }, msgtype = "text" }, cfgDingtalk, "胜云航通客服消息", YsPsotType.Json).Result;
continue;
}
var balance = DbBus.Get(DbList.djyolddb)
.Select<CustBalance>()
.Where(x => x.COMNAME == customerComp.CompName)
.ToOne();
//没有钱包
if (balance == null)
{
//推送钉钉消息给客服
var content = $"公司{ord.ClientName}没有钱包";
_LogsAdd(content, "胜云航通客服消息", null);
var gethtml = DjyTools.PostOnLogs(new { text = new { content = $"【未扣费提醒】\r\n{content}\r\n----报关消息通知" }, msgtype = "text" }, cfgDingtalk, "胜云航通客服消息", YsPsotType.Json).Result;
continue;
}
var price = DbBus.Get(DbList.djyolddb)
.Select<CustPrice>()
.Where(x => x.COMNAME == customerComp.CompName && x.SENDTYPE == 0 && x.BSTYPE == 13)
.ToOne();
//未设置单价
if (price == null)
{
//推送钉钉消息给客服
var content = $"公司{ord.ClientName}的报关单价未设置";
var gethtml = DjyTools.PostOnLogs(new { text = new { content = $"【未扣费提醒】\r\n{content}\r\n----报关消息通知" }, msgtype = "text" }, cfgDingtalk, "胜云航通客服消息", YsPsotType.Json).Result;
continue;
}
//余额不足
if (price.PRICE > balance.Balance)
{
//推送钉钉消息给客服
var content = $"公司{ord.ClientName}的余额不足";
var gethtml = DjyTools.PostOnLogs(new { text = new { content = $"【未扣费提醒】\r\n{content}\r\n----报关消息通知" }, msgtype = "text" }, cfgDingtalk, "胜云航通客服消息", YsPsotType.Json).Result;
continue;
}
//执行扣费
var fin = new FinanceService();
var getfinrs = fin.Expend(new djy.Model.CustFee
{
SENDUSERID = customerComp.AdminUser,
LURURENID = customerComp.AdminUser,
CtnrCount = 1,
CtnrInfo = string.Empty,
BSTYPE = 13,
SENDTYPE = 0,
BSNO = ord.Gid.ToString(),
MBLNO = ord.ShipOrderNo
}, 1);
if (getfinrs.Status)
{
//设置状态
DbBus.Get(DbList.djypublicedb).Update<tb_BaoGuanOrderList>()
.Where(x => x.Gid == ord.Gid)
.Set(x => x.StaCustFee, "OK")
.Set(x => x.TimeCustFee, DateTime.Now)
.ExecuteAffrows();
}
else
{
//推送钉钉消息给客服
var content = $"公司{ord.ClientName}报关扣费失败:{getfinrs.Message}";
var gethtml = DjyTools.PostOnLogs(new { text = new { content = $"【未扣费提醒】\r\n{content}\r\n----报关消息通知" }, msgtype = "text" }, cfgDingtalk, "胜云航通客服消息", YsPsotType.Json).Result;
}
}
}
}
catch (Exception ex)
{
_LogsAdd(ex.Message, "胜云航通自动扣费", new { ex.StackTrace });
}
}
}
#endregion
}
}