Beispiel #1
0
        public async Task CreateTenant(CreateTenantInput input)
        {
            //Create tenant
            var tenant = ObjectMapper.Map <Tenant>(input);

            tenant.ConnectionString = input.ConnectionString.IsNullOrEmpty()
                ? null
                : SimpleStringCipher.Instance.Encrypt(input.ConnectionString);

            var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName);

            if (defaultEdition != null)
            {
                tenant.EditionId = defaultEdition.Id;
            }

            await TenantManager.CreateAsync(tenant);

            await CurrentUnitOfWork.SaveChangesAsync(); //To get new tenant's id.

            //Create tenant database
            _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);

            //We are working entities of new tenant, so changing tenant filter
            using (CurrentUnitOfWork.SetTenantId(tenant.Id))
            {
                //Create static roles for new tenant
                CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));

                await CurrentUnitOfWork.SaveChangesAsync(); //To get static role ids

                //grant all permissions to admin role
                var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin);
                await _roleManager.GrantAllPermissionsAsync(adminRole);

                //Create admin user for the tenant
                var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress);
                adminUser.Password = _passwordHasher.HashPassword(adminUser, User.DefaultPassword);
                CheckErrors(await UserManager.CreateAsync(adminUser));
                await CurrentUnitOfWork.SaveChangesAsync(); //To get admin user's id

                //Assign admin user to role!
                CheckErrors(await UserManager.AddToRoleAsync(adminUser, adminRole.Name));
                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }
        private async Task SetRandomProfilePictureAsync(User user)
        {
            try
            {
                //Save a random profile picture
                var storedFile = new BinaryObject(user.TenantId, GetRandomProfilePictureBytes());
                await _binaryObjectManager.SaveAsync(storedFile);

                //Update new picture on the user
                user.ProfilePictureId = storedFile.Id;
                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch
            {
                //we can ignore this exception
            }
        }
Beispiel #3
0
        /// <summary>
        /// 通过邮箱重置密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task ResetPasswordByEmail(ResetPasswordByEmailInput input)
        {
            await VerificationResetPasswordByEmail(input);

            _passwordComplexityChecker.Check(input.Password);

            var user = await _userManager.Users.FirstOrDefaultAsync(n => n.EmailAddress == input.Email);

            if (user == null)
            {
                throw new UserFriendlyException("找不到此邮箱关联的用户");
            }
            user.Password = new PasswordHasher <User>().HashPassword(user, input.Password);
            await CurrentUnitOfWork.SaveChangesAsync();

            await _cacheManager.GetCache("EmailCode").RemoveAsync(input.Email);
        }
        public virtual async Task ExternalUserRegister(ExternalUserRegisterDto externalUserRegisterDto)
        {
            var manager = Manager as UserManager;

            using (CurrentUnitOfWork.SetTenantId(externalUserRegisterDto.TenantId))
            {
                var userLoginInfo = new Microsoft.AspNetCore.Identity.UserLoginInfo(externalUserRegisterDto.LoginProvider, externalUserRegisterDto.ProviderKey, "");
                //判断此第三方账号是否已绑定过
                var user = await manager.FindAsync(userLoginInfo);

                if (user != null)
                {
                    throw new UserFriendlyException(L("此登录信息已绑定过系统账号"));
                }
                //判断对应手机号是否已存在
                if (await manager.GetAll().CountAsync(o => o.PhoneNumber == externalUserRegisterDto.Mobile) > 0)
                {
                    throw new UserFriendlyException(L("此手机号已被注册"));
                }
                user = new User()
                {
                    UserName       = externalUserRegisterDto.Mobile,
                    PhoneNumber    = externalUserRegisterDto.Mobile,
                    Name           = externalUserRegisterDto.Name,
                    Sex            = externalUserRegisterDto.Sex,
                    TenantId       = externalUserRegisterDto.TenantId,
                    OrganizationId = externalUserRegisterDto.OrganizationId,
                    IsActive       = false,
                };
                user.ToBeVerified = true;//设置用户未审核
                //插入员工信息
                await manager.InsertAsync(user);

                await CurrentUnitOfWork.SaveChangesAsync();

                //设置角色
                await manager.SetRoles(user, externalUserRegisterDto.RoleIds);

                //设置密码
                await manager.SetPassword(user, externalUserRegisterDto.Password);

                //绑定第三方登录信息
                await manager.BindExternalLogin(user, userLoginInfo);
            }
        }
Beispiel #5
0
        public virtual async Task <MenuDto> CreateAsync(MenuCreateDto input)
        {
            var layout = await LayoutRepository.GetAsync(input.LayoutId);

            var data = await DataRepository.GetAsync(layout.DataId);

            var menu = await MenuManager.CreateAsync(
                GuidGenerator.Create(),
                layout.Id,
                input.Path,
                input.Name,
                input.Component,
                input.DisplayName,
                input.Redirect,
                input.Description,
                layout.PlatformType,
                input.ParentId,
                CurrentTenant.Id,
                input.IsPublic);

            // 利用布局约定的数据字典来校验必须的路由元数据,元数据的加入是为了适配多端路由
            foreach (var dataItem in data.Items)
            {
                if (!input.Meta.TryGetValue(dataItem.Name, out object meta))
                {
                    if (!dataItem.AllowBeNull)
                    {
                        throw new BusinessException(PlatformErrorCodes.MenuMissingMetadata)
                              .WithData("Name", dataItem.DisplayName)
                              .WithData("DataName", data.DisplayName);
                    }
                    // 是否需要设定默认值
                    menu.SetProperty(dataItem.Name, dataItem.DefaultValue);
                }
                else
                {
                    // 需要检查参数是否有效
                    menu.SetProperty(dataItem.Name, DataItemMapping.MapToString(dataItem.ValueType, meta));
                }
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <Menu, MenuDto>(menu));
        }
Beispiel #6
0
        public async Task <User> SignUpAsync(string name, string surname, string emailAddress, string phone, string userName, string plainPassword, bool isEmailConfirmed)
        {
            CheckForTenant();

            var tenant = await GetActiveTenantAsync();

            var user = new User
            {
                TenantId         = tenant.Id,
                Name             = name,
                Surname          = surname,
                EmailAddress     = emailAddress ?? RandomStringGeneratorUtil.GenerateFakeEmail(),
                PhoneNumber      = phone,
                IsActive         = true,
                UserName         = userName,
                IsEmailConfirmed = isEmailConfirmed,
                Roles            = new List <UserRole>()
            };

            user.SetNormalizedNames();

            foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
            {
                user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
            }

            await _userManager.InitializeOptionsAsync(tenant.Id);

            try
            {
                Logger.Info("About to save new user...");
                CheckErrors(await _userManager.CreateAsync(user, plainPassword));
                Logger.Info("Created new user, and next is to save...");
                await CurrentUnitOfWork.SaveChangesAsync();

                Logger.Info("S|aved new user.");
            }
            catch (Exception exc)
            {
                Logger.Error($"Err Message: {exc.Message}");
                Logger.Error($"StackTrace: {exc.StackTrace}");
            }

            return(user);
        }
Beispiel #7
0
        protected virtual async Task CreateUserAsync(CreateOrUpdateUserInput input)
        {
            var user = input.User.MapTo <User>(); //Passwords is not mapped (see mapping configuration)

            user.TenantId = AbpSession.TenantId;

            //Set password
            if (!input.User.Password.IsNullOrEmpty())
            {
                CheckErrors(await UserManager.PasswordValidator.ValidateAsync(input.User.Password));
            }
            else
            {
                input.User.Password = User.CreateRandomPassword();
            }

            user.Password = new PasswordHasher().HashPassword(input.User.Password);
            user.ShouldChangePasswordOnNextLogin = input.User.ShouldChangePasswordOnNextLogin;

            //Assign roles
            user.Roles = new Collection <UserRole>();
            foreach (var roleName in input.AssignedRoleNames)
            {
                var role = await _roleManager.GetRoleByNameAsync(roleName);

                user.Roles.Add(new UserRole {
                    RoleId = role.Id
                });
            }

            CheckErrors(await UserManager.CreateAsync(user));
            await CurrentUnitOfWork.SaveChangesAsync(); //To get new user's Id.

            //Notifications
            await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(user.ToUserIdentifier());

            await _appNotifier.WelcomeToTheApplicationAsync(user);

            //Send activation email
            if (input.SendActivationEmail)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(user, input.User.Password);
            }
        }
Beispiel #8
0
        public async Task <ChannelDto> CreateChannel(CreateChannelInput input)
        {
            var channel = new Channel(AppId, input.DisplayName, input.ParentId);

            if (input.ChannelTemplateId.HasValue)
            {
                channel.ChannelTemplateId = input.ChannelTemplateId.Value;
            }
            if (input.ContentTemplateId.HasValue)
            {
                channel.ContentTemplateId = input.ContentTemplateId.Value;
            }
            await _channelManager.CreateAsync(channel);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(channel.MapTo <ChannelDto>());
        }
Beispiel #9
0
        public virtual async Task SetCurrentTenantAsync(UpdateSettingsDto input)
        {
            if (CurrentTenant.IsAvailable)
            {
                foreach (var setting in input.Settings)
                {
                    await SettingManager.SetForTenantAsync(CurrentTenant.GetId(), setting.Name, setting.Value);
                }

                CurrentUnitOfWork.OnCompleted(async() =>
                {
                    // 发送刷新用户缓存事件
                    await EventBus.PublishAsync(new CurrentApplicationConfigurationCacheResetEventData());
                });

                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }
Beispiel #10
0
        public override async Task <GetAllEmpDTO> Update(CreateEmpDTO input)
        {
            if (input.DepartmentId != null && !deptDomainService.DepartmentExists((int)input.DepartmentId))
            {
                throw new ArgumentException();
            }
            CheckUpdatePermission();

            Employee entity = await GetEntityByIdAsync(input.Id);

            //value object mapping
            entity.Address = new Address(input.Address.FullAddress, input.Address.AppartmentNumber);

            MapToEntity(input, entity);
            await CurrentUnitOfWork.SaveChangesAsync();

            return(MapToEntityDto(entity));
        }
Beispiel #11
0
        public async Task DeleteNoticeAsync(EntityDto <Guid> intput)
        {
            var noticemodel = await _noticeTextRepository.GetAll().FirstOrDefaultAsync(r => r.Id == intput.Id);

            if (noticemodel == null)
            {
                throw new UserFriendlyException((int)ErrorCode.DataAccessErr, "数据异常");
            }
            else
            {
                var logmodels = await _noticeLogRepository.GetAll().Where(r => r.TextId == intput.Id).ToListAsync();

                logmodels.ForEach(r => { _noticeLogRepository.DeleteAsync(r); });
                await _noticeTextRepository.DeleteAsync(noticemodel);

                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }
        public async Task <bool> Update(UpdateLeatherInput input)
        {
            var leather = await _repository.GetAll()
                          .Where(x => x.Status == LeatherProductionChainStatus.Slaughterhouse &&
                                 x.Id == input.Id)
                          .FirstOrDefaultAsync();

            if (leather == null)
            {
                throw new UserFriendlyException("Animal not found");
            }

            leather.Weight = input.Weight;
            leather.EarsOn = input.EarsOn;
            await CurrentUnitOfWork.SaveChangesAsync();

            return(true);
        }
Beispiel #13
0
        public async Task DeleteAPHeaderTransactionUnit(IdInput <long> input)
        {
            var invoiceDetailsList = await _invoiceEntryDocumentDetailUnitRepository.GetAllListAsync(p => p.AccountingDocumentId == input.Id);

            foreach (var invoiceDetail in invoiceDetailsList)
            {
                if (invoiceDetail.PoAccountingItemId.HasValue && invoiceDetail.PoAccountingItemId.Value > 0)
                {
                    await _purchaseOrderEntryDocumentAppService.PoProcessingByPayType(invoiceDetail, null);
                }
            }

            await _invoiceEntryDocumentDetailUnitRepository.DeleteAsync(p => p.AccountingDocumentId == input.Id);

            await _apHeaderTransactionsUnitManager.DeleteAsync(input);

            await CurrentUnitOfWork.SaveChangesAsync();
        }
Beispiel #14
0
        /*
         * public async Task<ListResultDto<EventoDto>> GetDatosEventos()
         * {
         *  var eventos = await _eventoRepository.GetAll()
         *      .Include(e => e.UsuarioOrganizador.Name)
         *      .ToListAsync();
         *
         *  return new ListResultDto<EventoDto>(ObjectMapper.Map<List<EventoDto>>(eventos));
         * }
         */


        public async Task <CreateEventoDto> CreateEventoAsync(CreateEventoDto input)
        {
            CheckCreatePermission();

            var userLogado = await _userManager.GetUserByIdAsync(AbpSession.GetUserId());

            var evento = ObjectMapper.Map <Evento>(input);

            evento.CreatorUserId = userLogado.Id;
            //userLogado.EventosCreados.Add(evento);

            await _eventoRepository.InsertAsync(evento);

            await CurrentUnitOfWork.SaveChangesAsync();


            return(ObjectMapper.Map <CreateEventoDto>(evento));
        }
Beispiel #15
0
        public async Task DeleteContractor(EntityDto input)
        {
            try
            {
                var contractor = _contractorRepository.GetAll()
                                 .Include(x => x.User)
                                 .FirstOrDefault(x => x.Id == input.Id);
                await UserManager.DeleteAsync(contractor?.User);

                await _contractorRepository.DeleteAsync(input.Id);

                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch
            {
                throw new UserFriendlyException(L("YouCanNotDeleteThisRecord"));
            }
        }
Beispiel #16
0
    public virtual async Task <IdentityRoleDto> UpdateAsync(Guid id, IdentityRoleUpdateDto input)
    {
        var role = await RoleManager.GetByIdAsync(id);

        role.SetConcurrencyStampIfNotNull(input.ConcurrencyStamp);

        (await RoleManager.SetRoleNameAsync(role, input.Name)).CheckErrors();

        role.IsDefault = input.IsDefault;
        role.IsPublic  = input.IsPublic;

        input.MapExtraPropertiesTo(role);

        (await RoleManager.UpdateAsync(role)).CheckErrors();
        await CurrentUnitOfWork.SaveChangesAsync();

        return(ObjectMapper.Map <IdentityRole, IdentityRoleDto>(role));
    }
Beispiel #17
0
        public virtual async Task ChangePhoneNumberAsync(ChangePhoneNumberDto input)
        {
            // 是否已有用户使用手机号绑定
            if (await UserRepository.IsPhoneNumberConfirmedAsync(input.NewPhoneNumber))
            {
                throw new BusinessException(IdentityErrorCodes.DuplicatePhoneNumber);
            }
            //TODO: 可以查询缓存用 securityTokenCacheItem.SecurityToken 与 user.SecurityStamp 作对比
            var user = await UserManager.GetByIdAsync(CurrentUser.GetId());

            // 更换手机号
            (await UserManager.ChangePhoneNumberAsync(user, input.NewPhoneNumber, input.Code)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();

            var securityTokenCacheKey = SmsSecurityTokenCacheItem.CalculateCacheKey(input.NewPhoneNumber, "SmsChangePhoneNumber");
            await SecurityTokenCache.RemoveAsync(securityTokenCacheKey);
        }
        public async Task <long> CreateSurgeryProcedureAsync(CreateSurgeryProcedureInput input)
        {
            try
            {
                var record = _mapper.Map <SystemSurgeryProcedure>(input);
                record.CreatorUserId = GetCurrentUser();

                await _surgeryProcedureRepository.InsertAsync(record);

                await CurrentUnitOfWork.SaveChangesAsync();

                return(record.Id);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
Beispiel #19
0
        public virtual async Task <IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            var user = new IdentityUser(
                GuidGenerator.Create(),
                input.UserName,
                input.Email,
                CurrentTenant.Id
                );

            input.MapExtraPropertiesTo(user);

            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();
            await UpdateUserByInput(user, input);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto>(user));
        }
        public virtual async Task <IdentityUserDto> CreateAsync(IdentityUserCreateDto input)
        {
            var user = new IdentityUser(GuidGenerator.Create(), input.UserName, input.Email, CurrentTenant.Id);

            (await _userManager.CreateAsync(user, input.Password)).CheckErrors();
            await UpdateUserByInput(user, input);

            await CurrentUnitOfWork.SaveChangesAsync();

            //Send activation email
            if (input.SendActivationEmail)
            {
                user.SetNewEmailConfirmationCode();
                await _userEmailer.SendEmailActivationLinkAsync(user, input.Password);
            }

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto>(user));
        }
Beispiel #21
0
        public async Task <SDI_UserDto> UpdateApiKey(SDI_UserDto input)
        {
            var user = await _sdiUserRepository.FirstOrDefaultAsync(t => t.Id == input.Id && t.SDI_ApplicationId == input.SDI_ApplicationId); //there should only be one.  if not a passcode needs to be created by calling program, but we return null if it does not exist

            //cant find the user so we Create it and return it.
            if (user == null)
            {
                throw new System.Exception("User should exists");
            }

            ObjectMapper.Map(input, user);

            await _sdiUserRepository.UpdateAsync(user);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <SDI_UserDto>(user));
        }
Beispiel #22
0
        //public List<EmployeeListDetailDto> GetListEmployee()
        //{
        //    var result = new List<EmployeeListDetailDto>(){};
        //     result = _taskRepository.GetAll()
        //                    .Where(s => s.AssignedEmployeeId.HasValue)
        //                    .Select(e => new
        //                    {
        //                        EmployeeId = e.AssignedEmployeeId,
        //                        EmployeeName = e.AssignedEmployee.Name,
        //                        Age = e.AssignedEmployee.BirthDate,
        //                        e.State
        //                    })
        //                    .GroupBy(l => new { l.EmployeeId, l.EmployeeName , l.Age})
        //                    .Select(cl => new EmployeeListDetailDto
        //                    {
        //                        EmployeeId = cl.Key.EmployeeId,
        //                        EmployeeName = cl.Key.EmployeeName,
        //                        Age= DateTime.Today.Year- cl.Key.Age.Year,
        //                        TaskPending = cl.Where(x => x.State == TaskState.Open).Count(),
        //                        TaskComplete = cl.Where(y => y.State == TaskState.Completed).Count(),
        //                    }).ToList();

        //    return result;
        //}

        public async Task <TaskListDto> Create(CreateTaskInput input)
        {
            try
            {
                input.TenantId = 1;
                input.State    = TaskState.Completed;
                var task = ObjectMapper.Map <WS.Tasks.Task>(input);
                await _taskRepository.InsertAsync(task);

                await CurrentUnitOfWork.SaveChangesAsync();

                return(ObjectMapper.Map <TaskListDto>(task));
            }
            catch (Exception e)
            {
                throw (e);
            }
        }
        public virtual async Task ClearSubscriptionToken(string eventSubscriptionId, string token)
        {
            var uid            = new Guid(eventSubscriptionId);
            var existingEntity = await _eventSubscriptionRepository.GetAll()
                                 .Where(x => x.Id == uid)
                                 .AsTracking()
                                 .FirstAsync();

            if (existingEntity.ExternalToken != token)
            {
                throw new InvalidOperationException();
            }

            existingEntity.ExternalToken       = null;
            existingEntity.ExternalWorkerId    = null;
            existingEntity.ExternalTokenExpiry = null;
            await CurrentUnitOfWork.SaveChangesAsync();
        }
Beispiel #24
0
        public async Task <EntityDto> CreateOrUpdateVoucherPlatform(VoucherPlatformEditDto input)
        {
            try
            {
                var isEdit = input.Id > 0;

                VoucherPlatform platform;
                if (isEdit)
                {
                    platform = await _voucherPlatformManager.FindAsync(input.Id);

                    if (platform == null)
                    {
                        throw new UserFriendlyException(L("InvalidVoucherPlatform"));
                    }
                }
                else
                {
                    platform = new VoucherPlatform(input.Name);
                }

                platform.UpdateName(input.Name);
                platform.UpdateSettings(input.TermConditionJson);

                if (!isEdit)
                {
                    await _voucherPlatformManager.CreateAsync(platform);
                }
                else
                {
                    await _voucherPlatformManager.UpdateVoucherPlatformAsync(platform);
                }

                await CurrentUnitOfWork.SaveChangesAsync();

                return(new EntityDto(platform.Id));
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }

            return(new EntityDto());
        }
Beispiel #25
0
        public virtual async Task RegisterAsync(WeChatRegisterDto input)
        {
            ThowIfInvalidEmailAddress(input.EmailAddress);

            await CheckSelfRegistrationAsync();

            await IdentityOptions.SetAsync();

            var options = await MiniProgramOptionsFactory.CreateAsync();

            var wehchatOpenId = await WeChatOpenIdFinder.FindAsync(input.Code, options.AppId, options.AppSecret);

            var user = await UserManager.FindByLoginAsync(AbpWeChatMiniProgramConsts.ProviderKey, wehchatOpenId.OpenId);

            if (user != null)
            {
                // 应该要抛出微信号已注册异常,而不是直接返回注册用户数据,否则造成用户信息泄露
                throw new UserFriendlyException(L["DuplicateWeChat"]);
            }
            var userName = input.UserName;

            if (userName.IsNullOrWhiteSpace())
            {
                userName = "******" + wehchatOpenId.OpenId.ToMd5().ToLower();
            }

            var userEmail = input.EmailAddress;//如果邮件地址不验证,随意写入一个

            if (userEmail.IsNullOrWhiteSpace())
            {
                userEmail = $"{userName}@{CurrentTenant.Name ?? "default"}.io";
            }

            user = new IdentityUser(GuidGenerator.Create(), userName, userEmail, CurrentTenant.Id);
            (await UserManager.CreateAsync(user, input.Password)).CheckErrors();

            (await UserManager.AddDefaultRolesAsync(user)).CheckErrors();

            var userLogin = new UserLoginInfo(AbpWeChatMiniProgramConsts.ProviderKey, wehchatOpenId.OpenId, AbpWeChatGlobalConsts.DisplayName);

            (await UserManager.AddLoginAsync(user, userLogin)).CheckErrors();

            await CurrentUnitOfWork.SaveChangesAsync();
        }
        public async Task <User> RegisterAsync(string name, string surname, string emailAddress, string userName, string plainPassword, bool isEmailConfirmed, string city, string town, DateTime birthDate, string qualities)
        {
            CheckForTenant();

            // var tenant = await GetActiveTenantAsync();
            //var tenant = null;

            var user = new User
            {
                //TenantId = tenant.Id,
                TenantId         = null,
                Name             = name,
                Surname          = surname,
                EmailAddress     = emailAddress,
                IsActive         = true,
                UserName         = userName,
                IsEmailConfirmed = isEmailConfirmed,
                Roles            = new List <UserRole>(),
                City             = city,
                Town             = town,
                BirthDate        = birthDate,
                Qualities        = qualities
            };

            user.SetNormalizedNames();

            //foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
            //{
            //  user.Roles.Add(new UserRole(null, user.Id, defaultRole.Id));
            //}
            user.Roles.Add(new UserRole(null, user.Id, 3));
            await _userManager.InitializeOptionsAsync(null);

            user.Photo = "http://192.168.1.43:21021/Resources/ProfilePics/user_profilepic.png";

            user.TenantId = null;
            CheckErrors(await _userManager.CreateAsync(user, plainPassword));
            user.Roles.Add(new UserRole(null, user.Id, 3));
            user.TenantId = null;
            await CurrentUnitOfWork.SaveChangesAsync();


            return(user);
        }
Beispiel #27
0
        public async Task <EntityDto <long> > CreateOrUpdateTenantLogistics(CreateOrUpdateTenantLogisticsInput input)
        {
            TenantLogistics tenantLogistics = null;

            if (input.Id > 0)
            {
                tenantLogistics = await UpdateTenantLogisticsAsync(input);
            }
            else
            {
                tenantLogistics = await CreateTenantLogisticsAsync(input);
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            return(new EntityDto <long> {
                Id = tenantLogistics.Id
            });
        }
Beispiel #28
0
        public async Task <EntityDto <long> > CreateOrUpdateLogistics(CreateOrUpdateLogisticsInput input)
        {
            Logistics logistics = null;

            if (input.Id.HasValue && input.Id.Value > 0)
            {
                logistics = await UpdateLogisticsAsync(input);
            }
            else
            {
                logistics = await CreateLogisticsAsync(input);
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            return(new EntityDto <long> {
                Id = logistics.Id
            });
        }
        public async Task <int> Surrender(SurrenderDto input)
        {
            CheckUpdatePermission();

            int surrenderNum = 0;

            input.InsurancePolicyIds.ForEach(x =>
            {
                var insurancePolicy = Repository.FirstOrDefault(p => p.Id == x);

                CheckInsurancePolicy(insurancePolicy);

                var insuranceDetails = _insuranceDetailRepository.GetAll().Where(d => d.InsurancePolicyId == x).ToList();
                if (insurancePolicy == null || insuranceDetails == null || insuranceDetails.Count <= 0)
                {
                    throw new UserFriendlyException("保单资料异常");
                }
                var percent = Convert.ToDecimal(Math.Round((input.EndTime.ToLocalTime().Date - insurancePolicy.StartTime.ToLocalTime().Date).TotalDays) / Math.Round((insurancePolicy.EndTime.ToLocalTime().Date - insurancePolicy.StartTime.ToLocalTime().Date).TotalDays));
                for (int i = 0; i < insuranceDetails.Count; i++)
                {
                    var OldInsuranceJson = JsonConvert.SerializeObject(insuranceDetails[i]);
                    insuranceDetails[i].OriginalAmount                = insuranceDetails[i].OriginalAmount * percent;
                    insuranceDetails[i].TransactionAmount             = insuranceDetails[i].TransactionAmount * percent;
                    insuranceDetails[i].NoDeductibleOriginalAmount    = insuranceDetails[i].NoDeductibleOriginalAmount * percent;
                    insuranceDetails[i].NoDeductibleTransactionAmount = insuranceDetails[i].NoDeductibleTransactionAmount * percent;
                    insuranceDetails[i] = UpdateInsuranceCalculation(insuranceDetails[i]);
                    _insuranceLogRepository.Insert(new InsuranceLog
                    {
                        InsuranceOperationType = InsuranceOperationType.Surrender,
                        InsuranceDetailId      = insuranceDetails[i].Id,
                        SerialNumber           = input.SerialNumber,
                        OldInsuranceJson       = OldInsuranceJson,
                        NewInsuranceJson       = JsonConvert.SerializeObject(insuranceDetails[i])
                    });
                }
                insurancePolicy.EndTime = input.EndTime.ToLocalTime();
                surrenderNum++;
            });

            await CurrentUnitOfWork.SaveChangesAsync();

            return(surrenderNum);
        }
        public async Task <JsonResult> UploadFile()
        {
            try
            {
                var file = Request.Form.Files.First();

                //Check input
                if (file == null)
                {
                    throw new UserFriendlyException(L("File_Empty_Error"));
                }

                if (file.Length > 10000000) //10MB
                {
                    throw new UserFriendlyException(L("File_SizeLimit_Error"));
                }

                byte[] fileBytes;
                using (var stream = file.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                var fileObject = new BinaryObject(null, fileBytes, $"File uploaded from chat by {AbpSession.UserId}, File name: {file.FileName} {DateTime.UtcNow}");
                using (CurrentUnitOfWork.SetTenantId(null))
                {
                    await BinaryObjectManager.SaveAsync(fileObject);

                    await CurrentUnitOfWork.SaveChangesAsync();
                }

                return(Json(new AjaxResponse(new
                {
                    id = fileObject.Id,
                    name = file.FileName,
                    contentType = file.ContentType
                })));
            }
            catch (UserFriendlyException ex)
            {
                return(Json(new AjaxResponse(new ErrorInfo(ex.Message))));
            }
        }