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 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 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 SetData(StringBuilder strSql, bool isNoForward = false) { var headList = new List(); 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(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(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 通知签单 /// /// 向客户发出签单条 /// /// /// 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; } foreach (var item in headList) { var _r= DoSendMail(item,path); if (_r.Success) { item.SENDED = true; item.SENDTIME = DateTime.Now; item.SENDER = username; } else { return _r; } } cdc.SaveChanges(); result.OK("发送成功"); 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); result.OK(head.SIGNPDFURL); } catch (Exception e) { result.SetErrorInfo(e.Message); } return result; } 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) { var result = new DBResult(); //1根据业务的明细 生成一个pdf result=MakeCheckOutPdf( head, path); if (!result.Success) return result; var filename = result.Message; //2作为附件发出 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(" "); Body.Append("
尊敬的客户:
您的提单已经生成,请携带领单申请书签单,谢谢!"); //Body.Append("
客户名称:" + headData.CUSTOMERNAME); //Body.Append("
揽货人" + headData.SALE); //Body.Append("
录入人" + headData.INPUTBY); //Body.Append("
港口:" + headData.DESTINATION); //Body.Append("
船期:" + headData.ETD); //Body.Append("
船公司:" + headData.CARRIER); //Body.Append("
箱量:" + headData.CNTRTOTAL); //Body.Append("
备注:" + OrderData.REMARK); Body.Append(" "); 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(); 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"); /// /// 添加文件 /// /// /// 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; } } /// /// 发送 /// /// 主题 /// 发送人 /// 接收人 /// 邮件内容支持html /// 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 } }