Exemple #1
0
        public DocumentTypeSequence GetNextDocSequence(Company company, DocumentType docType)
        {

            //crea el objeto de DocumentTypeSequence
            DocumentTypeSequence docSeq = new DocumentTypeSequence();
            docSeq.Company = company;
            docSeq.DocType = docType;

            //Solicita el Consecutivo para el documento
            docSeq = Factory.DaoDocumentTypeSequence().Select(docSeq).First();


            //Check Label Sequence 
            if (docType.DocTypeID == LabelType.ProductLabel)
            {
                long labelSeq = Factory.DaoLabel().SelectSequence();
                if (labelSeq > docSeq.NumSequence)
                    docSeq.NumSequence = labelSeq;
            }




            //Aumenta el consecutivo en Uno y lo guarda
            docSeq.NumSequence++;
            Factory.DaoDocumentTypeSequence().Update(docSeq);

            return docSeq;

        }
        public IList<DocumentType> Select(DocumentType data)
        {
            IList<DocumentType> datos = new List<DocumentType>();

            datos = GetHsql(data).List<DocumentType>();
            if (!Factory.IsTransactional)
                Factory.Commit();
            return datos;

        }
 public DocumentType SelectById(DocumentType data)
 {
     return (DocumentType)base.SelectById(data);
 }
 public Boolean Delete(DocumentType data)
 {
     return base.Delete(data);
 }
 public Boolean Update(DocumentType data)
 {
     return base.Update(data);
 }
        private void UpdatePostedReceipts()
        {
            Status posted = WType.GetStatus(new Status { StatusID = DocStatus.Posted });
            DocumentType docType = new DocumentType { DocTypeID = SDocType.PurchaseReceipt };

            Document document; //for the foreach
            Document pattern = new Document { DocType = docType, DocStatus = new Status { StatusID = DocStatus.Completed } };

            //Obtiene la lista de los pendientes
            IList<Document> unPostedList = Factory.DaoDocument().Select(pattern);

            foreach (Document curDocument in unPostedList)
            {
                try
                {
                    //Obtiene si esta posteado o no
                    document = ErpFactory.Documents().GetReceiptPostedStatus(curDocument);

                    if (document != null)
                    {
                        document.DocStatus = posted;
                        Factory.DaoDocument().Update(document);
                    }
                }
                catch (Exception ex) {
                    ExceptionMngr.WriteEvent("UpdatePostedReceipts:Doc#" + curDocument.DocNumber, ListValues.EventType.Fatal, ex, null, 
                        ListValues.ErrorCategory.Business);
                }
            }
        }
Exemple #7
0
 public DocumentTypeSequence GetNextDocSequence(Company company, DocumentType docType)
 {
     return BasicMngr.GetNextDocSequence(company, docType);
 }
Exemple #8
0
 public void UpdateDocumentType(DocumentType data) { Factory.DaoDocumentType().Update(data); }
Exemple #9
0
 public IList<DocumentType> GetDocumentType(DocumentType data) { return Factory.DaoDocumentType().Select(data); }
        //Mueve cantidades de un package a otro
        public void MoveQtyBetweenPackages(DocumentPackage curPack, DocumentPackage newPack, 
            Product product, double qty)
        {

            Factory.IsTransactional = true;

            Unit baseUnit = product.BaseUnit;

            try
            {

                DocumentLine line = new DocumentLine
                {
                    Quantity = qty,
                    Product = product,
                    Unit = baseUnit,
                    CreatedBy = newPack.CreatedBy
                };

                #region remove from OLD package
                //#########################################################################
                //Remover la cantidad del paquete origen
                //Saca las cantidades para es BIN y de ese producto.
                IList<Label> labelList = GetPackageLabels(curPack.PackLabel, line);

                Label sourceLabel = null;

                if (labelList.Sum(f => f.BaseCurrQty) < line.Quantity * line.Unit.BaseAmount)
                {
                    Factory.Rollback();
                    throw new Exception("No quantity available for the transaction.");
                }


                //Recorre los labels hasta que termine el saldo y se salga.
                double qtyBalance = line.Quantity * line.Unit.BaseAmount;
                double curQty;
                foreach (Label label in labelList)
                {

                    if (qtyBalance <= 0)
                        break;

                    label.CurrQty = label.BaseCurrQty;
                    label.StartQty = label.BaseStartQty;
                    label.Unit = baseUnit;

                    //Cantidad a Disminuir
                    curQty = qtyBalance > label.CurrQty ? label.CurrQty : qtyBalance;

                    qtyBalance -= curQty;
                   
                    label.CurrQty -= curQty;
                    label.ModDate = DateTime.Now;
                    label.ModifiedBy = line.CreatedBy;
                    Factory.DaoLabel().Update(label);
                    sourceLabel = label;

                }

                #endregion

                #region add to NEW package
                //#########################################################################
                //Adicionar la cantidad al paquete destino
                Label tmpLabel = null;
                Status statusLock = WType.GetStatus(new Status { StatusID = EntityStatus.Locked }); //Active

                DocumentType lblType = new DocumentType { DocTypeID = LabelType.ProductLabel };
                //DocumentTypeSequence initSequence = DocMngr.GetNextDocSequence(curPack.Document.Company, lblType); //Funcion para obtener siguiente Label


                //Salvar con el nuevo status
                tmpLabel = new Label();

                //To Send
                Node node = WType.GetNode(new Node { NodeID = NodeType.Released });
                tmpLabel.Node = curPack.PackLabel.Node;

                tmpLabel.Bin = curPack.PackLabel.Bin;
                tmpLabel.CurrQty = line.Quantity;
                tmpLabel.Product = line.Product;
                tmpLabel.StartQty = line.Quantity;
                tmpLabel.Unit = line.Product.BaseUnit;
                tmpLabel.CreatedBy = line.CreatedBy;

                tmpLabel.Status = statusLock;
                tmpLabel.LabelType = lblType;
                tmpLabel.LabelCode = ""; // initSequence.NumSequence.ToString() + GetRandomHex(line.CreatedBy, initSequence.NumSequence);

                tmpLabel.Printed = false;
                tmpLabel.CreationDate = DateTime.Now;
                tmpLabel.IsLogistic = false;
                tmpLabel.ShippingDocument = curPack.Document;
                tmpLabel.LabelSource = sourceLabel;

                tmpLabel.FatherLabel = newPack.PackLabel;
                tmpLabel = Factory.DaoLabel().Save(tmpLabel);


                #endregion

                Factory.Commit();

            }
            catch  {
                Factory.Rollback();
                throw;
            }
        }
        private void UpdatePostedAssemblyOrders()
        {
            Status posted = WType.GetStatus(new Status { StatusID = DocStatus.Posted });
            DocumentType docType = new DocumentType { DocTypeID = SDocType.KitAssemblyTask };

            Document document; //for the foreach
            Document pattern = new Document
            {
                DocType = docType,
                DocStatus = new Status { StatusID = DocStatus.Completed }
            };

            //Obtiene la lista de los pendientes
            IList<Document> unPostedList = Factory.DaoDocument().Select(pattern);

            foreach (Document curDocument in unPostedList)
            {
                try
                {
                    //Obtiene si esta posteado o no
                    document = ErpFactory.Documents().GetAssemblyOrderPostedStatus(curDocument);

                    if (document != null)
                    {
                        document.DocStatus = posted;
                        Factory.DaoDocument().Update(document);
                    }
                }
                catch { }
            }


           pattern = new Document
            {
                DocType = docType,
                DocStatus = new Status { StatusID = DocStatus.New }
            };


            //Lista de Ordenes nuevos que hay que revisar si se eliminaron
           IList<Document> newList = Factory.DaoDocument().Select(pattern);
           Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled });

           foreach (Document curDocument in newList)
           {
               try
               {
                   if (ErpFactory.Documents().AssemblyOrderWasDeleted(curDocument))
                   {
                       curDocument.DocStatus = cancelled;
                       Factory.DaoDocument().Update(curDocument);
                   }
               }
               catch { }
           }


        }
        private void UpdateInventoryAdjustments()
        {
            Status posted = WType.GetStatus(new Status { StatusID = DocStatus.Posted });
            DocumentType docType = new DocumentType { DocTypeID = SDocType.InventoryAdjustment };

            Document document; //for the foreach
            Document pattern = new Document { DocType = docType, DocStatus = new Status { StatusID = DocStatus.Completed } };

            //Obtiene la lista de los pendientes
            IList<Document> unPostedList = Factory.DaoDocument().Select(pattern);

            foreach (Document curDocument in unPostedList)
            {
                try
                {
                    //Obtiene si esta posteado o no
                    document = ErpFactory.Documents().GetAdjustmentPostedStatus(curDocument);

                    if (document != null)
                    {
                        document.DocStatus = posted;
                        Factory.DaoDocument().Update(document);
                    }
                }
                catch { }
            }
        }
        private void UpdatePostedInvoices()
        {
            Status completed = WType.GetStatus(new Status { StatusID = DocStatus.Completed });
            DocumentType docType = new DocumentType { DocTypeID = SDocType.SalesShipment };

            Document document; //for the foreach
            Document pattern = new Document { DocType = docType, DocStatus = new Status { StatusID = DocStatus.InProcess } };

            //Obtiene la lista de los pendientes
            IList<Document> unPostedList = Factory.DaoDocument().Select(pattern);

            foreach (Document curDocument in unPostedList)
            {
                try
                {
                    //Obtiene si esta posteado o no la factura relacionada a ese shipment
                    document = null; // ErpFactory.Documents().GetReceiptPostedStatus(curDocument); //Cambiar a Invoice

                    if (document != null)
                    {
                        document.DocStatus = completed;
                        Factory.DaoDocument().Update(document);
                    }
                }
                catch { }
            }
        }
        private void FulfillCrossDockSalesDocuments()
        {
            //Este proceso aplica solo cuando hay conexion con el ERP hace lo siguiente:
            //1. Recorre los documentos de cross dock en status New.
            //2. Revisa que el Purchase Receipt Created no haya sido cancelado
            //3. Hace el fullfill de las cantidades en el ERP.

            Status completed = WType.GetStatus(new Status { StatusID = DocStatus.Completed });
            DocumentType docType = new DocumentType { DocTypeID = SDocType.CrossDock };

            Document pattern = new Document { DocType = docType, 
                DocStatus = new Status { StatusID = DocStatus.New } };

            //Obtiene la lista de los pendientes
            IList<Document> unPostedList = Factory.DaoDocument().Select(pattern);

            //1. Recorre los documentos de cross dock en status New.
            foreach (Document curDocument in unPostedList)
            {
                //Check if receipt was posted.
                if (!curDocument.TaskDocuments.Select(f => f.IncludedDoc).Where(f => f.DocType.DocTypeID == SDocType.PurchaseReceipt)
                    .Any(f => f.DocStatus.StatusID == DocStatus.Posted))
                    continue;

                //COmentado en Oct 09 /2009
                //Si el documento PR asociado no ha sido completado (posteado) va la siguiente
                //if (curDocument.TaskDocuments.Select(f => f.IncludedDoc)
                //    .Where(f => f.DocType.DocTypeID == SDocType.PurchaseReceipt).First()
                //    .DocStatus.StatusID != DocStatus.Posted)
                //    continue;

                try
                {
                    //3. Hace el fullfill de las cantidades en el ERP para cada documento relacionado
                    foreach (Document shDocument in curDocument.TaskDocuments.Select(f => f.IncludedDoc)
                    .Distinct().Where(f => f.DocType.DocClass.DocClassID == SDocClass.Shipping))
                    {
                        try { 
                            CreateShipmentDocument(shDocument); 
                        }

                        catch (Exception ex)
                        {
                            ExceptionMngr.WriteEvent("CrossDock:CreateShipmentDocument: " + curDocument.DocNumber, ListValues.EventType.Fatal,
                                ex, null, ListValues.ErrorCategory.Business);
                        }
                    }

                    curDocument.DocStatus = completed;
                    Factory.DaoDocument().Update(curDocument);

                }
                catch (Exception ex) {

                    ExceptionMngr.WriteEvent("FulfillCrossDockSalesDocuments: " + curDocument.DocNumber, ListValues.EventType.Fatal, 
                        ex, null, ListValues.ErrorCategory.Business);
                }
            }

        }
/*
        private void DeleteNodeTrace(Label packLabel)
        {
            IList<NodeTrace> traceList = Factory.DaoNodeTrace().Select(new NodeTrace { Label = packLabel });

            foreach (NodeTrace nTrace in traceList)
                Factory.DaoNodeTrace().Delete(nTrace);
        }
        */



        private string CreateWareHouseTransferReceiptOrder(Document ssDocument, Location destLocation)
        {

            DocumentTypeSequence docSeq = null;

            //1. Create the Document Head
            DocumentType docType = new DocumentType { DocTypeID = SDocType.WarehouseTransferReceipt };
            docSeq = GetNextDocSequence(ssDocument.Company, docType);

            Document whTranferDoc = new Document
            {
                DocNumber = docSeq.CodeSequence,
                DocType = docType,
                Location = destLocation,
                IsFromErp = false,
                CrossDocking = false,
                Customer = ssDocument.Customer,
                Reference = ssDocument.CustPONumber,
                Date1 = DateTime.Now,
                CustPONumber = ssDocument.DocNumber,
                CreatedBy = ssDocument.CreatedBy,
                Company = ssDocument.Company,
                Comment = "Warehose Receipt for Doc# " + ssDocument.CustPONumber + ", Ship# " + ssDocument.DocNumber

            };
            whTranferDoc = DocMngr.CreateNewDocument(whTranferDoc, false);


            //2. Create Document Lines (Idem to Shipment but changing Warehouse)
            IList<DocumentLine> docLines = new List<DocumentLine>();
            DocumentLine transferLine;
            foreach (DocumentLine dl in ssDocument.DocumentLines)
            {
                transferLine = new DocumentLine
                {
                    Document = whTranferDoc,
                    LineNumber = dl.LineNumber,
                    LineStatus = dl.LineStatus,
                    Product = dl.Product,
                    IsDebit = dl.IsDebit,
                    Quantity = dl.Quantity,
                    Unit = dl.Unit,
                    UnitBaseFactor = dl.UnitBaseFactor,
                    Date1 = dl.Date1,
                    Date2 = DateTime.Now,
                    CreatedBy = ssDocument.CreatedBy,
                    CreationDate = DateTime.Now,
                    Location = destLocation, //Location DEST
                    Location2 = ssDocument.Location, //Location FROM,
                    UnitCost = dl.UnitCost,
                    ExtendedCost = dl.ExtendedCost
                };
                docLines.Add(transferLine);
            }


            whTranferDoc.DocumentLines = docLines;

            //Salvando el Docuemnto
            Factory.DaoDocument().Save(whTranferDoc);
            return " Receipt Transfer Doc# " + whTranferDoc.DocNumber;

        }
        public Document CreateShipmentDocument(Document shipTask)
        {
            

            //Revisa si se debe enviar el recibo al ERP, es decir si esta en true la opcion de conexion a ERP
            bool ErpConnected = GetCompanyOption(shipTask.Company, "WITHERPSH").Equals("T");
            bool existsPreviowsShipment = false;
            Status inactive = WType.GetStatus(new Status { StatusID = EntityStatus.Inactive });

            //Valida que la conexion al ERP exista
            if (ErpConnected)
            {
                if (shipTask.Company.ErpConnection == null)
                    throw new Exception("Please setup Erp Connection.");

                SetConnectMngr(shipTask.Company);
            }


            string docNumberSeq = null;
            Document ssDocument = null;
            //Obtiene los Nodetrace a procesar y Arma las lineas segun los nodetrace
            IList<NodeTrace> traceList  = null;
            Connection curConnection;
          

            DocumentType docType = new DocumentType { DocTypeID = SDocType.SalesShipment };
            bool fistTimeFulfill = true;

            //ADICION Marzo 9 de 2010 //Si la variable ONESHIP = 'T' debe utilizar el mismo Shipment
            //si ya existe y no crear uno nuevo 
            try
            {
                if (GetCompanyOption(shipTask.Company, "ONESHIPMENT").Equals("T"))
                {
                    ssDocument = Factory.DaoDocument().Select(new Document
                    {
                        Company = shipTask.Company,
                        CustPONumber = shipTask.DocNumber,
                        DocStatus = new Status { StatusID = DocStatus.Completed }
                    }).First();

                    existsPreviowsShipment = true;
                }
            }
            catch { };


            if (ssDocument == null)
            {
                //Se obtinen el numero de fullfill documents para este sales docuemnt.
                //Porque si es primera vez el tratameinto es diferente.
                try
                {
                    fistTimeFulfill = Factory.DaoDocument().Select(new Document
                    {
                        DocType = docType,
                        CustPONumber = shipTask.DocNumber,
                        Company = shipTask.Company,
                        DocStatus = new Status { StatusID = DocStatus.Completed }
                    }).Count > 0 ? false : true;
                }
                catch { fistTimeFulfill = false; }


                //Tipo de docuemnto Sales Shipment, en que legaliza el piqeuo y salida de la mercancia
                if (string.IsNullOrEmpty(shipTask.PostingDocument))
                    docNumberSeq = GetNextDocSequence(shipTask.Company, docType).CodeSequence;
                else
                    docNumberSeq = shipTask.PostingDocument; //21 SEP Cuando ya el shipment tiene numero preasignado.
            }


            //Refresh Document Lines
            shipTask.DocumentLines = Factory.DaoDocumentLine().Select(
                new DocumentLine { Document = new Document { DocID = shipTask.DocID } });


            Factory.IsTransactional = true;

            try
            {
               

                #region Doc Creation

                if (ssDocument == null)
                {
                    //Crear Document header
                    ssDocument = new Document
                    {
                        DocNumber = docNumberSeq, //docSeq.CodeSequence,
                        Location = shipTask.Location,
                        DocType = docType,
                        IsFromErp = false,
                        CrossDocking = false,
                        Customer = shipTask.Customer,
                        Reference = shipTask.Reference,
                        Date1 = DateTime.Now,
                        CustPONumber = shipTask.DocNumber,
                        CreatedBy = shipTask.ModifiedBy,
                        Company = shipTask.Company,
                        Comment = "Shipment for Doc# " + shipTask.DocNumber,
                        UseAllocation = shipTask.UseAllocation,
                        Date3 = shipTask.Date3,
                        Date4 = shipTask.Date4,
                        QuoteNumber = shipTask.CustPONumber,
                        Notes = shipTask.Notes,
                        UserDef1 = shipTask.UserDef1,
                        UserDef2 = shipTask.UserDef2,
                        UserDef3 = shipTask.UserDef3

                    };
                    DocMngr.CreateNewDocument(ssDocument, false);

                }
                else if (existsPreviowsShipment)
                {
                    Status cancelled = WType.GetStatus(new Status { StatusID = DocStatus.Cancelled });                    
                    Status active = WType.GetStatus(new Status { StatusID = EntityStatus.Active });
                    Node voidNode = WType.GetNode(new Node { NodeID = NodeType.Voided });

                    //Remueve todo los datos de informacion de posteo de los labels
                    //para hacer Repost
                    IList<NodeTrace> nodeShipment = Factory.DaoNodeTrace().Select(new NodeTrace { PostingDocument = ssDocument });
                    foreach (NodeTrace ndShip in nodeShipment)
                    {

                        if (ndShip.Node.NodeID == NodeType.Released)
                        {

                            ndShip.Node = voidNode;
                            ndShip.Status = inactive;
                            ndShip.ModDate = DateTime.Now;
                            Factory.DaoNodeTrace().Update(ndShip);
                        }

                        if (ndShip.Node.NodeID == NodeType.Picked)
                        {
                            ndShip.DocumentLine = null;
                            ndShip.PostingDate = null;
                            ndShip.PostingDocument = null;
                            ndShip.PostingUserName = null;
                            ndShip.PostingDocLineNumber = 0;
                            ndShip.ModDate = DateTime.Now;
                        }

                        Factory.DaoNodeTrace().Update(ndShip);
                    }

                    //DELETE the Shipment Document Lines
                    if (ssDocument != null && ssDocument.DocID > 0)
                        foreach (DocumentLine shLine in Factory.DaoDocumentLine().Select(new DocumentLine { Document = new Document { DocID = ssDocument.DocID } }))
                            Factory.DaoDocumentLine().Delete(shLine);

                }


                Console.WriteLine("0. Start");

                Object[] ssResult = new Object[2];

                if (shipTask.IsFromErp == true)
                    ssResult = SalesLinesForErpDocument(shipTask, ssDocument);

                else
                    ssResult = SalesLinesForTask(shipTask, ssDocument);


                Console.WriteLine("1. Getting SalesLines");

                //Info to update records after receipt creation in ERP
                ssDocument.DocumentLines = (List<DocumentLine>)ssResult[0]; //Armar las lineas del documento de Recibo
                traceList = (List<NodeTrace>)ssResult[1];

                //Si el documento no tienen lineas se sale
                if (ssDocument.DocumentLines == null || ssDocument.DocumentLines.Count == 0)
                    //ExceptionMngr.WriteEvent("CreateShipmentDocument:Doc#" + shipTask.DocNumber + ". Document does not contain lines.", 
                        //ListValues.EventType.Fatal, null, null, ListValues.ErrorCategory.ErpPosting);
                    throw new Exception("Document does not contain lines.");


                #endregion


                #region Additional Process & Packages


                Console.WriteLine("2. Kits");

                //Mayo 19 de 2009 - Jairo Murillo
                //Si la opcion SHOWCOMP esta activa y si es un documento del ERP. debe acomodarse el 
                //Shipment con los Kits y ordenar la sequence.
                if (GetCompanyOption(shipTask.Company, "SHOWCOMP").Equals("T") && shipTask.IsFromErp == true)
                    ssDocument.DocumentLines = GetLinesWithKitAssemblyHeaders(ssDocument.DocumentLines);


                string batchNumber="";

                //El proceso de Fullfilment se hace solo para sales orders
                if (ErpConnected && shipTask.DocType.DocTypeID == SDocType.SalesOrder)
                {
                    //Enviar el documento de shipping al ERP
                    curConnection = ssDocument.Company.ErpConnection;

                    //Evaluar si debe crear/full fill order en el ERP
                    if (GetCompanyOption(shipTask.Company, "CREERPSH").Equals("T"))
                    {
                        //Evaular si debe Update BATCH
                        if (GetCompanyOption(shipTask.Company, "UPDSHBATCH").Equals("T"))
                            batchNumber = string.IsNullOrEmpty(shipTask.Location.BatchNo) ? "" : shipTask.Location.BatchNo;


                        Console.WriteLine("3. In GP");
                        string shortAge = GetCompanyOption(shipTask.Company, "SHORTAGE");
                        ErpFactory.Documents().FulFillSalesDocument(ssDocument, shortAge, fistTimeFulfill, batchNumber);
                    }

  
                }
                else if (ErpConnected && shipTask.DocType.DocTypeID == SDocType.MergedSalesOrder) //FULLFILMENT of Merged Sales Ordes
                {
                    //Enviar el documento de shipping al ERP
                    curConnection = ssDocument.Company.ErpConnection;

                    //Evaluar si debe crear/full fill order en el ERP
                    if (GetCompanyOption(shipTask.Company, "CREERPSH").Equals("T"))
                    {                        
                        if (GetCompanyOption(shipTask.Company, "UPDSHBATCH").Equals("T"))
                            batchNumber = string.IsNullOrEmpty(shipTask.Location.BatchNo) ? "" : shipTask.Location.BatchNo;

                        ErpFactory.Documents().FulFillMergedSalesDocument(ssDocument, shipTask.DocumentLines, fistTimeFulfill, batchNumber);

                    }

                    try { ssDocument.QuoteNumber = GetHazMat(ssDocument.DocumentLines); }
                    catch { }
                }


                Console.WriteLine("4. After GP");

                //Se dejan los documentos en InProcess cuando se posteen pasan a Completed
                Status inProcess = WType.GetStatus(new Status { StatusID = DocStatus.InProcess });
                Status completed = WType.GetStatus(new Status { StatusID = DocStatus.Completed });


                //Ajustando los nodetrace y los labels procesados
                ProcessShippingTransactionTrace(traceList, ssDocument, shipTask, new Node { NodeID = NodeType.Released });


                //Put the posting Document to the Document Packages
                IList<DocumentPackage> packs = Factory.DaoDocumentPackage().Select(
                    new DocumentPackage
                    {
                        Document = new Document { DocID = shipTask.DocID }, 
                      PostingDocument = new Document { DocID = -1} }); //-1 equals NULL


                foreach (DocumentPackage pk in packs)
                {
                    //Si el pack no tiene labels contenidos se borra el pack y su label.
                    /*
                    if (Factory.DaoLabel().Select(new Label { FatherLabel = pk.PackLabel }).Count == 0)
                    {
                        try
                        {
                            Factory.DaoLabel().Update(pk.PackLabel);
                        }
                        catch { }

                        pk.PackLabel.Status = inactive;
                        Factory.DaoLabel().Update(pk.PackLabel);
                        continue;
                    }
                    */

                    pk.PostingDate = DateTime.Now;
                    pk.PostingDocument = ssDocument;
                    pk.PostingUserName = ssDocument.CreatedBy;
                    Factory.DaoDocumentPackage().Update(pk);
                }


                // Evalua sobre el documento si hay que hacer procesos adicionales ejemplo en el Documento WareHouse Transfer se debe crear el docuemto de recibo 
                // Para la Bodega que recibe la mercancia.
                if (shipTask.DocType.DocTypeID == SDocType.WarehouseTransferShipment)
                {
                    Location destLocation = Factory.DaoDocumentLine().Select(new DocumentLine { Document = shipTask }).First().Location2;
                    ssDocument.Comment += CreateWareHouseTransferReceiptOrder(ssDocument, destLocation);
                    //Factory.DaoDocument().Update(ssDocument);
                }


                //Mira si debe inprimir Generic Labels for Kit Assembly - Maxiforce.
                //Cuando se implemente Procesos de documento este Bloque pasara al proceso de 
                //Shipment      

                //Comentado para Maxiforce el 13 de Mayo de 2010
                //try
                //{
                //    if (GetCompanyOption(shipTask.Company, "PRTKTLBL").Equals("T"))
                //        PrintKitAssemblyLabels(ssDocument, 2);
                //}
                //catch { }



                #endregion


                //Creacion del Assembly Order en caso de que haya conexion al ERP y la opcion
                // ERPASMORDER este en True paar esa compania
                // 14 Mayo de 2007
                // COMENTARIADO EL 3 Junio de 2009 - Se quita el envio a GP
                /* if (GetCompanyOption(ssDocument.Company, "SHOWCOMP").Equals("T") && GetCompanyOption(ssDocument.Company, "ERPASMORDER").Equals("T"))
                    CreateKitAssemblyOrderBasedOnSalesDocument(shipTask, ssDocument); */


                ////15 jun 2010
                ////Aumentar el valor de COUNTRAND
                //DocMngr.IncreaseOption("COUNTRAND", shipTask.Company);

                //try
                //{ //Aumentar el VAlor de COUNTAMOUNT
                //    if (ssDocument.DocumentLines.Sum(f=>f.Quantity*f.Unit.BaseAmount*f.Product.ProductCost)
                //        > double.Parse(GetCompanyOption(shipTask.Company, "AMOUNTOVER")))
                //        //> double.Parse(Factory.DaoConfigOption().Select(new ConfigOption { Code = "AMOUNTOVER" }).First().DefValue))
                    
                //        DocMngr.IncreaseOption("COUNTAMOUNT", shipTask.Company);
                //}
                //catch { }

                Factory.Commit();

                ssDocument.DocStatus = completed;
                Factory.DaoDocument().Update(ssDocument);

                try
                {
                    //Update the Shipping Doc as In Process
                    if (shipTask.Arrived == true)
                        shipTask.DocStatus = completed; 
                    else
                        shipTask.DocStatus = inProcess; 

                    Factory.DaoDocument().Update(shipTask);
                }
                catch { }


                //Commit
                Factory.Commit();

                return ssDocument;


            }
            catch (Exception ex)
            {

                Factory.Rollback();

                //Ajusta la secuencia para reusar el numero
                //docSeq.NumSequence--;
                //Factory.DaoDocumentTypeSequence().Update(docSeq);
                //Factory.DaoDocument().Delete(ssDocument);
                //ReverseProcessTransactionTrace(traceList);

                ExceptionMngr.WriteEvent("CreateShipmentDocument:Doc#" + shipTask.DocNumber, ListValues.EventType.Fatal, ex, null, ListValues.ErrorCategory.ErpPosting);
                throw;
            }

        }
Exemple #17
0
 public void ReverseReceiptNodeTraceByLabels(List<NodeTrace> nodeTraceList, SysUser user, DocumentType docType)
 {
     TranMngr.ReverseReceiptNodeTraceByLabels(nodeTraceList, user, docType);
 }
        public void CreateScheduledCount()
        {
            DocumentType docType = new DocumentType { DocClass = new DocumentClass { DocClassID = SDocClass.Task } };
            docType.DocTypeID = SDocType.CountTask;

            // search for the Scheduled counts...
            IList<CountSchedule> list = Factory.DaoCountSchedule().Select(new CountSchedule { NextDateRun = DateTime.Today, IsDone = false });

            foreach (CountSchedule sch in list)
            {

                Document document = new Document
                {
                    Comment = "Scheduled Counting : "+sch.Title, 
                    DocType = docType,
                    CrossDocking = false,
                    IsFromErp = false,
                    Location = sch.Location, 
                    Company = sch.Location.Company, 
                    Date1 = DateTime.Today,
                    CreationDate = DateTime.Now,
                    CreatedBy = WmsSetupValues.SystemUser,
                    Notes = sch.CountOption.ToString()
                };
                document = DocMngr.CreateNewDocument(document, true);

                // parametros para ejecutar el query
                DataSet paramsQuery = BasicMngr.GetDataSet(sch.Parameters);

                // ejecuta el query q trae los productos/bines 
                DataSet dataSet = Factory.DaoIqReport().GetReportObject(sch.Query, paramsQuery);


                bool useProduct = true;

                if (sch.CountOption == 0) //Only BIN
                    useProduct = false;

                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    //  siempre deben enviar los alias "producto" "binCode" en el reporte !!!
                    Product prod = null;
                    try
                    {
                        if (!string.IsNullOrEmpty(row["Product"].ToString()) && useProduct)
                            prod = Factory.DaoProduct().Select(new Product { ProductCode = row["Product"].ToString() }, 0)[0];
                    }
                    catch { }

                    Bin bin = null;
                    try
                    {
                        if (!string.IsNullOrEmpty(row["BinCode"].ToString()))
                            bin = Factory.DaoBin().Select(new Bin { BinCode = row["BinCode"].ToString() })[0];
                    }
                    catch { }

                    //Crea el BinTask x prod/bin
                    BinByTask binByTask = new BinByTask
                    {
                        CreatedBy = WmsSetupValues.SystemUser,
                        CreationDate = DateTime.Now,
                        Bin = bin,
                        Product = prod,
                        TaskDocument = document,
                        Status = new Status { StatusID = DocStatus.New }
                    };

                    try
                    {
                        Factory.DaoBinByTask().Save(binByTask);
                    }
                    catch (Exception e)
                    {
                        continue;
                    }
                }

                // programamos sgte fecha de conteo (si no se pasa de la fecha final)
                if (sch.NextDateRun.Value.AddDays(double.Parse(sch.RepeatEach.ToString())) <= sch.Finish.Value)
                    sch.NextDateRun = sch.NextDateRun.Value.AddDays(double.Parse(sch.RepeatEach.ToString()));

                else  // ya finaliza el conteo repetitivo
                    sch.IsDone = true;

                sch.ModDate = DateTime.Now;
                sch.ModifiedBy = WmsSetupValues.SystemUser;

                Factory.DaoCountSchedule().Update(sch);
            }
        }
Exemple #19
0
 public DocumentType SaveDocumentType(DocumentType data) { return Factory.DaoDocumentType().Save(data); }
Exemple #20
0
 public DocumentType GetDocumentType(DocumentType data)
 {
    return Factory.DaoDocumentType().Select(data).First();
 }
Exemple #21
0
 public void DeleteDocumentType(DocumentType data) { Factory.DaoDocumentType().Delete(data); }
        /// <summary>
        /// Aumenta el stock d eun Bin Determinado
        /// </summary>
        /// <param name="line">Product, Unit, Qty a ajustar</param>
        /// <param name="node"></param>
        /// <param name="destBin"></param>
        /// <param name="comment"></param>
        /// <param name="saveTrace"></param>
        /// <returns></returns>
        public Label IncreaseQtyIntoBin(DocumentLine line, Node node, Bin destBin, string comment,
            bool saveTrace, DateTime recDate, IList<LabelTrackOption> trackOptions, Label sourceLabel)
        {


            bool isTransactional = Factory.IsTransactional;

            if (!isTransactional)
                Factory.IsTransactional = true;


            Label tmpLabel = null;
            Status status = WType.GetStatus(new Status { StatusID = EntityStatus.Active }); //Active

            DocumentType lblType = new DocumentType { DocTypeID = LabelType.ProductLabel };
            //DocumentTypeSequence initSequence = DocMngr.GetNextDocSequence(destBin.Location.Company, lblType); //Funcion para obtener siguiente Label

            //Crear el nuevo label en Node Storage

            DocumentType curType = null;
            if (line.Document != null)
                curType = Factory.DaoDocumentType().Select(line.Document.DocType).First();

            //Salvar con el nuevo status
            //El estatus es Active in printed en 0 (virtual)
            tmpLabel = new Label();

            //To Send
            tmpLabel.Node = node;

            tmpLabel.Bin = destBin;
            tmpLabel.CurrQty = line.Quantity;
            tmpLabel.Product = line.Product;
            tmpLabel.StartQty = line.Quantity;
            tmpLabel.Unit = line.Unit;
            tmpLabel.CreatedBy = line.CreatedBy;

            tmpLabel.Status = status;
            tmpLabel.CreationDate = DateTime.Now;
            tmpLabel.ReceivingDate = (recDate == null) ? DateTime.Now : recDate;
            tmpLabel.IsLogistic = false;

            // CAA [2010/05/28]
            // Validacion adjustments x serial#  (AccountItem guarda el Serial para estos casos) 
            if (line.AccountItem != null && !string.IsNullOrEmpty(line.AccountItem) && !line.AccountItem.Equals("-"))
            {
                tmpLabel.LabelType = new DocumentType { DocTypeID = LabelType.UniqueTrackLabel };
                tmpLabel.LabelCode = line.AccountItem;
                tmpLabel.Printed = true;
            }
            else
            {
                tmpLabel.LabelType = lblType;
                tmpLabel.LabelCode = ""; // initSequence.NumSequence.ToString() + GetRandomHex(line.CreatedBy, initSequence.NumSequence);
                tmpLabel.Printed = false;
            }



            if (curType != null)
            {
                if (curType.DocClass.DocClassID == SDocClass.Receiving)
                {
                    tmpLabel.ReceivingDocument = line.Document;
                }

                else if (curType.DocClass.DocClassID == SDocClass.Shipping)
                    tmpLabel.ShippingDocument = line.Document;

            }

            //Adicion de los TRackOptions Oct09/2009
            if (trackOptions != null && trackOptions.Count > 0)
            {
                tmpLabel.TrackOptions = new List<LabelTrackOption>();
                foreach (LabelTrackOption lto in trackOptions)
                {
                    lto.Label = tmpLabel;
                    lto.RowID = 0;
                    lto.CreationDate = DateTime.Now;
                    tmpLabel.TrackOptions.Add(lto);
                }

            }


            //Save the source if come from a Label LabelTypeID = 1002
            //Para poder rastrear el label de donde se saca el producto
            if (sourceLabel != null && sourceLabel.LabelType.DocTypeID == LabelType.ProductLabel)
            {
                tmpLabel.LabelSource = sourceLabel;
                //Confirmando que el producto este OK. Si no pone el del label Source
                //Mayo 10 problema de manzo
                if (tmpLabel.Product.ProductID != sourceLabel.Product.ProductID)
                    tmpLabel.Product = sourceLabel.Product;
            }

            tmpLabel = Factory.DaoLabel().Save(tmpLabel);
            if (tmpLabel.LabelCode.Equals(""))
                tmpLabel.LabelCode = tmpLabel.LabelID.ToString();

            //Registra el movimiento en NodeTrace
            if (saveTrace)
            {
                SaveNodeTrace(new NodeTrace
                {
                    Node = node,
                    Document = line.Document,
                    Label = tmpLabel,
                    Quantity = line.Quantity,
                    IsDebit = false,
                    Comment = comment,
                    CreationDate = DateTime.Now,
                    CreatedBy = line.CreatedBy,
                    Unit = line.Unit
                });
            }


            //Ajustando la sequencia
            //initSequence.NumSequence++;
            //Factory.DaoDocumentTypeSequence().Update(initSequence);

            if (!isTransactional)
                Factory.Commit();

            return tmpLabel;

        }
Exemple #23
0
 public DocumentType Save(DocumentType data)
 {
     return (DocumentType)base.Save(data);
 }
Exemple #24
0
        //Get document that mach with products of the Receiving Document
        public IList<Document> GetCrossDockSalesOrders(Document data)
        {
            Factory.IsTransactional = true;
            //Sales Doc Type
            DocumentType docType = new DocumentType { DocClass = new DocumentClass { DocClassID = SDocClass.Shipping } };

            //Purchase Products
            IList<Product> purchaseProducts = Factory.DaoDocumentLine()
                .Select(new DocumentLine { Document = data} ).Select(f => f.Product).Distinct().ToList();

            //Pending CrossDock List
            IList<Document> listDoc = Factory.DaoDocument().SelectPendingCrossDock(
                new Document { DocType = docType, Company = data.Company }, purchaseProducts).Distinct().ToList();

            Factory.Commit();

            return listDoc;


            ////Document Lines to make the Join
            //IList<DocumentLine> salesLineList = new List<DocumentLine>();
            //foreach (Document doc in salesDocList)
            //{
            //    if (doc.DocumentLines == null)
            //        continue;

            //    foreach (DocumentLine line in doc.DocumentLines)
            //        salesLineList.Add(line);
            //}

            ////Purchase Document Lines
            //IList<DocumentLine> purchaseLineList = Factory.DaoDocument().Select(data).First().DocumentLines;

            //IList<Document> returnList = purchaseLineList
            //    .Join<DocumentLine, DocumentLine, int, Document>
            //    (salesLineList, purchase => purchase.Product.ProductID, sales => sales.Product.ProductID, 
            //    (purchase, sales) => sales.Document ).Distinct().ToList(); 

            ////Join Operation to Get Cross Sales Orders
            //var selectedDocs =
            //        from purchase in purchaseLineList
            //        join sales in salesLineList 
            //        on purchase.Product.ProductID equals sales.Product.ProductID
            //        select sales.Document; //produces flat sequence

            //return selectedDocs as IList<Document>;

            //return returnList;
        }