public PriceOfferViewModel(PriceComposedId priceId, bool showLeaders, OfferComposedId initOfferId = null)
            : base(initOfferId)
        {
            //мы не можем принимать объект который принадлежит другой форме
            //это может вызвать исключение если сессия в которой был загружен объект будет закрыта
            //утечки памяти если текущая форма подпишется на события изменения в переданном объекте
            //между формами можно передавать только примитивные объекты
            this.priceId = priceId;

            DisplayName = "Заявка поставщику";
            Price       = new NotifyValue <Price>();
            IsLoading   = new NotifyValue <bool>();

            Filters       = filters;
            CurrentFilter = new NotifyValue <string>(filters[0]);
            if (showLeaders)
            {
                FilterLeader();
            }

            //по идее это не нужно тк обо всем должен позаботится сборщик мусора
            //но если не удалить подписку будет утечка памяти
            OnCloseDisposable.Add(this.ObservableForProperty(m => m.Price.Value.Order)
                                  .Subscribe(_ => NotifyOfPropertyChange(nameof(CanDeleteOrder))));
            SearchBehavior = new SearchBehavior(this);

            CurrentProducer.Cast <object>()
            .Merge(CurrentFilter.Cast <object>())
            .Merge(SearchBehavior.ActiveSearchTerm.Cast <object>())
            .Subscribe(_ => Filter());

            PrintMenuItems = new ObservableCollection <MenuItem>();
            IsView         = true;
        }
Esempio n. 2
0
        public Mails()
        {
            DisplayName = "Минипочта";
            Sort        = new[] {
                "Сортировка: Дата",
                "Сортировка: Тема",
                "Сортировка: Отправитель",
                "Сортировка: Важность",
            };

            Term          = new NotifyValue <string>();
            CurrentItem   = new NotifyValue <Mail>();
            SelectedItems = new ObservableCollection <Mail>();
            CurrentSort   = new NotifyValue <string>("Сортировка: Дата");
            IsAsc         = new NotifyValue <bool>(false);

            Items = Term.Cast <object>()
                    .Throttle(TimeSpan.FromMilliseconds(100), Scheduler)
                    .Merge(CurrentSort)
                    .Merge(IsAsc.Select(v => (object)v))
                    .ObserveOn(UiScheduler)
                    .ToValue(_ => Apply());
            CanDelete = SelectedItems.Changed().ToValue(_ => SelectedItems.Count > 0);
            var updateStat = Items.ObservableForProperty(i => i.Value)
                             .Select(l => l.Value.Changed())
                             .Switch();

            OnCloseDisposable.Add(updateStat.Subscribe(_ => Shell.NewMailsCount.Value = mails.Count(m => m.IsNew)));
        }
Esempio n. 3
0
 public Frontend2()
 {
     DisplayName = "Регистрация продаж";
     InitFields();
     Status.Value        = "Готов к работе(F1 для справки)";
     Lines               = new ReactiveCollection <CheckLine>();
     CheckLinesForReturn = new List <CheckLine>();
     Warning             = new InlineEditWarning(Scheduler, Manager);
     OnCloseDisposable.Add(SearchBehavior = new SearchBehavior(Env));
     SearchBehavior.ActiveSearchTerm.Where(x => !String.IsNullOrEmpty(x))
     .Subscribe(x => Coroutine.BeginExecute(Enter().GetEnumerator()));
     CurrentCatalog.Select(x => x?.Name?.Description != null)
     .Subscribe(CanShowDescription);
 }
Esempio n. 4
0
 public void Reload(int page = 0)
 {
     if (page < 0)
     {
         page = 0;
     }
     IsLoading.Value = true;
     if (client == null)
     {
         client = new HttpClient();
         OnCloseDisposable.Add(client);
     }
     Observable.StartAsync(async() => {
         if (!client.DefaultRequestHeaders.Contains("X-SBISSessionID"))
         {
             var login = await client.JsonRpc("СБИС.Аутентифицировать", new {
                 Логин  = Settings.Value.SbisUsername,
                 Пароль = Settings.Value.SbisPassword
             });
             client.DefaultRequestHeaders.Add("X-SBISSessionID", login["result"].ToObject <string>());
         }
         var result = await client.JsonRpc("СБИС.СписокДокументовПоСобытиям", new {
             Фильтр = new {
                 ТипРеестра      = "Входящие",
                 НашаОтганизация = new {
                     СвЮЛ = new {
                         КодФилиала = ""
                     }
                 },
                 Навигация = new {
                     азмерСтраницы       = "100",
                     Страница            = page.ToString(),
                     ВернутьРазмерСписка = "Да"
                 }
             }
         });
         return(result.GetValue("result").ToObject <Result>());
     })
     .ObserveOn(UiScheduler)
     .Do(_ => IsLoading.Value = false, _ => IsLoading.Value = false)
     .Subscribe(x => {
         SearchTerm.Value = "";
         Total.Value      = $"{page + 1} из {x.Навигация.РазмерСписка / x.Навигация.РазмерСтраницы}";
         currentPage      = page;
         var display      = new List <DisplayItem>();
         foreach (var message in x.еестр)
         {
             DateTime date;
             DateTime.TryParseExact(message.ДатаВремя, "dd.MM.yyyy HH.mm.ss", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out date);
             var sender = message.Документ?.Контрагент?.СвЮЛ?.Название;
             foreach (var attachment in message.Документ?.Вложение ?? new Attach[0])
             {
                 display.Add(new DisplayItem {
                     Sender     = sender,
                     FileName   = attachment.Название,
                     Date       = date,
                     Status     = message.Документ?.Состояние?.Название,
                     Department = message.Документ?.Ответственный?.ToString(),
                     Attachment = attachment,
                     Message    = message.Документ,
                 });
                 sender = null;
             }
         }
         items       = display.ToObservableCollection();
         Items.Value = display.ToObservableCollection();
     }, e => {
         Log.Error("Не удалось загрузить документы", e);
         Manager.Error(ErrorHelper.TranslateException(e)
                       ?? "Не удалось выполнить операцию, попробуйте повторить позднее.");
     });
 }
        public CatalogViewModel()
        {
            ViewOffersByCatalog        = true;
            ViewOffersByCatalogEnabled = Settings.Select(s => s.CanViewOffersByCatalogName).ToValue();

            this.ObservableForProperty(m => m.Mode).Subscribe(x =>
            {
                CatalogSelectorVisible.Value = Mode == CatalogViewMode.CatalogSelector;
                AddToAwaitedVisible.Value    = Mode == CatalogViewMode.Basic;
                ShowAwaitedVisible.Value     = Mode == CatalogViewMode.Basic;
            });


            DisplayName = "Поиск препаратов в каталоге";
            Filters     = new[] {
                new FilterDeclaration("Все"),
                new FilterDeclaration("Жизненно важные", "жизненно важным", "только жизненно важные",
                                      FilterType.VitallyImportant),
                new FilterDeclaration("Обязательный ассортимент", "обязательному ассортименту", "только обязательные ассортимент",
                                      FilterType.Mandatory),
                new FilterDeclaration("Ожидаемые позиции", "ожидаемым позициям", "только ожидаемые позиции",
                                      FilterType.Awaited),
                new FilterDeclaration("ПКУ", "ПКУ", "только ПКУ",
                                      FilterType.PKU),
                new FilterDeclaration("ПКУ:Наркотические и психотропные",
                                      "ПКУ:Наркотические и психотропные",
                                      "только ПКУ:Наркотические и психотропные",
                                      FilterType.PKUNarcotic),
                new FilterDeclaration("ПКУ:Сильнодействующие. и ядовитые",
                                      "ПКУ:Сильнодействующие. и ядовитые",
                                      "только ПКУ:Сильнодействующие. и ядовитые",
                                      FilterType.PKUToxic),
                new FilterDeclaration("ПКУ:Комбинированные", "ПКУ:Комбинированные", "только ПКУ:Комбинированные",
                                      FilterType.PKUCombined),
                new FilterDeclaration("ПКУ:Иные лек.средства", "ПКУ:Иные лек.средства", "только ПКУ:Иные лек.средства",
                                      FilterType.PKUOther),
            };
            CurrentFilter = Filters[0];

            CatalogSearch = new NotifyValue <bool>();
            this.ObservableForProperty(m => m.ActiveItem)
            .Select(i => i.Value != null ? i.Value.CanExport : Observable.Return(false))
            .Switch()
            .Subscribe(CanExport);
            CatalogSearch.CatchSubscribe(_ => UpdateActiveItem(), CloseCancellation);

            CanAddToAwaited = this
                              .ObservableForProperty(m => (object)m.CurrentCatalog, skipInitial: false)
                              .Merge(this.ObservableForProperty(m => (object)m.CurrentCatalogName))
                              .Select(v => GuessCatalog() != null)
                              .ToValue();

            CanCatalogSelector = this
                                 .ObservableForProperty(m => (object)m.CurrentCatalog, skipInitial: false)
                                 .Merge(this.ObservableForProperty(m => (object)m.CurrentCatalogName))
                                 .Select(v => CurrentCatalog != null)
                                 .ToValue();

            this.ObservableForProperty(m => m.CurrentCatalogName)
            .Subscribe(_ => NotifyOfPropertyChange("CanShowDescription"));

            ViewOffersByCatalogVisible = CatalogSearch.Select(v => !v)
                                         .ToValue();

            OnCloseDisposable.Add(Disposable.Create(() => {
                if (ActiveItem is IDisposable)
                {
                    ((IDisposable)ActiveItem).Dispose();
                }
            }));
            IsEnabled = new NotifyValue <bool>(true);
            InitFields();
            Mode = CatalogViewMode.Basic;
        }
Esempio n. 6
0
        public OrdersViewModel()
        {
            DisplayName = "Заказы";

            InitFields();
            AddressSelector       = new AddressSelector(this);
            SelectedOrders        = new List <Order>();
            SelectedSentOrders    = new List <SentOrder>();
            SelectedDeletedOrders = new List <DeletedOrder>();
            deletedOrders         = new ReactiveCollection <DeletedOrder>();

            OnCloseDisposable.Add(this.ObservableForProperty(m => (object)m.CurrentOrder)
                                  .Merge(this.ObservableForProperty(m => (object)m.IsCurrentSelected.Value))
                                  .Subscribe(_ => {
                SetAddressesToMove();
                NotifyOfPropertyChange(nameof(CanDelete));
                NotifyOfPropertyChange(nameof(CanFreeze));
                NotifyOfPropertyChange(nameof(CanUnfreeze));
                NotifyOfPropertyChange(nameof(CanReorder));
                NotifyOfPropertyChange(nameof(CanMove));
            }));

            OnCloseDisposable.Add(IsSentSelected
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(RestoreOrderVisible));
                NotifyOfPropertyChange(nameof(CanReorder));
                NotifyOfPropertyChange(nameof(EditableOrder));
            }));

            OnCloseDisposable.Add(IsCurrentSelected
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(FreezeVisible));
                NotifyOfPropertyChange(nameof(UnfreezeVisible));
                NotifyOfPropertyChange(nameof(MoveVisible));
                NotifyOfPropertyChange(nameof(EditableOrder));
            }));

            OnCloseDisposable.Add(IsDeletedSelected
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(UnDeleteVisible));
                NotifyOfPropertyChange(nameof(ReorderVisible));
            }));

            OnCloseDisposable.Add(this.ObservableForProperty(m => m.CurrentDeletedOrder)
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(CanDelete));
                NotifyOfPropertyChange(nameof(CanUnDelete));
            }));

            OnCloseDisposable.Add(this.ObservableForProperty(m => m.CurrentSentOrder)
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(CanDelete));
                NotifyOfPropertyChange(nameof(CanRestoreOrder));
                NotifyOfPropertyChange(nameof(CanReorder));
            }));

            OnCloseDisposable.Add(this.ObservableForProperty(m => m.CurrentOrder.Frozen)
                                  .Subscribe(_ => {
                NotifyOfPropertyChange(nameof(CanFreeze));
                NotifyOfPropertyChange(nameof(CanUnfreeze));
            }));

            var ordersChanged = this.ObservableForProperty(m => m.Orders);
            var update        = ordersChanged
                                .SelectMany(e => e.Value.ItemChanged.Cast <Object>().Merge(e.Value.Changed));

            var observable = ordersChanged.Cast <object>()
                             .Merge(update)
                             .Throttle(Consts.RefreshOrderStatTimeout, UiScheduler)
                             .Select(e => new Stat(Address));

            OnCloseDisposable.Add(Bus.RegisterMessageSource(observable));
            IsCurrentSelected
            .Select(v => v ? "Orders" : "SentOrders")
            .Subscribe(ExcelExporter.ActiveProperty);

            PrintMenuItems = new ObservableCollection <MenuItem>();
            IsView         = true;
        }
Esempio n. 7
0
        public OrderLinesViewModel()
        {
            DisplayName = "Сводный заказ";

            InitFields();
            Lines             = new NotifyValue <ObservableCollection <OrderLine> >(new ObservableCollection <OrderLine>());
            SentLines         = new NotifyValue <List <SentOrderLine> >(new List <SentOrderLine>());
            IsCurrentSelected = new NotifyValue <bool>(true);
            Begin             = new NotifyValue <DateTime>(DateTime.Today.AddMonths(-3).FirstDayOfMonth());
            End             = new NotifyValue <DateTime>(DateTime.Today);
            AddressSelector = new AddressSelector(this);

            FilterItems = new List <Selectable <Tuple <string, string> > >();
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("InFrozenOrders", "Позиции присутствуют в замороженных заказах")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsMinCost", "Позиции по мин.ценам")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("IsNotMinCost", "Позиции не по мин.ценам")));
            FilterItems.Add(new Selectable <Tuple <string, string> >(Tuple.Create("OnlyWarning", "Только позиции с корректировкой")));

            CanDelete    = CurrentLine.CombineLatest(IsCurrentSelected, (l, s) => l != null && s).ToValue();
            BeginEnabled = IsSentSelected.ToValue();
            EndEnabled   = IsSentSelected.ToValue();

            IsCurrentSelected.Subscribe(_ => NotifyOfPropertyChange(nameof(CanPrint)));
            IsCurrentSelected.Subscribe(_ => NotifyOfPropertyChange(nameof(CanExport)));

            Sum = new NotifyValue <decimal>(() => {
                if (IsCurrentSelected)
                {
                    return(Lines.Value.Sum(l => l.MixedSum));
                }
                return(SentLines.Value.Sum(l => l.MixedSum));
            }, SentLines, Lines, IsCurrentSelected);

            OrderWarning = new InlineEditWarning(UiScheduler, Manager);
            QuickSearch  = new QuickSearch <OrderLine>(UiScheduler,
                                                       s => Lines.Value.FirstOrDefault(l => l.ProductSynonym.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0),
                                                       CurrentLine);
            QuickSearch2 = new QuickSearch <SentOrderLine>(UiScheduler,
                                                           s => SentLines.Value.FirstOrDefault(l => l.ProductSynonym.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0),
                                                           SelectedSentLine);
            Editor = new Editor(OrderWarning, Manager, CurrentLine, Lines.Cast <IList>().ToValue());

            var currentLinesChanged = this.ObservableForProperty(m => m.CurrentLine.Value.Count)
                                      .Throttle(Consts.RefreshOrderStatTimeout, UiScheduler)
                                      .Select(e => new Stat(Address));

            OnCloseDisposable.Add(Bus.RegisterMessageSource(currentLinesChanged));
            OnCloseDisposable.Add(currentLinesChanged.Subscribe(_ => Sum.Recalculate()));

            Settings.Subscribe(_ => CalculateOrderLine());

            if (Session != null)
            {
                Prices = Session.Query <Price>().OrderBy(p => p.Name).ToList()
                         .Select(p => new Selectable <Price>(p))
                         .ToList();
            }
            else
            {
                Prices = new List <Selectable <Price> >();
            }

            MatchedWaybills = new MatchedWaybills(this, SelectedSentLine, IsSentSelected);
            IsCurrentSelected
            .Select(v => v ? "Lines" : "SentLines")
            .Subscribe(ExcelExporter.ActiveProperty);

            Observable.Merge(IsCurrentSelected.Select(x => (object)x), Lines, SentLines, currentLinesChanged)
            .Select(_ => {
                if (IsCurrentSelected)
                {
                    return(Lines.Value?.Count ?? 0);
                }
                return(SentLines.Value?.Count ?? 0);
            })
            .Subscribe(LinesCount);
            IsLoading = new NotifyValue <bool>();
            IsCurrentSelected.Where(v => v)
            .Select(_ => false)
            .Subscribe(IsLoading);

            SessionValue(Begin, GetType().Name + ".Begin");
            SessionValue(End, GetType().Name + ".End");
            SessionValue(IsSentSelected, GetType().Name + ".IsSentSelected");
            Persist(IsExpanded, "IsExpanded");

            PrintMenuItems = new ObservableCollection <MenuItem>();
            IsView         = true;
        }
Esempio n. 8
0
        protected override void OnInitialize()
        {
            base.OnInitialize();

            Promotions         = new PromotionPopup(Shell.Config, CurrentCatalog.Select(x => x?.Name), Env);
            ProducerPromotions = new ProducerPromotionPopup(Shell.Config, CurrentCatalog.Select(x => x?.Name), Env);

            OrderWarning = new InlineEditWarning(UiScheduler, Manager);
            CurrentOffer
            .Throttle(Consts.LoadOrderHistoryTimeout, Scheduler)
            .Select(_ => RxQuery(LoadHistoryOrders))
            .Switch()
            .Subscribe(HistoryOrders, CloseCancellation.Token);
            CurrentOffer
            .Where(x => !(x?.StatLoaded).GetValueOrDefault())
            .Throttle(Consts.LoadOrderHistoryTimeout, Scheduler)
            .Select(_ => RxQuery(LoadStat))
            .Switch()
            .Subscribe(x => {
                if (x == null || CurrentOffer.Value == null)
                {
                    return;
                }
                ApplyStat(x);
            }, CloseCancellation.Token);

            CurrentOffer
#if !DEBUG
            .Throttle(Consts.ScrollLoadTimeout)
#endif
            .Select(x => RxQuery(s => {
                if (x == null)
                {
                    return(null);
                }
                if (CurrentCatalog.Value?.Id == x.CatalogId)
                {
                    return(CurrentCatalog.Value);
                }
                var sql = @"select c.*, cn.*, m.*, cn.DescriptionId as Id
from Catalogs c
join CatalogNames cn on cn.Id = c.NameId
left join Mnns m on m.Id = cn.MnnId
where c.Id = ?";
                return(s
                       .Connection.Query <Catalog, CatalogName, Mnn, ProductDescription, Catalog>(sql, (c, cn, m, d) => {
                    c.Name = cn;
                    if (cn != null)
                    {
                        cn.Mnn = m;
                        cn.Description = d;
                    }
                    return c;
                }, new { x.CatalogId }).FirstOrDefault());
            }))
            .Switch()
            .Subscribe(CurrentCatalog, CloseCancellation.Token);

            //изменения в LastEditOffer могут произойти уже после перехода на другое предложение
            //по этому нужно отслеживать изменения в CurrentOffer и LastEditOffer
            var observable = this.ObservableForProperty(m => m.CurrentOffer.Value.OrderCount)
                             .Merge(this.ObservableForProperty(m => m.LastEditOffer.Value.OrderCount))
                             .Throttle(Consts.RefreshOrderStatTimeout, UiScheduler)
                             .Select(e => new Stat(Address));

            OnCloseDisposable.Add(Bus.RegisterMessageSource(observable));
        }
        protected override void OnInitialize()
        {
            base.OnInitialize();

            OnCloseDisposable.Add(Shell.SpecialMarkupProducts.Subscribe(_ => Calculate()));

            if (Session == null)
            {
                return;
            }

            Waybill = Session.Get <Waybill>(id);
            if (Waybill == null)
            {
                return;
            }
            Waybill.Settings = Settings;
            Waybill.ObservableForProperty(x => x.Status, skipInitial: false)
            .Select(x => x.Value == DocStatus.NotPosted).Subscribe(CanStock);
            Waybill.ObservableForProperty(x => x.Status, skipInitial: false)
            .Select(x => x.Value == DocStatus.NotPosted && Waybill.SupplierSum == null).Subscribe(CanEditSum);

            Waybill.ObservableForProperty(m => (object)m.Status, skipInitial: false)
            .Merge(Waybill.ObservableForProperty(m => (object)m.IsCreatedByUser))
            .Select(_ => !User.IsStockEnabled && Waybill.Status == DocStatus.NotPosted && !Waybill.IsCreatedByUser)
            .Subscribe(CanToEditable);

            Waybill.ObservableForProperty(m => (object)m.Status, skipInitial: false)
            .Merge(Waybill.ObservableForProperty(m => (object)m.IsCreatedByUser))
            .Select(_ => Waybill.Status == DocStatus.NotPosted && Waybill.IsCreatedByUser)
            .Subscribe(CanAddFromCatalog);

            if (Waybill.IsNew)
            {
                Waybill.IsNew = false;
                if (Shell.NewDocsCount.Value > 0)
                {
                    Shell.NewDocsCount.Value--;
                }
            }

            Calculate();

            var stockids = Waybill.Lines.Where(x => x.StockId != null).Select(x => x.StockId).ToArray();

            RxQuery(s => s.Query <Stock>().Where(x => stockids.Contains(x.ServerId)).ToDictionary(x => x.ServerId))
            .ObserveOn(UiScheduler)
            .Subscribe(x => {
                Waybill.Lines.Each(y => {
                    y.Stock = x.GetValueOrDefault(y.StockId);
                });
            });

            Lines.Value = new ListCollectionView(Waybill.Lines.OrderBy(l => l.Product).ToList());
            Taxes       = new List <ValueDescription <int?> > {
                new ValueDescription <int?>("Все", -1),
            };
            Taxes.AddRange(Lines.Value.Cast <WaybillLine>().Select(l => l.Nds).Distinct()
                           .OrderBy(t => t)
                           .Select(t => new ValueDescription <int?>(((object)t ?? "Нет значения").ToString(), t)));
            CurrentTax.Value = Taxes.FirstOrDefault();
            Reject           = CurrentWaybillLine
                               .Throttle(Consts.ScrollLoadTimeout, Scheduler)
                               .Select(v => RxQuery(s => {
                if (v?.RejectId == null)
                {
                    return(null);
                }
                return(s.Get <Reject>(v.RejectId.Value));
            }))
                               .Switch()
                               .ToValue(CloseCancellation);
            IsRejectVisible = Reject.Select(r => r != null).ToValue();
            if (Waybill.IsCreatedByUser)
            {
                EmptyLabelVisibility   = EmptyLabelVisibility.Select(s => Visibility.Collapsed).ToValue();
                OrderDetailsVisibility = OrderDetailsVisibility.Select(s => Visibility.Collapsed).ToValue();
            }

            RxQuery(s => PriceTag.LoadOrDefault(s.Connection, TagType.PriceTag, Waybill.Address))
            .Subscribe(x => priceTag = x);
            RxQuery(s => PriceTag.LoadOrDefault(s.Connection, TagType.RackingMap, Waybill.Address))
            .Subscribe(x => rackingMap = x);
        }