예제 #1
0
        public PdfCreator(IOptionsMonitor <ILog> logger,
                          Files.Classes.PathProvider filesPathProvider,
                          DocumentServiceConnector documentServiceConnector,
                          IServiceProvider serviceProvider,
                          OrganisationLogoManager organisationLogoManager,
                          DaoFactory daoFactory,
                          InvoiceFormattedData invoiceFormattedData)
        {
            _filesPathProvider = filesPathProvider;

            _logger = logger.Get("ASC.CRM");

            _documentServiceConnector = documentServiceConnector;
            _serviceProvider          = serviceProvider;
            _organisationLogoManager  = organisationLogoManager;
            _daoFactory           = daoFactory;
            _invoiceFormattedData = invoiceFormattedData;
        }
예제 #2
0
        private static Stream GetStreamDocx(Invoice data)
        {
            var invoiceData = InvoiceFormattedData.GetData(data, 0, 0);
            var logo = new byte[] {};

            if (!string.IsNullOrEmpty(invoiceData.LogoBase64))
            {
                logo = Convert.FromBase64String(invoiceData.LogoBase64);
            }
            else if (invoiceData.LogoBase64Id != 0)
            {
                logo = Convert.FromBase64String(OrganisationLogoManager.GetOrganisationLogoBase64(invoiceData.LogoBase64Id));
            }

            using (var zip = ZipFile.Read(TemplatePath))
            {
                var documentXmlStream = new MemoryStream();
                foreach (var entry in zip.Entries.Where(entry => entry.FileName == DocumentXml))
                {
                    entry.Extract(documentXmlStream);
                }
                documentXmlStream.Position = 0;
                zip.RemoveEntry(DocumentXml);
                var document = new XmlDocument();
                document.Load(documentXmlStream);
                var documentStr = GenerateDocumentXml(document, invoiceData, logo);
                zip.AddEntry(DocumentXml, documentStr, Encoding.UTF8);

                if (logo.Length > 0)
                {
                    zip.UpdateEntry(DocumentLogoImage, logo);
                }

                var streamZip = new MemoryStream();
                zip.Save(streamZip);
                streamZip.Seek(0, SeekOrigin.Begin);
                streamZip.Flush();
                return streamZip;
            }

        }
예제 #3
0
        private static string GenerateDocumentXml(XmlDocument xDocument, InvoiceFormattedData data, byte[] logo)
        {
            XmlNodeList nodeList;
            XmlNode parent;
            XmlNode child;


            #region Seller

            nodeList = xDocument.SelectNodes("//*[@ascid='seller']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Seller == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Seller.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Seller.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Logo

            nodeList = xDocument.SelectNodes("//*[@ascid='logo']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (logo.Length <= 0)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var stream = new MemoryStream(logo);
                    var img = System.Drawing.Image.FromStream(stream);
                    var cx = img.Width * 9525;//1px =  9525emu
                    var cy = img.Height * 9525;//1px =  9525emu
                    
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${width}", cx.ToString(CultureInfo.InvariantCulture))
                        .Replace("${height}", cy.ToString(CultureInfo.InvariantCulture));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Number

            nodeList = xDocument.SelectNodes("//*[@ascid='number']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Number == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Number.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Number.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Invoice

            nodeList = xDocument.SelectNodes("//*[@ascid='invoice']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                nodeList = xDocument.SelectNodes("//*[@ascid='invoice']//*[@ascid='row']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.Invoice == null || data.Invoice.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        foreach (var line in data.Invoice)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }
            }

            #endregion


            #region Customer

            nodeList = xDocument.SelectNodes("//*[@ascid='customer']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Customer == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Customer.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Customer.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            nodeList = xDocument.SelectNodes("//*[@ascid='table']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                #region TableHeaderRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='headerRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableHeaderRow == null || data.TableHeaderRow.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        for (var i = 0; i < data.TableHeaderRow.Count; i++)
                        {
                            newText = newText
                                .Replace("${label" + i + "}", EncodeAndReplaceLineBreaks(data.TableHeaderRow[i]));
                        }
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableBodyRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='bodyRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableBodyRows == null || data.TableBodyRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        foreach (var line in data.TableBodyRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            for (var i = 0; i < line.Count; i++)
                            {
                                newText = newText
                                    .Replace("${value" + i + "}", EncodeAndReplaceLineBreaks(line[i]));
                            }
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableFooterRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='footerRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableFooterRows == null || data.TableFooterRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        foreach (var line in data.TableFooterRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableTotalRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='totalRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableTotalRow == null)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        newText = newText
                            .Replace("${label}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item1))
                            .Replace("${value}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item2));
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion
            }


            #region Terms

            nodeList = xDocument.SelectNodes("//*[@ascid='terms']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Terms == null)
                {
                    if (parent.ParentNode != null)
                        parent.ParentNode.RemoveChild(parent);
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Terms.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Terms.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Notes

            nodeList = xDocument.SelectNodes("//*[@ascid='notes']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Notes == null)
                {
                    if (parent.ParentNode != null)
                        parent.ParentNode.RemoveChild(parent);
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Notes.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Notes.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Consignee

            nodeList = xDocument.SelectNodes("//*[@ascid='consignee']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Consignee == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Consignee.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Consignee.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            return xDocument.InnerXml;
        }
        private static InvoiceFormattedData CreateDataAfterLinesUpdated(Invoice invoice,
                                                                        InvoiceFormattedData invoiceOldData)
        {
            using (var scope = DIHelper.Resolve())
            {
                var daoFactory = scope.Resolve <DaoFactory>();

                var data = invoiceOldData;

                var cultureInfo = string.IsNullOrEmpty(invoice.Language)
                    ? CultureInfo.CurrentCulture
                    : CultureInfo.GetCultureInfo(invoice.Language);

                #region TableBodyRows, TableFooterRows, TableTotalRow

                data.TableBodyRows = new List <List <string> >();

                var invoiceLines = invoice.GetInvoiceLines(daoFactory);
                var invoiceTaxes = new Dictionary <int, decimal>();

                decimal subtotal = 0;
                decimal discount = 0;
                decimal amount   = 0;

                foreach (var line in invoiceLines)
                {
                    var item = daoFactory.InvoiceItemDao.GetByID(line.InvoiceItemID);
                    var tax1 = line.InvoiceTax1ID > 0
                        ? daoFactory.InvoiceTaxDao.GetByID(line.InvoiceTax1ID)
                        : null;
                    var tax2 = line.InvoiceTax2ID > 0
                        ? daoFactory.InvoiceTaxDao.GetByID(line.InvoiceTax2ID)
                        : null;

                    var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                    var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                    decimal rate = 0;
                    if (tax1 != null)
                    {
                        rate += tax1.Rate;
                        if (invoiceTaxes.ContainsKey(tax1.ID))
                        {
                            invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] +
                                                    Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                        }
                        else
                        {
                            invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                        }
                    }
                    if (tax2 != null)
                    {
                        rate += tax2.Rate;
                        if (invoiceTaxes.ContainsKey(tax2.ID))
                        {
                            invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] +
                                                    Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                        }
                        else
                        {
                            invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                        }
                    }

                    decimal taxValue    = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                    decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                    subtotal += subtotalValue;
                    discount += discountValue;
                    amount   += amountValue;

                    data.TableBodyRows.Add(new List <string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " + line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue - discountValue).ToString(CultureInfo.InvariantCulture)
                    });
                }

                data.TableFooterRows = new List <Tuple <string, string> >();
                data.TableFooterRows.Add(
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo),
                                               (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

                foreach (var invoiceTax in invoiceTaxes)
                {
                    var iTax = daoFactory.InvoiceTaxDao.GetByID(invoiceTax.Key);
                    data.TableFooterRows.Add(new Tuple <string, string>(
                                                 string.Format("{0} ({1}%)", iTax.Name, iTax.Rate),
                                                 invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
                }

                //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

                data.TableTotalRow =
                    new Tuple <string, string>(
                        string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo),
                                      invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


                #endregion


                return(data);
            }
        }
        private static InvoiceFormattedData ReadData(string jsonData)
        {
            var data    = new InvoiceFormattedData();
            var jsonObj = JObject.Parse(jsonData);


            #region TemplateType

            data.TemplateType = jsonObj.Value <int>("TemplateType");

            #endregion


            #region Seller, LogoBase64, LogoSrcFormat

            var seller = jsonObj.Value <JObject>("Seller");
            if (seller != null)
            {
                data.Seller = seller.ToObject <Tuple <string, string> >();
            }

            data.LogoBase64   = jsonObj.Value <string>("LogoBase64");
            data.LogoBase64Id = !String.IsNullOrEmpty(jsonObj.Value <string>("LogoBase64Id")) ? jsonObj.Value <int>("LogoBase64Id") : 0;

            if (string.IsNullOrEmpty(data.LogoBase64) && data.LogoBase64Id != 0)
            {
                data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(data.LogoBase64Id);
            }


            data.LogoSrcFormat = jsonObj.Value <string>("LogoSrcFormat");

            #endregion


            #region Number

            var number = jsonObj.Value <JObject>("Number");
            if (number != null)
            {
                data.Number = number.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region Invoice

            var invoice = jsonObj.Value <JArray>("Invoice");
            if (invoice != null)
            {
                data.Invoice = invoice.ToObject <List <Tuple <string, string> > >();
            }

            #endregion


            #region Customer

            var customer = jsonObj.Value <JObject>("Customer");
            if (customer != null)
            {
                data.Customer = customer.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region TableHeaderRow, TableBodyRows, TableFooterRows, Total

            var tableHeaderRow = jsonObj.Value <JArray>("TableHeaderRow");
            if (tableHeaderRow != null)
            {
                data.TableHeaderRow = tableHeaderRow.ToObject <List <string> >();
            }

            var tableBodyRows = jsonObj.Value <JArray>("TableBodyRows");
            if (tableBodyRows != null)
            {
                data.TableBodyRows = tableBodyRows.ToObject <List <List <string> > >();
            }

            var tableFooterRows = jsonObj.Value <JArray>("TableFooterRows");
            if (tableFooterRows != null)
            {
                data.TableFooterRows = tableFooterRows.ToObject <List <Tuple <string, string> > >();
            }

            var tableTotalRow = jsonObj.Value <JObject>("TableTotalRow");
            if (tableTotalRow != null)
            {
                data.TableTotalRow = tableTotalRow.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region Terms

            var terms = jsonObj.Value <JObject>("Terms");
            if (terms != null)
            {
                data.Terms = terms.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region Notes

            var notes = jsonObj.Value <JObject>("Notes");
            if (notes != null)
            {
                data.Notes = notes.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region Consignee

            var consignee = jsonObj.Value <JObject>("Consignee");
            if (consignee != null)
            {
                data.Consignee = consignee.ToObject <Tuple <string, string> >();
            }

            #endregion


            #region Addresses

            data.DeliveryAddressID = !String.IsNullOrEmpty(jsonObj.Value <string>("DeliveryAddressID")) ? jsonObj.Value <int>("DeliveryAddressID") : 0;
            data.BillingAddressID  = !String.IsNullOrEmpty(jsonObj.Value <string>("BillingAddressID")) ? jsonObj.Value <int>("BillingAddressID") : 0;

            #endregion

            return(data);
        }
        private static InvoiceFormattedData CreateData(Invoice invoice, int billingAddressID, int deliveryAddressID)
        {
            using (var scope = DIHelper.Resolve())
            {
                var daoFactory = scope.Resolve <DaoFactory>();

                var data        = new InvoiceFormattedData();
                var sb          = new StringBuilder();
                var list        = new List <string>();
                var cultureInfo = string.IsNullOrEmpty(invoice.Language)
                    ? CultureInfo.CurrentCulture
                    : CultureInfo.GetCultureInfo(invoice.Language);


                #region TemplateType

                data.TemplateType = (int)invoice.TemplateType;

                #endregion


                #region Seller, LogoBase64, LogoSrcFormat

                var invoiceSettings = daoFactory.InvoiceDao.GetSettings();

                if (!string.IsNullOrEmpty(invoiceSettings.CompanyName))
                {
                    sb.Append(invoiceSettings.CompanyName);
                }

                if (!string.IsNullOrEmpty(invoiceSettings.CompanyAddress))
                {
                    var obj = JObject.Parse(invoiceSettings.CompanyAddress);

                    var str = obj.Value <string>("street");
                    if (!string.IsNullOrEmpty(str))
                    {
                        list.Add(str);
                    }

                    str = obj.Value <string>("city");
                    if (!string.IsNullOrEmpty(str))
                    {
                        list.Add(str);
                    }

                    str = obj.Value <string>("state");
                    if (!string.IsNullOrEmpty(str))
                    {
                        list.Add(str);
                    }

                    str = obj.Value <string>("zip");
                    if (!string.IsNullOrEmpty(str))
                    {
                        list.Add(str);
                    }

                    str = obj.Value <string>("country");
                    if (!string.IsNullOrEmpty(str))
                    {
                        list.Add(str);
                    }

                    if (list.Count > 0)
                    {
                        sb.AppendLine();
                        sb.Append(string.Join(", ", list));
                    }
                }

                data.Seller =
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Seller", cultureInfo),
                                               sb.ToString());

                if (invoiceSettings.CompanyLogoID != 0)
                {
                    data.LogoBase64Id = invoiceSettings.CompanyLogoID;
                    //data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(invoiceSettings.CompanyLogoID);
                    data.LogoSrcFormat = OrganisationLogoManager.OrganisationLogoSrcFormat;
                }

                #endregion


                #region Number

                data.Number =
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Invoice", cultureInfo),
                                               invoice.Number);

                #endregion


                #region Invoice

                data.Invoice = new List <Tuple <string, string> >();
                data.Invoice.Add(
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("IssueDate", cultureInfo),
                                               invoice.IssueDate.ToShortDateString()));
                if (!string.IsNullOrEmpty(invoice.PurchaseOrderNumber))
                {
                    data.Invoice.Add(
                        new Tuple <string, string>(
                            CRMInvoiceResource.ResourceManager.GetString("PONumber", cultureInfo),
                            invoice.PurchaseOrderNumber));
                }
                data.Invoice.Add(
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("DueDate", cultureInfo),
                                               invoice.DueDate.ToShortDateString()));

                #endregion


                #region Customer

                var customer = daoFactory.ContactDao.GetByID(invoice.ContactID);

                if (customer != null)
                {
                    sb = new StringBuilder();

                    sb.Append(customer.GetTitle());

                    var billingAddress = billingAddressID != 0
                        ? daoFactory.ContactInfoDao.GetByID(billingAddressID)
                        : null;
                    if (billingAddress != null && billingAddress.InfoType == ContactInfoType.Address &&
                        billingAddress.Category == (int)AddressCategory.Billing)
                    {
                        list = new List <string>();

                        var obj = JObject.Parse(billingAddress.Data);

                        var str = obj.Value <string>("street");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("city");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("state");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("zip");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("country");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        if (list.Count > 0)
                        {
                            sb.AppendLine();
                            sb.Append(string.Join(", ", list));
                        }
                    }

                    data.Customer =
                        new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("BillTo", cultureInfo),
                                                   sb.ToString());
                }

                #endregion


                #region TableHeaderRow, TableBodyRows, TableFooterRows, TableTotalRow

                data.TableHeaderRow = new List <string>
                {
                    CRMInvoiceResource.ResourceManager.GetString("ItemCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("QuantityCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("PriceCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("DiscountCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("AmountCol", cultureInfo)
                };

                data.TableBodyRows = new List <List <string> >();

                var invoiceLines = invoice.GetInvoiceLines(daoFactory);
                var invoiceTaxes = new Dictionary <int, decimal>();

                decimal subtotal = 0;
                decimal discount = 0;
                decimal amount   = 0;

                foreach (var line in invoiceLines)
                {
                    var item = daoFactory.InvoiceItemDao.GetByID(line.InvoiceItemID);
                    var tax1 = line.InvoiceTax1ID > 0
                        ? daoFactory.InvoiceTaxDao.GetByID(line.InvoiceTax1ID)
                        : null;
                    var tax2 = line.InvoiceTax2ID > 0
                        ? daoFactory.InvoiceTaxDao.GetByID(line.InvoiceTax2ID)
                        : null;

                    var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                    var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                    decimal rate = 0;
                    if (tax1 != null)
                    {
                        rate += tax1.Rate;
                        if (invoiceTaxes.ContainsKey(tax1.ID))
                        {
                            invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] +
                                                    Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                        }
                        else
                        {
                            invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                        }
                    }
                    if (tax2 != null)
                    {
                        rate += tax2.Rate;
                        if (invoiceTaxes.ContainsKey(tax2.ID))
                        {
                            invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] +
                                                    Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                        }
                        else
                        {
                            invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                        }
                    }

                    decimal taxValue    = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                    decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                    subtotal += subtotalValue;
                    discount += discountValue;
                    amount   += amountValue;

                    data.TableBodyRows.Add(new List <string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " + line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue - discountValue).ToString(CultureInfo.InvariantCulture)
                    });
                }

                data.TableFooterRows = new List <Tuple <string, string> >();
                data.TableFooterRows.Add(
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo),
                                               (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

                foreach (var invoiceTax in invoiceTaxes)
                {
                    var iTax = daoFactory.InvoiceTaxDao.GetByID(invoiceTax.Key);
                    data.TableFooterRows.Add(new Tuple <string, string>(
                                                 string.Format("{0} ({1}%)", iTax.Name, iTax.Rate),
                                                 invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
                }

                //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

                data.TableTotalRow =
                    new Tuple <string, string>(
                        string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo),
                                      invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


                #endregion


                #region Terms

                data.Terms =
                    new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("Terms", cultureInfo),
                                               invoice.Terms);

                #endregion


                #region Notes

                if (!string.IsNullOrEmpty(invoice.Description))
                {
                    data.Notes =
                        new Tuple <string, string>(
                            CRMInvoiceResource.ResourceManager.GetString("ClientNotes", cultureInfo),
                            invoice.Description);
                }

                #endregion


                #region Consignee

                var consignee = daoFactory.ContactDao.GetByID(invoice.ConsigneeID);

                if (consignee != null)
                {
                    sb = new StringBuilder();

                    sb.Append(consignee.GetTitle());

                    var deliveryAddress = deliveryAddressID != 0
                        ? daoFactory.ContactInfoDao.GetByID(deliveryAddressID)
                        : null;
                    if (deliveryAddress != null && deliveryAddress.InfoType == ContactInfoType.Address &&
                        deliveryAddress.Category == (int)AddressCategory.Postal)
                    {
                        list = new List <string>();

                        var obj = JObject.Parse(deliveryAddress.Data);

                        var str = obj.Value <string>("street");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("city");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("state");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("zip");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        str = obj.Value <string>("country");
                        if (!string.IsNullOrEmpty(str))
                        {
                            list.Add(str);
                        }

                        if (list.Count > 0)
                        {
                            sb.AppendLine();
                            sb.Append(string.Join(", ", list));
                        }
                    }

                    data.Consignee =
                        new Tuple <string, string>(CRMInvoiceResource.ResourceManager.GetString("ShipTo", cultureInfo),
                                                   sb.ToString());
                }

                #endregion

                #region Addresses

                data.BillingAddressID  = billingAddressID;
                data.DeliveryAddressID = deliveryAddressID;

                #endregion

                return(data);
            }
        }
예제 #7
0
        private static string GenerateDocumentXml(XmlDocument xDocument, InvoiceFormattedData data, byte[] logo)
        {
            XmlNodeList nodeList;
            XmlNode     parent;
            XmlNode     child;


            #region Seller

            nodeList = xDocument.SelectNodes("//*[@ascid='seller']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Seller == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Seller.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Seller.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Logo

            nodeList = xDocument.SelectNodes("//*[@ascid='logo']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (logo.Length <= 0)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var stream = new MemoryStream(logo);
                    var img    = System.Drawing.Image.FromStream(stream);
                    var cx     = img.Width * 9525;  //1px =  9525emu
                    var cy     = img.Height * 9525; //1px =  9525emu

                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${width}", cx.ToString(CultureInfo.InvariantCulture))
                              .Replace("${height}", cy.ToString(CultureInfo.InvariantCulture));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Number

            nodeList = xDocument.SelectNodes("//*[@ascid='number']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Number == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Number.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Number.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Invoice

            nodeList = xDocument.SelectNodes("//*[@ascid='invoice']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                nodeList = xDocument.SelectNodes("//*[@ascid='invoice']//*[@ascid='row']");
                child    = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.Invoice == null || data.Invoice.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        foreach (var line in data.Invoice)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                      .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                      .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }
            }

            #endregion


            #region Customer

            nodeList = xDocument.SelectNodes("//*[@ascid='customer']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Customer == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Customer.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Customer.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            nodeList = xDocument.SelectNodes("//*[@ascid='table']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                #region TableHeaderRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='headerRow']");
                child    = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableHeaderRow == null || data.TableHeaderRow.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        for (var i = 0; i < data.TableHeaderRow.Count; i++)
                        {
                            newText = newText
                                      .Replace("${label" + i + "}", EncodeAndReplaceLineBreaks(data.TableHeaderRow[i]));
                        }
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableBodyRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='bodyRow']");
                child    = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableBodyRows == null || data.TableBodyRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        foreach (var line in data.TableBodyRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            for (var i = 0; i < line.Count; i++)
                            {
                                newText = newText
                                          .Replace("${value" + i + "}", EncodeAndReplaceLineBreaks(line[i]));
                            }
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableFooterRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='footerRow']");
                child    = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableFooterRows == null || data.TableFooterRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        foreach (var line in data.TableFooterRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                      .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                      .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableTotalRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='totalRow']");
                child    = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableTotalRow == null)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        newText = newText
                                  .Replace("${label}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item1))
                                  .Replace("${value}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item2));
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion
            }


            #region Terms

            nodeList = xDocument.SelectNodes("//*[@ascid='terms']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Terms == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Terms.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Terms.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Notes

            nodeList = xDocument.SelectNodes("//*[@ascid='notes']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Notes == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Notes.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Notes.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Consignee

            nodeList = xDocument.SelectNodes("//*[@ascid='consignee']");
            parent   = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Consignee == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                              .Replace("${label}", EncodeAndReplaceLineBreaks(data.Consignee.Item1))
                              .Replace("${value}", EncodeAndReplaceLineBreaks(data.Consignee.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            return(xDocument.InnerXml);
        }
예제 #8
0
        private InvoiceFormattedData ReadData(string jsonData)
        {
            var data    = new InvoiceFormattedData(_daoFactory, _organisationLogoManager);
            var jsonObj = JsonDocument.Parse(jsonData).RootElement;

            #region TemplateType

            data.TemplateType = jsonObj.GetProperty("TemplateType").GetInt32();

            #endregion


            #region Seller, LogoBase64, LogoSrcFormat

            JsonElement seller;
            if (jsonObj.TryGetProperty("Seller", out seller))
            {
                data.Seller = JsonSerializer.Deserialize <Tuple <string, string> >(seller.ToString());
            }

            data.LogoBase64   = jsonObj.GetProperty("LogoBase64").GetString();
            data.LogoBase64Id = !String.IsNullOrEmpty(jsonObj.GetProperty("LogoBase64Id").GetString()) ? jsonObj.GetProperty("LogoBase64Id").GetInt32() : 0;

            if (string.IsNullOrEmpty(data.LogoBase64) && data.LogoBase64Id != 0)
            {
                data.LogoBase64 = _organisationLogoManager.GetOrganisationLogoBase64(data.LogoBase64Id);
            }


            data.LogoSrcFormat = jsonObj.GetProperty("LogoSrcFormat").GetString();

            #endregion


            #region Number

            JsonElement number;
            if (jsonObj.TryGetProperty("Number", out number))
            {
                data.Number = JsonSerializer.Deserialize <Tuple <string, string> >(number.ToString());
            }

            #endregion


            #region Invoice

            JsonElement invoice;
            if (jsonObj.TryGetProperty("Invoice", out invoice))
            {
                data.Invoice = JsonSerializer.Deserialize <List <Tuple <string, string> > >(invoice.ToString());
            }

            #endregion


            #region Customer

            JsonElement customer;
            if (jsonObj.TryGetProperty("Customer", out customer))
            {
                data.Customer = JsonSerializer.Deserialize <Tuple <string, string> >(customer.ToString());
            }

            #endregion


            #region TableHeaderRow, TableBodyRows, TableFooterRows, Total

            JsonElement tableHeaderRow;
            if (jsonObj.TryGetProperty("TableHeaderRow", out tableHeaderRow))
            {
                data.TableHeaderRow = tableHeaderRow.EnumerateArray().Select(x => x.GetString()).ToList();
            }

            JsonElement tableBodyRows;
            if (jsonObj.TryGetProperty("TableBodyRows", out tableBodyRows))
            {
                data.TableBodyRows = JsonSerializer.Deserialize <List <List <string> > >(tableBodyRows.ToString());
            }

            JsonElement tableFooterRows;
            if (jsonObj.TryGetProperty("TableFooterRows", out tableFooterRows))
            {
                data.TableFooterRows = JsonSerializer.Deserialize <List <Tuple <string, string> > >(tableFooterRows.ToString());
            }

            JsonElement tableTotalRow;
            if (jsonObj.TryGetProperty("TableTotalRow", out tableTotalRow))
            {
                data.TableTotalRow = JsonSerializer.Deserialize <Tuple <string, string> >(tableTotalRow.ToString());
            }

            #endregion


            #region Terms

            JsonElement terms;
            if (jsonObj.TryGetProperty("Terms", out terms))
            {
                data.Terms = JsonSerializer.Deserialize <Tuple <string, string> >(terms.ToString());
            }

            #endregion


            #region Notes

            JsonElement notes;
            if (jsonObj.TryGetProperty("Notes", out notes))
            {
                data.Notes = JsonSerializer.Deserialize <Tuple <string, string> >(notes.ToString());
            }

            #endregion


            #region Consignee

            JsonElement consignee;
            if (jsonObj.TryGetProperty("Consignee", out consignee))
            {
                data.Consignee = JsonSerializer.Deserialize <Tuple <string, string> >(consignee.ToString());
            }

            #endregion


            #region Addresses

            data.DeliveryAddressID = !String.IsNullOrEmpty(jsonObj.GetProperty("DeliveryAddressID").GetString()) ? jsonObj.GetProperty("DeliveryAddressID").GetInt32() : 0;
            data.BillingAddressID  = !String.IsNullOrEmpty(jsonObj.GetProperty("BillingAddressID").GetString()) ? jsonObj.GetProperty("BillingAddressID").GetInt32() : 0;

            #endregion

            return(data);
        }
        private static InvoiceFormattedData CreateData(Invoice invoice, int billingAddressID, int deliveryAddressID)
        {
            var data = new InvoiceFormattedData();
            var sb = new StringBuilder();
            var list = new List<string>();
            var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language);


            #region TemplateType

            data.TemplateType = (int)invoice.TemplateType;

            #endregion


            #region Seller, LogoBase64, LogoSrcFormat

            var invoiceSettings = Global.DaoFactory.GetInvoiceDao().GetSettings();

            if (!string.IsNullOrEmpty(invoiceSettings.CompanyName))
            {
                sb.Append(invoiceSettings.CompanyName);
            }

            if (!string.IsNullOrEmpty(invoiceSettings.CompanyAddress))
            {
                var obj = JObject.Parse(invoiceSettings.CompanyAddress);

                var str = obj.Value<string>("country");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("state");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("city");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("street");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                str = obj.Value<string>("zip");
                if (!string.IsNullOrEmpty(str))
                    list.Add(str);

                if (list.Count > 0)
                {
                    sb.AppendLine();
                    sb.Append(string.Join(", ", list));
                }
            }

            data.Seller = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Seller", cultureInfo), sb.ToString());

            if (invoiceSettings.CompanyLogoID != 0)
            {
                data.LogoBase64Id = invoiceSettings.CompanyLogoID;
                //data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(invoiceSettings.CompanyLogoID);
                data.LogoSrcFormat = OrganisationLogoManager.OrganisationLogoSrcFormat;
            }

            #endregion


            #region Number

            data.Number = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Invoice", cultureInfo), invoice.Number);

            #endregion


            #region Invoice

            data.Invoice = new List<Tuple<string, string>>();
            data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("IssueDate", cultureInfo), invoice.IssueDate.ToShortDateString()));
            if (!string.IsNullOrEmpty(invoice.PurchaseOrderNumber))
            {
                data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("PONumber", cultureInfo), invoice.PurchaseOrderNumber));
            }
            data.Invoice.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("DueDate", cultureInfo), invoice.DueDate.ToShortDateString()));

            #endregion


            #region Customer

            var customer = Global.DaoFactory.GetContactDao().GetByID(invoice.ContactID);

            if (customer != null)
            {
                sb = new StringBuilder();

                sb.Append(customer.GetTitle());

                var billingAddress = billingAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(billingAddressID) : null;
                if (billingAddress != null && billingAddress.InfoType == ContactInfoType.Address && billingAddress.Category == (int)AddressCategory.Billing)
                {
                    list = new List<string>();

                    var obj = JObject.Parse(billingAddress.Data);

                    var str = obj.Value<string>("country");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("state");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("city");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("street");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("zip");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    if (list.Count > 0)
                    {
                        sb.AppendLine();
                        sb.Append(string.Join(", ", list));
                    }
                }

                data.Customer = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("BillTo", cultureInfo), sb.ToString());
            }

            #endregion


            #region TableHeaderRow, TableBodyRows, TableFooterRows, TableTotalRow

            data.TableHeaderRow = new List<string>
                {
                    CRMInvoiceResource.ResourceManager.GetString("ItemCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("QuantityCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("PriceCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("DiscountCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("TaxCol", cultureInfo),
                    CRMInvoiceResource.ResourceManager.GetString("AmountCol", cultureInfo)
                };

            data.TableBodyRows = new List<List<string>>();

            var invoiceLines = invoice.GetInvoiceLines();
            var invoiceTaxes = new Dictionary<int, decimal>();

            decimal subtotal = 0;
            decimal discount = 0;
            decimal amount = 0;

            foreach (var line in invoiceLines)
            {
                var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID);
                var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null;
                var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null;

                var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                var rate = 0;
                if (tax1 != null)
                {
                    rate += tax1.Rate;
                    if (invoiceTaxes.ContainsKey(tax1.ID))
                    {
                        invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                    }
                }
                if (tax2 != null)
                {
                    rate += tax2.Rate;
                    if (invoiceTaxes.ContainsKey(tax2.ID))
                    {
                        invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                    }
                }

                decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                subtotal += subtotalValue;
                discount += discountValue;
                amount += amountValue;

                data.TableBodyRows.Add(new List<string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " +line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue-discountValue).ToString(CultureInfo.InvariantCulture)
                    });
            }

            data.TableFooterRows = new List<Tuple<string, string>>();
            data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

            foreach (var invoiceTax in invoiceTaxes)
            {
                var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key);
                data.TableFooterRows.Add(new Tuple<string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
            }

            //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

            data.TableTotalRow = new Tuple<string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


            #endregion


            #region Terms

            data.Terms = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Terms", cultureInfo), invoice.Terms);

            #endregion


            #region Notes

            if (!string.IsNullOrEmpty(invoice.Description))
            {
                data.Notes = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("ClientNotes", cultureInfo), invoice.Description);
            }

            #endregion


            #region Consignee

            var consignee = Global.DaoFactory.GetContactDao().GetByID(invoice.ConsigneeID);

            if (consignee != null)
            {
                sb = new StringBuilder();

                sb.Append(consignee.GetTitle());

                var deliveryAddress = deliveryAddressID != 0 ? Global.DaoFactory.GetContactInfoDao().GetByID(deliveryAddressID) : null;
                if (deliveryAddress != null && deliveryAddress.InfoType == ContactInfoType.Address && deliveryAddress.Category == (int)AddressCategory.Postal)
                {
                    list = new List<string>();

                    var obj = JObject.Parse(deliveryAddress.Data);

                    var str = obj.Value<string>("country");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("state");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("city");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("street");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    str = obj.Value<string>("zip");
                    if (!string.IsNullOrEmpty(str))
                        list.Add(str);

                    if (list.Count > 0)
                    {
                        sb.AppendLine();
                        sb.Append(string.Join(", ", list));
                    }
                }

                data.Consignee = new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("ShipTo", cultureInfo), sb.ToString());
            }

            #endregion

            #region Addresses

            data.BillingAddressID = billingAddressID;
            data.DeliveryAddressID = deliveryAddressID;

            #endregion

            return data;
        }
예제 #10
0
        private static InvoiceFormattedData CreateDataAfterLinesUpdated(Invoice invoice, InvoiceFormattedData invoiceOldData)
        {
            var data = invoiceOldData;

            var cultureInfo = string.IsNullOrEmpty(invoice.Language) ? CultureInfo.CurrentCulture : CultureInfo.GetCultureInfo(invoice.Language);

            #region TableBodyRows, TableFooterRows, TableTotalRow

            data.TableBodyRows = new List<List<string>>();

            var invoiceLines = invoice.GetInvoiceLines();
            var invoiceTaxes = new Dictionary<int, decimal>();

            decimal subtotal = 0;
            decimal discount = 0;
            decimal amount = 0;

            foreach (var line in invoiceLines)
            {
                var item = Global.DaoFactory.GetInvoiceItemDao().GetByID(line.InvoiceItemID);
                var tax1 = line.InvoiceTax1ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax1ID) : null;
                var tax2 = line.InvoiceTax2ID > 0 ? Global.DaoFactory.GetInvoiceTaxDao().GetByID(line.InvoiceTax2ID) : null;

                var subtotalValue = Math.Round(line.Quantity * line.Price, 2);
                var discountValue = Math.Round(subtotalValue * line.Discount / 100, 2);

                var rate = 0;
                if (tax1 != null)
                {
                    rate += tax1.Rate;
                    if (invoiceTaxes.ContainsKey(tax1.ID))
                    {
                        invoiceTaxes[tax1.ID] = invoiceTaxes[tax1.ID] + Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax1.ID, Math.Round((subtotalValue - discountValue) * tax1.Rate / 100, 2));
                    }
                }
                if (tax2 != null)
                {
                    rate += tax2.Rate;
                    if (invoiceTaxes.ContainsKey(tax2.ID))
                    {
                        invoiceTaxes[tax2.ID] = invoiceTaxes[tax2.ID] + Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2);
                    }
                    else
                    {
                        invoiceTaxes.Add(tax2.ID, Math.Round((subtotalValue - discountValue) * tax2.Rate / 100, 2));
                    }
                }

                decimal taxValue = Math.Round((subtotalValue - discountValue) * rate / 100, 2);
                decimal amountValue = Math.Round(subtotalValue - discountValue + taxValue, 2);

                subtotal += subtotalValue;
                discount += discountValue;
                amount += amountValue;

                data.TableBodyRows.Add(new List<string>
                    {
                        item.Title + (string.IsNullOrEmpty(line.Description) ? string.Empty : ": " +line.Description),
                        line.Quantity.ToString(CultureInfo.InvariantCulture),
                        line.Price.ToString(CultureInfo.InvariantCulture),
                        line.Discount.ToString(CultureInfo.InvariantCulture),
                        tax1 != null ? tax1.Name : string.Empty,
                        tax2 != null ? tax2.Name : string.Empty,
                        (subtotalValue-discountValue).ToString(CultureInfo.InvariantCulture)
                    });
            }

            data.TableFooterRows = new List<Tuple<string, string>>();
            data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Subtotal", cultureInfo), (subtotal - discount).ToString(CultureInfo.InvariantCulture)));

            foreach (var invoiceTax in invoiceTaxes)
            {
                var iTax = Global.DaoFactory.GetInvoiceTaxDao().GetByID(invoiceTax.Key);
                data.TableFooterRows.Add(new Tuple<string, string>(string.Format("{0} ({1}%)", iTax.Name, iTax.Rate), invoiceTax.Value.ToString(CultureInfo.InvariantCulture)));
            }

            //data.TableFooterRows.Add(new Tuple<string, string>(CRMInvoiceResource.ResourceManager.GetString("Discount", cultureInfo), "-" + discount.ToString(CultureInfo.InvariantCulture)));

            data.TableTotalRow = new Tuple<string, string>(string.Format("{0} ({1})", CRMInvoiceResource.ResourceManager.GetString("Total", cultureInfo), invoice.Currency), amount.ToString(CultureInfo.InvariantCulture));


            #endregion


            return data;
        }
예제 #11
0
        private static InvoiceFormattedData ReadData(string jsonData)
        {
            var data = new InvoiceFormattedData();
            var jsonObj = JObject.Parse(jsonData);


            #region TemplateType

            data.TemplateType = jsonObj.Value<int>("TemplateType");

            #endregion


            #region Seller, LogoBase64, LogoSrcFormat

            var seller = jsonObj.Value<JObject>("Seller");
            if (seller != null)
            {
                data.Seller = seller.ToObject<Tuple<string, string>>();
            }

            data.LogoBase64 = jsonObj.Value<string>("LogoBase64");
            data.LogoBase64Id = !String.IsNullOrEmpty(jsonObj.Value<string>("LogoBase64Id")) ? jsonObj.Value<int>("LogoBase64Id") : 0;

            if (string.IsNullOrEmpty(data.LogoBase64) && data.LogoBase64Id != 0)
            {
                 data.LogoBase64 = OrganisationLogoManager.GetOrganisationLogoBase64(data.LogoBase64Id);
            }


            data.LogoSrcFormat = jsonObj.Value<string>("LogoSrcFormat");

            #endregion


            #region Number

            var number = jsonObj.Value<JObject>("Number");
            if (number != null)
            {
                data.Number = number.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region Invoice

            var invoice = jsonObj.Value<JArray>("Invoice");
            if (invoice != null)
            {
                data.Invoice = invoice.ToObject<List<Tuple<string, string>>>();
            }

            #endregion


            #region Customer

            var customer = jsonObj.Value<JObject>("Customer");
            if (customer != null)
            {
                data.Customer = customer.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region TableHeaderRow, TableBodyRows, TableFooterRows, Total

            var tableHeaderRow = jsonObj.Value<JArray>("TableHeaderRow");
            if (tableHeaderRow != null)
            {
                data.TableHeaderRow = tableHeaderRow.ToObject<List<string>>();
            }

            var tableBodyRows = jsonObj.Value<JArray>("TableBodyRows");
            if (tableBodyRows != null)
            {
                data.TableBodyRows = tableBodyRows.ToObject<List<List<string>>>();
            }

            var tableFooterRows = jsonObj.Value<JArray>("TableFooterRows");
            if (tableFooterRows != null)
            {
                data.TableFooterRows = tableFooterRows.ToObject<List<Tuple<string, string>>>();
            }

            var tableTotalRow = jsonObj.Value<JObject>("TableTotalRow");
            if (tableTotalRow != null)
            {
                data.TableTotalRow = tableTotalRow.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region Terms

            var terms = jsonObj.Value<JObject>("Terms");
            if (terms != null)
            {
                data.Terms = terms.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region Notes

            var notes = jsonObj.Value<JObject>("Notes");
            if (notes != null)
            {
                data.Notes = notes.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region Consignee

            var consignee = jsonObj.Value<JObject>("Consignee");
            if (consignee != null)
            {
                data.Consignee = consignee.ToObject<Tuple<string, string>>();
            }

            #endregion


            #region Addresses

            data.DeliveryAddressID = !String.IsNullOrEmpty(jsonObj.Value<string>("DeliveryAddressID")) ? jsonObj.Value<int>("DeliveryAddressID") : 0;
            data.BillingAddressID = !String.IsNullOrEmpty(jsonObj.Value<string>("BillingAddressID")) ? jsonObj.Value<int>("BillingAddressID") : 0;

            #endregion

            return data;
        }
예제 #12
0
        private static Stream GetStreamDocx(Invoice data)
        {
            var invoiceData = InvoiceFormattedData.GetData(data, 0, 0);
            var logo        = new byte[] { };

            if (!string.IsNullOrEmpty(invoiceData.LogoBase64))
            {
                logo = Convert.FromBase64String(invoiceData.LogoBase64);
            }
            else if (invoiceData.LogoBase64Id != 0)
            {
                logo = Convert.FromBase64String(OrganisationLogoManager.GetOrganisationLogoBase64(invoiceData.LogoBase64Id));
            }

            var result = new MemoryStream();

            using (var zipOutputStream = new ZipOutputStream(result))
                using (var zipInputStream = new ZipInputStream(Template))
                {
                    ZipEntry zipEntry;
                    zipOutputStream.IsStreamOwner = false;

                    while ((zipEntry = zipInputStream.GetNextEntry()) != null)
                    {
                        zipOutputStream.PutNextEntry(new ZipEntry(zipEntry.Name));

                        if (zipEntry.Name == DocumentXml)
                        {
                            using (var documentXmlStream = new MemoryStream())
                            {
                                zipInputStream.CopyTo(documentXmlStream);
                                documentXmlStream.Position = 0;

                                var document = new XmlDocument();
                                document.Load(documentXmlStream);
                                var documentStr = GenerateDocumentXml(document, invoiceData, logo);
                                using (var documentStrAsStream = new MemoryStream(Encoding.UTF8.GetBytes(documentStr)))
                                {
                                    documentStrAsStream.CopyTo(zipOutputStream);
                                }
                            }
                            continue;
                        }

                        if (zipEntry.Name == DocumentLogoImage && logo.Length > 0)
                        {
                            using (var logoAsStream = new MemoryStream(logo))
                            {
                                logoAsStream.CopyTo(zipOutputStream);
                            }
                            continue;
                        }

                        zipInputStream.CopyTo(zipOutputStream);
                    }

                    zipOutputStream.Finish();

                    result.Position = 0;
                }

            return(result);
        }