private void DeleteExpiredReplenish(Company company) { int expHours; try { expHours = int.Parse(GetCompanyOption(company, "RPOEXP")); } catch { expHours = WmsSetupValues.ReplenishmentExpHours; } IList <Document> list = Factory.DaoDocument().Select(new Document { DocType = new DocumentType { DocTypeID = SDocType.ReplenishPackTask }, DocStatus = new Status { StatusID = DocStatus.New } }).Where(f => f.CreationDate < DateTime.Now.AddHours(-1 * expHours)).ToList(); Status status = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); foreach (Document doc in list) { doc.DocStatus = status; Factory.DaoDocument().Update(doc); } }
public void ResetCountedBinTask(BinByTask binTask) { //Saca el listado delso completado, para cancelarlos. IList <BinByTaskExecution> list = Factory.DaoBinByTaskExecution() .Select(new BinByTaskExecution { BinTask = binTask }) .Where(f => f.Status.StatusID == DocStatus.Completed || f.Status.StatusID == DocStatus.New) .ToList(); //, Status = new Status { StatusID = DocStatus.Completed } if (list == null || list.Count == 0) { return; } Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); foreach (BinByTaskExecution bte in list) { bte.Status = cancelled; bte.ModDate = DateTime.Now; bte.ModifiedBy = binTask.ModifiedBy; Factory.DaoBinByTaskExecution().Update(bte); } }
public Label EmptyUniqueTrackLabel(Product product, string labelCode, string user) { //Chequear que no exista un labelcode igual para el mismo producto. En estado Activo. try { Label lbl = Factory.DaoLabel().Select(new Label { LabelCode = labelCode.Trim(), Product = product, Node = new Node { NodeID = NodeType.Stored }, Status = new Status { StatusID = EntityStatus.Active } }).First(); lbl.CurrQty = 0; lbl.LabelCode = "VOID_" + DateTime.Now.ToString("YMdHms") + lbl.LabelCode; lbl.ModDate = DateTime.Now; lbl.Node = WType.GetNode(new Node { NodeID = NodeType.Voided }); lbl.Status = WType.GetStatus(new Status { StatusID = EntityStatus.Inactive }); Factory.DaoLabel().Update(lbl); return(lbl); } catch { throw new Exception("Track # [" + labelCode + "] does not exists or is inactive."); } }
public void UnPickUniqueLabel(Document document, Label label, SysUser picker) { Node storedNode = WType.GetNode(new Node { NodeID = NodeType.Stored }); Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); IList <NodeTrace> nodeList = Factory.DaoNodeTrace().Select( new NodeTrace { Document = document, Label = label, Node = label.Node }); if (nodeList == null || nodeList.Count == 0) { return; } ReverseNodeTrace(nodeList, picker.UserName, storedNode, label.LastBin, status); }
//Permite reversar un documento PR que fue posteado en el ERP, //solo se reversa si en el ERP no lo ha posteado public void ReversePurchaseReceipt(Document data) { Factory.IsTransactional = true; //if (data.Company.ErpConnection == null) // throw new Exception("Please setup Erp Connection."); //SetConnectMngr(data.Company); Node recNode = new Node { NodeID = NodeType.Received }; Node storedNode = new Node { NodeID = NodeType.Stored }; try { //Update document status to Cancelled Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); Status inactive = WType.GetStatus(new Status { StatusID = EntityStatus.Inactive }); //Cross Dock 7 - Marzo - 09 ReverseCrossDockProcess(data); data.DocStatus = cancelled; Factory.DaoDocument().Update(data); //Pasa las lineas del documento a Cancelled IList <DocumentLine> docLines = Factory.DaoDocumentLine().Select(new DocumentLine { Document = data }); foreach (DocumentLine dl in docLines) { dl.LineStatus = cancelled; Factory.DaoDocumentLine().Update(dl); } //update NodeTrace NodeTrace qNodeTrace = new NodeTrace { PostingDocument = data }; //Busca todo los registros de ese documento y los reversa IList <NodeTrace> nodeTraceList = Factory.DaoNodeTrace().Select(qNodeTrace); Node voidNode = WType.GetNode(new Node { NodeID = NodeType.Voided }); Label curLabel; foreach (NodeTrace trace in nodeTraceList) { //Crear un trace que tenga la transaccion del posting eliminado en el nodo void //Registra el movimiento del nodo if (trace.Node.NodeID == NodeType.Stored) { trace.Node = voidNode; trace.Status = inactive; trace.ModDate = DateTime.Now; trace.ModifiedBy = data.ModifiedBy; trace.Comment = "Stored: " + trace.PostingDocument.DocNumber + " Reversed"; Factory.DaoNodeTrace().Update(trace); /* * SaveNodeTrace( * new NodeTrace * { * Node = voidNode, * Document = trace.Document, * Label = trace.Label, * Quantity = trace.Quantity, * IsDebit = trace.IsDebit, * CreatedBy = trace.CreatedBy, * PostingDocument = trace.PostingDocument, * PostingUserName = trace.PostingUserName, * Status = inactive, * Comment = "Receipt " + trace.PostingDocument.DocNumber + " Reversed", * ModDate = DateTime.Now, * ModifiedBy = data.ModifiedBy, * PostingDate = trace.PostingDate, * }); */ } //Reversa el trace original para poderlo postear nuevamente if (trace.Node.NodeID == NodeType.Received) { trace.DocumentLine = null; trace.PostingDate = null; trace.PostingDocument = null; trace.PostingUserName = null; trace.ModifiedBy = data.ModifiedBy; trace.ModDate = DateTime.Now; Factory.DaoNodeTrace().Update(trace); //Reverse labels to node trace received curLabel = trace.Label; curLabel.Node = recNode; try { curLabel.Notes += "Receipt " + trace.PostingDocument.DocNumber + " Reversed"; } catch { } curLabel.ModDate = DateTime.Now; curLabel.ModifiedBy = data.ModifiedBy; Factory.DaoLabel().Update(curLabel); } } Factory.Commit(); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("ReversePurchaseReceipt #" + data.DocNumber, ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Persistence); throw; //return; } }
public Label ReceiveLabelForTransfer(Document document, Label label, Bin destLocation, Node recNode) { try { Factory.IsTransactional = true; Status active = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); //Trae de nuevo le label para cargar los childs en caso de que sea logistica label = Factory.DaoLabel().SelectById(new Label { LabelID = label.LabelID }); ////////////////////////////////////////////////////// //Check if label is in the pending List Document shipment; try { shipment = Factory.DaoDocument().Select(new Document { DocNumber = document.CustPONumber, Company = document.Company }).First(); } catch { throw new Exception("Shipment transfer " + document.CustPONumber + " does not exists."); } //List of Pending Labels IList <Label> balanceList = Factory.DaoLabel().GetDocumentLabelAvailableFromTransfer(document, shipment, label); if (!balanceList.Any(f => f.LabelID == label.LabelID)) { throw new Exception("Label [" + label.LabelCode + "] is not in the list of labels to be received."); } ////////////////////////////////////////////////// //Valida si el docuemnto no es nulo Rules.ValidateDocument(document, true); Rules.ValidateBinStatus(destLocation, true); //Valida si el label es un label de producto, Rules.ValidateIsProductLabel(label, true); //Validar Product Restriction Rules.ValidateRestrictedProductInBin(label.Product, destLocation, true); //Valida si el producto esta en ese documento //Se debe ejecutar proceso para saber si la company permite //recibir producto no existente en el docuemnto DocumentLine docLine = new DocumentLine { Document = document, Product = label.Product, LineStatus = new Status { StatusID = DocStatus.New }, Unit = label.Unit }; Rules.ValidateProductInDocument(docLine, true); //Valida si hay saldo pendiente por recibir docLine.Quantity = Factory.DaoLabel().SelectCurrentQty(label, null, true); Rules.ValidateBalanceQuantityInDocument(docLine, recNode, true, false); //Actualiza Label with new data label.Node = recNode; label.Bin = destLocation; label.ModifiedBy = document.ModifiedBy; label.ModDate = DateTime.Now; label.ReceivingDate = DateTime.Now; label.ReceivingDocument = document; label.Status = active; //Si el label estaba contenido en una logistica, al recibilo solo quiere decir que lo extrae de la logistica label.FatherLabel = null; Factory.DaoLabel().Update(label); //Registra el movimiento del label en el nodo SaveNodeTrace(new NodeTrace { Node = recNode, Document = document, Label = label, Quantity = label.CurrQty, IsDebit = false, CreatedBy = document.ModifiedBy, Comment = "Transfer " + document.DocNumber }); //Actualiza Los Hijos (si existen) try { label.ChildLabels = Factory.DaoLabel().Select(new Label { FatherLabel = label }); if (label.ChildLabels != null && label.ChildLabels.Count > 0) { foreach (Label curLabel in label.ChildLabels) { curLabel.Node = recNode; curLabel.Bin = label.Bin; curLabel.ModifiedBy = document.ModifiedBy; curLabel.ModDate = DateTime.Now; Factory.DaoLabel().Update(curLabel); SaveNodeTrace(new NodeTrace { Node = recNode, Document = document, Label = curLabel, Quantity = curLabel.CurrQty, IsDebit = false, CreatedBy = document.ModifiedBy, Comment = "Transfer " + document.DocNumber }); } } } catch { } Factory.Commit(); return(label); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("ReceiveLabelForTransfer:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); throw new Exception(WriteLog.GetTechMessage(ex)); } }
private IList <DocumentLine> GetLocationTransferDocumentLines(Document doc, Company company, String docID) { DocumentLine tmpData; IList <DocumentLine> list = new List <DocumentLine>(); Status lineStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); int curLine = 0; string curMaster = ""; Query = GetErpQuery("TRANSFER_LINE").Replace("__DOCUMENT", docID); DataSet ds = ReturnDataSet(Query, null, "TRANSFER_LINE", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } try { foreach (DataRow dr in ds.Tables[0].Rows) { tmpData = new DocumentLine(); tmpData.Date1 = doc.Date1; curMaster = ""; tmpData.LineNumber = (int)double.Parse(dr["f470_rowid"].ToString()); tmpData.Sequence = tmpData.LineNumber; curLine = tmpData.LineNumber; tmpData.Document = doc; tmpData.IsDebit = false; tmpData.Quantity = double.Parse(dr["f470_cantidad"].ToString(), new NumberFormatInfo { NumberDecimalSeparator = Separator }); tmpData.CreatedBy = WmsSetupValues.SystemUser; tmpData.CreationDate = DateTime.Now; tmpData.Note = dr["f470_notas"].ToString(); tmpData.BinAffected = dr["ubicacion"].ToString(); tmpData.PostingUserName = dr["f470_id_un_movto"].ToString(); tmpData.LineStatus = lineStatus; //Location de donde proviene la mercancia curMaster = "Location:" + dr["bodega_entrada"].ToString(); tmpData.Location = WType.GetLocation(new Location { Company = company, ErpCode = dr["bodega_entrada"].ToString() }); //Lcation a donde va la mercancia curMaster = "Location To:" + dr["bodega_salida"].ToString(); tmpData.Location2 = WType.GetLocation(new Location { Company = company, ErpCode = dr["bodega_salida"].ToString() }); try { curMaster = "Product:" + dr["itemext"].ToString(); tmpData.Product = WType.GetProduct(new Product { Company = company, ProductCode = dr["f121_rowid_item"].ToString() }); tmpData.LineDescription = tmpData.Product.Name; //dr["ITEMDESC"].ToString(); tmpData.AccountItem = dr["itemext"].ToString(); //ITEM EXT curMaster = "Uom:" + dr["f470_id_unidad_medida"].ToString(); tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["f470_id_unidad_medida"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup }); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetLocationTransferDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); continue; // //Pone el Default Product // tmpData.Product = WType.GetProduct(new Product { Company = company, ProductCode = WmsSetupValues.DEFAULT }); // tmpData.LineDescription = "Unknown: " + dr["ITEMNMBR"].ToString(); // curMaster = "Uom:" + dr["UOFM"].ToString(); // tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() }); } list.Add(tmpData); } return((list.Count > 0) ? list : null); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetTransferDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); //throw; return(null); } }
private IList <Document> GetKitAssemblyDocuments(String sWhere) { //retorna la lista de Documentos de Assembly Document tmpData = null; try { Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString); Query = GetErpQuery("KITDOC"); //Console.WriteLine(Query); DataSet ds = ReturnDataSet(Query, null, "KITDOC", Command.Connection); //Console.WriteLine(ds.Tables.Count); if (ds == null || ds.Tables.Count == 0) { return(null); } if (ds == null || ds.Tables.Count == 0) { return(null); } List <Document> list = new List <Document>(); Status status = WType.GetStatus(new Status { StatusID = DocStatus.New }); Account defAccount = WType.GetAccount(new Account { AccountCode = WmsSetupValues.DEFAULT }); SysUser user = WType.GetUser(new SysUser { UserName = WmsSetupValues.AdminUser }); Company company = CurCompany; DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass { DocClassID = SDocClass.Inventory }); DocumentType docType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.KitAssemblyTask }); foreach (DataRow dr in ds.Tables[0].Rows) { try { //Map Properties tmpData = new Document(); tmpData.Date1 = DateTime.Parse(dr["f350_fecha"].ToString()); //Tran date //tmpData.Date2 = DateTime.Parse(dr["BM_Start_Date"].ToString()); //BM_Start_Date //tmpData.Date3 = DateTime.Parse(dr["PSTGDATE"].ToString()); //PSTGDATE tmpData.DocNumber = dr["docnumber"].ToString(); tmpData.CreatedBy = dr["f350_usuario_creacion"].ToString(); try { tmpData.Location = WType.GetLocation(new Location { Company = CurCompany, ErpCode = dr["cod_bodega"].ToString() }); } catch { } tmpData.DocStatus = status; tmpData.DocConcept = docConcept; tmpData.Vendor = defAccount; tmpData.Customer = defAccount; tmpData.IsFromErp = true; tmpData.CrossDocking = false; tmpData.ErpMaster = int.Parse(dr["f350_rowid"].ToString()); tmpData.Company = CurCompany; tmpData.Reference = dr["f350_referencia"].ToString(); tmpData.DocType = docType; tmpData.PickMethod = docType.PickMethod; //Asignacion de Lines - Seguen el tipo de orden tmpData.DocumentLines = GetKitAssemblyDocumentLines(tmpData); if (tmpData.DocumentLines != null && tmpData.DocumentLines.Count > 0) { list.Add(tmpData); } } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); } } return(list); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocuments:", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); return(null); } }
public IList <Document> GetShippingDocuments(string sWhere, int docType, bool useRemain) { IList <Document> list = new List <Document>(); DocumentClass docClass = new DocumentClass(); Document tmpData = null; string pos = "0"; try { sWhere = ""; Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString); Query = GetErpQuery("SALESORDER"); //Console.WriteLine(Query); DataSet ds = ReturnDataSet(Query, null, "SALESORDER", Command.Connection); pos = "1"; if (ds.Tables.Count == 0) { return(null); } DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass { DocClassID = SDocClass.Shipping }); //Definiendo los tipos de documento de shipping DocumentType soType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.SalesOrder }); DocumentType siType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.SalesInvoice }); DocumentType bkType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.BackOrder }); DocumentType returnType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.Return }); //Status docStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); Account defAccount = WType.GetAccount(new Account { AccountCode = WmsSetupValues.DEFAULT }); SysUser user = WType.GetUser(new SysUser { UserName = WmsSetupValues.AdminUser }); Company company = CurCompany; // WType.GetDefaultCompany(); Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); //En el dataset, Tables: 1 - DocumentHeader, 2 - DocumentLine, 3 - DocumentComments foreach (DataRow dr in ds.Tables[0].Rows) { try { //Map Properties tmpData = new Document(); tmpData.Date1 = DateTime.Parse(dr["f430_id_fecha"].ToString()); tmpData.Date2 = DateTime.Parse(dr["f430_fecha_entrega"].ToString()); tmpData.Date3 = DateTime.Parse(dr["f430_fecha_ts_cumplido"].ToString()); tmpData.DocNumber = dr["documento"].ToString(); tmpData.ErpMaster = int.Parse(dr["f430_rowid"].ToString()); tmpData.DocStatus = GetShippingStatus(0); tmpData.Comment = dr["f430_notas"].ToString(); tmpData.SalesPersonName = dr["f200_razon_social"].ToString(); //LAs ordenes con status void en GP, salen como canceladas. try { if (int.Parse(dr["f430_ind_estado"].ToString()) == 9) //9 Anulado. { tmpData.DocStatus = cancelled; } } catch { } tmpData.CreatedBy = dr["f430_usuario_creacion"].ToString(); tmpData.CustPONumber = dr["f430_num_docto_referencia"].ToString(); tmpData.DocConcept = docConcept; tmpData.Vendor = defAccount; tmpData.Customer = WType.GetAccount( new Account { AccountCode = dr["id_cliente"].ToString(), BaseType = new AccountType { AccountTypeID = AccntType.Customer }, Company = company }); try { if (!string.IsNullOrEmpty(dr["id_ruta"].ToString())) { tmpData.ShippingMethod = WType.GetShippingMethod( new ShippingMethod { ErpCode = dr["id_ruta"].ToString(), Company = company }); } } catch { } //tmpData.User = user; tmpData.IsFromErp = true; tmpData.CrossDocking = false; tmpData.Company = CurCompany; tmpData.Reference = dr["f430_referencia"].ToString(); //tmpData.Notes = dr["BACHNUMB"].ToString(); //Asignacion de Address tmpData.DocumentAddresses = GetShippingDocumentAddress(tmpData, null, dr); DocumentAddress billAddress = null; if (!string.IsNullOrEmpty(dr["f430_id_sucursal_fact"].ToString())) { billAddress = GetBillAddress(tmpData, dr["f430_id_sucursal_fact"].ToString(), dr["id_cliente"].ToString(), AccntType.Customer); } if (billAddress != null) { tmpData.DocumentAddresses.Add(billAddress); } tmpData.DocType = soType; tmpData.PickMethod = soType.PickMethod; //Asignacion de Lines - Seguen el tipo de orden tmpData.DocumentLines = GetShippingDocumentLines(tmpData, company, dr["f430_rowid"].ToString(), useRemain); if (tmpData.DocumentLines != null && tmpData.DocumentLines.Count > 0) { if (tmpData.Location == null) { tmpData.Location = tmpData.DocumentLines[0].Location; } list.Add(tmpData); } } catch (Exception ex) { ExceptionMngr.WriteEvent("GetShippingDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); } } //retornar la lista return(list); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetShippingDocuments:" + pos + ":", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); //throw; return(null); } }
/// <summary> /// Get Print file string to print /// </summary> /// <param name="labels">List of labels to print</param> /// <param name="template">Template to use for the printing</param> /// <returns></returns> public String ProcessPrintingLine(DocumentBalance printLine, LabelTemplate template, String printLot, Node node, Bin bin, UserByRol userByRol) { string result = ""; Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); //Active //Obteniendo el listado de TAGS que se deben reemplazar en el template IList <LabelMapping> labelmappings = Factory.DaoLabelMapping().Select( new LabelMapping { LabelType = template.LabelType }); //Template base //int i; IList <Label> labelList = new List <Label>(); //Tipo De impresion //1. Normal Imprime standar, sin logistica //2. Logistic (Notes tiene data) - imprime normal mas la Logistica Unit logisticUnit = null; if (printLine.Notes != null && printLine.Notes.Contains("Logistic")) { string[] dataLogistic = printLine.Notes.Split(':'); //El primer elemento contiene la unidad logistica. logisticUnit = Factory.DaoUnit().SelectById(new Unit { UnitID = int.Parse(dataLogistic[1]) }); //3. Only print Logistic (notes tiene "ONLYPACK") - no imprime la normal (si las crea), solo imprime las logisticas //if (printLine.Notes.Contains("ONLYPACK")) //printOnlyLogistic = true; } //CReating Document Line to Send DocumentLine prnLine = new DocumentLine { Product = printLine.Product, Document = printLine.Document, Unit = printLine.Unit, Quantity = printLine.Quantity }; //Crea las etiquetas de la cantidad de producto a recibir Logisticas y sus Hijas double logisticFactor = (logisticUnit != null) ? (double)(logisticUnit.BaseAmount / printLine.Unit.BaseAmount) : 1; labelList = CreateProductLabels(logisticUnit, prnLine, node, bin, logisticFactor, printLot, "", DateTime.Now) .Where(f => f.FatherLabel == null).ToList(); //Reemplazando el Header if (template.Header != null) { result += ReplaceTemplate(labelmappings, template.Header, labelList[0]) + Environment.NewLine; } //Reemplazando el Body if (template.Body != null) { foreach (Label label in labelList) { result += ReplaceTemplate(labelmappings, template.Body, label) + Environment.NewLine; } } return(result); }
/// <summary> /// Piquea un producto a una orden teneindo en cuanta las tracking options. /// </summary> /// <param name="label"></param> /// <param name="qtyToPick"></param> /// <param name="node"></param> /// <param name="picker"></param> public Label PickProductWithTrack(Document document, Label label, double qtyToPick, Node destNode, SysUser picker, Label packLabel) { //Debe piquear de producto suelto, teniendo en cuanta el Track del Label. Factory.IsTransactional = true; Node storedNode = WType.GetNode(new Node { NodeID = NodeType.Stored }); Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); Status locked = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); //DocumentType labelType = WType.GetLabelType(new DocumentType { DocTypeID = LabelType.ProductLabel }); Bin destBin = Rules.GetBinForNode(destNode, document.Location); try { //Valida si el docuemnto no es nulo Rules.ValidateDocument(document, true); Rules.ValidateBinStatus(label.Bin, true); //Valida si el producto esta en ese documento DocumentLine docLine = new DocumentLine { Document = document, Product = label.Product, LineStatus = new Status { StatusID = DocStatus.New }, Unit = label.Unit, Quantity = qtyToPick, CreatedBy = picker.UserName }; if (document.DocType.DocTypeID != SDocType.PickTicket) { Rules.ValidateProductInDocument(docLine, true); //Valida si hay saldo pendiente por procesar Rules.ValidateBalanceQuantityInDocument(docLine, destNode, true, false); } //Evaluacion de tipo de source, Bin or Label DateTime recDate = DateTime.Now; //if (Rules.ValidateIsBinLabel(sourceLocation, false)) //{ IList <Label> tranLabel = DecreaseQtyFromBin(label, docLine, "Picking Source Track", true, storedNode); try { recDate = (DateTime)tranLabel.Where(f => f.ReceivingDate != null).OrderBy(f => f.ReceivingDate).First().ReceivingDate; } catch { recDate = DateTime.Now; } //} // //SI el ajustes es sobre un Label //else if (Rules.ValidateIsProductLabel(sourceLocation, false)) //{ // DecreaseQtyFromLabel(sourceLocation, line, "Picking Source", true, storedNode); // try { recDate = (sourceLocation.ReceivingDate == null) ? DateTime.Now : (DateTime)sourceLocation.ReceivingDate; } // catch { recDate = DateTime.Now; } //} //Creando el package para ingresar la mercancia. if (packLabel == null) { packLabel = new Label { LabelID = -1 } } ; document.Location = label.Bin.Location; //Revalidando que el location sea correcto try { packLabel = GetPackageLabel(packLabel, document, picker).PackLabel; } catch (Exception ex) { Factory.Rollback(); throw new Exception("Package label could not be created.\n" + ex.Message); } //Increasing the Record of Product on Dest Bin. //Oct 09 /2009 Se adiciona el track option. Label pickedLabel = IncreaseQtyIntoBin(docLine, destNode, destBin, "Picking Dest Track", true, recDate, label.TrackOptions, label); pickedLabel.FatherLabel = packLabel; pickedLabel.Status = locked; pickedLabel.ShippingDocument = document; Factory.DaoLabel().Update(pickedLabel); Factory.Commit(); return(pickedLabel); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("PickProductWithTrack:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); throw new Exception(WriteLog.GetTechMessage(ex)); } }
public void PickCrossDockProduct(Document purchase, IList <DocumentBalance> crossDockBalance, SysUser picker) { Factory.IsTransactional = true; Node storedNode = WType.GetNode(new Node { NodeID = NodeType.Stored }); Node node = WType.GetNode(new Node { NodeID = NodeType.Picked }); Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); DocumentType labelType = WType.GetLabelType(new DocumentType { DocTypeID = LabelType.ProductLabel }); Bin pickingBin = WType.GetBin(new Bin { Location = purchase.Location, BinCode = DefaultBin.PICKING }); Dictionary <Document, Label> packageLabel = new Dictionary <Document, Label>(); Status locked = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); try { //Solo toma las lineas de sales y deja quietas las del docuemnto de purchasing foreach (DocumentBalance line in crossDockBalance.Where(f => f.Document.DocType.DocClass.DocClassID == SDocClass.Shipping)) { //Valida si el documento no es nulo Rules.ValidateDocument(line.Document, true); if (line.Document.DocType.DocTypeID != SDocType.PickTicket) { //Valida si el producto esta en ese documento DocumentLine docLine = new DocumentLine { Document = line.Document, Product = line.Product, LineStatus = new Status { StatusID = DocStatus.New }, Unit = line.Unit, Quantity = line.QtyProcessed //Quatity processed que es la que hace el cruce con el CrossDock }; Rules.ValidateProductInDocument(docLine, true); //Valida si hay saldo pendiente por procesar try { Rules.ValidateBalanceQuantityInDocument(docLine, node, true, true); } catch { continue; } } //Toma el producto del nodetrace //Obtiene los labels que va a mover NodeTrace sourceTrace = new NodeTrace { Document = purchase, //Dec 7/09 no se puede forzar a que sea la misma unidad del balance //Unit = line.Unit, Label = new Label { Product = line.Product, Node = storedNode, Status = status }, Status = status, Node = storedNode }; //Obtiene las transacciones del node trace para ese documento especifico de Purchase. IList <Label> labelList = Factory.DaoNodeTrace().Select(sourceTrace).Select(f => f.Label) //.Take(int.Parse(line.QtyProcessed.ToString())) .ToList(); if (labelList.Sum(f => f.CurrQty * f.Unit.BaseAmount) < line.QtyProcessed * line.Unit.BaseAmount) { Factory.Rollback(); throw new Exception("No quantity available in the purchase document " + purchase.DocNumber + " for product " + line.Product.FullDesc + ".\nQty Available: " + labelList.Sum(f => f.CurrQty * f.Unit.BaseAmount).ToString() + " Qty Requested: " + (line.QtyProcessed * line.Unit.BaseAmount).ToString() + " in Doc# " + line.Document.DocNumber); } //Package Label para el Despacho if (!packageLabel.ContainsKey(line.Document)) { packageLabel.Add(line.Document, GetPackageLabel(new Label { LabelID = -1 }, line.Document, picker).PackLabel); } //Debe piquear la cantidad necesaria para suplir el SO con los labels //recibidos. double crQtyBal = line.QtyProcessed * line.Unit.BaseAmount; //LLevada a la unidad basica foreach (Label curLabel in labelList) { if (crQtyBal <= 0) { break; } //Si el Qty del label menor que lo pendiente mando todo el label if (curLabel.CurrQty * curLabel.Unit.BaseAmount <= crQtyBal) { //Si el destino es logitico lo hace su padre, si no es producto suelto en BIN curLabel.ModifiedBy = purchase.ModifiedBy; curLabel.Node = node; curLabel.LastBin = curLabel.Bin; curLabel.Bin = pickingBin; curLabel.ModDate = DateTime.Now; curLabel.FatherLabel = null; curLabel.FatherLabel = packageLabel[line.Document]; curLabel.Status = locked; SaveNodeTrace(new NodeTrace { Node = node, Label = curLabel, Quantity = curLabel.CurrQty, Bin = pickingBin, IsDebit = false, CreatedBy = purchase.ModifiedBy, Document = line.Document, // 07 Marzo 2009 // En el comenttario se pone el # del PO de cross dock, // este dato sirve en caso de reversion del crossdock process Comment = purchase.DocNumber }); curLabel.ShippingDocument = line.Document; Factory.DaoLabel().Update(curLabel); crQtyBal -= curLabel.CurrQty * curLabel.Unit.BaseAmount; } //Si no: disminuyo el Qty del label y hago un Increase else { //Si el destino es logitico lo hace su padre, si no es producto suelto en BIN curLabel.ModifiedBy = purchase.ModifiedBy; curLabel.ModDate = DateTime.Now; curLabel.CurrQty -= crQtyBal; Factory.DaoLabel().Update(curLabel); //Increase The Pick Node Node pickNode = WType.GetNode(new Node { NodeID = NodeType.Picked }); DocumentLine crdLine = new DocumentLine { Document = line.Document, Product = line.Product, Quantity = crQtyBal, CreatedBy = purchase.ModifiedBy }; Label pickedLabel = IncreaseQtyIntoBin(crdLine, pickNode, Rules.GetBinForNode(pickNode, purchase.Location), "Picking Dest", true, DateTime.Now, null, curLabel); pickedLabel.FatherLabel = packageLabel[line.Document]; pickedLabel.Status = locked; pickedLabel.ShippingDocument = line.Document; Factory.DaoLabel().Update(pickedLabel); //Factory.Commit(); } } /* * //Acutualiza la ubicacion Nuevo Bin * foreach (Label curLabel in labelList) * { * //Si el destino es logitico lo hace su padre, si no es producto suelto en BIN * curLabel.ModifiedBy = purchase.ModifiedBy; * curLabel.Node = node; * curLabel.LastBin = curLabel.Bin; * curLabel.Bin = pickingBin; * * SaveNodeTrace(new NodeTrace * { * Node = node, * Label = curLabel, * Quantity = curLabel.CurrQty, * Bin = pickingBin, * IsDebit = false, * CreatedBy = purchase.ModifiedBy, * Document = line.Document, * // 07 Marzo 2009 * // En el comenttario se pone el # del PO de cross dock, * // este dato sirve en caso de reversion del crossdock process * Comment = purchase.DocNumber * }); * * curLabel.FatherLabel = null; * Factory.DaoLabel().Update(curLabel); * } */ } Factory.Commit(); //Actualiza el estado de los documentos de shiiping a CrossDock foreach (Document doc in crossDockBalance.Where(f => f.Document.DocType.DocClass.DocClassID == SDocClass.Shipping).Select(f => f.Document).Distinct()) { doc.CrossDocking = true; Factory.DaoDocument().Update(doc); } Factory.Commit(); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("PickCrossDockProduct:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); throw new Exception(WriteLog.GetTechMessage(ex)); } }
/// <summary> /// Recibe producto, con etiqueta (recibo capturado por scanner generalmente) /// </summary> /// <param name="document">Task Document in Process</param> /// <param name="label">Label de transaccion </param> public Label PickLabel(Document document, Label label, Node node, Label packageLabel, SysUser picker, Bin destBin) { Factory.IsTransactional = true; //Node node = WType.GetNode(new Node { NodeID = NodeType.Picked }); try { if (label.LabelID == 0) { try { label = Factory.DaoLabel().Select(label).First(); } catch { throw new Exception("Label " + label.LabelCode + " does not exists."); } } //Check if already picked if (label.Node.NodeID == NodeType.Picked || label.Node.NodeID == NodeType.Released) { throw new Exception("Label " + label.LabelCode + " already picked."); } if (destBin == null) { destBin = Rules.GetBinForNode(node, label.Bin.Location); } Status locked = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); //Valida si el docuemnto no es nulo Rules.ValidateDocument(document, true); //Valida si el label es un label de producto, //TODO: alarma cuand o suceda el evento de que no es un label de producto Rules.ValidateIsProductLabel(label, true); Rules.ValidateBinStatus(label.Bin, true); //Valida si el status es Activo Rules.ValidateActiveStatus(label.Status, true); //Valida si el label esta en el nodo que debe estar (Ruta de Nodos) //TODO: alarma cuand o suceda el evento de que no es un label de producto Rules.ValidateNodeRoute(label, node, true); //revisa si el label tiene zero Qty Rules.ValidateLabelQuantity(label, true); //Validar si las locations son iguales Rules.ValidatePickLocation(document.Location, label.Bin.Location, true); //label.ChildLabels = Factory.DaoLabel().Select( // new Label { FatherLabel = label, Status = new Status { StatusID = EntityStatus.Active } }); if (document.IsFromErp == true) { //Valida si el producto esta en ese documento //Se debe ejecutar proceso para saber si la company permite //recibir producto no existente en el docuemnto DocumentLine docLine = new DocumentLine { Document = document, Product = label.Product, LineStatus = new Status { StatusID = DocStatus.New }, Unit = label.Unit, Quantity = label.StockQty, //label.CurrQty, CreatedBy = document.ModifiedBy }; Rules.ValidateProductInDocument(docLine, true); //Valida si hay saldo pendiente por recibir //Calcula el Current Qty y Valida si esa cantidad aun esta pendiente en el documento //Double quantity = (label.IsLogistic == true) ? Factory.DaoLabel().SelectCurrentQty(label, null, true) : label.CurrQty; Rules.ValidateBalanceQuantityInDocument(docLine, node, true, false); } if (packageLabel != null) { try { packageLabel = GetPackageLabel(packageLabel, document, picker).PackLabel; } catch (Exception ex) { Factory.Rollback(); throw new Exception("Package label could not be created.\n" + ex.Message); } } //Actualiza Label with new data label.Node = node; label.LastBin = label.Bin; label.Bin = destBin; label.ModifiedBy = picker.UserName; label.ModDate = DateTime.Now; label.ShippingDocument = document; label.Printed = true; label.Status = locked; //Registra el movimiento del label en el nodo SaveNodeTrace(new NodeTrace { Node = node, Document = document, Label = label, Quantity = label.CurrQty, IsDebit = false }); label.LabelSource = label.FatherLabel; label.FatherLabel = packageLabel; Factory.DaoLabel().Update(label); //Actualiza Los Hijos (si existen) try { label.ChildLabels = Factory.DaoLabel().Select(new Label { FatherLabel = label }); if (label.ChildLabels != null && label.ChildLabels.Count > 0) { foreach (Label curLabel in label.ChildLabels) { curLabel.Node = node; curLabel.LastBin = label.LastBin; curLabel.Bin = label.Bin; curLabel.ModifiedBy = picker.UserName; curLabel.ModDate = DateTime.Now; curLabel.ShippingDocument = document; curLabel.Status = locked; SaveNodeTrace(new NodeTrace { Node = node, Document = document, Label = curLabel, Quantity = curLabel.CurrQty, IsDebit = false, CreatedBy = document.CreatedBy }); Factory.DaoLabel().Update(curLabel); } } } catch { } Factory.Commit(); return(label); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("PickLabel:", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.Business); throw new Exception(WriteLog.GetTechMessage(ex)); } }
/// <summary> /// Recolecta= producto, sin etiqueta (recibo manual) toma de los labels virtuales para cada unidad basica de producto /// </summary> /// <param name="line"></param> /// <param name="sourceLocation"></param> /// <param name="node"></param> /// <param name="packageLabel"></param> /// <param name="picker"></param> public void PickProduct(DocumentLine line, Label sourceLocation, Node destNode, Label packageLabel, SysUser picker, Bin destBin) { Factory.IsTransactional = true; Node storedNode = WType.GetNode(new Node { NodeID = NodeType.Stored }); Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); Status locked = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); DocumentType labelType = WType.GetLabelType(new DocumentType { DocTypeID = LabelType.ProductLabel }); if (destBin == null) { destBin = Rules.GetBinForNode(destNode, sourceLocation.Bin.Location); } try { //Valida si el docuemnto no es nulo Rules.ValidateDocument(line.Document, true); Rules.ValidateBinStatus(sourceLocation.Bin, true); //Validar si las locations son iguales Rules.ValidatePickLocation(line.Document.Location, sourceLocation.Bin.Location, true); if (sourceLocation.LabelType.DocTypeID == LabelType.ProductLabel) { //Valida que este activo Rules.ValidateActiveStatus(sourceLocation.Status, true); //Validar que no este vod Rules.ValidateVoided(sourceLocation.Node, true); } if (line.Document.DocType.DocTypeID != SDocType.PickTicket) { //Valida si el producto esta en ese documento DocumentLine docLine = new DocumentLine { Document = line.Document, Product = line.Product, LineStatus = new Status { StatusID = DocStatus.New }, Unit = line.Unit, Quantity = line.Quantity, CreatedBy = picker.UserName }; Rules.ValidateProductInDocument(docLine, true); //Valida si hay saldo pendiente por procesar Rules.ValidateBalanceQuantityInDocument(docLine, destNode, true, false); } //Evaluacion de tipo de source, Bin or Label DateTime recDate = DateTime.Now; if (Rules.ValidateIsBinLabel(sourceLocation, false)) { IList <Label> tranLabel = DecreaseQtyFromBin(sourceLocation, line, "Picking Source Product", true, storedNode); try { recDate = (DateTime)tranLabel.Where(f => f.ReceivingDate != null).OrderBy(f => f.ReceivingDate).First().ReceivingDate; } catch { recDate = DateTime.Now; } } //SI el ajustes es sobre un Label else if (Rules.ValidateIsProductLabel(sourceLocation, false)) { DecreaseQtyFromLabel(sourceLocation, line, "Picking Source Product", true, storedNode, true); try { recDate = (sourceLocation.ReceivingDate == null) ? DateTime.Now : (DateTime)sourceLocation.ReceivingDate; } catch { recDate = DateTime.Now; } } //Creando el package para ingresar la mercancia. if (packageLabel != null) { line.Document.Location = sourceLocation.Bin.Location; //Revalidando que el location sea correcto try { packageLabel = GetPackageLabel(packageLabel, line.Document, picker).PackLabel; } catch (Exception ex) { Factory.Rollback(); throw new Exception("Package label could not be created.\n" + ex.Message); } } //Increasing the Record of Product on Dest Bin. Label pickedLabel = IncreaseQtyIntoBin(line, destNode, destBin, "Picking Dest Product", true, recDate, null, sourceLocation); pickedLabel.FatherLabel = packageLabel; pickedLabel.Status = locked; pickedLabel.ShippingDocument = line.Document; Factory.DaoLabel().Update(pickedLabel); Factory.Commit(); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("PickProduct:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); throw new Exception(WriteLog.GetTechMessage(ex)); } }
/// <summary> /// Crea a new label package for a specific document, this package will contain product picked for the order. /// </summary> /// <param name="line"></param> /// <param name="picker"></param> /// <returns></returns> public DocumentPackage CreateNewPackage(Document document, SysUser picker, bool isOpen, DocumentPackage parent, string packageType) { Factory.IsTransactional = true; Node node = WType.GetNode(new Node { NodeID = NodeType.Picked }); Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); DocumentType labelType = WType.GetLabelType(new DocumentType { DocTypeID = LabelType.CustomerLabel }); Unit logisticUnit = WType.GetUnit(new Unit { Company = document.Company, Name = WmsSetupValues.CustomUnit }); Bin destLocation = WType.GetBin(new Bin { Location = document.Location, BinCode = DefaultBin.PICKING }); int sequence = Factory.DaoDocumentPackage().Select(new DocumentPackage { Document = document, //PostingDocument = new Document {DocID = -1 } }).Count + 1; //Generate new logistig labels located in MAIN //Labels shouldbe activated the next transaction try { //Funcion para obtener siguiente Label //DocumentTypeSequence initSequence = GetNextDocSequence(document.Company, labelType); Label packLabel = new Label(); packLabel.Node = node; packLabel.Bin = destLocation; packLabel.CreatedBy = picker.UserName; packLabel.Status = status; packLabel.LabelType = labelType; packLabel.CreationDate = DateTime.Now; packLabel.Printed = false; packLabel.Unit = logisticUnit; packLabel.IsLogistic = true; packLabel.LabelCode = ""; // initSequence.NumSequence.ToString() + GetRandomHex(picker.UserName, initSequence.NumSequence); packLabel.Notes = "Package label for Document # " + document.DocNumber; packLabel.ShippingDocument = document; //Added on 14/ENE/09 if (parent != null && parent.PackLabel != null && parent.PackLabel.LabelID != 0) { try { packLabel.FatherLabel = parent.PackLabel; } catch { } } //Creado el document Package Asociado al Label DocumentPackage docPack = new DocumentPackage { Document = document, CreatedBy = picker.UserName, CreationDate = DateTime.Now, IsClosed = !isOpen, PackLabel = packLabel, Picker = picker, StartTime = DateTime.Now, EndTime = DateTime.Now, Sequence = (short)sequence, Dimension = "", ShipToName = document.Customer.Name, //Added on 14/ENE/09 ParentPackage = (parent != null && parent.PackID != 0) ? parent : null, PackageType = packageType }; //Address Line for package 16/oct/09 DocumentAddress ShipTo_address = null; try { ShipTo_address = Factory.DaoDocumentAddress().Select( new DocumentAddress { Document = document, AddressType = AddressType.Shipping }) .Where(f => f.DocumentLine == null).First(); docPack.AddressLine1 = ShipTo_address.AddressLine1 + " " + ShipTo_address.AddressLine2; docPack.AddressLine2 = ShipTo_address.City + ", " + ShipTo_address.State + " " + ShipTo_address.ZipCode; docPack.AddressLine3 = ShipTo_address.Country; } catch { } packLabel.DocumentPackages = new List <DocumentPackage> { docPack }; packLabel = Factory.DaoLabel().Save(packLabel); packLabel.LabelCode = packLabel.LabelID.ToString(); //Registra el movimiento del nodo SaveNodeTrace( new NodeTrace { Node = node, Document = document, Label = packLabel, Quantity = packLabel.CurrQty, IsDebit = false, CreatedBy = picker.UserName } ); //initSequence.NumSequence; //Factory.DaoDocumentTypeSequence().Update(initSequence); Factory.Commit(); //actualizando el documento try { if (string.IsNullOrEmpty(document.UserDef3)) { //document.UserDef3 = picker.UserName; Factory.DaoDocument().Update(document); } } catch { } return(docPack); } catch { throw; } }
private Status GetShippingStatus(int p) { return(WType.GetStatus(new Status { StatusID = DocStatus.New })); }
//This method revisa si el recibo pertenece a aun procesos de cross dock //y Anula el docuemnto de crossdock y sus lineas, y Unpick las cantidades //piqueadas para los documentos de ventas private void ReverseCrossDockProcess(Document receipt) { if (receipt.CrossDocking != true) { return; } try { Factory.IsTransactional = true; Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); TaskDocumentRelation taskRel = new TaskDocumentRelation { IncludedDoc = receipt, TaskDoc = new Document { DocType = new DocumentType { DocTypeID = SDocType.CrossDock } } }; IList <TaskDocumentRelation> listTask = Factory.DaoTaskDocumentRelation().Select(taskRel) .Where(f => f.TaskDoc.DocStatus.StatusID != DocStatus.Cancelled).ToList(); //Cuando no tiene docuemnto asociado if (listTask == null || listTask.Count == 0) { return; } //Si tiene docuemnto asociado continua. //1. Cancela el documento cross dock y sus lineas. Document crossDockDocument = listTask[0].TaskDoc; crossDockDocument.DocStatus = cancelled; WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); crossDockDocument.Comment += "\nDocument cancelled due the reversion of receipt " + receipt.DocNumber; crossDockDocument.ModifiedBy = receipt.ModifiedBy; crossDockDocument.ModDate = DateTime.Now; foreach (DocumentLine line in crossDockDocument.DocumentLines) { line.LineStatus = cancelled; Factory.DaoDocumentLine().Update(line); } //Actualizando el documento Factory.DaoDocument().Update(crossDockDocument); //Reversando las cantidades piqeuadas para suplir los documentos de ventas. //Obtiene las cantidades que fueron piquedas por cada liena de cada documento de vantas //Node traces que fueron afectados con ese recibo. NodeTrace sourceTrace = new NodeTrace { Node = new Node { NodeID = NodeType.Picked }, Status = new Status { StatusID = EntityStatus.Active }, Comment = receipt.CustPONumber }; IList <NodeTrace> nodes = Factory.DaoNodeTrace().Select(sourceTrace); Node labelNode = Factory.DaoNode().Select(new Node { NodeID = NodeType.Stored }).First(); //revesar todo lo piqueado a main Bin bin = WType.GetBin(new Bin { Location = receipt.Location, BinCode = DefaultBin.PUTAWAY }); Status status = Factory.DaoStatus().Select(new Status { StatusID = EntityStatus.Active }).First(); ReverseNodeTrace(nodes, receipt.ModifiedBy, labelNode, bin, status); Factory.Commit(); } catch (Exception ex) { Factory.Rollback(); ExceptionMngr.WriteEvent("ReverseCrossDockProcess:Doc#" + receipt.DocNumber, ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); throw; } }
//Mueve cantidades de un package a otro public void MoveQtyBetweenPackages(DocumentPackage curPack, DocumentPackage newPack, Product product, double qty) { Factory.IsTransactional = true; Unit baseUnit = product.BaseUnit; try { DocumentLine line = new DocumentLine { Quantity = qty, Product = product, Unit = baseUnit, CreatedBy = newPack.CreatedBy }; #region remove from OLD package //######################################################################### //Remover la cantidad del paquete origen //Saca las cantidades para es BIN y de ese producto. IList <Label> labelList = GetPackageLabels(curPack.PackLabel, line); Label sourceLabel = null; if (labelList.Sum(f => f.BaseCurrQty) < line.Quantity * line.Unit.BaseAmount) { Factory.Rollback(); throw new Exception("No quantity available for the transaction."); } //Recorre los labels hasta que termine el saldo y se salga. double qtyBalance = line.Quantity * line.Unit.BaseAmount; double curQty; foreach (Label label in labelList) { if (qtyBalance <= 0) { break; } label.CurrQty = label.BaseCurrQty; label.StartQty = label.BaseStartQty; label.Unit = baseUnit; //Cantidad a Disminuir curQty = qtyBalance > label.CurrQty ? label.CurrQty : qtyBalance; qtyBalance -= curQty; label.CurrQty -= curQty; label.ModDate = DateTime.Now; label.ModifiedBy = line.CreatedBy; Factory.DaoLabel().Update(label); sourceLabel = label; } #endregion #region add to NEW package //######################################################################### //Adicionar la cantidad al paquete destino Label tmpLabel = null; Status statusLock = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); //Active DocumentType lblType = new DocumentType { DocTypeID = LabelType.ProductLabel }; //DocumentTypeSequence initSequence = DocMngr.GetNextDocSequence(curPack.Document.Company, lblType); //Funcion para obtener siguiente Label //Salvar con el nuevo status tmpLabel = new Label(); //To Send Node node = WType.GetNode(new Node { NodeID = NodeType.Released }); tmpLabel.Node = curPack.PackLabel.Node; tmpLabel.Bin = curPack.PackLabel.Bin; tmpLabel.CurrQty = line.Quantity; tmpLabel.Product = line.Product; tmpLabel.StartQty = line.Quantity; tmpLabel.Unit = line.Product.BaseUnit; tmpLabel.CreatedBy = line.CreatedBy; tmpLabel.Status = statusLock; tmpLabel.LabelType = lblType; tmpLabel.LabelCode = ""; // initSequence.NumSequence.ToString() + GetRandomHex(line.CreatedBy, initSequence.NumSequence); tmpLabel.Printed = false; tmpLabel.CreationDate = DateTime.Now; tmpLabel.IsLogistic = false; tmpLabel.ShippingDocument = curPack.Document; tmpLabel.LabelSource = sourceLabel; tmpLabel.FatherLabel = newPack.PackLabel; tmpLabel = Factory.DaoLabel().Save(tmpLabel); #endregion Factory.Commit(); } catch { Factory.Rollback(); throw; } }
private void ProcessDocuments(IList <Document> list, Company company) { if (list == null) { return; } Document qDoc; DocumentLine curLine; Factory.Commit(); Factory.IsTransactional = true; Status cancell = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled }); string flag = ""; //pregunta si sobre escribe las cantidades ya guardadas con las nuevas del ERP string overWriteQtys = "T"; try { overWriteQtys = GetCompanyOption(company, "OVERWQTY"); } catch { overWriteQtys = "T"; } int i, y; foreach (Document e in list) { try { flag = "Document"; qDoc = new Document { DocNumber = e.DocNumber, //DocType = new DocumentType { DocTypeID = e.DocType.DocTypeID }, Company = new Company { CompanyID = e.Company.CompanyID } }; //Evalua si el documento ya existe IList <Document> exList = Factory.DaoDocument().Select(qDoc); e.ModDate = DateTime.Now; e.ModifiedBy = WmsSetupValues.SystemUser; Factory.Commit(); //Si No existe if (exList.Count == 0) { e.CreationDate = DateTime.Now; e.CreatedBy = string.IsNullOrEmpty(e.CreatedBy) ? WmsSetupValues.SystemUser : e.CreatedBy; Factory.DaoDocument().Save(e); Factory.Commit(); } else { //Si el documento esta completado no puede ser actualizado por el DEL ERP //13 Oct 2009 //if (exList.First().DocStatus.StatusID == DocStatus.Completed) //continue; //Si el last change del document e sdiferente de nulo y no es mayor al ultimo las change if (exList.First().LastChange != null && exList.First().LastChange >= e.LastChange) { continue; } //Console.WriteLine("Document:" + e.DocNumber); //Valores que no pueden cambiar asi se reciban de nuevo del ERP e.DocID = exList.First().DocID; e.CreationDate = exList.First().CreationDate; e.CreatedBy = exList.First().CreatedBy; e.Priority = exList.First().Priority; e.Notes = exList.First().Notes; e.CrossDocking = exList.First().CrossDocking; if (!string.IsNullOrEmpty(exList.First().Comment)) { e.Comment = exList.First().Comment; } e.PickMethod = exList.First().PickMethod; e.AllowPartial = exList.First().AllowPartial; e.ModDate = DateTime.Now; e.ModifiedBy = e.CreatedBy; //Conserva el status si el actual es mayor al que viene del el ERP. if (exList.First().DocStatus.StatusID > e.DocStatus.StatusID) { e.DocStatus = exList.First().DocStatus; } flag = "Address"; #region DocAddress if (e.DocumentAddresses != null) { //Evaluar los document Address i = 0; DocumentAddress curAddr; foreach (DocumentAddress addr in e.DocumentAddresses) { curAddr = new DocumentAddress(); curAddr.Document = new Document { DocID = e.DocID }; curAddr.Name = addr.Name; curAddr.DocumentLine = new DocumentLine { LineID = -1 }; IList <DocumentAddress> listAddrs = Factory.DaoDocumentAddress().Select(curAddr); Factory.Commit(); if (listAddrs.Count > 0) { e.DocumentAddresses[i].ModDate = DateTime.Now; e.DocumentAddresses[i].ModifiedBy = WmsSetupValues.SystemUser; e.DocumentAddresses[i].RowID = listAddrs.First().RowID; e.DocumentAddresses[i].CreationDate = listAddrs.First().CreationDate; e.DocumentAddresses[i].CreatedBy = listAddrs.First().CreatedBy; } else { e.DocumentAddresses[i].CreationDate = DateTime.Now; e.DocumentAddresses[i].CreatedBy = WmsSetupValues.SystemUser; } i++; } } //Factory.DaoDocument().Update(e); #endregion flag = "Lines"; //Evaluar los document Lines #region DocLines if (e.DocumentLines != null) { IList <DocumentLine> currentLines = Factory.DaoDocumentLine().Select(new DocumentLine { Document = new Document { DocID = e.DocID } }); //Elimina la lineas que no sean de procesos originale del ERP //Para recrealas en pasos posteriores if (currentLines != null && currentLines.Count > 0) { //foreach (DocumentLine curxLine in currentLines.Where(f=>f.Note != "1" && f.Note != "2" && f.LinkDocLineNumber == 0 )) foreach (DocumentLine curxLine in currentLines.Where(f => f.LinkDocLineNumber <= 0)) { //Borra las lineas que no existan ya y que no sean de tipo kit assembly. //if (!e.DocumentLines.Any(f => f.LineNumber == curxLine.LineNumber || ((f.Note == "1" || f.Note == "2") && f.LinkDocLineNumber > 0))) //Console.WriteLine("\t" + curxLine.LineNumber); if (!e.DocumentLines.Any(f => f.LineNumber == curxLine.LineNumber)) { //if (curxLine.Note != "1" && curxLine.Note != "2" && curxLine.LinkDocLineNumber == 0) Factory.DaoDocumentLine().Delete(curxLine); //Console.WriteLine("\tDeleted " + curxLine.LineNumber); } //curxLine.LineStatus = cancell; //Factory.DaoDocumentLine().Update(curxLine); } Factory.Commit(); } i = 0; IList <DocumentLine> linesToRemove = new List <DocumentLine>(); foreach (DocumentLine line in e.DocumentLines) { curLine = new DocumentLine { Document = new Document { DocID = e.DocID }, LineNumber = line.LineNumber }; IList <DocumentLine> listLines = Factory.DaoDocumentLine().Select(curLine); Factory.Commit(); //Console.WriteLine(e.DocNumber + "," + e.DocID + "," + line.LineNumber + "," + listLines.Count.ToString()); if (listLines.Count > 0) { //if (listLines.First().LineStatus.StatusID == DocStatus.InProcess || listLines.First().LineStatus.StatusID == DocStatus.Completed) if (listLines.First().LineStatus.StatusID != DocStatus.New) { linesToRemove.Add(e.DocumentLines[i]); i++; continue; } e.DocumentLines[i].ModDate = DateTime.Now; e.DocumentLines[i].ModifiedBy = WmsSetupValues.SystemUser; e.DocumentLines[i].LineID = listLines.First().LineID; e.DocumentLines[i].CreationDate = listLines.First().CreationDate; e.DocumentLines[i].CreatedBy = listLines.First().CreatedBy; e.DocumentLines[i].QtyShipped = listLines.First().QtyShipped; e.DocumentLines[i].LinkDocLineNumber = listLines.First().LinkDocLineNumber; e.DocumentLines[i].LinkDocNumber = listLines.First().LinkDocNumber; if (overWriteQtys.Equals("F")) { if (e.DocumentLines[i].QtyAllocated > 0 && listLines.First().QtyAllocated == 0) { e.DocumentLines[i].QtyAllocated = listLines.First().QtyAllocated; } if (e.DocumentLines[i].QtyBackOrder > 0 && listLines.First().QtyBackOrder == 0) { e.DocumentLines[i].QtyBackOrder = listLines.First().QtyBackOrder; } if (e.DocumentLines[i].QtyCancel > 0 && listLines.First().QtyCancel == 0) { e.DocumentLines[i].QtyCancel = listLines.First().QtyCancel; } } #region Document Line Address //Evaluar los document Line Address if (line.DocumentLineAddresses != null) { y = 0; DocumentAddress curLineAddr; foreach (DocumentAddress lineAddr in line.DocumentLineAddresses) { curLineAddr = new DocumentAddress(); curLineAddr.Document = new Document { DocID = line.Document.DocID }; curLineAddr.DocumentLine = line; curLineAddr.Name = lineAddr.Name; IList <DocumentAddress> listLineAddrs = Factory.DaoDocumentAddress().Select(curLineAddr); Factory.Commit(); if (listLineAddrs.Count > 0) { line.DocumentLineAddresses[y].ModDate = DateTime.Now; line.DocumentLineAddresses[y].ModifiedBy = WmsSetupValues.SystemUser; line.DocumentLineAddresses[y].RowID = listLineAddrs.First().RowID; line.DocumentLineAddresses[y].CreationDate = listLineAddrs.First().CreationDate; line.DocumentLineAddresses[y].CreatedBy = listLineAddrs.First().CreatedBy; } else { line.DocumentLineAddresses[y].CreationDate = DateTime.Now; line.DocumentLineAddresses[y].CreatedBy = WmsSetupValues.SystemUser; } y++; } } #endregion } else { e.DocumentLines[i].CreationDate = DateTime.Now; e.DocumentLines[i].CreatedBy = WmsSetupValues.SystemUser; } i++; } //Remueve las lineas que no van a ser procesadas. foreach (DocumentLine lr in linesToRemove) { e.DocumentLines.Remove(lr); } } #endregion flag = "Update Document"; Factory.DaoDocument().Update(e); Factory.Commit(); } flag = "Explode Kit"; //Incluido Mayo 14 de 2009 Evalua si el documento de Venta tiene lineas de assembly y debe mostrar //Los componentes //e.DocType.DocClass.DocClassID == SDocClass.Shipping - Removido ON Sep 17/09 //Console.WriteLine("\tDocument Before Explode:" + e.DocNumber); if (e.DocType.DocTypeID == SDocType.SalesOrder && GetCompanyOption(e.Company, "SHOWCOMP").Equals("T")) { //Console.WriteLine("\tDocument Explode:" + e.DocNumber); ExplodeKitAssemblyComponents(e, true); } //Incluido Mayo 26 de 2009 Evalua si el documento de Return tiene lineas de assembly y debe mostrar //Los componentes, pero no recibirlos, recibe el asembli, por eso el parametro en false. if (e.DocType.DocTypeID == SDocType.Return && GetCompanyOption(e.Company, "RETURNCOMP").Equals("T")) { ExplodeKitAssemblyComponents(e, false); } } catch (Exception ex) { Factory.Rollback(); if (e.DocType.DocTypeID != SDocType.KitAssemblyTask) //&& !ex.Message.Contains("Problem updating the record.") { ExceptionMngr.WriteEvent("ProcessDocuments:" + flag + ":" + e.DocNumber, ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business); } //throw; } } }
private IList <Document> GetKitAssemblyDocuments(String sWhere) { //retorna la lista de Documentos de Assembly Document tmpData = null; try { Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString); // BM00101 - KitAssemblyHeader DataSet ds = ReturnDataSet("SELECT h.*,d.LOCNCODE FROM BM10200 h INNER JOIN BM10300 d ON h.TRX_ID=d.TRX_ID AND d.Parent_Component_ID=-1 WHERE h.BM_Trx_Status=3 AND h.USERDEF1 <> 'WMSEXPRESS'", sWhere, "BM10200", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } List <Document> list = new List <Document>(); Status status = WType.GetStatus(new Status { StatusID = DocStatus.New }); Account defAccount = WType.GetAccount(new Account { AccountCode = WmsSetupValues.DEFAULT }); SysUser user = WType.GetUser(new SysUser { UserName = WmsSetupValues.AdminUser }); Company company = CurCompany; DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass { DocClassID = SDocClass.Inventory }); DocumentType docType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.KitAssemblyTask }); foreach (DataRow dr in ds.Tables[0].Rows) { try { //Map Properties tmpData = new Document(); tmpData.Date1 = DateTime.Parse(dr["TRXDATE"].ToString()); //Tran date tmpData.Date2 = DateTime.Parse(dr["BM_Start_Date"].ToString()); //BM_Start_Date tmpData.Date3 = DateTime.Parse(dr["PSTGDATE"].ToString()); //PSTGDATE tmpData.DocNumber = dr["TRX_ID"].ToString(); tmpData.CreatedBy = dr["USER2ENT"].ToString(); try { tmpData.Location = WType.GetLocation(new Location { Company = CurCompany, ErpCode = dr["LOCNCODE"].ToString() }); } catch { } tmpData.DocStatus = status; tmpData.DocConcept = docConcept; tmpData.Vendor = defAccount; tmpData.Customer = defAccount; tmpData.IsFromErp = true; tmpData.CrossDocking = false; tmpData.Company = CurCompany; tmpData.Reference = dr["REFRENCE"].ToString(); tmpData.DocType = docType; tmpData.PickMethod = docType.PickMethod; //Asignacion de Lines - Seguen el tipo de orden tmpData.DocumentLines = GetKitAssemblyDocumentLines(tmpData); if (tmpData.DocumentLines != null && tmpData.DocumentLines.Count > 0) { list.Add(tmpData); } } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); } } return(list); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocuments:", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); return(null); } }
private IList <DocumentLine> GetKitAssemblyDocumentLines(Document doc) { DocumentLine tmpData; IList <DocumentLine> list = new List <DocumentLine>(); Status lineStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); int curLine = 1; string curMaster = ""; Query = GetErpQuery("KITDOC_LINE").Replace("__DOCUMENT", doc.ErpMaster.ToString()); DataSet ds = ReturnDataSet(Query, null, "KITDOC_LINE", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } if (ds.Tables[0].Select("rowid=0").Length == 0) { return(null); } try { foreach (DataRow dr in ds.Tables[0].Rows) { tmpData = new DocumentLine(); tmpData.Date1 = doc.Date1; tmpData.LineNumber = int.Parse(dr["rowid"].ToString()); //curLine++; tmpData.Sequence = tmpData.LineNumber; tmpData.LinkDocLineNumber = int.Parse(dr["row_padre"].ToString()); tmpData.Note = dr["type"].ToString(); //TODO: Revisar el Status en GP para traer el equivalente tmpData.LineStatus = lineStatus; tmpData.Document = doc; tmpData.IsDebit = false; tmpData.Quantity = double.Parse(dr["f470_cant_base"].ToString(), ListValues.DoubleFormat()); tmpData.CreatedBy = WmsSetupValues.SystemUser; tmpData.CreationDate = DateTime.Now; curMaster = "Location"; tmpData.Location = doc.Location; //WType.GetLocation(new Location { Company = CurCompany, ErpCode = dr["LOCNCODE"].ToString() }); try { curMaster = "Product"; tmpData.Product = WType.GetProduct(new Product { Company = CurCompany, ProductCode = dr["item_id"].ToString() });; curMaster = "Unit"; tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["unit_id"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup }); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); continue; //{ // //Pone el Default Product // tmpData.Product = WType.GetProduct(new Product { Company = CurCompany, ProductCode = WmsSetupValues.DEFAULT }); // tmpData.LineDescription = "Unknown: " + dr["ITEMNMBR"].ToString() + ", " + dr["ITEMDESC"].ToString(); // curMaster = "Unit"; // tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() }); } list.Add(tmpData); } return((list.Count > 0) ? list : null); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); throw; //return null; } }
private IList <DocumentLine> GetShippingDocumentLines(Document doc, Company company, string docID, bool useRemain) { DocumentLine tmpData; IList <DocumentLine> list = new List <DocumentLine>(); Status lineStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); int curLine = 0; string curMaster = ""; try { Query = GetErpQuery("SALESORDER_LINE").Replace("__DOCUMENT", docID); DataSet ds = ReturnDataSet(Query, null, "SALESORDER_LINE", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } foreach (DataRow dr in ds.Tables[0].Rows) { tmpData = new DocumentLine(); tmpData.Date1 = doc.Date1; curMaster = ""; try { tmpData.Date2 = DateTime.Parse(dr["f431_fecha_entrega"].ToString()); } catch { } try { tmpData.Date3 = DateTime.Parse(dr["f431_fecha_cumplido"].ToString()); } catch { } tmpData.LineNumber = int.Parse(dr["f431_rowid"].ToString()); tmpData.Sequence = tmpData.LineNumber; curLine = tmpData.LineNumber; //TODO: Revisar el Status en GP para traer el equivalente tmpData.LineStatus = GetShippingStatus(0); tmpData.Document = doc; tmpData.IsDebit = false; if (useRemain) { tmpData.Quantity = double.Parse(dr["f431_cant_facturada_base"].ToString(), new NumberFormatInfo { NumberDecimalSeparator = Separator }); } else { tmpData.Quantity = double.Parse(dr["f431_cant_facturada_base"].ToString(), ListValues.DoubleFormat()); } //tmpData.QtyCancel = double.Parse(dr["QTYCANCE"].ToString(), ListValues.DoubleFormat()); //tmpData.QtyBackOrder = double.Parse(dr["QTYTBAOR"].ToString(), ListValues.DoubleFormat()); //tmpData.QtyPending = tmpData.Quantity - tmpData.QtyCancel - double.Parse(dr["QTYPRINV"].ToString(), ListValues.DoubleFormat()); //tmpData.QtyAllocated = double.Parse(dr["ATYALLOC"].ToString(), ListValues.DoubleFormat()); tmpData.CreatedBy = WmsSetupValues.SystemUser; tmpData.CreationDate = DateTime.Now; curMaster = "Location:" + dr["cod_bodega"].ToString(); tmpData.Location = WType.GetLocation(new Location { Company = company, ErpCode = dr["cod_bodega"].ToString() }); try { curMaster = "Product:" + dr["f121_rowid_item"].ToString(); tmpData.Product = WType.GetProduct(new Product { Company = company, ProductCode = dr["f121_rowid_item"].ToString() }); tmpData.LineDescription = dr["f120_descripcion"].ToString(); curMaster = "Uom:" + dr["f431_id_unidad_medida"].ToString(); tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["f431_id_unidad_medida"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup }); } catch { //Pone el Default Product tmpData.Product = WType.GetProduct(new Product { Company = doc.Location.Company, ProductCode = WmsSetupValues.DEFAULT }); tmpData.LineDescription = "Unknown: " + dr["f121_rowid_item"].ToString() + ", " + dr["f120_descripcion"].ToString(); curMaster = "Uom:" + dr["f431_id_unidad_medida"].ToString(); tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["f431_id_unidad_medida"].ToString() }); } //Manage Prices curMaster = "Prices Product:" + dr["f121_rowid_item"].ToString(); tmpData.UnitPrice = double.Parse(dr["f431_precio_unitario_base"].ToString(), ListValues.DoubleFormat()); tmpData.ExtendedPrice = double.Parse(dr["subtotal"].ToString(), ListValues.DoubleFormat()); //Asignacion de Address curMaster = "Address Doc:" + doc.DocNumber; //tmpData.DocumentLineAddresses = GetShippingDocumentAddress(tmpData.Document, tmpData, dr); list.Add(tmpData); } return((list.Count > 0) ? list : null); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetShippingDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); //throw; return(null); } }
private IList <Document> GetLocationTransferDocuments(string sWhere) { IList <Document> list = new List <Document>(); DocumentClass docClass = new DocumentClass(); Document tmpData = null; try { /* * 401 0 En elaboraciĆ³n * 401 1 Aprobado * 401 2 Parcial * 401 3 Cumplido * 401 9 Anulado */ sWhere = string.IsNullOrEmpty(sWhere) ? "" : " AND " + sWhere; Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString); Query = GetErpQuery("TRANSFER"); DataSet ds = ReturnDataSet(Query, null, "TRANSFER", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass { DocClassID = SDocClass.Receiving }); DocumentType docType = WType.GetDocumentType(new DocumentType { DocTypeID = SDocType.InTransitShipment }); Status docStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); Account defAccount = WType.GetAccount(new Account { AccountCode = WmsSetupValues.DEFAULT }); SysUser user = WType.GetUser(new SysUser { UserName = WmsSetupValues.AdminUser }); Company company = CurCompany; //En el dataset, Tables: 1 - DocumentHeader foreach (DataRow dr in ds.Tables[0].Rows) { try { //Map Properties tmpData = new Document(); tmpData.Date1 = DateTime.Parse(dr["f450_id_fecha"].ToString()); tmpData.DocNumber = dr["numero_doc"].ToString(); tmpData.DocStatus = docStatus; //GetReceivingStatus(int.Parse(dr["POSTATUS"].ToString())); tmpData.DocType = docType; tmpData.PickMethod = docType.PickMethod; tmpData.DocConcept = docConcept; tmpData.Vendor = defAccount; //Vendor Account; tmpData.Customer = defAccount; tmpData.CreatedBy = WmsSetupValues.SystemUser; tmpData.Reference = dr["f450_docto_alterno"].ToString(); tmpData.UserDef1 = dr["co_salida"].ToString(); //CO Origen - SALIDA tmpData.UserDef2 = dr["bodega_salida"].ToString(); //Bodega Origen - SALIDA //try { tmpData.LastChange = DateTime.Parse(dr["f450_ts"].ToString()); } //catch { } tmpData.IsFromErp = true; tmpData.CrossDocking = false; tmpData.Location = WType.GetLocation(new Location { ErpCode = dr["bodega_entrada"].ToString(), Company = company }); //location; tmpData.Company = CurCompany; //Asignacion de Lines tmpData.DocumentLines = GetLocationTransferDocumentLines(tmpData, company, dr["f450_rowid_docto"].ToString()); if (tmpData.DocumentLines != null && tmpData.DocumentLines.Count > 0) { //El location debe ser el de la primera linea if (tmpData.Location == null) { tmpData.Location = tmpData.DocumentLines[0].Location; } list.Add(tmpData); } } catch (Exception ex) { ExceptionMngr.WriteEvent("GetLocationTransferDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); } } //retornar la lista return(list); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetLocationTransferDocuments", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); //throw; return(null); } }
private IList <DocumentLine> GetKitAssemblyDocumentLines(Document doc) { DocumentLine tmpData; IList <DocumentLine> list = new List <DocumentLine>(); Status lineStatus = WType.GetStatus(new Status { StatusID = DocStatus.New }); int curLine = 1; string curMaster = ""; // BM10300 - KitAssembly Document Lines DataSet ds = ReturnDataSet("SELECT * FROM BM10300 WHERE 1=1 ", "TRX_ID='" + doc.DocNumber + "'", "BM10300", Command.Connection); if (ds == null || ds.Tables.Count == 0) { return(null); } try { foreach (DataRow dr in ds.Tables[0].Rows) { tmpData = new DocumentLine(); tmpData.Date1 = doc.Date1; tmpData.LineNumber = int.Parse(dr["Component_ID"].ToString()); //curLine++; tmpData.Sequence = tmpData.LineNumber; tmpData.LinkDocLineNumber = int.Parse(dr["Parent_Component_ID"].ToString()); tmpData.Note = dr["BM_Component_Type"].ToString(); //TODO: Revisar el Status en GP para traer el equivalente tmpData.LineStatus = lineStatus; tmpData.Document = doc; tmpData.IsDebit = false; tmpData.Quantity = double.Parse(dr["Extended_Standard_Quantity"].ToString(), ListValues.DoubleFormat()); tmpData.CreatedBy = WmsSetupValues.SystemUser; tmpData.CreationDate = DateTime.Now; curMaster = "Location"; tmpData.Location = WType.GetLocation(new Location { Company = CurCompany, ErpCode = dr["LOCNCODE"].ToString() }); try { curMaster = "Product"; tmpData.Product = WType.GetProduct(new Product { Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString() });; curMaster = "Unit"; tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup }); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); continue; //{ // //Pone el Default Product // tmpData.Product = WType.GetProduct(new Product { Company = CurCompany, ProductCode = WmsSetupValues.DEFAULT }); // tmpData.LineDescription = "Unknown: " + dr["ITEMNMBR"].ToString() + ", " + dr["ITEMDESC"].ToString(); // curMaster = "Unit"; // tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() }); } list.Add(tmpData); } return((list.Count > 0) ? list : null); } catch (Exception ex) { ExceptionMngr.WriteEvent("GetKitAssemblyDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection); throw; //return null; } }