using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using NFine.Code;
using NFine.Data.Extensions;
using NFine.Domain._03_Entity.SRM;
using NFine.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Net;
using NFine.Application.WMS;
using NFine.Application.Models;
using System.Reflection;
using NFine.Application.Entity;
using NFine.Domain.Entity.SystemSecurity;
using System.Xml;
using System.Collections;
using System.Data.SqlClient;
namespace NFine.Application.BBWMS
{
#region 工单子线实体对象
///
/// 新增工单子线实体对象
///
public class MOModel
{
///
/// 工单编码
///
public string MOCode { get; set; }
///
/// 行号
///
public string Sequence { get; set; }
///
/// 物料编码
///
public string InvCode { get; set; }
///
/// 数量
///
public decimal Quantity { get; set; }
///
///
///
public string ExtensionID { get; set; }
}
#endregion
public class ICSManufactureReceiveApp : RepositoryFactory
{
#region 获取送检单主表数据
///
/// 获取产品入库单数据
///
///
///
///
public DataTable GetManufactureReceive(string queryJson, ref Pagination jqgridparam)
{
DataTable dt = new DataTable();
var queryParam = queryJson.ToJObject();
List parameter = new List();
object Figure = GetDecimalDigits();
string wheresql = string.Empty;
string workPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
if (!string.IsNullOrWhiteSpace(queryJson))
{
if (!string.IsNullOrWhiteSpace(queryParam["POCode"].ToString()))
{
wheresql += " and a.CheckCode like '%" + queryParam["POCode"].ToString() + "%' ";
}
}
if (NFine.Code.OperatorProvider.Provider.GetCurrent().RoleEnCode != "admin")
{
wheresql += " and a.WorkPoint='" + workPoint + "'";
}
#region [SQL]
string sql = $@"SELECT DISTINCT a.CheckCode CheckNo,b.FinalResult,b.FinalUser,b.FinalTime,a.MTIME,a.MUSERName from ICSInspectionSheet a
LEFT JOIN IcsMatCheckResult b ON b.EATTRIBUTE4='1'AND a.CheckCode=b.CheckNo
WHERE 1=1 {wheresql} ";
#endregion
return Repository().FindTablePageBySql(sql.ToString(), parameter.ToArray(), ref jqgridparam);
}
#endregion
#region 获取条码信息
///
/// 获取条码信息
///
///
///
///
///
///
///
public DataTable GetManufactureReceiveLot(string ProductionCode, string WHCode, string InvCode,ref Pagination jqgridparam)
{
DataTable dt = new DataTable();
List parameter = new List();
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
//多个出库单会有重复数据,需要去重
string sql = $@" SELECT distinct c.ID,c.LotNo,c.Quantity,a.SourceCode ProductionCode,b.InvCode,b.InvName,b.InvStd,c.MUSERName,c.MTIME
FROM ICSManufactureReceive a
INNER JOIN ICSInventory b ON a.InvCode=b.InvCode AND a.WorkPoint=b.WorkPoint
INNER JOIN ICSManufactureReceiveLot c ON a.SourceCode=c.ProductionCode AND a.WorkPoint=c.WorkPoint AND a.InvCode=c.InvCode and IsBind='0'
WHERE a.SourceCode='{ProductionCode}' AND a.WHCode='{WHCode}' and a.InvCode='{InvCode}' and a.WorkPoint='{WorkPoint}' ";
return Repository().FindTablePageBySql(sql.ToString(), parameter.ToArray(), ref jqgridparam);
}
#endregion
#region 获取条码信息
///
/// 获取条码信息
///
///
///
///
///
///
///
public DataTable GetLotGridJson(string LotNo)
{
DataTable dt = new DataTable();
List parameter = new List();
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
//多个出库单会有重复数据,需要去重
string sql = $@" SELECT a.LOTNO,a.Quantity,b.BatchCode,c.InvCode,c.InvName,c.InvUnit,c.InvStd,c.InvDesc
FROM ICSInventoryLot a
INNER JOIN ICSExtension b ON a.ExtensionID=b.ID
INNER JOIN ICSInventory c ON a.INVCODE=c.InvCode AND a.WorkPoint=b.WorkPoint
WHERE a.WorkPoint='{WorkPoint}' AND a.LOTNO='{LotNo}' ";
return SqlHelper.CmdExecuteDataTable(sql);
}
#endregion
#region 创建送检单
///
/// 创建送检单
///
/// 条码信息
///
public string CreateCheckNO(string Lots)
{
string msg = string.Empty;
try
{
var lots = Lots.Substring(1, Lots.Length-3);
string WorkPoints = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
string MUSER = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
string MUSERNAME = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
string sqlSeach = $@" select * from dbo.ICSInventoryLot where EATTRIBUTE30='1' and LotNo IN({lots})";
DataTable dtASN = SqlHelper.GetDataTableBySql(sqlSeach);
if (dtASN != null && dtASN.Rows.Count > 0)
{
throw new Exception("所选条码中存在已检索状态的条码,无法创建!");
}
var pre = "CKNO" + DateTime.Now.ToString("yyyy-MM-dd");
var checkNO = GetSerialCode(WorkPoints, "ICSInspectionSheet", "CheckCode", pre, 5);
string sql = $@" INSERT INTO ICSInspectionSheet([ID], [CheckCode],[InvCode], [LotNo], [Quantity], [Amount], [ExtensionID], [MUSER], [MUSERName], [WorkPoint], [MTIME]) SELECT NEWID(),'{checkNO}',InvCode,LotNO,Quantity,Amount,ExtensionID,'{MUSER}','{MUSERNAME}','{WorkPoints}',GETDATE()
FROM ICSInventoryLot WHERE LOTNO IN({lots}); ";
int count = SqlHelper.CmdExecuteNonQueryLi(sql);
return msg;
}
catch (Exception ex)
{
return ex.Message;
}
}
#endregion
public object GetDecimalDigits()
{
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
try
{
string sql = string.Empty;
sql = @"select Figure from ICSConfiguration where Code='Figure001' and Enable='1' and WorkPoint='" + WorkPoint + "'";
object Figure = SqlHelper.ExecuteScalar(sql);
return Figure;
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
///
/// 删除条码
///
///
///
public string DeleteItemLot(string CheckNos)
{
string msg = string.Empty;
try
{
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
//string sql = $@"SELECT * FROM dbo.ICSMOSubInventoryLot
//WHERE MOCode IN ({MOCodes}) and WorkPoint in ('{WorkPoint}') and isnull(EATTRIBUTE1,'') !='' ";
//DataTable dtASN = SqlHelper.GetDataTableBySql(sql);
//if (dtASN != null && dtASN.Rows.Count > 0)
//{
// msg = "所选条码已绑定,无法删除!";
// return msg;
//}
if (string.IsNullOrEmpty(msg))
{
string sqls = $"DELETE FROM ICSInspectionSheet WHERE CheckCode in({CheckNos}) AND WorkPoint in ('{WorkPoint}') ";
SqlHelper.CmdExecuteNonQueryLi(sqls);
}
}
catch (Exception ex)
{
return ex.Message;
}
return msg;
}
public string GetSerialCode(string workPointCode, string tbName, string colName, string Pre, int numLen)
{
string sql = "EXEC Addins_GetSerialCode '{0}','{1}','{2}','{3}',{4}";
sql = string.Format(sql, new object[] { workPointCode, tbName, colName, Pre, numLen });
//return Repository().FindTableBySql(sql.ToString());
return SqlHelper.ExecuteScalar(sql).ToString();
//return DbHelper.ExecuteScalar(CommandType.Text, sql).ToString();
}
public static string HttpPost(string url, string body)
{
try
{
Encoding encoding = Encoding.UTF8;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
request.ContentType = "application/json; charset=utf-8";
byte[] buffer = encoding.GetBytes(body);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
{
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
}
///
/// 检验子表信息
///
///
///
///
///
///
public DataTable GetSubGridJson(string CheckNo, ref Pagination jqgridparam)
{
DataTable dt = new DataTable();
object Figure = GetDecimalDigits();
List parameter = new List();
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
string sql = $@" SELECT a.ID,a.LotNo,a.InvCode,c.InvName,c.InvUnit,a.CheckCode CheckNo,a.Quantity
FROM ICSInspectionSheet a
INNER JOIN ICSInventory c ON a.InvCode=c.InvCode AND a.WorkPoint=c.WorkPoint
WHERE a.CheckCode='{CheckNo}' AND a.WorkPoint='{WorkPoint}'";
sql = string.Format(sql, Figure);
return Repository().FindTablePageBySql(sql.ToString(), parameter.ToArray(), ref jqgridparam);
}
///
/// 出库单条码绑定导入
///
///
///
public string UploadFileBinding(String savePath)
{
//数据获取
try
{
int index = 1;
string msg = "";
string MUSER = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
string MUSERNAME = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
string MTIME = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string sql = string.Empty;
SqlConnection conn = SqlHelper.GetDataCenterConn();
int count = 0;
DataTable data = FileToExcel.ExcelToTable(savePath);
var parent = data.DefaultView.ToTable(true, "入库单号", "入库单行号", "生产订单号", "物料编码", "条码", "数量", "库位编码");
parent.PrimaryKey = new DataColumn[] { parent.Columns["column1"], parent.Columns["column2"], parent.Columns["column3"], parent.Columns["column4"], parent.Columns["column5"], parent.Columns["column6"] };
DataTable distinctTable = parent.DefaultView.ToTable(true);
foreach (DataRow distinctds in distinctTable.Rows)
{
string ID = Guid.NewGuid().ToString();
index++;
string RCVCode = distinctds["入库单号"].ToString().Trim();
string RCVSequence = distinctds["入库单行号"].ToString().Trim();
string ProductionCode = distinctds["生产订单号"].ToString().Trim();
string InvCode = distinctds["物料编码"].ToString().Trim();
string LotNo = distinctds["条码"].ToString().Trim();
string Quantity = distinctds["数量"].ToString().Trim();
string LocationCode = distinctds["库位编码"].ToString().Trim();
#region 判断必填项
if (ProductionCode == "" || ProductionCode == null)
{
throw new Exception("第 " + index + " 行生产订单号不能为空!");
}
if (InvCode == "" || InvCode == null)
{
throw new Exception("第 " + index + " 行物料编码不能为空!");
}
if (LotNo == "" || LotNo == null)
{
throw new Exception("第 " + index + " 行条码不能为空!");
}
if (Quantity == "" || Quantity == null)
{
throw new Exception("第 " + index + " 行数量不能为空!");
}
if (LocationCode == "" || LocationCode == null)
{
throw new Exception("第 " + index + " 行库位编码不能为空!");
}
#endregion
sql += $@"
INSERT INTO [dbo].[ICSInventoryLot] ([ID], [LotNo], [InvCode], [ProductDate], [ExpirationDate], [Quantity], [Amount], [ExtensionID], [Type], [PrintTimes], [LastPrintUser], [LastPrintTime], [MUSER], [MUSERName], [MTIME], [WorkPoint]) SELECT NEWID(), N'{LotNo}', N'{InvCode}', '{MTIME}', case when EffectiveEnable='1' THEN DATEADD(day,EffectiveDays,GETDATE()) else '2099-12-31' END, {Quantity}, 0.000000, (SELECT ID FROM ICSExtension WHERE Colspan='~~~~~~~~~~~~~'), N'9', NULL, NULL, NULL, N'{MUSER}', N'{MUSERNAME}', '{MTIME}', N'KC47' FROM ICSInventory WHERE InvCode='{InvCode}' AND WorkPoint='{WorkPoint}' ;
INSERT INTO [dbo].[ICSInventoryLotDetail] ([LotNo], [TransID], [TransCode], [TransSequence], [MUSER], [MUSERName], [MTIME], [WorkPoint]) SELECT N'{LotNo}', ID, MOCode, Sequence,'{MUSER}', N'{MUSERNAME}', '{MTIME}', N'{WorkPoint}' FROM ICSMO WHERE MOCode='{ProductionCode}' AND Sequence='1' AND WorkPoint='{WorkPoint}' ;
INSERT INTO [dbo].[ICSManufactureReceiveLot] ([ID], [ProductionCode], [ProductionSequence], [RCVCode], [RCVSequence], [LotNo], [InvCode], [WarehouseCode], [LocationCode], [Quantity], [Memo], [IsBind], [MUSER], [MUSERName], [MTIME], [WorkPoint]) SELECT NEWID(), N'{ProductionCode}', N'1', N'', N'', N'{LotNo}', N'{InvCode}', a.WarehouseCode, N'{LocationCode}', '{Quantity}', NULL, '0', N'{MUSER}', N'{MUSERNAME}', '{MTIME}', N'{WorkPoint}' FROM ICSWarehouse a
INNER JOIN ICSLocation b ON a.Id=b.WHID AND a.workpoint=b.WorkPoint
where b.LocationCode='{LocationCode}' and a.Workpoint='{WorkPoint}'; ";
if (RCVCode != "" && RCVCode != null && RCVSequence != "" && RCVSequence != null)
{
sql += $@" IF NOT EXISTS(SELECT a.ID FROM ICSManufactureReceive a
INNER JOIN ICSManufactureReceiveLot b ON a.SourceCode = b.ProductionCode AND a.WorkPoint = b.WorkPoint AND a.InvCode = b.InvCode
WHERE a.RCVCode = '{RCVCode}' AND a.InvCode = '{InvCode}' AND b.LOTNO = '{LotNo}' and a.Sequence = '{RCVSequence}' and a.WorkPoint = '{WorkPoint}')
BEGIN
RAISERROR('绑定的条码:{LotNo}和入库单:{RCVCode}的生产订单不一致,绑定失败', 16, 1);
RETURN
END;
UPDATE ICSManufactureReceiveLot SET IsBind = '1', RCVCode = '{RCVCode}', RCVSequence = '1' WHERE LotNo = '{LotNo}' and WorkPoint = '{WorkPoint}';
IF EXISTS(SELECT a.Quantity FROM ICSManufactureReceive a
INNER JOIN ICSManufactureReceiveLot b ON a.SourceCode = b.ProductionCode AND a.WorkPoint = b.WorkPoint AND a.InvCode = b.InvCode
WHERE a.RCVCode = '{RCVCode}' and a.Sequence = '{RCVSequence}' AND a.InvCode = '{InvCode}' AND b.IsBind = '1'
GROUP BY a.Quantity
HAVING sum(b.Quantity) > a.Quantity)
BEGIN
RAISERROR('绑定条码数量超过入库单:{RCVCode}的行数量', 16, 1);
RETURN
END; ";
}
}
count = SqlHelper.CmdExecuteNonQueryLi(sql);
if (count > 0)
{
msg = "导入成功";
}
else
{
return "无有效的导入数据。";
}
return msg;
}
catch (Exception ex)
{
return ex.Message;
}
}
public DataTable GetINV(string invcode, string Code, string Invstd, string EATTRIBUTE2, string TimeFrom, string TimeArrive,string isSeachStatus, ref Pagination jqgridparam)
{
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
List parameter = new List();
DataTable table = new DataTable();
string wherestr = "";
if (!string.IsNullOrEmpty(invcode) || !string.IsNullOrEmpty(Code) || !string.IsNullOrEmpty(Invstd) || !string.IsNullOrEmpty(isSeachStatus))
{
if (!string.IsNullOrEmpty(invcode))
{
wherestr += " and a.InvCode like '%" + invcode + "%'";
}
if (!string.IsNullOrEmpty(Code))
{
wherestr += " and c.TransCode like '%" + Code + "%'";
}
if (!string.IsNullOrEmpty(Invstd))
{
wherestr += " and b.InvStd like '%" + Invstd + "%'";
}
if (!string.IsNullOrEmpty(isSeachStatus))
{
if (isSeachStatus=="1")
{
wherestr += " and a.EATTRIBUTE30 = '1'";
}
else if (isSeachStatus == "2")
{
wherestr += " and (a.EATTRIBUTE30 = '0' or isnull(a.EATTRIBUTE30,'')='')";
}
else
{
}
}
}
else
{
wherestr += " and a.MTIME >= '" + TimeFrom + "'";
wherestr += " and a.MTIME <= '" + TimeArrive + "'";
}
string sql = @"
select a.ID,a.LotNo as LotNO,a.Quantity,a.InvCode,b.InvName,b.InvStd,b.InvUnit,d.BatchCode
,case when a.EATTRIBUTE30='1' then '是' else '否' end isSeachStatus,c.EATTRIBUTE30,c.TransCode
from dbo.ICSInventoryLot a
left join dbo.ICSInventory b on a.InvCode=b.InvCode and a.WorkPoint=b.WorkPoint
left join dbo.ICSInventoryLotDetail c on a.LotNo=c.LotNo and a.WorkPoint=b.WorkPoint
left join dbo.ICSExtension d on a.ExtensionID=d.ID and a.WorkPoint=d.WorkPoint
left join dbo.ICSInspectionSheet e on a.LotNo=e.LotNo and a.WorkPoint=e.WorkPoint
where a.Type='3' and e.LotNo is null and b.InvFQC='1' and a.WorkPoint = '" + WorkPoint + "'" + wherestr;
return Repository().FindTablePageBySql(sql.ToString(), parameter.ToArray(), ref jqgridparam);
}
public string UpdateLotSeachStatus(string keyValue,string Type)
{
//站点信息
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
string msg = "";
keyValue = keyValue.Substring(1, keyValue.Length - 2);
string sql = string.Empty;
sql = string.Format(@" update dbo.ICSInventoryLot set EATTRIBUTE30='{2}' WHERE LotNo IN ({0}) and WorkPoint ='{1}'", keyValue.TrimEnd(','), WorkPoint, Type);
try
{
if (SqlHelper.CmdExecuteNonQueryLi(sql) > 0)
{
}
}
catch (Exception ex)
{
msg = ex.Message;
}
return msg;
}
///
/// 送检单导出
///
///
///
///
///
public DataTable StatementExportAll(string CheckNo)
{
string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location.TrimEnd(',');
string sql = string.Empty;
object Figure = GetDecimalDigits();
string TableCode = string.Empty;
#region sql语句
sql = @"SELECT DISTINCT a.CheckCode '送检单号',a.LotNo '条码',a.InvCode '料品代码',c.InvName '料品名称',c.InvUnit '规格型号',a.Quantity '条码数量',a.Amount '辅计量数量',c.InvUnit '单位',b.FinalResult '检验结果',b.FinalUser '检验人',b.FinalTime '检验时间',a.MTIME '创建时间',a.MUSERName '创建人'
from ICSInspectionSheet a
LEFT JOIN IcsMatCheckResult b ON b.EATTRIBUTE4='1' AND a.CheckCode=b.CheckNo
INNER JOIN ICSInventory c ON a.InvCode=c.InvCode AND a.WorkPoint=c.WorkPoint and a.CheckCode in (" + CheckNo.TrimEnd(',') + ")";
#endregion
sql = sql + " and a.WorkPoint='{1}'";
sql = string.Format(sql, Figure, WorkPoint);
DataTable dt = SqlHelper.GetDataTableBySql(sql);
return dt;
}
}
}