public void CreatePurchaseOrder()
        {
            var supplierId = 0;
            var itemId     = 0;
            var taxTypeId  = 0;

            PurchaseOrder po       = new PurchaseOrder();
            var           supplier = Api.SupplierRequest.Get(supplierId);

            po.SupplierId   = supplierId;
            po.SupplierName = supplier.Name;
            po.Date         = DateTime.Now;
            po.DeliveryDate = DateTime.Now.AddDays(7);

            po.Lines = new List <CommercialDocumentLine>();
            var line1 = new CommercialDocumentLine
            {
                SelectionId        = itemId,    // This must be an item or account id
                TaxTypeId          = taxTypeId, // Use TaxTypeRequest to get list of Tax Types
                LineType           = 0,         // 0=Item/1=Account
                Quantity           = 1,
                UnitPriceExclusive = 390,
                UnitPriceInclusive = 390,
                DiscountPercentage = 0
            };

            po.Lines.Add(line1);

            var newPurchaseOrder = purchaseOrderRequest.Save(po);

            Assert.IsTrue(purchaseOrderRequest.StatusCode == HttpStatusCode.Created);
        }
Example #2
0
        /// <summary>
        /// Wiąże dwa dokumenty, z których conajmniej jeden może być korektą.
        /// </summary>
        /// <param name="previousDocument"></param>
        /// <param name="nextDocument"></param>
        /// <param name="last">true jeśli jest to próba powiązania z korygowanym dokumentem - wtedy już musimy powiązanie stworzyć</param>
        /// <returns>true jeśli udało się powiązać dokumenty, false jeśli nie</returns>
        public static bool RelateTwoCorrectiveDocuments(CommercialDocument previousDocument, CommercialDocument nextDocument, bool last)
        {
            nextDocument.CorrectedDocument = previousDocument;

            foreach (CommercialDocumentLine line in nextDocument.Lines.Children)
            {
                CommercialDocumentLine correctedLine = previousDocument.Lines.Children.Where(l => l.Id.Value == line.CorrectedLine.Id.Value).FirstOrDefault();

                if (correctedLine != null)
                {
                    line.CorrectedLine = correctedLine;
                }
                else
                {
                    correctedLine = nextDocument.Lines.Children.Where(l => l.Id.Value == line.CorrectedLine.Id.Value).FirstOrDefault();

                    if (correctedLine != null)
                    {
                        line.CorrectedLine = correctedLine;
                    }
                    else if (last)
                    {
                        throw new InvalidOperationException("Cannot find corrected line");
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #3
0
        private static void CalculateLineAfterCorrection(CommercialDocumentLine line)
        {
            if (line.CorrectedLine != null)
            {
                CommercialDocument parent = (CommercialDocument)line.Parent;

                //if the corrected line is in the same document so it already has been corrected so dont do it again
                if (parent.Lines.Children.Where(l => l.Id.Value == line.CorrectedLine.Id.Value).FirstOrDefault() == null)
                {
                    CommercialCorrectiveDocumentFactory.CalculateLineAfterCorrection(line.CorrectedLine);
                }

                line.DiscountGrossValue += line.CorrectedLine.DiscountGrossValue;
                line.DiscountNetValue   += line.CorrectedLine.DiscountNetValue;
                line.DiscountRate       += line.CorrectedLine.DiscountRate;
                line.GrossPrice         += line.CorrectedLine.GrossPrice;
                line.GrossValue         += line.CorrectedLine.GrossValue;
                line.InitialGrossPrice  += line.CorrectedLine.InitialGrossPrice;
                line.InitialGrossValue  += line.CorrectedLine.InitialGrossValue;
                line.InitialNetPrice    += line.CorrectedLine.InitialNetPrice;
                line.InitialNetValue    += line.CorrectedLine.InitialNetValue;
                line.NetPrice           += line.CorrectedLine.NetPrice;
                line.NetValue           += line.CorrectedLine.NetValue;
                line.VatValue           += line.CorrectedLine.VatValue;
                line.Quantity           += line.CorrectedLine.Quantity;
            }
        }
Example #4
0
        /// <summary>
        /// Creates the related business object from XML element.
        /// </summary>
        /// <param name="element">Xml element from which to create the <see cref="IBusinessObject"/>.</param>
        /// <param name="relatedObjectType">Type of the related object.</param>
        /// <returns>Related object.</returns>
        public static IBusinessObject CreateRelatedBusinessObjectFromXmlElement(XElement element, BusinessObjectType relatedObjectType)
        {
            if (relatedObjectType == BusinessObjectType.CommercialDocumentLine)
            {
                CommercialDocumentLine line = new CommercialDocumentLine(null);
                line.Deserialize(element);
                return(line);
            }
            else if (relatedObjectType == BusinessObjectType.WarehouseDocumentLine)
            {
                WarehouseDocumentLine line = new WarehouseDocumentLine(null);
                line.Deserialize(element);
                return(line);
            }
            else if (relatedObjectType == BusinessObjectType.Payment)
            {
                Payment pt = new Payment(null);
                pt.Deserialize(element);
                return(pt);
            }
            else
            {
                Mapper m = Mapper.GetMapperForSpecifiedBusinessObjectType(relatedObjectType);

                return(m.ConvertToBusinessObject(element, null));
            }
        }
        internal static void TryRemoveCommercialDocumentToSalesOrderRelations(CommercialDocumentLine documentLine)
        {
            DocumentLineAttrValue rsoliAttr = documentLine.Attributes[DocumentFieldName.LineAttribute_RealizedSalesOrderLineId];

            if (rsoliAttr != null)
            {
                documentLine.Attributes.Remove(rsoliAttr);
            }
        }
Example #6
0
        internal static string GetOption(CommercialDocumentLine line)
        {
            DocumentLineAttrValue sogdoAttr = line.Attributes[DocumentFieldName.LineAttribute_SalesOrderGenerateDocumentOption];

            if (sogdoAttr == null)
            {
                throw new ClientException(ClientExceptionId.MissingLineAttribute, null, "ordinalNumber:" + line.OrdinalNumber.ToString(CultureInfo.InvariantCulture));
            }
            return(sogdoAttr.Value.Value);
        }
        public void CreateQuote()
        {
            var customerId = 0;
            var salesRepId = 0;

            var itemId    = 0;
            var taxTypeId = 0;

            Quote quote    = new Quote();
            var   customer = Api.CustomerRequest.Get(customerId);
            var   salesRep = Api.SalesRepresentativeRequest.Get(salesRepId);

            // Must set both CustomerId and Customer in order to work
            quote.CustomerId = customerId;
            quote.Customer   = customer;

            // Must set both SalesRepresentativeId and SalesRepresentative in order to work
            quote.SalesRepresentativeId = salesRepId;
            quote.SalesRepresentative   = salesRep;

            quote.Date       = DateTime.Now;
            quote.ExpiryDate = new DateTime(2016, 12, 12);

            quote.Lines = new List <CommercialDocumentLine>();

            var line1 = new CommercialDocumentLine
            {
                SelectionId        = itemId,    // This must be an item or account id
                TaxTypeId          = taxTypeId, // Use TaxTypeRequest to get list of Tax Types
                LineType           = 0,         // 0=Item/1=Account
                Quantity           = 70,
                UnitPriceExclusive = 390,
                UnitPriceInclusive = 390,
                DiscountPercentage = 0
            };

            quote.Lines.Add(line1);

            var newQuote = quoteRequest.Save(quote);

            Assert.IsTrue(quoteRequest.StatusCode == HttpStatusCode.Created);
        }
Example #8
0
        private static void CalculateHeaderAndVatTableAfterCorrection(CommercialDocument document)
        {
            CommercialDocumentLine firstLine = document.Lines.Children.First();

            if (firstLine.CorrectedLine != null)
            {
                CommercialDocument previousDoc = (CommercialDocument)firstLine.CorrectedLine.Parent;
                CommercialCorrectiveDocumentFactory.CalculateHeaderAndVatTableAfterCorrection(previousDoc);

                decimal netValue   = previousDoc.NetValue;
                decimal grossValue = previousDoc.GrossValue;
                decimal vatValue   = previousDoc.VatValue;

                if (previousDoc.IsSettlementDocument)
                {
                    netValue   = previousDoc.VatTableEntries.Where(ss => ss.NetValue > 0 && ss.GrossValue > 0 && ss.VatValue > 0).Sum(s => s.NetValue);
                    grossValue = previousDoc.VatTableEntries.Where(ss => ss.NetValue > 0 && ss.GrossValue > 0 && ss.VatValue > 0).Sum(s => s.GrossValue);
                    vatValue   = previousDoc.VatTableEntries.Where(ss => ss.NetValue > 0 && ss.GrossValue > 0 && ss.VatValue > 0).Sum(s => s.VatValue);
                }

                document.NetValue   += netValue;
                document.GrossValue += grossValue;
                document.VatValue   += vatValue;

                foreach (CommercialDocumentVatTableEntry vtEntry in previousDoc.VatTableEntries.Children)
                {
                    if (previousDoc.IsSettlementDocument && (vtEntry.NetValue < 0 || vtEntry.GrossValue < 0 || vtEntry.VatValue < 0))
                    {
                        continue;
                    }

                    CommercialDocumentVatTableEntry currentVtEntry = document.VatTableEntries.Children.Where(v => v.VatRateId == vtEntry.VatRateId).FirstOrDefault();

                    if (currentVtEntry != null)
                    {
                        currentVtEntry.GrossValue += vtEntry.GrossValue;
                        currentVtEntry.NetValue   += vtEntry.NetValue;
                        currentVtEntry.VatValue   += vtEntry.VatValue;
                    }
                }
            }
        }
        /// <summary>
        /// Recursively creates new children (BusinessObjects) and loads settings from provided xml.
        /// </summary>
        /// <param name="element">Xml element to attach.</param>
        public override void Deserialize(XElement element)
        {
            base.Deserialize(element);

            this.RelatedLine = null;

            if (element.Element("relatedLine") != null && this.Parent.Parent != null)
            {
                if (this.Parent.Parent.BOType == BusinessObjectType.CommercialDocument)
                {
                    WarehouseDocumentLine line = new WarehouseDocumentLine(null);
                    line.Deserialize(element.Element("relatedLine").Element("line"));
                    this.RelatedLine = line;
                }
                else
                {
                    CommercialDocumentLine line = new CommercialDocumentLine(null);
                    line.Deserialize(element.Element("relatedLine").Element("line"));
                    this.RelatedLine = line;
                }
            }
        }
Example #10
0
        public static void GenerateSalesOrder(XElement source, CommercialDocument destination, bool isNew)
        {
            if (destination == null)
            {
                return;
            }

            #region Contractors
            string           str;
            ContractorMapper contractorMapper = DependencyContainerManager.Container.Get <ContractorMapper>();
            Contractor       sourceSeller     = null;
            if (source.Element("karta-klienta").Element("klient").Element("nip") != null)
            {
                str = source.Element("karta-klienta").Element("klient").Element("nip").Value;

                sourceSeller = contractorMapper.GetContractorByNip(str);
                if (sourceSeller == null)
                {
                    throw new ClientException(ClientExceptionId.ObjectNotFound);
                }
            }

            if (source.Element("karta-klienta").Element("klient").Element("nazwa") != null && sourceSeller == null)
            {
                str = source.Element("karta-klienta").Element("klient").Element("nazwa").Value;

                sourceSeller = contractorMapper.GetContractorByFullName(str);
                if (sourceSeller == null)
                {
                    throw new ClientException(ClientExceptionId.ObjectNotFound);
                }
            }


            destination.Contractor = sourceSeller;
            #endregion

            #region Parsing Lines
            var sourceLines = new List <CustomXmlOrderLine>();

            double            coloreValue            = 0;
            XDocument         codesInputDocument     = XDocument.Parse(XmlName.EmptyRoot);
            XPathDocument     itemsLists             = new XPathDocument(source.CreateReader());
            XPathNavigator    oXPathNavigator        = itemsLists.CreateNavigator();
            XPathNodeIterator oIpozycjaNodesIterator = oXPathNavigator.Select("/source/karta-klienta/pozycja");
            int lineNumber = 1;
            foreach (XPathNavigator item in oIpozycjaNodesIterator)
            {
                var lineInfo = new CustomXmlOrderLine();
                lineInfo.ItemUnit = item.SelectSingleNode("ilosc").Value.Replace(",", "."); //jeśli < 1000 to wstawiam ten produkt
                if (!item.SelectSingleNode("kod_fr").IsEmptyElement)
                {
                    lineInfo.ItemCode = item.SelectSingleNode("kod_fr").Value;
                }
                else
                {
                    lineInfo.ItemCode = item.SelectSingleNode("produkt").Value;
                }

                if (int.Parse(lineInfo.ItemUnit) < 1000)
                {
                    lineInfo.ItemDescription = "directUse";
                }
                else
                {
                    lineInfo.ItemDescription = "getItemEquivalent";
                }
                lineInfo.Quantity = decimal.Parse(item.SelectSingleNode("sztuk").ToString().Replace(",", "."));

                //Brakuje logiki zamiany towarów na opakowane
                sourceLines.Add(lineInfo);

                codesInputDocument.Root.Add(
                    new XElement("line"
                                 , new XElement("LineNumber", lineNumber.ToStringInvariant())
                                 , new XElement(XmlName.Code, lineInfo.ItemCode)
                                 , new XElement("itemDescription", lineInfo.ItemDescription)
                                 , new XElement("itemUnit", lineInfo.ItemUnit)
                                 , new XElement("quantity", lineInfo.Quantity)
                                 ));
                lineNumber++;

                if (!item.SelectSingleNode("wartosc-pigment").IsEmptyElement)
                {
                    //to się sumuje do usługi barwienie z sumą kosztów
                    coloreValue = coloreValue + double.Parse(item.SelectSingleNode("wartosc-pigment").Value);
                }
            }

            // Dodanie pozycji usługowej z wycena wartości barwienia
            if (coloreValue != 0)
            {
                var lineInfo = new CustomXmlOrderLine();
                coloreValue = Math.Round(coloreValue, 2);

                lineInfo.ItemCode = "Pigment - barwienie";
                lineInfo.Quantity = 1;
                sourceLines.Add(lineInfo);

                codesInputDocument.Root.Add(
                    new XElement("line"
                                 , new XElement("LineNumber", lineNumber.ToStringInvariant())
                                 , new XElement(XmlName.Code, lineInfo.ItemCode)
                                 , new XElement("defaultPrice", coloreValue)
                                 , new XElement("quantity", 1)
                                 , new XElement("itemDescription", "directUse")
                                 ));
            }
            #endregion



            #region AddLines
            XDocument  itemsNotFound = XDocument.Parse(XmlName.EmptyRoot);
            ItemMapper itemMapper    = DependencyContainerManager.Container.Get <ItemMapper>();
            XElement   documentItems = EcIntegrationFactory.CheckItemsExistence(itemMapper, codesInputDocument); //p_checkItemsExistenceByCode

            XPathDocument     itemsCheckedLists = new XPathDocument(documentItems.CreateReader());
            XPathNavigator    itemsNavigator    = itemsCheckedLists.CreateNavigator();
            XPathNodeIterator itemsIterator     = itemsNavigator.Select("/root/line");
            lineNumber = 1;
            foreach (XPathNavigator line in itemsIterator)
            {
                if (line.SelectSingleNode("id") != null)
                {
                    destination.CalculationType         = (CalculationType)Enum.Parse(typeof(CalculationType), "Gross");
                    destination.CalculationTypeSelected = true;

                    CommercialDocumentLine commercialDocumentLine = destination.Lines.CreateNew();
                    commercialDocumentLine.Quantity        = (decimal)line.SelectSingleNode("quantity").ValueAsDouble;
                    commercialDocumentLine.ItemVersion     = new Guid(line.SelectSingleNode("version").Value);
                    commercialDocumentLine.ItemId          = new Guid(line.SelectSingleNode("id").Value);
                    commercialDocumentLine.UnitId          = new Guid(line.SelectSingleNode("unitId").Value);
                    commercialDocumentLine.VatRateId       = new Guid(line.SelectSingleNode("vatRateId").Value);
                    commercialDocumentLine.ItemCode        = line.SelectSingleNode("code").Value;
                    commercialDocumentLine.ItemName        = line.SelectSingleNode("name").Value;
                    commercialDocumentLine.ItemTypeId      = line.SelectSingleNode("itemTypeId").Value;
                    commercialDocumentLine.InitialNetPrice = Convert.ToDecimal(line.SelectSingleNode("defaultPrice").Value, CultureInfo.InvariantCulture);

                    commercialDocumentLine.Calculate(commercialDocumentLine.Quantity, commercialDocumentLine.InitialNetPrice, 0);
                }
                else
                {
                    itemsNotFound.Root.Add(
                        new XElement("itemsNotFound",
                                     XElement.Load(line.ReadSubtree()))
                        );
                }
            }
            source.Add(XElement.Load(itemsNotFound.Root.CreateReader()));
            source.Element("karta-klienta").Remove();
            #endregion

            //Vat Table
            destination.Calculate();
        }
Example #11
0
        public static void GeneratePrepaymentDocument(XElement source, CommercialDocument destination)
        {
            /*
             *      <source type="salesOrder">
             *        <salesOrderId>{documentId}</salesOrderId>
             *        <processObject>prepaidInvoice</processObject>
             *        <closeOrder>false</closeOrder>
             *      </source>
             */
            DocumentMapper mapper = DependencyContainerManager.Container.Get <DocumentMapper>();

            bool closeOrder = false;

            if (source.Element("closeOrder") != null && source.Element("closeOrder").Value.ToUpperInvariant() == "TRUE")
            {
                closeOrder = true;
            }

            CommercialDocument salesOrder = (CommercialDocument)mapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, new Guid(source.Element("salesOrderId").Value));


            SalesOrderFactory.CheckIfSalesOrderHasWarehouseDocumentsWithInvoices(salesOrder, closeOrder);

            SalesOrderSettlements salesOrderSettlements = new SalesOrderSettlements();

            salesOrderSettlements.LoadSalesOrder(salesOrder);
            XElement settledAmount = mapper.GetSalesOrderSettledAmount(salesOrder.Id.Value);

            salesOrderSettlements.LoadPrepaids(settledAmount);
            destination.SalesOrderSettlements = salesOrderSettlements;

            string processType   = salesOrder.Attributes[DocumentFieldName.Attribute_ProcessType].Value.Value;
            string processObject = source.Element("processObject").Value;
            bool   isSimulated   = processObject == "simulatedInvoice";
            bool   hasProtocole  = source.Element("protocole") != null && source.Element("protocole").Value == "true";

            ProcessManager.Instance.AppendProcessAttributes(destination, processType, processObject, null, null);
            DuplicableAttributeFactory.DuplicateAttributes(salesOrder, destination);

            if (isSimulated && hasProtocole)
            {
                destination.Attributes.GetOrCreateNew(DocumentFieldName.Attribute_IsSimulateSettlementInvoiceWithProtocole).Value.Value = "1";
            }

            //sprawdzamy czy dokumenty zrodlowe maja zgodne sposoby liczenia

            if (salesOrder.CalculationType != destination.CalculationType && destination.DocumentType.CommercialDocumentOptions.AllowCalculationTypeChange)
            {
                destination.CalculationType = salesOrder.CalculationType;
            }

            if (salesOrder.Contractor != null)
            {
                destination.Contractor = (Contractor)salesOrder.Contractor;
            }

            if (salesOrder.ContractorAddressId != null)
            {
                destination.ContractorAddressId = salesOrder.ContractorAddressId;
            }

            int prepaidDocuments = 0;

            prepaidDocuments = salesOrder.Relations.Where(r => r.RelationType == DocumentRelationType.SalesOrderToInvoice).Count();

            destination.Tag = prepaidDocuments.ToString(CultureInfo.InvariantCulture);

            /* teraz wybieramy odpowiednia sciezke algorytmu. mamy takie mozliwosc:
             * 1) wystawiamy zaliczke
             *    - w takiej sytuacji wybieramy id towaru zaliczkowego dla kazdej ze stawek vat i wpisujemy tam wartosci nierozliczone
             * 2) wystawiamy fakture rozliczajaca (closeOrder == true) podczas gdy mamy zaliczki (prepaidDocuments > 0)
             *    - kopiujemy wszystkie pozycje z ZS 1:1, a tabele vat pomniejszamy o sume zaliczek
             * 3) wystawiamy fakture rozliczajaca (closeOrder == true) i nie mamy dokumentow zaliczkowych (prepaidDocuments == 0)
             *    - w takim przypadku zamowienie sprzedazowe traktujemy jako proforme, kopiujemy wszystkie pozycje i tabele vat bez zmian i tyle
             */


            //wstawiamy odpowiedni towar na zaliczke + ustawiamy odpowiednai wartosc
            int stage = 0;

            if (closeOrder)
            {
                stage = 0;
            }
            else if (prepaidDocuments == 0)
            {
                stage = 1;
            }
            else if (prepaidDocuments == 1)
            {
                stage = 2;
            }
            else if (prepaidDocuments == 2)
            {
                stage = 3;
            }
            else if (prepaidDocuments >= 3)
            {
                stage = 4;
            }

            List <Guid> items = new List <Guid>(2);

            ICollection <SalesOrderSettlement> unsettledValues = salesOrderSettlements.GetUnsettledValues();

            foreach (var v in salesOrder.VatTableEntries.GetVatRates())
            {
                items.Add(ProcessManager.Instance.GetPrepaidItemId(salesOrder, stage, v));
            }

            XDocument xml = DependencyContainerManager.Container.Get <ItemMapper>().GetItemsDetailsForDocument(false, null, null, items);

            if (closeOrder)
            {
                SalesOrderFactory.CopyLinesFromSalesOrder(salesOrder, destination, false, true, false, true);
                destination.Calculate();

                //Ostatnia rata pchamy do atrybutu zeby wydruk fiskalny wiedzial co ma wydrukowac
                if (destination.CalculationType == CalculationType.Gross && !isSimulated)
                {
                    XElement fiscalLines = new XElement("fiscalLines");

                    foreach (var v in unsettledValues)
                    {
                        XElement itemXml    = xml.Root.Elements().Where(i => i.Attribute("id").Value == ProcessManager.Instance.GetPrepaidItemId(salesOrder, stage, v.VatRateId).ToUpperString()).First();
                        XElement fiscalLine = new XElement("fiscalLine");
                        fiscalLine.Add(new XElement("itemName", itemXml.Attribute("name").Value));
                        fiscalLine.Add(new XElement("quantity", "1"));
                        fiscalLine.Add(new XElement("vatRateId", itemXml.Attribute("vatRateId").Value));
                        fiscalLine.Add(new XElement("grossPrice", v.GrossValue.ToString(CultureInfo.InvariantCulture)));
                        fiscalLine.Add(new XElement("grossValue", v.GrossValue.ToString(CultureInfo.InvariantCulture)));
                        fiscalLine.Add(new XElement("unitId", itemXml.Attribute("unitId").Value));
                        fiscalLines.Add(fiscalLine);
                    }

                    var attribute = destination.Attributes.CreateNew(DocumentFieldName.Attribute_FiscalPrepayment);
                    attribute.Value = fiscalLines;
                }

                if (prepaidDocuments > 0)                 // *2)
                {
                    decimal maxDifference = ProcessManager.Instance.GetMaxSettlementDifference(salesOrder);

                    foreach (var v in salesOrderSettlements.Prepaids)
                    {
                        if (v.NetValue > 0 || v.GrossValue > 0 || v.VatValue > 0)
                        {
                            var vt        = destination.VatTableEntries.Where(t => t.VatRateId == v.VatRateId).FirstOrDefault();
                            var prepaidVt = destination.VatTableEntries.CreateNewAfter(vt, v.VatRateId);
                            prepaidVt.VatRateId  = v.VatRateId;
                            prepaidVt.NetValue   = -v.NetValue;
                            prepaidVt.GrossValue = -v.GrossValue;
                            prepaidVt.VatValue   = -v.VatValue;

                            decimal vtNetValue   = 0;
                            decimal vtGrossValue = 0;
                            decimal vtVatValue   = 0;
                            if (vt != null)
                            {
                                vtNetValue   = vt.NetValue;
                                vtGrossValue = vt.GrossValue;
                                vtVatValue   = vt.VatValue;
                            }

                            decimal grossBalance = vtGrossValue + prepaidVt.GrossValue;
                            decimal netBalance   = vtNetValue + prepaidVt.NetValue;
                            decimal vatBalance   = vtVatValue + prepaidVt.VatValue;

                            SalesOrderBalanceValidator validator =
                                new SalesOrderBalanceValidator(maxDifference, grossBalance, netBalance, vatBalance);

                            if (validator.IsIllegalOverPayment)
                            {
                                throw new ClientException(ClientExceptionId.SalesOrderSettlementOverpaidError, null, "value:" + (-grossBalance).ToString(CultureInfo.InvariantCulture).Replace('.', ',')); //nadpłata powyżej granicy błędu
                            }
                            else if (validator.IsAcceptableOverPayment)                                                                                                                                    //czyli mamy nadplate w granicy bledu
                            {
                                prepaidVt.NetValue   = -vtNetValue;
                                prepaidVt.GrossValue = -vtGrossValue;
                                prepaidVt.VatValue   = -vtVatValue;
                            }
                        }
                    }
                }
                else
                {
                    throw new ClientException(ClientExceptionId.UnableToCreateSettlementDocument3);
                }

                decimal netValue   = 0;
                decimal grossValue = 0;
                decimal vatValue   = 0;

                foreach (var vt in destination.VatTableEntries)
                {
                    netValue   += vt.NetValue;
                    grossValue += vt.GrossValue;
                    vatValue   += vt.VatValue;
                }

                destination.NetValue   = netValue;
                destination.GrossValue = grossValue;
                destination.VatValue   = vatValue;

                destination.DisableLinesChange = DisableDocumentChangeReason.LINES_SETTLEMENT_INVOICE;

                if (!isSimulated)
                {
                    var attr = destination.Attributes.CreateNew(DocumentFieldName.Attribute_IsSettlementDocument);
                    attr.Value.Value = "1";
                }
            }
            else             //1) wystawiamy zaliczke
            {
                foreach (XElement itemXml in xml.Root.Elements("item"))
                {
                    CommercialDocumentLine line = destination.Lines.CreateNew();
                    line.ItemId = new Guid(itemXml.Attribute("id").Value);
                    Guid vatRateId = new Guid(itemXml.Attribute("vatRateId").Value);

                    if (itemXml.Attribute("code") != null)
                    {
                        line.ItemCode = itemXml.Attribute("code").Value;
                    }

                    line.UnitId      = new Guid(itemXml.Attribute("unitId").Value);
                    line.VatRateId   = vatRateId;
                    line.ItemVersion = new Guid(itemXml.Attribute("version").Value);
                    line.Quantity    = 1;
                    line.ItemName    = itemXml.Attribute("name").Value;
                }

                destination.Calculate();
            }
        }
Example #12
0
        private static void CreateNextCorrectiveDocument(CommercialDocument lastCorrectiveDoc, CommercialDocument destination)
        {
            destination.CorrectedDocument = lastCorrectiveDoc;

            //copy header
            destination.CalculationType    = lastCorrectiveDoc.CalculationType;
            destination.DocumentCurrencyId = lastCorrectiveDoc.DocumentCurrencyId;
            destination.GrossValue         = lastCorrectiveDoc.GrossValue;
            destination.NetValue           = lastCorrectiveDoc.NetValue;
            destination.SummationType      = lastCorrectiveDoc.SummationType;
            destination.VatValue           = lastCorrectiveDoc.VatValue;
            //Jednak event date powinien być podpowiadany jako bieżąca data
            destination.EventDate = SessionManager.VolatileElements.CurrentDateTime;            //lastCorrectiveDoc.EventDate;

            if (lastCorrectiveDoc.Contractor != null)
            {
                ContractorMapper contractorMapper = DependencyContainerManager.Container.Get <ContractorMapper>();
                Contractor       contractor       = (Contractor)contractorMapper.LoadBusinessObject(BusinessObjectType.CommercialDocument, lastCorrectiveDoc.Contractor.Id.Value);

                destination.Contractor          = contractor;
                destination.ContractorAddressId = lastCorrectiveDoc.ContractorAddressId;
            }

            //copy attributes if specified
            foreach (DocumentAttrValue attr in lastCorrectiveDoc.Attributes.Children)
            {
                if (attr.DocumentFieldName == DocumentFieldName.Attribute_SupplierDocumentDate ||
                    attr.DocumentFieldName == DocumentFieldName.Attribute_SupplierDocumentNumber)
                {
                    DocumentAttrValue dstAttr = destination.Attributes.CreateNew();
                    dstAttr.DocumentFieldName = attr.DocumentFieldName;
                    dstAttr.Value             = new XElement(attr.Value);
                }
            }

            //create vat tables
            foreach (CommercialDocumentVatTableEntry vtEntry in lastCorrectiveDoc.VatTableEntries.Children)
            {
                if (lastCorrectiveDoc.IsSettlementDocument && (vtEntry.GrossValue < 0 || vtEntry.NetValue < 0 || vtEntry.VatValue < 0))
                {
                    continue;
                }

                if (vtEntry.GrossValue != 0 || vtEntry.NetValue != 0 || vtEntry.VatValue != 0)
                {
                    CommercialDocumentVatTableEntry dstVtEntry = destination.VatTableEntries.CreateNew();

                    dstVtEntry.GrossValue = vtEntry.GrossValue;
                    dstVtEntry.NetValue   = vtEntry.NetValue;
                    dstVtEntry.VatValue   = vtEntry.VatValue;
                    dstVtEntry.VatRateId  = vtEntry.VatRateId;
                }
            }

            if (lastCorrectiveDoc.IsSettlementDocument)
            {
                destination.NetValue   = destination.VatTableEntries.Sum(s => s.NetValue);
                destination.GrossValue = destination.VatTableEntries.Sum(s => s.GrossValue);
                destination.VatValue   = destination.VatTableEntries.Sum(s => s.VatValue);
            }

            //create only these lines that werent corrected inside the same document
            var linesToCopy = from line in lastCorrectiveDoc.Lines.Children
                              where (lastCorrectiveDoc.Lines.Children.Where(w => w.CorrectedLine != null).Select(s => s.CorrectedLine.Id.Value)).Contains(line.Id.Value) == false
                              select line;

            foreach (CommercialDocumentLine srcLine in linesToCopy)
            {
                CommercialDocumentLine line = destination.Lines.CreateNew();
                line.CorrectedLine      = srcLine;
                line.DiscountGrossValue = srcLine.DiscountGrossValue;
                line.DiscountNetValue   = srcLine.DiscountNetValue;
                line.DiscountRate       = srcLine.DiscountRate;
                line.GrossPrice         = srcLine.GrossPrice;
                line.GrossValue         = srcLine.GrossValue;
                line.InitialGrossPrice  = srcLine.InitialGrossPrice;
                line.InitialGrossValue  = srcLine.InitialGrossValue;
                line.InitialNetPrice    = srcLine.InitialNetPrice;
                line.InitialNetValue    = srcLine.InitialNetValue;
                line.ItemId             = srcLine.ItemId;
                line.ItemName           = srcLine.ItemName;
                line.ItemVersion        = srcLine.ItemVersion;
                line.NetPrice           = srcLine.NetPrice;
                line.NetValue           = srcLine.NetValue;
                line.Quantity           = srcLine.Quantity;
                line.UnitId             = srcLine.UnitId;
                line.VatRateId          = srcLine.VatRateId;
                line.VatValue           = srcLine.VatValue;
                line.WarehouseId        = srcLine.WarehouseId;
                line.ItemCode           = srcLine.ItemCode;
                line.ItemTypeId         = srcLine.ItemTypeId;
            }
        }
Example #13
0
        private void ValidateServiceReservation(ServiceDocument document)
        {
            //sumujemy ile towarow potrzebujemy "dorezerwowac"
            //sprawdzamy czy jest an stanie tyle dostepnych
            //jezeli nie to rzucamy wyjatek
            WarehouseItemUnitQuantityDictionary dict = new WarehouseItemUnitQuantityDictionary();

            this.mapper.AddItemsToItemTypesCache(document);
            IDictionary <Guid, Guid> cache = SessionManager.VolatileElements.ItemTypesCache;

            foreach (var line in document.Lines)
            {
                Guid     itemTypeId = cache[line.ItemId];
                ItemType itemType   = DictionaryMapper.Instance.GetItemType(itemTypeId);

                if (!itemType.IsWarehouseStorable)
                {
                    continue;
                }

                if (line.OrderDirection == -1)
                {
                    decimal quantity = line.Quantity;

                    CommercialDocumentLine altLine = line.AlternateVersion as CommercialDocumentLine;

                    if (altLine != null)
                    {
                        quantity -= altLine.Quantity;
                    }

                    dict.Add(line.WarehouseId.Value, line.ItemId, line.UnitId, quantity);
                }
            }

            ServiceDocument alternateDocument = document.AlternateVersion as ServiceDocument;

            if (alternateDocument != null)
            {
                foreach (var line in alternateDocument.Lines)
                {
                    if (line.Status == BusinessObjectStatus.Deleted && line.OrderDirection == -1)
                    {
                        dict.Add(line.WarehouseId.Value, line.ItemId, line.UnitId, -line.Quantity);
                    }
                }
            }

            List <DeliveryRequest> deliveryRequests = new List <DeliveryRequest>();

            foreach (Guid warehouseId in dict.Dictionary.Keys)
            {
                var itemUnitQtyDict = dict.Dictionary[warehouseId];

                foreach (Guid itemId in itemUnitQtyDict.Keys)
                {
                    var unitQtyDict = itemUnitQtyDict[itemId];

                    foreach (Guid unitId in unitQtyDict.Keys)
                    {
                        decimal quantity = unitQtyDict[unitId];

                        if (quantity > 0)
                        {
                            DeliveryRequest delivery = deliveryRequests.Where(d => d.ItemId == itemId && d.WarehouseId == warehouseId).FirstOrDefault();

                            if (delivery == null)
                            {
                                deliveryRequests.Add(new DeliveryRequest(itemId, warehouseId, unitId));
                            }
                        }
                    }
                }
            }

            ICollection <DeliveryResponse> deliveryResponses = this.mapper.GetDeliveries(deliveryRequests);

            foreach (Guid warehouseId in dict.Dictionary.Keys)
            {
                var itemUnitQtyDict = dict.Dictionary[warehouseId];

                foreach (Guid itemId in itemUnitQtyDict.Keys)
                {
                    var unitQtyDict = itemUnitQtyDict[itemId];

                    foreach (Guid unitId in unitQtyDict.Keys)
                    {
                        decimal quantity = unitQtyDict[unitId];

                        if (quantity > 0)
                        {
                            var deliveryResponse = deliveryResponses.Where(d => d.ItemId == itemId && d.WarehouseId == warehouseId).First();

                            if (quantity > deliveryResponse.AvailableQuantity)
                            {
                                string itemName      = DependencyContainerManager.Container.Get <ItemMapper>().GetItemName(itemId);
                                string warehouseName = BusinessObjectHelper.GetBusinessObjectLabelInUserLanguage(DictionaryMapper.Instance.GetWarehouse(warehouseId)).Value;

                                throw new ClientException(ClientExceptionId.NoItemInStock, null, "itemName:" + itemName, "warehouseName:" + warehouseName);
                            }
                        }
                    }
                }
            }
        }
Example #14
0
        public override void Validate()
        {
            base.Validate();

            foreach (CommercialDocumentLine line in this.Lines.Children)
            {
                if (line.Attributes[DocumentFieldName.LineAttribute_GenerateDocumentOption] == null || line.Attributes[DocumentFieldName.LineAttribute_GenerateDocumentOption].Value.Value == String.Empty)
                {
                    throw new ClientException(ClientExceptionId.MissingLineAttribute, null, "ordinalNumber:" + line.OrdinalNumber.ToString(CultureInfo.InvariantCulture));
                }

                CommercialDocumentLine alternativeLine = line.AlternateVersion as CommercialDocumentLine;

                if (alternativeLine != null && alternativeLine.Attributes[DocumentFieldName.LineAttribute_GenerateDocumentOption].Value.Value !=
                    line.Attributes[DocumentFieldName.LineAttribute_GenerateDocumentOption].Value.Value &&
                    alternativeLine.Attributes[DocumentFieldName.LineAttribute_ServiceRealized] != null)
                {
                    throw new ClientException(ClientExceptionId.GenerateDocumentOptionAttriuteChangeError, null, "ordinalNumber:" + line.OrdinalNumber.ToString(CultureInfo.InvariantCulture));
                }

                var realizedAttr = line.Attributes[DocumentFieldName.LineAttribute_ServiceRealized];

                if (realizedAttr != null)
                {
                    decimal realized = Convert.ToDecimal(realizedAttr.Value.Value, CultureInfo.InvariantCulture);

                    if (line.Quantity < realized)
                    {
                        throw new ClientException(ClientExceptionId.QuantityBelowServiceRealized, null, "ordinalNumber:" + line.OrdinalNumber.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }

            CommercialDocument alternateDocument = this.AlternateVersion as CommercialDocument;

            if (alternateDocument != null)
            {
                var deletedRealized = alternateDocument.Lines.Children.Where(l => l.Status == BusinessObjectStatus.Deleted && l.Attributes[DocumentFieldName.LineAttribute_ServiceRealized] != null).FirstOrDefault();

                if (deletedRealized != null)
                {
                    throw new ClientException(ClientExceptionId.ServiceRealizedLineRemoval);
                }
            }

            if (this.Lines != null)
            {
                this.Lines.Validate();
            }

            if (this.VatTableEntries != null)
            {
                this.VatTableEntries.Validate();
            }

            if (this.ServiceDocumentEmployees != null)
            {
                this.ServiceDocumentEmployees.Validate();
            }

            if (this.ServiceDocumentServicePlaces != null)
            {
                this.ServiceDocumentServicePlaces.Validate();
            }

            if (this.ServiceDocumentServicedObjects != null)
            {
                this.ServiceDocumentServicedObjects.Validate();
            }
        }
Example #15
0
        internal static string TryGetOption(CommercialDocumentLine line)
        {
            DocumentLineAttrValue sogdoAttr = line.Attributes[DocumentFieldName.LineAttribute_SalesOrderGenerateDocumentOption];

            return(sogdoAttr == null ? null : sogdoAttr.Value.Value);
        }