Esempio n. 1
0
 public async Task <List <ShopProductListDto> > GetShopProductsByShopId(Guid shopId, int?tenantId)
 {
     using (CurrentUnitOfWork.SetTenantId(tenantId))
     {
         var query = from s in _shopproductRepository.GetAll().Where(s => s.ShopId == shopId)
                     join p in _productRepository.GetAll().Where(p => p.IsRare == true && p.IsAction == true) on s.ProductId equals p.Id
                     select new ShopProductListDto
         {
             Id            = p.Id,
             ProductId     = s.ProductId,
             ShopId        = s.ShopId,
             Specification = p.Specification,
             Type          = p.Type,
             Price         = p.Price,
             PackageCode   = p.PackageCode,
             BarCode       = p.BarCode,
             PhotoUrl      = p.PhotoUrl,
             Desc          = p.Desc
         };
         return(await query.OrderBy(q => q.Type).ThenBy(q => q.Specification).ToListAsync());
     }
 }
        public async Task <ActionResult> SendSecurityCode(SendSecurityCodeViewModel model)
        {
            var tenantId = await _signInManager.GetVerifiedTenantIdAsync();

            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                if (!await _signInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
                {
                    throw new UserFriendlyException(L("SendSecurityCodeErrorMessage"));
                }

                return(RedirectToAction(
                           "VerifySecurityCode",
                           new
                {
                    provider = model.SelectedProvider,
                    returnUrl = model.ReturnUrl,
                    rememberMe = model.RememberMe
                }
                           ));
            }
        }
Esempio n. 3
0
        public async Task <StripeIdResponse> GetOrCreatePlanForPayment(long paymentId)
        {
            var payment = await _subscriptionPaymentRepository.GetAsync(paymentId);

            string  planId;
            decimal amount;

            using (CurrentUnitOfWork.SetTenantId(null))
            {
                var edition = (SubscribableEdition)await _editionManager.GetByIdAsync(payment.EditionId);

                planId = GetPlanId(edition.Name, payment.GetPaymentPeriodType());
                amount = edition.GetPaymentAmount(payment.GetPaymentPeriodType());
            }

            var product = await GetOrCreateProductAsync(ProductName);

            var planInterval = GetPlanInterval(payment.PaymentPeriodType);


            return(await GetOrCreatePlanAsync(planId, amount, planInterval, product.Id));
        }
Esempio n. 4
0
        /// <summary>
        /// 运维专用:更新指定租户下的某一角色
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <RoleDto> UpdateRoleInTenantAsync(int tenantId, RoleDto input)
        {
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                try
                {
                    var role = await _roleManager.GetRoleByIdAsync(input.Id);

                    ObjectMapper.Map(input, role);

                    await _roleManager.UpdateRoleAndPermissionAsync(role, input.GrantedPermissions);

                    await RemoveRolePermissionCacheItem(tenantId, role);

                    return(ObjectMapper.Map <RoleDto>(role));
                }
                catch (Exception exception)
                {
                    throw new UserFriendlyException(exception.Message);
                }
            }
        }
        public async Task <PagedResultDto <NameValueDto> > FindUsers(FindUsersInput input)
        {
            if (AbpSession.TenantId != null)
            {
                //Prevent tenants to get other tenant's users.
                input.TenantId = AbpSession.TenantId;
            }

            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var query = UserManager.Users
                            .WhereIf(
                    !input.Filter.IsNullOrWhiteSpace(),
                    u =>
                    u.Name.Contains(input.Filter) ||
                    u.Surname.Contains(input.Filter) ||
                    u.UserName.Contains(input.Filter) ||
                    u.EmailAddress.Contains(input.Filter)
                    );

                var userCount = await query.CountAsync();

                var users = await query
                            .OrderBy(u => u.Name)
                            .ThenBy(u => u.Surname)
                            .PageBy(input)
                            .ToListAsync();

                return(new PagedResultDto <NameValueDto>(
                           userCount,
                           users.Select(u =>
                                        new NameValueDto(
                                            u.FullName + " (" + u.EmailAddress + ")",
                                            u.Id.ToString()
                                            )
                                        ).ToList()
                           ));
            }
        }
Esempio n. 6
0
        public async Task <List <RetailerListDto> > GetAllRetailByPageAsync(GetRetailersWeChatInput input)
        {
            using (CurrentUnitOfWork.SetTenantId(input.tenantId))
            {
                var retailList = new List <RetailerListDto>();
                if (input.IsMore)
                {
                    var retailListQ = await _retailerRepository.GetAll().Where(r => r.Telephone.Contains(input.Filter) || r.LicenseKey.Contains(input.Filter) || r.Name.Contains(input.Filter) && r.IsAction == true)
                                      .OrderBy(r => r.Name).Skip(input.SkipCount).Take(input.MaxResultCount).ToListAsync();

                    retailList = retailListQ.MapTo <List <RetailerListDto> >();
                }
                else
                {
                    var retailListQ = await _retailerRepository.GetAll().Where(r => r.Telephone.Contains(input.Filter) || r.LicenseKey.Contains(input.Filter) || r.Name.Contains(input.Filter) && r.IsAction == true)
                                      .OrderBy(r => r.Name).Skip(0).Take(20).ToListAsync();

                    retailList = retailListQ.MapTo <List <RetailerListDto> >();
                }
                return(retailList);
            }
        }
Esempio n. 7
0
 private List <ImportUserDto> GetUserListFromExcelOrNull(ImportUsersFromExcelJobArgs args)
 {
     using (var uow = _unitOfWorkManager.Begin())
     {
         using (CurrentUnitOfWork.SetTenantId(args.TenantId))
         {
             try
             {
                 var file = AsyncHelper.RunSync(() => _binaryObjectManager.GetOrNullAsync(args.BinaryObjectId));
                 return(_userListExcelDataReader.GetUsersFromExcel(file.Bytes));
             }
             catch (Exception)
             {
                 return(null);
             }
             finally
             {
                 uow.Complete();
             }
         }
     }
 }
        public async Task <PagedResultDto <NameValueDto> > FindUsersSetUserNameToValue(CommonLookupFindUsersInput input)
        {
            if (AbpSession.TenantId != null)
            {
                // 防止租户获取其他租户的用户
                input.TenantId = AbpSession.TenantId;
            }

            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var query = UserManager.Users
                            .WhereIf(
                    !input.FilterText.IsNullOrWhiteSpace(),
                    u =>
                    u.UserName.Contains(input.FilterText) ||
                    u.EmailAddress.Contains(input.FilterText)
                    );

                var userCount = await query.CountAsync();

                var users = query.ToList()
                            .OrderBy(u => u.Name)
                            .ThenBy(u => u.Surname)
                            .Take(input.MaxResultCount)
                            .Skip(input.SkipCount)
                            .ToList();

                return(new PagedResultDto <NameValueDto>(
                           userCount,
                           users.Select(u =>
                                        new NameValueDto(
                                            u.UserName + " (" + u.EmailAddress + ")",
                                            u.UserName
                                            )
                                        ).ToList()
                           ));
            }
        }
Esempio n. 9
0
        public async Task <ActivityFormCountDto> GetActivityFormCountByUserAsync(WeChatUserListDto user)
        {
            using (CurrentUnitOfWork.SetTenantId(user.TenantId))
            {
                ActivityFormCountDto countDto = new ActivityFormCountDto();
                switch (user.UserType)
                {
                case UserTypeEnum.零售客户:
                {
                    countDto.OutstandingCount = await _activityformRepository.GetAll()
                                                .Where(a => a.CreationId == user.UserId)
                                                .Where(a => a.Status == FormStatusEnum.提交申请 ||
                                                       a.Status == FormStatusEnum.初审通过 ||
                                                       a.Status == FormStatusEnum.资料回传已审核).CountAsync();

                    countDto.CompletedCount = await _activityformRepository.GetAll().Where(a => a.CreationId == user.UserId && a.Status == FormStatusEnum.营销中心已审核).CountAsync();
                }
                break;

                case UserTypeEnum.内部员工:
                {
                    countDto.OutstandingCount = await _activityformRepository.GetAll()
                                                .Where(a => a.ManagerId == user.UserId)
                                                .Where(a => a.Status == FormStatusEnum.提交申请 ||
                                                       a.Status == FormStatusEnum.初审通过 ||
                                                       a.Status == FormStatusEnum.资料回传已审核).CountAsync();

                    countDto.CompletedCount = await _activityformRepository.GetAll().Where(a => a.ManagerId == user.UserId && a.Status == FormStatusEnum.营销中心已审核).CountAsync();
                }
                break;

                default:
                    break;
                }

                return(countDto);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Created by us for get the users by TenantId
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <PagedResultOutput <NameValueDto> > FindUsersByTenant(FindUsersInputDto input)
        {
            if (AbpSession.TenantId != null)
            {
                //Prevent tenants to get other tenant's users.
                input.TenantId = AbpSession.TenantId;
            }

            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var query = UserManager.Users;
                if (!ReferenceEquals(input.Filters, null))
                {
                    SearchTypes mapSearchFilters = Helper.MappingFilters(input.Filters);
                    if (!ReferenceEquals(mapSearchFilters, null))
                    {
                        query = Helper.CreateFilters(query, mapSearchFilters);
                    }
                }
                var userCount = await query.CountAsync();

                var users = await query
                            .OrderBy(u => u.Name)
                            .ThenBy(u => u.Surname)
                            .PageBy(input)
                            .ToListAsync();

                return(new PagedResultOutput <NameValueDto>(
                           userCount,
                           users.Select(u =>
                                        new NameValueDto(
                                            u.FullName + " (" + u.EmailAddress + ")",
                                            u.Id.ToString()
                                            )
                                        ).ToList()
                           ));
            }
        }
Esempio n. 11
0
        public async virtual Task <IHttpActionResult> ReplaceGatherDelivery(string userName, string token, long homeOwerId, long deliveryId, string code, int?tenantId = null)
        {
            base.AuthUser();
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                var homeOwer = await _homeOwerManager.HomeOwerRepository.FirstOrDefaultAsync(homeOwerId);

                if (homeOwer == null)
                {
                    throw ErrorCodeTypeUtils.ThrowError(ErrorCodeType.HomeOwerNotExists);
                }
                var delivery = await _deliveryManager.DeliveryRepository.FirstOrDefaultAsync(deliveryId);

                if (delivery.IsGather)
                {
                    throw ErrorCodeTypeUtils.ThrowError(ErrorCodeType.DeliveryIsGathered);
                }
                if (delivery.HomeOwerId != homeOwerId)
                {
                    if (delivery.Token == code)
                    {
                        delivery.IsGather          = true;
                        delivery.GatherTime        = Clock.Now;
                        delivery.IsReplace         = true;
                        delivery.ReplaceHomeOwerId = homeOwerId;
                        delivery.Token             = string.Empty;
                        await _deliveryManager.UpdateAsync(delivery);

                        return(Ok());
                    }
                    else
                    {
                        throw ErrorCodeTypeUtils.ThrowError(ErrorCodeType.ValidateCodeError);
                    }
                }
                throw ErrorCodeTypeUtils.ThrowError(ErrorCodeType.UnknowError);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 通过报工类型获取对应的提醒策略
        /// </summary>
        /// <param name="reportType"></param>
        /// <returns></returns>
        public virtual async Task <List <Tactic> > GetActiveTacticsByReportType(ReportType reportType, int tenantId, string projectSN)
        {
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                //使用缓存优化性能
                var allTactics = await GetAllActiveTactics();

                //限制模具编号
                if (!string.IsNullOrEmpty(projectSN))
                {
                    allTactics = allTactics.Where(o => o.RemindTacticInfo == null || o.RemindTacticInfo.RemindProjectSNs.Count == 0 || o.RemindTacticInfo.RemindProjectSNs.Contains(projectSN)).ToList();
                }
                switch (reportType)
                {
                case ReportType.到料:
                    allTactics = allTactics.Where(o => o.RemindTacticInfo.EnableReceiveRemind).ToList();
                    break;

                case ReportType.机:
                    allTactics = allTactics.Where(o => o.RemindTacticInfo.EnableStartRemind).ToList();
                    break;

                case ReportType.机:
                    allTactics = allTactics.Where(o => o.RemindTacticInfo.EnableEndRemind).ToList();
                    break;

                case ReportType.加工:
                    allTactics = allTactics.Where(o => o.RemindTacticInfo.EnableProcessingRemind).ToList();
                    break;

                case ReportType.暂停:
                    allTactics = allTactics.Where(o => o.RemindTacticInfo.EnableSuspendRemind).ToList();
                    break;
                }

                return(allTactics);
            }
        }
        public async virtual Task <IHttpActionResult> GetMessages(string userName, string token, int skipCount, int maxResultCount, string sorting = null, int?tenantId = null)
        {
            base.AuthUser();
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                var homeOwerUser = await _homeOwerUserManager.GetHomeOwerUserByUserName(userName);

                if (homeOwerUser.HomeOwerId == 0)
                {
                    throw ErrorCodeTypeUtils.ThrowError(ErrorCodeType.HomeOwerNotExists);
                }
                var input = new GetMessagesInput();
                input.HomeOwerId     = homeOwerUser.HomeOwerId;
                input.MaxResultCount = maxResultCount;
                input.SkipCount      = skipCount;
                if (!string.IsNullOrEmpty(sorting))
                {
                    input.Sorting = sorting;
                }

                return(Ok(await _messageService.GetAllMessages(input)));
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 按钮信息
        /// </summary>
        /// <param name="moduleKey"></param>
        /// <returns></returns>
        public virtual async Task <IEnumerable <BtnInfoDto> > GetBtnInfos(string moduleKey)
        {
            var tenantId = AbpSession.TenantId;

            //如果是Host登录,从session中获取账套信息
            if (AbpSession.MultiTenancySide == Abp.MultiTenancy.MultiTenancySides.Host)
            {
                tenantId = _httpContextAccessor.HttpContext.Session.Get <int?>("TenantId");
            }
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                var moduleInfo = await _moduleManager.GetModuleInfo(moduleKey);

                var btns = ObjectMapper.Map <List <BtnInfoDto> >(moduleInfo.Buttons.OrderBy(o => o.Sort));
                foreach (var btn in btns)
                {
                    btn.IsForNoneRow      = btn.ButtonType.HasFlag(ButtonType.ForNoneRow);
                    btn.IsForSelectedRows = btn.ButtonType.HasFlag(ButtonType.ForSelectedRows);
                    btn.IsForSingleRow    = btn.ButtonType.HasFlag(ButtonType.ForSingleRow);
                }
                return(btns);
            }
        }
        public async Task <ActionResult> GetPaymentResult(string sessionId)
        {
            var payment = await StripePaymentAppService.GetPaymentAsync(
                new StripeGetPaymentInput
            {
                StripeSessionId = sessionId
            });

            using (CurrentUnitOfWork.SetTenantId(null))
            {
                var tenant = await _tenantManager.GetByIdAsync(payment.TenantId);

                await _stripeGatewayManager.UpdateCustomerDescriptionAsync(sessionId, tenant.TenancyName);
            }

            if (payment.TenantId != AbpSession.TenantId)
            {
                return(new NotFoundResult());
            }

            ViewBag.PaymentId = payment.Id;
            return(View());
        }
Esempio n. 16
0
        public virtual async Task <IHttpActionResult> DeleteAccessKey(string userName, string token, [FromBody] ApplyAccessKeyModel applyAccessKeyModel)
        {
            var tenantId    = applyAccessKeyModel.TenantId;
            var homeOwerId  = applyAccessKeyModel.HomeOwerId;
            var communityId = applyAccessKeyModel.CommunityId;
            var doorType    = applyAccessKeyModel.DoorType;
            var vilidity    = applyAccessKeyModel.Vilidity;

            base.AuthUser();
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                var doors = from d in _doorManager.DoorRepository.GetAll()
                            where d.DoorType == doorType.ToString() && d.IsAuth
                            select d;
                var homeOwer = await _homeOwerManager.HomeOwerRepository.FirstOrDefaultAsync(homeOwerId);

                foreach (var door in homeOwer.Doors)
                {
                    await _accessKeyManager.AccessKeyRepository.DeleteAsync(a => a.Door == door);
                }
                return(Ok());
            }
        }
Esempio n. 17
0
        public async Task UpdateRolePermissions(string tenancyName, UpdateRolePermissionsInput input)
        {
            var tenant = await _tenantManager.FindByTenancyNameAsync(tenancyName);

            if (tenant == null)
            {
                return;
            }

            using (CurrentUnitOfWork.SetTenantId(tenant.Id))
            {
                var role = await _roleManager.GetRoleByIdAsync(input.RoleId);

                await _roleManager.ResetAllPermissionsAsync(role);

                var grantedPermissions = PermissionManager
                                         .GetAllPermissions()
                                         .Where(p => input.GrantedPermissionNames.Contains(p.Name))
                                         .ToList();

                await _roleManager.SetGrantedPermissionsAsync(role, grantedPermissions);
            }
        }
Esempio n. 18
0
        public override async Task <TenantDto> UpdateAsync(TenantDto input)
        {
            var tenant = await base.UpdateAsync(input);

            using (CurrentUnitOfWork.SetTenantId(tenant.Id))
            {
                try
                {
                    var adminUser = await _userManager.FindByNameAsync(StaticRoleNames.Tenants.Admin);

                    if (adminUser.PhoneNumber != input.AdminPhoneNumber)
                    {
                        await CheckDuplicatedPhoneNumber(input.AdminPhoneNumber);

                        adminUser.PhoneNumber = input.AdminPhoneNumber;
                    }

                    if (adminUser.EmailAddress != input.AdminEmailAddress)
                    {
                        await CheckDuplicatedEmail(input.AdminEmailAddress);

                        adminUser.EmailAddress = input.AdminEmailAddress;
                    }

                    await RemoveTenantAdminCacheItem(tenant.Id);
                }
                catch (UserFriendlyException ex)
                {
                    throw ex;
                }
                catch (System.Exception)
                {
                    throw new UserFriendlyException("Can not find the admin user of tenant " + tenant.Name);
                }
            }
            return(tenant);
        }
        public async Task <UserDto> CreateUserInTenantAsync(int tenantId, CreateUserDto input)
        {
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                var user = ObjectMapper.Map <User>(input);

                user.TenantId         = AbpSession.TenantId;
                user.IsEmailConfirmed = true;

                await _userManager.InitializeOptionsAsync(AbpSession.TenantId);

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

                // if (input.RoleNames != null)
                // {
                //     CheckErrors(await _userManager.SetRolesAsync(user, input.RoleNames));
                // }

                foreach (string orgUnitName in input.OrgUnitNames)
                {
                    OrganizationUnit ou = _orgUnitRepository.FirstOrDefault(
                        ou => ou.DisplayName.ToLower() == orgUnitName.ToLower());

                    if (ou == null)
                    {
                        continue;
                    }

                    await AddUserToOuAndSetRoleAsync(user, ou);
                }

                CurrentUnitOfWork.SaveChanges();

                return(ObjectMapper.Map <UserDto>(user));
            }
        }
Esempio n. 20
0
        public void InsertInStock(int objectId, int shelfId, int sourceId, double quantity, string remark, int workerId)
        {
            using (CurrentUnitOfWork.SetTenantId(1))
            {
                var entity = new InStock()
                {
                    ObjectId     = objectId,
                    CarryoutDate = DateTime.Today,
                    ShelfId      = shelfId,
                    SourceId     = sourceId,
                    Quantity     = quantity,
                    Remark       = remark,
                    WorkerId     = workerId,
                    CreateTime   = DateTime.Now
                };

                _inStockRepository.Insert(entity);

                var shelf = _shelfRepository.Get(shelfId);
                if (!shelf.Inventory.HasValue)
                {
                    shelf.Inventory = 0;
                }
                shelf.Inventory += GetRatio(shelf, quantity);
                if (!shelf.LastInTime.HasValue || shelf.LastInTime.Value.Date != DateTime.Now.Date)
                {
                    shelf.NumInToday      = 0;
                    shelf.QuantityInToday = 0;
                }
                shelf.NumInToday      += 1;
                shelf.QuantityInToday += quantity;
                shelf.LastInTime       = DateTime.Now;

                CurrentUnitOfWork.SaveChanges();
            }
        }
        /// <summary>
        /// 对某个账套进行初始化表单
        /// </summary>
        /// <param name="tenantId"></param>
        /// <returns></returns>
        public virtual async Task InitDefaultForm(int?tenantId)
        {
            var defaultForms = Configuration.Modules.WorkFlow().DefaultForms;
            var setTenantId  = tenantId ?? AbpSession.TenantId;

            using (CurrentUnitOfWork.SetTenantId(setTenantId))
            {
                //var oriForms = await Manager.GetAll().ToListAsync();
                var oriForms = await Manager.GetAllList();

                foreach (var newForm in defaultForms)
                {
                    var oriForm = oriForms.FirstOrDefault(o => o.FormKey == newForm.FormKey);
                    if (oriForm == null)
                    {
                        var form = new FlowForm()
                        {
                            FormKey      = newForm.FormKey,
                            IsSystemForm = true,
                            FormName     = newForm.FormName,
                            FormType     = newForm.FormType
                        };
                        //var formToBeAdd = newForm.MapTo<FlowForm>();
                        //formToBeAdd.IsSystemForm = true;
                        //formToBeAdd.FormContent = "";//清空表单内容,约定当表单内容为空时读取内置表单内容
                        await Manager.InsertAsync(form);
                    }
                    //else
                    //{
                    //    //如果表单内容为空,则将默认表单内容填入
                    //    oriForm.FormContent = newForm.FormContent;
                    //}
                }
                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }
Esempio n. 22
0
        public async Task <ActivityFormForWechat> GetActivityFormList(bool check, WeChatUserListDto user)
        {
            using (CurrentUnitOfWork.SetTenantId(user.TenantId))
            {
                var query = _activityformRepository.GetAll()
                            .WhereIf(user.UserType == UserTypeEnum.内部员工, a => a.ManagerId == user.UserId)
                            .WhereIf(user.UserType == UserTypeEnum.零售客户, a => a.CreationId == user.UserId)
                            .WhereIf(check, a => a.Status == FormStatusEnum.营销中心已审核)
                            .WhereIf(!check, a => a.Status == FormStatusEnum.初审通过 || a.Status == FormStatusEnum.提交申请 || a.Status == FormStatusEnum.资料回传已审核)
                            .OrderByDescending(a => a.CreationTime);
                ActivityFormForWechat result = new ActivityFormForWechat();
                if (check)
                {
                    result.ActivityFormListDtos = query.Take(30).MapTo <List <ActivityFormListDto> >();
                }
                else
                {
                    result.ActivityFormListDtos = query.MapTo <List <ActivityFormListDto> >();
                }
                result.Count = await query.CountAsync();

                return(result.MapTo <ActivityFormForWechat>());
            }
        }
Esempio n. 23
0
        public async Task <RegisterTenantOutput> RegisterTenant(RegisterTenantInput input)
        {
            if (input.EditionId.HasValue)
            {
                await CheckEditionSubscriptionAsync(input.EditionId.Value, input.SubscriptionStartType, input.Gateway, input.PaymentId);
            }
            else
            {
                await CheckRegistrationWithoutEdition();
            }

            using (CurrentUnitOfWork.SetTenantId(null))
            {
                CheckTenantRegistrationIsEnabled();

                if (UseCaptchaOnRegistration())
                {
                    await _recaptchaValidator.ValidateAsync(input.CaptchaResponse);
                }

                //Getting host-specific settings
                var isNewRegisteredTenantActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync <bool>(AppSettings.TenantManagement.IsNewRegisteredTenantActiveByDefault);

                var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueForApplicationAsync <bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);

                DateTime?subscriptionEndDate = null;
                var      isInTrialPeriod     = false;

                if (input.EditionId.HasValue)
                {
                    isInTrialPeriod = input.SubscriptionStartType == SubscriptionStartType.Trial;

                    if (isInTrialPeriod)
                    {
                        var edition = (SubscribableEdition)await _editionManager.GetByIdAsync(input.EditionId.Value);

                        subscriptionEndDate = Clock.Now.AddDays(edition.TrialDayCount ?? 0);
                    }
                }

                var tenantId = await _tenantManager.CreateWithAdminUserAsync(
                    input.TenancyName,
                    input.Name,
                    input.AdminPassword,
                    input.AdminEmailAddress,
                    null,
                    isNewRegisteredTenantActiveByDefault,
                    input.EditionId,
                    false,
                    true,
                    subscriptionEndDate,
                    isInTrialPeriod,
                    AppUrlService.CreateEmailActivationUrlFormat(input.TenancyName)
                    );

                Tenant tenant;

                if (input.SubscriptionStartType == SubscriptionStartType.Paid)
                {
                    if (!input.Gateway.HasValue)
                    {
                        throw new Exception("Gateway is missing!");
                    }

                    var payment = await _subscriptionPaymentRepository.GetByGatewayAndPaymentIdAsync(
                        input.Gateway.Value,
                        input.PaymentId
                        );

                    tenant = await _tenantManager.UpdateTenantAsync(
                        tenantId,
                        true,
                        false,
                        payment.PaymentPeriodType,
                        payment.EditionId,
                        EditionPaymentType.NewRegistration);

                    await _subscriptionPaymentRepository.UpdateByGatewayAndPaymentIdAsync(input.Gateway.Value,
                                                                                          input.PaymentId, tenantId, SubscriptionPaymentStatus.Completed);
                }
                else
                {
                    tenant = await TenantManager.GetByIdAsync(tenantId);
                }

                await _appNotifier.NewTenantRegisteredAsync(tenant);

                if (input.EditionId.HasValue && input.Gateway.HasValue && !input.PaymentId.IsNullOrEmpty())
                {
                    _paymentCache.RemoveCacheItem(input.Gateway.Value, input.PaymentId);
                }

                return(new RegisterTenantOutput
                {
                    TenantId = tenant.Id,
                    TenancyName = input.TenancyName,
                    Name = input.Name,
                    UserName = AbpUserBase.AdminUserName,
                    EmailAddress = input.AdminEmailAddress,
                    IsActive = tenant.IsActive,
                    IsEmailConfirmationRequired = isEmailConfirmationRequiredForLogin,
                    IsTenantActive = tenant.IsActive
                });
            }
        }
Esempio n. 24
0
        public async Task <RegisterTenantOutput> RegisterTenant(RegisterTenantInput input)
        {
            if (input.EditionId.HasValue)
            {
                await CheckEditionSubscriptionAsync(input.EditionId.Value, input.SubscriptionStartType);
            }
            else
            {
                await CheckRegistrationWithoutEdition();
            }

            using (CurrentUnitOfWork.SetTenantId(null))
            {
                CheckTenantRegistrationIsEnabled();

                if (UseCaptchaOnRegistration())
                {
                    await _recaptchaValidator.ValidateAsync(input.CaptchaResponse);
                }

                //Getting host-specific settings
                var isActive = await IsNewRegisteredTenantActiveByDefault(input.SubscriptionStartType);

                var isEmailConfirmationRequired = await SettingManager.GetSettingValueForApplicationAsync <bool>(
                    AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin
                    );

                DateTime?subscriptionEndDate = null;
                var      isInTrialPeriod     = false;

                if (input.EditionId.HasValue)
                {
                    isInTrialPeriod = input.SubscriptionStartType == SubscriptionStartType.Trial;

                    if (isInTrialPeriod)
                    {
                        var edition = (SubscribableEdition)await _editionManager.GetByIdAsync(input.EditionId.Value);

                        subscriptionEndDate = Clock.Now.AddDays(edition.TrialDayCount ?? 0);
                    }
                }

                var tenantId = await _tenantManager.CreateWithAdminUserAsync(
                    input.TenancyName,
                    input.Name,
                    input.AdminPassword,
                    input.AdminEmailAddress,
                    null,
                    isActive,
                    input.EditionId,
                    shouldChangePasswordOnNextLogin : false,
                    sendActivationEmail : true,
                    subscriptionEndDate,
                    isInTrialPeriod,
                    AppUrlService.CreateEmailActivationUrlFormat(input.TenancyName)
                    );

                var tenant = await TenantManager.GetByIdAsync(tenantId);

                await _appNotifier.NewTenantRegisteredAsync(tenant);

                return(new RegisterTenantOutput
                {
                    TenantId = tenant.Id,
                    TenancyName = input.TenancyName,
                    Name = input.Name,
                    UserName = AbpUserBase.AdminUserName,
                    EmailAddress = input.AdminEmailAddress,
                    IsActive = tenant.IsActive,
                    IsEmailConfirmationRequired = isEmailConfirmationRequired,
                    IsTenantActive = tenant.IsActive
                });
            }
        }
        public virtual async Task <ActionResult> Register(RegisterTenantInput model)
        {
            try
            {
                if (UseCaptchaOnRegistration())
                {
                    model.CaptchaResponse = HttpContext.Request.Form[RecaptchaValidator.RecaptchaResponseKey];
                }

                var result = await _tenantRegistrationAppService.RegisterTenant(model);

                CurrentUnitOfWork.SetTenantId(result.TenantId);

                var user = await _userManager.FindByNameAsync(AbpUserBase.AdminUserName);

                //Directly login if possible
                if (result.IsTenantActive && result.IsActive && !result.IsEmailConfirmationRequired &&
                    !_webUrlService.SupportsTenancyNameInUrl)
                {
                    var loginResult = await GetLoginResultAsync(user.UserName, model.AdminPassword, model.TenancyName);

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await _signInManager.SignOutAsync();

                        await _signInManager.SignInAsync(loginResult.Identity, false);

                        SetTenantIdCookie(result.TenantId);

                        return(Redirect(Url.Action("Index", "Home", new { area = "AppAreaName" })));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                //Show result page
                var resultModel = ObjectMapper.Map <TenantRegisterResultViewModel>(result);

                resultModel.TenantLoginAddress = _webUrlService.SupportsTenancyNameInUrl
                    ? _webUrlService.GetSiteRootAddress(model.TenancyName).EnsureEndsWith('/') + "Account/Login"
                    : "";

                return(View("RegisterResult", resultModel));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.UseCaptcha   = UseCaptchaOnRegistration();
                ViewBag.ErrorMessage = ex.Message;

                var viewModel = new TenantRegisterViewModel
                {
                    PasswordComplexitySetting = await _passwordComplexitySettingStore.GetSettingsAsync(),
                    EditionId             = model.EditionId,
                    SubscriptionStartType = model.SubscriptionStartType,
                    EditionPaymentType    = EditionPaymentType.NewRegistration,
                    Gateway   = model.Gateway,
                    PaymentId = model.PaymentId
                };

                if (model.EditionId.HasValue)
                {
                    viewModel.Edition = await _tenantRegistrationAppService.GetEdition(model.EditionId.Value);

                    viewModel.EditionId = model.EditionId.Value;
                }

                return(View("Register", viewModel));
            }
        }
        public async Task <APIResultDto> ExchangeIntegralAsync(ExchangeIntegralDto input)
        {
            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                //获取积分配置
                var config = await GetIntegralConfig(input.TenantId);

                int?   xintegral = 0; //消费者获得积分
                int?   rintegral = 0; //零售客户获得积分
                string refIds    = string.Empty;
                foreach (var item in input.ShopProductList)
                {
                    //购买记录
                    var purchaseRecord = input.MapTo <PurchaseRecord>();
                    purchaseRecord.Integral      = (int)(item.Price * item.Num * config[DeployCodeEnum.商品购买]);
                    purchaseRecord.Quantity      = item.Num;
                    purchaseRecord.ProductId     = item.Id;
                    purchaseRecord.Specification = item.Specification;
                    purchaseRecord.Remark        = string.Format("数量{0}*指导零售价{1}*兑换比例{2}=积分{3}", item.Num, item.Price, config[DeployCodeEnum.商品购买], purchaseRecord.Integral);
                    await _purchaserecordRepository.InsertAsync(purchaseRecord);

                    await CurrentUnitOfWork.SaveChangesAsync();

                    refIds    += purchaseRecord.Id.ToString() + ",";
                    xintegral += purchaseRecord.Integral;
                    rintegral += ((int)(item.Price * item.Num * config[DeployCodeEnum.店铺扫码兑换]));
                }
                if (refIds.Length > 0)
                {
                    refIds = refIds.Substring(0, refIds.Length - 1);
                }
                //更新消费者总积分 和 积分明细
                if (xintegral > 0)
                {
                    var user = await _weChatUserRepository.GetAll().Where(u => u.OpenId == input.OpenId).FirstOrDefaultAsync();

                    var intDetail = new IntegralDetail();
                    intDetail.InitialIntegral = user.IntegralTotal;
                    intDetail.Integral        = xintegral;
                    intDetail.FinalIntegral   = user.IntegralTotal + xintegral;
                    intDetail.OpenId          = user.OpenId;
                    intDetail.RefId           = refIds;
                    intDetail.TenantId        = input.TenantId;
                    intDetail.Type            = IntegralTypeEnum.购买商品兑换;
                    intDetail.Desc            = "店铺购买商品兑换";
                    await _integralDetailRepository.InsertAsync(intDetail);

                    //await CurrentUnitOfWork.SaveChangesAsync();
                    user.IntegralTotal = intDetail.FinalIntegral.Value;
                    await _weChatUserRepository.UpdateAsync(user);

                    //发送微信模板通知-消费者
                    await PurchaseSendWXMesssageToCust(user.OpenId, input.host, user.MemberBarCode, intDetail.FinalIntegral, intDetail.Integral);
                }

                //更新店铺管理员总积分 和 积分明细
                if (rintegral > 0)
                {
                    //获取零售客户 店铺管理员
                    var shopKeeper = await _weChatUserRepository.GetAll().Where(w => w.UserId == input.RetailerId &&
                                                                                w.UserType == UserTypeEnum.零售客户 && w.IsShopkeeper == true).FirstOrDefaultAsync();

                    if (shopKeeper != null)
                    {
                        var intDetail = new IntegralDetail();
                        intDetail.InitialIntegral = shopKeeper.IntegralTotal;
                        intDetail.Integral        = rintegral;
                        intDetail.FinalIntegral   = shopKeeper.IntegralTotal + rintegral;
                        intDetail.OpenId          = shopKeeper.OpenId;
                        intDetail.RefId           = refIds;
                        intDetail.TenantId        = input.TenantId;
                        intDetail.Type            = IntegralTypeEnum.扫码积分赠送;
                        intDetail.Desc            = "店铺消费者购买商品赠送";
                        await _integralDetailRepository.InsertAsync(intDetail);

                        shopKeeper.IntegralTotal = intDetail.FinalIntegral.Value;
                        await _weChatUserRepository.UpdateAsync(shopKeeper);

                        //发送微信模板通知-店铺管理员
                        await PurchaseSendWXMesssageToShopKeeper(shopKeeper.OpenId, input.host, shopKeeper.MemberBarCode, intDetail.FinalIntegral, intDetail.Integral);
                    }
                }


                //更新店铺销量
                var shop = await _shopRepository.GetAsync(input.ShopId.Value);

                shop.ReadTotal++;                                      //人气增加
                await AddSingleTotalAsync(input.OpenId, input.ShopId); // 店铺人气查重改写

                shop.SaleTotal++;                                      //销量增加
                await _shopRepository.UpdateAsync(shop);

                //发送积分微信通知

                APIResultDto result = new APIResultDto();
                result.Code = 0;
                result.Msg  = "积分兑换成功";
                result.Data = new { RetailerIntegral = rintegral, UserIntegral = xintegral };
                return(result);
            }
        }
        private async Task <Dictionary <DeployCodeEnum?, decimal> > GetIntegralConfig(int?tenantId)
        {
            using (CurrentUnitOfWork.SetTenantId(tenantId))
            {
                //获取积分配置
                var configList = await _memberConfigRepository.GetAll().Where(c => c.Type == DeployTypeEnum.积分配置).ToListAsync();

                if (!configList.Exists(c => c.Code == DeployCodeEnum.商品评价))
                {
                    configList.Add(new MemberConfig()
                    {
                        Code  = DeployCodeEnum.商品评价,
                        Value = "5"
                    });
                }
                if (!configList.Exists(c => c.Code == DeployCodeEnum.商品购买))
                {
                    configList.Add(new MemberConfig()
                    {
                        Code  = DeployCodeEnum.商品购买,
                        Value = "1"
                    });
                }
                if (!configList.Exists(c => c.Code == DeployCodeEnum.店铺扫码兑换))
                {
                    configList.Add(new MemberConfig()
                    {
                        Code  = DeployCodeEnum.店铺扫码兑换,
                        Value = "0.5"
                    });
                }
                return(configList.ToDictionary(key => key.Code,
                                               value =>
                {
                    decimal v = 0;
                    if (!decimal.TryParse(value.Value, out v))
                    {
                        switch (value.Code)
                        {
                        case DeployCodeEnum.商品评价:
                            {
                                v = 5;
                            }
                            break;

                        case DeployCodeEnum.商品购买:
                            {
                                v = 1;
                            }
                            break;

                        case DeployCodeEnum.店铺扫码兑换:
                            {
                                v = 0.5M;
                            }
                            break;
                        }
                    }
                    return v;
                }));
            }
        }
Esempio n. 28
0
        public virtual async Task <ActionResult> Register(TenantRegistrationViewModel model)
        {
            try
            {
                CheckTenantRegistrationIsEnabled();

                if (UseCaptchaOnRegistration())
                {
                    var recaptchaHelper = this.GetRecaptchaVerificationHelper();
                    if (recaptchaHelper.Response.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("CaptchaCanNotBeEmpty"));
                    }

                    if (recaptchaHelper.VerifyRecaptchaResponse() != RecaptchaVerificationResult.Success)
                    {
                        throw new UserFriendlyException(L("IncorrectCaptchaAnswer"));
                    }
                }

                //Getting host-specific settings
                var isNewRegisteredTenantActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync <bool>(AppSettings.TenantManagement.IsNewRegisteredTenantActiveByDefault);

                var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueForApplicationAsync <bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);

                var defaultEditionIdValue = await SettingManager.GetSettingValueForApplicationAsync(AppSettings.TenantManagement.DefaultEdition);

                int?defaultEditionId = null;

                if (!string.IsNullOrEmpty(defaultEditionIdValue) && (await _editionManager.FindByIdAsync(Convert.ToInt32(defaultEditionIdValue)) != null))
                {
                    defaultEditionId = Convert.ToInt32(defaultEditionIdValue);
                }

                CurrentUnitOfWork.SetTenantId(null);

                var tenantId = await _tenantManager.CreateWithAdminUserAsync(
                    model.TenancyName,
                    model.Name,
                    model.AdminPassword,
                    model.AdminEmailAddress,
                    null,
                    isNewRegisteredTenantActiveByDefault,
                    defaultEditionId,
                    false,
                    true);

                ViewBag.UseCaptcha = UseCaptchaOnRegistration();

                var tenant = await _tenantManager.GetByIdAsync(tenantId);

                await _appNotifier.NewTenantRegisteredAsync(tenant);

                CurrentUnitOfWork.SetTenantId(tenant.Id);

                var user = await _userManager.FindByNameAsync(AbpUserBase.AdminUserName);

                //Directly login if possible
                if (tenant.IsActive && user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin))
                {
                    var loginResult = await GetLoginResultAsync(user.UserName, model.AdminPassword, tenant.TenancyName);

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await SignInAsync(loginResult.User, loginResult.Identity);

                        return(Redirect(Url.Action("Index", "Application")));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                return(View("RegisterResult", new TenantRegisterResultViewModel
                {
                    TenancyName = model.TenancyName,
                    Name = model.Name,
                    UserName = AbpUserBase.AdminUserName,
                    EmailAddress = model.AdminEmailAddress,
                    IsActive = isNewRegisteredTenantActiveByDefault,
                    IsEmailConfirmationRequired = isEmailConfirmationRequiredForLogin
                }));
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.UseCaptcha   = UseCaptchaOnRegistration();
                ViewBag.ErrorMessage = ex.Message;

                return(View("Index", model));
            }
        }
Esempio n. 29
0
        public async Task <RegisterTenantOutput> RegisterTenant(RegisterTenantInput input)
        {
            try
            {
                if (input.EditionId.HasValue)
                {
                    await CheckEditionSubscriptionAsync(input.EditionId.Value, input.SubscriptionStartType, input.Gateway, input.PaymentId);
                }
                else
                {
                    await CheckRegistrationWithoutEdition();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            try
            {
                using (CurrentUnitOfWork.SetTenantId(null))
                {
                    CheckTenantRegistrationIsEnabled();

                    if (UseCaptchaOnRegistration())
                    {
                        await _recaptchaValidator.ValidateAsync(input.CaptchaResponse);
                    }

                    //Getting host-specific settings
                    var isNewRegisteredTenantActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync <bool>(AppSettings.TenantManagement.IsNewRegisteredTenantActiveByDefault);

                    var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueForApplicationAsync <bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);

                    DateTime?subscriptionEndDate = null;
                    var      isInTrialPeriod     = false;

                    if (input.EditionId.HasValue)
                    {
                        isInTrialPeriod = input.SubscriptionStartType == SubscriptionStartType.Trial;

                        if (isInTrialPeriod)
                        {
                            var edition = (SubscribableEdition)await _editionManager.GetByIdAsync(input.EditionId.Value);

                            subscriptionEndDate = Clock.Now.AddDays(edition.TrialDayCount ?? 0);
                        }
                    }

                    var tenantId = await _tenantManager.CreateWithAdminUserAsync(
                        input.TenancyName,
                        input.Name,
                        input.AdminPassword,
                        input.AdminEmailAddress,
                        null,
                        isNewRegisteredTenantActiveByDefault,
                        input.EditionId,
                        false,
                        true,
                        subscriptionEndDate,
                        isInTrialPeriod,
                        AppUrlService.CreateEmailActivationUrlFormat(input.TenancyName),
                        input.TenantTypeId
                        );

                    Tenant tenant;

                    if (input.SubscriptionStartType == SubscriptionStartType.Paid)
                    {
                        if (!input.Gateway.HasValue)
                        {
                            throw new Exception("Gateway is missing!");
                        }

                        var payment = await _subscriptionPaymentRepository.GetByGatewayAndPaymentIdAsync(
                            input.Gateway.Value,
                            input.PaymentId
                            );

                        tenant = await _tenantManager.UpdateTenantAsync(
                            tenantId,
                            true,
                            false,
                            payment.PaymentPeriodType,
                            payment.EditionId,
                            EditionPaymentType.NewRegistration);

                        await _subscriptionPaymentRepository.UpdateByGatewayAndPaymentIdAsync(input.Gateway.Value,
                                                                                              input.PaymentId, tenantId, SubscriptionPaymentStatus.Completed);
                    }
                    else
                    {
                        tenant = await TenantManager.GetByIdAsync(tenantId);
                    }

                    await _appNotifier.NewTenantRegisteredAsync(tenant);

                    if (input.EditionId.HasValue && input.Gateway.HasValue && !input.PaymentId.IsNullOrEmpty())
                    {
                        _paymentCache.RemoveCacheItem(input.Gateway.Value, input.PaymentId);
                    }



                    CreateMileInputDto mob = new CreateMileInputDto();
                    mob.Code        = "LD";
                    mob.Name        = "Lead";
                    mob.TenantId    = tenantId;
                    mob.Id          = 0;
                    mob.IsQuotation = false;
                    var milestone2 = mob.MapTo <MileStone>();
                    await _MilestoneRepository.InsertAsync(milestone2);

                    CreateMileInputDto mobj = new CreateMileInputDto();
                    mobj.Code        = "QL";
                    mobj.Name        = "Qualified";
                    mobj.TenantId    = tenantId;
                    mobj.Id          = 0;
                    mobj.IsQuotation = false;
                    var milestone = mobj.MapTo <MileStone>();
                    await _MilestoneRepository.InsertAsync(milestone);

                    CreateMileInputDto QT = new CreateMileInputDto();
                    QT.Code        = "QT";
                    QT.Name        = "Qouted";
                    QT.TenantId    = tenantId;
                    QT.Id          = 0;
                    QT.IsQuotation = true;
                    var Qouted = QT.MapTo <MileStone>();
                    await _MilestoneRepository.InsertAsync(Qouted);

                    CreateMileInputDto NG = new CreateMileInputDto();
                    NG.Code        = "NG";
                    NG.Name        = "Negotiation";
                    NG.TenantId    = tenantId;
                    NG.Id          = 0;
                    NG.IsQuotation = true;
                    var Negotiation = NG.MapTo <MileStone>();
                    await _MilestoneRepository.InsertAsync(Negotiation);

                    CreateMileInputDto CL = new CreateMileInputDto();
                    CL.Code        = "CL";
                    CL.Name        = "Closed";
                    CL.TenantId    = tenantId;
                    CL.Id          = 0;
                    CL.IsQuotation = true;
                    var Closed = CL.MapTo <MileStone>();
                    await _MilestoneRepository.InsertAsync(Closed);

                    CreateQuotationStatusInput QS1 = new CreateQuotationStatusInput();
                    QS1.QuotationStatusCode = "NW";
                    QS1.QuotationStatusName = "New";
                    QS1.New      = true;
                    QS1.TenantId = tenantId;
                    QS1.Id       = 0;
                    var QS1s = QS1.MapTo <QuotationStatus>();
                    await _QuotationStatusRepository.InsertAsync(QS1s);

                    CreateQuotationStatusInput QS2 = new CreateQuotationStatusInput();
                    QS2.QuotationStatusCode = "SU";
                    QS2.QuotationStatusName = "Submitted";
                    QS2.Submitted           = true;
                    QS2.TenantId            = tenantId;
                    QS2.Id = 0;
                    var QS2s = QS2.MapTo <QuotationStatus>();
                    await _QuotationStatusRepository.InsertAsync(QS2s);

                    CreateQuotationStatusInput QS3 = new CreateQuotationStatusInput();
                    QS3.QuotationStatusCode = "WO";
                    QS3.QuotationStatusName = "Won";
                    QS3.Won      = true;
                    QS3.TenantId = tenantId;
                    QS3.Id       = 0;
                    var QS3s = QS3.MapTo <QuotationStatus>();
                    await _QuotationStatusRepository.InsertAsync(QS3s);

                    CreateQuotationStatusInput QS4 = new CreateQuotationStatusInput();
                    QS4.QuotationStatusCode = "LO";
                    QS4.QuotationStatusName = "Lost";
                    QS4.Lost     = true;
                    QS4.TenantId = tenantId;
                    QS4.Id       = 0;
                    var QS4s = QS4.MapTo <QuotationStatus>();
                    await _QuotationStatusRepository.InsertAsync(QS4s);

                    CreateQuotationStatusInput QS5 = new CreateQuotationStatusInput();
                    QS5.QuotationStatusCode = "RE";
                    QS5.QuotationStatusName = "Revised";
                    QS5.Revised             = true;
                    QS5.TenantId            = tenantId;
                    QS5.Id = 0;
                    var QS5s = QS5.MapTo <QuotationStatus>();
                    await _QuotationStatusRepository.InsertAsync(QS5s);


                    return(new RegisterTenantOutput
                    {
                        TenantId = tenant.Id,
                        TenancyName = input.TenancyName,
                        Name = input.Name,
                        UserName = AbpUserBase.AdminUserName,
                        EmailAddress = input.AdminEmailAddress,
                        IsActive = tenant.IsActive,
                        IsEmailConfirmationRequired = isEmailConfirmationRequiredForLogin,
                        IsTenantActive = tenant.IsActive
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 30
0
        public async Task MarkAllUnreadMessagesOfUserAsRead(MarkAllUnreadMessagesOfUserAsReadInput input)
        {
            var userId   = AbpSession.GetUserId();
            var tenantId = AbpSession.TenantId;

            // receiver messages
            var messages = await _chatMessageRepository
                           .GetAll()
                           .Where(m =>
                                  m.UserId == userId &&
                                  m.TargetTenantId == input.TenantId &&
                                  m.TargetUserId == input.UserId &&
                                  m.ReadState == ChatMessageReadState.Unread)
                           .ToListAsync();

            if (!messages.Any())
            {
                return;
            }

            foreach (var message in messages)
            {
                message.ChangeReadState(ChatMessageReadState.Read);
            }

            // sender messages
            using (CurrentUnitOfWork.SetTenantId(input.TenantId))
            {
                var reverseMessages = await _chatMessageRepository.GetAll()
                                      .Where(m => m.UserId == input.UserId && m.TargetTenantId == tenantId && m.TargetUserId == userId)
                                      .ToListAsync();

                if (!reverseMessages.Any())
                {
                    return;
                }

                foreach (var message in reverseMessages)
                {
                    message.ChangeReceiverReadState(ChatMessageReadState.Read);
                }
            }

            var userIdentifier   = AbpSession.ToUserIdentifier();
            var friendIdentifier = input.ToUserIdentifier();

            _userFriendsCache.ResetUnreadMessageCount(userIdentifier, friendIdentifier);

            var onlineUserClients = _onlineClientManager.GetAllByUserId(userIdentifier);

            if (onlineUserClients.Any())
            {
                await _chatCommunicator.SendAllUnreadMessagesOfUserReadToClients(onlineUserClients, friendIdentifier);
            }

            var onlineFriendClients = _onlineClientManager.GetAllByUserId(friendIdentifier);

            if (onlineFriendClients.Any())
            {
                await _chatCommunicator.SendReadStateChangeToClients(onlineFriendClients, userIdentifier);
            }
        }