Ejemplo n.º 1
0
        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));
            }
        }
        //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;
            }
        }
        //
        /// <summary>
        ///Receive Returns, primero recibe normal la cantidad total y luego saca de ese label todo lo que o sea onHand.
        /// Deja el mismo receiving document para poder crear el documento a postear en el ERP.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="retProduct"></param>
        /// <param name="sysUser"></param>
        /// <param name="retTotalQty"></param>
        /// <returns></returns>
        public bool ReceiveReturn(Document document, IList <ProductStock> retProduct,
                                  SysUser sysUser, double retTotalQty, Node recNode)
        {
            Factory.IsTransactional = true;

            try
            {
                DocumentLine line = new DocumentLine
                {
                    Document     = document,
                    Product      = retProduct.First().Product, //View.ComboProduct.SelectedItem,
                    Unit         = retProduct.First().Unit,
                    Quantity     = retTotalQty,
                    QtyPending   = retTotalQty,
                    QtyAllocated = 1,
                    CreatedBy    = sysUser.UserName
                };

                //RETURN
                Bin binDest = WType.GetBin(new Bin {
                    BinCode = DefaultBin.RETURN, Location = retProduct.First().Bin.Location
                });
                //retProduct.Where(f => f.Bin.BinCode == DefaultBin.RETURN).Select(f => f.Bin).First();

                ReceiveProduct(line, new Unit(), binDest, recNode);

                //Mueve las cantidades diferentes del Bin Return a el Bin Correcto.
                Label label = Factory.DaoLabel().Select(new Label {
                    ReceivingDocument = document,
                    Product           = retProduct.First().Product,
                    Status            = new Status {
                        StatusID = EntityStatus.Active
                    }, Node = recNode
                }).First();
                DocumentLine tmpLine = null;

                foreach (ProductStock ps in retProduct.Where(f => f.Bin.BinCode != DefaultBin.RETURN))
                {
                    tmpLine = new DocumentLine {
                        Quantity = ps.Stock, Document = document,
                        Product  = ps.Product, CreatedBy = sysUser.UserName, Unit = ps.Unit
                    };

                    //Disminuye el Label Original
                    DecreaseQtyFromLabel(label, tmpLine, "Decreased in return " + document.DocNumber, false, recNode, false);
                    label.StartQty = label.CurrQty;

                    //Crea un Lable Nuevo en el bin de destino.
                    IncreaseQtyIntoBin(tmpLine, recNode, ps.Bin, "Decreased in return " + document.DocNumber + ", Bin: " + ps.Bin.BinCode, true, DateTime.Now, null, label);
                }

                //Reversado el Node trace del label original al la cantidad final.
                try {
                    NodeTrace ndtrace = Factory.DaoNodeTrace().Select(new NodeTrace {
                        Label = label, Document = document
                    }).First();

                    if (label.CurrQty == 0)
                    {//Lo elimina porque la QTY es cero.
                        Factory.DaoNodeTrace().Delete(ndtrace);
                        Factory.DaoLabel().Delete(label);
                    }
                    else
                    {
                        ndtrace.Quantity = label.CurrQty;
                        Factory.DaoNodeTrace().Update(ndtrace);
                        Factory.DaoLabel().Update(label);
                    }
                }
                catch { }



                return(true);
            }
            catch (Exception ex)
            {
                Factory.Rollback();
                ExceptionMngr.WriteEvent("ReceiveReturn:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business);
                throw new Exception(WriteLog.GetTechMessage(ex));
            }
        }
Ejemplo n.º 4
0
        private IList <Account> GetCustomers(string sWhere)
        {
            IList <Account>     list = new List <Account>();
            Account             tmpData;
            AccountTypeRelation tmpAccTypeRel;

            try
            {
                //Lamar los documents que necesita del Erp usando econnect
                //TODO: Revisar obtener solo lo modificado last X days
                ds = DynamicsGP_ec.GetDataSet(DynamicsGP_ec.RetreiveData("Customer", false, 2, 0, sWhere, true));

                if (ds.Tables.Count == 0)
                {
                    return(null);
                }

                //Company company = WType.GetDefaultCompany();
                AccountType accType = WType.GetAccountType(new AccountType {
                    AccountTypeID = AccntType.Customer
                });
                Status status = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });

                //En el dataset, Tables: 1 - CustomerHeader, 2 - CustomerAddress
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    //Map Properties
                    tmpData = new Account();

                    try
                    {
                        tmpData.AccountCode = dr["CUSTNMBR"].ToString();

                        if (string.IsNullOrEmpty(tmpData.AccountCode))
                        {
                            continue;
                        }

                        tmpData.Company       = CurCompany;
                        tmpData.ContactPerson = dr["CNTCPRSN"].ToString();

                        tmpData.Name        = dr["CUSTNAME"].ToString();
                        tmpData.Phone       = dr["PHONE1"].ToString();
                        tmpData.UserDefine1 = dr["USERDEF1"].ToString();
                        tmpData.UserDefine2 = dr["USERDEF2"].ToString();

                        //Account Type
                        tmpAccTypeRel              = new AccountTypeRelation();
                        tmpAccTypeRel.Account      = tmpData;
                        tmpAccTypeRel.AccountType  = accType;
                        tmpAccTypeRel.ErpCode      = dr["CUSTNMBR"].ToString();
                        tmpAccTypeRel.Status       = status;
                        tmpAccTypeRel.CreationDate = DateTime.Now;
                        tmpAccTypeRel.CreatedBy    = WmsSetupValues.SystemUser;
                        tmpData.AccountTypes       = new AccountTypeRelation[] { tmpAccTypeRel };
                        tmpData.IsFromErp          = true;
                        tmpData.BaseType           = accType;

                        //Asignacion de Lines
                        tmpData.AccountAddresses = GetCustomerAddress(tmpData,
                                                                      ds.Tables[2].Select("CUSTNMBR='" + dr["CUSTNMBR"].ToString() + "'"));

                        list.Add(tmpData);
                    }

                    catch (Exception ex) {
                        ExceptionMngr.WriteEvent("GetCustomers:" + tmpData.AccountCode + "-" +
                                                 tmpData.Name, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                    }
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetCustomers", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
        /// <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 ReceiveLabel(Document document, Label label, Bin destLocation, Node recNode)
        {
            try
            {
                if (label.LabelID == 0)
                {
                    try {
                        IList <Label> labelList = Factory.DaoLabel().Select(label);

                        //Revisa que solo un label sea entregado.
                        if (labelList != null && labelList.Count > 1)
                        {
                            throw new Exception("Label " + label.LabelCode + " exists more than once.\nPlease check it.");
                        }

                        label = labelList.First();
                    }
                    catch {
                        throw new Exception("Label " + label.LabelCode + " does not exists.");
                    }
                }
                else
                {
                    //Trae de nuevo le label para cargar los childs en caso de que sea logistica
                    label = Factory.DaoLabel().SelectById(new Label {
                        LabelID = label.LabelID
                    });
                }


                Factory.IsTransactional = true;

                //Valida si el docuemnto no es nulo
                Rules.ValidateDocument(document, true);

                Rules.ValidateBinStatus(destLocation, true);

                //Valida si el status es Activo
                Rules.ValidateActiveStatus(label.Status, 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);

                //Validar Product Restriction
                Rules.ValidateRestrictedProductInBin(label.Product, destLocation, 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, recNode, true);


                if (document.DocType.DocTypeID != SDocType.ReceivingTask)
                {
                    //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 = 0
                    };

                    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().CurrentQty(label) : label.CurrQty * label.UnitBaseFactor;
                    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.Printed           = true;

                //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   = "Receiving " + 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   = "Receiving " + document.DocNumber
                            });
                        }
                    }
                }
                catch { }


                Factory.Commit();
                return(label);
            }
            catch (Exception ex)
            {
                Factory.Rollback();
                ExceptionMngr.WriteEvent("ReceiveLabel:", ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.Business);
                throw new Exception(WriteLog.GetTechMessage(ex));
            }
        }
Ejemplo n.º 6
0
        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);
            }
        }
Ejemplo n.º 7
0
        public IList <KitAssemblyFormula> GetKitAssemblyFormula(string sWhere)
        {
            //retorna la lista de Formulas.

            KitAssemblyFormula tmpData = null;

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                // BM00101 - KitAssemblyHeader
                DataSet ds = ReturnDataSet("SELECT * FROM BM00111 WHERE Bill_Status = 1 AND Component_Status=1 ", sWhere, "BM00111", Command.Connection);


                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }


                List <KitAssemblyFormula> list = new List <KitAssemblyFormula>();
                Status statusOK = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });
                Status statusInactive = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Inactive
                });

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new KitAssemblyFormula();

                        tmpData.KitAssembly = WType.GetKitAssembly(new KitAssembly {
                            Product = new Product {
                                Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString()
                            }
                        });
                        tmpData.Status       = (dr["Component_Status"].ToString() == "1") ? statusOK : statusInactive;
                        tmpData.EfectiveDate = DateTime.Parse(dr["Effective_Date"].ToString());
                        tmpData.ObsoleteDate = DateTime.Parse(dr["Obsolete_Date"].ToString());
                        tmpData.Component    = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["CMPTITNM"].ToString()
                        });
                        tmpData.Unit = WType.GetUnit(new Unit {
                            ErpCode = dr["UOFM"].ToString(), ErpCodeGroup = tmpData.Component.BaseUnit.ErpCodeGroup
                        });
                        tmpData.FormulaQty    = Double.Parse(dr["Design_Qty"].ToString());;
                        tmpData.Ord           = int.Parse(dr["ORD"].ToString());;
                        tmpData.ScrapPercent  = Double.Parse(dr["Scrap_Percentage"].ToString());
                        tmpData.DirectProduct = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString()
                        });

                        list.Add(tmpData);
                    }
                    catch (Exception ex)
                    {
                        ExceptionMngr.WriteEvent("GetKitAssemblyFormula:" + tmpData.KitAssembly.Product.ProductCode + ", " + tmpData.Component.ProductCode, ListValues.EventType.Error, ex, null,
                                                 ListValues.ErrorCategory.ErpConnection);

                        return(null);
                    }
                }


                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetKitAssemblyFormula:", ListValues.EventType.Error, ex, null,
                                         ListValues.ErrorCategory.ErpConnection);

                return(null);
            }
        }
Ejemplo n.º 8
0
        private IList <Product> GetProducts(string sWhere)
        {
            Product         tmpData  = null;
            IList <Product> list     = new List <Product>();
            IList <Unit>    unitList = GetAllUnits();
            IList <Unit>    curList  = unitList;
            Unit            curUnit;
            ProductCategory curCategory;
            string          flag   = "";
            Status          active = WType.GetStatus(new Status {
                StatusID = EntityStatus.Active
            });

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = "select i.ITEMNO,i.DESCRIPT,i.CATEGORY, i.MATRIX_ITEM_TYPE,i.SERIALIZE,i.FORCE_LOT,i.LINK_SERIAL, i.COST, 'EACH' as SALEUNIT,'EACH' as PURCHUNIT, isNull(m.DESCRIPT,'') AS Manuf " +
                        " from items i LEFT OUTER JOIN MANUFACT m ON i.MANUCODE = m.code where i.ACTIVE ='T' "; // AND m.ACTIVE ='T'

                ds = ReturnDataSet(Query, sWhere, "items", Command.Connection);

                Console.WriteLine(ds.Tables.Count.ToString());

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new Product();

                        flag = "BASE";

                        tmpData.Company     = CurCompany;
                        tmpData.Name        = dr["DESCRIPT"].ToString();
                        tmpData.ProductCode = dr["ITEMNO"].ToString();
                        tmpData.Description = dr["DESCRIPT"].ToString();
                        tmpData.IsKit       = (dr["MATRIX_ITEM_TYPE"].ToString() == "3") ? true : false;

                        // CAA ????
                        tmpData.ErpTrackOpt  = IsTrackOpt(dr["FORCE_LOT"].ToString(), dr["SERIALIZE"].ToString());
                        tmpData.Manufacturer = dr["Manuf"].ToString();
                        // tmpData.Reference = dr["f120_rowid"].ToString();

                        /*
                         * try { tmpData.CountRank = ;
                         * catch { }
                         */

                        // ???   AVG_COST ???
                        try { tmpData.ProductCost = double.Parse(dr["COST"].ToString()); }
                        catch { }

                        tmpData.Status = active;
                        //tmpData.Status = GetProductStatus(int.Parse(dr["ITEMTYPE"].ToString()));

                        /*
                         * try { tmpData.Weight = double.Parse(dr["ITEMSHWT"].ToString()) / 100; }
                         * catch { }
                         * // ???
                         */

                        //Basic Unit
                        flag                 = "BASEUNIT";
                        curUnit              = new Unit();
                        curUnit.Company      = CurCompany;
                        curUnit.ErpCodeGroup = WmsSetupValues.DEFAULT;
                        curUnit.BaseAmount   = 1;
                        try
                        {
                            tmpData.BaseUnit = WType.GetUnit(curUnit);
                        }
                        catch { }
                        tmpData.IsFromErp  = true;
                        tmpData.PrintLabel = true;


                        //Product Category
                        if (!string.IsNullOrEmpty(dr["CATEGORY"].ToString()))
                        {
                            flag = "CATEGORY";
                            try
                            {
                                curCategory         = new ProductCategory();
                                curCategory.Company = CurCompany;
                                curCategory.ErpCode = dr["CATEGORY"].ToString();
                                tmpData.Category    = WType.GetProductCategory(curCategory);
                            }
                            catch { }
                        }

                        //Purchase Units
                        try
                        {
                            curUnit              = new Unit();
                            curUnit.Company      = CurCompany;
                            curUnit.ErpCodeGroup = WmsSetupValues.DEFAULT;
                            curUnit.ErpCode      = dr["PURCHUNIT"].ToString();
                            tmpData.PurchaseUnit = WType.GetUnit(curUnit);
                        }
                        catch { }


                        //Sale Unit
                        try
                        {
                            curUnit              = new Unit();
                            curUnit.Company      = CurCompany;
                            curUnit.ErpCodeGroup = WmsSetupValues.DEFAULT;
                            curUnit.ErpCode      = dr["SALEUNIT"].ToString();
                            tmpData.SaleUnit     = WType.GetUnit(curUnit);
                        }
                        catch { }

                        //Obteniendo las unidades que ese producto puede tener
                        flag    = "UNITLIST";
                        curList = unitList;  // .Where(unit => unit.ErpCodeGroup == dr["f120_id_unidad_inventario"].ToString()).ToList();

                        flag = "PRODUCT_TRACK";
                        tmpData.ProductTrack = GetProductTrack(tmpData.ErpTrackOpt, tmpData);

                        flag = "PRODUCT_UNITS";
                        tmpData.ProductUnits = GetProductUnits(tmpData, curList);

                        // CAA ??
                        flag = "VENDORS";
                        tmpData.ProductAccounts = GetProductVendors(tmpData);

                        // CAA ???
                        //Productos Alternos.

                        /*
                         * flag = "ALTERN";
                         * try
                         * {
                         *  tmpData.AlternProducts = GetAlternateProducts(tmpData);
                         * }
                         * catch (Exception ex) { Console.WriteLine(flag + " " + ex.Message); }
                         */

                        list.Add(tmpData);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(flag + " " + ex.Message);
                    }
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetProducts" + tmpData.ProductCode + "," + flag, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 9
0
        private IList <ProductAccountRelation> GetProductVendors(Product product)
        {
            IList <ProductAccountRelation> productVendor = new List <ProductAccountRelation>();
            ProductAccountRelation         curId         = null;
            AccountType accType = WType.GetAccountType(new AccountType {
                AccountTypeID = AccntType.Vendor
            });

            string curItemVendor = "";

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = "SELECT VEND_CODE,VENDOR_PART_NO " +
                        " FROM ITEM_REPLENISH_VENDOR WHERE ITEM_CODE = '" + product.ProductCode + "' ";

                ds = ReturnDataSet(Query, null, "ITEM_REPLENISH_VENDOR", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    curId = new ProductAccountRelation();

                    curId.ItemNumber = dr["VENDOR_PART_NO"].ToString();

                    //Si esta vacio se sale al proximo
                    if (string.IsNullOrEmpty(curId.ItemNumber))
                    {
                        continue;
                    }

                    curItemVendor = dr["VEND_CODE"].ToString() + ":" + curId.ItemNumber;

                    curId.IsFromErp   = true;
                    curId.AccountType = accType;
                    curId.Account     = WType.GetAccount(new Account {
                        AccountCode = dr["VEND_CODE"].ToString(), BaseType = new AccountType {
                            AccountTypeID = AccntType.Vendor
                        }
                    });
                    curId.Product      = product;
                    curId.CreatedBy    = WmsSetupValues.SystemUser;
                    curId.CreationDate = DateTime.Now;

                    productVendor.Add(curId);
                }


                return(productVendor);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetProductVendors:" + curItemVendor, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 10
0
        private IList <KitAssembly> GetKitAssembly(string sWhere)
        {
            //retorna la lista de Kits Headers

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = " select DISTINCT KIT_CODE from X_KIT WHERE DESC_TYPE=1 ";
                DataSet ds = ReturnDataSet(Query, sWhere, "X_KIT", Command.Connection);


                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                List <KitAssembly> list   = new List <KitAssembly>();
                Status             status = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });


                KitAssembly tmpData = null;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new KitAssembly();

                        tmpData.Product = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["KIT_CODE"].ToString()
                        });;
                        tmpData.Unit         = tmpData.Product.BaseUnit;
                        tmpData.AsmType      = 2;
                        tmpData.Status       = status;
                        tmpData.EfectiveDate = DateTime.Now;
                        tmpData.ObsoleteDate = DateTime.Now;
                        tmpData.IsFromErp    = true;

                        list.Add(tmpData);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            ExceptionMngr.WriteEvent("GetKitAssembly:" + tmpData.Product.ProductCode, ListValues.EventType.Error, ex, null,
                                                     ListValues.ErrorCategory.ErpConnection);
                        }
                        catch { }

                        //return null;
                    }
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetKitAssembly Connection", ListValues.EventType.Error, ex, null,
                                         ListValues.ErrorCategory.ErpConnection);

                return(null);
            }
        }
Ejemplo n.º 11
0
        public IList <KitAssemblyFormula> GetKitAssemblyFormula(string sWhere)
        {
            //retorna la lista de Formulas.

            KitAssemblyFormula tmpData = null;

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = "select KIT_CODE, ITEM_CODE, ITEM_QTY from X_KIT WHERE DESC_TYPE=1  ";
                DataSet ds = ReturnDataSet(Query, sWhere, "X_KIT", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }


                List <KitAssemblyFormula> list = new List <KitAssemblyFormula>();
                Status statusOK = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });
                Status statusInactive = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Inactive
                });

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new KitAssemblyFormula();

                        tmpData.KitAssembly = WType.GetKitAssembly(new KitAssembly {
                            Product = new Product {
                                Company = CurCompany, ProductCode = dr["KIT_CODE"].ToString()
                            }
                        });
                        tmpData.Status       = statusOK;
                        tmpData.EfectiveDate = DateTime.Now;
                        tmpData.ObsoleteDate = DateTime.Now;
                        tmpData.Component    = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["ITEM_CODE"].ToString()
                        });
                        tmpData.Unit          = tmpData.Component.BaseUnit;
                        tmpData.FormulaQty    = Double.Parse(dr["ITEM_QTY"].ToString());;
                        tmpData.Ord           = 1;
                        tmpData.ScrapPercent  = 0;
                        tmpData.DirectProduct = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["KIT_CODE"].ToString()
                        });

                        list.Add(tmpData);
                    }
                    catch (Exception ex)
                    {
                        ExceptionMngr.WriteEvent("GetKitAssemblyFormula:" + tmpData.KitAssembly.Product.ProductCode + ", " + tmpData.Component.ProductCode, ListValues.EventType.Error, ex, null,
                                                 ListValues.ErrorCategory.ErpConnection);

                        return(null);
                    }
                }


                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetKitAssemblyFormula:", ListValues.EventType.Error, ex, null,
                                         ListValues.ErrorCategory.ErpConnection);

                return(null);
            }
        }
        public IList <Document> GetReceivingDocuments(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
                 */

                //Console.WriteLine("Entramos");

                sWhere = string.IsNullOrEmpty(sWhere) ? " t420.f420_ind_estado IN (1,2,3,9) " : " t420.f420_ind_estado IN (1,2,3,9) AND " + sWhere;


                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = GetErpQuery("PURCHASEORDER");

                //Console.WriteLine(Query);

                DataSet ds = ReturnDataSet(Query, null, "PURCHASEORDER", Command.Connection);


                Console.WriteLine(ds.Tables.Count);

                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.PurchaseOrder
                });

                //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();
                //Location location = WType.GetDefaultLocation();


                //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["f420_fecha"].ToString());
                        //tmpData.Date2 = DateTime.Parse(dr["PRMDATE"].ToString());
                        //tmpData.Date3 = DateTime.Parse(dr["PRMSHPDTE"].ToString());
                        //tmpData.Date4 = DateTime.Parse(dr["REQDATE"].ToString());
                        //tmpData.Date5 = DateTime.Parse(dr["DUEDATE"].ToString()); //USADA PARA NOtification en IMAGE
                        tmpData.DocNumber       = dr["ponumber"].ToString();
                        tmpData.DocStatus       = GetReceivingStatus(int.Parse(dr["f420_ind_estado"].ToString()));
                        tmpData.DocType         = docType;
                        tmpData.PickMethod      = docType.PickMethod;
                        tmpData.DocConcept      = docConcept;
                        tmpData.QuoteNumber     = dr["f420_id_sucursal_prov"].ToString();
                        tmpData.Reference       = dr["f420_num_docto_referencia"].ToString();
                        tmpData.SalesPersonName = dr["id_comprador"].ToString();
                        tmpData.UserDef1        = dr["f420_id_moneda_docto"].ToString();


                        //try { tmpData.LastChange = DateTime.Parse(dr["f420_fecha_ts_actualizacion"].ToString()); }
                        //catch { }

                        tmpData.Comment = dr["f420_notas"].ToString();


                        tmpData.Vendor = WType.GetAccount(
                            new Account
                        {
                            AccountCode = dr["id_proveedor"].ToString(),
                            BaseType    = new AccountType {
                                AccountTypeID = AccntType.Vendor
                            },
                            Company = company
                        });     //Vendor Account;

                        tmpData.Customer  = defAccount;
                        tmpData.CreatedBy = dr["f420_usuario_creacion"].ToString();

                        //try { tmpData.ShippingMethod = WType.GetShippingMethod(new ShippingMethod { ErpCode = dr["SHIPMTHD"].ToString(), Company = company }); }
                        //catch { }

                        tmpData.IsFromErp    = true;
                        tmpData.CrossDocking = false;

                        //tmpData.Location = WType.GetLocation(new Location { ErpCode = dr["LOCNCODE"].ToString(), Company = company }); //location;
                        tmpData.Company = CurCompany;


                        //Asignacion de Lines
                        tmpData.DocumentLines = GetReceivingDocumentLines(tmpData, company, dr["f420_rowid"].ToString());


                        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("GetReceiptDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                    }
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetReceiptDocuments", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
        private IList <DocumentLine> GetReceivingDocumentLines(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 = "";

            try
            {
                Query = GetErpQuery("PURCHASEORDER_LINE").Replace("__DOCUMENT", docID);

                DataSet ds = ReturnDataSet(Query, null, "PURCHASEORDER_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["f421_fecha_entrega"].ToString()); }
                    catch { }

                    //tmpData.Date3 = DateTime.Parse(dr["PRMSHPDTE"].ToString());
                    //tmpData.Date4 = DateTime.Parse(dr["PRMDATE"].ToString());
                    tmpData.LineNumber  = int.Parse(dr["f421_rowid"].ToString());
                    tmpData.AccountItem = dr["f421_cod_item_prov"].ToString();
                    tmpData.Sequence    = tmpData.LineNumber;

                    curLine          = tmpData.LineNumber;
                    tmpData.Document = doc;
                    tmpData.IsDebit  = false;
                    tmpData.Quantity = double.Parse(dr["f421_cant_pedida"].ToString(), new NumberFormatInfo {
                        NumberDecimalSeparator = Separator
                    });
                    tmpData.UnitBaseFactor = double.Parse(dr["fact_adicional"].ToString(), new NumberFormatInfo {
                        NumberDecimalSeparator = Separator
                    });


                    tmpData.CreatedBy    = WmsSetupValues.SystemUser;
                    tmpData.CreationDate = DateTime.Now;

                    curMaster          = "Status:" + dr["f421_ind_estado"].ToString();
                    tmpData.LineStatus = GetReceivingStatus(int.Parse(dr["f421_ind_estado"].ToString())); //doc.DocStatus;

                    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["f421_id_unidad_medida"].ToString();
                        tmpData.Unit = WType.GetUnit(new Unit {
                            ErpCode = dr["f421_id_unidad_medida"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup
                        });
                    }
                    catch (Exception ex)
                    {
                        ExceptionMngr.WriteEvent("GetReceiptDocumentLines: " + 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() + ", " + dr["ITEMDESC"].ToString();

                        //    curMaster = "Uom:" + dr["UOFM"].ToString();
                        //    tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() });
                    }

                    //Unit - Price, Cost
                    tmpData.UnitPrice = double.Parse(dr["f421_precio_unitario"].ToString(), new NumberFormatInfo {
                        NumberDecimalSeparator = Separator
                    });
                    tmpData.ExtendedPrice = double.Parse(dr["subtotal"].ToString(), new NumberFormatInfo {
                        NumberDecimalSeparator = Separator
                    });

                    //SOP POP Link
                    //object[] sop_popLink = GetSOP_POPLink(doc.DocNumber, tmpData.LineNumber, doc.DocType.DocTypeID);
                    //if (sop_popLink != null)
                    //{
                    //    tmpData.LinkDocNumber = sop_popLink[0].ToString();
                    //    tmpData.LinkDocLineNumber = int.Parse(sop_popLink[1].ToString());
                    //}


                    list.Add(tmpData);
                }

                return((list.Count > 0) ? list : null);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetReceiptDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster,
                                         ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 14
0
        /// <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));
            }
        }
Ejemplo n.º 15
0
        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;
            }
        }
Ejemplo n.º 16
0
        private IList <Account> GetVendors(string sWhere)
        {
            IList <Account>     list = new List <Account>();
            Account             tmpData;
            AccountTypeRelation tmpAccTypeRel;

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = " select v.VEND_CODE, v.NAME, v.CONTCODE, IsNull(a.first_name+' '+a.last_name,a.name) as CONTNAME " +
                        " from VENDORS v LEFT OUTER JOIN ADDRESS a ON v.CONTCODE = a.ADDR_CODE WHERE v.ACTIVE ='T' ";

                ds = ReturnDataSet(Query, sWhere, "VENDORS", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }


                //Company company = WType.GetDefaultCompany();
                AccountType accType = WType.GetAccountType(new AccountType {
                    AccountTypeID = AccntType.Vendor
                });
                Status status = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //Map Properties
                    tmpData = new Account();

                    tmpData.AccountCode = dr["VEND_CODE"].ToString();
                    if (string.IsNullOrEmpty(tmpData.AccountCode))
                    {
                        continue;
                    }

                    tmpData.Company       = CurCompany;
                    tmpData.ContactPerson = dr["CONTNAME"].ToString();


                    tmpData.Name = dr["NAME"].ToString();
                    // tmpData.Phone = dr["PHNUMBR1"].ToString();
                    // tmpData.UserDefine1 = dr["f200_nit"].ToString();
                    // tmpData.UserDefine2 = dr["USERDEF2"].ToString();

                    //Account Type
                    tmpAccTypeRel              = new AccountTypeRelation();
                    tmpAccTypeRel.Account      = tmpData;
                    tmpAccTypeRel.AccountType  = accType;
                    tmpAccTypeRel.ErpCode      = dr["VEND_CODE"].ToString();
                    tmpAccTypeRel.Status       = status;
                    tmpAccTypeRel.CreationDate = DateTime.Now;
                    tmpAccTypeRel.CreatedBy    = WmsSetupValues.SystemUser;
                    tmpData.AccountTypes       = new AccountTypeRelation[] { tmpAccTypeRel };
                    tmpData.IsFromErp          = true;
                    tmpData.BaseType           = accType;

                    //Asignacion de Lines.... Datos del contacto del vendor (proveedor)
                    // caa ???  info de ADDRESS ?
                    // tmpData.AccountAddresses = GetVendorAddress(tmpData, dr["f200_rowid"].ToString());

                    list.Add(tmpData);
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetVendors", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 17
0
        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);
            }
        }
Ejemplo n.º 18
0
        private IList <Account> GetCustomers(string sWhere)
        {
            IList <Account>     list = new List <Account>();
            Account             tmpData;
            AccountTypeRelation tmpAccTypeRel;

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                // CAA ???  CUST ???
                Query = "select DISTINCT t.f200_rowid, t.f200_id, t.f200_nit, t.f200_razon_social, c.f015_contacto " +
                        " from dbo.t200_mm_terceros t JOIN t201_mm_clientes cli ON t.f200_rowid = cli.f201_rowid_tercero AND cli.f201_id_cia = " + CurCompany.ErpCode +
                        "   LEFT OUTER JOIN t015_mm_contactos c ON t.f200_rowid_contacto = c.f015_rowid " +
                        " WHERE t.f200_ind_cliente = 1 AND t.f200_id_cia=" + CurCompany.ErpCode + " AND c.f015_id_cia = " + CurCompany.ErpCode;

                ds = ReturnDataSet(Query, sWhere, "f200_ind_cliente", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                //Company company = WType.GetDefaultCompany();
                AccountType accType = WType.GetAccountType(new AccountType {
                    AccountTypeID = AccntType.Customer
                });
                Status status = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    //Map Properties
                    tmpData             = new Account();
                    tmpData.AccountCode = dr["f200_id"].ToString();

                    if (string.IsNullOrEmpty(tmpData.AccountCode))
                    {
                        continue;
                    }

                    tmpData.Company       = CurCompany;
                    tmpData.ContactPerson = dr["f015_contacto"].ToString();

                    tmpData.Name = dr["f200_razon_social"].ToString();
                    //tmpData.Phone = dr["PHONE1"].ToString();
                    tmpData.UserDefine1 = dr["f200_nit"].ToString();
                    //tmpData.UserDefine2 = dr["USERDEF2"].ToString();

                    //Account Type
                    tmpAccTypeRel              = new AccountTypeRelation();
                    tmpAccTypeRel.Account      = tmpData;
                    tmpAccTypeRel.AccountType  = accType;
                    tmpAccTypeRel.ErpCode      = dr["f200_rowid"].ToString();
                    tmpAccTypeRel.Status       = status;
                    tmpAccTypeRel.CreationDate = DateTime.Now;
                    tmpAccTypeRel.CreatedBy    = WmsSetupValues.SystemUser;
                    tmpData.AccountTypes       = new AccountTypeRelation[] { tmpAccTypeRel };
                    tmpData.IsFromErp          = true;
                    tmpData.BaseType           = accType;

                    //Asignacion de Lines
                    tmpData.AccountAddresses = GetCustomerAddress(tmpData, dr["f200_rowid"].ToString());

                    list.Add(tmpData);
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetCustomers", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 19
0
        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);
            }
        }
Ejemplo n.º 20
0
        private IList <AccountAddress> GetCustomerAddress(Account account, string personId)
        {
            AccountAddress         tmpData;
            IList <AccountAddress> list = new List <AccountAddress>();
            Status lineStatus           = WType.GetStatus(new Status {
                StatusID = EntityStatus.Active
            });

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                Query = "select cli.f201_id_sucursal, cli.f201_descripcion_sucursal, c.f015_direccion1, c.f015_direccion2, c.f015_direccion3, c.f015_telefono, " +
                        " c.f015_cod_postal, c.f015_email, p.f011_descripcion pais, d.f012_descripcion dpto, city.f013_descripcion city " +
                        "   from t201_mm_clientes cli JOIN dbo.t015_mm_contactos c ON cli.f201_rowid_contacto = c.f015_rowid " +
                        "     LEFT OUTER JOIN dbo.t011_mm_paises p ON c.f015_id_pais = p.f011_id " +
                        "     LEFT OUTER JOIN dbo.t012_mm_deptos d ON c.f015_id_depto = d.f012_id AND c.f015_id_pais = d.f012_id_pais " +
                        "     LEFT OUTER JOIN dbo.t013_mm_ciudades city ON c.f015_id_ciudad = city.f013_id AND c.f015_id_pais = city.f013_id_pais AND c.f015_id_depto = city.f013_id_depto " +
                        "   where cli.f201_rowid_tercero= " + personId + " AND cli.f201_id_cia = " + CurCompany.ErpCode + " AND c.f015_id_cia = " + CurCompany.ErpCode;

                ds = ReturnDataSet(Query, "", "t015_mm_contactos", Command.Connection);

                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    tmpData              = new AccountAddress();
                    tmpData.Account      = account;
                    tmpData.Name         = dr["f201_id_sucursal"].ToString();
                    tmpData.ErpCode      = dr["f201_id_sucursal"].ToString();
                    tmpData.AddressLine1 = dr["f015_direccion1"].ToString();
                    tmpData.AddressLine2 = dr["f015_direccion2"].ToString();
                    tmpData.AddressLine3 = dr["f015_direccion3"].ToString();
                    tmpData.City         = dr["city"].ToString();
                    tmpData.State        = dr["dpto"].ToString();
                    tmpData.ZipCode      = dr["f015_cod_postal"].ToString();
                    tmpData.Country      = dr["pais"].ToString();
                    tmpData.Phone1       = dr["f015_telefono"].ToString();
                    //tmpData.Phone2 = dr["PHNUMBR2"].ToString();
                    //tmpData.Phone3 = dr["FAXNUMBR"].ToString();
                    tmpData.Email         = dr["f015_email"].ToString();
                    tmpData.Status        = lineStatus;
                    tmpData.IsMain        = false;
                    tmpData.ContactPerson = account.ContactPerson;
                    tmpData.CreationDate  = DateTime.Now;
                    tmpData.CreatedBy     = WmsSetupValues.SystemUser;
                    tmpData.IsFromErp     = true;

                    list.Add(tmpData);
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetCustomerAddress", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 21
0
        private IList <Product> GetProducts(string sWhere)
        {
            Product         tmpData  = null;
            IList <Product> list     = new List <Product>();
            IList <Unit>    unitList = GetAllUnits();
            IList <Unit>    curList  = unitList;
            Unit            curUnit;
            ProductCategory curCategory;
            string          flag = "";


            try
            {
                //Lamar los documents que necesita del Erp usando econnect
                //sWhere = string.IsNullOrEmpty(sWhere) ? "ITEMTYPE=1" : "ITEMTYPE=1 AND " + sWhere;

                ds = DynamicsGP_ec.GetDataSet(DynamicsGP_ec.RetreiveData("Item", false, 2, 0, sWhere, true));

                Console.WriteLine(ds.Tables.Count.ToString());

                if (ds.Tables.Count == 0)
                {
                    return(list);
                }

                //Company company = WType.GetDefaultCompany();
                //Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active });

                //En el dataset, Tables: 1 - Item
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new Product();

                        flag = "BASE";

                        tmpData.Company     = CurCompany;
                        tmpData.Name        = dr["ITEMDESC"].ToString();
                        tmpData.ProductCode = dr["ITEMNMBR"].ToString();
                        tmpData.Description = dr["ITEMDESC"].ToString();
                        tmpData.IsKit       = (dr["ITEMTYPE"].ToString() == "4") ? true : false;
                        tmpData.ErpTrackOpt = short.Parse(dr["ITMTRKOP"].ToString());

                        tmpData.Manufacturer = dr["ITMSHNAM"].ToString();
                        tmpData.Reference    = dr["ITMGEDSC"].ToString();


                        try { tmpData.CountRank = short.Parse(dr["ABCCODE"].ToString()); }
                        catch { }

                        try { tmpData.ProductCost = double.Parse(dr["CURRCOST"].ToString()); }
                        catch { }

                        tmpData.Status = GetProductStatus(int.Parse(dr["ITEMTYPE"].ToString()));
                        try { tmpData.Weight = double.Parse(dr["ITEMSHWT"].ToString()) / 100; }
                        catch { }

                        //Basic Unit
                        flag                 = "BASEUNIT";
                        curUnit              = new Unit();
                        curUnit.Company      = CurCompany;
                        curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                        curUnit.BaseAmount   = 1;
                        tmpData.BaseUnit     = WType.GetUnit(curUnit);
                        tmpData.IsFromErp    = true;
                        tmpData.PrintLabel   = true;


                        //Product Category
                        if (!string.IsNullOrEmpty(dr["ITMCLSCD"].ToString()))
                        {
                            flag = "CATEGORY";
                            try
                            {
                                curCategory         = new ProductCategory();
                                curCategory.Company = CurCompany;
                                curCategory.ErpCode = dr["ITMCLSCD"].ToString();
                                tmpData.Category    = WType.GetProductCategory(curCategory);
                            }
                            catch { }
                        }

                        //Purchase Units
                        if (!string.IsNullOrEmpty(dr["PRCHSUOM"].ToString()))
                        {
                            try
                            {
                                curUnit              = new Unit();
                                curUnit.Company      = CurCompany;
                                curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                                curUnit.ErpCode      = dr["PRCHSUOM"].ToString();
                                tmpData.PurchaseUnit = WType.GetUnit(curUnit);
                            }
                            catch { }
                        }

                        //Sale Unit
                        if (!string.IsNullOrEmpty(dr["SELNGUOM"].ToString()))
                        {
                            try
                            {
                                curUnit              = new Unit();
                                curUnit.Company      = CurCompany;
                                curUnit.ErpCodeGroup = dr["UOMSCHDL"].ToString();
                                curUnit.ErpCode      = dr["SELNGUOM"].ToString();
                                tmpData.SaleUnit     = WType.GetUnit(curUnit);
                            }
                            catch { }
                        }

                        //Obteniendo las unidades que ese producto puede tener
                        flag    = "UNITLIST";
                        curList = unitList.Where(unit => unit.ErpCodeGroup == dr["UOMSCHDL"].ToString()).ToList();

                        flag = "PRODUCT_TRACK";
                        tmpData.ProductTrack = GetProductTrack(int.Parse(dr["ITMTRKOP"].ToString()), tmpData);

                        flag = "PRODUCT_UNITS";
                        tmpData.ProductUnits = GetProductUnits(tmpData, curList);

                        flag = "VENDORS";
                        tmpData.ProductAccounts = GetProductVendors(tmpData);

                        //Productos Alternos.
                        flag = "ALTERN";
                        try
                        {
                            tmpData.AlternProducts = GetAlternateProducts(tmpData, dr["ALTITEM1"].ToString().Trim(),
                                                                          dr["ALTITEM2"].ToString().Trim());
                        }
                        catch (Exception ex) { Console.WriteLine(flag + " " + ex.Message); }

                        list.Add(tmpData);
                    }
                    catch (Exception ex) {
                        Console.WriteLine(flag + " " + ex.Message);
                    }
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetProducts" + tmpData.ProductCode + "," + flag, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 22
0
        private IList <DocumentLine> GetReceivingDocumentLines(Document doc, Company company, DataRow[] dLines)
        {
            DocumentLine         tmpData;
            IList <DocumentLine> list = new List <DocumentLine>();
            //Status lineStatus = WType.GetStatus(new Status { StatusID = DocStatus.New });

            int    curLine   = 0;
            string curMaster = "";

            try
            {
                foreach (DataRow dr in dLines)
                {
                    tmpData       = new DocumentLine();
                    tmpData.Date1 = doc.Date1;
                    curMaster     = "";

                    tmpData.Date2       = DateTime.Parse(dr["REQDATE"].ToString());
                    tmpData.Date3       = DateTime.Parse(dr["PRMSHPDTE"].ToString());
                    tmpData.Date4       = DateTime.Parse(dr["PRMDATE"].ToString());
                    tmpData.LineNumber  = int.Parse(dr["ORD"].ToString());
                    tmpData.AccountItem = dr["VNDITNUM"].ToString();
                    tmpData.Sequence    = tmpData.LineNumber;

                    curLine              = tmpData.LineNumber;
                    tmpData.Document     = doc;
                    tmpData.IsDebit      = false;
                    tmpData.Quantity     = double.Parse(dr["QTYORDER"].ToString(), ListValues.DoubleFormat());
                    tmpData.QtyCancel    = double.Parse(dr["QTYCANCE"].ToString(), ListValues.DoubleFormat());
                    tmpData.QtyPending   = double.Parse(dr["QTYUNCMTBASE"].ToString(), ListValues.DoubleFormat());
                    tmpData.CreatedBy    = WmsSetupValues.SystemUser;
                    tmpData.CreationDate = DateTime.Now;

                    curMaster          = "Status:" + dr["POLNESTA"].ToString();
                    tmpData.LineStatus = GetReceivingStatus(int.Parse(dr["POLNESTA"].ToString())); //doc.DocStatus;
                    curMaster          = "Location:" + dr["LOCNCODE"].ToString();
                    tmpData.Location   = WType.GetLocation(new Location {
                        Company = company, ErpCode = dr["LOCNCODE"].ToString()
                    });

                    try
                    {
                        curMaster       = "Product:" + dr["ITEMNMBR"].ToString();
                        tmpData.Product = WType.GetProduct(new Product {
                            Company = company, ProductCode = dr["ITEMNMBR"].ToString()
                        });
                        tmpData.LineDescription = dr["ITEMDESC"].ToString();

                        curMaster    = "Uom:" + dr["UOFM"].ToString();
                        tmpData.Unit = WType.GetUnit(new Unit {
                            ErpCode = dr["UOFM"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup
                        });
                    }
                    catch (Exception ex)
                    {
                        ExceptionMngr.WriteEvent("GetReceiptDocumentLines: " + 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() + ", " + dr["ITEMDESC"].ToString();

                        //    curMaster = "Uom:" + dr["UOFM"].ToString();
                        //    tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() });
                    }

                    //Unit - Price, Cost
                    tmpData.UnitCost     = double.Parse(dr["UNITCOST"].ToString(), ListValues.DoubleFormat());
                    tmpData.ExtendedCost = double.Parse(dr["EXTDCOST"].ToString(), ListValues.DoubleFormat());

                    //SOP POP Link
                    object[] sop_popLink = GetSOP_POPLink(doc.DocNumber, tmpData.LineNumber, doc.DocType.DocTypeID);
                    if (sop_popLink != null)
                    {
                        tmpData.LinkDocNumber     = sop_popLink[0].ToString();
                        tmpData.LinkDocLineNumber = int.Parse(sop_popLink[1].ToString());
                    }


                    list.Add(tmpData);
                }

                return((list.Count > 0) ? list : null);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetReceiptDocumentLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster,
                                         ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
Ejemplo n.º 23
0
        private IList <KitAssembly> GetKitAssembly(string sWhere)
        {
            //retorna la lista de Kits Headers

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                // BM00101 - KitAssemblyHeader
                //DataSet ds = ReturnDataSet("SELECT * FROM BM00101 WHERE Bill_Status = 1 A", sWhere, "BM00101", Command.Connection);
                DataSet ds = ReturnDataSet("select b.* from BM00101 b LEFT OUTER JOIN SY03900 s ON s.NOTEINDX = b.NOTEINDX  WHERE CAST(ISNULL(TXTFIELD,'') AS VARCHAR(50)) <> 'NOTINWMS'", sWhere, "BM00101", Command.Connection);


                if (ds == null || ds.Tables.Count == 0)
                {
                    return(null);
                }

                List <KitAssembly> list   = new List <KitAssembly>();
                Status             status = WType.GetStatus(new Status {
                    StatusID = EntityStatus.Active
                });


                KitAssembly tmpData = null;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData = new KitAssembly();

                        tmpData.Product = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString()
                        });;
                        tmpData.Unit = WType.GetUnit(new Unit {
                            ErpCode = dr["UOFM"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup
                        });
                        tmpData.AsmType      = 2;
                        tmpData.Status       = status;
                        tmpData.EfectiveDate = DateTime.Parse(dr["Effective_Date"].ToString());
                        tmpData.ObsoleteDate = DateTime.Parse(dr["Obsolete_Date"].ToString());
                        tmpData.IsFromErp    = true;

                        list.Add(tmpData);
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            ExceptionMngr.WriteEvent("GetKitAssembly:" + tmpData.Product.ProductCode, ListValues.EventType.Error, ex, null,
                                                     ListValues.ErrorCategory.ErpConnection);
                        }
                        catch { }

                        //return null;
                    }
                }

                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetKitAssembly Connection", ListValues.EventType.Error, ex, null,
                                         ListValues.ErrorCategory.ErpConnection);

                return(null);
            }
        }
Ejemplo n.º 24
0
        public IList <Document> GetPurchaseReturns(string sWhere, int docType)
        {
            IList <Document> list     = new List <Document>();
            DocumentClass    docClass = new DocumentClass();
            Document         tmpData  = null;
            string           pos      = "0";

            try
            {
                //Lamar los documents que necesita del Erp usando econnect
                sWhere = string.IsNullOrEmpty(sWhere) ? "POPTYPE IN (7,6,5,4)" : "POPTYPE IN (7,6,5,4) AND " + sWhere;
                string xmlData = DynamicsGP_ec.RetreiveData("PO_Receiving_Transaction", false, 2, 0, sWhere, true);

                pos = "1";

                int rem = 0x02;
                xmlData = xmlData.Replace((char)rem, ' ');
                ds      = DynamicsGP_ec.GetDataSet(xmlData);

                pos = "2";


                Console.WriteLine("\t" + ds.Tables.Count);

                if (ds.Tables.Count == 0)
                {
                    return(null);
                }


                DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass {
                    DocClassID = SDocClass.Shipping
                });

                //Definiendo los tipos de documento de return
                DocumentType prtType = WType.GetDocumentType(new DocumentType {
                    DocTypeID = SDocType.PurchaseReturn
                });


                //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
                });


                //Console.WriteLine(ds.GetXml());

                //En el dataset, Tables: 1 - DocumentHeader, 2 - DocumentLine, 3 - DocumentComments
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData       = new Document();
                        tmpData.Date1 = DateTime.Parse(dr["receiptdate"].ToString());
                        tmpData.Date2 = DateTime.Parse(dr["DUEDATE"].ToString());


                        tmpData.DocNumber = dr["POPRCTNM"].ToString();
                        tmpData.DocStatus = GetShippingStatus(0);

                        //try
                        //{
                        //    tmpData.Comment = GetDocumentNotes(dr["NOTEINDX"].ToString(), dr["COMMNTID"].ToString());
                        //}
                        //catch { }

                        tmpData.CreatedBy    = dr["USER2ENT"].ToString();
                        tmpData.CustPONumber = dr["VNDDOCNM"].ToString();

                        tmpData.DocConcept = docConcept;

                        tmpData.Vendor = tmpData.Customer = WType.GetAccount(new Account
                        {
                            AccountCode = dr["VENDORID"].ToString(),
                            BaseType    = new AccountType {
                                AccountTypeID = AccntType.Vendor
                            },
                            Company = company
                        });

                        //Console.WriteLine("1");

                        try
                        {
                            if (!string.IsNullOrEmpty(dr["SHIPMTHD"].ToString()))
                            {
                                tmpData.ShippingMethod = WType.GetShippingMethod(
                                    new ShippingMethod {
                                    ErpCode = dr["SHIPMTHD"].ToString(), Company = company
                                });
                            }
                        }
                        catch { }
                        //tmpData.User = user;

                        tmpData.IsFromErp    = true;
                        tmpData.CrossDocking = false;

                        tmpData.Company = CurCompany;

                        tmpData.Reference = dr["REFRENCE"].ToString();
                        tmpData.Notes     = dr["BACHNUMB"].ToString();

                        //Console.WriteLine("2");

                        //Asignacion de Address
                        //tmpData.DocumentAddresses = GetPurchaseReturnsAddress(tmpData, null, dr);

                        DocumentAddress billAddress = null;
                        try { billAddress = GetBillAddress(tmpData, "", dr["VENDORID"].ToString(), AccntType.Vendor); }
                        catch { }

                        tmpData.DocumentAddresses = new List <DocumentAddress>();

                        if (billAddress != null)
                        {
                            tmpData.DocumentAddresses.Add(billAddress);
                        }


                        tmpData.DocType = prtType;
                        try { tmpData.PickMethod = prtType.PickMethod; }
                        catch { }

                        //Console.WriteLine("3");

                        //Asignacion de Lines - Seguen el tipo de orden
                        tmpData.DocumentLines = GetPurchaseReturnsLines(tmpData, ds.Tables[2].Select("POPRCTNM='" + dr["POPRCTNM"].ToString() + "'"),
                                                                        ds.Tables[3]);


                        //Console.WriteLine("4");

                        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("GetPurchaseReturns: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                    }
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetPurchaseReturns:" + pos + ":", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
        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));
            }
        }
Ejemplo n.º 26
0
        private IList <DocumentLine> GetPurchaseReturnsLines(Document doc, DataRow[] dLines, DataTable dtQty)
        {
            DocumentLine         tmpData;
            IList <DocumentLine> list = new List <DocumentLine>();
            Status lineStatus         = WType.GetStatus(new Status {
                StatusID = DocStatus.New
            });


            int    curLine   = 0;
            string curMaster = "";

            DataRow[] qtyReceipt;

            try
            {
                foreach (DataRow dr in dLines)
                {
                    tmpData       = new DocumentLine();
                    tmpData.Date1 = doc.Date1;
                    curMaster     = "";


                    tmpData.LineNumber = int.Parse(dr["RCPTLNNM"].ToString());
                    tmpData.Sequence   = tmpData.LineNumber;
                    curLine            = tmpData.LineNumber;

                    try
                    {
                        qtyReceipt = dtQty.Select("RCPTLNNM = '" + dr["RCPTLNNM"].ToString() + "' AND POPRCTNM='" + dr["POPRCTNM"].ToString() + "'");

                        //Console.WriteLine("RCPTLNNM = " + dr["RCPTLNNM"].ToString() + " AND POPRCTNM='" + dr["POPRCTNM"].ToString() + "'" + qtyReceipt.Length.ToString());

                        tmpData.Quantity = double.Parse(qtyReceipt[0]["QTYRESERVED"].ToString(), ListValues.DoubleFormat());
                    }
                    catch (Exception ez) {
                        ExceptionMngr.WriteEvent("QTYRESERVED: " + dr["POPRCTNM"].ToString() + "," + dr["RCPTLNNM"].ToString(),
                                                 ListValues.EventType.Error, ez, null, ListValues.ErrorCategory.ErpConnection);

                        tmpData.Quantity = 0;
                    }


                    //TODO: Revisar el Status en GP para traer el equivalente
                    tmpData.LineStatus   = GetShippingStatus(0);
                    tmpData.Document     = doc;
                    tmpData.IsDebit      = false;
                    tmpData.CreatedBy    = WmsSetupValues.SystemUser;
                    tmpData.CreationDate = DateTime.Now;

                    curMaster        = "Location:" + dr["LOCNCODE"].ToString();
                    tmpData.Location = WType.GetLocation(new Location {
                        Company = CurCompany, ErpCode = dr["LOCNCODE"].ToString()
                    });

                    try
                    {
                        curMaster       = "Product:" + dr["ITEMNMBR"].ToString();
                        tmpData.Product = WType.GetProduct(new Product {
                            Company = CurCompany, ProductCode = dr["ITEMNMBR"].ToString()
                        });;
                        tmpData.LineDescription = dr["ITEMDESC"].ToString();

                        curMaster    = "Uom:" + dr["UOFM"].ToString();
                        tmpData.Unit = WType.GetUnit(new Unit {
                            ErpCode = dr["UOFM"].ToString(), ErpCodeGroup = tmpData.Product.BaseUnit.ErpCodeGroup
                        });
                    }
                    catch (Exception ex)
                    {
                        ExceptionMngr.WriteEvent("GetPurchaseReturnsLines: " + 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 = "Uom:" + dr["UOFM"].ToString();
                        //    tmpData.Unit = WType.GetUnit(new Unit { ErpCode = dr["UOFM"].ToString() });
                    }



                    //Manage Prices
                    tmpData.UnitPrice     = double.Parse(dr["UNITCOST"].ToString(), ListValues.DoubleFormat());
                    tmpData.ExtendedPrice = double.Parse(dr["EXTDCOST"].ToString(), ListValues.DoubleFormat());

                    //Asignacion de Address
                    //tmpData.DocumentLineAddresses = GetShippingDocumentAddress(tmpData.Document, tmpData, dr);

                    list.Add(tmpData);
                }

                return((list.Count > 0) ? list : null);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetPurchaseReturnsLines: " + doc.DocNumber + "," + curLine.ToString() + "," + curMaster,
                                         ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
        //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;
            }
        }
Ejemplo n.º 28
0
        public IList <Document> GetReceivingDocuments(string sWhere)
        {
            IList <Document> list     = new List <Document>();
            DocumentClass    docClass = new DocumentClass();
            Document         tmpData  = null;

            try
            {
                sWhere = string.IsNullOrEmpty(sWhere) ? "POSTATUS IN (1,2,3,4,5,6)" : "POSTATUS IN (1,2,3,4,5,6) AND " + sWhere;
                //Lamar los documents que necesita del Erp usando econnect
                ds = DynamicsGP_ec.GetDataSet(DynamicsGP_ec.RetreiveData("Purchase_Order_Transaction", false, 2, 0, sWhere, true));

                if (ds.Tables.Count == 0)
                {
                    return(null);
                }

                DocumentConcept docConcept = WType.GetDefaultConcept(new DocumentClass {
                    DocClassID = SDocClass.Receiving
                });
                DocumentType docType = WType.GetDocumentType(new DocumentType {
                    DocTypeID = SDocType.PurchaseOrder
                });

                //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();
                //Location location = WType.GetDefaultLocation();


                //En el dataset, Tables: 1 - DocumentHeader, 2 - DocumentLine, 3 - DocumentComments
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    try
                    {
                        //Map Properties
                        tmpData       = new Document();
                        tmpData.Date1 = DateTime.Parse(dr["DOCDATE"].ToString());
                        tmpData.Date2 = DateTime.Parse(dr["PRMDATE"].ToString());
                        tmpData.Date3 = DateTime.Parse(dr["PRMSHPDTE"].ToString());
                        tmpData.Date4 = DateTime.Parse(dr["REQDATE"].ToString());
                        //tmpData.Date5 = DateTime.Parse(dr["DUEDATE"].ToString()); //USADA PARA NOtification en IMAGE
                        tmpData.DocNumber  = dr["PONUMBER"].ToString();
                        tmpData.DocStatus  = GetReceivingStatus(int.Parse(dr["POSTATUS"].ToString()));
                        tmpData.DocType    = docType;
                        tmpData.PickMethod = docType.PickMethod;
                        tmpData.DocConcept = docConcept;
                        try { tmpData.CustPONumber = dr["POPCONTNUM"].ToString(); }
                        catch { }


                        tmpData.LastChange = GetDocumentLastChange("POP10100", "PONUMBER", dr["PONUMBER"].ToString());

                        try
                        {
                            tmpData.Comment = GetDocumentNotesPurchase("", dr["COMMNTID"].ToString(), dr["PONUMBER"].ToString());
                        }
                        catch { }



                        tmpData.Vendor = WType.GetAccount(
                            new Account
                        {
                            AccountCode = dr["VENDORID"].ToString(),
                            BaseType    = new AccountType {
                                AccountTypeID = AccntType.Vendor
                            },
                            Company = company
                        });     //Vendor Account;

                        tmpData.Customer  = defAccount;
                        tmpData.CreatedBy = dr["USER2ENT"].ToString();
                        try { tmpData.ShippingMethod = WType.GetShippingMethod(new ShippingMethod {
                                ErpCode = dr["SHIPMTHD"].ToString(), Company = company
                            }); }
                        catch { }

                        tmpData.IsFromErp    = true;
                        tmpData.CrossDocking = false;

                        //tmpData.Location = WType.GetLocation(new Location { ErpCode = dr["LOCNCODE"].ToString(), Company = company }); //location;
                        tmpData.Company = CurCompany;


                        //Asignacion de Lines
                        tmpData.DocumentLines = GetReceivingDocumentLines(tmpData, company,
                                                                          ds.Tables[2].Select("PONUMBER='" + dr["PONUMBER"].ToString() + "'"));


                        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("GetReceiptDocuments: " + tmpData.DocNumber, ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                    }
                }

                //retornar la lista
                return(list);
            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("GetReceiptDocuments", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                //throw;
                return(null);
            }
        }
        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;
                }
            }
        }
Ejemplo n.º 30
0
        public void PickAtOnce(Document document, Label sourceLocation, Node node, SysUser picker)
        {
            Factory.IsTransactional = true;
            //Node node = WType.GetNode(new Node { NodeID = NodeType.Picked });

            DocumentBalance docBal = new DocumentBalance
            {
                Document = document,
                Node     = node
            };

            IList <DocumentBalance> balanceList = Factory.DaoDocumentBalance().BalanceByUnit(docBal);

            //Recorre las lineas del documento y las pickea usando PickProduct, pero solo si el balance
            //existe en la location indicada para todo lo pendiente.

            if (balanceList == null || balanceList.Count == 0)
            {
                throw new Exception("Document " + document.DocNumber + " not contains product pending to pick.");
            }


            DocumentLine curLine;
            string       fullExistence = "";

            foreach (DocumentBalance line in balanceList.Where(f => f.QtyPending > 0))
            {
                //Define Document, Product, Unit and Qty to send to receiving transaction
                curLine = new DocumentLine
                {
                    Document  = document,
                    Product   = line.Product,
                    Unit      = line.Unit,
                    Quantity  = line.QtyPending,
                    CreatedBy = picker.UserName
                };

                fullExistence += CheckForStockInLocation(curLine, sourceLocation);
            }


            //Si alguno no tiene existencia no puede ejecutar el PickAtOnce
            if (!string.IsNullOrEmpty(fullExistence))
            {
                ExceptionMngr.WriteEvent("PickAtOnce:", ListValues.EventType.Error, null, null, ListValues.ErrorCategory.Business);
                throw new Exception(fullExistence);
            }


            //Ejecutando el Picking despues de que se confirma la existencia
            foreach (DocumentBalance line in balanceList)
            {
                //Define Document, Product, Unit and Qty to send to receiving transaction
                curLine = new DocumentLine
                {
                    Document = document,
                    Product  = line.Product,
                    Unit     = line.Unit,
                    Quantity = line.QtyPending
                };

                Label packageLabel = new Label {
                    LabelID = -1
                };
                PickProduct(curLine, sourceLocation, node, packageLabel, picker, null);
            }
        }