public CommentCheckWindow(Window owner, string sourceMessage, Customer sender, Order order, Product product, OrderOperation requestedOperation)
        {
            InitializeComponent();

            Owner = owner;
            m_order = order;
            m_requestedOperation = requestedOperation;

            tbOriginalText.IsReadOnly = true;
            tbOriginalText.Text = sourceMessage;
            tbAmount.Text = order.Amount.ToString();
            lblPrice.Content = product.Price.ToString("C", CultureInfo.CurrentCulture);
            lblMin.Content = product.MinAmount.ToString("");
            tbTitle.Text = product.Title;
            lblCustomer.Content = sender.GetFullName();

            switch (requestedOperation)
            {
                case OrderOperation.Add:
                    rbAppendOrder.IsChecked = true;
                    break;
                case OrderOperation.Remove:
                    rbRemovePosition.IsChecked = true;
                    break;
                case OrderOperation.Decrease:
                    rbSkipComment.IsChecked = true;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("requestedOperation");
            }

            if (!String.IsNullOrEmpty(product.ImageFile)
                && System.IO.File.Exists(System.IO.Path.Combine(RegistrySettings.GetInstance().GalleryPath, product.ImageFile)))
            {
                image1.Source =
                    new BitmapImage(new Uri(String.Format("file://{0}",
                        System.IO.Path.Combine(RegistrySettings.GetInstance().GalleryPath, product.ImageFile))));
            }
            else
            {
                // set default image
                image1.Source =
                    new BitmapImage(new Uri("pack://application:,,,/Images/default.png"));
            }
        }
예제 #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)
        {
            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);
        }