public void CanCreate()
 {
     var invoice = new Invoices
         {
             price_currency = "BTC",
             base_price = 134.00f,
             base_price_currency = "USD",
             confirmations_required = 6,
             notification_level = "all",
             callback_url = "https://www.example.com/gocoin/callback",
             redirect_url = "https://www.example.com/redirect"
         };
     var result = Client.api.invoices.create(User.merchant_id, invoice);
     Assert.IsNotNullOrEmpty(result.id);
 }
Beispiel #2
0
        public static void CalculateInvoicePrices(Invoices entity, 
            out double totalPriceWithoutDiscountWithoutTax,
            out double totalPriceWithoutTax,
            out double totalPrice,
            out double summaryPrice)
        {
            totalPriceWithoutDiscountWithoutTax = 0;
            totalPriceWithoutTax = 0;
            totalPrice = 0;

            var allPositions = entity.InvoicePositions.Where(o => !o.DeleteDate.HasValue).ToList();

            //total price for positions
            foreach (var position in allPositions)
            {
                totalPriceWithoutDiscountWithoutTax += CalculatePositionPrice(position.Price, position.Amount, position.Payment);
            }
            
            summaryPrice = CalculateTaxesAndDiscount(entity.Discount, entity.TaxValue, entity.WithTaxes, entity.ManualPrice,
                ref totalPriceWithoutDiscountWithoutTax, ref totalPriceWithoutTax, ref totalPrice);
        }
Beispiel #3
0
        private string ReplaceInvoicePositions(Invoices invoice, List<InvoicePositions> positions, string xmlMainXMLDoc,
            string parentTag, string priceTag, string titleText, ref bool manualPricePrinted)
        {
            var xmlDoc = XDocument.Parse(xmlMainXMLDoc);
            var temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains(parentTag));
            var parentTableElement = GetParentElementByName(temp, "<w:tr ");

            if (parentTableElement != null)
            {
                var prevTableElem = parentTableElement;

                bool firstElem = true;

                foreach (var position in positions.Where(o => !o.DeleteDate.HasValue))
                {
                    double price = 0;
                    if (!invoice.ManualPrice.HasValue)
                    {
                        price = CalculationHelper.CalculatePositionPrice(position.Price, position.Amount, position.Payment);
                    }
                    else if (!manualPricePrinted)
                    {
                        price = invoice.ManualPrice.Value;
                        manualPricePrinted = true;
                    }

                    var description = String.Empty;
                    if (position.PositionId.HasValue)
                    {
                        description = String.Format("{0} x {1}", position.Amount, position.Positions.Description);
                    }
                    else if(position.TermPositionMaterialId.HasValue)
                    {
                        description = String.Format("{0} {1} {2}",
                            position.TermPositionMaterialRsp.Amount.HasValue ? position.TermPositionMaterialRsp.Amount.Value : 1,
                            position.TermPositionMaterialRsp.Materials.MaterialAmountTypes == MaterialAmountTypes.Item ? "x" : "Meter",
                            position.TermPositionMaterialRsp.Materials.Name);
                    }
                    else if(position.TermCostId.HasValue)
                    {
                        description = position.TermCosts.Name;
                    }


                    var rowElem = XElement.Parse(ReplaceFieldValue(
                        parentTableElement.ToString(), parentTag,
                            String.Format("{0}{1}", firstElem ? titleText : "", description)).
                        Replace(priceTag, price.ToString("N2")));
                    prevTableElem.AddAfterSelf(rowElem);
                    prevTableElem = rowElem;

                    if (firstElem)
                    {
                        firstElem = false;
                    }
                }

                parentTableElement.Remove();
            }

            return xmlDoc.Root.ToString();
        }
Beispiel #4
0
        private string ReplaceFooterTexts(string xmlMainXMLDoc, Orders order, Invoices invoice)
        {
            var xmlDoc = XDocument.Parse(xmlMainXMLDoc);
            var temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#PlanedPayDate"));
            var parentElement = GetParentElementByName(temp, "<w:tr ");

            var payDate = invoice.CreateDate.AddDays(invoice.PayInDays);

            //pay due information
            if (parentElement != null)
            {
                if (!String.IsNullOrEmpty(order.Customers.Iban) && !String.IsNullOrEmpty(order.Customers.Bic))
                {
                    temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#PayCashInterval"));
                    parentElement = GetParentElementByName(temp, "<w:tr ");
                    parentElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();

                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#PlanedPayDate",
                        invoice.IsSellInvoice ? String.Empty : String.Format("am {0}", payDate.ToShortDateString()));
                }
                else
                {
                    parentElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();

                    if (invoice.IsSellInvoice)
                    {
                        temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#PayCashInterval"));
                        parentElement = GetParentElementByName(temp, "<w:tr ");
                        parentElement.Remove();
                        xmlMainXMLDoc = xmlDoc.Root.ToString();
                    }
                    else
                    {
                        xmlMainXMLDoc = xmlMainXMLDoc.Replace("#PayCashInterval",
                            invoice.PayInDays == 0 ? "einem Tag" : String.Format("{0} Tage", invoice.PayInDays));
                    }
                }
            }


            //for sell Invoices
            xmlDoc = XDocument.Parse(xmlMainXMLDoc);
            temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#PayParts"));
            parentElement = GetParentElementByName(temp, "<w:tr ");

            if (parentElement != null)
            {
                if (invoice.IsSellInvoice)
                {
                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#PayParts",
                        String.Format("{0}% der Gesamtsumme bis {1} rein netto. {2}{3}% der Gesamtsumme nach Lieferung rein netto.",
                            invoice.PayPartOne.HasValue ? invoice.PayPartOne.Value : 75,
                            payDate.ToShortDateString(),
                            invoice.PayPartTwo.HasValue && invoice.PayPartTree.HasValue ?
                                String.Format("{0}% der Gesamtsumme bis {1} rein netto. ", invoice.PayPartTwo.Value,
                                payDate.AddDays(invoice.PayInDays).ToShortDateString()) : String.Empty,
                            invoice.PayPartTwo.HasValue && invoice.PayPartTree.HasValue ? invoice.PayPartTree.Value :
                                invoice.PayPartTwo.HasValue ? invoice.PayPartTwo.Value : 25
                        ));
                }
                else
                {
                    parentElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();
                }
            }


            //Invoice without taxe
            xmlDoc = XDocument.Parse(xmlMainXMLDoc);
            temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#InvoiceWithoutTaxes"));
            parentElement = GetParentElementByName(temp, "<w:tr ");

            if (parentElement != null)
            {
                if (!invoice.WithTaxes)
                {
                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#InvoiceWithoutTaxes", String.Empty);
                }
                else
                {
                    parentElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();
                }
            }

            return xmlMainXMLDoc;
        }
Beispiel #5
0
        public async Task <ActionResult <Invoices> > UpdateInvoice(int invoiceNumber, [FromBody] Invoices invoice)
        {
            try
            {
                if (invoiceNumber != invoice.InvoiceNumber)
                {
                    return(BadRequest("Invoice number mismatch"));
                }

                var invoiceToUpdate = await invoicesRepository.GetInvoice(invoiceNumber);

                if (invoiceToUpdate == null)
                {
                    return(NotFound($"Invoice with number = {invoiceNumber} cannot be found"));
                }

                return(await invoicesRepository.UpdateInvoice(invoice));
            }
            catch (Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Error updating invoice"));
            }
        }
Beispiel #6
0
        private string ReplaceFields(IOrdersManager ordersManager, int id, PrintTypes printType, string xmlMainXMLDoc,
            IInvoicesManager invoicesManager, ITaxesManager taxesManager, Invoices invoice = null,
            IInvoiceStornosManager invoiceStornosManager = null,
            ITransportOrdersManager transportOrdersManager = null,
            ITermsManager termsManager = null, 
            IEnumerable<Image> images = null)
        {
            string result = xmlMainXMLDoc;

            switch (printType)
            {
                case PrintTypes.Order:
                    var order = ordersManager.GetById(id);
                    result = ReplaceCommonFields(order, result);
                    result = ReplaceBaseOrderFields(order, result);

                    result = result.Replace("#SignatureDate", order.CreateDate.AddDays(2).ToShortDateString());

                    result = ReplaceRentPositions(order, result, taxesManager);
                    result = ReplaceTotalPrice(order, result, taxesManager);
                    result = ReplaceRentAdditionalCostPositions(order, result);
                    break;
                case PrintTypes.Offer:
                    order = ordersManager.GetById(id);
                    result = ReplaceCommonFields(order, result);
                    result = ReplaceBaseOfferFields(order, result);
                    result = ReplaceBaseOrderFields(order, result);
                    result = ReplaceRentPositions(order, result, taxesManager);
                    result = ReplaceRentAdditionalCostPositions(order, result);
                    break;
                case PrintTypes.Invoice:

                    if (invoice == null)
                    {
                        invoice = invoicesManager.GetById(id);
                    }

                    order = invoice.Orders;

                    result = ReplaceCommonFields(order, result);
                    result = ReplaceBaseOrderFields(order, result);
                    result = ReplaceBaseInvoiceFields(invoice, result, printType);

                    bool manualPricePrinted = false;
                    result = ReplaceInvoicePositions(invoice, invoice.InvoicePositions.ToList(), result,
                        "#PositionDescription", "#PositionPrice", "Leistungen: ", ref manualPricePrinted);

                    result = ReplaceInvoicePrices(invoice, result);
                    break;
                case PrintTypes.InvoiceStorno:

                    var invoiceStorno = invoiceStornosManager.GetById(id);
                    invoice = invoiceStorno.Invoices;
                    order = invoice.Orders;

                    result = ReplaceCommonFields(order, result);
                    result = ReplaceBaseOrderFields(order, result);
                    result = ReplaceBaseInvoiceFields(invoice, result, printType);
                    result = ReplaceInvoiceStornoPrices(invoiceStorno, result);

                    result = ReplaceFieldValue(result, "#FreeText", invoiceStorno.FreeText);

                    break;
                case PrintTypes.ReminderMail:

                    invoice = invoicesManager.GetById(id);
                    order = invoice.Orders;

                    result = ReplaceCommonFields(order, result);
                    result = ReplaceReminderPositions(invoice.InvoicePositions.ToList(), result);
                    result = ReplaceReminderTotalPrice(invoice, result, taxesManager);

                    break;
                case PrintTypes.DeliveryNote:

                    var term = termsManager.GetById(id);
                    result = ReplaceCommonFields(term.Orders, result);
                    result = ReplaceBaseOrderFields(term.Orders, result);

                    result = result.Replace("#DeliveryNoteType", "Lieferschein");
                    result = result.Replace("#DateType", "Liefertermin");
                    result = result.Replace("#AdressType", "Lieferanschrift");
                    result = result.Replace("#OrderNumber", term.Orders.OrderNumber);
                    
                    result = ReplacePositionWithDescription(term, result);


                    if (term.DeliveryNoteSignatures.Count != 0)
                    {
                        var doc = XDocument.Parse(result);
                        var signatureElement = doc.Descendants().FirstOrDefault(o => o.Value.Equals("#Signature",
                            StringComparison.InvariantCultureIgnoreCase));

                        if (signatureElement != null && images != null && images.Count() != 0)
                        {
                            var currentElement = signatureElement;
                            for (var i = 0; i < images.Count(); i++)
                            {
                                var image = images.ElementAt(images.Count() - i - 1);
                                //TODO doesnt work ((
                                //pkg.CreateRelationship(uri, TargetMode.Internal,
                                //    "Http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
                                //    "barcodeImageId");
                                
                                //insert image
                                XmlElement tagDrawing = GetImageTag(image.Width, image.Height,
                                    term.DeliveryNoteSignatures.Count - i);

                                signatureElement.AddAfterSelf(XDocument.Parse(tagDrawing.InnerXml).Root);
                            }

                            signatureElement.Remove();
                            result = doc.Root.ToString();
                        }
                        else
                        {
                            result = result.Replace("#Signature", String.Empty);
                        }
                    }
                    else
                    {
                        result = result.Replace("#Signature", String.Empty);
                    }

                    break;
                default:
                    throw new NotImplementedException();
            }

            return result;
        }
 /// <summary>
 /// Create a new Invoices object.
 /// </summary>
 /// <param name="customerName">Initial value of CustomerName.</param>
 /// <param name="salesperson">Initial value of Salesperson.</param>
 /// <param name="orderID">Initial value of OrderID.</param>
 /// <param name="shipperName">Initial value of ShipperName.</param>
 /// <param name="productID">Initial value of ProductID.</param>
 /// <param name="productName">Initial value of ProductName.</param>
 /// <param name="unitPrice">Initial value of UnitPrice.</param>
 /// <param name="quantity">Initial value of Quantity.</param>
 /// <param name="discount">Initial value of Discount.</param>
 public static Invoices CreateInvoices(string customerName, string salesperson, int orderID, string shipperName, int productID, string productName, decimal unitPrice, short quantity, float discount)
 {
     Invoices invoices = new Invoices();
     invoices.CustomerName = customerName;
     invoices.Salesperson = salesperson;
     invoices.OrderID = orderID;
     invoices.ShipperName = shipperName;
     invoices.ProductID = productID;
     invoices.ProductName = productName;
     invoices.UnitPrice = unitPrice;
     invoices.Quantity = quantity;
     invoices.Discount = discount;
     return invoices;
 }
Beispiel #8
0
    public static string ExportInvoices(Invoices currentInvoice, string addressFillInInvoice,
        string exportDirectory)
    {
        IPdfManager manager = new PdfManager();
        IPdfDocument document = null;
        IPdfPage page = null;
        if (WebConfig.UsedPredefinedInvoicePaperToPrintInvoice.Trim() == "true")
        {

            document = manager.OpenDocument(WebConfig.AbsolutePathPredefinedInvoicePaper, Missing.Value);
            page = document.Pages[1];
        }
        else
        {
            document = manager.CreateDocument(Missing.Value);
            page = document.Pages.Add(Missing.Value, Missing.Value, Missing.Value);

            ////////////////Draw logo and template///////////////////////////////////
            IPdfImage verticalLine = document.OpenImage(HttpContext.Current.Request.MapPath("~/images/neos-vertical-line.gif"), Missing.Value);
            IPdfParam verticalParam = manager.CreateParam(Missing.Value);
            verticalParam["x"].Value = 5;
            verticalParam["y"].Value = 0;
            verticalParam["ScaleX"].Value = 0.4f;
            //logoParam1["ScaleY"].Value = 0.8f;

            page.Canvas.DrawImage(verticalLine, verticalParam);

            IPdfImage logoImage = document.OpenImage(HttpContext.Current.Request.MapPath("~/images/logo_neos_new.gif"), Missing.Value);
            IPdfParam logoParam = manager.CreateParam(Missing.Value);
            logoParam["x"].Value = 20;
            logoParam["y"].Value = page.Height - 140;
            logoParam["ScaleX"].Value = 0.8f;
            logoParam["ScaleY"].Value = 0.8f;

            page.Canvas.DrawImage(logoImage, logoParam);

            string imageFooterPath = WebConfig.AbsolutePathImageFooterPath;
            if (!File.Exists(imageFooterPath))
            {
                imageFooterPath = HttpContext.Current.Request.MapPath("~/images/logo-neos-footer.gif");
            }
            IPdfImage footerImage = document.OpenImage(imageFooterPath, Missing.Value);
            IPdfParam footerParam = manager.CreateParam(Missing.Value);
            footerParam["x"].Value = 130;
            footerParam["y"].Value = 10;
            footerParam["ScaleX"].Value = 0.55f;
            footerParam["ScaleY"].Value = 0.55f;

            page.Canvas.DrawImage(footerImage, footerParam);
        }

        IPdfParam param = manager.CreateParam(Missing.Value);

        //Get invoice details and payments.
        IList<InvoiceDetails> detailList = new InvoiceDetailsRepository().GetInvoiceDetailsOfInvoice(
                                        currentInvoice.IdFactNumber, currentInvoice.IdTypeInvoice, currentInvoice.IdYear, null);
        CompanyAddress comAddress = new CompanyAddressRepository().FindOne(
            new CompanyAddress(currentInvoice.RefCustomerNumber.Value));

        //-----Do not show payment----------------//
        //IList<InvoicePayments> paymentList =
        //    new InvoicePaymentsRepository().GetInvoicePaymentsOfInvoice(
        //        currentInvoice.IdFactNumber, currentInvoice.IdTypeInvoice, currentInvoice.IdYear);
        //double paymentTotal = new InvoicePaymentsRepository().GetSumPaymentOfInvoice(
        //        currentInvoice.IdFactNumber, currentInvoice.IdTypeInvoice, currentInvoice.IdYear);

        //////////////// Draw Invoice title. ////////////////////////////////////
        //int height = 750;
        string title = currentInvoice.IdTypeInvoice == "I" ? ResourceManager.GetString("lblInvoiceInvoice") : ResourceManager.GetString("lblInvoiceCreditNote");
        title = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 12pt; font-weight: bold; color: black"">{0}</FONT>",
            title);
        page.Canvas.DrawText(title, "x=360, y=720, html=true", document.Fonts["Arial", Missing.Value]);

        ///////////////////////Draw Customers .///////////////////////////////////
        string companyName = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 12pt; font-weight: bold; color: black"">{0}</FONT>",
            (string.IsNullOrEmpty(comAddress.Name) ? "" : comAddress.Name));
        page.Canvas.DrawText(companyName, "x=320, y=650, html=true", document.Fonts["Arial", Missing.Value]);

        string coName = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            (string.IsNullOrEmpty(comAddress.Co) ? "" : comAddress.Co));
        page.Canvas.DrawText(coName, "x=320, y=635, html=true", document.Fonts["Arial", Missing.Value]);

        string companyAddr = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            (string.IsNullOrEmpty(comAddress.Address) ? "" : comAddress.Address));
        page.Canvas.DrawText(companyAddr, "x=320, y=620, html=true", document.Fonts["Arial", Missing.Value]);

        string companyCity = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            (string.IsNullOrEmpty(comAddress.ZipCode) ? "" : comAddress.ZipCode) + " " +
            (string.IsNullOrEmpty(comAddress.City) ? "" : comAddress.City));
        page.Canvas.DrawText(companyCity, "x=320, y=605, html=true", document.Fonts["Arial", Missing.Value]);

        string vatNumber = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            ResourceManager.GetString("lblInvoiceVATNumber") + " : "
            + (string.IsNullOrEmpty(comAddress.VatNumber) ? "" : comAddress.VatNumber));
        page.Canvas.DrawText(vatNumber, "x=320, y=575, html=true", document.Fonts["Arial", Missing.Value]);

        string invoiceNumber = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            ResourceManager.GetString("lblInvoiceNumber") + " : " + currentInvoice.IdFactNumber.ToString());
        page.Canvas.DrawText(invoiceNumber, "x=70, y=560, html=true", document.Fonts["Arial", Missing.Value]);

        string invoiceDate = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
            ResourceManager.GetString("lblInvoiceDate") + " : "
            + (currentInvoice.Date.HasValue ? currentInvoice.Date.Value.ToString("dd/MM/yyyy") : string.Empty));
        page.Canvas.DrawText(invoiceDate, "x=320, y=560, html=true", document.Fonts["Arial", Missing.Value]);

        ///////////////////Draw details//////////////////////////////////////
        int heightDetail = 15;
        for (int i = 0; i < detailList.Count; i++)
        {
            heightDetail += CountLineOfString(detailList[i].Description, 33) * 13;
        }

        string rowsDetail = ((int)(detailList.Count + 1)).ToString();
        string detailParam = "width=500;height=" + heightDetail + "; Rows=" + rowsDetail
            + "; Cols=4; cellborder=0.1; cellbordercolor = lightgray ; cellspacing=0; cellpadding=0";
        IPdfTable tableDetail = document.CreateTable(detailParam);
        tableDetail.Font = document.Fonts["Arial", Missing.Value];
        param.Set("alignment=left; size=10;");

        tableDetail.Rows[1].Cells[1].Width = 330;
        tableDetail.Rows[1].Cells[2].Width = 50;
        tableDetail.Rows[1].Cells[3].Width = 50;
        tableDetail.Rows[1].Cells[4].Width = 70;
        //tableDetail.Rows[1].Cells[5].Width = 50;
        //tableDetail.Rows[1].Cells[5].Width = 40;
        //tableDetail.Rows[1].Cells[6].Width = 50;
        //tableDetail.Rows[1].Cells[7].Width = 50;

        //New requirement (20-11-2009) : not show %VAT, VAT amuount and total
        tableDetail.Rows[1].Cells[1].AddText(ResourceManager.GetString("columnInvoiceDetailDescriptionHeader"), param, Missing.Value);
        tableDetail.Rows[1].Cells[2].AddText(ResourceManager.GetString("columnInvoiceDetailQuantityHeader"), param, Missing.Value);
        tableDetail.Rows[1].Cells[3].AddText(ResourceManager.GetString("columnInvoiceDetailUnitPriceHeader"), param, Missing.Value);
        tableDetail.Rows[1].Cells[4].AddText(ResourceManager.GetString("columnInvoiceDetailAmountHeader"), param, Missing.Value);
        //tableDetail.Rows[1].Cells[5].AddText(ResourceManager.GetString("columnInvoiceDetailCodeVATHeader"), param, Missing.Value);
        //tableDetail.Rows[1].Cells[5].AddText(ResourceManager.GetString("columnInvoiceDetailPercentVATHeader"), param, Missing.Value);
        //tableDetail.Rows[1].Cells[6].AddText(ResourceManager.GetString("columnInvoiceDetailAmountVATHeader"), param, Missing.Value);
        //tableDetail.Rows[1].Cells[7].AddText(ResourceManager.GetString("columnInvoiceDetailTotalAmountHeader"), param, Missing.Value);
        IPdfParam paramLeft = manager.CreateParam(Missing.Value);
        paramLeft.Set("alignment=right; size=10;");
        for (int i = 0; i < detailList.Count; i++)
        {
            InvoiceDetails detail = detailList[i];
            tableDetail.Rows[i + 2].Cells[1].Height = CountLineOfString(detail.Description, 33) * 13;
            tableDetail.Rows[i + 2].Cells[1].AddText(string.IsNullOrEmpty(detail.Description) ? "" : detail.Description, param, document.Fonts["Arial", Missing.Value]);
            tableDetail.Rows[i + 2].Cells[2].AddText(Get2DigitStringOfDouble(detail.Quantity), paramLeft, document.Fonts["Arial", Missing.Value]);
            tableDetail.Rows[i + 2].Cells[3].AddText(Get2DigitStringOfDouble(detail.UnitPriceEuro), paramLeft, document.Fonts["Arial", Missing.Value]);
            tableDetail.Rows[i + 2].Cells[4].AddText(Get2DigitStringOfDouble(detail.AmountEuro), paramLeft, document.Fonts["Arial", Missing.Value]);
            //tableDetail.Rows[i + 2].Cells[5].AddText(detail.VatCode.HasValue ? detail.VatCode.Value.ToString() : "", param, document.Fonts["Arial", Missing.Value]);
            //tableDetail.Rows[i + 2].Cells[5].AddText(detail.VatRate.HasValue ? detail.VatRate.Value.ToString() : "", param, document.Fonts["Arial", Missing.Value]);
            //tableDetail.Rows[i + 2].Cells[6].AddText(Get2DigitStringOfDouble(detail.AmountVAT), param, document.Fonts["Arial", Missing.Value]);
            //tableDetail.Rows[i + 2].Cells[7].AddText(Get2DigitStringOfDouble(detail.TotalAmountVAT), param, document.Fonts["Arial", Missing.Value]);
        }
        page.Canvas.DrawTable(tableDetail, "x=70, y=530");

        //////////////////Draw total of details/////////////////////////////////////////////////
        //string totalHVTA = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-weight: normal; color: black"">{0}</FONT>",
        //    ResourceManager.GetString("lblInvoiceTotalHTVA") + " : "
        //    + (currentInvoice.TotalHtvaEuro.HasValue ? currentInvoice.TotalHtvaEuro.Value.ToString() : "0"));
        //page.Canvas.DrawText(invoiceNumber, "x=70, y=575, html=true", document.Fonts["Arial", Missing.Value]);

        IPdfTable tableTotal = document.CreateTable("width=165;height=50; Rows=3; Cols=2; cellborder=0;  cellspacing=0; cellpadding=0");
        tableTotal.Font = document.Fonts["Arial", Missing.Value];
        param.Set("alignment=left; size=10;");
        tableTotal.Rows[1].Cells[1].Width = 85;
        tableTotal.Rows[1].Cells[2].Width = 80;

        tableTotal.Rows[1].Cells[1].AddText(ResourceManager.GetString("lblInvoiceTotalHTVA"), param, Missing.Value);
        tableTotal.Rows[1].Cells[2].AddText(": " + (Get2DigitStringOfDouble(currentInvoice.TotalHtvaEuro)), param, Missing.Value);

        tableTotal.Rows[2].Cells[1].AddText(ResourceManager.GetString("lblInvoiceTotalVAT"), param, Missing.Value);
        tableTotal.Rows[2].Cells[2].AddText(": " + (Get2DigitStringOfDouble(currentInvoice.AmountVatEuro)), param, Missing.Value);

        tableTotal.Rows[3].Cells[1].AddText(ResourceManager.GetString("lblInvoiceTotal"), param, Missing.Value);
        tableTotal.Rows[3].Cells[2].AddText(": " + (Get2DigitStringOfDouble(currentInvoice.TotalAmountIncludeVatEuro)), param, Missing.Value);

        int totalY = 530 - heightDetail - 20;
        if (!string.IsNullOrEmpty(comAddress.FactoringCode))
        {
            page.Canvas.DrawTable(tableTotal, "x=400, y=200");
        }
        else
        {
            page.Canvas.DrawTable(tableTotal, "x=400, y=145");
        }

        ///////////////Draw factoring code////////////////////////////////////
        if (!string.IsNullOrEmpty(currentInvoice.Remark))
        {
            int remarkHeight = CountLineOfString(currentInvoice.Remark, 33) * 13;
            string remarkParam = "width=300;height=" + remarkHeight + "; Rows=1; Cols=1; cellborder=0.0; cellbordercolor = lightgray ; cellspacing=0; cellpadding=0";
            IPdfTable tableRemark = document.CreateTable(remarkParam);
            tableRemark.Font = document.Fonts["Arial", Missing.Value];
            param.Set("alignment=left; size=10;");

            tableRemark.Rows[1].Cells[1].AddText(currentInvoice.Remark, param, Missing.Value);

            page.Canvas.DrawTable(tableRemark, "x=70, y=220");
        }

        ///////////////Draw factoring code////////////////////////////////////
        if (!string.IsNullOrEmpty(comAddress.FactoringCode))
        {
            //string factParam = "width=500;height=40; Rows=2; Cols=1; cellborder=0.0; cellbordercolor = lightgray ; cellspacing=0; cellpadding=0";
            //IPdfTable tableFact = document.CreateTable(factParam);
            //tableFact.Font = document.Fonts["Arial", Missing.Value];
            //param.Set("alignment=left; size=10;");
            string factoringCode1 = ResourceManager.GetString("MessagePrintFactoringCode1");
            string factoringCode2 = ResourceManager.GetString("MessagePrintFactoringCode2");
            factoringCode1 = string.Format(factoringCode1, comAddress.FactoringCode,
                currentInvoice.IdFactNumber, currentInvoice.IdYear.ToString().Substring(2, 2));
            //string factoringCode = ResourceManager.GetString("lblFactoringCode") + " : " + comAddress.FactoringCode.HasValue.ToString()
            //    + currentInvoice.IdFactNumber.ToString();
            //if (currentInvoice.Date.HasValue)
            //{
            //    factoringCode += currentInvoice.Date.Value.Year.ToString().Substring(2);
            //}
            //tableFact.Rows[1].Cells[1].Width = 470;
            //tableFact.Rows[1].Cells[1].AddText(factoringCode1, param, Missing.Value);
            //tableFact.Rows[2].Cells[1].AddText(factoringCode2, param, Missing.Value);
            //totalY = totalY - 100;
            //page.Canvas.DrawTable(tableFact, "x=70, y=140");

            factoringCode1 = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-style: Italic; font-weight: Normal; color: black"">{0}</FONT>",
                                                factoringCode1);
            page.Canvas.DrawText(factoringCode1, "x=70, y=120, html=true", document.Fonts["Arial", Missing.Value]);
            factoringCode2 = string.Format(@"<FONT STYLE=""font-family: Arial; font-size: 10pt; font-style: Italic; font-weight: Normal; color: black"">{0}</FONT>",
                                                factoringCode2);
            page.Canvas.DrawText(factoringCode2, "x=70, y=105, html=true", document.Fonts["Arial", Missing.Value]);
        }

        /*
        ////////////////////////////////Draw payments /////////////////////////////////
        totalY = totalY - 25;
        page.Canvas.DrawText(ResourceManager.GetString("tabInvoicePayment"), "x=70, y=" + totalY.ToString() + ", size=15;", document.Fonts["Helvetica", Missing.Value]);

        string heightPayment = ((int)(paymentList.Count * 12 + 20)).ToString();
        string rowsPayment = ((int)(paymentList.Count + 1)).ToString();
        string paymentParam = "width=500;height=" + heightPayment + "; Rows=" + rowsPayment
            + "; Cols=3; cellborder=0.1; cellbordercolor = lightgray ; cellspacing=0; cellpadding=0";
        IPdfTable tablePayment = document.CreateTable(paymentParam);
        tablePayment.Font = document.Fonts["Helvetica", Missing.Value];
        param.Set("alignment=left; size=10;");

        tablePayment.Rows[1].Cells[1].Width = 300;
        tablePayment.Rows[1].Cells[2].Width = 110;
        tablePayment.Rows[1].Cells[3].Width = 60;

        tablePayment.Rows[1].Cells[1].AddText(ResourceManager.GetString("columnInvoicePaymentRemarkHeader"), param, Missing.Value);
        tablePayment.Rows[1].Cells[2].AddText(ResourceManager.GetString("columnInvoicePaymentDateHeader"), param, Missing.Value);
        tablePayment.Rows[1].Cells[3].AddText(ResourceManager.GetString("columnInvoicePaymentAmountHeader"), param, Missing.Value);

        for (int i = 0; i < paymentList.Count; i++)
        {
            InvoicePayments payment = paymentList[i];
            tablePayment.Rows[i + 2].Cells[1].AddText(string.IsNullOrEmpty(payment.Remark) ? "" : payment.Remark, param, document.Fonts["Arial", Missing.Value]);
            tablePayment.Rows[i + 2].Cells[2].AddText(
                payment.DatePayment.HasValue ? payment.DatePayment.Value.ToString("dd/MM/yyyy") : "",
                param, document.Fonts["Courier", Missing.Value]);
            tablePayment.Rows[i + 2].Cells[3].AddText(
                payment.Amount.HasValue ? payment.Amount.Value.ToString() : "0",
                param, document.Fonts["Courier", Missing.Value]);
        }
        totalY = totalY - 20;
        page.Canvas.DrawTable(tablePayment, "x=70, y=" + totalY.ToString());

        totalY = totalY - int.Parse(heightPayment) - 5;

        ////////////////////Draw total of payment///////////////////////////////////////////
        page.Canvas.DrawText(ResourceManager.GetString("labelTotalInvoicePaymentAmount"), "x=70, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);
        page.Canvas.DrawText(paymentTotal.ToString(), "x=480, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);

        totalY = totalY - 15;
        double remain = 0;
        if (currentInvoice.TotalAmountIncludeVatEuro.HasValue)
        {
            remain = currentInvoice.TotalAmountIncludeVatEuro.Value - paymentTotal;
        }
        else
        {
            remain = -paymentTotal;
        }
        page.Canvas.DrawText(ResourceManager.GetString("labelTotalInvoiceRemainAmount"), "x=70, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);
        page.Canvas.DrawText(remain.ToString(), "x=480, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);

        totalY = totalY - 15;
        if (currentInvoice.Payement.HasValue && currentInvoice.Payement.Value && currentInvoice.DateOfPayement.HasValue)
        {
            page.Canvas.DrawText(ResourceManager.GetString("labelTotalInvoicePaid"), "x=70, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);
            page.Canvas.DrawText(currentInvoice.DateOfPayement.Value.ToString("dd/MM/yyyy"), "x=370, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);
        }
        else
        {
            page.Canvas.DrawText(ResourceManager.GetString("labelTotalInvoiceUnpaid"), "x=70, y=" + totalY.ToString() + ", size=10;", document.Fonts["Helvetica", Missing.Value]);
        }
        */

        /////// Save document, the Save method returns generated file name///////////////
        string fileName = exportDirectory + "\\";
        //string fileName = string.Empty;
        if (currentInvoice.IdTypeInvoice == "I")
            fileName += "Invoice";
        else
            fileName += "Credit Note";
        fileName += "-" + currentInvoice.IdFactNumber.ToString() + currentInvoice.IdTypeInvoice + currentInvoice.IdYear;
        fileName += "-" + DateTime.Today.Year;
        if (DateTime.Today.Month < 10)
        {
            fileName += "0";
        }
        fileName += DateTime.Today.Month;
        if (DateTime.Today.Day < 10)
        {
            fileName += "0";
        }
        fileName += DateTime.Today.Day + ".pdf";
        //fileName = "attachment;filename=" + fileName;
        string strFilename = document.Save(fileName, true);
        //document.SaveHttp(fileName, Missing.Value);
        return fileName;
    }
Beispiel #9
0
 public ActionResult AddInvoice(Invoices invoice)
 {
     repository.AddInvoice(invoice);
     return(RedirectToAction("Index"));
 }
Beispiel #10
0
 public IEnumerable <Invoice> Create(IEnumerable <Invoice> items)
 {
     return(Invoices.Create(items));
 }
        private void SaveInvoice(object sender, RoutedEventArgs e)
        {
            Invoices newInvoice = new Invoices()
            {
                email        = selectedEmail,
                CouponUsed   = SelectedCoupon.Name,
                Nazwa_firmy  = this.FirmaTxtBox.Text,
                Imie         = this.ImieTxtBox.Text,
                Nazwisko     = this.NazwiskoTxtBox.Text,
                Ulica        = this.UlicaTxtBox.Text,
                Numer        = this.NumberTxtBox.Text,
                Miasto       = this.MiastoTxtBox.Text,
                Kod_pocztowy = this.KodTxtBox.Text,
                Standardowe  = double.Parse(this.StandardowetxtBox.Text),
                Zwoskiem     = double.Parse(this.woskiemTxtBx.Text),
                TotalPrice   = totalPrice,
            };

            if (SelectedCoupon != null)
            {
                if (SelectedCoupon.Name == "Mycie Standardowe")
                {
                    if (int.Parse(StandardowetxtBox.Text) > 0)
                    {
                        newInvoice.TotalPrice -= mycie_stand;
                        if (newInvoice.TotalPrice < 0)
                        {
                            newInvoice.TotalPrice = 0;
                        }

                        string command = $"delete from Coupon where id in ( select id FROM Coupon where name='Mycie Standardowe' AND  Owner='{couponOwner}'  Limit 1 )";
                        using (SQLiteConnection connection = new SQLiteConnection(App.databasePath))
                        {
                            SQLiteCommand cm = new SQLiteCommand(connection);
                            cm.CommandText = command;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
                else
                {
                    if (int.Parse(woskiemTxtBx.Text) > 0)
                    {
                        newInvoice.TotalPrice -= mycie_wosk;
                        if (newInvoice.TotalPrice < 0)
                        {
                            newInvoice.TotalPrice = 0;
                        }

                        string command = $"delete from Coupon where id in ( select id FROM Coupon where name='Mycie Woskiem' AND  Owner='{couponOwner}'  Limit 1 )";
                        using (SQLiteConnection connection = new SQLiteConnection(App.databasePath))
                        {
                            SQLiteCommand cm = new SQLiteCommand(connection);
                            cm.CommandText = command;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }

            if (newInvoice.TotalPrice != 0)
            {
                newInvoice.TotalPrice = Math.Truncate(newInvoice.TotalPrice * 100) / 100;
            }

            using (SQLiteConnection conn = new SQLiteConnection(App.databasePath))
            {
                conn.CreateTable <Invoices>();
                conn.Insert(newInvoice);
            }

            this.FirmaTxtBox.Text          = "";
            this.ImieTxtBox.Text           = "";
            this.NazwiskoTxtBox.Text       = "";
            this.UlicaTxtBox.Text          = "";
            this.NumberTxtBox.Text         = "";
            this.MiastoTxtBox.Text         = "";
            this.KodTxtBox.Text            = "";
            this.StandardowetxtBox.Text    = "";
            this.woskiemTxtBx.Text         = "";
            CustomersComboBox.SelectedItem = customerList[0];

            double standard_point, woskiem_point;

            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(App.databasePath))
            {
                standard_point = connection.Table <ProgramLojalnościowy>().Select(s => s.mycie_standardowe).FirstOrDefault();
                woskiem_point  = connection.Table <ProgramLojalnościowy>().Select(s => s.mycie_z_woskiem).FirstOrDefault();
            }

            Konto AccountToUpdate = new Konto();

            using (SQLite.SQLiteConnection connection = new SQLite.SQLiteConnection(App.databasePath))
            {
                AccountToUpdate = connection.Table <Konto>().FirstOrDefault(a => a.Email == selectedEmail);
            }

            AccountToUpdate.Points += ((int)standard_point * (int)newInvoice.Standardowe) + ((int)woskiem_point * (int)newInvoice.Zwoskiem);

            using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.databasePath))
            {
                conn.CreateTable <Konto>();
                conn.InsertOrReplace(AccountToUpdate);
            }

            MessageBox.Show("Faktura dodana.");
            MainWindow mainwindow = new MainWindow(_loggedInAccount);

            mainwindow.Show();
            this.Close();
        }
Beispiel #12
0
        /// <summary>
        /// Przycisk dodający nową pozycje do bazy danych
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string   name          = textBoxName.Text;
            string   lastName      = textBoxLastName.Text;
            string   productName   = textBoxProductName.Text;
            int      quantity      = 0;
            int      price         = 0;
            int      invoiceNumber = 0;
            DateTime dateOfIssue   = DateTime.Now;

            try
            {
                quantity      = Int32.Parse(textBoxQuantity.Text);
                price         = Int32.Parse(textBoxPrice.Text);
                invoiceNumber = Int32.Parse(textBoxInvoiceNumber.Text);
            }
            catch
            {
                MessageBox.Show("Wprowadź poprawne wartości! ");
            }

            //Sprawdzanie,czy są podane przez używkownika wszystkie wymagane pola.
            //Jest to wymagane, ponieważ użyto [Required] przy polach klasy
            if (name != String.Empty && lastName != String.Empty && productName != String.Empty)
            {
                Orders newOrder = new Orders()
                {
                    ProductName = productName,
                    Quantity    = quantity,
                    Price       = price,
                };
                Order.Create(newOrder);
                int myId = newOrder.Id;

                Customers newCustomer = new Customers()
                {
                    Name     = name,
                    LastName = lastName,
                    OrderId  = myId
                };
                Customer.Create(newCustomer);

                int customerId = newCustomer.Id;
                MessageBox.Show(dateOfIssue.ToString());
                Invoices newInvoice = new Invoices()
                {
                    InvoiceNumber = invoiceNumber,
                    DateOfIssue   = dateOfIssue,
                    CustomerId    = customerId
                };
                Invoice.Create(newInvoice);

                //komunikat informujący o dodaniu informacji
                MessageBox.Show("Dodano");
                //odświeżenie dataGridView
                GetAllDataAboutInvoicesToDataGridView();
            }
            else
            {
                //komunikat, ze dane sa zle
                MessageBox.Show("Wprowadź poprawne wartości! ");
            }
        }
        public async Task <ActionResult <InvoicesDTO> > addItem(int inInvoiceID, int inProductOptionID, int inQuantity)
        {
            Invoices invoice = await db.Invoices.FindAsync(inInvoiceID);

            if (invoice == null)
            {
                return(new JsonResult(new { Status = "error", Message = "No Invoices With The Id: " + inInvoiceID }));
            }

            ProductOptions prodOpt = await db.ProductOptions.FindAsync(inProductOptionID);

            if (prodOpt == null)
            {
                return(new JsonResult(new { Status = "error", Message = "No Product Option With The Id: " + inProductOptionID }));
            }

            Products prod = await db.Products.FindAsync(prodOpt.ProductID);

            if (prod == null)
            {
                return(new JsonResult(new { Status = "error", Message = "No Product With The Id: " + prodOpt.ProductID }));
            }

            prodOpt.Product = prod;

            if (inQuantity < 1)
            {
                return(new JsonResult(new { Status = "error", Message = "Quantity Can't be less than 1" }));
            }


            InvoiceItems invoiceItems = new InvoiceItems
            {
                InvoiceID         = invoice.Id,
                ProductOptionID   = prodOpt.Id,
                prod_name         = prodOpt.Product.name,
                prod_desc         = prodOpt.Product.desc,
                prod_region       = prodOpt.Product.region,
                prod_roast        = prodOpt.Product.roast,
                prod_altitude_max = prodOpt.Product.altitude_max,
                prod_altitude_min = prodOpt.Product.altitude_min,
                prod_bean_type    = prodOpt.Product.bean_type,
                prod_image_url    = prodOpt.Product.image_url,
                opt_price         = prodOpt.price,
                opt_weight        = prodOpt.weight,
                quantity          = inQuantity
            };

            db.InvoiceItems.Add(invoiceItems);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception e)
            {
                return(new JsonResult(new { Status = "error", Message = "Error adding item to invoice" }));
            }

            try
            {
                updateTotalInvoice(invoice.Id, invoiceItems.opt_price, invoiceItems.quantity);
            }
            catch (Exception e)
            {
                return(new JsonResult(new { Status = "error", Message = e }));
            }

            InvoicesDTO invcDTO = new InvoicesDTO
            {
                Id                  = invoice.Id,
                total               = invoice.total,
                UserID              = invoice.UserID,
                discount_code       = invoice.discount_code,
                discount_percentage = invoice.discount_percentage,
                isFreeShipping      = invoice.isFreeShipping,
                tax                 = invoice.tax,
                created_at          = invoice.created_at,
                updated_at          = invoice.created_at
            };

            InvoiceItemsDTO invoiceItemsDTO = new InvoiceItemsDTO
            {
                Id                = invoiceItems.Id,
                InvoiceID         = invoice.Id,
                ProductOptionID   = prodOpt.Id,
                prod_name         = prodOpt.Product.name,
                prod_desc         = prodOpt.Product.desc,
                prod_region       = prodOpt.Product.region,
                prod_roast        = prodOpt.Product.roast,
                prod_altitude_max = prodOpt.Product.altitude_max,
                prod_altitude_min = prodOpt.Product.altitude_min,
                prod_bean_type    = prodOpt.Product.bean_type,
                prod_image_url    = prodOpt.Product.image_url,
                opt_price         = prodOpt.price,
                opt_weight        = prodOpt.weight,
                quantity          = inQuantity
            };

            if (invcDTO.invoiceItems == null)
            {
                List <InvoiceItemsDTO> tempList = new List <InvoiceItemsDTO>();
                tempList.Add(invoiceItemsDTO);
                invcDTO.invoiceItems = tempList;
            }
            else
            {
                invcDTO.invoiceItems.Add(invoiceItemsDTO);
            }

            return(new JsonResult(new { Status = "success", Message = invcDTO }));
        }
Beispiel #14
0
 protected virtual void ClearNavigationProperties()
 {
     Devices.Clear();
     Invoices.Clear();
 }
Beispiel #15
0
    public static string ExportInvoicesTemplate(Invoices currentInvoice, string addressFillInInvoice,
        string exportDirectory)
    {
        IPdfManager manager = new PdfManager();
        IPdfDocument document = null;
        IPdfPage page = null;

        document = manager.CreateDocument(Missing.Value);
        page = document.Pages.Add(Missing.Value, Missing.Value, Missing.Value);

        ////////////////Draw logo and template///////////////////////////////////
        IPdfImage verticalLine = document.OpenImage(HttpContext.Current.Request.MapPath("~/images/neos-vertical-line.gif"), Missing.Value);
        IPdfParam verticalParam = manager.CreateParam(Missing.Value);
        verticalParam["x"].Value = 5;
        verticalParam["y"].Value = 0;
        verticalParam["ScaleX"].Value = 0.4f;
        //logoParam1["ScaleY"].Value = 0.8f;

        page.Canvas.DrawImage(verticalLine, verticalParam);

        IPdfImage logoImage = document.OpenImage(HttpContext.Current.Request.MapPath("~/images/logo_neos_new.gif"), Missing.Value);
        IPdfParam logoParam = manager.CreateParam(Missing.Value);
        logoParam["x"].Value = 20;
        logoParam["y"].Value = page.Height - 140;
        logoParam["ScaleX"].Value = 0.8f;
        logoParam["ScaleY"].Value = 0.8f;

        page.Canvas.DrawImage(logoImage, logoParam);

        string imageFooterPath = WebConfig.AbsolutePathImageFooterPath;
        if (!File.Exists(imageFooterPath))
        {
            imageFooterPath = HttpContext.Current.Request.MapPath("~/images/logo-neos-footer.gif");
        }
        IPdfImage footerImage = document.OpenImage(imageFooterPath, Missing.Value);
        IPdfParam footerParam = manager.CreateParam(Missing.Value);
        footerParam["x"].Value = 130;
        footerParam["y"].Value = 10;
        footerParam["ScaleX"].Value = 0.55f;
        footerParam["ScaleY"].Value = 0.55f;

        page.Canvas.DrawImage(footerImage, footerParam);

        string fileName = "C:\\Temp\\Invoice-Template.pdf";
        string strFilename = document.Save(fileName, true);
        //document.SaveHttp(fileName, Missing.Value);
        return fileName;
    }
Beispiel #16
0
 public Invoice Update(Invoice item)
 {
     return(Invoices.Update(item));
 }
Beispiel #17
0
 public ActionResult EditInvoice(Invoices Invoice, int id)
 {
     repository.EditInvoice(Invoice, id);
     return(RedirectToAction("Index"));
 }
Beispiel #18
0
 public Task <Invoice> CreateAsync(Invoice item)
 {
     return(Invoices.CreateAsync(item));
 }
Beispiel #19
0
 public int Update(Invoices input)
 {
     return(invoiceAccess.Update(input));
 }
Beispiel #20
0
 public Invoice Create(Invoice item)
 {
     return(Invoices.Create(item));
 }
Beispiel #21
0
        public static decimal?RedistributeValueCotaIndivizaForSpecificApartments(Apartments apartment, Invoices invoice, List <Apartments> apartments)
        {
            decimal?sumOfIndiviza = apartments.Sum(t => t.CotaIndiviza);
            decimal?result        = null;

            if (invoice != null)
            {
                decimal?allInvoicesSum = invoice.Value;
                result = (sumOfIndiviza != null && allInvoicesSum.HasValue && sumOfIndiviza.Value != 0)
                ? (allInvoicesSum.Value * apartment.CotaIndiviza) / sumOfIndiviza.Value
                : null;
            }

            return(result);
        }
 public Status EP_GetPaidInvoices(string mer_no, string pass, string order, out Invoices invoices)
 {
     object[] results = this.Invoke("EP_GetPaidInvoices", new object[] {
             mer_no,
             pass,
             order});
     invoices = ((Invoices)(results[1]));
     return ((Status)(results[0]));
 }
Beispiel #23
0
 public async Task <IEnumerable <Invoice> > CreateAsync(IEnumerable <Invoice> items)
 {
     return(await Invoices.CreateAsync(items));
 }
Beispiel #24
0
        public async Task <IActionResult> PostProceedToCheckOutDetails(List <OrderDetailsModel> OrderDetails)
        {
            try
            {
                AutoGenerateNumber _serviceGenAutoNum = new AutoGenerateNumber();
                //Ref order status code
                int orderStatusCode       = Convert.ToInt32(_serviceGenAutoNum.GenStatusCode());
                var Ref_Order_Status_Code = new RefOrderStatusCodes()
                {
                    OrderStatusCode        = orderStatusCode,
                    OrderStatusDescription = "Completed"
                };
                await _context.RefOrderStatusCodes.AddAsync(Ref_Order_Status_Code);

                await _context.SaveChangesAsync();

                //order
                DateTime orderDate = DateTime.Now;
                string   address   = (from u in _context.UserDetails
                                      where u.UserId == Convert.ToInt32(OrderDetails[0].UserId)
                                      select u.Address).Single();
                var order_details = new Orders()
                {
                    DateOrderPlaced     = orderDate,
                    LocationOrderPlaced = address,
                    UserId          = Convert.ToInt32(OrderDetails[0].UserId),
                    OrderStatusCode = orderStatusCode
                };
                await _context.Orders.AddAsync(order_details);

                await _context.SaveChangesAsync();

                //Ref Order Item Status Code
                int itemStatusCode             = Convert.ToInt32(_serviceGenAutoNum.GenItemStatusCode());
                var ref_order_item_status_code = new RefOrderItemStatusCodes()
                {
                    OrderItemStatusCode        = itemStatusCode,
                    OrderItemStatusDescription = "Delivered"
                };
                await _context.RefOrderItemStatusCodes.AddAsync(ref_order_item_status_code);

                await _context.SaveChangesAsync();

                //Order Item
                var pCode     = OrderDetails.Select(p => p.ProductCode).ToList();
                var productId = (from p in _context.Products
                                 where pCode.Contains(p.ProductCode)
                                 select p.ProductId).ToList();
                Orders orders = new Orders()
                {
                    OrderId = _context.Orders
                              .FirstOrDefault(o => o.OrderStatusCode == orderStatusCode).OrderId
                };
                List <OrderItems> orderItemsList = new List <OrderItems>();
                for (int i = 0; i < OrderDetails.Count; i++)
                {
                    orderItemsList.Add(
                        new OrderItems
                    {
                        OrderItemQnt        = Convert.ToInt32(OrderDetails[i].ProductQuantity),
                        OrderItemPrice      = Convert.ToDecimal(OrderDetails[i].ProductPrice),
                        TotalAmount         = Convert.ToDecimal(OrderDetails[0].TotalAmount),
                        ProductId           = productId[i],
                        OrderId             = orders.OrderId,
                        OrderItemStatusCode = itemStatusCode
                    });
                }
                foreach (var orderItem in orderItemsList)
                {
                    await _context.OrderItems.AddAsync(orderItem);

                    await _context.SaveChangesAsync();
                }

                //Ref Invoice Status Code
                int invoiceStatusCode       = Convert.ToInt32(_serviceGenAutoNum.GenInvoiceStatusCode());
                var ref_invoice_status_code = new RefInvoiceStatusCode()
                {
                    InvoiceStatusCode = invoiceStatusCode,
                    InvoiceStatusDesc = "Issued"
                };
                await _context.RefInvoiceStatusCodes.AddAsync(ref_invoice_status_code);

                await _context.SaveChangesAsync();

                //Invoice
                string   invoiceNumber = _serviceGenAutoNum.GenInvoiceNumber();
                DateTime invoiceDate   = DateTime.Now;
                //List<Invoices> invoiceList = new List<Invoices>();
                //for (int i = 0; i < OrderDetails.Count; i++)
                //{
                //    invoiceList.Add(
                //        new Invoices
                //        {
                //            InvoiceNumber = invoiceNumber,
                //            InvoiceDate = invoiceDate,
                //            ItemName = OrderDetails[i].ProductTitle,
                //            ItemPrice = Convert.ToDecimal(OrderDetails[i].ProductPrice),
                //            TotalAmount = Convert.ToDecimal(OrderDetails[i].TotalAmount),
                //            OrderId = orders.OrderId,
                //            InvoiceStatusCode = invoiceStatusCode
                //        });
                //}
                var invoice_details = new Invoices()
                {
                    InvoiceNumber     = invoiceNumber,
                    InvoiceStatusCode = invoiceStatusCode,
                    InvoiceDate       = invoiceDate,
                    OrderId           = orders.OrderId
                };
                await _context.Invoices.AddAsync(invoice_details);

                await _context.SaveChangesAsync();

                return(Ok(orderStatusCode));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 /// <remarks/>
 public Status EndEP_GetPaidInvoices(System.IAsyncResult asyncResult, out Invoices invoices)
 {
     object[] results = this.EndInvoke(asyncResult);
     invoices = ((Invoices)(results[1]));
     return ((Status)(results[0]));
 }
 public Invoices_CurrentInvoiceRemindersToSend()
 {
     this.Results = Invoices.CurrentInvoiceRemindersToSend();
 }
Beispiel #27
0
 public InvoiceStateDto GetById(Guid id)
 {
     return(Invoices.AsQueryable <InvoiceStateDto>()
            .Single(c => c.Id == id));
 }
Beispiel #28
0
        private string ReplaceReminderTotalPrice(Invoices invoice, string xmlMainXMLDoc, ITaxesManager taxesManager)
        {
            if (invoice.InvoicePositions != null && invoice.InvoicePositions.Count != 0)
            {
                double totalPriceWithoutDiscountWithoutTax = 0;
                double totalPriceWithoutTax = 0;
                double totalPrice = 0;
                double summaryPrice = 0;

                CalculationHelper.CalculateInvoicePrices(invoice, out totalPriceWithoutDiscountWithoutTax, out totalPriceWithoutTax,
                    out totalPrice, out summaryPrice);

                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TotalPrice", summaryPrice.ToString("N2"));
            }
            else
            {
                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TotalPrice", String.Empty);
            }

            return xmlMainXMLDoc;
        }
Beispiel #29
0
 public void Save(InvoiceStateDto invoice)
 {
     Invoices.Save(invoice);
 }
Beispiel #30
0
        private string ReplaceBaseInvoiceFields(Invoices invoice, string xmlMainXMLDoc, PrintTypes printType)
        {
            var order = invoice.Orders;

            if (printType == PrintTypes.InvoiceStorno)
            {
                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#InvoiceType", "Gutschrift");
            }
            else
            {
                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#InvoiceType", "Rechnung");
            }

            xmlMainXMLDoc = xmlMainXMLDoc.Replace("#InvoiceNumber", invoice.InvoiceNumber);
            xmlMainXMLDoc = xmlMainXMLDoc.Replace("#InvoiceDate", invoice.CreateDate.ToShortDateString());
            
            xmlMainXMLDoc = xmlMainXMLDoc.Replace("#OrderNumber", order.OrderNumber);

            xmlMainXMLDoc = ReplaceUstId(xmlMainXMLDoc, order);
            
            xmlMainXMLDoc = ReplaceFooterTexts(xmlMainXMLDoc, order, invoice);

            return xmlMainXMLDoc;
        }               
        public static void ImportDataFedEx(String fileName, String fullPath)
        {
            //ALS: no db...
            //ClientsDataClassesDataContext clientdb = new ClientsDataClassesDataContext();
            //FreightBillDataClassesDataContext fbdb = new FreightBillDataClassesDataContext();

            //initialize tracking number (column 6) and loop until the number changes
            String FBInvoiceNumber = String.Empty;
            String TrackingNumber  = String.Empty;

            // get total from the K column - used for validation - it equals the total invoice amount
            Decimal TotalInvoice         = 0;
            Decimal TotalInvoiceValidate = 0;

            //calulate this Fridays date
            var      today      = DateTime.Today;
            var      startDay   = ((int)today.DayOfWeek);
            DateTime thisFriday = today.AddDays(5 - startDay);

            DateTime?WeekendingDate = thisFriday;
            DateTime?BatchDate      = today; //Maxine 9/9/2015 changed the batch date from friday to date of import
            DateTime?InvoiceDate    = thisFriday;
            DateTime DueDate        = thisFriday;
            String   InvoiceNumber  = String.Format("{0}HOP10", thisFriday.ToString("MMddyy")); //.Replace("/", ""));

            // init the variables
            String  RecipentNumber    = String.Empty;
            String  CarrierAcctNumber = String.Empty;
            String  InvTypeCode       = String.Empty;
            String  InvDetailCode     = String.Empty;
            String  ProDate           = String.Empty;
            String  Ref1              = String.Empty;
            String  Ref2              = String.Empty;
            String  Ref3              = String.Empty;
            String  PayCode           = String.Empty;
            int     Pieces            = 0;
            String  ProNumber         = String.Empty;
            int     ActualWeight      = 0;
            int     BilledWeight      = 0;
            String  ChargeClassCode   = String.Empty;
            String  ProTransNote      = String.Empty;
            Decimal PayAmount         = 0;
            String  ShipperName       = String.Empty;
            String  ShipperAddress1   = String.Empty;
            String  ShipperAddress2   = String.Empty;
            String  ShipperCity       = String.Empty;
            String  ShipperState      = String.Empty;
            String  ShipperZip        = String.Empty;
            String  ShipperCountry    = String.Empty;
            String  ConsigneeName     = String.Empty;
            String  ConsigneeAddress1 = String.Empty;
            String  ConsigneeAddress2 = String.Empty;
            String  ConsigneeCity     = String.Empty;
            String  ConsigneeState    = String.Empty;
            String  ConsigneeZip      = String.Empty;
            String  ConsigneeCountry  = String.Empty;
            Decimal FSC          = 0;
            String  LoadCode     = String.Empty;
            String  ErrorCode    = String.Empty;
            String  Status       = String.Empty;
            String  GLCode       = String.Empty;
            String  SLCode       = String.Empty;
            String  ServiceLevel = String.Empty;

            //fullPath = String.Format("{0}{1}", fullPath, fileName);
            CsvFileClass.CsvFile[] CsvFile;
            var f = File.ReadAllLines(fullPath);

            int lCount = f.Length;

            CsvFile = new CsvFileClass.CsvFile[lCount];

            using (CsvFileReader reader = new CsvFileReader(fullPath))
            {
                bool hasRow = true;
                int  i      = 0;

                TotalInvoiceValidate = 0;

                CsvRow row = new CsvRow();
                if (row.Count() == 0)
                {
                    reader.ReadRow(row);
                }

                else
                {
                    reader.ReadRow(row);
                }

                while (hasRow)
                {
                    CsvFile[i] = new CsvFileClass.CsvFile
                    {
                        // row array is zero base...
                        //RecipentNumber = Convert.ToString(row[1]),
                        AccountNumber = Convert.ToString(row[0]),
                        //InvTypeCode = Convert.ToString(row[6]),
                        //InvDetailCode = Convert.ToString(row[7]),
                        ProDate      = Convert.ToString(row[13]),
                        Ref1         = Convert.ToString(row[48]),
                        Ref2         = Convert.ToString(row[49]),
                        Ref3         = Convert.ToString(row[50]),
                        PayCode      = Convert.ToString(row[17]),
                        Pieces       = Convert.ToString(row[18]),
                        ProNumber    = Convert.ToString(row[20]),
                        ActualWeight = Convert.ToString(row[26].ToString()),
                        BilledWeight = Convert.ToString(row[28].ToString()),
                        //ChargeClassCode = Convert.ToString(row[43]),
                        //ProTransNote = Convert.ToString(row[45]),
                        //FSCCheck = Convert.ToString(row[43]),
                        PayAmount   = Convert.ToString(row[10].ToString()), // bill and pay amounts
                        ShipperName = Convert.ToString(row[40]),
                        //ShipperAddress1 = Convert.ToString(row[68]),
                        //ShipperAddress2 = Convert.ToString(row[69]),
                        ShipperCity  = Convert.ToString(row[444]),
                        ShipperState = Convert.ToString(row[45]),
                        ShipperZip   = Convert.ToString(row[46]),
                        //ShipperCountry = Convert.ToString(row[73]),
                        ConsigneeName = Convert.ToString(row[33]),
                        //ConsigneeAddress1 = Convert.ToString(row[76]),
                        //ConsigneeAddress2 = Convert.ToString(row[77]),
                        ConsigneeCity  = Convert.ToString(row[36]),
                        ConsigneeState = Convert.ToString(row[37]),
                        ConsigneeZip   = Convert.ToString(row[38]),
                        //ErrorCodeCheck = Convert.ToString(row[2]),
                        PaymentType = Convert.ToString(row[6]),
                        //TotalInvoice = Convert.ToString(row[10]),
                        PieceCount = Convert.ToString(row[22])
                                     // FBInvoiceNumber = Convert.ToString(row[5])
                    };
                    i++;

                    //get the next row

                    hasRow = reader.ReadRow(row);
                }
            }

            CsvFile = CsvFile.AsEnumerable().OrderBy(l => l.FBInvoiceNumber).ThenBy(l => l.ProNumber).ToArray();

            TotalInvoiceValidate = 0;
            for (var i = 0; i < CsvFile.Length; i++)
            {
                if (TrackingNumber != CsvFile[i].ProNumber)

                {
                    TrackingNumber = CsvFile[i].ProNumber;
                    //new tracking number reset variables
                    PayAmount    = 0;
                    ActualWeight = 0;
                    BilledWeight = 0;
                    Pieces       = 0;
                    FSC          = 0;
                }

                if (TotalInvoice != TotalInvoiceValidate && FBInvoiceNumber != CsvFile[i].FBInvoiceNumber)
                {
                    writelog(String.Format("VALIDATION ERROR! Total Invoice {0} is not equal to all of the records {1} for Invoice Number {2}", TotalInvoice, TotalInvoiceValidate, FBInvoiceNumber));
                }

                TotalInvoice = Convert.ToDecimal(CsvFile[i].TotalInvoice);
                if (FBInvoiceNumber != CsvFile[i].FBInvoiceNumber)
                {
                    FBInvoiceNumber      = CsvFile[i].FBInvoiceNumber;
                    TotalInvoiceValidate = 0;
                }

                while (i < CsvFile.Length && TrackingNumber == CsvFile[i].ProNumber && FBInvoiceNumber == CsvFile[i].FBInvoiceNumber)
                {
                    //RecipentNumber = CsvFile[i].RecipentNumber;
                    //CarrierAcctNumber = CsvFile[i].AccountNumber;
                    //InvTypeCode = CsvFile[i].InvTypeCode;
                    //InvDetailCode = CsvFile[i].InvDetailCode;
                    ProDate = CsvFile[i].ProDate;
                    Ref1    = CsvFile[i].Ref1;
                    Ref2    = CsvFile[i].Ref2;
                    Ref3    = CsvFile[i].Ref3;
                    PayCode = CsvFile[i].PayCode;
                    int result = 0;
                    if (int.TryParse(CsvFile[i].Pieces, out result))
                    {
                        Pieces += Convert.ToInt32(CsvFile[i].Pieces);
                    }
                    if (TrackingNumber == String.Empty)
                    {
                        ProNumber = FBInvoiceNumber;
                    }
                    else
                    {
                        ProNumber = CsvFile[i].ProNumber;
                    }

                    if (int.TryParse(CsvFile[i].ActualWeight, out result))
                    {
                        ActualWeight = Convert.ToInt32(CsvFile[i].ActualWeight);
                    }
                    result = 0;
                    if (int.TryParse(CsvFile[i].BilledWeight, out result))
                    {
                        BilledWeight = Convert.ToInt32(CsvFile[i].BilledWeight);
                    }
                    //ChargeClassCode = CsvFile[i].ChargeClassCode;
                    //ProTransNote = CsvFile[i].ProTransNote;
                    if (CsvFile[i].FSCCheck == "FSC")
                    {
                        FSC       += Convert.ToDecimal(CsvFile[i].PayAmount);
                        PayAmount += Convert.ToDecimal(CsvFile[i].PayAmount);
                    }
                    else
                    {
                        PayAmount += Convert.ToDecimal(CsvFile[i].PayAmount);
                    }

                    ShipperName = CsvFile[i].ShipperName;
                    //ShipperAddress1 = CsvFile[i].ShipperAddress1;
                    //ShipperAddress2 = CsvFile[i].ShipperAddress2;
                    ShipperCity  = CsvFile[i].ShipperCity;
                    ShipperState = CsvFile[i].ShipperState;
                    if (CsvFile[i].ShipperZip.Length > 5)
                    {
                        ShipperZip = CsvFile[i].ShipperZip.Substring(0, 4);
                    }
                    else
                    {
                        ShipperZip = CsvFile[i].ShipperZip;
                    }
                    //ShipperCountry = CsvFile[i].ShipperCountry;
                    ConsigneeName = CsvFile[i].ConsigneeName;
                    //ConsigneeAddress1 = CsvFile[i].ConsigneeAddress1;
                    //ConsigneeAddress2 = CsvFile[i].ConsigneeAddress2;
                    ConsigneeCity  = CsvFile[i].ConsigneeCity;
                    ConsigneeState = CsvFile[i].ConsigneeState;
                    if (CsvFile[i].ConsigneeZip.Length > 5)
                    {
                        ConsigneeZip = CsvFile[i].ConsigneeZip.Substring(0, 4);
                    }
                    else
                    {
                        ConsigneeZip = CsvFile[i].ConsigneeZip;
                    }
                    //ConsigneeCountry = CsvFile[i].ConsigneeCountry;
                    Status = "O";
                    //apply the rules
                    if ((ConsigneeName != null && ConsigneeCity != null & ConsigneeZip != null) && ConsigneeState == null)
                    {
                        LoadCode = "INT";
                    }
                    else if ((ShipperName != null && ShipperCity != null & ShipperZip != null) && ShipperState == null)
                    {
                        LoadCode = "INT";
                    }
                    else
                    {
                        LoadCode = "P";
                    }
                    if (CsvFile[i].AccountNumber == null)
                    {
                        ErrorCode = "J";
                    }
                    else if (CheckForDupePro(CsvFile[i].ProNumber))
                    {
                        ErrorCode = "J";
                        if (CsvFile[i].FSCCheck == "FRT")
                        {
                            ProTransNote = String.Format("DUPLICATE PRO {0}", CsvFile[i].ProTransNote);
                        }
                        else if (CsvFile[i].FSCCheck == "FRT" && ProTransNote == null)
                        {
                            ProTransNote = CsvFile[i].ProTransNote;
                        }
                    }
                    else if (ProNumber == null && CheckForDupePro(CsvFile[i].FBInvoiceNumber))
                    {
                        ErrorCode = "J";
                        if (CsvFile[i].FSCCheck == "FRT")
                        {
                            ProTransNote = String.Format("DUPLICATE PRO_INVOICE_ {0}", CsvFile[i].ProTransNote);
                        }
                        else if (CsvFile[i].FSCCheck == "FRT" && ProTransNote == null)
                        {
                            ProTransNote = CsvFile[i].ProTransNote;
                        }
                    }
                    else
                    {
                        ErrorCode = "A";
                    }

                    GLCode = QueryGLInformation(ProNumber);

                    i++;

                    ////get the next row
                    //row = ds.Tables[0].Rows[i];
                    ////hasRow = reader.ReadRow(row);
                }
                TotalInvoiceValidate += PayAmount;
                // dropped from the while - update index
                i--;
                // create the freight bill
                //get the clientid
                //ALS: need db
                //var id = (from c in clientdb.Clients
                //          where c.Code == "HOP10"
                //          select c.ClientsId).FirstOrDefault();
                Guid id = new Guid("6c800fed-1b77-4bfe-8244-cfc246448594"); //PPP10 sample

                if (id != Guid.Empty && ProNumber != "")
                {
                    writelog(String.Format("adding: {0}, weekending date {1} ", FBInvoiceNumber, WeekendingDate));


                    //id is the ClientsId

                    //get the CarrierSCACsId for FEDX
                    int CarrierSCACsId = GetCarrierSCACsId("FEDX");

                    //get shipper addressid or GetShippersIdreate the address and return the id
                    //ShippersId
                    int ShippersId = GetShippersId(id, ShipperName, ShipperCity, ShipperState, ShipperZip);
                    //get consignees addressid or create the address and return the id;
                    //ConsigneesId
                    int ConsigneesId = GetConsigneesId(id, ConsigneeName, ConsigneeCity, ConsigneeState, ConsigneeZip);

                    //using TBill.Load Code - get the load code id to store in FB
                    //Load Code
                    int LoadCodeId = GetLoadCodeId(LoadCode);
                    //using TBill.Create Payment recordent Type - get the PaymentType key
                    //PaymentTypesId
                    int PaymentTypesId = GetPaymentTypeId(CsvFile[i].PaymentType);
                    //using TBill.Error Code to get the InvoiceStatuses key
                    //InvoiceStatusesId
                    int InvoiceStatusesId = GetInvoiceStatusesId(ErrorCode);

                    try
                    {
                        Invoices invoice = new Invoices()
                        {
                            WeekendingDate      = ErrorCode == "J" ? null : WeekendingDate,
                            BatchDate           = ErrorCode == "J" ? null : BatchDate,
                            ProNumber           = ProNumber,
                            InvoiceNumber       = FBInvoiceNumber,
                            ProDate             = Convert.ToDateTime(ProDate),
                            CarrierSCACsId      = CarrierSCACsId,
                            ConsigneesId        = ConsigneesId,
                            ClientsId           = id,
                            InvoiceStatusId     = InvoiceStatusesId,
                            LoadsId             = LoadCodeId,
                            EmployeesId         = 51,
                            PaymentTypesId      = PaymentTypesId,
                            ShippersId          = ShippersId,
                            GeneralLedgerNumber = QueryGLInformation(ProNumber),
                            ActualWeight        = ActualWeight,
                            BilledWeight        = BilledWeight,
                            PaymentAmount       = PayAmount,
                            BilledAmount        = PayAmount,
                            Status = Status,

                            FuelSurcharge = FSC,
                            //Maxine - 8/20/2013 - default to 1 per Al
                            PieceCount = Pieces == 0 ? 1 : Convert.ToInt32(Pieces),
                            //PalletCount = 1,
                            //DeliveryDate = bill.Delivery_Date == null ? (Nullable<DateTime>)null : bill.Delivery_Date,
                            //CreatedBy = CreateById,
                            CreatedDate = DateTime.Today,
                            //UpdatedBy = UpdatedById,
                            //UpdatedDate = bill.PRO_Update_Date_Time == null ? (Nullable<DateTime>)null : bill.PRO_Trans_Update_DAte_Time,

                            Deleted = false,
                            //PreferredCarrierSCAC = bill.Preferred_Carrier_SCAC  == null ? null : bill.Preferred_Carrier_SCAC,
                            //PreferredCarrierAmount = bill.Preferred_Carrier_Amount  == null ? 0 : (decimal)bill.Preferred_Carrier_Amount
                        };
                        fbdb.Invoices.InsertOnSubmit(invoice);
                        fbdb.SubmitChanges();

                        //now create the support/details table since we have the invoiceid
                        bool success = false;
                        //using TBill CTL Invoice Number to create a new record in the InvoiceDetails table
                        //this record needs the InvoicesId
                        if (ErrorCode == "J")
                        {
                            success = CreateInvoiceDetailsRecord(invoice.InvoicesId, null, null, null);
                        }
                        else
                        {
                            success = CreateInvoiceDetailsRecord(invoice.InvoicesId, InvoiceNumber, InvoiceDate, DueDate);
                        }
                        //using TBill.Reference1,2,3 create a record in the ReferencesDetails table
                        ////this record needs the InvoicesId
                        if (Ref1 != null || Ref2 != null)
                        {
                            success = CreateReferencesDetailsRecord(invoice.InvoicesId, Ref1, Ref2);
                        }
                        ////using TBill BIDReason - create a record in the BillsInDisputeDetails table
                        ////this record needs the InvoicesId
                        //if (BIDReason != null)
                        //{
                        //    int BillInDisputeReasonsId = GetBillInDisputeReasonsId(BIDReason);
                        //    success = CreateBillsInDisputeDReasonRecord(invoice.InvoicesId, BillInDisputeReasonsId, bill.BIDReasonOther, bill.BIDOrgAmt, bill.BIDSBAmt, bill.BIDActualWeight);
                        //}
                        //using bill.class code to get the FreightClassId from the FreightClasses table
                        //this record needs the InvoicesId to relate back to the FB
                        //if (bill.Class_Code != null)
                        //{
                        //    int FreightClassId = GetFreightClassId(ClassCode);
                        //    success = CreateInvoice_FreightClassesRecord(invoice.InvoicesId, FreightClassId, ActualWeight, BilledWeight, Pieces);
                        //}
                        //using TBill.Pro Transaction Note as a key to ProTransNote table to get the key - create a ProTransNotesDetail record - need InvoicesId
                        //NOTE: is no matches then put the Pro Transaction Note in the Note column of the new record
                        //ProTransNotesDetailsId - this record needs the InvoicesId
                        if (ProTransNote != null)
                        {
                            int ProTransNoteId = 0;
                            ProTransNoteId = GetProTransNoteId(ProTransNote);

                            //if (ProTransNoteId > 0)
                            success = CreateProTansNoteDetailsRecord(invoice.InvoicesId, ProTransNoteId, ProTransNote);
                        }
                    } //ends try
                    catch (Exception ex)
                    {
                        writelog(String.Format("error! creating invoice pro number {0}", ProNumber));

                        writelog(ex.Message);
                        //log.Close();
                    }
                }
                //}// end while
            } //end using
            //move the file to the processed folder
            File.Move(fullPath, String.Format(ConfigHelper.FetchStringValue("PostProcessFolder", true), fileName));
        }
Beispiel #32
0
        private string ReplaceInvoicePrices(Invoices invoice, string xmlMainXMLDoc)
        {
            if (invoice.InvoicePositions != null && invoice.InvoicePositions.Count != 0)
            {
                double totalPriceWithoutDiscountWithoutTax = 0;
                double totalPriceWithoutTax = 0;
                double totalPrice = 0;
                double summaryPrice = 0;

                if (!invoice.ManualPrice.HasValue)
                {
                    CalculationHelper.CalculateInvoicePrices(invoice,out totalPriceWithoutDiscountWithoutTax, out totalPriceWithoutTax,
                        out totalPrice, out summaryPrice);
                }
                else
                {
                    totalPriceWithoutTax = invoice.ManualPrice.Value;
                    var taxValue = (totalPriceWithoutTax / (double)100) * invoice.TaxValue;
                    if (invoice.WithTaxes && invoice.TaxValue > 0)
                    {
                        //with taxes
                        totalPrice = totalPriceWithoutTax + taxValue;
                    }
                    else
                    {
                        totalPrice = totalPriceWithoutTax;
                    }
                }

                //Discount
                var xmlDoc = XDocument.Parse(xmlMainXMLDoc);
                var temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#DiscountText"));
                var parentTableElement = GetParentElementByName(temp, "<w:tr ");

                if (!invoice.ManualPrice.HasValue && invoice.Discount > 0 && parentTableElement != null)
                {
                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#DiscountText",
                        String.Format("Abzüglich {0}% Rabatt", invoice.Discount));

                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#DiscountValue",
                        String.Format("-{0}", Math.Round(totalPriceWithoutDiscountWithoutTax - totalPriceWithoutTax, 2).
                            ToString("N2")));

                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#PriceWithoutTax", totalPriceWithoutTax.ToString("N2"));
                }
                else
                {
                    parentTableElement.Remove();
                    temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#PriceWithoutTax"));
                    parentTableElement = GetParentElementByName(temp, "<w:tr ");
                    parentTableElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();
                }

                //Taxes
                xmlDoc = XDocument.Parse(xmlMainXMLDoc);
                temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#TaxText"));
                parentTableElement = GetParentElementByName(temp, "<w:tr ");

                if (invoice.WithTaxes && invoice.TaxValue > 0 && parentTableElement != null)
                {
                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TaxText",
                        String.Format("Zuzüglich {0}% MwSt.", invoice.TaxValue));

                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TaxValue",
                        String.Format("{0}", Math.Round(totalPrice - totalPriceWithoutTax, 2).ToString("N2")));
                }
                else
                {
                    parentTableElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();
                }

                if (!invoice.ManualPrice.HasValue)
                {
                    //total price without discount and tax for main positions only                
                    xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TotalPriceWithoutDiscount", totalPriceWithoutDiscountWithoutTax.ToString("N2"));
                }
                else
                {
                    xmlDoc = XDocument.Parse(xmlMainXMLDoc);
                    temp = xmlDoc.Descendants().LastOrDefault(o => o.Value.Contains("#TotalPriceWithoutDiscount"));
                    parentTableElement = GetParentElementByName(temp, "<w:tr ");
                    parentTableElement.Remove();
                    xmlMainXMLDoc = xmlDoc.Root.ToString();
                }


                //total price
                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TotalPriceText", "Zu zahlender Betrag");
                xmlMainXMLDoc = xmlMainXMLDoc.Replace("#TotalPrice", totalPrice.ToString("N2"));
            }

            return xmlMainXMLDoc;
        }
 public IInvoice GetById(Guid id)
 {
     return(Invoices.AsQueryable <Invoice>()
            .Single(c => c.Id == id));
 }
Beispiel #34
0
 public void addInvoice(Invoice invoice)
 {
     Invoices.Add(invoice);
 }
 public IInvoice GetByNumber(string invoiceNumber)
 {
     return(Invoices.AsQueryable <Invoice>()
            .Single(c => c.Number == invoiceNumber));
 }
Beispiel #36
0
 public Task <IEnumerable <Invoice> > UpdateAsync(IEnumerable <Invoice> items)
 {
     return(Invoices.UpdateAsync(items));
 }
 public void Save(IInvoice invoice)
 {
     Invoices.Save(invoice);
 }
Beispiel #38
0
 public Task <Invoice> UpdateAsync(Invoice item)
 {
     return(Invoices.UpdateAsync(item));
 }
Beispiel #39
0
        public ActionResult DeleteExportStep(int id) //id=QBExportLogID
        {
            Invoices.QBExportLog_DeleteExportStep(id);

            return(RedirectToAction("Index"));
        }
Beispiel #40
0
 public IEnumerable <Invoice> Update(IEnumerable <Invoice> items)
 {
     return(Invoices.Update(items));
 }
Beispiel #41
0
 public void Run(Invoices invoice)
 {
     _invoice = invoice;
     _newInvoiceView.Show();
 }
 public void AddInvoice([MarshalAs(UnmanagedType.IDispatch)] object invoice)
 {
     Invoices.Add((InvoiceForCorrectionInfo)invoice);
 }
Beispiel #43
0
 public int Create(Invoices input)
 {
     return(invoiceAccess.Create(input));
 }
 /// <summary>
 /// There are no comments for Invoices in the schema.
 /// </summary>
 public void AddToInvoices(Invoices invoices)
 {
     base.AddObject("Invoices", invoices);
 }
    private Invoices GetInvoice(out string message)
    {
        message = string.Empty;
        InvoicesRepository invoiceRepo = new InvoicesRepository();
        if (!datInvoiceDate.SelectedDate.HasValue)
        {
            message = ResourceManager.GetString("messageInvoiceDateNotNull");
            return null;
        }

        string[] fiscalKey = WebConfig.FiscalDate.Split('/');

        Invoices saveItem = null;
        int firstFutureNumber = int.Parse(WebConfig.FirstNumberFutureInvoice);
        //if (SessionManager.CurrentInvoice != null)
        if (!string.IsNullOrEmpty(Request.QueryString["InvoiceIdPK"]))
        {
            saveItem = SessionManager.CurrentInvoice;
            DateTime fiscalDateMin = new DateTime(saveItem.IdYear, int.Parse(fiscalKey[1]), int.Parse(fiscalKey[0]));
            DateTime fiscalDateMax = new DateTime(saveItem.IdYear + 1, int.Parse(fiscalKey[1]), int.Parse(fiscalKey[0]));
            if (datInvoiceDate.SelectedDate.Value < fiscalDateMin
                || datInvoiceDate.SelectedDate.Value >= fiscalDateMax)
            {
                message = string.Format(ResourceManager.GetString("messageInvoiceDateNotValidFiscalDate"),
                    fiscalDateMin.ToString("dd/MM/yyyy"), fiscalDateMax.ToString("dd/MM/yyyy"));
                return null;
            }
            //if this is a future invoice.
            if (!string.IsNullOrEmpty(Request.QueryString["type"]) && Request.QueryString["type"] == "future")
            {
                //If change the date less than or equal today, we will change this future invoice to normal invoice.
                if (datInvoiceDate.SelectedDate.Value <= DateTime.Today)
                {
                    Invoices lastNormalInvoice = invoiceRepo.GetInvoicesWithMaxNumber(
                        saveItem.IdYear, saveItem.IdTypeInvoice, false, firstFutureNumber);
                    if (lastNormalInvoice != null && lastNormalInvoice.Date.HasValue
                        && lastNormalInvoice.Date.Value > datInvoiceDate.SelectedDate.Value)
                    {
                        message = ResourceManager.GetString("messageInvoiceDateMustHigherthan") + lastNormalInvoice.Date.Value.ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        saveItem.IdFactNumberNew = new InvoicesRepository().GetMaxInvoiceNumber(
                            saveItem.IdYear, saveItem.IdTypeInvoice, false, firstFutureNumber);
                        if (!saveItem.IdFactNumberNew.HasValue)
                        {
                            if (saveItem.IdTypeInvoice == "I")
                                saveItem.IdFactNumberNew = int.Parse(WebConfig.FirstNumberInvoice);
                            else
                                saveItem.IdFactNumberNew = int.Parse(WebConfig.FirstNumberCreditNote);
                        }
                        else
                        {
                            saveItem.IdFactNumberNew = saveItem.IdFactNumberNew.Value + 1;
                        }
                    }
                }
            }
            else
            {
                //If the date is changed.
                if (datInvoiceDate.SelectedDate.Value != saveItem.Date.Value)
                {
                    bool isFuture = saveItem.IdFactNumber >= firstFutureNumber;
                    Invoices nextInvoice = invoiceRepo.GetNextInvoices(saveItem.IdFactNumber,
                        saveItem.IdYear, saveItem.IdTypeInvoice, isFuture, firstFutureNumber);
                    if (nextInvoice != null && nextInvoice.Date.HasValue
                        && nextInvoice.Date.Value < datInvoiceDate.SelectedDate.Value)
                    {
                        message = ResourceManager.GetString("messageInvoiceDateMustHigherthan") + nextInvoice.Date.Value.ToString("dd/MM/yyyy");
                    }

                    Invoices previousInvoice = invoiceRepo.GetPreviousInvoices(saveItem.IdFactNumber,
                        saveItem.IdYear, saveItem.IdTypeInvoice, isFuture, firstFutureNumber);
                    if (previousInvoice != null && previousInvoice.Date.HasValue
                        && previousInvoice.Date.Value > datInvoiceDate.SelectedDate.Value)
                    {
                        message = ResourceManager.GetString("messageInvoiceDateMustLowerthan") + previousInvoice.Date.Value.ToString("dd/MM/yyyy");

                    }
                    //If this is the lasted normal invocie, then change the date to future, we have to change this invoice to future invoice.
                    if (string.IsNullOrEmpty(message))
                    {
                        int? maxNumber = invoiceRepo.GetMaxInvoiceNumber(
                            saveItem.IdYear, saveItem.IdTypeInvoice, false, firstFutureNumber);
                        if (maxNumber.HasValue && maxNumber.Value == saveItem.IdFactNumber
                            && datInvoiceDate.SelectedDate.Value > DateTime.Today)
                        {
                            int? maxNumberFuture = invoiceRepo.GetMaxInvoiceNumber(
                                saveItem.IdYear, saveItem.IdTypeInvoice, true, firstFutureNumber);
                            if (maxNumberFuture.HasValue)
                                saveItem.IdFactNumberNew = maxNumberFuture.Value + 1;
                            else
                                saveItem.IdFactNumberNew = firstFutureNumber;
                        }

                    }
                }
            }
        }
        else
        {
            saveItem = new Invoices();
            int idYear = 0;
            string type = "C";
            int idFactNumber = 0;
            if (radInvoice.Checked)
            {
                type = "I";
                idFactNumber = int.Parse(WebConfig.FirstNumberInvoice);
            }
            else
                idFactNumber = int.Parse(WebConfig.FirstNumberCreditNote);

            DateTime today = DateTime.Today;
            DateTime fiscalDate = new DateTime(DateTime.Today.Year, int.Parse(fiscalKey[1]), int.Parse(fiscalKey[0]));
            //If Current date is lower than FiscalDate in the current civil year:
            //    IdYear=Year(Current Date) – 1
            //Elseif Current date is higher than FiscalDate in the current civil year:
            //    IdYear= Year(Current Date)
            if (today < fiscalDate)
                idYear = today.Year - 1;
            else
                idYear = today.Year;

            int? maxNbr = 1;
            if (datInvoiceDate.SelectedDate.HasValue && datInvoiceDate.SelectedDate.Value > today)
            {
                maxNbr = new InvoicesRepository().GetMaxInvoiceNumber(idYear, type, true, firstFutureNumber);
                idFactNumber = firstFutureNumber;
            }
            else
            {
                maxNbr = new InvoicesRepository().GetMaxInvoiceNumber(idYear, type, false, firstFutureNumber);
            }

            if (maxNbr.HasValue)
                idFactNumber = maxNbr.Value + 1;

            saveItem.IdFactNumber = idFactNumber;
            saveItem.IdYear = idYear;
            saveItem.IdTypeInvoice = type;

            bool isFuture = saveItem.IdFactNumber >= firstFutureNumber;
            Invoices lastNormalInvoice = invoiceRepo.GetInvoicesWithMaxNumber(
                       saveItem.IdYear, saveItem.IdTypeInvoice, isFuture, firstFutureNumber);
            if (lastNormalInvoice != null && lastNormalInvoice.Date.HasValue
                    && lastNormalInvoice.Date.Value > datInvoiceDate.SelectedDate.Value)
            {
                message = ResourceManager.GetString("messageInvoiceDateMustHigherthan") + lastNormalInvoice.Date.Value.ToString("dd/MM/yyyy");
            }
        }

        saveItem.InvoiceIdPK = saveItem.IdFactNumber.ToString() + "-" + saveItem.IdTypeInvoice + "-" + saveItem.IdYear;

        saveItem.RefCustomerNumber = int.Parse(hiddenCompanyAddressId.Value);
        saveItem.Date = datInvoiceDate.SelectedDate;
        saveItem.Currency = WebConfig.Currency;
        if (!string.IsNullOrEmpty(txtTotalVAT.Text))
        {
            saveItem.AmountVatEuro = Convert.ToDouble(txtTotalVAT.Text, Common.GetDoubleFormatProvider());
        }
        else
        {
            saveItem.AmountVatEuro = 0;
        }
        if (!string.IsNullOrEmpty(txtTotalHTVA.Text))
        {
            saveItem.TotalHtvaEuro = Convert.ToDouble(txtTotalHTVA.Text, Common.GetDoubleFormatProvider());
        }
        else
        {
            saveItem.TotalHtvaEuro = 0;
        }
        saveItem.Remark = txtRemark.Text;
        saveItem.Remark_Internal = txtInternalRemark.Text;
        saveItem.Payement = chkPayment.Checked;
        saveItem.Factoring = chkFactoring.Checked;
        if (!string.IsNullOrEmpty(txtPaymentDate.Text))
            saveItem.DateOfPayement = DateTime.ParseExact(txtPaymentDate.Text, "dd/MM/yyyy",
                    System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
        return saveItem;
    }