public ProductEditWindow(Window owner, Product product)
        {
            InitializeComponent();

            m_product = product;
            Owner = owner;

            KeyUp += OnKeyUp;

            tbTitle.Text = product.Title;
            tbGenericUrl.Text = product.GenericUrl;
            tbPrice.Text = product.Price.ToString("F2");
            tbMinAmount.Text = product.MinAmount.ToString();
            tbCodeNumber.Text = product.CodeNumber;
            tbCodeNumber.TextChanged += TbCodeNumberOnTextChanged;
            tbCodeNumber.SelectionChanged += TbCodeNumberOnSelectionChanged;

            try
            {
                var imgFile = System.IO.Path.Combine(RegistrySettings.GetInstance().GalleryPath, product.ImageFile);
                if(!System.IO.File.Exists(imgFile))
                {
                    throw new ApplicationException();
                }

                image1.Source =
                    new BitmapImage(new Uri(String.Format("file://{0}", imgFile)));
            }
            catch
            {
                // set default image
                image1.Source =
                    new BitmapImage(new Uri("pack://application:,,,/Images/default.png"));
            }
        }
        public ProductCheckWindow(Window owner, Product product, string sourceTitle)
        {
            m_product = product;

            InitializeComponent();
            Owner = owner;

            tbGenericUrl.Text = product.GenericUrl;
            tbTitle.Text = product.Title;
            tbPrice.Text = product.Price.ToString();
            tbMinAmount.Text = product.MinAmount.ToString();
            tbSourceDescription.Text = sourceTitle;

            if (!String.IsNullOrEmpty(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"));
            }

            m_dialogResult = Result.Ignore;
        }
Пример #3
0
 public ProductListViewItem(Product product)
 {
     Source = product;
     Source.PropertyChanged += SourceOnPropertyChanged;
     Source.PropertyChanged += SourcePropertyChangedEventHandler;
     OrderedAmount = 0;
 }
Пример #4
0
        public OrderListViewItem(Order orderInfo, ManagedRate comission)
        {
            m_orderInfo = orderInfo;
            m_productInfo = orderInfo.GetOrderedProduct();
            m_comission = comission;

            m_orderInfo.PropertyChanged += OrderInfoOnPropertyChanged;
        }
        public CommentsViewWindow(Window owner, Product product)
        {
            m_product = product;

            InitializeComponent();
            Owner = owner;

            LoadComments();
        }
Пример #6
0
 public List<ParsedComment> GetForProduct(Product p)
 {
     using (var s = m_dbManger.OpenSession())
     {
         IQuery q = s.CreateQuery("from ParsedComment as a where a.ProductId = :pid");
         q.SetInt32("pid", p.Id);
         var res = (List<ParsedComment>) q.List<ParsedComment>();
         return res;
     }
 }
Пример #7
0
 public void Delete(Product product)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Delete(product);
             t.Commit();
             DeleteFromCache(product);
         }
     }
 }
        private void btnAcceptClick(object sender, RoutedEventArgs e)
        {
            if (lvSimilars.SelectedItems.Count < 0)
            {
                this.ShowError("Необходимо выбрать товар из списка");
                return;
            }

            m_selectedProduct = lvSimilars.SelectedItems[0] as Product;
            DialogResult = true;
            Close();
        }
Пример #9
0
 public void Add(Product product)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Save(product);
             t.Commit();
             AddToCache(product);
         }
     }
 }
        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 ProductCustomersView(Window owner, ProductListViewItem lvi)
        {
            InitializeComponent();
            Owner = owner;

            m_logger = log4net.LogManager.GetLogger("ManagerMainWindow");
            m_lvi = lvi;

            m_product = lvi.Source;
            m_product.PropertyChanged += ProductOnPropertyChanged;

            tbProductTitle.Text = String.Format("{0} ({1:C}; min: {2})", m_product.Title, m_product.Price,
                                                m_product.MinAmount);
            Closed += (sender, args) => { m_product.PropertyChanged -= ProductOnPropertyChanged; };
            KeyUp += OnKeyUp;

            GetContent();
        }
Пример #12
0
 public Order()
 {
     m_cachedProduct = null;
 }
Пример #13
0
        public Product GetOrderedProduct()
        {
            if (m_cachedProduct == null)
            {
                var repo = Core.Repositories.DbManger.GetInstance().GetProductRepository();
                m_cachedProduct = repo.GetById(ProductId);
            }

            return m_cachedProduct;
        }
Пример #14
0
 public Product CopyToAlbum(Album album)
 {
     var p = new Product
     {
         AlbumId = album.Id,
         GenericUrl = this.GenericUrl,
         ImageFile = this.ImageFile,
         MinAmount = this.MinAmount,
         Price = this.Price,
         Title = this.Title,
         VkId = this.VkId,
         CodeNumber = this.CodeNumber
     };
     return p;
 }
Пример #15
0
 public long GetCountProductOrders(Product product)
 {
     using (var s = m_dbManger.OpenSession())
     {
         IQuery q = s.CreateQuery("select count(*) from Order as o where o.ProductId = :pid");
         q.SetInt32("pid", product.Id);
         var result = q.UniqueResult();
         return (long) result;
     }
 }
Пример #16
0
 private void AddToCache(Product p)
 {
     if (!s_idToProductCache.ContainsKey(p.Id)) s_idToProductCache.Add(p.Id, p);
     if (!s_vkidToProductCache.ContainsKey(p.VkId)) s_vkidToProductCache.Add(p.VkId, p);
 }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (tbTitle.Text.Length > 0)
            {
                m_product.Title = tbTitle.Text;
            }
            else
            {
                this.ShowError("Ошибка: Поле наименование должно быть заполнено.");
                return;
            }
            if (tbCodeNumber.Text.Length > 0)
            {
                m_product.CodeNumber = tbCodeNumber.Text.Trim();
            }

            m_product.GenericUrl = tbGenericUrl.Text;
            try
            {
                m_product.Price = Decimal.Parse(tbPrice.Text);
            }
            catch
            {
                this.ShowError("Ошибка: Поле цены заполнено не верно.");
                return;
            }

            try
            {
                m_product.MinAmount = Int32.Parse(tbMinAmount.Text);
                if(m_product.MinAmount < 1) throw new ApplicationException();
            }
            catch
            {
                this.ShowError("Ошибка: Поле количества заполнено не верно. Минимальное количество - 1 шт.");
                return;
            }

            try
            {
                var db = DbManger.GetInstance().GetProductRepository();

                if (m_product.Id == Int32.MinValue)
                {
                    Product selectedFromExisting = null;
                    if (m_product.CodeNumber.Length > 0)
                    {
                        // check for code number...
                        var similars = db.GetByCodeNumber(m_product.CodeNumber);
                        if (similars != null && similars.Count > 0)
                        {
                            // there are some products with such code number
                            var w = new SimilarProductsWindow(similars);
                            var wres = w.ShowDialog();
                            if (wres.HasValue && wres.Value)
                            {
                                selectedFromExisting = w.GetSelectedProduct();
                            }
                        }
                    }
                    if (selectedFromExisting == null)
                    {
                        db.Add(m_product);
                    }
                    else
                    {
                        m_product = selectedFromExisting;
                    }
                }
                else db.Update(m_product);
            }
            catch (Exception exception)
            {
                this.ShowError("Ошибка. Не удалось сохранить запись", exception.GetType().Name);
                return;
            }

            m_result = Result.Saved;
            Close();
        }
Пример #18
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);
        }
Пример #19
0
 private void UpdateInCache(Product p)
 {
     if (s_idToProductCache.ContainsKey(p.Id)) s_idToProductCache[p.Id] = p;
     if (s_vkidToProductCache.ContainsKey(p.VkId)) s_vkidToProductCache[p.VkId] = p;
 }
Пример #20
0
 private void DeleteFromCache(Product p)
 {
     if (s_idToProductCache.ContainsKey(p.Id)) s_idToProductCache.Remove(p.Id);
     if (s_vkidToProductCache.ContainsKey(p.VkId)) s_vkidToProductCache.Remove(p.VkId);
 }
Пример #21
0
        private void cmdAlbumAddProduct_OnClick(object sender, RoutedEventArgs e)
        {
            if (SelectedAlbum == null)
            {
                this.ShowError("Необходимо выбрать альбом.");
                return;
            }

            var p = new Product
                {
                    AlbumId = SelectedAlbum.Id,
                    VkId = Int32.MinValue,
                    Id = Int32.MinValue,
                    MinAmount = 1
                };
            var f = new ProductEditWindow(this, p);
            f.ShowDialog();

            if (f.GetResult() == ProductEditWindow.Result.Saved && m_selectedView == ServiceTreeNodes.AlbumProducts)
            {
                ShowAlbumProductsDetails(SelectedAlbum);
            }
        }
Пример #22
0
 public List<Order> GetOrdersForProduct(Product product)
 {
     using (var s = m_dbManger.OpenSession())
     {
         IQuery q = s.CreateQuery("from Order as o where o.ProductId = :pid");
         q.SetInt32("pid", product.Id);
         return (List<Order>)q.List<Order>();
     }
 }
        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!
                        }
                    }
                }
            }
        }
Пример #24
0
 public void Update(Product product)
 {
     using (var s = m_dbManger.OpenSession())
     {
         using (var t = s.BeginTransaction())
         {
             s.Update(product);
             t.Commit();
             UpdateInCache(product);
         }
     }
 }