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
{
///
/// 采购入库红字
///
public class PurchaseReceiveDoctNegative
{
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["PurRDCRDNAME"];
///
/// 获取采购入库单(红字)
///
/// 传入参数
///
public string Get(List infos)
{
List szJson = new List();
DataTable dt = null;
DataTable dtNew = null;
string json = "";
string connS = "";
if (infos.Count <= 0)
{
throw new Exception("传送数据为空!");
}
string res = string.Empty;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
string sql = string.Empty;
foreach (ICSPurchaseReceiveDoc info in infos)
{
try
{
connS = string.Format(connString, info.WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
if (info.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + info.MTime);
sql = @"select a.ID,a.cCode,a.cVenCode,''as cVenName,cWhCode,''as cWhName,cARVCode,cMaker,dnmaketime,cHandler,dVeriDate,
AutoID,irowno,cInvCode,iQuantity,iNum,iUnitCost,iArrsId
FROM RdRecord01 a
LEFT JOIN rdrecords01 b on a.ID=b.ID
INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and iQuantity<0";
if (!string.IsNullOrWhiteSpace(info.RCVTCode))
{
sql += " and a.cCode='{0}'";
}
if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
{
sql += " and ISNULL(b.cbCloseTime,ISNULL(a.cChangAuditTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime))))>='{2}'";
}
if (!string.IsNullOrWhiteSpace(info.User))
{
sql += "and a.CMAKER='{3}'";
}
sql = string.Format(sql, info.RCVTCode, ERPDB, info.MTime, info.User);
dt = DBHelper.SQlReturnData(sql, cmd);
if (dtNew == null)
dtNew = dt;
else
dtNew.Merge(dt);
cmd.Transaction.Commit();
}
catch (Exception ex)
{
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;
}
///
//创建采购入库单(红字)
///
///
///
public string CreatePurchaseReceiveDoctNegative(List Bills)
{
string szJson = "";
string sql = "";
string connS = "";
int iFatherId = 0;
int iChildId = 0;
DateTime time = DateTime.Now;
int num = 0;
DataTable dtNew1 = null;
DataTable dtNew2 = null;
decimal iTaxRate = 0;
VouchKey key = new VouchKey();
if (Bills.Count <= 0)
{
throw new Exception("传送数据为空!");
}
string res = string.Empty;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
foreach (ICSPurchaseReceiveDoc head in Bills)
{
try
{
string iFatherIdTwo = "";
connS = string.Format(connString, head.WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
if (DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
{
}
else
{
throw new Exception("U8正在整理现存量,请稍后再试");
}
string[] ss = head.WorkPoint.Split('_');
ERPDB = ss[1];
num = head.details.Count();
string[] dd = CRNALL.Split('~');
string crdname = dd[0];
string carname = dd[1];
string surface = dd[2];
string cardnewcode = DBHelper.GetCardNumber(carname, cmd);
Dictionary dic = DBHelper.GetAllCode("" + ERPDB + "", surface, "" + num + "", head.WorkPoint);
iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
iChildId = Convert.ToInt32(dic["iChildId"].ToString());
DateTime dates = DateTime.Now;
string iBaseCodeLen = DBHelper.GetAllRDCode(cardnewcode, "" + time + "", "admin", head.WorkPoint);
string cRDcode = DBHelper.GetRDCode(crdname, cmd);
string DEF_ID08 = DBHelper.GetDefaultTemplate(cardnewcode, cmd);
if (head.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + head.MTime);
#region 验证入库数量不能大于采购订单数量
// foreach (ICSPurchaseReceiveDocs body in head.details)
// {
// sql = @"SELECT a.iQuantity,a.ID,isnull(a.iReceivedQTY,0) as iReceivedQTY,isnull(a.freceivedqty,0) as freceivedqty,ISNULL(c.fInExcess,0) AS fInExcess
// FROM dbo.PO_Podetails a
// INNER JOIN dbo.PO_Pomain b ON a.POID=b.POID
// LEFT JOIN dbo.Inventory c ON a.cInvCode=c.cInvCode
// where a.ID='" + head.ID + "'";
// cmd.CommandText = sql;
// DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
// if (dtQty != null && dtQty.Rows.Count > 0)
// {
// decimal fInExcess = decimal.Parse(dtQty.Rows[0]["fInExcess"].ToString());//入库超额上限
// decimal PoQty = decimal.Parse(dtQty.Rows[0]["iQuantity"].ToString());
// decimal iReceicedQty = decimal.Parse(dtQty.Rows[0]["iReceivedQTY"].ToString());//累计到货数量
// decimal freceivedqty = decimal.Parse(dtQty.Rows[0]["freceivedqty"].ToString());//合格品入库数量
// PoQty = PoQty * (1 + fInExcess);
// log.Info("PO数量:" + PoQty.ToString() + "入库超额上限:" + fInExcess.ToString() + ",累计到货数量:" + iReceicedQty.ToString() + ",合格品入库数量:" + freceivedqty.ToString());
// //2021-11-05 回写字段变更,见行408
// //decimal to = PoQty - iReceicedQty - freceivedqty;
// decimal to = PoQty - freceivedqty;
// if (body.Quantity > to)
// {
// throw new Exception("入库数量" + body.Quantity.ToString("f3") + "大于采购订单可入库数量" + to.ToString("f3")
// );
// }
// }
//}
#endregion
#region 采购入库单表头
string BusType = "";//业务类型
sql = @"select b.POID,b.cPOID,a.cVenCode,a.cDepCode,a.cexch_name,a.iTaxRate,a.cMaker,a.cpocode,
b.nflat,a.cPersonCode,a.cptcode ,a.ID,a.cCode,a.cBusType
FROM PU_ArrivalVouch a
LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
WHERE a.cCode ='" + head.DNRTCode + "'";
cmd.CommandText = sql;
DataTable dtPOMain = DBHelper.SQlReturnData(sql, cmd);
if (dtPOMain != null && dtPOMain.Rows.Count > 0)
{
string cSource = "";
string cCode = "";
int bredvouch = 0;
string WHCode = "";
BusType = dtPOMain.Rows[0]["cBusType"].ToString();
//校验采购订单类型是固定资产仓库
if (BusType.Equals("固定资产"))
{
string sqlwh = @"SELECT bWhAsset FROM Warehouse WHERE cWhCode='" + head.WHCode + "'";
cmd.CommandText = sqlwh;
DataTable dtwhcode = DBHelper.SQlReturnData(sqlwh, cmd);
log.Info(dtwhcode.Rows[0]["bWhAsset"].ToString());
if (!dtwhcode.Rows[0]["bWhAsset"].ToString().Equals("True"))
{
throw new Exception("采购订单:" + dtPOMain.Rows[0]["cPOID"].ToString() + ",业务类型:固定资产,只能入固定资产仓库!");
}
else
{
WHCode = head.WHCode;
}
}
else
{
WHCode = head.WHCode;
}
cSource = "采购退货单";
cCode = dtPOMain.Rows[0]["cCode"].ToString();
bredvouch = 1;
sql = @"
INSERT INTO dbo.RdRecord01
(ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,
cWhCode ,dDate ,cCode ,cRdCode ,cDepCode ,
cPersonCode ,cVenCode ,cOrderCode ,cARVCode,
cHandler ,bTransFlag ,cMaker,cDefine1,cDefine2,
dVeriDate ,bpufirst ,biafirst , dARVDate ,VT_ID ,
bIsSTQc ,ipurorderid ,iTaxRate ,iExchRate ,cExch_Name ,
bOMFirst ,bFromPreYear ,bIsComplement ,iDiscountTaxType ,ireturncount ,
iverifystate ,iswfcontrolled ,cModifyPerson ,dnmaketime ,dnverifytime ,
bredvouch ,bCredit ,iPrintCount,ipurarriveid,cPTCode,cVenPUOMProtocol)
SELECT
@ID,1,'01','" + BusType + @"',@cSource,
@cWhCode,@dDate,@cCode,@cRdCode,@cDepCode,
@cPersonCode,b.cVenCode,b.cPOID,@cARVCode,
@cHandler,0,@cMaker,b.cDefine1,b.cDefine2,
@cVeriDate,0,0,@dARVDate,@VT_ID,
0,@ipurorderid,b.iTaxRate,b.nflat,b.cexch_name,
0,0,0,0,0,
0,0,'',@dnmakertime,@dnverifytime,
@bredvouch,0,0,@ipurarriveid,b.cPTCode,b.cPayCode
FROM PU_ArrivalVouch a
LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
WHERE a.cCode ='" + head.DNRTCode + "'";
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
cmd.Parameters.Add(new SqlParameter("@cSource", cSource));
cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
cmd.Parameters.Add(new SqlParameter("@dDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy -MM-dd")));
cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
cmd.Parameters.Add(new SqlParameter("@cDepCode", dtPOMain.Rows[0]["cDepCode"].ToString()));
cmd.Parameters.Add(new SqlParameter("@cPersonCode", dtPOMain.Rows[0]["cPersonCode"].ToString()));
cmd.Parameters.Add(new SqlParameter("@cARVCode", cCode));
cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
cmd.Parameters.Add(new SqlParameter("@cVeriDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd")));
cmd.Parameters.Add(new SqlParameter("@dARVDate", Convert.ToDateTime(head.MTime)));
cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID08));
cmd.Parameters.Add(new SqlParameter("@ipurorderid", dtPOMain.Rows[0]["POID"].ToString()));
cmd.Parameters.Add(new SqlParameter("@dnmakertime", Convert.ToDateTime(DateTime.Now).ToString()));
cmd.Parameters.Add(new SqlParameter("@dnverifytime", Convert.ToDateTime(DateTime.Now).ToString()));
cmd.Parameters.Add(new SqlParameter("@bredvouch", bredvouch));
cmd.Parameters.Add(new SqlParameter("@ipurarriveid", dtPOMain.Rows[0]["ID"].ToString()));
cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode));
;
cmd.CommandText = sql;
try
{
int count = cmd.ExecuteNonQuery();
if (count <= 0)
{
log.Error("生成红字采购入库单表头失败,受影响行数<=0;");
throw new Exception("生成红字采购入库单表头失败,受影响行数<=0;");
}
}
catch (Exception ex)
{
log.Error("生成红字采购入库单表头失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
throw new Exception("生成红字采购入库单表头失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
}
}
else
{
throw new Exception("对应采购订单不存在!采购订单号:" + dtPOMain.Rows[0]["cPOID"].ToString());
}
#endregion
#region 采购入库单表体
foreach (ICSPurchaseReceiveDocs body in head.details)
{
sql = @"SELECT c.id,c.cInvCode,c.iUnitPrice ,c.iMoney AS 原币无税金额 ,c.ivouchrowno,
c.iTax AS 原币税额 ,c.iSum AS 原币价税合计 ,c.iNatUnitPrice ,
c.iNatMoney AS 本币无税金额 ,c.iNatTax AS 本币税额 ,c.iNatSum AS 本币价税合计 ,
c.iTaxPrice ,c.freceivedqty AS 合格品入库数量 ,c.iPerTaxRate,b.Autoid,a.cCode,a.dDate
FROM dbo.PU_ArrivalVouch a
LEFT JOIN dbo.PU_ArrivalVouchs b ON a.ID=b.ID
LEFT JOIN dbo.PO_Podetails c ON b.iPOsID=c.ID
left JOIN dbo.PO_Pomain d ON c.POID=d.POID
where b.AutoID='" + body.DNRTDetailID + @"' ";
cmd.CommandText = sql;
DataTable dtPODetails = DBHelper.SQlReturnData(sql, cmd);
decimal iUnitPrice = 0;
decimal iNatUnitPrice = 0;
decimal iTaxPrice = 0;
string id = "";
string code = "";
string date = "";
if (dtPODetails != null && dtPODetails.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iUnitPrice"].ToString()))
iUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iUnitPrice"].ToString());//原币无税单价
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iNatUnitPrice"].ToString()))
iNatUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iNatUnitPrice"].ToString());//本币无税单价
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iTaxPrice"].ToString()))
iTaxPrice = decimal.Parse(dtPODetails.Rows[0]["iTaxPrice"].ToString());//原币含税单价
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iPerTaxRate"].ToString()))
iTaxRate = Convert.ToDecimal(dtPODetails.Rows[0]["iPerTaxRate"]);
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["Autoid"].ToString()))//采购退货单字体标识
id = dtPODetails.Rows[0]["Autoid"].ToString();
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["cCode"].ToString()))//采购退货单号
code = dtPODetails.Rows[0]["cCode"].ToString();
if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["dDate"].ToString()))//采购退货单日期
date = dtPODetails.Rows[0]["dDate"].ToString();
sql = @"INSERT INTO dbo.rdrecords01
(
AutoID ,ID ,cInvCode ,iNum ,iQuantity ,
iUnitCost ,iPrice ,iAPrice ,cBatch ,iFlag ,
dSDate ,iSQuantity ,iSNum ,iMoney ,iPOsID ,
fACost ,iNQuantity ,chVencode ,iOriTaxCost ,iOriCost ,
iOriMoney ,iOriTaxPrice ,ioriSum ,iTaxRate ,iTaxPrice ,
iSum ,bTaxCost ,cPOID ,iMatSettleState ,iBillSettleCount ,
bLPUseFree ,iOriTrackID ,cbaccounter ,dbKeepDate ,bCosting ,
iSumBillQuantity ,bVMIUsed ,iExpiratDateCalcu ,isotype ,irowno,
iArrsId,cbarvcode,dbarvdate,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10
)
select
@AutoID,@ID1,@cInvCode,0,@iQuantity,
@iUnitCost,@iPrice,@iAPrice,@cBatch,0,
null,0,0,0,b.ID,
@fACost,@iNQuantity,c.cVenCode,@iOriTaxCost,@iOriCost,
@iOriMoney,@iOriTaxPrice,@ioriSum,@iTaxRate,@iTaxPrice,
@iSum,1,c.cPOID,0,0,
0,0,null,null,d.bInCost,
null,0,0,0,@irowno,
@iArrsId,@cbarvcode,@dbarvdate,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10
FROM dbo.PU_ArrivalVouchs a
left JOIN dbo.PO_Podetails b ON a.iPOsID = b.ID
left JOIN dbo.PO_Pomain c ON b.POID = c.POID
left JOIN dbo.Warehouse d ON d.cWhCode ='{0}'
WHERE a.Autoid = '{1}'
EXEC PROC_Update_PO_RdRecord01 @ID= @ID1 ";
sql = string.Format(sql, head.WHCode, body.DNRTDetailID);
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
cmd.Parameters.Add(new SqlParameter("@ID1", iFatherId));
cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
cmd.Parameters.Add(new SqlParameter("@iQuantity", -body.Quantity));
cmd.Parameters.Add(new SqlParameter("@iUnitCost", iUnitPrice));
cmd.Parameters.Add(new SqlParameter("@iPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
cmd.Parameters.Add(new SqlParameter("@iAPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
cmd.Parameters.Add(new SqlParameter("@cBatch", body.BatchCode));
//cmd.Parameters.Add(new SqlParameter("@iSQuantity", 0));
//cmd.Parameters.Add(new SqlParameter("@iMoney", 0));
cmd.Parameters.Add(new SqlParameter("@fACost", iNatUnitPrice));
cmd.Parameters.Add(new SqlParameter("@iNQuantity", body.Quantity));
cmd.Parameters.Add(new SqlParameter("@iOriTaxCost", iUnitPrice));
cmd.Parameters.Add(new SqlParameter("@iOriCost", iTaxPrice));
cmd.Parameters.Add(new SqlParameter("@iOriMoney", Math.Round(body.Quantity * iUnitPrice, 2)));
cmd.Parameters.Add(new SqlParameter("@iOriTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
cmd.Parameters.Add(new SqlParameter("@ioriSum", Math.Round(iTaxPrice * body.Quantity, 2)));
cmd.Parameters.Add(new SqlParameter("@iTaxRate", iTaxRate));
cmd.Parameters.Add(new SqlParameter("@iTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
cmd.Parameters.Add(new SqlParameter("@iSum", Math.Round(iTaxPrice * body.Quantity, 2)));
cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
//cmd.Parameters.Add(new SqlParameter("@cPOID", head.POCode));
cmd.Parameters.Add(new SqlParameter("@iArrsId", id));
cmd.Parameters.Add(new SqlParameter("@cbarvcode", code));
cmd.Parameters.Add(new SqlParameter("@dbarvdate", Convert.ToDateTime(date)));
cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));
cmd.CommandText = sql;
try
{
int count = cmd.ExecuteNonQuery();
if (count <= 0)
{
log.Error("生成采购入库单表体失败,受影响行数<=0;");
throw new Exception("生成采购入库单表体失败,受影响行数<=0;");
}
}
catch (Exception ex)
{
log.Error("生成采购入库单表体失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
throw new Exception("生成采购入库单表体失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
}
#region 更新[采购到货单子表]PU_ArrivalVouchs 合格品入库数量20211019
sql = @"UPDATE PU_ArrivalVouchs SET fValidInQuan=ISNULL(fValidInQuan,0)+@iQty WHERE Autoid=@Autoid";
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
cmd.Parameters.Add(new SqlParameter("@Autoid", body.DNRTDetailID));
try
{
log.Info("PU_Autoid:" + body.DNRTDetailID);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
log.Error("回写采购到货单子表合格品入库数量失败:采购订单:" + dtPOMain.Rows[0]["cPOID"].ToString()+",行号:"+body.Sequence + ";异常:" + ex.Message);
throw new Exception("程序异常,请联系开发人员!");
}
#endregion
#region 更新[采购订单子表]PO_PODetails累计到货数量和累计到货金额
//sql = @"Update a set iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty,iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney FROM dbo.PO_Podetails a where a.ID='" + body.iPOsID + "'";
sql = @"
Update a set
iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney
,freceivedqty=isnull(freceivedqty ,0)+ @iQty
FROM dbo.PO_Podetails a where a.ID=@ID"
;
//2021-11-05
//1.移除 iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty 由采购到货,创建到货单CreatePU时写入iReceivedQTY,此处不再回写,累计到货数量
//2.加入 freceivedqty =isnull(freceivedqty ,0) + @iQty 合格品入库数量
cmd.CommandText = sql;
cmd.Parameters.Clear();
cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
cmd.Parameters.Add(new SqlParameter("@iMoney", body.Quantity * iUnitPrice));
cmd.Parameters.Add(new SqlParameter("@ID", body.DNRTDetailID));
try
{
log.Info("iPOsID:" + body.DNRTDetailID);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
log.Error("回写采购订单累计到货数量和累计到货金额失败:采购订单表体行号:" + body.Sequence + ";异常:" + ex.Message);
throw new Exception("程序异常,请联系开发人员!");
}
#endregion
#region 判断现存量是否超入库
sql = @"IF EXISTS(SELECT ID FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0})
BEGIN
DECLARE @MSG NVARCHAR(100)
SELECT @MSG='ERP入库数量不能大于订单数量!ID:'+CAST(ID AS NVARCHAR(100)) FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0}
RAISERROR(@MSG,16,1)
END";
sql = string.Format(sql, body.DNRTDetailID);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
#endregion
if (head.UpdateStock)
{
//更新现存量
key.cBustypeUN = "普通采购";
key.cVouchTypeUN = "01";
key.TableName = "IA_ST_UnAccountVouch01";
DBHelper.UpdateCurrentStockNEW(cmd, body.InvCode, head.WHCode, body.BatchCode, -body.Quantity, body.cFree1, body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10, key);
//DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, body.InvCode, -body.Quantity, key);
}
}
iFatherIdTwo += "'" + iFatherId + "',";
iChildId--;
////更新主键ID,DID
//DBHelper.UpdateIDandDID("rd", head.list.Count(), cmd);
}
#endregion
#region 查询
sql = @" select a.ID as ID,a.ID as IDs,a.cCode as RCVNEGCode,a.cVenCode,D.cVenName,
a.cWhCode,c.cWhName,cARVCode as DNRTCode,cMaker as CreateUser,
dnmaketime as CreateDateTime,cHandler as Checker,dVeriDate as CheckDateTime
FROM RdRecord01 a
LEFT JOIN Warehouse C ON A.cWhCode=C.cWhCode
LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and a.ID in ({0})
select a.ID as IDs, AutoID as DetailID,irowno as Sequence,
cInvCode as InvCode,iQuantity as Quantity,iNum as Amount,iArrsId as DNRTDetailID
FROM RdRecord01 a
LEFT JOIN rdrecords01 b on a.ID=b.ID
LEFT JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and a.ID in ({0}) ";
sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
if (dtNew1 == null)
dtNew1 = ds.Tables[0];
else
dtNew1.Merge(ds.Tables[0]);
if (dtNew2 == null)
dtNew2 = ds.Tables[1];
else
dtNew2.Merge(ds.Tables[1]);
#endregion
cmd.Transaction.Commit();
}
catch (Exception ex)
{
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
string RelationName = "details";
DataSet dz = new DataSet();
dtNew1.TableName = "Table0";
dtNew2.TableName = "Table1";
dz.Tables.Add(dtNew1.Copy());
dz.Tables.Add(dtNew2.Copy());
DataRelation dh = new DataRelation(RelationName, dz.Tables[0].Columns["IDs"], dz.Tables[1].Columns["IDs"]);
dz.Relations.Add(dh);
szJson = DBHelper.DataSetToJson(dz, RelationName);
return szJson;
}
///
/// 审核采购入库单(红字)
///
///
///
public bool Approve(List infos)
{
bool ResultFlag = false;
string connS = "";
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
if (infos.Count <= 0)
{
throw new Exception("传送数据为空!");
}
LogInfo(infos);
foreach (ICSPurchaseReceiveDoc head in infos)
{
try
{
connS = string.Format(connString, head.WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
if (DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint))
{
}
else
{
throw new Exception("U8正在整理现存量,请稍后再试");
}
string[] ss = head.WorkPoint.Split('_');
ERPDB = ss[1];
string sql = "";
ICSUserInfo userInfo = new ICSUserInfo();
userInfo = DBHelper.GetPersonInfo(head.User, cmd);
#region 检验单号是否存在
sql = "select * from RdRecord01 where ID='" + head.ID + "'";
DataTable dt = DBHelper.SQlReturnData(sql, cmd);
if (dt != null && dt.Rows.Count > 0)
{
string cHandler = dt.Rows[0]["cHandler"].ToString();
if (!string.IsNullOrEmpty(cHandler))
{
throw new Exception("单据ID:" + head.ID + "不是开立状态!");
}
}
else
{
throw new Exception("单据ID:" + head.ID + "在U8中不存在!");
}
#endregion
#region 审核其他出库单
sql = @"UPDATE dbo.RdRecord01 SET cHandler='" + userInfo.UserName + @"' ,
dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
DBHelper.CmdExecuteNonQuery(sql, cmd, "审核其他出库单失败!");
#endregion
sql = "select * from dbo.RdRecords01 a inner join RdRecord01 b on a.ID=b.ID where b.ID='" + head.ID + "';";
DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
if (head.UpdateStock)
{
#region 更新现存量
for (int i = 0; i < dtChecks.Rows.Count; i++)
{
//判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
//sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch='" + dtChecks.Rows[i]["cBatch"].ToString() + @"'AND cFree1='" + dtChecks.Rows[i]["cFree1"].ToString() + @"' AND cFree2='" + dtChecks.Rows[i]["cFree2"].ToString() + @"' AND cFree3='" + dtChecks.Rows[i]["cFree3"].ToString() + @"' AND cFree4='" + dtChecks.Rows[i]["cFree4"].ToString() + @"' AND cFree5='" + dtChecks.Rows[i]["cFree5"].ToString() + @"' AND cFree6='" + dtChecks.Rows[i]["cFree6"].ToString() + @"' AND cFree7='" + dtChecks.Rows[i]["cFree7"].ToString() + @"' AND cFree8='" + dtChecks.Rows[i]["cFree8"].ToString() + @"' AND cFree9='" + dtChecks.Rows[i]["cFree9"].ToString() + @"' AND cFree10='" + dtChecks.Rows[i]["cFree10"].ToString() + @"' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
if (dtItem != null && dtItem.Rows.Count > 0)
{
//if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
//{
// throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
//}
if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()))
{
throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString());
}
}
else
{
throw new Exception("物料:" + dtChecks.Rows[i]["cInvCode"].ToString() + "在现存量表中不存在!");
}
VouchKey key = new VouchKey();
key.cBustypeUN = "普通采购";
key.cVouchTypeUN = "01";
key.TableName = "IA_ST_UnAccountVouch01";
//DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);
DBHelper.UpdateCurrentStockNEW(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), dtChecks.Rows[i]["cBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(), dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(), key);
//回写fOutQuantityy
// sql = @"Update CurrentStock set fOutQuantity=isnull(fOutQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @"
// where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
//if (body.cBatch != null)
//{
// sql += "and cBatch='" + body.cBatch + "'";
//}
//else
//{
// sql += "and cBatch=''";
//}
//DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fOutQuantity失败!");
//if (head.UpdateTodoQuantity == true)
//{
#region 判断现存量是否足够
sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0)
BEGIN
DECLARE @MSG NVARCHAR(100)
SELECT @MSG='ERP待出库数量不足!AutoID:'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
RAISERROR(@MSG,16,1)
END";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
#endregion
}
#endregion
}
cmd.Transaction.Commit();
}
catch (Exception ex)
{
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
ResultFlag = true;
return ResultFlag;
// List szJson = new List();
// DataTable dt = null;
// string json = "";
// if (infos.Count <= 0)
// {
// throw new Exception("传送数据为空!");
// }
// string res = string.Empty;
// SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
// conn.Open();
// SqlTransaction sqlTran = conn.BeginTransaction();
// SqlCommand cmd = new SqlCommand();
// cmd.Transaction = sqlTran;
// cmd.Connection = conn;
// try
// {
// string sql = string.Empty;
// foreach (ICSPurchaseReceiveDoc info in infos)
// {
// if (info.MTime < new DateTime(2000, 01, 01))
// throw new Exception("请输入正确的操作时间:" + info.MTime);
// sql = @"UPDATE [{0}].dbo.RdRecord01 SET cVerifier ='" + info.User + @"' ,
// cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='" + info.ID + "'";
// sql = string.Format(sql, ERPDB);
// DBHelper.CmdExecuteNonQuery(sql, cmd, "审核采购红字入库单失败!");
// }
// cmd.Transaction.Commit();
// return json;
// }
// catch (Exception ex)
// {
// cmd.Transaction.Rollback();
// log.Error(ex.Message);
// throw new Exception(ex.Message);
// }
// finally
// {
// if (conn.State == ConnectionState.Open)
// {
// conn.Close();
// }
// conn.Dispose();
// }
}
///
/// 删除采购入库单(红字)
///
///
///
public string Delete(List infos)
{
List szJson = new List();
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;
foreach (ICSPurchaseReceiveDoc info in infos)
{
try
{
connS = string.Format(connString, info.WorkPoint);
conn = new System.Data.SqlClient.SqlConnection(connS);
conn.Open();
SqlTransaction sqlTran = conn.BeginTransaction();
cmd = new SqlCommand();
cmd.Transaction = sqlTran;
cmd.Connection = conn;
if (info.MTime < new DateTime(2000, 01, 01))
throw new Exception("请输入正确的操作时间:" + info.MTime);
sql = @"delete rdrecord11 where rdrecord11.ID='" + info.ID + "'";
sql += @"delete rdrecords11 where rdrecords11.ID='" + info.ID + "'";
//UPDATE dbo.rdrecord11 a SET cHandler='" + info.User + @"' ,
// dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE()
// WHERE a.ID='" + info.ID + "'";
DBHelper.CmdExecuteNonQuery(sql, cmd, "删除采购红字入库单失败!");
cmd.Transaction.Commit();
}
catch (Exception ex)
{
cmd.Transaction.Rollback();
log.Error(ex.Message);
throw new Exception(ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
return res;
}
public string GetSerialCode(string ID)
{
string sql = "EXEC Addins_GetSerialCode '{0}'";
sql = string.Format(sql, new object[] { ID });
return DBHelper.ExecuteScalar(CommandType.Text, sql, connString).ToString();
}
///
/// 记录日志
///
///
private void LogInfo(List Bills)
{
string HeadList = string.Empty;
string BodyList = string.Empty;
foreach (ICSPurchaseReceiveDoc head in Bills)
{
HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint;
}
log.Info(HeadList);
log.Info(BodyList);
}
}
}