Beispiel #1
0
        /// <summary>
        /// Before closing.
        /// </summary>
        /// <param name="e">used for decision whether to close form or not</param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (this.IsModified)
            {
                if (isAutoValidate)
                {
                    DialogResult result = new SaveDialog().ShowDialog();
                    switch (result)
                    {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;

                    case DialogResult.No:
                        AutoValidate   = System.Windows.Forms.AutoValidate.Disable;
                        isAutoValidate = false;
                        e.Cancel       = false;
                        log.Warn(string.Format("The form {0} has been closed without saving.", this.ToString()));
                        break;

                    case DialogResult.Yes:
                        if (SaveCommand != null && SaveCommand.CanExecute())
                        {
                            SaveCommand.Execute();
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            base.OnFormClosing(e);
        }
        public void CanExecuteIsAlwaysTrue()
        {
            var saveService    = new Mock <ISettingsSaveService>();
            var classUnderTest = new SaveCommand(saveService.Object, Mock.Of <IClosableWindow>());

            var result = classUnderTest.CanExecute(null);

            result.Should().BeTrue("because it should always be possible to save");
        }
Beispiel #3
0
        public AddNewTimeEntryViewModel()
        {
            LoadProjects();

            _newTimeEntry = new TimeEntry()
            {
                UserId = WebContext.Current.User.Id
            };
            _newTimeEntry.PropertyChanged += (s, e) => SaveCommand.CanExecute(null);

            SaveCommand   = new DelegateCommand(o => this.Save(), o => this.IsTimeEntryValid());
            CancelCommand = new DelegateCommand(o => this.Cancel(), o => true);
        }
Beispiel #4
0
        protected override void GoBackCommand_Execute()
        {
            //если придет запрос при несохраненных изменениях
            if (SaveCommand.CanExecute())
            {
                var dr = Container.Resolve <IMessageService>().ShowYesNoMessageDialog("Сохранение", "Сохранить сделанные изменения?", defaultNo: true);
                if (dr == MessageDialogResult.Yes)
                {
                    SaveCommand.Execute();
                }

                if (dr == MessageDialogResult.No)
                {
                    IsConfirmGoBackWithoutSaving = true;
                }
            }

            base.GoBackCommand_Execute();
        }
        /// <summary>
        /// Ends the edit.
        /// </summary>
        /// <param name="commit">if set to <c>true</c> [commit].</param>
        private void EndEdit(bool commit)
        {
            if (this.textBox == null)
            {
                return;
            }

            var textBoxBindingExpression   = this.textBox.GetBindingExpression(TextBox.TextProperty);
            var textBlockBindingExpression = this.GetBindingExpression(TextProperty);

            if (commit)
            {
                var isDirty = textBoxBindingExpression.IsDirty;

                if (textBoxBindingExpression != null)
                {
                    textBoxBindingExpression.UpdateSource();
                }

                if (textBlockBindingExpression != null)
                {
                    textBlockBindingExpression.UpdateTarget();
                }

                if (isDirty && SaveCommand != null && SaveCommand.CanExecute(null))
                {
                    SaveCommand.Execute(null);
                }
            }

            this.internalIsEditingChange = true;
            this.IsEditing = false;
            this.internalIsEditingChange = false;
            var p = (Panel)this.Parent;

            p.Children.Remove(this.textBox);
            this.textBox    = null;
            this.Visibility = Visibility.Visible;
            if (this.oldfocus != null && this.oldfocus.IsVisible)
            {
                this.oldfocus.Focus();
            }
        }
        /// <summary>
        /// load ItemInstance based on item selected from list, ie load shadow object
        /// </summary>
        /// <param name="selListItem"></param>
        protected override void loadSelectedItem(ItemResult selListItem)
        {
            if ((selListItem?.pk != null) && (selListItem.pk != Guid.Empty))
            {
                selectedItem = db.db.Load <Item>(selListItem.pk);

#if false
                // if not currently editing anything then we match current item, but
                // we don't update currentItem otherwise as may be a clone, etc.
                if (isDetailViewInActive && EditCommand.CanExecute(null))
                {
                    EditCommand.Execute(null);
                }
#else
                // update detail view immediately when a new item is selected
                // note this will loose changes for a clone
                if (currentItem != null && currentItem.IsChanged)
                {
                    var x = MessageBox.Show("Current item has been modified, do you wish to save changes?", $"Changes to {currentItem.displayName} will be lost!", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                    if (x == MessageBoxResult.Yes)
                    {
                        if (SaveCommand.CanExecute(null))
                        {
                            SaveCommand.Execute(null);
                        }
                    }
                }
                if (EditCommand.CanExecute(null))
                {
                    EditCommand.Execute(null);
                }
#endif
            }
            else
            {
                selectedItem = null;
            }
        }
Beispiel #7
0
        public TransferViewModel() : base(PermissionItemName.TransferForm)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                OpenItemSearch = new RelayCommand(() => {
                    try
                    {
                        if (SelectedMainRow.TblWarehouseFrom != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseFrom.Code) &&
                            SelectedMainRow.TblWarehouseTo != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseTo.Code))
                        {
                            var vm             = new ItemDimensionSearchViewModel();
                            vm.WarehouseCode   = SelectedMainRow.TblWarehouseFrom.Code;
                            vm.WarehouseToCode = SelectedMainRow.TblWarehouseTo.Code;
                            vm.SiteIserial     = SelectedMainRow.TblWarehouseFrom.TblSite;
                            vm.AppliedSearchResultList.CollectionChanged += (s, e) => {
                                // هنا هبدا اعبى الى جاى من السيرش
                                foreach (var item in vm.AppliedSearchResultList)
                                {
                                    var temp = SelectedMainRow.TblTransferDetails.FirstOrDefault(td => td.ItemDimFrom == item.ItemDimFromIserial &&
                                                                                                 td.ItemTransfer.ColorToId == item.ColorToId &&
                                                                                                 (td.ItemTransfer.SizeTo == item.SizeTo || (string.IsNullOrEmpty(td.ItemTransfer.SizeTo) && string.IsNullOrEmpty(item.SizeTo))) &&
                                                                                                 (td.ItemTransfer.BatchNoTo == item.BatchNoTo || (string.IsNullOrEmpty(td.ItemTransfer.BatchNoTo) && string.IsNullOrEmpty(item.BatchNoTo))));
                                    decimal allTransferedQuantity = SelectedMainRow.TblTransferDetails.Where(td =>
                                                                                                             td.ItemTransfer.ItemDimFromIserial == item.ItemDimFromIserial).Sum(td => td.ItemTransfer.TransferredQuantity);

                                    if (temp == null)// مش موجود
                                    {
                                        if ((item.AvailableQuantity < (allTransferedQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0) ||
                                            ((item.AvailableQuantity + item.PendingQuantity) < (allTransferedQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0))
                                        {
                                            MessageBox.Show(strings.CheckQuantities);
                                            return;
                                        }
                                        var transferDetail = new TransferDetail()
                                        {
                                            TransferHeader = SelectedMainRow.Iserial,
                                            ItemDimFrom    = item.ItemDimFromIserial,
                                            ItemDimTo      = item.ItemDimToIserial,
                                            Quantity       = item.TransferredQuantity,
                                            ItemTransfer   = item,
                                        };
                                        ValidateDetailRow(transferDetail);
                                    }
                                    else// لو موجود هحدث الكمية
                                    {
                                        if ((item.AvailableQuantity < (allTransferedQuantity - temp.ItemTransfer.AvailableQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0) ||
                                            ((item.AvailableQuantity + item.PendingQuantity) < (allTransferedQuantity - temp.ItemTransfer.AvailableQuantity + item.TransferredQuantity) && item.PendingQuantity >= 0))
                                        {
                                            MessageBox.Show(strings.CheckQuantities);
                                            return;
                                        }
                                        temp.ItemTransfer.AvailableQuantity   = item.AvailableQuantity;
                                        temp.ItemTransfer.PendingQuantity     = item.PendingQuantity;
                                        temp.ItemTransfer.TransferredQuantity = item.TransferredQuantity;
                                        temp.Quantity = item.TransferredQuantity;
                                    }
                                }
                                RaisePropertyChanged(nameof(Total));
                            };
                            var childWindowSeach = new ItemDimensionSearchChildWindow(vm);
                            childWindowSeach.Show();
                            childWindowSeach.IsTransfer    = true;
                            childWindowSeach.QuantityTitle = strings.Transferred;
                            vm.FromTitle = string.Format("From {0}", SelectedMainRow.TblWarehouseFrom.Ename);
                            vm.ToTitle   = string.Format("To {0}", SelectedMainRow.TblWarehouseTo.Ename);
                            vm.Title     = strings.TransferItem;
                            _FormMode    = FormMode.Search;
                        }
                        else
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                        }
                    }
                    catch (Exception ex) { throw ex; }
                });
                OpenFPItemSearch = new RelayCommand(() =>
                {
                    try
                    {
                        if (SelectedMainRow.TblWarehouseFrom != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseFrom.Code) &&
                            SelectedMainRow.TblWarehouseTo != null &&
                            !string.IsNullOrWhiteSpace(SelectedMainRow.TblWarehouseTo.Code))
                        {
                            var vm = new ItemFPSearchViewModel();
                            vm.FPAppliedSearchResultList.CollectionChanged += (s, e) =>
                            {
                                if (vm.FPAppliedSearchResultList.Count > 0)
                                {
                                    var SearchItem = vm.FPAppliedSearchResultList.FirstOrDefault();
                                    if (SelectedMainRow.TblTransferDetails != null && SelectedMainRow.TblTransferDetails.Count > 0)
                                    {
                                        SelectedDetailRow.ItemFPName    = SearchItem.ItemPerRow.Name;
                                        SelectedDetailRow.ItemFPCode    = SearchItem.ItemPerRow.Code;
                                        SelectedDetailRow.ItemFPIserial = SearchItem.ItemPerRow.Iserial;

                                        foreach (var item in SelectedMainRow.TblTransferDetails)
                                        {
                                            if (item.ItemTransfer.ItemCode == SelectedDetailRow.ItemTransfer.ItemCode)
                                            {
                                                item.ItemFPName    = SearchItem.ItemPerRow.Name;
                                                item.ItemFPCode    = SearchItem.ItemPerRow.Code;
                                                item.ItemFPIserial = SearchItem.ItemPerRow.Iserial;
                                            }
                                        }
                                    }
                                }
                            };
                            var childWindowSeach = new ItemFPSearchChildWindow(vm);
                            childWindowSeach.Show();
                            _FormMode = FormMode.Search;
                        }
                        else
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                        }
                    } catch (Exception ex) { throw ex; }
                });

                ApproveTransfer = new RelayCommand(() => {
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    SelectedMainRow.Approved    = true;
                    SelectedMainRow.ApproveDate = DateTime.Now;
                    SelectedMainRow.ApprovedBy  = LoggedUserInfo.Iserial;
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    if (SelectedMainRow.Approved)//كده نفذ فهعمل جديد
                    {
                        if (NewCommand.CanExecute(null))
                        {
                            NewCommand.Execute(null);
                        }
                    }
                }, () => CheckCanApprove());
                DeleteTransferDetail = new RelayCommand <object>((o) =>
                {
                    if (((KeyEventArgs)(o)).Key == Key.Delete)
                    {
                        if (SelectedMainRow.Iserial <= 0 || SelectedDetailRow.Iserial <= 0)
                        {
                            SelectedMainRow.TblTransferDetails.Remove(SelectedDetailRow);
                            if (SelectedMainRow.TblTransferDetails.Count == 0)
                            {
                                AddNewDetailRow(false);
                            }
                        }
                        else
                        {
                            DeleteDetailRow();
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                }, (o) => {
                    return(SelectedMainRow != null && !SelectedMainRow.Approved);
                });
                LoadingDetailRows = new RelayCommand <object>((o) =>
                {
                    var e = o as DataGridRowEventArgs;
                    //if (SelectedMainRow.TblTransferDetails.Count < PageSize)
                    //{
                    //    return;
                    //}
                    //if (SelectedMainRow.TblTransferDetails.Count - 2 < e.Row.GetIndex() && !Loading)
                    //{
                    //    GetDetailData();
                    //}
                });
                WarehouseClient.GetItemDimensionQuantitiesCompleted += (s, e) =>
                {
                    var temp = SelectedMainRow.TblTransferDetails.FirstOrDefault(ad =>
                                                                                 ad.ItemDimFrom == e.Result.ItemDimFromIserial);
                    var qtemp = e.Result.AvailableQuantity;
                    if (temp != null)
                    {
                        SelectedDetailRow = temp;
                    }
                    else//هعمل واحد جديد
                    {
                        temp = new TransferDetail()
                        {
                            TransferHeader = SelectedMainRow.Iserial,
                            ItemDimFrom    = e.Result.ItemDimFromIserial,
                            ItemDimTo      = e.Result.ItemDimToIserial,
                        };
                        temp.ItemTransfer.InjectFrom(e.Result);
                        temp.ItemTransfer.ColorPerRow.InjectFrom(e.Result.ColorPerRow);
                        temp.ItemTransfer.AvailableQuantity   = qtemp;
                        temp.ItemTransfer.TransferredQuantity = 0;
                        temp.Quantity = 0;
                        ValidateDetailRow(temp);
                    }
                };
                GetDetailItem = new RelayCommand <object>((o) =>
                {
                    if (((KeyEventArgs)(o)).Key == Key.Enter)
                    {
                        if (SelectedMainRow.TblWarehouseFrom == null || SelectedMainRow.TblWarehouseTo == null)
                        {
                            MessageBox.Show(strings.PleaseSelectWarehouse);
                            return;
                        }
                        WarehouseClient.GetItemDimensionQuantitiesAsync(
                            SelectedMainRow.TblWarehouseFrom.Code,
                            SelectedMainRow.TblWarehouseTo.Code,
                            ItemDimFromIserial,
                            SelectedMainRow.DocDate);
                    }
                });
                //SearchComboFrom = new RelayCommand<object>((o) =>
                //{
                //    if (((KeyEventArgs)(o)).Key == Key.F2)
                //    {if (SelectedMainRow.TblWarehouseFrom == null) SelectedMainRow.TblWarehouseFrom = new WarehouseService.TblWarehouse();
                //    new GenericSearchViewModel<TblWarehouse>().SearchLookup(WarehouseListFrom, SelectedMainRow.TblWarehouseFrom
                //            , new SilverlightCommands.RelayCommand((p) => { int x = 0;x++; }), "search warehouse", new Models.LookupItemModel(),
                //            new SilverlightCommands.RelayCommand((p) => { int y = 0;y++; }));
                //    }
                //});
                ReturnToBarcode = new RelayCommand <object>((o) =>
                {
                    //if (((KeyEventArgs)(o)).Key == Key.Enter)
                    //{
                    //    foreach (var item in SelectedMainRow.TblTransferDetails)
                    //    {
                    //        item.IsQuantityFocused = false;
                    //    }
                    //    IsRefFocused = true;
                    //}
                    RaisePropertyChanged(nameof(Total));
                });
                DetailSelectionChanged = new RelayCommand <object>((o) =>
                {
                    var e = o as SelectionChangedEventArgs;
                    // هنا هنقل الفوكس للكمية شوف بقى ازاى
                    IsRefFocused = false;
                    foreach (var item in SelectedMainRow.TblTransferDetails)
                    {
                        item.IsQuantityFocused = false;
                    }
                    SelectedDetailRow.IsQuantityFocused = true;
                });
                this.PremCompleted += (s, sv) =>
                {
                    if (this.CustomePermissions.SingleOrDefault(x => x.Code == "TransferApprove") != null)
                    {
                        CanApprove = true;
                    }
                };
                this.GetCustomePermissions(PermissionItemName.TransferForm.ToString());

                MainRowList = new ObservableCollection <TransferHeader>();
                AddNewMainRow(false);

                WarehouseClient.GetUserAsignedWarehousesForTransferCompleted += (s, e) =>
                {
                    UserWarehouseList.Clear();
                    foreach (var item in e.Result)
                    {
                        UserWarehouseList.Add(item);
                    }
                };
                WarehouseClient.GetUserAsignedWarehousesForTransferAsync(LoggedUserInfo.Iserial);

                WarehouseClient.GetTransferCompleted += (s, sv) =>
                {
                    foreach (var row in sv.Result)
                    {
                        var newrow = new TransferHeader();
                        newrow.InjectFrom(row);
                        MainRowList.Add(newrow);
                    }
                    Loading   = false;
                    FullCount = sv.fullCount;
                    if (SearchWindow != null)
                    {
                        SearchWindow.FullCount = sv.fullCount;
                        SearchWindow.Loading   = false;
                    }
                    if (FullCount == 0 && MainRowList.Count == 0)
                    {
                        AddNewMainRow(false);
                    }
                };
                WarehouseClient.GetTransferDetailCompleted += (s, sv) =>
                {
                    SelectedMainRow.TblTransferDetails.Clear();
                    foreach (var row in sv.Result)
                    {
                        var newrow = new TransferDetail();
                        newrow.InjectFrom(row);
                        newrow.ItemTransfer.InjectFrom(row.ItemTransfer);
                        newrow.ItemTransfer.ColorPerRow.InjectFrom(row.ItemTransfer.ColorPerRow);
                        SelectedMainRow.TblTransferDetails.Add(newrow);
                    }
                    if (!SelectedMainRow.TblTransferDetails.Any())
                    {
                        AddNewDetailRow(false);
                    }
                    Loading = false;
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                WarehouseClient.UpdateOrInsertTransferHeaderCompleted += (s, x) =>
                {
                    TransferHeader savedRow = null;
                    if (x.outindex >= 0)
                    {
                        savedRow = MainRowList.ElementAt(x.outindex);
                    }

                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                        savedRow.TblWarehouseFrom = WarehouseListFrom.FirstOrDefault(w => w.Iserial == savedRow.WarehouseFrom);
                        savedRow.TblWarehouseTo   = WarehouseListTo.FirstOrDefault(w => w.Iserial == savedRow.WarehouseTo);
                        savedRow.TblTransferDetails.Clear();
                        foreach (var item in x.Result.TblTransferDetails)
                        {
                            var detailTemp = new TransferDetail();
                            detailTemp.InjectFrom(item);
                            detailTemp.ItemTransfer.InjectFrom(item.ItemTransfer);
                            detailTemp.ItemTransfer.ColorPerRow.InjectFrom(item.ItemTransfer.ColorPerRow);
                            savedRow.TblTransferDetails.Add(detailTemp);
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                    DeleteCommand.RaiseCanExecuteChanged();
                    ApproveTransfer.RaiseCanExecuteChanged();
                    DeleteTransferDetail.RaiseCanExecuteChanged();
                    // IsNewChanged();
                };
                WarehouseClient.UpdateOrInsertTransferDetailCompleted += (s, x) =>
                {
                    var savedRow = SelectedMainRow.TblTransferDetails.ElementAt(x.outindex);
                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                WarehouseClient.DeleteTransferCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }

                    var oldrow = MainRowList.FirstOrDefault(x => x.Iserial == ev.Result);
                    if (oldrow != null)
                    {
                        MainRowList.Remove(oldrow);
                    }
                };
                WarehouseClient.DeleteTransferDetailCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }
                    var oldrow = SelectedMainRow.TblTransferDetails.FirstOrDefault(x => x.Iserial == ev.Result.Iserial);
                    if (oldrow != null)
                    {
                        SelectedMainRow.TblTransferDetails.Remove(oldrow);
                    }
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };

                WarehouseClient.GetLookUpWarehouseForTransferFromCompleted += (s, e) => {
                    foreach (var row in e.Result)
                    {
                        var newrow = new TblWarehouse();
                        newrow.InjectFrom(row);
                        WarehouseListFrom.Add(newrow);
                    }
                    Loading = false;
                };
                WarehouseClient.GetLookUpWarehouseForTransferToCompleted += (s, e) => {
                    foreach (var row in e.Result)
                    {
                        var newrow = new TblWarehouse();
                        newrow.InjectFrom(row);
                        WarehouseListTo.Add(newrow);
                    }
                    Loading = false;
                };

                GetComboData();
                GetMaindata();
            }
        }
Beispiel #8
0
 private bool CanAdd()
 {
     return(SaveCommand.CanExecute()); // CommitCommand.CanExecute(null);
 }
Beispiel #9
0
        /// <summary>
        /// load ItemResult based on item selected from list, ie load shadow object
        /// </summary>
        /// <param name="selListItem"></param>
        protected override void loadSelectedItem(ItemResult selListItem)
        {
            try
            {
                if (currentItem != null)
                {
                    currentItem.PropertyChanged -= CurrentItem_PropertyChanged;
                }

                if ((selListItem?.pk != null) && (selListItem.pk != Guid.Empty))
                {
                    selectedItem = db.db.Load <ItemType>(selListItem.pk);

#if false
                    // if not currently editing anything then we match current item, but
                    // we don't update currentItem otherwise as may be a clone, etc.
                    if (isDetailViewInActive && EditCommand.CanExecute(null))
                    {
                        EditCommand.Execute(null);
                    }
#else
                    // update detail view immediately when a new item is selected
                    // note this will loose changes for a clone
                    if (currentItem != null && currentItem.IsChanged)
                    {
                        var x = MessageBox.Show("Current item has been modified, do you wish to save changes?", $"Changes to {currentItem.displayName} will be lost!", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                        if (x == MessageBoxResult.Yes)
                        {
                            if (SaveCommand.CanExecute(null))
                            {
                                SaveCommand.Execute(null);
                            }
                        }
                    }
                    if (EditCommand.CanExecute(null))
                    {
                        EditCommand.Execute(null);
                    }

                    /*
                     * currentItem = selectedItem;  //DoEdit();
                     *                           // Note: need same object so changes triggered via items bound to selectedListItem will show in detail view
                     * selListItem.entity = currentItem;
                     */
#endif
                }
                else
                {
                    selectedItem = null;
                }

                if (currentItem != null)
                {
                    currentItem.PropertyChanged += CurrentItem_PropertyChanged;
                }
                // flag other items that may change when selected item changes
                RaisePropertyChanged(nameof(HasMultipleImages));

                // select first image (or clear)
                currentImageIndex = 0;
            }
            catch (Exception e)
            {
                logger.Error(e, $"Exception in loadSelectedItem - {e.Message}");
                throw;
            }
        }
Beispiel #10
0
        public BankStatementViewModel() : base(PermissionItemName.BankStatement)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                ApproveBankStat = new RelayCommand(() => {
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    SelectedMainRow.Approved    = true;
                    SelectedMainRow.ApproveDate = DateTime.Now;
                    SelectedMainRow.ApprovedBy  = LoggedUserInfo.Iserial;
                    if (SaveCommand.CanExecute(null))
                    {
                        SaveCommand.Execute(null);
                    }
                    if (SelectedMainRow.Approved)//كده نفذ فهعمل جديد
                    {
                        if (NewCommand.CanExecute(null))
                        {
                            NewCommand.Execute(null);
                        }
                    }
                }, () => CheckCanApprove());
                DeleteBankStatDetail = new RelayCommand <object>((o) =>
                {
                    if (((KeyEventArgs)(o)).Key == Key.Delete)
                    {
                        if (SelectedMainRow.Iserial <= 0 || SelectedDetailRow.Iserial <= 0)
                        {
                            SelectedMainRow.TblBankStatDetails.Remove(SelectedDetailRow);
                            if (SelectedMainRow.TblBankStatDetails.Count == 0)
                            {
                                AddNewDetailRow(false);
                            }
                        }
                        else
                        {
                            DeleteDetailRow();
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                }, (o) => {
                    return(SelectedMainRow != null && !SelectedMainRow.Approved);
                });
                LoadingDetailRows = new RelayCommand <object>((o) =>
                {
                    var e = o as DataGridRowEventArgs;
                    if (SelectedMainRow.TblBankStatDetails.Count < PageSize)
                    {
                        return;
                    }
                    if (SelectedMainRow.TblBankStatDetails.Count - 2 < e.Row.GetIndex() && !Loading)
                    {
                        GetDetailData();
                    }
                });

                NewDetail = new RelayCommand <object>((o) =>
                {
                    var e = o as SelectionChangedEventArgs;
                    if (((KeyEventArgs)(o)).Key == Key.Down)
                    {
                        AddNewDetailRow(false);
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                });
                this.PremCompleted += (s, sv) =>
                {
                    if (this.CustomePermissions.SingleOrDefault(x => x.Code == "BankStatApprove") != null)
                    {
                        CanApprove = true;
                    }
                };
                this.GetCustomePermissions(PermissionItemName.BankStatement.ToString());

                MainRowList = new ObservableCollection <BankStatHeader>();
                AddNewMainRow(false);

                BankStatClient.GetBankStatHeaderCompleted += (s, sv) =>
                {
                    foreach (var row in sv.Result)
                    {
                        var newrow = new BankStatHeader();
                        newrow.InjectFrom(row);
                        MainRowList.Add(newrow);
                    }
                    Loading   = false;
                    FullCount = sv.fullCount;
                    if (SearchWindow != null)
                    {
                        SearchWindow.FullCount = sv.fullCount;
                        SearchWindow.Loading   = false;
                    }
                    if (FullCount == 0 && MainRowList.Count == 0)
                    {
                        AddNewMainRow(false);
                    }
                };
                BankStatClient.GetBankStatDetailCompleted += (s, sv) =>
                {
                    foreach (var row in sv.Result)
                    {
                        var newrow = new BankStatDetail();
                        newrow.InjectFrom(row);
                        //newrow.TblBankTransactionType1 = BankTransactionTypeList.FirstOrDefault(btt => btt.Iserial == newrow.TblBankTransactionType);
                        SelectedMainRow.TblBankStatDetails.Add(newrow);
                    }
                    if (!SelectedMainRow.TblBankStatDetails.Any())
                    {
                        AddNewDetailRow(false);
                    }
                    Loading = false;
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                BankStatClient.UpdateOrInsertBankStatHeaderCompleted += (s, x) =>
                {
                    BankStatHeader savedRow = null;
                    if (x.outindex >= 0)
                    {
                        savedRow = MainRowList.ElementAt(x.outindex);
                    }

                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                        savedRow.TblBank1     = BankList.FirstOrDefault(b => b.Iserial == savedRow.TblBank);
                        savedRow.TblCurrency1 = CurrencyList.FirstOrDefault(c => c.Iserial == savedRow.TblCurrency);
                        savedRow.TblBankStatDetails.Clear();
                        foreach (var item in x.Result.TblBankStatDetails)
                        {
                            var detailTemp = new BankStatDetail();
                            detailTemp.InjectFrom(item);
                            savedRow.TblBankStatDetails.Add(detailTemp);
                        }
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                    DeleteCommand.RaiseCanExecuteChanged();
                    ApproveBankStat.RaiseCanExecuteChanged();
                    DeleteBankStatDetail.RaiseCanExecuteChanged();
                    IsNewChanged();
                };
                BankStatClient.UpdateOrInsertBankStatDetailCompleted += (s, x) =>
                {
                    var savedRow = SelectedMainRow.TblBankStatDetails.ElementAt(x.outindex);
                    if (savedRow != null)
                    {
                        savedRow.InjectFrom(x.Result);
                        savedRow.TblBankTransactionType1 = BankTransactionTypeList.FirstOrDefault(bt => bt.Iserial == savedRow.TblBankTransactionType);
                    }
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };
                BankStatClient.DeleteBankStatHeaderCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }

                    var oldrow = MainRowList.FirstOrDefault(x => x.Iserial == ev.Result);
                    if (oldrow != null)
                    {
                        MainRowList.Remove(oldrow);
                    }
                };
                BankStatClient.DeleteBankStatDetailCompleted += (s, ev) =>
                {
                    if (ev.Error != null)
                    {
                        throw ev.Error;
                    }
                    var oldrow = SelectedMainRow.TblBankStatDetails.FirstOrDefault(x => x.Iserial == ev.Result.Iserial);
                    if (oldrow != null)
                    {
                        SelectedMainRow.TblBankStatDetails.Remove(oldrow);
                    }
                    RaisePropertyChanged(nameof(Total));
                    RaisePropertyChanged(nameof(IsHeaderHasDetails));
                };

                BankStatClient.IsBankStatHeaderHasMatchedRowsCompleted += (s, e) =>
                {
                    if (SelectedMainRow.Iserial == e.Iserial)
                    {
                        hasMatched = e.Result;
                    }
                    else
                    {
                        hasMatched = false;
                    }
                    RaisePropertyChanged(nameof(IsReadOnly));
                };

                BankStatClient.GetLookUpBankTransactionTypeCompleted += (s, e) =>
                {
                    BankTransactionTypeList = e.Result;
                };
                BankStatClient.GetLookUpBankCompleted += (s, e) =>
                {
                    BankList = e.Result;
                };
                BankStatClient.GetLookUpCurrencyCompleted += (s, e) =>
                {
                    CurrencyList = e.Result;
                };

                BankStatClient.InsertImportedItemsCompleted += (s, e) =>
                {
                    for (int i = 0; i < RemainningImportList.Count; i = i + step)
                    {
                        bool approve = (i + step >= RemainningImportList.Count);                                       //هل دى اخر لفة
                        var  temp    = new ObservableCollection <ImportedBankStatement>(RemainningImportList.Skip(i).Take(step));
                        BankStatClient.InsertRemainingImportedItemsAsync(e.Result, temp, LoggedUserInfo.DatabasEname); // First Time
                        requestes++;
                    }
                    ImportHeaderIserial = e.Result;
                    Loading             = false;
                };
                BankStatClient.InsertRemainingImportedItemsCompleted += (s, e) =>
                {
                    requestes--;// على اساس ان الريكويست اسرع من الريسبونس

                    foreach (var item in e.Result)
                    {
                        error += item + "\r\n";
                    }
                    if (e.Error != null)
                    {
                        requestes = -1;
                        throw e.Error;
                    }
                    else if (requestes == 0)// كده ده اخر واحد
                    {
                        if (string.IsNullOrWhiteSpace(error))
                        {
                            MessageBox.Show("Import Completed Succesfully");
                            //هجيب الريكورد الى اتحفظ ده اعرضه بقى
                            BankStatClient.GetBankStatHeaderByIserialAsync(ImportHeaderIserial, LoggedUserInfo.DatabasEname);
                            ImportHeaderIserial = -1;
                            return;
                        }
                        BankStatClient.DeleteBankStatByIserialAsync(ImportHeaderIserial, LoggedUserInfo.DatabasEname);
                        ImportHeaderIserial = -1;
                        if (MessageBox.Show("Import Completed, Do you want to view logs?", "Info", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {
                            new LogView(error).Show();
                            error = "";
                        }
                    }
                };
                BankStatClient.GetBankStatHeaderByIserialCompleted += (s, e) =>
                {
                    SelectedMainRow.InjectFrom(e.Result);
                    SelectedMainRow.TblBank1     = BankList.FirstOrDefault(b => b.Iserial == SelectedMainRow.TblBank);
                    SelectedMainRow.TblCurrency1 = CurrencyList.FirstOrDefault(c => c.Iserial == SelectedMainRow.TblCurrency);
                    if (SelectedMainRow.TblBankStatDetails != null)
                    {
                        SelectedMainRow.TblBankStatDetails = new ObservableCollection <BankStatDetail>();
                    }
                    RaisePropertyChanged(nameof(SelectedMainRow));
                    DeleteCommand.RaiseCanExecuteChanged();
                    ApproveBankStat.RaiseCanExecuteChanged();
                    DeleteBankStatDetail.RaiseCanExecuteChanged();
                    IsNewChanged();
                    GetDetailData();
                };
                BankStatClient.InsertExcelFileDateCompleted += (s, e) => {
                    //if (e.Error != null) MessageBox.Show(e.Error.Message);
                };
                ImportFromExcelCommand = new RelayCommand(() => {
                    if (!ValidHeaderData())
                    {
                        return;
                    }
                    OpenFileDialog ofd = new OpenFileDialog();
                    ofd.Filter         = "Excel Files (*.xls)|*.xls";
                    if (ofd.ShowDialog() == true)
                    {
                        var importedList = new ObservableCollection <ImportedBankStatement>();
                        var fs           = ofd.File.OpenRead();

                        var book  = Workbook.Open(fs);
                        var sheet = book.Worksheets[0];

                        var dataList = new ObservableCollection <Models.Excel.CellModel>();
                        for (int i = sheet.Cells.FirstColIndex; i < sheet.Cells.LastColIndex + 1; i++)
                        {
                            for (int j = sheet.Cells.FirstRowIndex; j < sheet.Cells.LastRowIndex + 1; j++)
                            {
                                var cellModel = new Models.Excel.CellModel()
                                {
                                    Column = i,
                                    Row    = j,
                                    Value  = sheet.Cells[j, i].StringValue.ToUpper(),
                                };
                                dataList.Add(cellModel);
                                if (i == 1)
                                {
                                    var t = sheet.Cells[j, i].StringValue.ToUpper().Split('-');
                                    if (t.Length == 3)
                                    {
                                        cellModel.Day    = t[0];
                                        cellModel.Mounth = t[1];
                                        cellModel.Year   = t[2];
                                    }
                                }
                            }
                        }
                        TblBankStatHeader headerRow = new TblBankStatHeader();
                        headerRow.InjectFrom(SelectedMainRow);
                        BankStatClient.InsertExcelFileDateAsync(headerRow, dataList, LoggedUserInfo.DatabasEname);// new ObservableCollection<Models.Excel.CellModel>(dataList.Take(300)));
                        //int docDateIndex = 0, transactionTypeIndex = 0, descriptionIndex = 0, amountIndex = 0, chequeNoIndex = 0, depositNoIndex = 0;
                        //FillList(importedList, sheet, ref docDateIndex, ref transactionTypeIndex, ref descriptionIndex, ref amountIndex, ref chequeNoIndex, ref depositNoIndex);
                        //InsertImportedDetail(importedList);
                    }
                });
                MatchCommand = new RelayCommand(() => {
                    if (SelectedMainRow.Iserial <= 0)
                    {
                        MessageBox.Show("Bank Statement must save first");
                        return;
                    }
                    var matchingView            = new BankStatementMatchView();
                    var matchingViewModel       = new BankStatementMatchViewModel();
                    matchingViewModel.HeaderRow = SelectedMainRow;
                    matchingView.DataContext    = matchingViewModel;
                    matchingView.Show();
                });

                GetComboData();
                GetMaindata();
            }
        }