public override void ExportCustomerOrders(Customer customer)
        {
            var orderRepository = DbManger.GetInstance().GetOrderRepository();
            var productRepository = DbManger.GetInstance().GetProductRepository();
            //            var ratesRepository = DbManger.GetInstance().GetRatesRepository();

            var customerExport = new StringBuilder();
            customerExport.AppendLine(String.Format("{0}", customer.GetFullName().ToUpper()));
            customerExport.AppendLine();

            // информация о комиссии пользователя
            //            ManagedRate comission;
            List<Order> orders;
            try
            {
            //                comission = ratesRepository.GetById(customer.AccountTypeId);
                orders = orderRepository.GetOrdersForCustomerFromAlbum(customer, WorkingAlbum);
            }
            catch (Exception exception)
            {
                m_logger.ErrorException(exception);
                throw new ApplicationException("Ошибка: Не удалось выполнить чтение из БД");
            }

            int positionNum = 1;
            decimal cleanSum = 0;

            foreach (Order order in orders)
            {
                if (!IsIncludingEmpty && order.Amount == 0) continue;

                Product productInfo = null;
                OnProgressChanged("Получение информации о продукте");

                string partialIndicator = "";
                try
                {
                    productInfo = productRepository.GetById(order.ProductId);
                    var total = orderRepository.GetProductTotalOrderedAmount(productInfo);
                    if (total < productInfo.MinAmount)
                    {
                        if (!IsIncludingPartial)
                        {
                            continue;
                        }
                        else partialIndicator = "(!)";
                    }

                }
                catch (Exception exception)
                {
                    m_logger.ErrorException(exception);
                    continue;
                }

                decimal sum = order.Amount * productInfo.Price;
                cleanSum += sum;

                customerExport.AppendLine(String.Format("{0} {1}. {2} {3}: {4:C}", positionNum, partialIndicator, productInfo.Title, order.Amount, sum));
                positionNum++;
            }

            var comission = customer.GetCommissionInfo();
            var comissionValue = cleanSum*(comission.Rate/100);
            var summary = cleanSum*(1 + (comission.Rate/100));

            customerExport.AppendLine(String.Format("Сумма: {0:C2}", cleanSum));
            customerExport.AppendLine(String.Format("{0}: {1:C2}", comission.Comment, comissionValue));

            var delivery = customer.GetDeliveryInfo();
            if (delivery != null && delivery.IsActive)
            {
                if ((delivery.IsConditional &&
                         delivery.MinimumOrderSummaryCondition > summary) ||
                        delivery.IsConditional == false)
                {
                    summary += delivery.Price;
                    customerExport.AppendLine(String.Format("Доставка: {0:C0}", delivery.Price));
                }
            }

            customerExport.AppendLine(String.Format("Итог: {0:C0}", summary));
            System.IO.File.WriteAllText(m_filename, customerExport.ToString(), Encoding.UTF8);
        }
Пример #2
0
        public override void ExportCustomerOrders(Customer customer)
        {
            if (!System.IO.File.Exists(CustomerOrderTemplate))
            {
                throw new ApplicationException("Файл шаблона для данного документа не найден!");
            }

            const string itemsTableBookmark = @"customer_orders_table";
            const string customerNameBookmark = @"customer_name";
            const string dateBookmark = @"current_date";
            const string clearSumBookmark = @"clear_sum";
            const string comissionSumBookmark = @"comission";
            const string totalSumBookmark = @"total";
            const string addressBookmark = @"customer_address";
            const string deliveryBookmark = @"delivery_value";

            var orderRepo = DbManger.GetInstance().GetOrderRepository();
            var prodRepo = DbManger.GetInstance().GetProductRepository();
            //            var ratesRepo = DbManger.GetInstance().GetRatesRepository();

            //            ManagedRate comission;
            //            try
            //            {
            //                comission = ratesRepo.GetById(customer.AccountTypeId);
            //            }
            //            catch (Exception e)
            //            {
            //                m_log.ErrorException(e);
            //                throw new ApplicationException("Ошибка. Не удалось получить ставку покупателя.");
            //            }
            if(customer.GetCommissionInfo() == null)
                throw new ApplicationException("Ошибка. Не удалось получить ставку покупателя.");

            List<Order> orders;
            try
            {
                orders = orderRepo.GetOrdersForCustomerFromAlbum(customer, WorkingAlbum);
            }
            catch (Exception e)
            {
                m_log.ErrorException(e);
                throw new ApplicationException("Не удалось получить список заказов для покупателя.");
            }

            Word.Application word;
            try
            {
                word = new Word.Application();
            }
            catch (Exception e)
            {
                m_log.ErrorException(e);
                throw new ApplicationException("Не удалось запустить MS Word. Пожалуйста удостоверьтесь, что установлена версия MS MSWord не ниже 2007.");
            }

            // word.Visible = true;
            var doc = word.Documents.Open(CustomerOrderTemplate);
            if (!doc.Bookmarks.Exists(itemsTableBookmark))
            {
                m_log.ErrorFormat("Content bookmark '{0}' not found in template!", itemsTableBookmark);
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }

            var range = doc.Bookmarks[itemsTableBookmark].Range;
            if (range.Tables.Count == 0)
            {
                m_log.ErrorFormat("Content bookmark '{0}' is not containing table to fill!", itemsTableBookmark);
                doc.Close();
                word.Quit();
                throw new ApplicationException(String.Format("Шаблон '{0}' некорректен!", CustomerOrderTemplate));
            }

            var table = range.Tables[1];
            int row = 2;
            decimal clearSum = 0;
            for (int i = 0; i < orders.Count; i++)
            {
                var order = orders[i];

                if (order.Amount == 0 && !IsIncludingEmpty) continue;

                //string partialIndicator = "";
                Product p;
                try
                {
                    p = prodRepo.GetById(order.ProductId);
                    if (p == null)
                    {
                        continue;
                    }
                    var total = orderRepo.GetProductTotalOrderedAmount(p);
                    if (total < p.MinAmount)
                    {
                        if (!IsIncludingPartial)
                        {
                            continue;
                        }
                       // else partialIndicator = "(!)";
                    }
                }
                catch (Exception e)
                {
                    m_log.ErrorException(e);
                    throw new ApplicationException("Ошибка БД.");
                }

                var title = p.GenericUrl.Length > 0 ? String.Format("{0} ({1})", p.Title, p.GenericUrl) : p.Title;

                table.Rows.Add();
                table.Cell(row, 1).Range.Text = (row - 1).ToString();
                table.Cell(row, 2).Range.Text = title;
                table.Cell(row, 3).Range.Text = p.Price.ToString("C2");
                table.Cell(row, 4).Range.Text = order.Amount.ToString();
                table.Cell(row, 5).Range.Text = (p.Price*order.Amount).ToString("C2");

                clearSum += (p.Price*order.Amount);
                row++;
            }

            try
            {
                table.Rows[row].Delete();
            }
            catch (Exception)
            {

            }

            var comission = customer.GetCommissionInfo();
            var comissionValue = (clearSum*(comission.Rate/100));
            var summary = clearSum*(1 + comission.Rate/100);
            decimal deliveryPrice = 0;

            var delivery = customer.GetDeliveryInfo();
            if (delivery != null && delivery.IsActive)
            {
                if ((delivery.IsConditional &&
                         delivery.MinimumOrderSummaryCondition > summary) ||
                        delivery.IsConditional == false)
                {
                    summary += delivery.Price;
                    deliveryPrice = delivery.Price;
                }
            }

            if (doc.Bookmarks.Exists(customerNameBookmark))
            {
                doc.Bookmarks[customerNameBookmark].Range.Text = customer.GetFullName();
            }
            if (doc.Bookmarks.Exists(dateBookmark))
            {
                doc.Bookmarks[dateBookmark].Range.Text = DateTime.Now.ToLongDateString();
            }
            if (doc.Bookmarks.Exists(clearSumBookmark))
            {
                doc.Bookmarks[clearSumBookmark].Range.Text = String.Format("Сумма: {0:C2}", clearSum);
            }
            if (doc.Bookmarks.Exists(comissionSumBookmark))
            {
                doc.Bookmarks[comissionSumBookmark].Range.Text = String.Format("{0}: {1:C2}", comission.Comment, comissionValue);
            }
            if (doc.Bookmarks.Exists(deliveryBookmark))
            {
                doc.Bookmarks[deliveryBookmark].Range.Text = String.Format("Доставка: {0:C0}", deliveryPrice);
            }
            if (doc.Bookmarks.Exists(totalSumBookmark))
            {
                doc.Bookmarks[totalSumBookmark].Range.Text = String.Format("Итого: {0:C0}", summary);
            }
            if (doc.Bookmarks.Exists(addressBookmark))
            {
                doc.Bookmarks[addressBookmark].Range.Text = customer.Address;
            }

            doc.SaveAs(m_filename);
            doc.Close();
            word.Quit();
        }
        public override void ExportCustomerOrders(Customer customer)
        {
            ClearDocument();

            var orderRepository = DbManger.GetInstance().GetOrderRepository();
            var productRepository = DbManger.GetInstance().GetProductRepository();
            //            var ratesRepository = DbManger.GetInstance().GetRatesRepository();

            if (customer.GetCommissionInfo() == null)
                throw new ApplicationException("Для покупателя неверно установлена ставка комиссии!");

            // информация о комиссии пользователя
            //            ManagedRate comission;
            List<Order> orders;
            try
            {
            //                comission = ratesRepository.GetById(customer.AccountTypeId);
                orders = orderRepository.GetOrdersForCustomerFromAlbum(customer, WorkingAlbum);
            }
            catch (Exception exception)
            {
                m_logger.ErrorException(exception);
                throw new ApplicationException("Ошибка: Не удалось выполнить чтение из БД");
            }

            // прелоад информации о способе доставки
            customer.GetDeliveryInfo();

            var orderInfo = new CustomerOrderInfo(customer);
            foreach (Order order in orders)
            {
                if (!IsIncludingEmpty && order.Amount == 0) continue;

                Product productInfo;
                OnProgressChanged("Получение информации о продукте");

                string partialIndicator = "";
                try
                {
                    productInfo = productRepository.GetById(order.ProductId);
                    var total = orderRepository.GetProductTotalOrderedAmount(productInfo);
                    if (total < productInfo.MinAmount)
                    {
                        if (!IsIncludingPartial)
                        {
                            continue;
                        }

                        partialIndicator = "(!)";
                    }
                }
                catch (Exception exception)
                {
                    m_logger.ErrorException(exception);
                    continue;
                }

                orderInfo.Items.Add(new CustomerOrderItem
                    {
                        Amount = order.Amount,
                        Price = productInfo.Price,
                        IsPartial = partialIndicator.Length > 0,
                        Title = productInfo.Title
                    });
            }

            m_document.Dispatcher.Invoke(DispatcherPriority.Normal, new Action<object>(o =>
            {
                var borderThick = new Thickness(1);
                var borderColor = Brushes.LightGray;

                var corders = (CustomerOrderInfo) o;

                m_document.Blocks.Add(
                    new Paragraph(new Run(corders.Customer.GetFullName().ToUpper()))
                        {
                            FontSize = 16,
                            FontWeight = FontWeights.Bold
                        });

                var table = new Table { CellSpacing = 3, FontSize = 12 };

                const int numberOfColumns = 5;
                for (int x = 0; x < numberOfColumns; x++)
                {
                    table.Columns.Add(new TableColumn());
                    table.Columns[x].Background = x % 2 == 0 ? Brushes.White : Brushes.WhiteSmoke;
                }

                table.Columns[0].Width = new GridLength(30);
                table.Columns[1].Width = new GridLength(400);
                table.Columns[2].Width = new GridLength(100);
                table.Columns[3].Width = new GridLength(60);
                table.Columns[4].Width = new GridLength(100);

                var rowGroup = new TableRowGroup();
                table.RowGroups.Add(rowGroup);

                var row = new TableRow { FontWeight = FontWeights.Bold };
                rowGroup.Rows.Add(row);

                #region Table title
                row.Cells.Add(new TableCell(new Paragraph(new Run("№")))
                {
                    TextAlignment = TextAlignment.Center,
                    Padding = new Thickness(5),
                    BorderThickness = borderThick,
                    BorderBrush = borderColor
                });
                row.Cells.Add(new TableCell(new Paragraph(new Run("Наименование")))
                {
                    TextAlignment = TextAlignment.Center,
                    Padding = new Thickness(5),
                    BorderThickness = borderThick,
                    BorderBrush = borderColor
                });
                row.Cells.Add(new TableCell(new Paragraph(new Run("Цена")))
                {
                    TextAlignment = TextAlignment.Center,
                    Padding = new Thickness(5),
                    BorderThickness = borderThick,
                    BorderBrush = borderColor
                });
                row.Cells.Add(new TableCell(new Paragraph(new Run("Кол-во")))
                {
                    TextAlignment = TextAlignment.Center,
                    Padding = new Thickness(5),
                    BorderThickness = borderThick,
                    BorderBrush = borderColor
                });
                row.Cells.Add(new TableCell(new Paragraph(new Run("Сумма")))
                {
                    TextAlignment = TextAlignment.Center,
                    Padding = new Thickness(5),
                    BorderThickness = borderThick,
                    BorderBrush = borderColor
                });
                #endregion

                var rowNum = 1;
                decimal summary = 0;
                foreach (var order in corders.Items)
                {
                    summary += order.Total;

                    row = new TableRow { Background = rowNum % 2 == 0 ? Brushes.WhiteSmoke : Brushes.White };
                    rowGroup.Rows.Add(row);

                    row.Cells.Add(new TableCell(new Paragraph(new Run(rowNum.ToString())))
                    {
                        TextAlignment = TextAlignment.Center,
                        Padding = new Thickness(5),
                        BorderThickness = borderThick,
                        BorderBrush = borderColor
                    });
                    row.Cells.Add(new TableCell(new Paragraph(new Run(order.Title)))
                    {
                        TextAlignment = TextAlignment.Left,
                        Padding = new Thickness(5),
                        BorderThickness = borderThick,
                        BorderBrush = borderColor
                    });
                    row.Cells.Add(new TableCell(new Paragraph(new Run(order.Price.ToString("C2"))))
                    {
                        TextAlignment = TextAlignment.Center,
                        Padding = new Thickness(5),
                        BorderThickness = borderThick,
                        BorderBrush = borderColor
                    });
                    row.Cells.Add(new TableCell(new Paragraph(new Run(order.Amount.ToString())))
                    {
                        TextAlignment = TextAlignment.Center,
                        Padding = new Thickness(5),
                        BorderThickness = borderThick,
                        BorderBrush = borderColor
                    });
                    row.Cells.Add(new TableCell(new Paragraph(new Run(order.Total.ToString("C2"))))
                    {
                        TextAlignment = TextAlignment.Center,
                        Padding = new Thickness(5),
                        BorderThickness = borderThick,
                        BorderBrush = borderColor
                    });
                    rowNum++;
                }

                var commission = corders.Customer.GetCommissionInfo();
                var comissionValue = summary * (commission.Rate / 100);
                var total = summary * (1 + (commission.Rate / 100));
                var delivery = corders.Customer.GetDeliveryInfo();

                var p = new Paragraph(new Run(String.Format("Сумма: {0}", summary.ToString("C2"))))
                    {
                        FontSize = 13,
                        FontWeight = FontWeights.Bold
                    };
                p.Inlines.Add(new LineBreak());
                p.Inlines.Add(new Run(String.Format("Сбор ({0}): {1:C2}", commission.Comment, comissionValue))
                    {
                        FontSize = 13,
                        FontWeight = FontWeights.Bold
                    });
                p.Inlines.Add(new LineBreak());

                if (delivery != null && delivery.IsActive)
                {
                    if ((delivery.IsConditional &&
                         delivery.MinimumOrderSummaryCondition > summary) ||
                        delivery.IsConditional == false)
                    {
                        total += delivery.Price;
                        p.Inlines.Add(new Run(String.Format("Доставка: {0:C2}", delivery.Price))
                        {
                            FontSize = 13,
                            FontWeight = FontWeights.Bold
                        });
                        p.Inlines.Add(new LineBreak());
                    }
                }

                p.Inlines.Add(new Run(String.Format("Итог: {0:C0}", total))
                {
                    FontSize = 13,
                    FontWeight = FontWeights.Bold
                });
                p.Inlines.Add(new LineBreak());

                m_document.Blocks.Add(table);
                m_document.Blocks.Add(p);

                m_document.Tag = corders.Customer.GetFullName();
            }), orderInfo);
        }