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.
DS7/DSWeb/Areas/MvcShipping/DAL/BillCheckOut/BillCheckOutDAL.cs

724 lines
28 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.Data;
using System.Collections.Generic;
using System.Text;
using DSWeb.Common.DB;
using System.Linq;
using DSWeb.MvcShipping.Helper;
using DSWeb.Common.Helper;
using DSWeb.Areas.CommMng.Models;
using static DSWeb.Areas.CommMng.DAL.BasicDataRefDAL;
using DSWeb.EntityDA;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DSWeb.Areas.CommMng.DAL;
using HcUtility.Comm;
using System.Web.Mvc;
using DSWeb.MvcShipping.DAL.DsSendmail;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using sun.swing;
using DSWeb.Areas.Import.DAL.ReceiptDoc;
using DSWeb.Areas.SysMng.DAL.SysUser;
using Renci.SshNet.Common;
using DSWeb.MvcShipping.DAL.MsSeaeOrderDAL;
using System.Data.Entity.Migrations;
using Aspose.Words.Saving;
using System.Web;
using DSWeb.MvcShipping.DAL.MsSysBillNoSet;
using DSWeb.Areas.MvcShipping.Helper;
using MailKit.Security;
using MimeKit;
using System.Net.Mime;
using Aspose.Cells.Charts;
using System.Net.Mail;
using DSWeb.Areas.MvcShipping.DAL.MsOp_BLISSUE;
using System.Web.UI.WebControls;
namespace DSWeb.MvcShipping.DAL.BillCheckOut
{
public class BillCheckOutDAL
{
public static List<BillCheckOut_md> GetDataList(int start, int limit, string sort, string strCondition,string userid,string username, string companyid, ref int count)
{
var rangstr = GetRangDAStr("index", userid, username, companyid);
var strSql = new StringBuilder();
strSql.Append(" select * from ");
strSql.Append(" BillCheckOut where 1=1 ");
var sortstring = DatasetSort.Getsortstring(sort);
PagedQuaryParam pp = new PagedQuaryParam();
pp.strSql = strSql.ToString();
pp.start = start;
pp.limit = limit;
pp.strCondition = strCondition;
pp.defaultsortstr = "CREATETIME desc";
pp.sortstring = sortstring;
pp.rangestr = rangstr;
var result = PagedQuaryStr(pp);
count = PagedCount(pp);
return SetData(result);
}
public static List<VW_BillCheckOut_Detail_md> GetBodyList(string LINKGID)
{
var cdc = new CommonDataContext();
var dataList = cdc.VW_BillCheckOut_Detail.Where(x=>x.LINKGID== LINKGID).ToList();
//var count = dataList.Count();
//var list = dataList.Skip(start).Take(limit).ToList();
return dataList;
}
public static string GetRangDAStr(string tb, string userid, string username, string companyid)
{
string str = "";
var strSql = new StringBuilder();
strSql.Append("SELECT ");
strSql.Append(" VISIBLERANGE,OPERATERANGE,AUTHORITYID,VSSQL ");
strSql.Append(" from VW_User_Authority ");
strSql.Append(" where [NAME]='modBillCheckOut' and USERID='" + userid + "' and ISDELETE=0");
string visiblerange = "4";
string operaterange = "4";
string AUTHORITYID = "";
string VSSQL = "";
Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
{
while (reader.Read())
{
visiblerange = Convert.ToString(reader["VISIBLERANGE"]);
operaterange = Convert.ToString(reader["OPERATERANGE"]);
AUTHORITYID = Convert.ToString(reader["AUTHORITYID"]);
VSSQL = Convert.ToString(reader["VSSQL"]);
break;
}
reader.Close();
}
if (visiblerange == "4")
{
str = "1=2";
}
else if (visiblerange == "3")
{
str = " (INPUTBY='" + username + "' OR SENDER='" + username + "' OR CHECKOUTUSER='" + username + "' )";
}
else if (visiblerange == "2")
{
if (tb == "index")
{
var rangeDa = new RangeDA();
var deptid = rangeDa.GetDEPTGID(userid);
str = $" exists(select 1 from vw_user where deptgid='{deptid}' and SHOWNAME in(INPUTBY,SENDER,CHECKOUTUSER)) ";
}
else
{
str = " (UPPER(CORPID)='" + companyid + "' or SALECORPID='" + companyid + "') ";
}
}
else if (visiblerange == "5")
{
if (tb == "index")
{
var userstr = new StringBuilder();
userstr.Append(" select COMPANYID from user_authority_range_company where userid='" + userid + "' and AUTHORITYID='" + AUTHORITYID + "' and VISIBLERANGE=1");
Database userdb = DatabaseFactory.CreateDatabase();
using (IDataReader reader = userdb.ExecuteReader(CommandType.Text, userstr.ToString()))
{
str = "";
while (reader.Read())
{
if (str == "")
{
str = " (CORPID='" + Convert.ToString(reader["COMPANYID"]) + "' or SALECORPID='" + Convert.ToString(reader["COMPANYID"]) + "' ";
}
else
{
str = str + " or CORPID='" + Convert.ToString(reader["COMPANYID"]) + "' or SALECORPID='" + Convert.ToString(reader["COMPANYID"]) + "'";
};
}
str = str + ")";
reader.Close();
}
}
else
{
str = " (UPPER(CORPID)='" + companyid + "' or SALECORPID='" + companyid + "') ";
}
}
else if (visiblerange == "6")
{
if (tb == "index")
{
str = " EXISTS (select 1 from user_authority_range_op P left join [user] u on (u.GID=P.OPID) where (INPUTBY=U.SHOWNAME OR SENDER=U.SHOWNAME OR CHECKOUTUSER=U.SHOWNAME ) AND P.userid='" + userid + "' and P.AUTHORITYID='" + AUTHORITYID + "' and P.VISIBLERANGE=1) ";
}
else
{
str = " (UPPER(CORPID)='" + companyid + "' or SALECORPID='" + companyid + "') ";
}
}
else if (visiblerange == "1")
{
str = " (UPPER(B.Corpid)='" + companyid + "' or B.SALECORPID='" + companyid + "') ";
}
VSSQL = VSSQL.Trim();
if (!string.IsNullOrEmpty(VSSQL))
{
if (!string.IsNullOrEmpty(str))
{
str = str + " and (" + VSSQL + ") ";
}
else
{
str = " (" + VSSQL + ") ";
}
}
return str;
}
private static List<BillCheckOut_md> SetData(StringBuilder strSql, bool isNoForward = false)
{
var headList = new List<BillCheckOut_md>();
Database db = DatabaseFactory.CreateDatabase();
using (IDataReader reader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
{
while (reader.Read())
{
BillCheckOut_md data = new BillCheckOut_md();
#region Set DB data to Object
data.GID = Convert.ToString(reader["GID"]);
data.CHECKOUTNO = Convert.ToString(reader["CHECKOUTNO"]);
data.CUSTOMERNAME = Convert.ToString(reader["CUSTOMERNAME"]);
data.CORPID = Convert.ToString(reader["CORPID"]);
data.SALECORPID = Convert.ToString(reader["SALECORPID"]);
data.INPUTBY = Convert.ToString(reader["INPUTBY"]);
if (reader["CREATETIME"] != DBNull.Value)
data.CREATETIME = Convert.ToDateTime(reader["CREATETIME"]);
data.MODIFIER = Convert.ToString(reader["MODIFIER"]);
if (reader["MODIFYTIME"] != DBNull.Value)
data.MODIFYTIME = Convert.ToDateTime(reader["MODIFYTIME"]);
//if (reader["SENDED"] != DBNull.Value)
// data.SENDED = Convert.ToBoolean(reader["SENDED"]);
data.SENDED =(bool) getValue(reader, "SENDED");
data.SENDER = Convert.ToString(reader["SENDER"]);
if (reader["SENDTIME"] != DBNull.Value)
data.SENDTIME = Convert.ToDateTime(reader["SENDTIME"]);
data.RECEIVER = Convert.ToString(reader["RECEIVER"]);
data.RECEIVEEMAIL = Convert.ToString(reader["RECEIVEEMAIL"]);
//if (reader["ISCHECKOUT"] != DBNull.Value)
// data.ISCHECKOUT = Convert.ToBoolean(reader["ISCHECKOUT"]);
data.ISCHECKOUT = (bool)getValue(reader, "ISCHECKOUT");
if (reader["CHECKOUTTIME"] != DBNull.Value)
data.CHECKOUTTIME = Convert.ToDateTime(reader["CHECKOUTTIME"]);
data.CHECKOUTUSER = Convert.ToString(reader["CHECKOUTUSER"]);
data.MAILPDFURL = Convert.ToString(reader["MAILPDFURL"]);
data.SIGNPDFURL = Convert.ToString(reader["SIGNPDFURL"]);
#endregion
headList.Add(data);
}
reader.Close();
}
return headList;
}
public static DBResult DoSave(string opstatus, string data, string SHOWNAME, string companyid) {
var result = new DBResult();
try {
var cdc = new CommonDataContext();
var headData = JsonConvert.Deserialize<BillCheckOut_md>(data);
if (headData == null) headData=new BillCheckOut_md();
if (headData.SENDED == null) headData.SENDED = false;
if (headData.ISCHECKOUT == null) headData.ISCHECKOUT = false;
if (opstatus == "add")
{
headData.GID = Guid.NewGuid().ToString();
headData.INPUTBY = SHOWNAME;
headData.CORPID= companyid;
var billnoset = MsSysBillNoSetDAL.GetData("OPLBNAME='签单管理'", companyid);
if (billnoset.BILLTYPE != "")
headData.CHECKOUTNO = MsSysBillNoSetDAL.GetBillNo(billnoset, headData.INPUTBY.ToString().Trim(), headData.INPUTBY.ToString().Trim());
else {
result.SetErrorInfo("未配置命名规则【签单管理】");
return result;
}
//headData.CHECKOUTNO = PubSysDAL.GetBillNo("0311");
cdc.BillCheckOut.Add(headData);
}
else if (opstatus == "edit")
{
var oldheaddata = cdc.BillCheckOut.First(x => x.GID == headData.GID);
oldheaddata = AutoMapperHelper.MapTo<BillCheckOut_md, BillCheckOut_md>(headData);
cdc.BillCheckOut.AddOrUpdate(oldheaddata);
}
//设定sended ischange默认值
cdc.SaveChanges();
headData = cdc.BillCheckOut.FirstOrDefault(x => x.GID == headData.GID);
result.OK("保存成功", headData);
} catch (Exception e) {
result.SetErrorInfo(e.Message);
}
return result;
}
#region 通知签单
/// <summary>
/// 向客户发出签单条
/// </summary>
/// <param name="BSNOs"></param>
/// <returns></returns>
public static DBResult NoticeCustomerToCheckOut(string BSNOs,string path,string username)
{
var result = new DBResult();
var gidList= BSNOs.Split(',').ToList();
var cdc = new CommonDataContext();
var headList = cdc.BillCheckOut.Where(x => gidList.Contains(x.GID)).ToList();
foreach (var item in headList) {
var cansend = CanSend(item);
if (!cansend.Success) return cansend;
}
var customernames = headList.Select(s => s.CUSTOMERNAME).ToList();
var = cdc.V_CUSTOMER_NODR.Where(x => customernames.Contains(x.CUSTOMERNAME)).ToList();
bool (BillCheckOut_md head) {
var _result = true;
if (.Exists(x => x.CUSTOMERNAME == head.CUSTOMERNAME))
{
var zq= .First(x => x.CUSTOMERNAME == head.CUSTOMERNAME);
if (zq.ACCTYPE == "票结")
{//看这些业务欠费没有
var bsnolist = cdc.BillCheckOut_Detail.Where(x => x.LINKGID == head.GID).Select(s => s.BSNO).ToList();
var billgainList = cdc.v_op_bill_gain.Where(x => bsnolist.Contains(x.PARENTID)).ToList();
if (billgainList.Exists(x => x.TTLNODR > 0)) {
return false;
}
}
else
//if (zq.ACCTYPE == "月结")
{
if (zq.CQTTLNODR > 0) {
return false;
}
}
return _result;
}
else {
_result = false;
}
return _result;
}
var nosendCust = new List<string>();
foreach (var item in headList)
{
//20230608 判断客户是否欠费
//如月结 看是否有超期欠费
//如票结 看是否该票欠费
//如有 则不发邮件
var cansendemail = (item);
if (!cansendemail) {
if (nosendCust.Exists(x => x == item.CUSTOMERNAME))
{
}
else {
nosendCust.Add(item.CUSTOMERNAME);
}
}
var _r= DoSendMail(item,path, cansendemail);
if (_r.Success)
{
item.SENDED = true;
item.SENDTIME = DateTime.Now;
item.SENDER = username;
}
else {
return _r;
}
}
cdc.SaveChanges();
result.OK("生成和发送签单条成功");
if (nosendCust!=null && nosendCust.Count>0) {
var custstr = string.Join( ",",nosendCust);
result.OK($"但以下客户由于欠费原因没有发送邮件【{custstr}】");
}
return result;
}
public static DBResult SaveSignPdf(string GID, string Base64Str, string path, string username) {
var result = new DBResult();
try
{
var cdc = new CommonDataContext();
var head = cdc.BillCheckOut.FirstOrDefault(x => x.GID == GID);
byte[] bytes = Convert.FromBase64String(Base64Str);
string location = path+"/"+ head.CHECKOUTNO + "_Sign.pdf";
head.SIGNPDFURL = location;
if (File.Exists(location))
{
File.Delete(location);
}
System.IO.FileStream stream = new FileStream(location, FileMode.CreateNew);
System.IO.BinaryWriter writer = new BinaryWriter(stream);
writer.Write(bytes, 0, bytes.Length);
writer.Close();
head.ISCHECKOUT = true;
head.CHECKOUTUSER=username;
head.CHECKOUTTIME=DateTime.Now;
//head.SIGNPDFURL = location;
cdc.BillCheckOut.AddOrUpdate(head);
cdc.SaveChanges();
//var BodyList = cdc.BillCheckOut_Detail.Where(x => x.LINKGID == GID).ToList();
//var BsnoList = BodyList.Select(s => s.BSNO).ToList();
//var condition = "b.bsno in('"+string.Join(",", BsnoList) +"')";
//var _recordcount = 0;
//var blissuedataList = MsOp_BLISSUEDAL.GetDataList(condition, 0, 999, out _recordcount, "");
//var QCResult = MsOp_BLISSUEDAL.QC(blissuedataList, username, "签单条签字签出", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), username);
var QCResult = DoQC(GID, username);
result.OK(head.SIGNPDFURL);
}
catch (Exception e) {
result.SetErrorInfo(e.Message);
}
return result;
}
public static DBResult DoQC(string GID,string username) {
var cdc = new CommonDataContext();
var BodyList = cdc.BillCheckOut_Detail.Where(x => x.LINKGID == GID).ToList();
var BsnoList = BodyList.Select(s => s.BSNO).ToList();
var condition = "b.bsno in('" + string.Join("','", BsnoList) + "')";
var _recordcount = 0;
var blissuedataList = MsOp_BLISSUEDAL.GetDataList(condition, 0, 999, out _recordcount, "");
var QCResult = MsOp_BLISSUEDAL.QC(blissuedataList, username, "签单条签字签出", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), username);
return QCResult;
}
public static DBResult CanSend(BillCheckOut_md head) {
var result = new DBResult();
result.OK();
if (string.IsNullOrWhiteSpace(head.RECEIVEEMAIL)) {
result.SetErrorInfo("未指定收件人邮箱");
}
return result;
}
public static DBResult DoSendMail(BillCheckOut_md head, string path,bool dosend=true)
{
var result = new DBResult();
//1根据业务的明细 生成一个pdf
result=MakeCheckOutPdf( head, path);
if (!result.Success) return result;
var filename = result.Message;
//2作为附件发出
if (dosend)
{
result = SendCheckOutEmail(head, path);
}
return result;
}
public static DBResult MakeCheckOutPdf(BillCheckOut_md head, string path) {
var result = new DBResult();
//读取基本dpf 在其中增加内容
PDFHelper ph = new PDFHelper();
result = ph.MakePdf_BillCheckOut(head, path);
return result;
}
public static DBResult SendCheckOutEmail(BillCheckOut_md head,string path)
{
var cdc = new CommonDataContext();
var result = new DBResult(true, "");
try
{
head = cdc.BillCheckOut.FirstOrDefault(x => x.GID == head.GID);
var detailList = cdc.VW_BillCheckOut_Detail.Where(x => x.LINKGID == head.GID).ToList();
var mblnoList = detailList.Select(s => s.MBLNO).ToList();
var mblnostr = string.Join(",", mblnoList);
if (mblnostr.Length > 50) {
mblnostr = mblnostr.Substring(0, 50) + "...等";
}
var mailtitle = mblnostr+" 领单申请";
var Body = new StringBuilder();
Body.Append("<html> <Body>");
Body.Append("<br />尊敬的客户:<br />您的提单已经生成,请携带领单申请书签单,谢谢!");
//Body.Append("<br />客户名称:" + headData.CUSTOMERNAME);
//Body.Append("<br />揽货人" + headData.SALE);
//Body.Append("<br />录入人" + headData.INPUTBY);
//Body.Append("<br />港口:" + headData.DESTINATION);
//Body.Append("<br />船期:" + headData.ETD);
//Body.Append("<br />船公司:" + headData.CARRIER);
//Body.Append("<br />箱量:" + headData.CNTRTOTAL);
//Body.Append("<br />备注:" + OrderData.REMARK);
Body.Append("</Body></html> ");
var mailto = head.RECEIVEEMAIL;
//var oplist = SysUserDAL.GetDataList("U.SHOWNAME='" + op + "' or U.SHOWNAME='" + headData.SALE + "' or U.SHOWNAME='" + OrderData.INPUTBY + "' ");
//foreach (var opbs in oplist)
//{
// if (opbs.EMAIL1 != "")
// {
// if (mailto == "")
// mailto = opbs.EMAIL1;
// else
// mailto = mailto + ";" + opbs.EMAIL1;
// }
//}
//if (mailto != "")
//{
// var j = 0;
// var filepath = "";
// var doclist = ReceiptDocDAL.GetDocList("BSNO='" + headData.BSNO + "'", " MODIFIEDTIME DESC ");
// foreach (var doc in doclist)
// {
// if (j == 0)
// {
// filepath = doc.Driect_URL;
// }
// j = j = 1;
// }
// result = MsSeaeOrderDAL.SendMailWithFile(mailtitle, Body.ToString(), filepath, mailto, Convert.ToString(Session["SHOWNAME"]));
//}
//20230328 首先trycatch删除 head.MAILPDFURL_*的文件
//然后复制一个head.MAILPDFURL文件至head.MAILPDFURL_yyyyMMddHHmm.pdf
//DirectoryInfo direction = new DirectoryInfo(filepath);
//var allfilename = head.MAILPDFURL.Replace(".pdf", "_*");
//FileInfo[] files= direction.GetFiles(allfilename,SearchOption.AllDirectories);
//if (files != null && files.Length > 0) {
// for (int i = 0; i < files.Length; i++)
// {
// try {
// File.Delete(files[i].FullName);
// }
// catch(Exception ex)
// {
// }
// }
//}
var filedic = GetLogicInfo(head.GID, "filename");
var upddic = new Dictionary<string,string>();
if (filedic!=null && filedic.Count>0)
foreach (var item in filedic) {
if (item.Value == "1") {
try
{
File.Delete(path+"/" + item.Key);
upddic.Add(item.Key, "0");
}
catch(Exception ex)
{
}
}
}
string sourceFile = path+"/" + head.CHECKOUTNO+".pdf";
string filelastname = DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
string destinationFile = sourceFile.Replace(".pdf","_") + filelastname ;
//记录复制的附件到
if (System.IO.File.Exists(sourceFile))
{
// true is overwrite
System.IO.File.Copy(sourceFile, destinationFile, true);
}
upddic.Add(head.CHECKOUTNO + "_" + filelastname , "1");
SaveLogicInfo(head.GID, "filename", upddic);
//var sendpath = destinationFile.Replace(path, "../../UploadFiles/MailFile");
SendEmail se = new SendEmail(mailto, head.SENDER, "", "", mailtitle, Body.ToString(), true);
se.Attachments(destinationFile);
se.SetSmtp();
result.OK("发送成功");
}
catch (Exception e)
{
result.Success = false;
result.Message = e.Message;
BasicDataRefDAL.SaveLog(e.Message, "", "签单条邮件", "发送错误");
}
return result;
}
public class BillCheckOutEmail
{
Multipart multipart = new Multipart("mixed");
/// <summary>
/// 添加文件
/// </summary>
/// <param name="file"></param>
/// <param name="name"></param>
public bool AddFile(string file, string name)
{
if (!System.IO.File.Exists(file))
{
return false;
}
try
{
System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
//附件
var attimg = new MimePart(MediaTypeNames.Application.Octet)
{
Content = new MimeContent(fs, ContentEncoding.Default),
ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Default,
FileName = name,
IsAttachment = true,
};
multipart.Add(attimg);
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 发送
/// </summary>
/// <param name="subject">主题</param>
/// <param name="from">发送人</param>
/// <param name="to">接收人</param>
/// <param name="html">邮件内容支持html</param>
/// <returns></returns>
public string Send(string subject, string from, string to, string html)
{
using (var smtp = new MailKit.Net.Smtp.SmtpClient())
{
MimeMessage mail = new MimeMessage();
mail.From.Add(new MailboxAddress("Yuan天空", from));
mail.To.Add(new MailboxAddress(to, to));
mail.Subject = subject;
if (string.IsNullOrEmpty(html))
{
return "发送内容不能为空";
}
var Html = new TextPart(MimeKit.Text.TextFormat.Html)
{
Text = html
};
multipart.Add(Html);
mail.Body = multipart;
smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
//连接邮箱服务器
//!!!需要注意的是阿里云服务器默认是禁止25端口的,安全组添加也不行需要提交阿里云审核才能开通 , 这里使用587端口是可以发送的(服务器实测发送延迟很高 ,本地调试发送挺快, 不知道是不是服务器配置比较低的原因)
smtp.Connect("smtp.qq.com", 587, SecureSocketOptions.None);
//登录认证 qq邮箱账号和授权密钥
smtp.Authenticate("xxxx@qq.com", "xxxx");
smtp.Timeout = 600000;
string res = "";
smtp.Send(mail);
smtp.Disconnect(true);
return res;
}
}
}
#endregion
}
}