Esempio n. 1
0
        private void LoadData()
        {
            storeNamesService = Program.kernel.Get <IStoreNamesService>();
            wareHousesService = Program.kernel.Get <IWareHousesService>();

            storeLoadList    = storeNamesService.GetStoreLoad().ToList();
            cellLoadList     = wareHousesService.GetWareHouses().ToList();
            cellPresenceList = wareHousesService.GetWareHousePresences().ToList();
        }
Esempio n. 2
0
 private void LoadCellZonesData()
 {
     zoneNamesService         = Program.kernel.Get <IZoneNamesService>();
     storeNamesService        = Program.kernel.Get <IStoreNamesService>();
     wareHousesService        = Program.kernel.Get <IWareHousesService>();
     storageGroupsService     = Program.kernel.Get <IStorageGroupsService>();
     storageGroupZonesService = Program.kernel.Get <IStorageGroupZonesService>();
     cellZonesService         = Program.kernel.Get <ICellZonesService>();
 }
Esempio n. 3
0
        public InventoryBillPageViewModel(INavigationService navigationService,
                                          IProductService productService,
                                          ITerminalService terminalService,
                                          IUserService userService,
                                          IWareHousesService wareHousesService,
                                          IAccountingService accountingService,
                                          IInventoryService inventoryService,
                                          IDialogService dialogService) : base(navigationService, productService,
                                                                               terminalService,
                                                                               userService,
                                                                               wareHousesService,
                                                                               accountingService,
                                                                               dialogService)
        {
            Title = "选择盘点库存";

            _inventoryService = inventoryService;


            //载入仓库
            this.Load = WareHousesLoader.Load(async() =>
            {
                try
                {
                    var result      = await _wareHousesService.GetWareHousesAsync(BillTypeEnum.InventoryAllTaskBill, force: this.ForceRefresh, calToken: new System.Threading.CancellationToken());
                    this.WareHouses = new ObservableCollection <WareHouseModel>(result?.ToList());
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
                return(WareHouses.ToList());
            });

            //开始盘点
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async wareHouse =>
            {
                if (wareHouse != null)
                {
                    var pendings = await _inventoryService.CheckInventoryAsync(wareHouse.Id, new System.Threading.CancellationToken());
                    if (pendings != null && pendings.Count > 0)
                    {
                        await UserDialogs.Instance.AlertAsync("库存正在盘点中,不能在生成盘点单.", okText: "确定");
                        return;
                    }
                    //转向盘点
                    await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName), ("WareHouse", wareHouse), ("SerchKey", ""));
                }
            })
            .DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);
        }
Esempio n. 4
0
 public MainLayoutPageViewModel(INavigationService navigationService,
                                IProductService productService,
                                IUserService userService,
                                ITerminalService terminalService,
                                IWareHousesService wareHousesService,
                                IAccountingService accountingService,
                                IDialogService dialogService) : base(navigationService, productService, terminalService,
                                                                     userService, wareHousesService, accountingService, dialogService)
 {
 }
Esempio n. 5
0
        private void LoadKeepingData(int storeEntry)
        {
            receiptsService     = Program.kernel.Get <IReceiptsService>();
            wareHousesService   = Program.kernel.Get <IWareHousesService>();
            materialsService    = Program.kernel.Get <IMaterialsService>();
            keepingsService     = Program.kernel.Get <IKeepingsService>();
            expendituresService = Program.kernel.Get <IExpendituresService>();

            keepingMaterials            = keepingsService.GetExpendituresFromKeeping().Where(s => s.StoreNameId == storeEntry || s.StoreNameId == 0).ToList();
            keepingBS.DataSource        = keepingMaterials;
            expendituresGrid.DataSource = keepingBS;
        }
Esempio n. 6
0
        private void LoadData()
        {
            storeNamesService = Program.kernel.Get <IStoreNamesService>();

            wareHousesService = Program.kernel.Get <IWareHousesService>();
            reportsService    = Program.kernel.Get <IReportsService>();
            zoneNamesService  = Program.kernel.Get <IZoneNamesService>();
            storeNamesBS.Clear();
            storeNamesBS.DataSource      = storeNamesService.GetStoreNames().Where(sn => sn.ParentId != null).OrderBy(o => o.ParentName);
            zoneNamesList                = zoneNamesService.GetZoneNameByStore();
            zoneUnspecifiedBS.DataSource = zoneNamesService.GetZonesUnspecified();
            zoneInfoList = zoneNamesService.GetCellQuantityByZones();
        }
Esempio n. 7
0
 public GlobalService(MakeRequest makeRequest,
                      IUserService userService,
                      ISettingService settingService,
                      IProductService productService,
                      ITerminalService terminalService,
                      IWareHousesService wareHousesService)
 {
     _makeRequest       = makeRequest;
     _userService       = userService;
     _productService    = productService;
     _terminalService   = terminalService;
     _wareHousesService = wareHousesService;
     _settingService    = settingService;
 }
Esempio n. 8
0
        private void RunToControlVisual()
        {
            wareHousesService = Program.kernel.Get <IWareHousesService>();

            if (storeNamesBS.Count != 0)
            {
                showWareHouseBtn.Enabled = true;

                int line = (int)((StoreNamesDTO)storeNamesBS.Current).LineCount;

                int column = (int)((StoreNamesDTO)storeNamesBS.Current).ColumnCount;
                int cell   = (int)((StoreNamesDTO)storeNamesBS.Current).CellCount;
                cellNo = line * column - cell;

                GetCellList();

                if (cellList.Count != 0)
                {
                    ControlVisual(line, column, cellList);

                    if ((cellList[1].NumberCell == null))
                    {
                        if ((line * column - cell) > 0)
                        {
                            MessageBox.Show("Необходимо указать " + (line * column - cell).ToString() + " отсутствующие ячейки!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {
                    panel.Controls.Clear();
                }
            }
            else
            {
                panel.Controls.Clear();
            }
        }
Esempio n. 9
0
        public AllfunPageViewModel(INavigationService navigationService,
                                   IProductService productService,
                                   IUserService userService,
                                   ITerminalService terminalService,
                                   IWareHousesService wareHousesService,
                                   IAccountingService accountingService,
                                   IDialogService dialogService) : base(navigationService,
                                                                        productService,
                                                                        terminalService,
                                                                        userService,
                                                                        wareHousesService,
                                                                        accountingService,
                                                                        dialogService)
        {
            Title = "全部";

            this.Load = ReactiveCommand.Create(() =>
            {
                try
                {
                    var pending  = new List <ModuleGroup>();
                    var gModules = GlobalSettings.AppDatas?.GroupBy(s => s.AType)?.ToList();
                    if (gModules != null && gModules.Any())
                    {
                        foreach (var group in gModules)
                        {
                            var first = group.FirstOrDefault();
                            if (first != null)
                            {
                                if (first.AType == 0)
                                {
                                    first.ATypeName = "单据类";
                                }
                                else if (first.AType == 1)
                                {
                                    first.ATypeName = "报表类";
                                }
                                else if (first.AType == 2)
                                {
                                    first.ATypeName = "市场类";
                                }
                                else if (first.AType == 3)
                                {
                                    first.ATypeName = "档案类";
                                }

                                if (group != null && group.Any())
                                {
                                    pending.Add(new ModuleGroup(first.ATypeName, group.ToList()));
                                }
                            }
                        }
                    }

                    if (pending.Any())
                    {
                        this.Modules = new ObservableCollection <ModuleGroup>(pending);
                    }
                }
                catch (Exception)
                {
                }
            });

            this.InvokeAppCommand = ReactiveCommand.CreateFromTask <Module>(async r =>
            {
                if (!IsFastClick())
                {
                    return;
                }

                await this.Access(r, AccessStateEnum.View, async() =>
                {
                    using (UserDialogs.Instance.Loading("加载中..."))
                    {
                        if (r.Navigation == "VisitStorePage")
                        {
                            var check = await CheckSignIn();
                            if (!check)
                            {
                                await this.NavigateAsync($"{nameof(CurrentCustomerPage)}");
                                return;
                            }
                        }
                        await this.NavigateAsync(r.Navigation, ("Reference", this.PageName));
                    }
                });
            });
        public CurrentCustomerPageViewModel(INavigationService navigationService,
                                            IProductService productService,
                                            IUserService userService,
                                            ITerminalService terminalService,
                                            IWareHousesService wareHousesService,
                                            IAccountingService accountingService,
                                            IDialogService dialogService,
                                            ILiteDbService <VisitStore> conn) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "拜访选择终端客户";
            _conn = conn;

            this.PageSize = 20;


            //搜索(默认触发Load)
            this.WhenAnyValue(x => x.Filter.SerchKey)
            .Skip(1)
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s => ((ICommand)Load)?.Execute(null))
            .DisposeWith(DeactivateWith);

            //片区选择
            this.WhenAnyValue(x => x.Filter.DistrictId)
            .Where(s => s > 0)
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s => ((ICommand)Load)?.Execute(null))
            .DisposeWith(DeactivateWith);

            //距离排序
            this.WhenAnyValue(x => x.Filter.DistanceOrderBy)
            .Where(s => s > 0)
            .Select(s => s)
            .Skip(1)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s => ((ICommand)Load)?.Execute(null))
            .DisposeWith(DeactivateWith);

            //加载数据
            this.Load = ReactiveCommand.Create(async() =>
            {
                try
                {
                    System.Diagnostics.Debug.Print("----------------------CurrentCustomerPageViewModel----------------------------->");

                    //重载时排它
                    ItemTreshold = 1;

                    try
                    {
                        if (Terminals != null && Terminals.Any())
                        {
                            Terminals?.Clear();
                        }
                    }
                    catch (Exception) { }

                    PageCounter  = 0;
                    itemTreshold = true;

                    DataVewEnable  = false;
                    NullViewEnable = true;

                    this.Longitude = GlobalSettings.Longitude ?? 0;
                    this.Latitude  = GlobalSettings.Latitude ?? 0;

                    string searchStr    = Filter?.SerchKey;
                    int?districtId      = Filter?.DistrictId;
                    int?channelId       = Filter?.ChannelId;
                    int?businessUserId  = Filter?.BusinessUserId;
                    int?rankId          = Filter?.RankId;
                    int pageNumber      = 0;
                    int pageSize        = PageSize;
                    int?lineTierId      = Filter?.LineId;
                    int distanceOrderBy = Filter.DistanceOrderBy;

                    var tuple = await _terminalService.SearchTerminals(searchStr,
                                                                       districtId,
                                                                       channelId,
                                                                       rankId,
                                                                       lineTierId,
                                                                       businessUserId,
                                                                       true,
                                                                       distanceOrderBy,
                                                                       GlobalSettings.Latitude ?? 0,
                                                                       GlobalSettings.Longitude ?? 0,
                                                                       1.5,
                                                                       pageNumber,
                                                                       pageSize);


                    var series = tuple.Item2;
                    if (series != null && series.Any())
                    {
                        this.Terminals = new AsyncObservableCollection <TerminalModel>(series);
                    }
                    else
                    {
                        ItemTreshold = -1;
                    }

                    itemTreshold = false;
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
                finally
                {
                    DataVewEnable  = true;
                    NullViewEnable = false;
                }
            });

            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                if (ItemTreshold == -1 || itemTreshold)
                {
                    return;
                }

                try
                {
                    itemTreshold = true;
                    int pageIdex = Terminals.Count / (PageSize == 0 ? 1 : PageSize);
                    if (pageIdex > 0)
                    {
                        using (var dig = UserDialogs.Instance.Loading("加载中..."))
                        {
                            string searchStr    = Filter?.SerchKey;
                            int?districtId      = Filter?.DistrictId;
                            int?channelId       = Filter?.ChannelId;
                            int?businessUserId  = Filter?.BusinessUserId;
                            int?rankId          = Filter?.RankId;
                            int pageNumber      = pageIdex;
                            int pageSize        = PageSize;
                            int?lineTierId      = Filter?.LineId;
                            int distanceOrderBy = Filter.DistanceOrderBy;

                            var tuple = await _terminalService.SearchTerminals(searchStr,
                                                                               districtId,
                                                                               channelId,
                                                                               rankId,
                                                                               lineTierId,
                                                                               businessUserId,
                                                                               true,
                                                                               distanceOrderBy,
                                                                               GlobalSettings.Latitude ?? 0,
                                                                               GlobalSettings.Longitude ?? 0,
                                                                               1.5,
                                                                               pageNumber,
                                                                               pageSize);

                            var series = tuple.Item2;
                            if (series != null && series.Any())
                            {
                                try
                                {
                                    foreach (var s in series)
                                    {
                                        if (!(this.Terminals?.Select(s => s.Id).Contains(s.Id) ?? true))
                                        {
                                            this.Terminals?.Add(s);
                                        }
                                    }
                                }
                                catch (Exception) { }
                                itemTreshold = false;
                            }
                            else
                            {
                                ItemTreshold = -1;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                    ItemTreshold = -1;
                }
            });


            //线路选择
            this.LineSelected = ReactiveCommand.Create <object>(async e => await SelectUserLine((data) =>
            {
                if (data != null)
                {
                    Filter.LineId   = data.Id;
                    Filter.LineName = data.Name;
                    if (Filter.LineId > 0)
                    {
                        var dts = data.Terminals;
                        if (dts != null && dts.Any())
                        {
                            var series = dts.OrderByDescending(t => t.Id);

                            series?.ToList().ForEach(s =>
                            {
                                s.RankName = string.IsNullOrEmpty(s.RankName) ? "A级" : s.RankName;
                                s.Distance = MapHelper.CalculateDistance(GlobalSettings.Latitude ?? 0, GlobalSettings.Longitude ?? 0, s.Location_Lat ?? 0, s.Location_Lng ?? 0);
                            });

                            if (series.Count() > 0)
                            {
                                Terminals = new AsyncObservableCollection <TerminalModel>(series);
                                MessageBus.Current.SendMessage(Terminals, Constants.TRACKTERMINALS_KEY);
                            }
                        }
                    }
                }
            }, Filter.LineId));

            //打开导航
            this.OpenNavigationToCommand = ReactiveCommand.Create <TerminalModel>(e =>
            {
                try
                {
                    var _baiduLocationService = App.Resolve <IBaiduNavigationService>();
                    _baiduLocationService?.OpenNavigationTo(e.Location_Lat ?? 0, e.Location_Lng ?? 0, e.Address);
                }
                catch (Exception)
                {
                    _dialogService.LongAlert("没有安装导航软件");
                }
            });

            //距离排序
            this.DistanceOrderCommand = ReactiveCommand.Create <int>(e =>
            {
                if (!OrderByDistance)
                {
                    this.OrderByDistance        = true;
                    this.Filter.DistanceOrderBy = 1;
                }
                else
                {
                    this.OrderByDistance        = false;
                    this.Filter.DistanceOrderBy = 2;
                }
            });

            //片区选择
            this.DistrictSelected = ReactiveCommand.Create <object>(async e => await this.NavigateAsync("SelectAreaPage", null));

            //附近客户
            this.OtherCustomerCommand = ReactiveCommand.Create <object>(e =>
            {
                if (this.MapVewEnable == false)
                {
                    Title = "附近客户";
                    this.ListVewEnable = false;
                    this.MapVewEnable  = true;
                    Filter.LineId      = 0;
                    ((ICommand)RefreshCommand)?.Execute(null);
                }
                else
                {
                    Title = "选择客户";
                    this.ListVewEnable = true;
                    this.MapVewEnable  = false;
                }
            });

            //添加客户
            this.AddCustomerCommand = ReactiveCommand.Create <object>(async e => await this.NavigateAsync("AddCustomerPage"));

            //客户选择
            this.WhenAnyValue(x => x.Selecter)
            .Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                await this.NavigateAsync("VisitStorePage", ("Terminaler", item));
                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);


            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //整单备注
                { MenuEnum.NEARCUSTOMER, (m, vm) => {
                      if (this != null)
                      {
                          Title         = "附近客户";
                          Filter.LineId = 0;
                          ((ICommand)RefreshCommand)?.Execute(null);
                      }
                  } },
                //清空单据
                { MenuEnum.LINESELECT, (m, vm) => {
                      if (this != null)
                      {
                          ((ICommand)LineSelected)?.Execute(null);
                      }
                  } }
            });

            this.BindBusyCommand(Load);
        }
Esempio n. 11
0
        public AddCustomerPageViewModel(INavigationService navigationService,
                                        ITerminalService terminalService,
                                        IProductService productService,
                                        IUserService userService,
                                        IWareHousesService wareHousesService,
                                        IAccountingService accountingService,
                                        IPermissionsService permissionsService,
                                        IDialogService dialogService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "添加客户档案";

            _permissionsService = permissionsService;
            httpClientHelper    = new HttpClientHelper();

            this.EntryUnfocused = ReactiveCommand.Create <object>(e =>
            {
                Storage();
            });

            this.EntryNameUnfocused = ReactiveCommand.Create <object>(async e =>
            {
                var s      = PostMData.Name;
                var result = await _terminalService.CheckTerminalAsync(s);
                if (result)
                {
                    var ok = await _dialogService.ShowConfirmAsync("终端名称已经存在,是否继续添加。?", "提示", "确定", "取消");
                    if (!ok)
                    {
                        PostMData.Name = "";
                    }
                }
            });

            //片区选择
            this.DistrictSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectDistrict((data) =>
                {
                    if (data != null)
                    {
                        PostMData.DistrictId   = data.Id;
                        PostMData.DistrictName = data.Name;
                        Storage();
                    }
                });
            });

            //渠道选择
            this.ChannelSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectChannel((data) =>
                {
                    if (data != null)
                    {
                        PostMData.ChannelId   = data.Id;
                        PostMData.ChannelName = data.Name;
                        Storage();
                    }
                });
            });

            //线路选择
            this.LineSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectLine((data) =>
                {
                    if (data != null)
                    {
                        PostMData.LineId   = data.Id;
                        PostMData.LineName = data.Name;
                        Storage();
                    }
                });
            });

            //地图定位
            this.AddressSelected = ReactiveCommand.Create <object>(async e =>
            {
                await this.NavigateAsync("SelectLocationPage");
            });

            //客户等级
            this.RankSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectRank((data) =>
                {
                    if (data != null)
                    {
                        PostMData.RankId   = data.Id;
                        PostMData.RankName = data.Name;
                        Storage();
                    }
                });
            });

            //验证
            var valid_Photo     = this.ValidationRule(x => x.PostMData.DoorwayPhoto, _isDefined, "请添加门头照片");
            var valid_Name      = this.ValidationRule(x => x.PostMData.Name, _isDefined, "客户名称未指定");
            var valid_BossName  = this.ValidationRule(x => x.PostMData.BossName, _isDefined, "老板姓名未指定");
            var valid_BossCall  = this.ValidationRule(x => x.PostMData.BossCall, _isDefined, "联系电话未指定");
            var valid_ChannelId = this.ValidationRule(x => x.PostMData.ChannelId, _isZero, "渠道未指定");
            var valid_Address   = this.ValidationRule(x => x.PostMData.Address, _isDefined, "请填写详细地址");

            //保存
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.EndPointListSave, async() =>
                {
                    if (PostMData.DoorwayPhoto.Equals("PhotoIcon.png"))
                    {
                        _dialogService.LongAlert("请添加门头照片!");
                        return Unit.Default;
                    }

                    var postMData = Storage();

                    return await SubmitAsync(postMData, _terminalService.CreateOrUpdateAsync, async(result) =>
                    {
                        try
                        {
                            GlobalSettings.TempAddCustomerStore = null;
                            PostMData = new TerminalModel();
                        }
                        catch (Exception ex)
                        { }
                    }, reffPage: this.PageName);
                }));
            }, this.IsValid());

            this.AddSaveCommand = ReactiveCommand.Create <object>(e =>
            {
                ((ICommand)SubmitDataCommand)?.Execute(null);
            }, this.IsValid());

            //上传门头
            this.UploadFaceCommand = ReactiveCommand.Create(() =>
            {
                RapidTapPreventor(async() =>
                {
                    await this.NavigateAsync("CameraViewPage", ("TakeType", "AddCustomer"));
                });
            });

            //拍照上传
            MessageBus
            .Current
            .Listen <byte[]?>(string.Format(Constants.CAMERA_KEY, "AddCustomer"))
            .Subscribe(bit =>
            {
                if (bit != null && bit.Length > 0)
                {
                    UploadPhotograph((u) =>
                    {
                        var facePath           = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + "";
                        PostMData.DoorwayPhoto = facePath;
                        Storage();
                    }, new MemoryStream(bit));
                }
            }).DisposeWith(DeactivateWith);
        }
Esempio n. 12
0
        public AddCostPageViewModel(INavigationService navigationService,
                                    IProductService productService,
                                    IUserService userService,
                                    ITerminalService terminalService,
                                    IWareHousesService wareHousesService,
                                    IAccountingService accountingService,
                                    IDialogService dialogService
                                    ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "添加费用";

            //验证
            var valid_TerminalId         = this.ValidationRule(x => x.Model.CustomerId, _isZero, "客户未指定");
            var valid_AccountingOptionId = this.ValidationRule(x => x.Model.AccountingOptionId, _isZero, "类别未指定");
            var valid_Amount             = this.ValidationRule(x => x.Model.Amount, _isDZero, "金额未指定");

            //费用选择
            this.AccountingSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectCostAccounting((data) =>
                {
                    this.Accounting = data;

                    Model.AccountingOptionId   = data.AccountingOptionId;
                    Model.AccountingOptionName = data.Name;

                    Filter.AccountOptionId = data.AccountingOptionId;
                }, BillTypeEnum.CostContractBill);
            });


            //合同选择
            this.ContractSelected = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    this.Alert(valid_TerminalId.Message[0]); return;
                }
                if (!valid_AccountingOptionId.IsValid)
                {
                    this.Alert(valid_AccountingOptionId.Message[0]); return;
                }

                await this.NavigateAsync("SelectContractPage",
                                         ("Accounting", new AccountingModel()
                {
                    AccountingOptionId = Model.AccountingOptionId,
                    AccountingOptionName = Model.AccountingOptionName
                }),
                                         ("Terminaler", new TerminalModel()
                {
                    Id = Model.CustomerId,
                    Name = Model.CustomerName
                }));
            });

            //合同余额
            this.WhenAnyValue(x => x.Model.Balance)
            .Subscribe(s =>
            {
                this.Model.ShowBalance = s.HasValue && s.Value > 0;
            }).DisposeWith(DeactivateWith);


            this.WhenAnyValue(x => x.Model.AccountingOptionId)
            .Subscribe(s => { IsRemoveing = s > 0; })
            .DisposeWith(this.DeactivateWith);


            //保存
            this.SaveCommand = ReactiveCommand.CreateFromTask <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    this.Alert(valid_TerminalId.Message[0]); return;
                }
                if (!valid_AccountingOptionId.IsValid)
                {
                    this.Alert(valid_AccountingOptionId.Message[0]); return;
                }
                if (!valid_Amount.IsValid)
                {
                    this.Alert(valid_Amount.Message[0]); return;
                }

                if (Model.CostContractId > 0 && Model.Balance == 0)
                {
                    this.Alert("余额不足!"); return;
                }

                if (Model.CostContractId > 0)
                {
                    Model.Amount = Model.Balance;
                }

                await _navigationService.GoBackAsync(("CostExpenditure", Model));
            });

            //移除
            this.RemoveCommand = ReactiveCommand.CreateFromTask <object>(async e =>
            {
                var selecter = e as AddCostPageViewModel;
                await _navigationService.GoBackAsync(("RemoveCostExpenditure", selecter.Model));
            });
        }
Esempio n. 13
0
        public VisitStorePageViewModel(INavigationService navigationService,
                                       IProductService productService,
                                       ITerminalService terminalService,
                                       IUserService userService,
                                       IWareHousesService wareHousesService,
                                       IAccountingService accountingService,
                                       IMediaPickerService mediaPickerService,
                                       ILiteDbService <TrackingModel> conn,
                                       ILiteDbService <VisitStore> vsdb,
                                       IPermissionsService permissionsService,
                                       IDialogService dialogService) : base(navigationService,
                                                                            productService,
                                                                            terminalService,
                                                                            userService,
                                                                            wareHousesService,
                                                                            accountingService,
                                                                            dialogService)
        {
            _permissionsService = permissionsService;
            _mediaPickerService = mediaPickerService;

            _conn = conn;
            _vsdb = vsdb;

            Title = "拜访门店";

            httpClientHelper = new HttpClientHelper();

            this.SubmitText = "\uf017";

            this.Load = ReactiveCommand.Create(async() =>
            {
                try
                {
                    var check          = await CheckSignIn();
                    this.SignInEnabled = !check;

                    if (!string.IsNullOrWhiteSpace(Settings.DisplayPhotos))
                    {
                        var displayPhotos = JsonConvert.DeserializeObject <List <DisplayPhoto> >(Settings.DisplayPhotos);
                        if (displayPhotos != null)
                        {
                            this.Bill.DisplayPhotos = new ObservableCollection <DisplayPhoto>(displayPhotos);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(Settings.DoorheadPhotos))
                    {
                        var doorheadPhotos = JsonConvert.DeserializeObject <List <DoorheadPhoto> >(Settings.DoorheadPhotos);
                        if (doorheadPhotos != null)
                        {
                            this.Bill.DoorheadPhotos = new ObservableCollection <DoorheadPhoto>(doorheadPhotos);
                        }
                    }

                    //重新获取客户信息
                    if (Settings.LastSigninCoustmerId > 0)
                    {
                        var tt = await _terminalService.GetTerminalAsync(Settings.LastSigninCoustmerId);
                        if (tt != null)
                        {
                            this.Terminal     = tt;
                            Bill.TerminalId   = tt.Id;
                            Bill.TerminalName = tt.Name;
                        }
                    }


                    //有没签退信息时
                    if (this.OutVisitStore != null)
                    {
                        //刷新状态
                        Refresh(this.OutVisitStore);
                    }

                    //如果上次签到客户存在时
                    var terminalId = Settings.LastSigninCoustmerId > 0 ? Settings.LastSigninCoustmerId : Bill.TerminalId;
                    if (terminalId > 0)
                    {
                        //获取终端余额
                        _terminalService.Rx_GetTerminalBalance(terminalId, new CancellationToken())?.Subscribe((balance) =>
                        {
                            if (balance != null)
                            {
                                this.TBalance = balance;
                            }
                        }).DisposeWith(DeactivateWith);


                        //获取上次拜访信息
                        _terminalService.Rx_GetLastVisitStoreAsync(terminalId, Settings.UserId, new CancellationToken())?.Subscribe((result) =>
                        {
                            if (result != null && result.Id > 0)
                            {
                                try
                                {
                                    //上次签到时间
                                    if (result.SigninDateTime != null)
                                    {
                                        var seconds = (int)DateTime.Now.Subtract(result.SigninDateTime).TotalSeconds;
                                        var coms    = CommonHelper.ConvetToSeconds(seconds);

                                        if (!string.IsNullOrEmpty(coms))
                                        {
                                            this.Bill.LastSigninDateTimeName = coms;
                                        }
                                    }

                                    //上次采购时间
                                    if (result.LastPurchaseDate != null)
                                    {
                                        var seconds = (int)DateTime.Now.Subtract(result.LastPurchaseDate).TotalSeconds;
                                        var coms    = CommonHelper.ConvetToSeconds(seconds);
                                        if (!string.IsNullOrEmpty(coms))
                                        {
                                            this.Bill.LastPurchaseDateTimeName = coms;
                                        }
                                    }

                                    if (this.OutVisitStore == null && result.SigninDateTime != null)
                                    {
                                        this.Bill.SigninDateTime = result.SigninDateTime;
                                    }
                                }
                                catch (Exception) { }
                            }
                        }).DisposeWith(DeactivateWith);
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //历史记录选择
            this.HistoryCommand = ReactiveCommand.Create <object>(async e => await this.NavigateAsync($"{nameof(VisitRecordsPage)}", null));

            //到店签到
            this.OpenSignInCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                if (Bill.TerminalId == 0)
                {
                    await this.NavigateAsync("CurrentCustomerPage");
                    return(Unit.Default);
                }

                var loc = await _permissionsService.GetLocationConsent();
                if (loc != PermissionStatus.Granted)
                {
                    await _dialogService.ShowAlertAsync("你的位置服务没有开启,请打开GPS", "定位", "确定");
                    return(Unit.Default);
                }

                if (Bill.TerminalId == 0 || string.IsNullOrEmpty(Bill.TerminalName))
                {
                    this.Alert("未选择客户...");
                    return(Unit.Default);
                }

                if (IsFooterVisible)
                {
                    IsVisible  = true;
                    IsExpanded = true;
                    //载入位置
                    ReloadLocation();
                    IsFooterVisible = false;
                }
                else
                {
                    IsVisible       = false;
                    IsExpanded      = false;
                    IsFooterVisible = true;
                }

                return(Unit.Default);
            });

            //取消签到
            this.CancelSignIn = ReactiveCommand.Create(() =>
            {
                IsVisible       = false;
                IsExpanded      = false;
                IsFooterVisible = true;
            });

            //签到
            this.SignInCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    if (!IsFastClick())
                    {
                        return(Unit.Default);
                    }

                    bool continueTodo = true;
                    if (Terminal.CalcDistance() > 50)
                    {
                        continueTodo  = await UserDialogs.Instance.ConfirmAsync($"你确定要在{Terminal.Distance:#.00}米外签到吗?", "警告", cancelText: "不签到", okText: "继续签到");
                        Bill.Abnormal = true;
                        Bill.Distance = Math.Round(Terminal.Distance, 2);
                    }


                    var lat = GlobalSettings.Latitude ?? 0;
                    var lan = GlobalSettings.Longitude ?? 0;


                    if (!continueTodo)
                    {
                        return(Unit.Default);
                    }

                    //签到
                    Bill.Id                   = 0;
                    Bill.StoreId              = Settings.StoreId;
                    Bill.BusinessUserId       = Settings.UserId;
                    Bill.BusinessUserName     = Settings.UserRealName;
                    Bill.ChannelId            = Terminal.ChannelId;
                    Bill.DistrictId           = Terminal.DistrictId;
                    Bill.SigninDateTimeEnable = true;
                    Bill.SigninDateTime       = DateTime.Now;
                    Bill.SignOutDateTime      = DateTime.Now;
                    Bill.VisitTypeId          = 2;//计划内
                    Bill.SignTypeId           = 1;
                    Bill.SignType             = Enums.SignEnum.CheckIn;
                    Bill.Remark               = LocationAddress;

                    //获取坐标
                    Bill.Latitude  = lat;
                    Bill.Longitude = lan;

                    return(await SubmitAsync(Bill, _terminalService.SignInVisitStoreAsync, async(result) =>
                    {
                        if (!result.Success)
                        {
                            this.IsVisible = false;
                            this.IsExpanded = false;
                            this.IsFooterVisible = true;
                        }
                        else
                        {
                            if (result.Data is VisitStore data)
                            {
                                this.SignInEnabled = false;
                                this.SignOutEnabled = true;
                                this.OutVisitStore = null;

                                //drawer
                                this.IsVisible = false;
                                this.IsExpanded = false;
                                this.IsFooterVisible = true;

                                //记录下签到ID
                                Settings.LastSigninId = data.Id;
                                Settings.LastSigninCoustmerId = Bill.TerminalId;
                                Settings.LastSigninCoustmerName = Bill.TerminalName;

                                this.Bill.LastSigninDateTime = data.LastSigninDateTime;
                                this.Bill.LastPurchaseDateTime = data.LastPurchaseDateTime;

                                //添加签到记录
                                try
                                {
                                    Terminal.Id = Bill.TerminalId;
                                    Terminal.LastSigninDateTimeName = data.SigninDateTime.ToString();
                                    Terminal.SigninDateTime = data.SigninDateTime;
                                    await _terminalService.AddTerminal(Terminal);
                                }
                                catch (Exception) { }
                            }
                        }
                    }, goBack: false));
                }
                catch (Exception)
                {
                    this.IsVisible       = false;
                    this.IsExpanded      = false;
                    this.IsFooterVisible = true;

                    await ShowAlert(false, $"出错啦,内部异常!");
                    return(Unit.Default);
                }
            });

            //校准位置
            this.CorrectPositionCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    var lat = GlobalSettings.Latitude ?? 0;
                    var lan = GlobalSettings.Longitude ?? 0;

                    if (Terminal == null || Terminal.Id == 0)
                    {
                        await ShowAlert(false, $"无效操作!");
                        return;
                    }

                    if (lat != 0 && lan != 0)
                    {
                        var distance          = MapHelper.CalculateDistance(GlobalSettings.Latitude ?? 0, GlobalSettings.Longitude ?? 0, this.Terminal?.Location_Lat ?? 0, this.Terminal?.Location_Lng ?? 0);
                        Terminal.Location_Lat = GlobalSettings.Latitude;
                        Terminal.Location_Lng = GlobalSettings.Longitude;
                        Terminal.Distance     = distance;
                        await _terminalService.UpdateterminalAsync(Terminal.Id, GlobalSettings.Latitude ?? 0, GlobalSettings.Longitude ?? 0);
                    }

                    await ShowAlert(true, $"校准成功!");
                }
                catch (Exception)
                {
                    await ShowAlert(false, $"出错啦,内部异常!");
                }
            });

            //离店签退
            this.SignOutCommend = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    int onStoreStopSeconds = 0;
                    double subtract        = DateTime.Now.Subtract(Bill?.SigninDateTime ?? DateTime.Now).TotalMinutes;
                    if (!string.IsNullOrEmpty(Settings.CompanySetting))
                    {
                        var companySetting = JsonConvert.DeserializeObject <CompanySettingModel>(Settings.CompanySetting);
                        if (companySetting != null)
                        {
                            onStoreStopSeconds = companySetting.OnStoreStopSeconds;
                        }
                    }

                    if (!SignOutEnabled)
                    {
                        this.Alert("还没签到哦!");
                        return(Unit.Default);
                    }

                    if (onStoreStopSeconds > 0 && subtract < onStoreStopSeconds)
                    {
                        this.Alert($"签退无效,拜访在店时间必须大于{onStoreStopSeconds}分钟");
                        return(Unit.Default);
                    }

                    if (Settings.LastSigninId == 0)
                    {
                        this.Alert("签退无效,无法确定记录");
                        return(Unit.Default);
                    }

                    if (Bill.TerminalId == 0 || string.IsNullOrEmpty(Bill.TerminalName))
                    {
                        this.Alert("选择客户");
                        return(Unit.Default);
                    }

                    if (Bill.DoorheadPhotos == null || Bill.DoorheadPhotos.Count == 0)
                    {
                        this.Alert("请拍摄门头照片");
                        return(Unit.Default);
                    }

                    if (Bill.DisplayPhotos == null || Bill.DisplayPhotos.Count == 0)
                    {
                        this.Alert("请拍摄陈列照片");
                        return(Unit.Default);
                    }

                    if (BillId > 0)
                    {
                        switch (BillType)
                        {
                        case BillTypeEnum.SaleReservationBill:
                            this.Bill.SaleReservationBillId = BillId;
                            this.Bill.SaleOrderAmount       = Amount;
                            break;

                        case BillTypeEnum.SaleBill:
                            this.Bill.SaleBillId = BillId;
                            this.Bill.SaleAmount = Amount;
                            break;

                        case BillTypeEnum.ReturnReservationBill:
                            this.Bill.ReturnReservationBillId = BillId;
                            this.Bill.ReturnOrderAmount       = Amount;
                            break;

                        case BillTypeEnum.ReturnBill:
                            this.Bill.ReturnBillId = BillId;
                            this.Bill.ReturnAmount = Amount;
                            break;
                        }
                    }

                    //签退
                    Bill.Id = Settings.LastSigninId;
                    Bill.SignOutDateTime = DateTime.Now;
                    Bill.SignTypeId      = 2;

                    await SubmitAsync(Bill, _terminalService.SignOutVisitStoreAsync, async(result) =>
                    {
                        if (result.Success)
                        {
                            this.SignOutEnabled            = false;
                            this.Bill.SigninDateTimeEnable = false;
                            this.OutVisitStore             = null;

                            Settings.LastSigninId           = 0;
                            Settings.LastSigninCoustmerId   = 0;
                            Settings.LastSigninCoustmerName = "";

                            Settings.DisplayPhotos  = "";
                            Settings.DoorheadPhotos = "";

                            //更新签到记录
                            try
                            {
                                Terminal.Id = Bill.TerminalId;
                                Terminal.SignOutDateTime = Bill.SignOutDateTime;
                                await _terminalService.UpdateTerminal(Terminal);
                            }catch (Exception) { }
                        }
                    });

                    await _navigationService.GoBackAsync();

                    return(Unit.Default);
                }
                catch (Exception)
                {
                    await ShowAlert(false, $"出错啦,内部异常!");
                    return(Unit.Default);
                }
            });

            //应用选择执行
            this.InvokeAppCommand = ReactiveCommand.CreateFromTask <string>(async(r) =>
            {
                try
                {
                    if (Settings.LastSigninId != 0 && Settings.LastSigninCoustmerId != 0)
                    {
                        await this.NavigateAsync(r.ToString(),
                                                 ("TerminalId", Bill.TerminalId),
                                                 ("TerminalName", Bill.TerminalName),
                                                 ("Reference", this.PageName));
                    }
                    else
                    {
                        await ShowAlert(false, "需要先签到后操作");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //拍照选择
            this.CameraPhotoCmd = ReactiveCommand.CreateFromTask <string>(async(r) =>
            {
                if (!IsFastClick())
                {
                    return;
                }

                if (this.SignInEnabled)
                {
                    this.Alert("还没有签到哦!");
                }
                else
                {
                    await this.NavigateAsync("CameraViewPage", ("TakeType", r));
                }
            });

            //删除门头照片
            this.RemoveStoragePathCommand = ReactiveCommand.Create <string>(async x =>
            {
                var ok = await _dialogService.ShowConfirmAsync("是否要删除该图片?", okText: "确定", cancelText: "取消");
                if (ok)
                {
                    var temp = this.Bill.DoorheadPhotos.FirstOrDefault(s => s.StoragePath == x);
                    if (temp != null)
                    {
                        this.Bill.DoorheadPhotos.Remove(temp);
                        Settings.DoorheadPhotos = JsonConvert.SerializeObject(this.Bill.DoorheadPhotos);
                    }
                }
            });

            //删除陈列照片
            this.RemoveDisplayPathCommand = ReactiveCommand.Create <string>(async x =>
            {
                var ok = await _dialogService.ShowConfirmAsync("是否要删除该图片?", okText: "确定", cancelText: "取消");
                if (ok)
                {
                    var temp = this.Bill.DisplayPhotos.FirstOrDefault(s => s.DisplayPath == x);
                    if (temp != null)
                    {
                        this.Bill.DisplayPhotos.Remove(temp);
                        Settings.DisplayPhotos = JsonConvert.SerializeObject(this.Bill.DisplayPhotos);
                    }
                }
            });

            //定位
            this.OrientationCmd = ReactiveCommand.Create(() =>
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    ReloadLocation();
                });
            });

            //预览照片
            this.WhenAnyValue(x => x.DoorheadPhotoSelecter)
            .Throttle(TimeSpan.FromMilliseconds(200))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                var images = new List <string> {
                    item.StoragePath
                };
                await this.NavigateAsync("ImageViewerPage", ("ImageInfos", images));
                DoorheadPhotoSelecter = null;
            }).DisposeWith(DeactivateWith);

            this.WhenAnyValue(x => x.DisplayPhotoSelecter)
            .Throttle(TimeSpan.FromMilliseconds(200))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                var images = new List <string> {
                    item.DisplayPath
                };
                await this.NavigateAsync("ImageViewerPage", ("ImageInfos", images));
                DisplayPhotoSelecter = null;
            }).DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);


            //拍照上传
            MessageBus
            .Current
            .Listen <byte[]?>(string.Format(Constants.CAMERA_KEY, "DoorheadPhotos"))
            .Subscribe(bit =>
            {
                if (bit != null && bit.Length > 0)
                {
                    UploadPhotograph((u) =>
                    {
                        var photo = new DoorheadPhoto
                        {
                            StoragePath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + ""
                        };
                        this.Bill.DoorheadPhotos.Add(photo);
                        Settings.DoorheadPhotos = JsonConvert.SerializeObject(this.Bill.DoorheadPhotos);
                    }, new MemoryStream(bit));
                }
            }).DisposeWith(DeactivateWith);


            MessageBus
            .Current
            .Listen <byte[]?>(string.Format(Constants.CAMERA_KEY, "DisplayPhotos"))
            .Subscribe(bit =>
            {
                if (bit != null && bit.Length > 0)
                {
                    UploadPhotograph((u) =>
                    {
                        var photo = new DisplayPhoto
                        {
                            DisplayPath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + ""
                        };
                        this.Bill.DisplayPhotos.Add(photo);
                        Settings.DisplayPhotos = JsonConvert.SerializeObject(this.Bill.DisplayPhotos);
                    }, new MemoryStream(bit));
                }
            }).DisposeWith(DeactivateWith);

            this.Load.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.HistoryCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.OpenSignInCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CancelSignIn.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.SignInCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CorrectPositionCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.SignOutCommend.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.InvokeAppCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.CameraPhotoCmd.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.RemoveStoragePathCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.RemoveDisplayPathCommand.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
            this.OrientationCmd.ThrownExceptions.Subscribe(ex => { Debug.Print(ex.StackTrace); }).DisposeWith(this.DeactivateWith);
        }
Esempio n. 14
0
        public SelectCustomerPageViewModel(INavigationService navigationService,
                                           IProductService productService,
                                           ITerminalService terminalService,
                                           IUserService userService,
                                           IWareHousesService wareHousesService,
                                           IAccountingService accountingService,
                                           IDialogService dialogService,
                                           ILiteDbService <VisitStore> conn) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "选择客户";

            _conn = conn;

            //搜索
            this.WhenAnyValue(x => x.Filter.SerchKey)
            .Select(s => s)
            .Skip(1)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s =>
            {
                ((ICommand)Load)?.Execute(null);
            })
            .DisposeWith(DeactivateWith);

            //片区选择
            this.WhenAnyValue(x => x.Filter.DistrictId)
            .Where(s => s > 0)
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s =>
            {
                ((ICommand)Load)?.Execute(null);
            })
            .DisposeWith(DeactivateWith);

            //加载数据
            this.Load = ReactiveCommand.Create(async() =>
            {
                try
                {
                    //重载时排它
                    ItemTreshold = 1;

                    try
                    {
                        if (Terminals != null && Terminals.Any())
                        {
                            Terminals?.Clear();
                        }
                    }
                    catch (Exception) { }

                    DataVewEnable  = false;
                    NullViewEnable = true;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        this.Longitude = GlobalSettings.Longitude ?? 0;
                        this.Latitude  = GlobalSettings.Latitude ?? 0;

                        string searchStr    = Filter?.SerchKey;
                        int?districtId      = Filter?.DistrictId;
                        int?channelId       = Filter?.ChannelId;
                        int?businessUserId  = Filter?.BusinessUserId;
                        int?rankId          = Filter?.RankId;
                        int pageNumber      = 0;
                        int pageSize        = PageSize;
                        int?lineTierId      = Filter?.LineId;
                        int distanceOrderBy = Filter.DistanceOrderBy;

                        var tuple = await _terminalService.SearchTerminals(searchStr,
                                                                           districtId,
                                                                           channelId,
                                                                           rankId,
                                                                           lineTierId,
                                                                           businessUserId,
                                                                           true,
                                                                           distanceOrderBy,
                                                                           GlobalSettings.Latitude ?? 0,
                                                                           GlobalSettings.Longitude ?? 0,
                                                                           0.5,
                                                                           pageNumber,
                                                                           pageSize);

                        var series = tuple.Item2;
                        if (series != null && series.Any())
                        {
                            this.Terminals = new AsyncObservableCollection <TerminalModel>(series);
                        }
                        else
                        {
                            ItemTreshold = -1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
                finally
                {
                    NullViewEnable = false;
                    DataVewEnable  = true;
                }
            });

            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                if (ItemTreshold == -1)
                {
                    return;
                }
                try
                {
                    int pageIdex = Terminals.Count / (PageSize == 0 ? 1 : PageSize);
                    if (pageIdex > 0)
                    {
                        using (var dig = UserDialogs.Instance.Loading("加载中..."))
                        {
                            string searchStr    = Filter?.SerchKey;
                            int?districtId      = Filter?.DistrictId;
                            int?channelId       = Filter?.ChannelId;
                            int?businessUserId  = Filter?.BusinessUserId;
                            int?rankId          = Filter?.RankId;
                            int pageNumber      = pageIdex;
                            int pageSize        = PageSize;
                            int?lineTierId      = Filter?.LineId;
                            int distanceOrderBy = Filter.DistanceOrderBy;

                            var tuple = await _terminalService.SearchTerminals(searchStr,
                                                                               districtId,
                                                                               channelId,
                                                                               rankId,
                                                                               lineTierId,
                                                                               businessUserId,
                                                                               true,
                                                                               distanceOrderBy,
                                                                               GlobalSettings.Latitude ?? 0,
                                                                               GlobalSettings.Longitude ?? 0,
                                                                               0.5,
                                                                               pageNumber,
                                                                               pageSize);

                            var series = tuple.Item2;
                            if (series != null && series.Any())
                            {
                                try
                                {
                                    foreach (var s in series)
                                    {
                                        if (!(this.Terminals?.Select(s => s.Id).Contains(s.Id) ?? false))
                                        {
                                            this.Terminals?.Add(s);
                                        }
                                    }
                                }
                                catch (Exception) { }
                            }
                            else
                            {
                                ItemTreshold = -1;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                    ItemTreshold = -1;
                }
            });

            //选择
            this.WhenAnyValue(x => x.Selecter)
            .Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                Filter.SerchKey = "";
                await _navigationService.GoBackAsync(("Filter", Filter), ("Terminaler", item));
            })
            .DisposeWith(DeactivateWith);


            this.BindBusyCommand(Load);
        }
Esempio n. 15
0
        public TrackAllocationBillPageViewModel(INavigationService navigationService,
                                                IProductService productService,
                                                IUserService userService,
                                                ITerminalService terminalService,
                                                IWareHousesService wareHousesService,
                                                IAccountingService accountingService,
                                                IDialogService dialogService
                                                ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "装车调拨";

            InitBill();

            //验证
            var valid_ShipmentWareHouseId = this.ValidationRule(x => x.Bill.ShipmentWareHouseId, _isZero, "出货仓库未指定");
            var valid_IncomeWareHouseId   = this.ValidationRule(x => x.Bill.IncomeWareHouseId, _isZero, "入货仓库未指定");
            var valid_ProductCount        = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");
            var valid_IsVieweBill         = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (Bill.ShipmentWareHouseId == 0)
                {
                    _dialogService.ShortAlert(valid_ShipmentWareHouseId.Message[0]);
                    return;
                }

                if (Bill.IncomeWareHouseId == 0)
                {
                    _dialogService.ShortAlert(valid_IncomeWareHouseId.Message[0]);
                    return;
                }

                if (Bill.ShipmentWareHouseId == Bill.IncomeWareHouseId)
                {
                    _dialogService.ShortAlert("出入库不能相同!");
                    return;
                }
                //传入当前主库
                this.WareHouse.Id         = Bill.ShipmentWareHouseId;
                this.WareHouse.Name       = Bill.ShipmentWareHouseName;
                this.Filter.WareHouseId   = Bill.ShipmentWareHouseId;
                this.Filter.WareHouseName = Bill.ShipmentWareHouseName;

                await this.NavigateAsync("SelectProductPage",
                                         ("Reference", this.PageName),
                                         ("Bill", Bill),
                                         ("Filter", Filter),
                                         ("WareHouse", WareHouse),
                                         ("SerchKey", Filter.SerchKey));
            });

            //编辑商品
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                if (item != null)
                {
                    var product = ProductSeries.Select(p => p).Where(p => p.Id == item.ProductId).FirstOrDefault();
                    if (product != null)
                    {
                        product.UnitId   = item.UnitId;
                        product.Quantity = item.Quantity;
                        product.Remark   = item.Remark;
                        product.Subtotal = item.Subtotal;
                        product.UnitName = item.UnitName;

                        if (item.BigUnitId > 0)
                        {
                            product.bigOption.Name        = item.UnitName;
                            product.BigPriceUnit.Quantity = item.Quantity;
                            product.BigPriceUnit.UnitId   = item.BigUnitId ?? 0;
                            product.BigPriceUnit.Remark   = item.Remark;
                        }

                        if (item.SmallUnitId > 0)
                        {
                            product.bigOption.Name          = item.UnitName;
                            product.SmallPriceUnit.Quantity = item.Quantity;
                            product.SmallPriceUnit.UnitId   = item.SmallUnitId;
                            product.SmallPriceUnit.Remark   = item.Remark;
                        }

                        await this.NavigateAsync("EditAllocationProductPage", ("Product", product));
                    }
                }

                this.Selecter = null;
            }, ex => _dialogService.ShortAlert(ex.ToString()))
            .DisposeWith(DeactivateWith);

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                //await this.Access(AccessGranularityEnum.TrackSchedulingScheduling);
                return(await this.Access(AccessGranularityEnum.TrackSchedulingScheduling, async() =>
                {
                    if (!valid_ShipmentWareHouseId.IsValid)
                    {
                        this.Alert(valid_ShipmentWareHouseId.Message[0]); return Unit.Default;
                    }
                    if (!valid_IncomeWareHouseId.IsValid)
                    {
                        this.Alert(valid_IncomeWareHouseId.Message[0]); return Unit.Default;
                    }
                    if (!valid_ProductCount.IsValid)
                    {
                        this.Alert(valid_ProductCount.Message[0]); return Unit.Default;
                    }

                    var postMData = new AllocationUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        ShipmentWareHouseId = Bill.ShipmentWareHouseId,
                        IncomeWareHouseId = Bill.IncomeWareHouseId,
                        CreatedOnUtc = Bill.CreatedOnUtc,
                        AllocationByMinUnit = false,
                        Remark = Bill.Remark,
                        //商品项目
                        Items = Bill.Items?.Where(i => i.Quantity > 0).ToList(),
                    };

                    return await SubmitAsync(postMData, Bill.Id, _wareHousesService.CreateOrUpdateAllocationbillAsync, (result) =>
                    {
                        Bill = new AllocationBillModel();
                    });
                }));
            },
                                                                                   this.IsValid());

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //整单备注
                { MenuEnum.REMARK, (m, vm) => {
                      AllRemak((result) =>
                        {
                            Bill.Remark = result;
                        }, Bill.Remark);
                  } },
Esempio n. 16
0
        public StockQueryPageViewModel(INavigationService navigationService,
                                       IProductService productService,
                                       IUserService userService,
                                       ITerminalService terminalService,
                                       IWareHousesService wareHousesService,
                                       IAccountingService accountingService,
                                       IReportingService reportingService,
                                       IDialogService dialogService
                                       ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title             = "库存查询";
            this.ForceRefresh = true;

            _reportingService = reportingService;

            //搜索
            this.WhenAnyValue(x => x.Filter.SerchKey)
            .Where(s => !string.IsNullOrEmpty(s))
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(2), RxApp.MainThreadScheduler)
            .Subscribe(s => { ((ICommand)SerchCommand)?.Execute(s); })
            .DisposeWith(DeactivateWith);

            this.SerchCommand = ReactiveCommand.Create <string>(e =>
            {
                if (string.IsNullOrEmpty(Filter.SerchKey))
                {
                    this.Alert("请输入关键字!");
                    return;
                }
                ((ICommand)Load)?.Execute(null);
            });

            this.Load = StockSeriesLoader.Load(async() =>
            {
                //重载时排它
                ItemTreshold = 1;

                try
                {
                    this.StockSeries?.Clear();
                    var pending = new List <StockCategoryGroup>();
                    var results = await GetStockCategoryGroupPage(0, PageSize);
                    if (results != null && results.Any())
                    {
                        foreach (var item in results)
                        {
                            if (pending?.Count(s => s.CategoryName == item.CategoryName) == 0)
                            {
                                pending.Add(item);
                            }
                        }
                        this.TotalAmount = pending?.Select(p => p.SubCostAmount).Sum();

                        if (pending.Any())
                        {
                            this.StockSeries = new ObservableRangeCollection <StockCategoryGroup>(pending);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }

                return(StockSeries);
            });


            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                using (var dig = UserDialogs.Instance.Loading("加载中..."))
                {
                    try
                    {
                        int pageIdex = StockSeries?.Count ?? 0 / (PageSize == 0 ? 1 : PageSize);
                        var results  = await GetStockCategoryGroupPage(pageIdex, PageSize);
                        foreach (var item in results)
                        {
                            if (StockSeries?.Count(s => s.CategoryName == item.CategoryName) == 0)
                            {
                                StockSeries.Add(item);
                            }
                        }

                        this.TotalAmount = this.StockSeries?.Select(p => p.SubCostAmount).Sum();

                        if (results.Count() == 0 || results.Count() == StockSeries.Count)
                        {
                            ItemTreshold = -1;
                            return(this.StockSeries);
                        }
                    }
                    catch (Exception ex)
                    {
                        Crashes.TrackError(ex);
                        ItemTreshold = -1;
                    }

                    this.StockSeries = new ObservableRangeCollection <StockCategoryGroup>(StockSeries);
                    return(this.StockSeries);
                }
            }, this.WhenAny(x => x.StockSeries, x => x.GetValue().Count > 0));

            //仓库选择
            this.StockSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectStock((data) =>
                {
                    Filter.WareHouseId   = data.Id;
                    Filter.WareHouseName = data.Name;
                    ((ICommand)Load)?.Execute(null);
                }, BillTypeEnum.None);
            });


            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //ZEROSTOCK
                { MenuEnum.ZEROSTOCK, (m, vm) => {
                      ShowZero = true;
                      ((ICommand)Load)?.Execute(null);
                  } },
Esempio n. 17
0
        public CostContractBillPageViewModel(INavigationService navigationService,
                                             IProductService productService,
                                             IUserService userService,
                                             ITerminalService terminalService,
                                             IWareHousesService wareHousesService,
                                             IAccountingService accountingService,
                                             ICostContractService costContractService,
                                             IDialogService dialogService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "费用合同";

            _costContractService = costContractService;
            this.BillType        = BillTypeEnum.CostContractBill;

            InitBill();

            //验证
            var valid_IsReversed         = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited          = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_TerminalId         = this.ValidationRule(x => x.Bill.CustomerId, _isZero, "客户未指定");
            var valid_AccountingOptionId = this.ValidationRule(x => x.Bill.AccountingOptionId, _isZero, "费用类型未指定");
            var valid_ItemCount          = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "合同项目为空,请先添加");


            //编辑
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async x =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return;
                }

                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                if (x != null)
                {
                    var product = ProductSeries.Select(p => p).Where(p => p.ProductId == x.ProductId).FirstOrDefault();
                    if (product != null)
                    {
                        product.UnitId   = x.UnitId ?? 0;
                        product.Quantity = x.TotalQuantity;
                        product.Remark   = x.Remark;
                        product.UnitName = x.UnitName;

                        if (x.BigUnitId > 0)
                        {
                            product.Id                    = x.Id;
                            product.bigOption.Name        = x.UnitName;
                            product.BigPriceUnit.Quantity = x.TotalQuantity;
                            product.BigPriceUnit.Remark   = x.Remark;
                            product.BigPriceUnit.UnitId   = x.BigUnitId ?? 0;
                        }

                        if (x.SmallUnitId > 0)
                        {
                            product.Id                      = x.Id;
                            product.bigOption.Name          = x.UnitName;
                            product.SmallPriceUnit.Quantity = x.TotalQuantity;
                            product.SmallPriceUnit.Remark   = x.Remark;
                            product.SmallPriceUnit.UnitId   = x.SmallUnitId ?? 0;
                        }

                        await this.NavigateAsync("EditAllocationProductPage", ("Product", product));
                    }
                }

                this.Selecter = null;
            }, ex => _dialogService.ShortAlert(ex.ToString()))
            .DisposeWith(DeactivateWith);

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.CostContractSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return Unit.Default;
                    }

                    if (Bill.CustomerId == 0)
                    {
                        Bill.CustomerId = Settings.UserId;
                    }

                    var postData = new CostContractUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        EmployeeId = Settings.UserId,
                        CustomerId = Bill.CustomerId,
                        AccountingOptionId = Bill.AccountingOptionId,
                        Year = DateTime.Now.Year,
                        Month = DateTime.Now.Month,
                        ContractType = 1, //按单位量总计兑付
                        SaleRemark = Bill.SaleRemark,
                        Remark = Bill.Remark,
                        Items = Bill.Items
                    };

                    return await SubmitAsync(postData, Bill.Id, _costContractService.CreateOrUpdateAsync, (result) =>
                    {
                        Bill = new CostContractBillModel();
                    }, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //存储记录
            this.SaveCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!this.Bill.AuditedStatus && this.Bill.CustomerId != 0 && this.Bill.CustomerId != Settings.CostContractBill?.CustomerId)
                {
                    var ok = await _dialogService.ShowConfirmAsync("你是否要保存单据?", "提示", "确定", "取消");
                    if (ok)
                    {
                        if (!this.Bill.AuditedStatus)
                        {
                            Settings.CostContractBill = this.Bill;
                        }
                    }
                }
                await _navigationService.GoBackAsync();
            });

            //费用选择
            this.AccountingSelected = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    this.Alert(valid_TerminalId.Message[0]); return;
                }
                await SelectCostAccounting((data) =>
                {
                    Bill.AccountingOptionId   = data.AccountingOptionId;
                    Bill.AccountingOptionName = data.Name;
                }, BillTypeEnum.CostContractBill);
            });

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    this.Alert(valid_TerminalId.Message[0]); return;
                }
                if (!valid_AccountingOptionId.IsValid)
                {
                    this.Alert(valid_AccountingOptionId.Message[0]); return;
                }
                if (!valid_IsAudited.IsValid)
                {
                    this.Alert(valid_IsAudited.Message[0]); return;
                }
                await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName), ("SerchKey", Filter.SerchKey));
            });

            //审核
            this.AuditingDataCommand = ReactiveCommand.Create <object>(async _ =>
            {
                //是否具有审核权限
                await this.Access(AccessGranularityEnum.CostContractApproved);
                await SubmitAsync(Bill.Id, _costContractService.AuditingAsync, async(result) =>
                {
                    //红冲审核水印
                    this.Bill.AuditedStatus = true;

                    var _conn = App.Resolve <ILiteDbService <MessageInfo> >();
                    var ms    = await _conn.Table.FindByIdAsync(SelecterMessage.Id);
                    if (ms != null)
                    {
                        ms.IsRead = true;
                        await _conn.UpsertAsync(ms);
                    }
                });
            }, this.WhenAny(x => x.Bill.Id, (x) => x.GetValue() > 0));

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //整单备注
                { MenuEnum.REMARK, (m, vm) => {
                      AllRemak((result) => { Bill.Remark = result; }, Bill.Remark);
                  } },
                //清空单据
                { MenuEnum.CLEAR, (m, vm) => {
                      ClearBill <CostContractBillModel, CostContractItemModel>(Bill, DoClear);
                  } },
                //销售备注
                { MenuEnum.SALEREMARK, (m, vm) => {
                      AllRemak((result) => { Bill.SaleRemark = result; }, Bill.SaleRemark);
                  } }
            });
        }
Esempio n. 18
0
        public SelectUserPageViewModel(INavigationService navigationService,
                                       IProductService productService,
                                       ITerminalService terminalService,
                                       IUserService userService,
                                       IWareHousesService wareHousesService,
                                       IAccountingService accountingService,
                                       IDialogService dialogService
                                       ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "选择业务员";
            _navigationService = navigationService;
            _dialogService     = dialogService;
            _terminalService   = terminalService;


            //搜索
            this.WhenAnyValue(x => x.Filter.SerchKey)
            .Where(s => !string.IsNullOrEmpty(s))
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(2), RxApp.MainThreadScheduler)
            .Subscribe(s =>
            {
                ((ICommand)SerchCommand)?.Execute(s);
            }).DisposeWith(DeactivateWith);
            this.SerchCommand = ReactiveCommand.Create <string>(e =>
            {
                if (string.IsNullOrEmpty(Filter.SerchKey))
                {
                    this.Alert("请输入关键字!");
                    return;
                }
                ((ICommand)Load)?.Execute(null);
            });

            this.Load = BusinessVisitLoader.Load(async() =>
            {
                var pending = new List <BusinessVisitList>();
                var result  = await _terminalService.GetAllUserVisitedListAsync(SelectDateTime, this.ForceRefresh, new System.Threading.CancellationToken());
                if (result != null)
                {
                    var lists = result.ToList();
                    int i     = 0;
                    lists.ForEach(u => { u.ColumnIndex = i++; });

                    if (!string.IsNullOrEmpty(Filter.SerchKey))
                    {
                        lists = lists.Where(u => u.BusinessUserName.Contains(Filter.SerchKey)).ToList();
                    }

                    pending = lists;
                }

                if (pending != null && pending.Count > 0)
                {
                    BusinessUsers = new ObservableRangeCollection <BusinessVisitList>(pending);
                }

                return(await Task.FromResult(pending));
            });



            //选择
            this.ItemSelectedCommand = ReactiveCommand.Create <CollectionView>(async e =>
            {
                if (e.SelectedItem != null)
                {
                    await _navigationService.GoBackAsync(("BusinessVisitUser", Selecter));
                }
            });

            this.BindBusyCommand(Load);
        }
        public InventoryOPBillPageViewModel(INavigationService navigationService,
                                            IProductService productService,
                                            IUserService userService,
                                            ITerminalService terminalService,
                                            IWareHousesService wareHousesService,
                                            IAccountingService accountingService,
                                            IInventoryService inventoryService,
                                            IDialogService dialogService
                                            ) : base(navigationService,
                                                     productService,
                                                     terminalService,
                                                     userService,
                                                     wareHousesService,
                                                     accountingService,
                                                     dialogService)
        {
            Title = "盘点单";

            _inventoryService = inventoryService;


            this.BillType = BillTypeEnum.InventoryPartTaskBill;
            this.Bill     = new InventoryPartTaskBillModel()
            {
                BillTypeId      = (int)this.BillType,
                InventoryPerson = Settings.UserId,
                BillNumber      = CommonHelper.GetBillNumber(CommonHelper.GetEnumDescription(BillType).Split(',')[1], Settings.StoreId)
            };

            //验证
            var valid_IsReversed      = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited       = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_WareHouseId     = this.ValidationRule(x => x.Bill.WareHouseId, _isZero, "仓库未指定");
            var valid_InventoryPerson = this.ValidationRule(x => x.Bill.InventoryPerson, _isZero, "盘点人未指定");
            var valid_IsVieweBill     = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_ProductCount    = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");

            //初始化
            this.Load = ReactiveCommand.CreateFromTask(() => Task.Run(async() =>
            {
                var result = await _inventoryService.GetInventoryPartTaskBillAsync(Bill.Id, calToken: new System.Threading.CancellationToken());
                if (result != null)
                {
                    UpdateUI(result);
                }
            }));

            //删除选择
            this.DeleteCommand = ReactiveCommand.Create <object>(e =>
            {
                int productId = (int)e;
                var product   = Bill.Items?.Select(p => p).Where(p => p.ProductId == productId).FirstOrDefault();
                if (product != null)
                {
                    Bill.Items?.Remove(product);
                    var lists  = Bill.Items;
                    Bill.Items = new ObservableCollection <InventoryPartTaskItemModel>(lists);
                }
            });

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_WareHouseId.IsValid)
                {
                    this.Alert(valid_WareHouseId.Message[0]); return;
                }
                if (!valid_InventoryPerson.IsValid)
                {
                    this.Alert(valid_InventoryPerson.Message[0]); return;
                }
                if (!valid_IsVieweBill.IsValid)
                {
                    this.Alert(valid_IsVieweBill.Message[0]); return;
                }

                await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName),
                                         ("WareHouse", WareHouse),
                                         ("Products", ProductSeries.ToList()));
            });


            //选择仓库
            this.StockSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectStock(async(result) =>
                {
                    if (result != null && WareHouse != null && Bill != null)
                    {
                        WareHouse.Id       = result.Id;
                        WareHouse.Name     = result.Column;
                        Bill.WareHouseId   = result.Id;
                        Bill.WareHouseName = result.Column;

                        var pendings = await _inventoryService.CheckInventoryAsync(result.Id, new System.Threading.CancellationToken());
                        if (pendings != null && pendings.Any())
                        {
                            WareHouse.Id       = 0;
                            WareHouse.Name     = "";
                            Bill.WareHouseId   = 0;
                            Bill.WareHouseName = "";
                            this.Alert("库存正在盘点中,不能在生成盘点单!");
                            return;
                        }
                    }
                }, BillTypeEnum.InventoryAllTaskBill);
            });

            //保存盘点
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.InventoryAllSave, async() =>
                {
                    if (Bill.InventoryPerson == 0)
                    {
                        this.Alert("盘点人未指定!"); return Unit.Default;
                    }
                    if (Bill.WareHouseId == 0)
                    {
                        this.Alert("仓库未指定!"); return Unit.Default;
                    }
                    if (Bill.Items?.Count == 0)
                    {
                        this.Alert("请添加商品项目!"); return Unit.Default;
                    }

                    var postMData = new InventoryPartTaskUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        InventoryPerson = Bill.InventoryPerson,
                        WareHouseId = Bill.WareHouseId,
                        InventoryDate = DateTime.Now,
                        Items = Bill.Items
                    };

                    var confirm = await _dialogService.ShowConfirmAsync("确认保存盘点吗?", okText: "确定", cancelText: "取消");
                    if (confirm)
                    {
                        return await SubmitAsync(postMData, Bill.Id, _inventoryService.CreateOrUpdateAsync, (result) =>
                        {
                            Bill.Id = result.Return;
                            Bill.InventoryPerson = postMData.InventoryPerson;
                            Bill.WareHouseId = postMData.WareHouseId;
                        }, false, token: new System.Threading.CancellationToken());
                    }
                    else
                    {
                        return Unit.Default;
                    }
                }));
            },
                                                                                   this.IsValid());

            //放弃盘点
            this.CancelCommand = ReactiveCommand.CreateFromTask <object>(async e =>
            {
                if (Bill.Id == 0)
                {
                    this.Alert("操作失败,你需要先保存盘点!");
                    return;
                }

                if (Bill.InventoryPerson == 0)
                {
                    this.Alert("盘点人未指定!"); return;
                }
                if (Bill.WareHouseId == 0)
                {
                    this.Alert("仓库未指定!"); return;
                }
                if (Bill.Items?.Count == 0)
                {
                    this.Alert("请添加商品项目!"); return;
                }

                var confirm = await _dialogService.ShowConfirmAsync("确认放弃盘点吗?", okText: "确定", cancelText: "取消");
                if (confirm)
                {
                    await _inventoryService.CancelTakeInventoryAsync(Bill.Id, new System.Threading.CancellationToken());
                }
            });

            //完成确认
            this.CompletedCommand = ReactiveCommand.CreateFromTask <object>(async e =>
            {
                if (Bill.Id == 0)
                {
                    this.Alert("操作失败,你需要先保存盘点!");
                    return;
                }

                if (Bill.InventoryPerson == 0)
                {
                    this.Alert("盘点人未指定!"); return;
                }
                if (Bill.WareHouseId == 0)
                {
                    this.Alert("仓库未指定!"); return;
                }
                if (Bill.Items?.Count == 0)
                {
                    this.Alert("请添加商品项目!"); return;
                }

                var confirm = await _dialogService.ShowConfirmAsync("确认完成盘点吗?", okText: "确定", cancelText: "取消");
                if (confirm)
                {
                    if (Bill.InventoryPerson == 0)
                    {
                        this.Alert("盘点人未指定!"); return;
                    }
                    if (Bill.WareHouseId == 0)
                    {
                        this.Alert("仓库未指定!"); return;
                    }
                    if (Bill.Items?.Count == 0)
                    {
                        this.Alert("请添加商品项目!"); return;
                    }
                    var result = await _inventoryService.SetInventoryCompletedAsync(Bill.Id, new System.Threading.CancellationToken());
                    if (!result)
                    {
                        this.Alert("抱歉,系统错误,请反馈技术支持!");
                    }
                }
            });

            //编辑商品
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                if (this.Bill.IsSubmitBill)
                {
                    _dialogService.ShortAlert("已提交的单据不能编辑");
                    return;
                }

                if (item != null)
                {
                    List <ProductModel> products = null;
                    var product = new ProductModel()
                    {
                        Name         = item.ProductName,
                        ProductName  = item.ProductName,
                        ProductId    = item.ProductId,
                        BigPriceUnit = new PriceUnit()
                        {
                            UnitId = item.BigUnitId ?? 0, Quantity = item.BigQuantity ?? 0, UnitName = item.bigOption.Name
                        },
                        SmallPriceUnit = new PriceUnit()
                        {
                            UnitId = item.SmallUnitId, Quantity = item.SmallUnitQuantity ?? 0, UnitName = item.smallOption.Name
                        },
                        StockQty       = item.StockQty,
                        UnitConversion = item.UnitConversion
                    };
                    products.Add(product);

                    await this.NavigateAsync("AddInventoryProductPage",
                                             ("Reference", this.PageName),
                                             ("WareHouse", WareHouse),
                                             ("Products", products));
                }
            })
            .DisposeWith(DeactivateWith);

            //扫码商品
            this.ScanBarCommand = ReactiveCommand.Create <object>(async e => await this.NavigateAsync("ScanBarcodePage", ("action", "add")));

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //全部
                { Enums.MenuEnum.ALL, (m, vm) => {
                      var lists  = Bill.Items?.ToList();
                      Bill.Items = new ObservableCollection <InventoryPartTaskItemModel>(lists);
                  } },
                //未盘点
                { MenuEnum.WART, (m, vm) => {
                      var lists  = Bill.Items?.Where(s => string.IsNullOrEmpty(s.StatusName)).ToList();
                      Bill.Items = new ObservableCollection <InventoryPartTaskItemModel>(lists);
                  } },
                //已盘点
                { MenuEnum.YPD, (m, vm) => {
                      var lists  = Bill.Items?.Where(s => !string.IsNullOrEmpty(s.StatusName)).ToList();
                      Bill.Items = new ObservableCollection <InventoryPartTaskItemModel>(lists);
                  } },
                //整单备注
                { MenuEnum.REMARK, (m, vm) => {
                      AllRemak((result) =>
                        {
                            Bill.Remark = result;
                        }, Bill.Remark);
                  } },
                //历史单据
                { MenuEnum.HISTORY, async(m, vm) => {
                      await SelectHistory();
                  } }
            });



            this.BindBusyCommand(Load);
        }
Esempio n. 20
0
        public ReconciliationDetailPageViewModel(INavigationService navigationService,
                                                 IProductService productService,
                                                 IUserService userService,
                                                 ITerminalService terminalService,
                                                 IWareHousesService wareHousesService,
                                                 IAccountingService accountingService,
                                                 IFinanceReceiveAccountService financeReceiveAccountService,
                                                 IDialogService dialogService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "单据信息";

            _financeReceiveAccountService = financeReceiveAccountService;

            //选择单据
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async x =>
            {
                switch (x.BillType)
                {
                case (int)BillTypeEnum.SaleBill:
                    await this.NavigateAsync("SaleBillPage", ("BillId", x.BillId));
                    break;

                case (int)BillTypeEnum.ReturnBill:
                    await this.NavigateAsync("ReturnBillPage", ("BillId", x.BillId));
                    break;

                case (int)BillTypeEnum.CashReceiptBill:
                    await this.NavigateAsync("CashReceiptBillPage", ("BillId", x.BillId));
                    break;

                case (int)BillTypeEnum.AdvanceReceiptBill:
                    await this.NavigateAsync("AdvanceReceiptBillPage", ("BillId", x.BillId));
                    break;

                case (int)BillTypeEnum.CostExpenditureBill:
                    await this.NavigateAsync("CostExpenditureBillPage", ("BillId", x.BillId));
                    break;

                default:
                    break;
                }
                Selecter = null;
            }).DisposeWith(DeactivateWith);

            //选择业务员
            this.WhenAnyValue(x => x.Filter.BusinessUserId)
            .Skip(1)
            .Where(x => x > 0)
            .Subscribe(x =>
            {
                var fillter = this.TempBills.Where(s => s.UserId == x).ToList();
                this.Bills  = new ObservableCollection <FinanceReceiveAccountBillModel>(fillter);
            });

            //全选
            this.WhenAnyValue(x => x.SelectedAll)
            .Subscribe(x =>
            {
                foreach (var b in this.Bills)
                {
                    b.Selected = x;
                }
                CalcSum();
                var count        = this.Bills.Where(s => s.Selected).Count();
                this.ConfirmText = $"确认上交({count})";
            });

            //打印单据
            this.PrintCommand = ReactiveCommand.Create(() =>
            {
                Alert("请选择单据!");
            });


            //上交对账单
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async(e) =>
            {
                var bills = this.Bills.Where(s => s.Selected == true).ToList();
                if (bills.Count == 0)
                {
                    Alert("请选择单据!");
                    return(Unit.Default);
                }

                var postData = new FinanceReceiveAccountBillSubmitModel()
                {
                    Items = bills
                };

                return(await SubmitAsync(postData, 0, _financeReceiveAccountService.SubmitAccountStatementAsync, (result) =>
                {
                    //移除当前
                    bills.ForEach(b =>
                    {
                        this.Bills.Remove(b);
                    });
                }));
            });
        }
Esempio n. 21
0
        public ExchangeBillPageViewModel(INavigationService navigationService,
                                         IExchangeBillService exchangeBillService,
                                         IProductService productService,
                                         IUserService userService,
                                         ITerminalService terminalService,
                                         IWareHousesService wareHousesService,
                                         IAccountingService accountingService,
                                         IMicrophoneService microphoneService,
                                         ISaleBillService saleBillService,
                                         //IMapper mapper,
                                         IDialogService dialogService
                                         ) : base(navigationService,
                                                  productService, terminalService,
                                                  userService, wareHousesService,
                                                  accountingService, dialogService)
        {
            Title = "换货单";

            _saleBillService     = saleBillService;
            _exchangeBillService = exchangeBillService;
            _microphoneService   = microphoneService;
            //_mapper = mapper;

            InitBill();

            #region //配送日期指定
            var weekDays  = new List <WeekDay>();
            var startTime = DateTime.Now;
            var endTime   = DateTime.Now.AddDays(7);
            while (endTime.Subtract(startTime).Days > 0)
            {
                var wd = new WeekDay
                {
                    Wname           = $"{startTime:MM-dd} - {GlobalSettings.GetWeek(startTime.DayOfWeek.ToString())}",
                    Date            = startTime,
                    AMTimeRange     = $"09:00-12:00",
                    PMTimeRange     = $"15:00-21:00",
                    SelectedCommand = ReactiveCommand.Create <WeekDay>(r =>
                    {
                        this.WeekDays.ForEach(s => { s.Selected = false; });
                        r.Selected       = !r.Selected;
                        this.DeliverDate = r;
                        this.AMTimeRange = r.AMTimeRange;
                        this.PMTimeRange = r.PMTimeRange;
                    })
                };
                weekDays.Add(wd);
                startTime = startTime.AddDays(1);
            }
            var defaultWd = weekDays.FirstOrDefault();
            if (defaultWd != null)
            {
                defaultWd.Selected = true;
                this.AMTimeRange   = defaultWd.AMTimeRange;
                this.PMTimeRange   = defaultWd.PMTimeRange;
            }
            this.WeekDays = new ObservableCollection <WeekDay>(weekDays);

            #endregion

            //验证
            var valid_IsReversed     = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited      = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_TerminalId     = this.ValidationRule(x => x.Bill.TerminalId, _isZero, "客户未指定");
            var valid_BusinessUserId = this.ValidationRule(x => x.Bill.DeliveryUserId, _isZero, "配送员未指定");
            var valid_WareHouseId    = this.ValidationRule(x => x.Bill.WareHouseId, _isZero, "仓库未指定");
            var valid_ProductCount   = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (this.Bill.AuditedStatus && !this.ReferencePage.Equals("UnDeliveryPage"))
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                if (!valid_TerminalId.IsValid)
                {
                    _dialogService.ShortAlert(valid_TerminalId.Message[0]);
                    ((ICommand)CustomSelected)?.Execute(null);
                    return;
                }

                if (!valid_WareHouseId.IsValid)
                {
                    _dialogService.ShortAlert(valid_WareHouseId.Message[0]);
                    ((ICommand)StockSelected)?.Execute(null);
                    return;
                }

                if (!valid_BusinessUserId.IsValid)
                {
                    _dialogService.ShortAlert(valid_BusinessUserId.Message[0]);
                    ((ICommand)DeliverSelected)?.Execute(null);
                    return;
                }

                //转向商品选择
                await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName),
                                         ("WareHouse", WareHouse),
                                         ("TerminalId", Bill.TerminalId),
                                         ("Terminaler", this.Terminal),
                                         ("SerchKey", Filter.SerchKey));
            });

            //编辑商品
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return;
                }

                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                if (this.Bill.IsSubmitBill)
                {
                    _dialogService.ShortAlert("已提交的单据不能编辑");
                    return;
                }

                if (item != null)
                {
                    var product = ProductSeries.Select(p => p).Where(p => p.Id == item.ProductId).FirstOrDefault();
                    if (product != null)
                    {
                        product.UnitId   = item.UnitId;
                        product.Quantity = item.Quantity;
                        product.Price    = item.Price;
                        product.Amount   = item.Amount;
                        product.Remark   = item.Remark;
                        product.Subtotal = item.Subtotal;
                        product.UnitName = item.UnitName;

                        if (item.BigUnitId > 0)
                        {
                            product.bigOption.Name        = item.UnitName;
                            product.BigPriceUnit.Quantity = item.Quantity;
                            product.BigPriceUnit.UnitId   = item.BigUnitId;
                            product.BigPriceUnit.Amount   = item.Amount;
                            product.BigPriceUnit.Remark   = item.Remark;
                        }

                        if (item.SmallUnitId > 0)
                        {
                            product.bigOption.Name          = item.UnitName;
                            product.SmallPriceUnit.Quantity = item.Quantity;
                            product.SmallPriceUnit.UnitId   = item.SmallUnitId;
                            product.SmallPriceUnit.Amount   = item.Amount;
                            product.SmallPriceUnit.Remark   = item.Remark;
                        }

                        await this.NavigateAsync("EditProductPage", ("Product", product), ("Reference", PageName), ("Item", item), ("WareHouse", WareHouse));
                    }
                }

                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);

            //提交表单
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.ExchangeBillsSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    if (this.Bill.AuditedStatus || DispatchItem != null)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return Unit.Default;
                    }

                    //结算方式
                    Bill.PayTypeId = 0;
                    Bill.PayTypeName = "";

                    if (Bill.BusinessUserId == 0)
                    {
                        Bill.BusinessUserId = Settings.UserId;
                    }

                    var postMData = new ExchangeBillUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        //客户
                        TerminalId = Bill.TerminalId,
                        //业务员
                        BusinessUserId = Bill.BusinessUserId,
                        //送货员
                        DeliveryUserId = Bill.DeliveryUserId,
                        //仓库
                        WareHouseId = Bill.WareHouseId,
                        //交易日期
                        TransactionDate = DateTime.Now,
                        //默认售价方式
                        DefaultAmountId = Settings.DefaultPricePlan,
                        //备注
                        Remark = Bill.Remark,
                        //优惠金额
                        PreferentialAmount = 0,
                        //优惠后金额
                        PreferentialEndAmount = 0,
                        //欠款金额
                        OweCash = 0,
                        //商品项目
                        Items = Bill.Items,
                        //收款账户
                        //预收款
                        AdvanceAmount = 0,
                        //预收款余额
                        AdvanceAmountBalance = 0,
                        //配送时间
                        DeliverDate = this.DeliverDate?.Date ?? DateTime.Now,
                        AMTimeRange = this.DeliverDate?.AMTimeRange,
                        PMTimeRange = this.DeliverDate?.PMTimeRange
                    };


                    return await SubmitAsync(postMData, Bill.Id, _exchangeBillService.CreateOrUpdateAsync, async(result) =>
                    {
                        BillId = result.Code;
                        //清空单据
                        Bill = new ExchangeBillModel();


                        if (IsVisit) //拜访时开单
                        {
                            //转向拜访界面
                            await this.NavigateAsync("VisitStorePage", ("BillTypeId", BillTypeEnum.ExchangeBill),
                                                     ("BillId", BillId),
                                                     ("Amount", Bill.SumAmount));
                        }
                    }, !IsVisit, token: new System.Threading.CancellationToken());
                }));
            },
Esempio n. 22
0
        public AllocationBillPageViewModel(INavigationService navigationService,
                                           IProductService productService,
                                           IUserService userService,
                                           ITerminalService terminalService,
                                           IWareHousesService wareHousesService,
                                           IAccountingService accountingService,
                                           IDialogService dialogService,
                                           IMicrophoneService microphoneService
                                           ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "调拨单";
            _microphoneService = microphoneService;

            InitBill();

            //验证
            var valid_IsReversed          = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited           = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_ShipmentWareHouseId = this.ValidationRule(x => x.Bill.ShipmentWareHouseId, _isZero, "出货仓库未指定");
            var valid_IncomeWareHouseId   = this.ValidationRule(x => x.Bill.IncomeWareHouseId, _isZero, "入货仓库未指定");
            var valid_ProductCount        = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                try
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作"); return;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作!"); return;
                    }

                    if (!valid_ShipmentWareHouseId.IsValid)
                    {
                        _dialogService.ShortAlert(valid_ShipmentWareHouseId.Message[0]);
                        return;
                    }

                    if (!valid_IncomeWareHouseId.IsValid)
                    {
                        _dialogService.ShortAlert(valid_IncomeWareHouseId.Message[0]);
                        return;
                    }

                    if (Bill.ShipmentWareHouseId == Bill.IncomeWareHouseId)
                    {
                        _dialogService.ShortAlert("出入库不能相同!");
                        return;
                    }

                    //传入当前主库
                    this.WareHouse.Id   = Bill.ShipmentWareHouseId;
                    this.WareHouse.Name = Bill.ShipmentWareHouseName;

                    this.Filter.WareHouseId   = Bill.ShipmentWareHouseId;
                    this.Filter.WareHouseName = Bill.ShipmentWareHouseName;

                    //ShipmentWareHouseId
                    //IncomeWareHouseId

                    await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName),
                                             ("Bill", Bill),
                                             ("Filter", Filter),
                                             ("WareHouse", WareHouse),
                                             ("SerchKey", Filter.SerchKey));
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });

            //编辑商品
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                try
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return;
                    }

                    if (this.Bill.IsSubmitBill)
                    {
                        _dialogService.ShortAlert("已提交的单据不能编辑");
                        return;
                    }

                    if (item != null)
                    {
                        var product = ProductSeries.Select(p => p).Where(p => p.Id == item.ProductId).FirstOrDefault();
                        if (product != null)
                        {
                            product.UnitId   = item.UnitId;
                            product.Quantity = item.Quantity;
                            product.Remark   = item.Remark;
                            product.Subtotal = item.Subtotal;
                            product.UnitName = item.UnitName;
                            product.GUID     = item.GUID;
                            if (item.BigUnitId > 0)
                            {
                                product.bigOption.Name        = item.UnitName;
                                product.BigPriceUnit.Quantity = item.Quantity;
                                product.BigPriceUnit.UnitId   = item.BigUnitId ?? 0;
                                product.BigPriceUnit.Remark   = item.Remark;
                            }

                            if (item.SmallUnitId > 0)
                            {
                                product.bigOption.Name          = item.UnitName;
                                product.SmallPriceUnit.Quantity = item.Quantity;
                                product.SmallPriceUnit.UnitId   = item.SmallUnitId;
                                product.SmallPriceUnit.Remark   = item.Remark;
                            }

                            await this.NavigateAsync("EditAllocationProductPage", ("Product", product));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }

                this.Selecter = null;
            }, ex => _dialogService.ShortAlert(ex.ToString()))
            .DisposeWith(DeactivateWith);

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.AllocationFormSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return Unit.Default;
                    }

                    if (!valid_ShipmentWareHouseId.IsValid)
                    {
                        this.Alert(valid_ShipmentWareHouseId.Message[0]); return Unit.Default;
                    }
                    if (!valid_IncomeWareHouseId.IsValid)
                    {
                        this.Alert(valid_IncomeWareHouseId.Message[0]); return Unit.Default;
                    }
                    if (!valid_ProductCount.IsValid)
                    {
                        this.Alert(valid_ProductCount.Message[0]); return Unit.Default;
                    }

                    var zero = Bill.Items?.Where(s => s.Quantity == 0).Count() > 0;
                    if (zero)
                    {
                        this.Alert("存在数量为空的调拨商品!");
                        return Unit.Default;
                    }

                    var postMData = new AllocationUpdateModel()
                    {
                        BillNumber = Bill.BillNumber,
                        ShipmentWareHouseId = Bill.ShipmentWareHouseId,
                        IncomeWareHouseId = Bill.IncomeWareHouseId,
                        CreatedOnUtc = Bill.CreatedOnUtc,
                        AllocationByMinUnit = false,
                        Remark = Bill.Remark,
                        //商品项目
                        Items = Bill.Items?.ToList(),
                    };

                    ShowPrintBtn = true;
                    if (IsNeedShowPrompt)
                    {
                        var ok = await _dialogService.ShowConfirmAsync("是否保存并提交吗?", "", "确定", "取消");
                        if (!ok)
                        {
                            return Unit.Default;
                        }
                    }
                    IsNeedShowPrompt = true;

                    var gr = Bill.AuditedStatus;
                    return await SubmitAsync(postMData, Bill.Id, _wareHousesService.CreateOrUpdateAllocationbillAsync, async(result) =>
                    {
                        if (IsNeedPrint)
                        {
                            Bill.BillType = BillTypeEnum.AllocationBill;
                            await SelectPrint((AllocationBillModel)Bill.Clone());
                        }
                        IsNeedPrint = false;
                        Bill = new AllocationBillModel();
                        InitBill();
                    }, gr, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //存储记录
            this.SaveCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!this.Bill.AuditedStatus && this.Bill.ShipmentWareHouseId != 0 && this.Bill.ShipmentWareHouseId != Settings.AllocationBill?.ShipmentWareHouseId)
                {
                    var ok = await _dialogService.ShowConfirmAsync("你是否要保存单据?", "提示", "确定", "取消");
                    if (ok)
                    {
                        if (!this.Bill.AuditedStatus)
                        {
                            Settings.AllocationBill = this.Bill;
                        }
                    }
                }
                await _navigationService.GoBackAsync();
            });

            //审核
            this.AuditingDataCommand = ReactiveCommand.CreateFromTask <object>(async _ =>
            {
                //是否具有审核权限
                await this.Access(AccessGranularityEnum.AllocationFormApproved);
                await SubmitAsync(Bill.Id, _wareHousesService.AuditingAsync, async(result) =>
                {
                    //红冲审核水印
                    this.Bill.AuditedStatus = true;

                    var _conn = App.Resolve <ILiteDbService <MessageInfo> >();
                    var ms    = await _conn.Table.FindByIdAsync(SelecterMessage.Id);
                    if (ms != null)
                    {
                        ms.IsRead = true;
                        await _conn.UpsertAsync(ms);
                    }
                }, token: new System.Threading.CancellationToken());
            }, this.WhenAny(x => x.Bill.Id, (x) => x.GetValue() > 0));


            //启用麦克风
            this.WhenAnyValue(x => x.EnableMicrophone)
            .Subscribe(async x =>
            {
                var micAccessGranted = await _microphoneService.GetPermissionsAsync();
                if (!micAccessGranted)
                {
                    this.Alert("请打开麦克风");
                }
            })
            .DisposeWith(this.DeactivateWith);
            //匹配声音
            this.RecognitionCommand = ReactiveCommand.Create(() =>
            {
                RecognitionSpeech((key) =>
                {
                    Filter.SerchKey = key;
                    ((ICommand)this.AddProductCommand)?.Execute(null);
                });
            });
            //切换语音助手
            this.SpeechCommand = ReactiveCommand.Create(() =>
            {
                if (IsFooterVisible)
                {
                    IsVisible       = true;
                    IsExpanded      = true;
                    IsFooterVisible = false;
                }
                else
                {
                    IsVisible       = false;
                    IsExpanded      = false;
                    IsFooterVisible = true;
                }
            });


            //工具栏打印
            this.PrintCommand = ReactiveCommand.Create(async() =>
            {
                await Print();
            });

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //整单备注
                { MenuEnum.REMARK, (m, vm) => {
                      AllRemak((result) =>
                        {
                            Bill.Remark = result;
                        }, Bill.Remark);
                  } },
Esempio n. 23
0
        public InventoryReportPageViewModel(INavigationService navigationService,
                                            IProductService productService,
                                            ITerminalService terminalService,
                                            IUserService userService,
                                            IWareHousesService wareHousesService,
                                            IAccountingService accountingService,
                                            IDialogService dialogService
                                            ) : base(navigationService,
                                                     productService,
                                                     terminalService,
                                                     userService,
                                                     wareHousesService,
                                                     accountingService,
                                                     dialogService)
        {
            Title = "库存上报";

            this.Bill = new InventoryReportBillModel()
            {
                BusinessUserId = Settings.UserId,
                BillNumber     = CommonHelper.GetBillNumber("KCSB", Settings.StoreId),
                CreatedOnUtc   = DateTime.Now
            };

            //编辑项目
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                await this.NavigateAsync("AddReportProductPage", ("InventoryReportItemModel", item));
                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (Bill.TerminalId == 0)
                {
                    _dialogService.ShortAlert("请选择客户!");
                    return;
                }
                await this.NavigateAsync("SelectProductPage", ("Reference", $"{nameof(InventoryReportPage)}"), ("SerchKey", Filter.SerchKey));
            });

            //验证
            var valid_TerminalId     = this.ValidationRule(x => x.Bill.TerminalId, _isZero, "客户未指定");
            var valid_BusinessUserId = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "商品未指定");


            //提交
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                //await this.Access(AccessGranularityEnum.StockReportSave);
                return(await this.Access(AccessGranularityEnum.StockReportSave, async() =>
                {
                    Bill.StoreId = Settings.StoreId;
                    Bill.BusinessUserId = Settings.UserId;
                    Bill.ReversedUserId = 0;
                    Bill.ReversedStatus = false;

                    return await SubmitAsync(Bill, 0, _wareHousesService.CreateOrUpdateAsync, (result) =>
                    {
                        Bill = new InventoryReportBillModel();
                    }, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                { MenuEnum.CLEAR, (m, vm) => {
                      ClearForm(() =>
                        {
                            Bill.Items?.Clear();
                        });
                  } },
            });
        }
Esempio n. 24
0
        public SaleDetailPageViewModel(INavigationService navigationService,
                                       IReceiptCashService receiptCashService,
                                       IDialogService dialogService,
                                       IProductService productService,
                                       IUserService userService,
                                       ITerminalService terminalService,
                                       IWareHousesService wareHousesService,
                                       IAccountingService accountingService,
                                       IReportingService reportingService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "商品销售明细";


            this.Load = ReactiveCommand.CreateFromTask(async() =>
            {
                if (!string.IsNullOrEmpty(ProductName))
                {
                    Title = $"{ProductName}-明细";
                }

                //重载时排它
                ItemTreshold = 1;

                try
                {
                    this.Bills?.Clear();
                    PageCounter = 0;

                    var rankings       = new List <SaleReportItem>();
                    int?productId      = ProductId;
                    int?businessUserId = Filter.BusinessUserId;
                    DateTime?startTime = Filter.StartTime ?? DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
                    DateTime?endTime   = Filter.EndTime ?? DateTime.Now;

                    var result = await reportingService.GetHotSaleReportItemAsync(productId,
                                                                                  businessUserId,
                                                                                  startTime.Value,
                                                                                  endTime.Value,
                                                                                  this.ForceRefresh,
                                                                                  0,
                                                                                  new System.Threading.CancellationToken());

                    if (result != null)
                    {
                        foreach (var item in result)
                        {
                            this.Bills.Add(item);
                        }

                        if (this.Bills.Any())
                        {
                            this.Bills = new ObservableRangeCollection <SaleReportItem>(Bills);
                        }
                    }

                    UpdateUI();
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });


            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                if (ItemTreshold == -1)
                {
                    return;
                }

                int pageIdex = 0;

                var p = Bills.Count;

                if (this.Bills?.Count != 0)
                {
                    pageIdex = Bills.Count / 30;
                }

                if (PageCounter < pageIdex)
                {
                    PageCounter = pageIdex;
                    using (var dig = UserDialogs.Instance.Loading("加载中..."))
                    {
                        try
                        {
                            var rankings       = new List <SaleReportItem>();
                            int?productId      = ProductId;
                            int?businessUserId = Filter.BusinessUserId;
                            DateTime?startTime = Filter.StartTime ?? DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01 00:00:00"));
                            DateTime?endTime   = Filter.EndTime ?? DateTime.Now;

                            var result = await reportingService.GetHotSaleReportItemAsync(productId,
                                                                                          businessUserId,
                                                                                          startTime.Value,
                                                                                          endTime.Value,
                                                                                          this.ForceRefresh,
                                                                                          pageIdex,
                                                                                          new System.Threading.CancellationToken());

                            if (result != null && result.Any())
                            {
                                foreach (var item in result)
                                {
                                    Bills.Add(item);
                                }
                            }
                            else
                            {
                                ItemTreshold = -1;
                            }
                        }
                        catch (Exception ex)
                        {
                            Crashes.TrackError(ex);
                            ItemTreshold = -1;
                        }
                    }
                }
            }, this.WhenAny(x => x.Bills, x => x.GetValue().Count > 0));


            this.BindBusyCommand(Load);
        }
Esempio n. 25
0
        public SelectContractPageViewModel(INavigationService navigationService,
                                           IProductService productService,
                                           ITerminalService terminalService,
                                           IUserService userService,
                                           IWareHousesService wareHousesService,
                                           IAccountingService accountingService,
                                           ICostContractService costContractService,
                                           IDialogService dialogService
                                           ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "选择费用合同";

            _costContractService = costContractService;

            this.Load = CostContractLoader.Load(async() =>
            {
                //重载时排它
                ItemTreshold = 1;
                try
                {
                    //清除列表
                    CostContracts.Clear();

                    var items = await GetDataPages(0, PageSize);
                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            if (CostContracts.Count(s => (s.BillNumber == item.BillNumber) && (s.Month == item.Month)) == 0)
                            {
                                CostContracts.Add(item);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }

                this.CostContracts = new ObservableRangeCollection <CostContractBindingModel>(CostContracts);
                return(CostContracts);
            });

            //以增量方式加载数据
            this.ItemTresholdReachedCommand = ReactiveCommand.Create(async() =>
            {
                using (var dig = UserDialogs.Instance.Loading("加载中..."))
                {
                    try
                    {
                        int pageIdex         = CostContracts.Count / (PageSize == 0 ? 1 : PageSize);
                        var items            = await GetDataPages(pageIdex, PageSize);
                        var previousLastItem = Terminals.Last();
                        if (items != null)
                        {
                            foreach (var item in items)
                            {
                                if (CostContracts.Count(s => (s.BillNumber == item.BillNumber) && (s.Month == item.Month)) == 0)
                                {
                                    CostContracts.Add(item);
                                }
                            }

                            if (items.Count() == 0 || items.Count() == CostContracts.Count)
                            {
                                ItemTreshold = -1;
                                return(this.CostContracts);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Crashes.TrackError(ex);
                        ItemTreshold = -1;
                    }


                    this.CostContracts = new ObservableRangeCollection <CostContractBindingModel>(CostContracts);
                    return(this.CostContracts);
                }
            });

            //选择
            this.ItemSelectedCommand = ReactiveCommand.Create <CollectionView>(async e =>
            {
                if (e.SelectedItem != null)
                {
                    Selecter.AccountingOptionId   = this.Accounting.AccountingOptionId;
                    Selecter.AccountingOptionName = this.Accounting.AccountingOptionName;
                    await _navigationService.GoBackAsync(("CostContract", Selecter));
                }
            });

            this.BindBusyCommand(Load);
        }
Esempio n. 26
0
        public SystemSettingPageViewModel(INavigationService navigationService,
                                          IProductService productService,
                                          IUserService userService,
                                          ITerminalService terminalService,
                                          IWareHousesService wareHousesService,
                                          IAccountingService accountingService,
                                          ILiteDbService <TerminalModel> tliteDb,
                                          IDialogService dialogService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "系统设置";

            _tliteDb = tliteDb;

            this.Load = ReactiveCommand.CreateFromTask(() => Task.Run(() =>
            {
                try
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        //初始
                        this.SaleBill              = Settings.SaleBill ?? new SaleBillModel();
                        this.SaleReservationBill   = Settings.SaleReservationBill ?? new SaleReservationBillModel();
                        this.ReturnBill            = Settings.ReturnBill ?? new ReturnBillModel();
                        this.ReturnReservationBill = Settings.ReturnReservationBill ?? new ReturnReservationBillModel();
                        this.ExchangeBill          = Settings.ExchangeBill ?? new ExchangeBillModel();

                        this.AllocationBill        = Settings.AllocationBill ?? new AllocationBillModel();
                        this.CashReceiptBill       = Settings.CashReceiptBill ?? new CashReceiptBillModel();
                        this.PurchaseBill          = Settings.PurchaseBill ?? new PurchaseBillModel();
                        this.InventoryPartTaskBill = Settings.InventoryPartTaskBill ?? new InventoryPartTaskBillModel();
                        this.CostExpenditureBill   = Settings.CostExpenditureBill ?? new CostExpenditureBillModel();
                        this.CostContractBill      = Settings.CostContractBill ?? new CostContractBillModel();
                        this.AdvanceReceiptBill    = Settings.AdvanceReceiptBill ?? new AdvanceReceiptBillModel();


                        this.SaleBill.BillTypeName = "销售单";
                        this.SaleBill.BillType     = BillTypeEnum.SaleBill;
                        this.SaleBill.BillTypeId   = (int)BillTypeEnum.SaleBill;
                        this.SaleBill.Navigation   = "SaleBillPage";

                        this.SaleReservationBill.BillTypeName = "销售订单";
                        this.SaleReservationBill.BillType     = BillTypeEnum.SaleReservationBill;
                        this.SaleReservationBill.BillTypeId   = (int)BillTypeEnum.SaleReservationBill;
                        this.SaleReservationBill.Navigation   = "SaleOrderBillPage";

                        this.ReturnBill.BillTypeName = "退货单";
                        this.ReturnBill.BillType     = BillTypeEnum.ReturnBill;
                        this.ReturnBill.BillTypeId   = (int)BillTypeEnum.ReturnBill;
                        this.ReturnBill.Navigation   = "ReturnBillPage";

                        this.ReturnReservationBill.BillTypeName = "退货订单";
                        this.ReturnReservationBill.BillType     = BillTypeEnum.ReturnReservationBill;
                        this.ReturnReservationBill.BillTypeId   = (int)BillTypeEnum.ReturnReservationBill;
                        this.ReturnReservationBill.Navigation   = "ReturnOrderBillPage";

                        this.ExchangeBill.BillTypeName = "换货单";
                        this.ExchangeBill.BillType     = BillTypeEnum.ExchangeBill;
                        this.ExchangeBill.BillTypeId   = (int)BillTypeEnum.ExchangeBill;
                        this.ExchangeBill.Navigation   = "ExchangeBillPage";

                        this.AllocationBill.BillTypeName = "调拨单";
                        this.AllocationBill.BillType     = BillTypeEnum.AllocationBill;
                        this.AllocationBill.BillTypeId   = (int)BillTypeEnum.AllocationBill;
                        this.AllocationBill.Navigation   = "AllocationBillPage";

                        this.CashReceiptBill.BillTypeName = "收款单";
                        this.CashReceiptBill.BillType     = BillTypeEnum.CashReceiptBill;
                        this.CashReceiptBill.BillTypeId   = (int)BillTypeEnum.CashReceiptBill;
                        this.CashReceiptBill.Navigation   = "ReceiptBillPage";

                        this.PurchaseBill.BillTypeName = "采购单";
                        this.PurchaseBill.BillType     = BillTypeEnum.PurchaseBill;
                        this.PurchaseBill.BillTypeId   = (int)BillTypeEnum.PurchaseBill;
                        this.PurchaseBill.Navigation   = "PurchaseOrderBillPage";

                        this.InventoryPartTaskBill.BillTypeName = "盘点单";
                        this.InventoryPartTaskBill.BillType     = BillTypeEnum.InventoryPartTaskBill;
                        this.InventoryPartTaskBill.BillTypeId   = (int)BillTypeEnum.InventoryPartTaskBill;
                        this.InventoryPartTaskBill.Navigation   = "InventoryOPBillPage";

                        this.CostExpenditureBill.BillTypeName = "费用支付单";
                        this.CostExpenditureBill.BillType     = BillTypeEnum.CostExpenditureBill;
                        this.CostExpenditureBill.BillTypeId   = (int)BillTypeEnum.CostExpenditureBill;
                        this.CostExpenditureBill.Navigation   = "CostExpenditureBillPage";

                        this.CostContractBill.BillTypeName = "费用合同单";
                        this.CostContractBill.BillType     = BillTypeEnum.CostContractBill;
                        this.CostContractBill.BillTypeId   = (int)BillTypeEnum.CostContractBill;
                        this.CostContractBill.Navigation   = "CostContractBillPage";

                        this.AdvanceReceiptBill.BillTypeName = "预收款单";
                        this.AdvanceReceiptBill.BillType     = BillTypeEnum.AdvanceReceiptBill;
                        this.AdvanceReceiptBill.BillTypeId   = (int)BillTypeEnum.AdvanceReceiptBill;
                        this.AdvanceReceiptBill.Navigation   = "AdvanceReceiptBillPage";


                        this.PrintModules = new ObservableCollection <AbstractBill>()
                        {
                            this.SaleBill,
                            this.SaleReservationBill,
                            this.ReturnBill,
                            this.ReturnReservationBill,
                            this.ExchangeBill,
                            this.AllocationBill,
                            this.CashReceiptBill,
                            this.PurchaseBill,
                            this.InventoryPartTaskBill,
                            this.CostExpenditureBill,
                            this.CostContractBill,
                            this.AdvanceReceiptBill
                        };
                    });
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            }));

            //选择默认仓库
            this.StockSelected = ReactiveCommand.CreateFromTask <string>((type) => Task.Run(() =>
            {
                if (string.IsNullOrEmpty(type))
                {
                    _dialogService.ShortAlert($"参数错误!");
                    return;
                }
                //注意:设置以Id订阅,Column 一定先于赋值
                var btype = (BillTypeEnum)int.Parse(type);
                switch (btype)
                {
                case BillTypeEnum.SaleBill:
                    {
                        var sb = this.SaleBill;
                        GetSelectStock(btype, (result) =>
                        {
                            if (result != null && sb != null)
                            {
                                if (result.Id > 0)
                                {
                                    sb.WareHouseId    = result.Id;
                                    sb.WareHouseName  = result.Column;
                                    Settings.SaleBill = sb;
                                }
                            }
                        });
                    }
                    break;

                case BillTypeEnum.SaleReservationBill:
                    {
                        var sb = this.SaleReservationBill;
                        GetSelectStock(btype, (result) =>
                        {
                            if (result != null && sb != null)
                            {
                                if (result.Id > 0)
                                {
                                    sb.WareHouseId               = result.Id;
                                    sb.WareHouseName             = result.Column;
                                    Settings.SaleReservationBill = sb;
                                }
                            }
                        });
                    }
                    break;

                case BillTypeEnum.ReturnBill:
                    {
                        var sb = this.ReturnBill;
                        GetSelectStock(btype, (result) =>
                        {
                            if (result != null && sb != null)
                            {
                                if (result.Id > 0)
                                {
                                    sb.WareHouseId      = result.Id;
                                    sb.WareHouseName    = result.Column;
                                    Settings.ReturnBill = sb;
                                }
                            }
                        });
                    }
                    break;

                case BillTypeEnum.ReturnReservationBill:
                    {
                        var sb = this.ReturnReservationBill;
                        GetSelectStock(btype, (result) =>
                        {
                            if (result != null && sb != null)
                            {
                                if (result.Id > 0)
                                {
                                    sb.WareHouseId   = result.Id;
                                    sb.WareHouseName = result.Column;
                                    Settings.ReturnReservationBill = sb;
                                }
                            }
                        });
                    }
                    break;

                case BillTypeEnum.ExchangeBill:
                    {
                        var sb = this.ExchangeBill;
                        GetSelectStock(btype, (result) =>
                        {
                            if (result != null && sb != null)
                            {
                                if (result.Id > 0)
                                {
                                    sb.WareHouseId        = result.Id;
                                    sb.WareHouseName      = result.Column;
                                    Settings.ExchangeBill = sb;
                                }
                            }
                        });
                    }
                    break;
                }
            }));

            //增加次数
            this.Add = ReactiveCommand.CreateFromTask <int>((type) => Task.Run(() =>
            {
                if (type == 0)
                {
                    _dialogService.ShortAlert($"参数错误!");
                    return;
                }

                var btype = (BillTypeEnum)type;
                switch (btype)
                {
                case BillTypeEnum.SaleBill:
                    {
                        var sb = this.SaleBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.SaleBill = sb;
                    }
                    break;

                case BillTypeEnum.SaleReservationBill:
                    {
                        var sb = this.SaleReservationBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.SaleReservationBill = sb;
                    }
                    break;

                case BillTypeEnum.ReturnBill:
                    {
                        var sb = this.ReturnBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.ReturnBill = sb;
                    }
                    break;

                case BillTypeEnum.ReturnReservationBill:
                    {
                        var sb = this.ReturnReservationBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.ReturnReservationBill = sb;
                    }
                    break;

                case BillTypeEnum.ExchangeBill:
                    {
                        var sb = this.ExchangeBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.ExchangeBill = sb;
                    }
                    break;

                //
                case BillTypeEnum.AllocationBill:
                    {
                        var sb = this.AllocationBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.AllocationBill = sb;
                    }
                    break;

                case BillTypeEnum.CashReceiptBill:
                    {
                        var sb = this.CashReceiptBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.CashReceiptBill = sb;
                    }
                    break;

                case BillTypeEnum.PurchaseBill:
                    {
                        var sb = this.PurchaseBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.PurchaseBill = sb;
                    }
                    break;

                case BillTypeEnum.InventoryPartTaskBill:
                    {
                        var sb = this.InventoryPartTaskBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.InventoryPartTaskBill = sb;
                    }
                    break;

                case BillTypeEnum.CostExpenditureBill:
                    {
                        var sb = this.CostExpenditureBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.CostExpenditureBill = sb;
                    }
                    break;

                case BillTypeEnum.CostContractBill:
                    {
                        var sb = this.CostContractBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.CostContractBill = sb;
                    }
                    break;

                case BillTypeEnum.AdvanceReceiptBill:
                    {
                        var sb = this.AdvanceReceiptBill;
                        sb.PrintNum++;
                        if (sb.PrintNum >= 4)
                        {
                            sb.PrintNum = 4;
                        }
                        Settings.AdvanceReceiptBill = sb;
                    }
                    break;
                }
            }));

            //减少次数
            this.Remove = ReactiveCommand.CreateFromTask <int>((type) => Task.Run(() =>
            {
                if (type == 0)
                {
                    _dialogService.ShortAlert($"参数错误!");
                    return;
                }

                var btype = (BillTypeEnum)type;
                switch (btype)
                {
                case BillTypeEnum.SaleBill:
                    {
                        var sb = this.SaleBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.SaleBill = sb;
                    }
                    break;

                case BillTypeEnum.SaleReservationBill:
                    {
                        var sb = this.SaleReservationBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.SaleReservationBill = sb;
                    }
                    break;

                case BillTypeEnum.ReturnBill:
                    {
                        var sb = this.ReturnBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.ReturnBill = sb;
                    }
                    break;

                case BillTypeEnum.ReturnReservationBill:
                    {
                        var sb = this.ReturnReservationBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.ReturnReservationBill = sb;
                    }
                    break;

                case BillTypeEnum.ExchangeBill:
                    {
                        var sb = this.ExchangeBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.ExchangeBill = sb;
                    }
                    break;

                //
                case BillTypeEnum.AllocationBill:
                    {
                        var sb = this.AllocationBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.AllocationBill = sb;
                    }
                    break;

                case BillTypeEnum.CashReceiptBill:
                    {
                        var sb = this.CashReceiptBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.CashReceiptBill = sb;
                    }
                    break;

                case BillTypeEnum.PurchaseBill:
                    {
                        var sb = this.PurchaseBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.PurchaseBill = sb;
                    }
                    break;

                case BillTypeEnum.InventoryPartTaskBill:
                    {
                        var sb = this.InventoryPartTaskBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.InventoryPartTaskBill = sb;
                    }
                    break;

                case BillTypeEnum.CostExpenditureBill:
                    {
                        var sb = this.CostExpenditureBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.CostExpenditureBill = sb;
                    }
                    break;

                case BillTypeEnum.CostContractBill:
                    {
                        var sb = this.CostContractBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.CostContractBill = sb;
                    }
                    break;

                case BillTypeEnum.AdvanceReceiptBill:
                    {
                        var sb = this.AdvanceReceiptBill;
                        sb.PrintNum--;
                        if (sb.PrintNum < 0)
                        {
                            sb.PrintNum = 0;
                        }
                        Settings.AdvanceReceiptBill = sb;
                    }
                    break;
                }
            }));

            //商品
            this.WhenAnyValue(x => x.IsAutoAsyncProducts)
            .Skip(1)
            .Subscribe(x =>
            {
                if (x)
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        using (var dig = UserDialogs.Instance.Loading("同步商品..."))
                        {
                            await Task.Delay(3000);
                            //TODO....
                        }
                        this.IsAutoAsyncProducts = false;
                    });
                }
            }).DisposeWith(DeactivateWith);

            //同步终端
            this.WhenAnyValue(x => x.IsAutoAsyncTerminals)
            .Skip(1)
            .Subscribe(x =>
            {
                if (x)
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        using (var dig = UserDialogs.Instance.Loading("同步终端..."))
                        {
                            await Task.Delay(3000);
                            //TODO....
                        }
                        this.IsAutoAsyncProducts = false;
                    });
                }
            }).DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);
        }
        public SelectLocationPageViewModel(INavigationService navigationService,
                                           IProductService productService,
                                           ITerminalService terminalService,
                                           IUserService userService,
                                           IWareHousesService wareHousesService,
                                           IAccountingService accountingService,
                                           ILiteDbService <TrackingModel> conn,
                                           IDialogService dialogService
                                           ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "选择我的位置";

            _conn = conn;

            //搜索
            this.WhenAnyValue(x => x.Filter.SerchKey)
            .Select(s => s)
            .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
            .Subscribe(s =>
            {
                if (!string.IsNullOrEmpty(s))
                {
                    ((ICommand)Load)?.Execute(null);
                }
            }).DisposeWith(DeactivateWith);


            this.Load = ReactiveCommand.Create(async() =>
            {
                var gps = new List <TrackingModel>();

                try
                {
                    var data = await _conn.Table.FindAllAsync();
                    gps      = data?.Where(s => !string.IsNullOrEmpty(s.Address)).ToList();

                    if (!string.IsNullOrEmpty(Filter.SerchKey))
                    {
                        gps = gps?.Where(s => s.Address.Contains(Filter.SerchKey)).ToList();
                    }

                    gps = gps.Distinct(new FastPropertyComparer <TrackingModel>("Address"))
                          .OrderByDescending(s => s.CreateDateTime)
                          .ThenByDescending(s => s.Id).ToList();

                    if (gps != null && gps.Any())
                    {
                        this.GpsEvents = new  ObservableCollection <TrackingModel>(gps);
                    }
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex);
                }
            });


            this.WhenAnyValue(x => x.Selecter)
            .Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                await _navigationService.GoBackAsync(("AddGpsEvent", item));
                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);

            this.BindBusyCommand(Load);
        }
Esempio n. 28
0
        public CostExpenditureBillPageViewModel(INavigationService navigationService,
                                                IProductService productService,
                                                IUserService userService,
                                                ITerminalService terminalService,
                                                IWareHousesService wareHousesService,
                                                IAccountingService accountingService,
                                                ICostExpenditureService costExpenditureService,
                                                ISaleBillService saleBillService,
                                                IDialogService dialogService
                                                ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "费用支出";

            _costExpenditureService = costExpenditureService;
            _saleBillService        = saleBillService;

            InitBill();

            //验证
            var valid_IsReversed    = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited     = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_TerminalId    = this.ValidationRule(x => x.Bill.TerminalId, _isZero, "客户未指定");
            var valid_ItemCount     = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加费用项目");
            var valid_SelectesCount = this.ValidationRule(x => x.PaymentMethods.Selectes.Count, _isZero, "请选择支付方式");

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                //await this.Access(AccessGranularityEnum.ExpenseExpenditureSave);
                return(await this.Access(AccessGranularityEnum.ExpenseExpenditureSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    var postData = new CostExpenditureUpdateModel()
                    {
                        CustomerId = this.Bill.TerminalId,
                        BillNumber = this.Bill.BillNumber,
                        EmployeeId = Settings.UserId,
                        OweCash = Bill.OweCash,
                        Remark = Bill.Remark,
                        Items = Bill.Items,
                        Accounting = PaymentMethods.Selectes.Select(a =>
                        {
                            return new AccountMaping()
                            {
                                AccountingOptionId = a.AccountingOptionId,
                                CollectionAmount = a.CollectionAmount,
                                Name = a.Name,
                                BillId = 0,
                            };
                        }).ToList(),
                    };
                    return await SubmitAsync(postData, 0, _costExpenditureService.CreateOrUpdateAsync, (result) =>
                    {
                        Bill = new CostExpenditureBillModel();
                    }, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //存储记录
            this.SaveCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!this.Bill.AuditedStatus && this.Bill.TerminalId != 0 && this.Bill.TerminalId != Settings.CostExpenditureBill?.TerminalId)
                {
                    var ok = await _dialogService.ShowConfirmAsync("你是否要保存单据?", "提示", "确定", "取消");
                    if (ok)
                    {
                        if (!this.Bill.AuditedStatus)
                        {
                            Settings.CostExpenditureBill = this.Bill;
                        }
                    }
                }
                await _navigationService.GoBackAsync();
            });

            //编辑费用
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async x =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return;
                }

                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                await this.NavigateAsync("AddCostPage", ("Terminaler", this.Terminal), ("Selecter", x));
                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);

            //添加费用
            this.AddCostCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    _dialogService.ShortAlert(valid_TerminalId.Message[0]); return;
                }
                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作!"); return;
                }

                await this.NavigateAsync("AddCostPage", ("Terminaler", this.Terminal));
            });

            //更多支付方式
            this.MorePaymentCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_TerminalId.IsValid)
                {
                    _dialogService.ShortAlert("客户未指定!"); return;
                }
                this.PaymentMethods.PreferentialAmountShowFiled = false;
                await this.NavigateAsync("PaymentMethodPage", ("PaymentMethods", this.PaymentMethods), ("BillType", this.BillType));
            });

            //审核
            this.AuditingDataCommand = ReactiveCommand.Create <object>(async _ =>
            {
                //是否具有审核权限
                await this.Access(AccessGranularityEnum.ExpenseExpenditureApproved);
                await SubmitAsync(Bill.Id, _costExpenditureService.AuditingAsync, async(result) =>
                {
                    //红冲审核水印
                    this.Bill.AuditedStatus = true;

                    var _conn = App.Resolve <ILiteDbService <MessageInfo> >();
                    var ms    = await _conn.Table.FindByIdAsync(SelecterMessage.Id);
                    if (ms != null)
                    {
                        ms.IsRead = true;
                        await _conn.UpsertAsync(ms);
                    }
                });
            }, this.WhenAny(x => x.Bill.Id, (x) => x.GetValue() > 0));


            //拒签
            this.RefusedCommand = ReactiveCommand.CreateFromTask <object>(async _ =>
            {
                try
                {
                    var ok = await _dialogService.ShowConfirmAsync("你确定要放弃签收吗?", "", "确定", "取消");
                    if (ok)
                    {
                        var postMData = new DeliverySignUpdateModel()
                        {
                            //不关联调拨单
                            DispatchItemId = 0,
                            DispatchBillId = 0,
                            StoreId        = Settings.StoreId,
                            BillId         = Bill.Id,
                            BillTypeId     = (int)BillTypeEnum.CostExpenditureBill,
                            //
                            Latitude  = GlobalSettings.Latitude,
                            Longitude = GlobalSettings.Longitude,
                            Signature = ""
                        };
                        await SubmitAsync(postMData, postMData.Id, _saleBillService.RefusedConfirmAsync, async(result) =>
                        {
                            await _navigationService.GoBackAsync();
                        });
                    }
                }
                catch (Exception)
                {
                    await _dialogService.ShowAlertAsync("拒签失败,服务器请求错误!", "", "取消");
                }
            });

            //签收
            this.ConfirmCommand = ReactiveCommand.CreateFromTask <object>(async _ =>
            {
                try
                {
                    //如果签收距离>50 则计数
                    if (Terminal.CalcDistance() > 50)
                    {
                        var tmp = Settings.Abnormal;
                        if (tmp != null)
                        {
                            tmp.Id            = Terminal.Id;
                            tmp.Counter      += 1;
                            Settings.Abnormal = tmp;
                        }
                        else
                        {
                            Settings.Abnormal = new AbnormalNum {
                                Id = Terminal.Id, Counter = 1
                            };
                        }
                    }

                    var signature = await CrossDiaglogKit.Current.GetSignaturePadAsync("手写签名", "", Keyboard.Default, defaultValue: "", placeHolder: "请手写签名...");
                    if (!string.IsNullOrEmpty(signature))
                    {
                        var postMData = new DeliverySignUpdateModel()
                        {
                            //不关联调拨单
                            DispatchItemId = 0,
                            DispatchBillId = 0,
                            StoreId        = Settings.StoreId,
                            BillId         = Bill.Id,
                            BillTypeId     = (int)BillTypeEnum.CostExpenditureBill,
                            //
                            Latitude  = GlobalSettings.Latitude,
                            Longitude = GlobalSettings.Longitude,
                            Signature = signature
                        };

                        //如果终端异常签收大于5次,则拍照
                        //if (Settings.Abnormal.Counter > 5)
                        //{
                        //    await TakePhotograph((u, m) =>
                        //    {
                        //        var photo = new RetainPhoto
                        //        {
                        //            DisplayPath = $"{GlobalSettings.FileCenterEndpoint}HRXHJS/document/image/" + u.Id + ""
                        //        };
                        //        postMData.RetainPhotos.Add(photo);
                        //    });
                        //}

                        if (Settings.Abnormal.Counter > 5 && postMData.RetainPhotos.Count == 0)
                        {
                            await _dialogService.ShowAlertAsync("拒绝操作,请留存拍照!", "", "取消");
                            return;
                        }

                        await SubmitAsync(postMData, postMData.Id, _saleBillService.DeliverySignConfirmAsync, async(result) =>
                        {
                            await _navigationService.GoBackAsync();
                        });
                    }
                }
                catch (Exception)
                {
                    await _dialogService.ShowAlertAsync("签收失败,服务器请求错误!", "", "取消");
                }
            });


            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //整单备注
                { MenuEnum.REMARK, (m, vm) => {
                      AllRemak((result) => { Bill.Remark = result; }, Bill.Remark);
                  } },
                //清空单据
                { MenuEnum.CLEAR, (m, vm) => {
                      ClearBill <CostContractBillModel, CostContractItemModel>(null, DoClear);
                  } },
                //销售备注
                { MenuEnum.SALEREMARK, (m, vm) => {
                      AllRemak((result) => { Bill.Remark = result; }, Bill.Remark);
                  } }
            });
        }
        public AdvanceReceiptBillPageViewModel(INavigationService navigationService,
                                               IProductService productService,
                                               IUserService userService,
                                               ITerminalService terminalService,
                                               IWareHousesService wareHousesService,
                                               IAccountingService accountingService,
                                               IDialogService dialogService
                                               ,
                                               IAdvanceReceiptService advanceReceiptService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "预收款单据";

            _advanceReceiptService = advanceReceiptService;

            InitBill();

            //选择预收款科目
            this.AccountingSelected = ReactiveCommand.Create <object>(async e =>
            {
                await SelectAccounting((data) =>
                {
                    Bill.AccountingOptionId   = data.AccountingOptionId;
                    Bill.AccountingOptionName = data.Name;
                }, (int)this.BillType, true);
            });

            //选择支付方式
            this.MorePaymentCommand = ReactiveCommand.Create <object>(e =>
            {
                SelectPaymentMethods(("PaymentMethods", PaymentMethods), ("BillType", this.BillType), ("Reference", PageName));
            });

            //验证
            var valid_IsReversed     = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited      = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_TerminalId     = this.ValidationRule(x => x.Bill.TerminalId, _isZero, "客户未指定");
            var valid_BusinessUserId = this.ValidationRule(x => x.Bill.AdvanceAmount, _isDZero, "预收金额未指定");
            var valid_SelectesCount  = this.ValidationRule(x => x.PaymentMethods.Selectes.Count, _isZero, "请选择支付方式");

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return(Unit.Default);
                }

                return(await this.Access(AccessGranularityEnum.ReceivablesBillsSave, async() =>
                {
                    var postData = new AdvanceReceiptUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        CustomerId = Bill.TerminalId,
                        Payeer = Settings.UserId,
                        AdvanceAmount = Bill.AdvanceAmount,
                        DiscountAmount = Bill.DiscountAmount,
                        OweCash = Bill.OweCash,
                        Remark = Bill.Remark,
                        AccountingOptionId = Bill.AccountingOptionId ?? 0,
                        Accounting = PaymentMethods.Selectes.Select(a =>
                        {
                            return new AccountMaping()
                            {
                                AccountingOptionId = a.AccountingOptionId,
                                CollectionAmount = a.CollectionAmount,
                                Name = a.Name,
                                BillId = 0,
                            };
                        }).ToList(),
                    };

                    return await SubmitAsync(postData, Bill.Id, _advanceReceiptService.CreateOrUpdateAsync, (result) =>
                    {
                        Bill = new AdvanceReceiptBillModel();
                    }, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //存储记录
            this.SaveCommand = ReactiveCommand.Create <object>(async e =>
            {
                var c1 = this.Bill.TerminalId != 0 && this.Bill.TerminalId != (Settings.AdvanceReceiptBill?.TerminalId ?? 0);
                var c2 = this.Bill.AdvanceAmount != 0 && this.Bill.AdvanceAmount != (Settings.AdvanceReceiptBill?.AdvanceAmount ?? 0);
                if ((c1 || c2))
                {
                    if (!this.Bill.AuditedStatus && !this.Bill.IsSubmitBill)
                    {
                        var ok = await _dialogService.ShowConfirmAsync("你是否要保存单据?", "提示", "确定", "取消");
                        if (ok)
                        {
                            Settings.AdvanceReceiptBill = this.Bill;
                        }
                        else
                        {
                            await _navigationService.GoBackAsync();
                        }
                    }
                }
                else
                {
                    await _navigationService.GoBackAsync();
                }
            });

            //更改输入
            this.TextChangedCommand = ReactiveCommand.Create <object>(e =>
            {
                Observable.Timer(TimeSpan.FromSeconds(2)).Subscribe(x =>
                {
                    UpdateUI();
                });
            });

            //审核
            this.AuditingDataCommand = ReactiveCommand.CreateFromTask <object>(async _ =>
            {
                //是否具有审核权限
                await this.Access(AccessGranularityEnum.ReceivablesBillsApproved);
                await SubmitAsync(Bill.Id, _advanceReceiptService.AuditingAsync, async(result) =>
                {
                    //红冲审核水印
                    this.Bill.AuditedStatus = true;

                    var _conn = App.Resolve <ILiteDbService <MessageInfo> >();
                    var ms    = await _conn.Table.FindByIdAsync(SelecterMessage.Id);
                    if (ms != null)
                    {
                        ms.IsRead = true;
                        await _conn.UpsertAsync(ms);
                    }
                });
            }, this.WhenAny(x => x.Bill.Id, (x) => x.GetValue() > 0));

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //清空单据
                { MenuEnum.CLEAR, (m, vm) =>
                  {
                      ClearForm(() =>
                        {
                            Bill = new AdvanceReceiptBillModel()
                            {
                                Payeer       = Settings.UserId,
                                CreatedOnUtc = DateTime.Now,
                                BillNumber   = CommonHelper.GetBillNumber(
                                    CommonHelper.GetEnumDescription(
                                        BillTypeEnum.AdvanceReceiptBill).Split(',')[1], Settings.StoreId)
                            };
                        });
                  } },
                //打印
                {
                    MenuEnum.PRINT, async(m, vm) => {
                        Bill.BillType = BillTypeEnum.AdvanceReceiptBill;
                        await SelectPrint(Bill);
                    }
                },
                //审核
                { MenuEnum.SHENGHE, async(m, vm) => {
                      ResultData result = null;
                      using (UserDialogs.Instance.Loading("审核中..."))
                      {
                          result = await _advanceReceiptService.AuditingAsync(Bill.Id);
                      }
                      if (result != null && result.Success)
                      {
                          //红冲审核水印
                          this.EnableOperation    = true;
                          this.Bill.AuditedStatus = true;
                          await ShowConfirm(true, "审核成功", true, goReceipt: false);
                      }
                      else
                      {
                          await ShowConfirm(false, $"审核失败!{result?.Message}", false, goReceipt: false);
                      }
                  } },
                //红冲
                { MenuEnum.HONGCHOU, async(m, vm) => {
                      var remark = await CrossDiaglogKit.Current.GetInputTextAsync("红冲备注", "", Keyboard.Text);
                      if (!string.IsNullOrEmpty(remark))
                      {
                          bool result = false;
                          using (UserDialogs.Instance.Loading("红冲中..."))
                          {
                              //红冲审核水印
                              this.EnableOperation     = true;
                              this.Bill.ReversedStatus = true;
                              result = await _advanceReceiptService.ReverseAsync(Bill.Id, remark);
                          }
                          if (result)
                          {
                              await ShowConfirm(true, "红冲成功", true);
                          }
                          else
                          {
                              await ShowConfirm(false, "红冲失败!", false, goReceipt: false);
                          }
                      }
                  } },
                //冲改
                { MenuEnum.CHOUGAI, async(m, vm) => {
                      await _advanceReceiptService.ReverseAsync(Bill.Id);
                  } }
            });
        }
Esempio n. 30
0
        public ReturnOrderBillPageViewModel(INavigationService navigationService,
                                            IReturnReservationBillService returnReservationBillService,
                                            IProductService productService,
                                            IUserService userService,
                                            ITerminalService terminalService,
                                            IWareHousesService wareHousesService,
                                            IAccountingService accountingService,
                                            IMicrophoneService microphoneService,
                                            IDialogService dialogService) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "退货订单";

            _returnReservationBillService = returnReservationBillService;
            //_saleBillService = saleBillService;

            _microphoneService = microphoneService;


            InitBill();

            //验证
            var valid_IsReversed     = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited      = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_TerminalId     = this.ValidationRule(x => x.Bill.TerminalId, _isZero, "客户未指定");
            var valid_BusinessUserId = this.ValidationRule(x => x.Bill.DeliveryUserId, _isZero, "配送员未指定");
            var valid_WareHouseId    = this.ValidationRule(x => x.Bill.WareHouseId, _isZero, "仓库未指定");
            var valid_ProductCount   = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");
            var valid_SelectesCount  = this.ValidationRule(x => x.PaymentMethods.Selectes.Count, _isZero, "请选择支付方式");


            //初始化
            this.Load = ReactiveCommand.CreateFromTask(() => Task.Run(async() =>
            {
                var whs = await _wareHousesService.GetWareHousesAsync(this.BillType, force: true);
                if (whs != null && whs.FirstOrDefault() != null)
                {
                    var wh = whs.FirstOrDefault();
                    if (Bill.WareHouseId == 0)
                    {
                        WareHouse        = wh;
                        Bill.WareHouseId = wh.Id;
                    }

                    if (string.IsNullOrEmpty(Bill.WareHouseName))
                    {
                        Bill.WareHouseName = wh.Name;
                    }

                    if (Bill.Id == 0 && Bill.DeliveryUserId == 0)
                    {
                        Bill.DeliveryUserId   = Settings.UserId;
                        Bill.DeliveryUserName = Settings.UserRealName;
                    }
                }
                InitPayment();
            }));

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                if (!valid_TerminalId.IsValid)
                {
                    _dialogService.ShortAlert(valid_TerminalId.Message[0]);
                    ((ICommand)CustomSelected)?.Execute(null);
                    return;
                }

                if (!valid_WareHouseId.IsValid || WareHouse == null)
                {
                    _dialogService.ShortAlert(valid_WareHouseId.Message[0]);
                    ((ICommand)StockSelected)?.Execute(null);
                    return;
                }

                if (!valid_BusinessUserId.IsValid)
                {
                    _dialogService.ShortAlert(valid_BusinessUserId.Message[0]);
                    ((ICommand)DeliverSelected)?.Execute(null);
                    return;
                }

                await this.NavigateAsync("SelectProductPage",
                                         ("Reference", this.PageName),
                                         ("WareHouse", WareHouse),
                                         ("TerminalId", Bill.TerminalId),
                                         ("Terminaler", this.Terminal),
                                         ("SerchKey", Filter.SerchKey));
            });

            //编辑商品
            this.WhenAnyValue(x => x.Selecter).Throttle(TimeSpan.FromMilliseconds(500))
            .Skip(1)
            .Where(x => x != null)
            .SubOnMainThread(async item =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return;
                }

                if (this.Bill.AuditedStatus && !this.ReferencePage.Equals("UnDeliveryPage"))
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                //已提交未审核的可以编辑
                if (this.Bill.IsSubmitBill && !this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已提交的单据不能编辑");
                    return;
                }

                if (item != null)
                {
                    var product = ProductSeries.Select(p => p).Where(p => p.Id == item.ProductId).FirstOrDefault();
                    if (product != null)
                    {
                        product.UnitId   = item.UnitId;
                        product.Quantity = item.Quantity;
                        product.Price    = item.Price;
                        product.Amount   = item.Amount;
                        product.Remark   = item.Remark;
                        product.Subtotal = item.Subtotal;
                        product.UnitName = item.UnitName;

                        if (item.BigUnitId > 0)
                        {
                            product.bigOption.Name        = item.UnitName;
                            product.BigPriceUnit.Quantity = item.Quantity;
                            product.BigPriceUnit.UnitId   = item.BigUnitId;
                            product.BigPriceUnit.Amount   = item.Amount;
                            product.BigPriceUnit.Remark   = item.Remark;
                        }

                        if (item.SmallUnitId > 0)
                        {
                            product.bigOption.Name          = item.UnitName;
                            product.SmallPriceUnit.Quantity = item.Quantity;
                            product.SmallPriceUnit.UnitId   = item.SmallUnitId;
                            product.SmallPriceUnit.Amount   = item.Amount;
                            product.SmallPriceUnit.Remark   = item.Remark;
                        }
                        await this.NavigateAsync("EditProductPage", ("Product", product), ("Reference", PageName), ("Item", item), ("WareHouse", WareHouse));
                    }
                }

                this.Selecter = null;
            })
            .DisposeWith(DeactivateWith);

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                return(await this.Access(AccessGranularityEnum.ReturnOrderSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return Unit.Default;
                    }
                    if (IsNeedShowPrompt)
                    {
                        var ok = await _dialogService.ShowConfirmAsync("是否保存并提交吗?", "", "确定", "取消");
                        if (!ok)
                        {
                            return Unit.Default;
                        }
                    }
                    IsNeedShowPrompt = true;

                    if (Bill.BusinessUserId == 0)
                    {
                        Bill.BusinessUserId = Settings.UserId;
                    }

                    var postMData = new ReturnReservationBillUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        //客户
                        TerminalId = Bill.TerminalId,
                        //业务员
                        BusinessUserId = Bill.BusinessUserId,
                        //仓库
                        WareHouseId = Bill.WareHouseId,
                        //交易日期
                        TransactionDate = DateTime.Now,
                        //默认售价方式
                        DefaultAmountId = Settings.DefaultPricePlan,
                        //备注
                        Remark = Bill.Remark,
                        //优惠金额
                        PreferentialAmount = Bill.PreferentialAmount,
                        //优惠后金额
                        PreferentialEndAmount = Bill.SumAmount - Bill.PreferentialAmount,
                        //欠款金额
                        OweCash = Bill.OweCash,
                        //商品项目
                        Items = Bill.Items?.Where(i => i.Quantity > 0).ToList(),
                        //收款账户
                        Accounting = PaymentMethods.Selectes.Select(a =>
                        {
                            return new AccountMaping()
                            {
                                AccountingOptionId = a.AccountingOptionId,
                                CollectionAmount = a.CollectionAmount,
                                Name = a.Name,
                                BillId = 0,
                            };
                        }).ToList()
                    };

                    return await SubmitAsync(postMData, Bill.Id, _returnReservationBillService.CreateOrUpdateAsync, async(result) =>
                    {
                        if (IsNeedPrint)
                        {
                            Bill.BillType = BillTypeEnum.SaleBill;
                            await SelectPrint((ReturnReservationBillModel)Bill.Clone());
                        }
                        IsNeedPrint = false;

                        BillId = result.Code;
                        ClearBillCache();
                        PaymentMethods.Selectes.Clear();
                        InitPayment();
                        if (IsVisit)
                        {
                            //转向拜访界面
                            //await this.NavigateAsync("VisitStorePage", ("BillTypeId",BillTypeEnum.ReturnReservationBill),("BillId", BillId),("Amount", Bill.SumAmount));
                            await _navigationService.GoBackAsync(("BillTypeId", BillTypeEnum.ReturnReservationBill), ("BillId", BillId), ("Amount", Bill.SumAmount));
                        }
                    }, token: new System.Threading.CancellationToken());
                }));
            },