Exemplo n.º 1
0
 public CustomerListViewItem(Customer customer)
 {
     Payment = 0;
     Source = customer;
     Source.PropertyChanged += Source_PropertyChanged;
     HasPartialPosition = false;
     // OrderedItemsCount = 0;
     CleanSum = 0;
 }
Exemplo n.º 2
0
 public List<Payment> AllForCustomer(Customer customer)
 {
     using (var s = m_dbManger.OpenSession())
     {
         IQuery q = s.CreateQuery("from Payment as p where p.PayerId = :pid");
         q.SetInt32("pid", customer.Id);
         return (List<Payment>)q.List<Payment>();
     }
 }
        public CustomerEditWindow(Window owner, Customer customer)
        {
            m_customer = customer;

            InitializeComponent();
            Owner = owner;

            KeyUp += OnKeyUp;

            tbName.Text = customer.FirstName;
            tbSurname.Text = customer.LastName;

            var ratesRepo = DbManger.GetInstance().GetRatesRepository();
            List<ManagedRate> rates;
            try
            {
                rates = ratesRepo.GetAll();
            }
            catch (Exception)
            {
                rates = new List<ManagedRate>(0);
            }

            int selectedIndex = 0;
            for (int index = 0; index < rates.Count; index++)
            {
                ManagedRate managedRate = rates[index];
                if (m_customer.AccountTypeId == managedRate.Id) selectedIndex = index;
                comboBox1.Items.Add(managedRate);
            }

            if (comboBox1.Items.Count > 0) comboBox1.SelectedIndex = selectedIndex;

            List<DeliveryType> delivery;
            try
            {
                delivery = DbManger.GetInstance().GetDeliveryRepository().All();
            }
            catch
            {
                delivery = new List<DeliveryType>(0);
            }
            selectedIndex = 0;
            for (int i = 0; i < delivery.Count; i++)
            {
                DeliveryType dt = delivery[i];
                if (m_customer.DeliveryTypeId == dt.Id) selectedIndex = i;
                comboBox2.Items.Add(dt);
            }
            if (comboBox2.Items.Count > 0) comboBox2.SelectedIndex = selectedIndex;

            tbAddress.Text = customer.Address;
            tbPhone.Text = customer.Phone;
        }
Exemplo n.º 4
0
 public void Delete(Customer customer)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Delete(customer);
             t.Commit();
             DeleteFromCache(customer);
         }
     }
 }
Exemplo n.º 5
0
 public void Add(Customer c)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Save(c);
             t.Commit();
             AddToCache(c);
         }
     }
 }
Exemplo n.º 6
0
        public OrderEditWindow(Window owner, CustomerListViewItem customer, Album album)
        {
            m_sourceListViewItem = customer;
            m_customer = customer.Source;
            m_customerItem = customer;
            m_album = album;
            m_settings = RegistrySettings.GetInstance();
            m_orders = new List<Order>(0);

            InitializeComponent();
            Owner = owner;

            KeyUp += OnKeyUp;

            FillOrdersTable();
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            var c = new Customer
                {
                    FirstName = @"Новый покупатель",
                    AccountTypeId = 0,
                    VkId = Int32.MinValue,
                    Id = Int32.MinValue
                };
            var cew = new CustomerEditWindow(this, c);
            cew.ShowDialog();

            if (cew.DialogResult.HasValue && cew.DialogResult.Value)
            {
                ReloadList();
            }
        }
        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"));
            }
        }
 public ProductCustomerListViewItem(Order orderInfo, Customer customerInfo)
 {
     m_customerInfo = customerInfo;
     m_orderInfo = orderInfo;
     m_orderInfo.PropertyChanged += OrderInfoOnPropertyChanged;
 }
Exemplo n.º 10
0
 public CustomerOrderInfo(Customer customer)
 {
     Customer = customer;
     Items = new List<CustomerOrderItem>(0);
 }
        private void GetContent()
        {
            m_bgworker = new BackgroundWorker { WorkerReportsProgress = true };
            m_bgworker.DoWork += (sender, args) =>
            {
                var db = Core.Repositories.DbManger.GetInstance();
                var orderRepo = db.GetOrderRepository();
                var custRepo = db.GetCustomersRepository();

                List<Order> orders;
                try
                {
                    orders = orderRepo.GetOrdersForProduct(m_product);
                }
                catch (Exception exception)
                {
                    m_logger.ErrorException(exception);
                    throw new BgWorkerException("Не удалось получить список заказов для продукта. ");
                }

                var list = new List<ProductCustomerListViewItem>();
                foreach (Order order in orders)
                {
                    Customer c;
                    try
                    {
                        c = custRepo.GetById(order.CustomerId);
                    }
                    catch (Exception exception)
                    {
                        m_logger.ErrorException(exception);
                        c = new Customer { AccountTypeId = 0, FirstName = "???", LastName = "???", Id = 0 };
                    }

                    list.Add(new ProductCustomerListViewItem(order, c));
                }

                list.Sort(
                    (i1, i2) =>
                    String.Compare(i1.SourceCustomerInfo.LastName, i2.SourceCustomerInfo.LastName,
                                   StringComparison.CurrentCultureIgnoreCase));

                args.Result = list;
            };
            m_bgworker.RunWorkerCompleted += (sender, args) =>
            {
                lvOrderItems.Items.Clear();

                if (args.Cancelled) return;
                if (args.Error != null)
                {
                    this.ShowError(args.Error.Message);
                    return;
                }

                foreach (ProductCustomerListViewItem item in args.Result as List<ProductCustomerListViewItem>)
                {
                    lvOrderItems.Items.Add(item);
                }
            };

            m_bgworker.RunWorkerAsync();
        }
        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);
        }
Exemplo n.º 13
0
        public List<Order> GetOrdersForCustomerFromAlbum(Customer customer, Album album)
        {
            using (var s = m_dbManger.OpenSession())
            {
                IQuery productsQuery = s.CreateQuery("from Product p where p.AlbumId = :aid");
                productsQuery.SetInt32("aid", album.Id);
                var idsList = productsQuery.List<Product>().Select(product => product.Id).ToList();
                if (idsList.Count == 0) return new List<Order>(0);

                IQuery q = s.CreateQuery("from Order as o where o.CustomerId = :oid and o.ProductId in (:namesList)");
                q.SetInt32("oid", customer.Id);
                q.SetParameterList("namesList", idsList);

                return (List<Order>)q.List<Order>();
            }
        }
Exemplo n.º 14
0
 public void Update(Customer c)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Update(c);
             t.Commit();
             UpdateInCache(c);
         }
     }
 }
Exemplo n.º 15
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();
        }
Exemplo n.º 16
0
 private void UpdateInCache(Customer c)
 {
     if (s_idToCustomerCache.ContainsKey(c.Id)) s_idToCustomerCache[c.Id] = c;
     if (s_vkidToCustomerCache.ContainsKey(c.VkId)) s_vkidToCustomerCache[c.VkId] = c;
 }
Exemplo n.º 17
0
 private void DeleteFromCache(Customer c)
 {
     if (s_idToCustomerCache.ContainsKey(c.Id)) s_idToCustomerCache.Remove(c.Id);
     if (s_vkidToCustomerCache.ContainsKey(c.VkId)) s_vkidToCustomerCache.Remove(c.VkId);
 }
Exemplo n.º 18
0
 private void AddToCache(Customer c)
 {
     if (!s_idToCustomerCache.ContainsKey(c.Id)) s_idToCustomerCache.Add(c.Id, c);
     if (!s_vkidToCustomerCache.ContainsKey(c.VkId)) s_vkidToCustomerCache.Add(c.VkId, c);
 }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 20
0
 public abstract void ExportCustomerOrders(Customer customer);
Exemplo n.º 21
0
 public PaymentsListViewItem(Payment payment, Customer customer)
 {
     m_payment = payment;
     m_customer = customer;
 }
        private void UpdatePhotosInAlbumThreadProc(object sender, DoWorkEventArgs args)
        {
            var worker = sender as BackgroundWorker;
            var album = args.Argument as Album;
            if (album == null) return;

            var vkWraper = new VkObjectsWrapper();
            var photosMgr = new PhotosManager(m_settings.AccessToken);
            var usersMgr = new UsersManager(m_settings.AccessToken);

            var commentsRepo = DbManger.GetInstance().GetCommentsRepository();
            var customersRepo = DbManger.GetInstance().GetCustomersRepository();
            var ordersRepo = DbManger.GetInstance().GetOrderRepository();
            var prodsRepo = DbManger.GetInstance().GetProductRepository();

            var workGroup = vkWraper.GetVkGroupObject(m_settings.WorkGroupId, m_settings.LoggedUserId);
            List<VkPhoto> vkPhotos;
            try
            {
                worker.ReportProgress(0, "Загрузка фотографий альбома");
                vkPhotos = photosMgr.GetAlbumPhotos(vkWraper.GetVkGroupAlbum(workGroup, album.VkId));
            }
            catch (VkMethodInvocationException vkError)
            {
                m_logger.ErrorException(vkError);
                throw new BgWorkerException(vkError.Message);
            }
            catch (Exception e)
            {
                m_logger.ErrorException(e);
                throw new BgWorkerException("Ошибка. Не удалось загрузить фотографии для альбома '" + album.Title + "'");
            }

            int total = vkPhotos.Count;
            for (var n = 0; n < vkPhotos.Count; n++)
            {
                worker.ReportProgress(0, String.Format("Обработка {0} из {1}", (n + 1), total));
                if (vkPhotos[n].CommentsCount == 0) continue;

                Product productInfo = null;
                try
                {
                    var products = prodsRepo.GetByVkId(vkPhotos[n].Id);
                    if (products.Count > 0)
                    {
                        // по этому коду найдены продукты, найдем продукт из текущего альбома
                        productInfo = products.FirstOrDefault(product => product.AlbumId == album.Id);

                        if (productInfo == null)
                        {
                            // продукты с таким кодом есть, но они не в этом альбоме -> скопируем любую (первую) запись
                            var p = products[0].CopyToAlbum(album);
                            prodsRepo.Add(p);
                            productInfo = p;

                            m_logger.DebugFormat("Создан дубликат продукта '{0}' с ID={1}", p.Title, p.Id);
                        }
                    }
                }
                catch (Exception exception)
                {
                    m_logger.ErrorException(exception);
                    throw new BgWorkerException("Ошибка. Не удалось загрузить описание продукта из БД.");
                }

                #region Добавление нового продукта в репозиторий если productInfo = null
                if (productInfo == null)
                {
                    // добавим продукт в репозиторий
                    productInfo = new Product
                    {
                        AlbumId = album.Id,
                        VkId = vkPhotos[n].Id,
                        MinAmount = 1
                    };

                    #region если есть url к изображению, надо его закачать
                    if (!String.IsNullOrEmpty(vkPhotos[n].SourceUrl))
                    {
                        var name = String.Format("{0}_{1}", album.VkId, vkPhotos[n].Id);
                        var imgExtensions = new List<string> { ".jpg", ".png", ".gif", ".bmp" };
                        foreach (string imgExtension in imgExtensions)
                        {
                            if (!vkPhotos[n].SourceUrl.EndsWith(imgExtension)) continue;
                            name += imgExtension;
                            break;
                        }
                        var remoteFile = new FileDownloader(new Uri(vkPhotos[n].SourceUrl));
                        try
                        {
                            var file = System.IO.Path.Combine(m_settings.GalleryPath, name);
                            remoteFile.DownloadTo(file);
                            productInfo.ImageFile = name;
                        }
                        catch (Exception)
                        {

                        }
                    }
                    #endregion

                    // парсинг описания
                    productInfo.ParsePhotoDescription(vkPhotos[n].Text);

                    // проверка пользователем
                    var dialogResult = ProductCheckWindow.Result.Ignore;
                    var sourceText = vkPhotos[n].Text;
                    var handler = Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                         new Action(() =>
                                                             {
                                                                 var f = new ProductCheckWindow(this, productInfo,
                                                                                                sourceText);
                                                             f.ShowDialog();
                                                             dialogResult = f.GetResult();
                                                         }));
                    handler.Wait();

                    if (dialogResult == ProductCheckWindow.Result.Break)
                    {
                        break;
                    }
                    else if (dialogResult == ProductCheckWindow.Result.Accept)
                    {
                        try
                        {
                            prodsRepo.Add(productInfo);
                        }
                        catch (Exception e)
                        {
                            m_logger.ErrorException(e);
                            throw new BgWorkerException("Ошибка. Не удалось сохранить информацию о товаре.");
                        }
                    }
                }
                #endregion

                // загрузить комменты к этой фотографии
                List<VkComment> vkComments;
                try
                {
                    vkComments = photosMgr.GetPhotoComments(vkPhotos[n]);
                }
                catch (VkMethodInvocationException vkError)
                {
                    m_logger.ErrorException(vkError);
                    throw new BgWorkerException(vkError.Message);
                }
                catch (Exception exception)
                {
                    m_logger.ErrorException(exception);
                    throw new BgWorkerException("Не удалось получить комментарии к фото.");
                }

                foreach (VkComment vkComment in vkComments)
                {
                    // создание объекта хранимого комментария
                    var parsedComment = new ParsedComment
                    {
                        ParsingDate = DateTime.Now,
                        VkId = vkComment.Id,
                        ProductId = productInfo.Id
                    };

                    try
                    {
                        // проверка, не обрабатывался ли этот комментарий раньше
                        if (commentsRepo.Contains(parsedComment)) continue;
                    }
                    catch (Exception exception)
                    {
                        m_logger.ErrorException(exception);
                        throw new BgWorkerException("Ошибка: Не удалось получить данные из БД.");
                    }

                    // поиск юзера оставившего этот комментарий
                    Customer customer;
                    try
                    {
                        customer = customersRepo.GetByVkId(vkComment.SenderId);
                    }
                    catch (Exception exception)
                    {
                        m_logger.ErrorException(exception);
                        throw new BgWorkerException("Не удалось получить информацию о пользователе из БД!");
                    }

                    #region заведение заказчика в базе
                    if (customer == null)
                    {
                        // если нашего заказчика нет в базе, значит он заказывает первый раз - добавим его в базу
                        VkUser vkUser;
                        try
                        {
                            // скачиваем инфо из Вконтакте
                            vkUser = usersMgr.GetUserById(vkComment.SenderId);
                        }
                        catch (Exception exception)
                        {
                            m_logger.ErrorException(exception);
                            throw new BgWorkerException("Не удалось получить информацию о пользователе из Вконтакте.");
                        }
                        customer = new Customer
                        {
                            FirstName = vkUser.FirstName,
                            LastName = vkUser.LastName,
                            VkId = vkUser.Id,
                        };
                        try
                        {
                            customersRepo.Add(customer);
                        }
                        catch (Exception exception)
                        {
                            m_logger.ErrorException(exception);
                            throw new BgWorkerException("Ошибка. Не удалось сохранить информацию в БД.");
                        }

                        DispatcherOperation h = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                        {
                            var f = new CustomerEditWindow(this, customer);
                            f.ShowDialog();
                        }));
                        h.Wait();
                    }

                    #endregion

                    parsedComment.Message = vkComment.Message;
                    parsedComment.SenderName = customer.GetFullName();
                    parsedComment.PostingDate = vkComment.Date.ToString();

                    // начальная инициализация
                    var orderObj = new Order
                    {
                        ProductId = productInfo.Id,
                        CustomerId = customer.Id,
                        Comment = "",
                        Date = vkComment.Date,
                        Amount = 0
                    };
                    var requestedOperation = OrderOperation.Add;

                    #region парсинг текста комментария

                    /*
                     * ищем чтото типа "+N", "-N"
                     * */
                    var msg = vkComment.Message;
                    for (var i = 0; i < msg.Length; i++)
                    {
                        if (!Char.IsDigit(msg[i]) && msg[i] != '-' && msg[i] != '+' && msg[i] != ' ')
                        {
                            msg = msg.Replace(msg[i], ' ');
                        }
                    }
                    msg = msg.Replace(" ", "");
                    if (msg.Length > 0) // если чтото осталось от сообщения
                    {
                        if (msg[0] == '+')
                        {
                            // добавляем чтото к заказу
                            requestedOperation = OrderOperation.Add;
                            for (int i = 0; i < msg.Length; i++)
                            {
                                if (!Char.IsDigit(msg[i]) && msg[i] != ' ')
                                {
                                    msg = msg.Replace(msg[i], ' ');
                                }
                                msg = msg.Replace(" ", "");
                            }

                            if (msg.Length > 0)
                            {
                                try
                                {
                                    orderObj.Amount = Int32.Parse(msg);
                                }
                                catch (Exception)
                                {
                                    orderObj.Amount = 0;
                                }
                            }
                        }
                        else if (msg[0] == '-')
                        {
                            requestedOperation = OrderOperation.Remove;
                            for (int i = 0; i < msg.Length; i++)
                            {
                                if (!Char.IsDigit(msg[i]) && msg[i] != ' ')
                                {
                                    msg = msg.Replace(msg[i], ' ');
                                }
                                msg = msg.Replace(" ", "");
                            }
                            if (msg.Length > 0)
                            {
                                try{orderObj.Amount = Int32.Parse(msg);}
                                catch (Exception)
                                {
                                    orderObj.Amount = 0;
                                }
                            }
                        }
                    }

                    #endregion

                    // открыть форму проверки комметнария
                    var dialogResult = CommentCheckWindow.Result.Reject;
                    var resultAction = OrderOperation.Add;
                    msg = vkComment.Message;
                    DispatcherOperation ch = Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                    {
                        var f = new CommentCheckWindow(this, msg, customer, orderObj, productInfo, requestedOperation);
                        f.ShowDialog();

                        dialogResult = f.GetResult();
                        resultAction = f.GetRequestedOperation();
                    }));
                    ch.Wait();

                    if (dialogResult == CommentCheckWindow.Result.Accept)
                    {
                        // сохранить объект комметария в БД
                        try
                        {
                            commentsRepo.Add(parsedComment);
                            orderObj.InitialVkCommentId = parsedComment.Id;
                        }
                        catch (Exception exception)
                        {
                            m_logger.ErrorException(exception);
                            throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                        }

                        if (resultAction == OrderOperation.Add)
                        {
                            #region сохранить заказ в БД или добавить к существующему
                            List<Order> personOrders;
                            try
                            {
                                personOrders = ordersRepo.GetOrdersForCustomerFromAlbum(customer, album);
                            }
                            catch (Exception exception)
                            {
                                m_logger.ErrorException(exception);
                                throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                            }
                            var storedOrder = personOrders.FirstOrDefault(t => t.ProductId == orderObj.ProductId);
                            if (storedOrder == null)
                            {
                                try
                                {
                                    ordersRepo.Add(orderObj);
                                }
                                catch (Exception exception)
                                {
                                    m_logger.ErrorException(exception);
                                    throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                                }
                            }
                            else
                            {
                                storedOrder.Amount += orderObj.Amount;
                                if(!String.IsNullOrEmpty(orderObj.Comment))
                                    storedOrder.Comment += String.Format("; {0}", orderObj.Comment);

                                try
                                {
                                    ordersRepo.Update(storedOrder);
                                }
                                catch (Exception exception)
                                {
                                    m_logger.ErrorException(exception);
                                    throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                                }
                            }

                            #endregion
                        }
                        else if (resultAction == OrderOperation.Remove)
                        {
                            #region удалить в БД из заказов все что связано с этим товаром у этого заказчика

                            List<Order> personOrders;
                            try
                            {
                                personOrders = ordersRepo.GetOrdersForCustomerFromAlbum(customer, album);
                            }
                            catch (Exception exception)
                            {
                                m_logger.ErrorException(exception);
                                throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                            }
                            bool clean = true;
                            for (int i = 0; i < personOrders.Count; i++)
                            {
                                if (personOrders[i].ProductId == orderObj.ProductId)
                                {
                                    try
                                    {
                                        ordersRepo.Delete(personOrders[i]);
                                    }
                                    catch (Exception exception)
                                    {
                                        m_logger.ErrorException(exception);
                                        clean = false;
                                    }
                                }
                            }
                            if (!clean)
                            {
                                throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                            }

                            #endregion
                        }
                        else if (resultAction == OrderOperation.Decrease)
                        {
                            #region уменьшить кол-во заказаного товара в позиции

                            List<Order> personOrders;
                            try
                            {
                                personOrders = ordersRepo.GetOrdersForCustomerFromAlbum(customer, album);
                            }
                            catch (Exception exception)
                            {
                                m_logger.ErrorException(exception);
                                throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                            }
                            var storedOrder = personOrders.FirstOrDefault(t => t.ProductId == orderObj.ProductId);
                            if (storedOrder != null)
                            {
                                storedOrder.Amount -= orderObj.Amount;
                                if (storedOrder.Amount > 0)
                                {
                                    try
                                    {
                                        ordersRepo.Update(storedOrder);
                                    }
                                    catch (Exception exception)
                                    {
                                        m_logger.ErrorException(exception);
                                        throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                                    }
                                }
                                else
                                {
                                    // позиция нулевая, можно удалить
                                    try
                                    {
                                        ordersRepo.Delete(storedOrder);
                                    }
                                    catch (Exception exception)
                                    {
                                        m_logger.ErrorException(exception);
                                        throw new BgWorkerException("Ошибка соединения с БД. Операция не выполнена");
                                    }
                                }
                            }
                            else
                            {
                                m_logger.DebugFormat("Внимание! Невозможно уменьшить заказ которого нет!");
                            }

                            #endregion
                        }
                        else
                        {
                            // 'Forget' action is skiped too!
                        }
                    }
                }
            }
        }
Exemplo n.º 23
0
 public List<Order> GetOrdersForCustomer(Customer customer)
 {
     using (var s = m_dbManger.OpenSession())
     {
         IQuery q = s.CreateQuery("from Order as o where o.CustomerId = :oid");
         q.SetInt32("oid", customer.Id);
         return (List<Order>) q.List<Order>();
     }
 }
 private void lbCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (e.AddedItems.Count > 0)
     {
         var obj = e.AddedItems[0] as Customer;
         if (obj != null) m_selectedCustomer = obj;
     }
 }
Exemplo n.º 25
0
        public void OrderRepositoryTests()
        {
            var db = DbManger.GetInstance();
            var orders = db.GetOrderRepository();
            var products = db.GetProductRepository();
            var albums = db.GetAlbumsRepository();
            var customers = db.GetCustomersRepository();

            var user1 = new Customer {FirstName = "aaaa", LastName = "bbbbb", VkId = 1};
            var user2 = new Customer { FirstName = "aaaa", LastName = "bbbbb", VkId = 1 };
            customers.Add(user1);
            customers.Add(user2);

            var album1 = new Album {CreationDate = DateTime.Now, VkId = 1, Title = "Album 1"};
            var album2 = new Album { CreationDate = DateTime.Now, VkId = 2, Title = "Album 2" };
            albums.Add(album1);
            albums.Add(album2);

            var p1 = new Product { GenericUrl = "aaa", Title = "Product 1", Price = 10, VkId = 1, AlbumId = album1.Id};      // p1 -> album1
            var p2 = new Product { GenericUrl = "aaa", Title = "Product 2", Price = 10, VkId = 2, AlbumId = album1.Id };    // p2 -> album1
            var p3 = new Product { GenericUrl = "aaa", Title = "Product 3", Price = 10, VkId = 3, AlbumId = album1.Id };    // p3 -> album1
            var p4 = new Product { GenericUrl = "aaa", Title = "Product 4", Price = 10, VkId = 4, AlbumId = album1.Id };    // p4 -> album1

            var p5 = new Product { GenericUrl = "aaa", Title = "Product 5", Price = 10, VkId = 5, AlbumId = album2.Id };    // p5 -> album1
            var p6 = new Product { GenericUrl = "aaa", Title = "Product 6", Price = 10, VkId = 6, AlbumId = album2.Id };    // p6 -> album1

            products.Add(p1);
            products.Add(p2);
            products.Add(p3);
            products.Add(p4);
            products.Add(p5);
            products.Add(p6);

            orders.Add(new Order{Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p1.Id}); // user1 -> p1 (album1)
            orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p2.Id }); // user1 -> p2 (album1)
            orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p4.Id }); // user1 -> p4 (album1)
            orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p6.Id }); // user1 -> p6 (album2)

            orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p1.Id }); // user2 -> p1 (album1)
            orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p3.Id }); // user2 -> p3 (album1)
            orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p5.Id }); // user2 -> p5 (album2)

            var album1Orders = orders.GetOrdersForAlbum(album1);
            if (album1Orders.Count != 5) throw new Exception("GetOrdersForAlbum failed");

            var album2Orders = orders.GetOrdersForAlbum(album2);
            if (album2Orders.Count != 2) throw new Exception("GetOrdersForAlbum x2 failed");

            var user1Orders = orders.GetOrdersForCustomer(user1);
            if (user1Orders.Count != 4) throw new Exception("GetOrdersForCustomer failed");

            var user2Orders = orders.GetOrdersForCustomer(user2);
            if (user2Orders.Count != 3) throw new Exception("GetOrdersForCustomer x2 failed");

            var user1Album1Orders = orders.GetOrdersForCustomerFromAlbum(user1, album1);
            if (user1Album1Orders.Count != 3) throw new Exception("GetOrdersForCustomerFromAlbum failed");

            var user1Album2Orders = orders.GetOrdersForCustomerFromAlbum(user1, album2);
            if (user1Album2Orders.Count != 1) throw new Exception("GetOrdersForCustomerFromAlbum failed");

            var user2Album1Orders = orders.GetOrdersForCustomerFromAlbum(user2, album1);
            if (user2Album1Orders.Count != 2) throw new Exception("GetOrdersForCustomerFromAlbum failed");

            var user2Album2Orders = orders.GetOrdersForCustomerFromAlbum(user2, album2);
            if (user2Album2Orders.Count != 1) throw new Exception("GetOrdersForCustomerFromAlbum failed");

            products.Delete(p1);
            products.Delete(p2);
            products.Delete(p3);
            products.Delete(p4);
            products.Delete(p5);
            products.Delete(p6);
            albums.Delete(album1);
            albums.Delete(album2);
            customers.Delete(user1);
            customers.Delete(user2);
        }