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

561 lines
29 KiB

using ICSSoft.Common;
using ICSSoft.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ICSSoft.DataProject
{
/// <summary>
/// 销售发货
/// </summary>
public class SalesDeliveryNotice
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
private static string CRNALL = System.Configuration.ConfigurationManager.AppSettings["SaleDNCRDNAME"];
string bustype = string.Empty;
/// <summary>
/// 获取销售发货
/// </summary>
/// <param name="infos"></param>
/// <returns></returns>
public string Get(List<ICSSalesDeliveryNotice> infos)
{
List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
DataTable dt = null;
DataTable dtNew = null;
string connS = "";
string json = "";
if (infos.Count <= 0)
{
throw new Exception("传送数据为空!");
}
string res = string.Empty;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sql = string.Empty;
List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();
foreach (string WorkPoint in result)
{
try
{
connS = string.Format(connString, WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
foreach (ICSSalesDeliveryNotice info in infos)
{
if (WorkPoint != info.WorkPoint)
continue;
ICSUserInfo userInfo = new ICSUserInfo();
userInfo = DBHelper.GetPersonInfo(info.User, cmd);
if (info.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + info.MTime);
sql = @" select a.DLID ,a.cDLCode ,a.cCusCode,c.cCusName,a.cDepCode ,
d.cDepName,b.cordercode ,a.cMaker ,a.dcreatesystime ,
b.AutoID ,b.irowno,b.cInvCode ,b.iQuantity ,b.iNum ,b.iSOsID
FROM dbo.DispatchList a
INNER JOIN dbo.DispatchLists b ON a.DLID = b.DLID
LEFT JOIN dbo.Customer c ON a.cCusCode = c.cCusCode
left join Department d on a.cDepCode=d.cDepCode ";
if (!string.IsNullOrWhiteSpace(info.SDNCode))
{
sql += " and a.cDLCode='{0}'";
}
if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
{
sql += " and ISNULL(a.dnmodifytime ,ISNULL(a.dverifydate , ISNULL(a.dnmodifytime , a.dcreatesystime )))>='{1}'";
}
if (!string.IsNullOrWhiteSpace(info.User))
{
sql += "and a.CMAKER='{2}'";
}
sql = string.Format(sql, info.SOCode, info.MTime, userInfo.UserName);
dt = DBHelper.SQlReturnData(sql, cmd);
if (dt.Rows.Count <= 0 || dt == null)
throw new Exception("销售发货单号:" + info.SOCode + ",无信息!");
if (dtNew == null)
dtNew = dt;
else
dtNew.Merge(dt);
}
cmd.Transaction.Commit();
}
catch (Exception ex)
{
if (cmd.Transaction != null)
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
json = JsonConvert.SerializeObject(dtNew);
return json;
}
/// <summary>
/// 创建销售发货
/// </summary>
/// <param name="Bills"></param>
/// <returns></returns>
public string CerateSalesDeliveryNotice(List<ICSSalesDeliveryNotice> Bills)
{
string msg = "";
DataTable dt = null;
DataTable dtNew = null;
string connS = "";
//bool ResultFlag = false;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
VouchKey key = new VouchKey();
if (Bills.Count <= 0)
{
throw new Exception("传送数据为空!");
}
LogInfo(Bills);
List<string> result = Bills.Select(t => t.WorkPoint).Distinct().ToList();
foreach (string WorkPoint in result)
{
try
{
connS = string.Format(connString, WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
foreach (ICSSalesDeliveryNotice head in Bills)
{
string sql = "";
if (WorkPoint != head.WorkPoint)
continue;
ICSUserInfo userInfo = new ICSUserInfo();
userInfo = DBHelper.GetPersonInfo(head.User, cmd);
string[] ss = head.WorkPoint.Split('_');
ERPDB = ss[1];
#region 销售发货单表头
int num = 0;
num = head.details.Count();
string[] dd = CRNALL.Split('~');
string crdname = dd[0];
string carname = dd[1];
string surface = dd[2];
string SO_SOMain_VT_ID = DBHelper.GetDefaultTemplate("05", cmd);//目标账套销售订单VT_ID模板
DateTime time = DateTime.Now;
Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "DelNote", "" + num + "", head.WorkPoint, cmd);
int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
int iChildId = Convert.ToInt32(dic["iChildId"].ToString());
DateTime date = DateTime.Now;
string iBaseCodeLen = DBHelper.GetAllRDCode("05", "" + time + "", "admin", "", head.WorkPoint, cmd);
sql = string.Format(@"INSERT INTO dbo.DispatchList
(@DLID , @cDLCode , @cVouchType , cSTCode ,CONVERT(NVARCHAR(50),GETDATE(),23)
, @cDepCode ,SBVID , @cSOCode , @cCusCode , cPayCode
, cSCCode, cCusOAddress , cexch_name , iExchRate , iTaxRate , 0 , bReturnFlag
, bFirst , cMemo , cVerifier , cMaker , iSale, (select cCusName from {0}.dbo.Customer where cCusCode='@cCusCode')
, iVTid , ufts , cBusType , cCloser , cAccounter , cCreChpName
, bIAFirst , ioutgolden , cgatheringplan , dCreditStart , dGatheringDate , icreditdays , bCredit
, caddcode , iverifystate , ireturncount , iswfcontrolled , icreditstate , bARFirst
, cmodifier , dmoddate , dverifydate , ccusperson , dcreatesystime , dverifysystime , dmodifysystime
, csvouchtype , iflowid , bsigncreate , bcashsale , cgathingcode , cChanger , cChangeMemo
, outid , bmustbook , cBookDepcode , cBookType , bSaUsed , bneedbill , baccswitchflag
, iPrintCount , ccuspersoncode , cSourceCode , bsaleoutcreatebill , cSysBarCode , cCurrentAuditor
, csscode , cinvoicecompany , fEBweight , cEBweightUnit , cEBExpressCode , iEBExpressCoID
, SeparateID , bNotToGoldTax , cEBTrnumber , cEBBuyer , cEBBuyerNote , ccontactname , cEBprovince
, cEBcity , cEBdistrict , cmobilephone , cInvoiceCusName , cweighter , dweighttime , cPickVouchCode
, cGCRouteCode)
SELECT
@DLID , @cDLCode , @cVouchType , cSTCode ,CONVERT(NVARCHAR(50),GETDATE(),23)
, @cDepCode , 0 , @cSOCode , @cCusCode , cPayCode
, cSCCode, cCusOAddress , cexch_name , iExchRate , iTaxRate , 0 , bReturnFlag
, 0 , cMemo , cVerifier , @cMaker , 0 , (select cCusName from dbo.Customer where cCusCode='@cCusCode')
, @iVTid , ufts , cBusType , cCloser , NULL , NULL
, 0 , null , cgatheringplan , CONVERT(NVARCHAR(50),GETDATE(),23) ,NULL , NULL , 0
, caddcode , iverifystate , ireturncount , iswfcontrolled , icreditstate , 0
, NULL , NULL , NULL , ccusperson , CONVERT(NVARCHAR(50),GETDATE(),23) , dverifysystime , dmodifysystime
, csvouchtype , iflowid , 0 , 0 , cgathingcode , NULL , NULL
, outid , bmustbook , NULL , NULL , NULL , 0 , 0
, 0 , ccuspersoncode , NULL , 0 , cSysBarCode , cCurrentAuditor
, csscode , cinvoicecompany , NULL , NULL , NULL , NULL
, NULL , 0 , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , NULL , NULL , NULL , NULL
, NULL FROM SO_SOMain a
where a.cSOCode ='" + head.SOCode + "'");
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@DLID", iFatherId));
cmd.Parameters.Add(new SqlParameter("@cDLCode", iBaseCodeLen));
cmd.Parameters.Add(new SqlParameter("@cVouchType", "05"));
cmd.Parameters.Add(new SqlParameter("@cDepCode", head.DepCode));
cmd.Parameters.Add(new SqlParameter("@cMaker", userInfo.UserName));
cmd.Parameters.Add(new SqlParameter("@cSOCode", head.SOCode));
cmd.Parameters.Add(new SqlParameter("@cCusCode", head.CusCode));
cmd.Parameters.Add(new SqlParameter("@iVTid", SO_SOMain_VT_ID));
//cmd.Parameters.Add(new SqlParameter("@dDate", data.dMate));
cmd.CommandText = sql;
try
{
int count = cmd.ExecuteNonQuery();
if (count <= 0)
{
log.Error("生成销售出库单表头失败,受影响行数<=0;");
throw new Exception("生成销售出库单表头失败,受影响行数<=0;");
}
}
catch (Exception ex)
{
log.Error("生成销售出库单表头失败!销售订单号:" + head.SDNCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
throw new Exception("生成销售出库单表头失败!销售订单号:" + head.SDNCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
}
#endregion
#region 销售出库单表体
foreach (ICSSalesDeliveryNotices body in head.details)
{
#region 销售顶订单表体
sql = string.Format(@"INSERT INTO dbo.DispatchLists
(AutoID , DLID , iCorID , cWhCode , cInvCode , iQuantity , iNum
, iQuotedPrice , iUnitPrice , iTaxUnitPrice , iMoney , iTax , iSum , iDisCount , iNatUnitPrice
, iNatMoney , iNatTax , iNatSum , iNatDisCount , iSettleNum , iSettleQuantity , iBatch , cBatch
, bSettleAll , cMemo , iTB , dvDate , TBQuantity , TBNum , iSOsID , iDLsID
, KL , KL2 , cInvName , iTaxRate
, fOutQuantity , fOutNum , cItemCode , cItem_class , fSaleCost , fSalePrice , cVenAbbName
, cItemName , cItem_CName
, bIsSTQc , iInvExchRate , cUnitID , cCode , iRetQuantity , fEnSettleQuan , fEnSettleSum , iSettlePrice , dMDate , bGsp
, cGspState , cSoCode , cCorCode , iPPartSeqID , iPPartID , iPPartQty , cContractID , cContractTagCode , cContractRowGuid
, iMassDate , cMassUnit , bQANeedCheck , bQAUrgency , bQAChecking , bQAChecked , iQAQuantity , iQANum
, cCusInvCode , cCusInvName , fsumsignquantity , fsumsignnum , cbaccounter , bcosting , cordercode
, iorderrowno , fcusminprice , icostquantity , icostsum , ispecialtype , cvmivencode , iexchsum
, imoneysum , irowno , frettbquantity , fretsum , iExpiratDateCalcu , dblPreExchMomey , dblPreMomey , idemandtype
, cdemandcode , cdemandmemo , cdemandid , idemandseq , cvencode , cReasonCode , cInvSN , iInvSNCount , bneedsign
, bsignover , bneedloss , flossrate , frlossqty , fulossqty , isettletype , crelacuscode , cLossMaker
, dLossDate , dLossTime , icoridlsid , fretoutqty , body_outid , fVeriBillQty
, fVeriBillSum , fVeriRetQty , fVeriRetSum , fLastSettleQty
, fLastSettleSum , cBookWhcode , cInVouchType , cPosition , fretqtywkp , fretqtyykp , frettbqtyykp
, fretsumykp , dkeepdate , cSCloser , isaleoutid , bsaleprice , bgift , bmpforderclosed
, cbSysBarCode , fxjquantity , fxjnum
, bIAcreatebill , cParentCode , cChildCode , fchildqty , fchildrate , iCalcType , fappretwkpqty , fappretwkpsum
, fappretykpqty , fappretykpsum , fappretwkptbqty , fappretykptbqty , irtnappid , crtnappcode , fretailrealamount
, fretailsettleamount , cFactoryCode , GCSourceId , GCSourceIds , cConfirmer , dConfirmDate )
SELECT
@AutoID , @DLID , @cWhCode , @cInvCode , @iQuantity , @iNum
, iQuotedPrice , iUnitPrice , iTaxUnitPrice , iMoney , iTax , iSum , iDisCount , iNatUnitPrice
, iNatMoney , iNatTax , iNatSum , iNatDisCount , NULL , NULL
, 0 , cMemo , 0 , NULL , 0 , NULL , iSOsID , NULL
, KL , KL2 , cInvName , iTaxRate
, fOutQuantity , fOutNum , cItemCode , cItem_class , fSaleCost , fSalePrice ,NUll
, cItemName , cItem_CName
, 0 , iInvExchRate , cUnitID , NULL , 0 , 0 , 0 , 0 , NULL , 0
, NULL , @cSoCode , NULL , iPPartSeqID , iPPartID , iPPartQty , cContractID , cContractTagCode , cContractRowGuid
, NULL , NULL , 0 , 0 , 0 , 0 , 0 , 0
, cCusInvCode , cCusInvName , 0 , 0 , NULL , 0 , @cordercode
, NULL , fcusminprice , icostquantity , icostsum , NULL , NULL , iexchsum
, imoneysum , @irowno , 0 , 0 , NULL , 0 , 0 , NULL
, NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , 0 , 0 , NULL , NULL , NULL
, NULL , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , NULL
, NULL , NULL , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , isaleoutid , 1 , 0 , 0
, cbSysBarCode , NULL , NULL
, 1 , NULL , NULL , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , NULL , NULL , NULL , NULL
, NULL , NULL , NULL , NULL , NULL , NULL FROM SO_SODetails a
where a.AutoID ='" + body.SODetailID + "'");
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
cmd.Parameters.Add(new SqlParameter("@DLID", iFatherId));
cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity));
cmd.Parameters.Add(new SqlParameter("@iNum", body.Amount.ToString("0.00")));
cmd.Parameters.Add(new SqlParameter("@cSoCode", head.SOCode));
cmd.Parameters.Add(new SqlParameter("@cordercode", head.SOCode));
cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
//cmd.Parameters.Add(new SqlParameter("@dDate", data.dMate));
cmd.CommandText = sql;
try
{
int count = cmd.ExecuteNonQuery();
if (count <= 0)
{
log.Error("生成销售出库单表体失败,受影响行数<=0;");
throw new Exception("生成销售出库单表体失败,受影响行数<=0;");
}
}
catch (Exception ex)
{
log.Error("生成销售出库单表体失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
throw new Exception("生成销售出库单表体失败!销售订单号:" + head.SOCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
}
#endregion
sql = @"UPDATE a SET a.foutquantity=ISNULL(a.foutquantity,0)+" + body.Quantity + @"
FROM dbo.SO_SODetails a LEFT JOIN dbo.DispatchLists b ON a.iSOsID=b.iSOsID
WHERE b.AutoID='" + body.SODetailID + "'";
DBHelper.CmdExecuteNonQuery(sql, cmd, "回写销售订单累计发货数量失败!");
sql = @"select isnull(fOutQuantity,0)fOutQuantity,isnull(iQuantity,0)iQuantity,ISNULL(iNum, 0)iNum,ISNULL(NiNum, 0)NiNum,ISNULL(iNum, 0)-ISNULL(NiNum, 0) SiNum from SO_SODetails a
LEFT JOIN (select sum(iNum) NiNum,iSOsID from DispatchLists GROUP BY iSOsID) b on a.iSOsID=b.iSOsID
where a.AutoID='" + body.SODetailID + "'";
DataTable dtDisCheck = DBHelper.SQlReturnData(sql, cmd);
if (dtDisCheck != null && dtDisCheck.Rows.Count > 0)
{
foreach (DataRow item in dtDisCheck.Rows)
{
if (Convert.ToDecimal(item["fOutQuantity"].ToString()) == Convert.ToDecimal(item["iQuantity"].ToString()))
{
if (Convert.ToDecimal(item["iNum"].ToString()) != 0)
{
if (Convert.ToDecimal(item["SiNum"].ToString()) != 0)
{
sql = @"Update DispatchLists set iNum=isnull(iNum,0)+(" + item["SiNum"].ToString() + ") where autoid='" + iChildId + "' ";
DBHelper.CmdExecuteNonQuery(sql, cmd, "辅计量余数处理失败!");
}
}
}
}
}
iChildId--;
}
#endregion
sql = @"
select a.DLID ,a.cDLCode ,a.cCusCode,c.cCusName,a.cDepCode ,
d.cDepName,b.cordercode ,a.cMaker ,a.dcreatesystime ,
b.AutoID ,b.irowno,b.cInvCode ,b.iQuantity ,b.iNum ,b.iSOsID
FROM dbo.DispatchList a
INNER JOIN dbo.DispatchLists b ON a.DLID = b.DLID
LEFT JOIN dbo.Customer c ON a.cCusCode = c.cCusCode
left join Department d on a.cDepCode=d.cDepCode WHERE a.DLID = '{0}' ";
sql = string.Format(sql, iFatherId);
dt = DBHelper.SQlReturnData(sql, cmd);
if (dtNew == null)
dtNew = dt;
else
dtNew.Merge(dt);
}
cmd.Transaction.Commit();
}
catch (Exception ex)
{
if (cmd.Transaction != null)
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
msg = JsonConvert.SerializeObject(dtNew);
cmd.Transaction.Commit();
return msg;
}
/// <summary>
/// 审核销售发货
/// </summary>
/// <param name="infos"></param>
/// <returns></returns>
public string Approve(List<ICSSalesDeliveryNotice> infos)
{
List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
string connS = "";
string json = "";
if (infos.Count <= 0)
{
throw new Exception("传送数据为空!");
}
string res = string.Empty;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sql = string.Empty;
List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();
foreach (string WorkPoint in result)
{
try
{
connS = string.Format(connString, WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
foreach (ICSSalesDeliveryNotice info in infos)
{
if (WorkPoint != info.WorkPoint)
continue;
ICSUserInfo userInfo = new ICSUserInfo();
userInfo = DBHelper.GetPersonInfo(info.User, cmd);
if (info.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + info.MTime);
sql = @"UPDATE DispatchList SET cMaker ='" + userInfo.UserName + @"' ,
dverifysystime =CONVERT(VARCHAR(50),GETDATE(),112),dverifydate =GETDATE() WHERE DLID='{0}'";
sql = string.Format(sql, info.ID);
DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
}
cmd.Transaction.Commit();
}
catch (Exception ex)
{
if (cmd.Transaction != null)
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
return json;
}
/// <summary>
/// 删除销售发货
/// </summary>
/// <param name="infos"></param>
/// <returns></returns>
public string Delete(List<ICSSalesDeliveryNotice> infos)
{
List<ICSSalesDeliveryNotice> szJson = new List<ICSSalesDeliveryNotice>();
if (infos.Count <= 0)
{
throw new Exception("传送数据为空!");
}
string res = string.Empty;
string connS = "";
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sql = string.Empty;
List<string> result = infos.Select(t => t.WorkPoint).Distinct().ToList();
foreach (string WorkPoint in result)
{
try
{
connS = string.Format(connString, WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
foreach (ICSSalesDeliveryNotice info in infos)
{
if (WorkPoint != info.WorkPoint)
continue;
if (info.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + info.MTime);
sql = @" DELETE DispatchList WHERE DLID={0}";
sql = string.Format(sql, info.ID);
DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!");
}
cmd.Transaction.Commit();
}
catch (Exception ex)
{
if (cmd.Transaction != null)
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
return res;
}
/// <summary>
///
/// 记录日志
/// </summary>
/// <param name="Bills"></param>
private void LogInfo(List<ICSSalesDeliveryNotice> Bills)
{
string HeadList = string.Empty;
string BodyList = string.Empty;
foreach (ICSSalesDeliveryNotice head in Bills)
{
HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint;
foreach (ICSSalesDeliveryNotices body in head.details)
{
BodyList += "\r\n 表体主键ID:数量:" + body.Quantity;
}
}
log.Info(HeadList);
log.Info(BodyList);
}
}
}