예제 #1
0
        public virtual async Task <Order> GenerateAsync(CreateOrderDto input, Dictionary <Guid, ProductDto> productDict)
        {
            var orderLines = new List <OrderLine>();

            foreach (var orderLine in input.OrderLines)
            {
                orderLines.Add(await GenerateNewOrderLineAsync(orderLine, productDict));
            }

            var productTotalPrice = orderLines.Select(x => x.TotalPrice).Sum();

            var order = new Order(
                id: _guidGenerator.Create(),
                tenantId: _currentTenant.Id,
                storeId: input.StoreId,
                customerUserId: _currentUser.GetId(),
                currency: await GetStoreCurrencyAsync(input.StoreId),
                productTotalPrice: productTotalPrice,
                totalDiscount: orderLines.Select(x => x.TotalDiscount).Sum(),
                totalPrice: productTotalPrice,
                refundedAmount: 0,
                customerRemark: input.CustomerRemark);

            order.SetOrderLines(orderLines);

            return(order);
        }
        public virtual async Task HandleEventAsync(CreatePaymentEto eventData)
        {
            var providerType = _paymentServiceResolver.GetProviderTypeOrDefault(eventData.PaymentMethod) ??
                               throw new UnknownPaymentMethodException(eventData.PaymentMethod);

            var provider = _serviceProvider.GetService(providerType) as IPaymentServiceProvider ??
                           throw new UnknownPaymentMethodException(eventData.PaymentMethod);

            var paymentItems = eventData.PaymentItems.Select(inputPaymentItem =>
                                                             new PaymentItem(_guidGenerator.Create(), inputPaymentItem.ItemType, inputPaymentItem.ItemKey,
                                                                             inputPaymentItem.Currency, inputPaymentItem.OriginalPaymentAmount)).ToList();

            if (paymentItems.Select(item => item.Currency).Any(c => c != eventData.Currency))
            {
                throw new MultiCurrencyNotSupportedException();
            }

            if (await HasDuplicatePaymentItemInProgressAsync(paymentItems))
            {
                throw new DuplicatePaymentRequestException();
            }

            var payment = new Payment(_guidGenerator.Create(), eventData.TenantId, eventData.UserId,
                                      eventData.PaymentMethod, eventData.Currency, paymentItems.Select(item => item.OriginalPaymentAmount).Sum(),
                                      paymentItems);

            foreach (var property in eventData.ExtraProperties)
            {
                payment.SetProperty(property.Key, property.Value);
            }

            await _paymentRepository.InsertAsync(payment, autoSave : true);
        }
예제 #3
0
        public async Task SeedAsync(DataSeedContext context)
        {
            if (await _expenseRepository.GetCountAsync() > 0)
            {
                return;
            }

            await _expenseRepository.InsertAsync(
                new Expense(
                    id : _guidGenerator.Create(),
                    title : "油费",
                    type : ExpenseType.Traffic,
                    onDate : new DateTime(2020, 6, 12),
                    amount : 260
                    )
                );

            await _expenseRepository.InsertAsync(
                new Expense(
                    id : _guidGenerator.Create(),
                    title : "Microsoft 365订阅",
                    type : ExpenseType.Subscription,
                    onDate : new DateTime(2020, 6, 11),
                    amount : 215
                    )
                );
        }
예제 #4
0
        private async Task <ApiResource> CreateApiResourceAsync(string name, IEnumerable <string> claims)
        {
            var apiResource = await _apiResourceRepository.FindByNameAsync(name);

            if (apiResource == null)
            {
                apiResource = await _apiResourceRepository.InsertAsync(
                    new ApiResource(
                        _guidGenerator.Create(),
                        name,
                        name + " API"
                        ),
                    autoSave : true
                    );
            }

            foreach (var claim in claims)
            {
                if (apiResource.FindClaim(claim) == null)
                {
                    apiResource.AddUserClaim(claim);
                }
            }

            return(await _apiResourceRepository.UpdateAsync(apiResource));
        }
예제 #5
0
        public async Task SeedAsync(DataSeedContext context)
        {
            if (await _bookRepository.GetCountAsync() > 0)
            {
                return;
            }

            await _bookRepository.InsertAsync(
                new Book(
                    id : _guidGenerator.Create(),
                    name : "1984",
                    type : BookType.Dystopia,
                    publishDate : new DateTime(1949, 6, 8),
                    price : 19.84f)
                );

            await _bookRepository.InsertAsync(
                new Book(
                    id : _guidGenerator.Create(),
                    name : "The Hitchhiker's Guide to the Galaxy",
                    type : BookType.ScienceFiction,
                    publishDate : new DateTime(1995, 9, 27),
                    price : 42.0f
                    )
                );
        }
        public async Task SeedAsync(DataSeedContext context)
        {
            if (await _dataDictionaryRepository.GetCountAsync() == 0)
            {
                var dict1 = new Dict(_guidGenerator.Create(),
                                     context.TenantId,
                                     "Sex",
                                     "性别",
                                     "性别信息。",
                                     new List <DataDictionaryItem>());
                dict1.AddOrUpdateItem("1", "男", "男性");
                dict1.AddOrUpdateItem("2", "女", "女性");
                dict1.AddOrUpdateItem("3", "未知", "未知性别");

                var dict2 = new Dict(_guidGenerator.Create(),
                                     context.TenantId,
                                     "Level",
                                     "等级",
                                     "等级信息",
                                     new List <DataDictionaryItem>());
                dict2.AddOrUpdateItem("1", "一级", "一级");
                dict2.AddOrUpdateItem("2", "二级", "二级");
                dict2.AddOrUpdateItem("3", "三级", "三级");
                dict2.AddOrUpdateItem("4", "四级", "四级");

                await _dataDictionaryRepository.InsertAsync(dict1);

                await _dataDictionaryRepository.InsertAsync(dict2);
            }
        }
예제 #7
0
        public async Task SeedAsync(DataSeedContext context)
        {
            /* Instead of returning the Task.CompletedTask, you can insert your test data
             * at this point!
             */
            var fdName = new FieldDefinition(_guidGenerator.Create(), "name", "Name", "string");
            await _fieldDefinitionRepository.InsertAsync(fdName);

            var fdPrice = new FieldDefinition(_guidGenerator.Create(), "price", "Price", "number");
            await _fieldDefinitionRepository.InsertAsync(fdPrice);

            var mdBook = new ModelDefinition(_guidGenerator.Create(), "book", "Book", "DynamicEntity.Book");

            mdBook.AddField(fdPrice.Id, 2);
            mdBook.AddField(fdName.Id, 1);
            await _modelDefinitionRepository.InsertAsync(mdBook);

            var deBook1 = new DynamicEntities.DynamicEntity(_guidGenerator.Create());

            deBook1.SetModelDefinition(mdBook.Id);
            deBook1.SetProperty("name", "Book1");
            deBook1.SetProperty("price", 100.00f);
            await _dynamicEntityRepository.InsertAsync(deBook1);

            var deBook2 = new DynamicEntities.DynamicEntity(_guidGenerator.Create());

            deBook2.SetModelDefinition(mdBook.Id);
            deBook2.SetProperty("name", "Book2");
            deBook2.SetProperty("price", 200.00f);
            await _dynamicEntityRepository.InsertAsync(deBook2);
        }
예제 #8
0
        private async Task <ApiResource> CreateApiResourceAsync(string name, IEnumerable <string> claims)
        {
            var apiResource = await _apiResourceRepository.FindByNameAsync(name);

            if (apiResource == null)
            {
                apiResource = await _apiResourceRepository.InsertAsync(
                    new ApiResource(
                        _guidGenerator.Create(),
                        name,
                        name + " API"
                        ),
                    autoSave : true
                    );
            }

            foreach (var claim in claims)
            {
                if (apiResource.FindClaim(claim) == null)
                {
                    apiResource.AddUserClaim(claim);
                }
            }
            var secret = "123456".Sha256();

            if (!apiResource.Secrets.Any(p => p.Value == secret))
            {
                apiResource.AddSecret(secret);
            }
            return(await _apiResourceRepository.UpdateAsync(apiResource));
        }
        public async Task SeedAsync(DataSeedContext context)
        {
            await _bookRepository.InsertAsync(
                new Book
            {
                Id          = _guidGenerator.Create(),
                Name        = "Test book 1",
                Type        = BookType.Fantasy,
                PublishDate = new DateTime(2015, 05, 24),
                Price       = 21
            }
                );

            await _bookRepository.InsertAsync(
                new Book
            {
                Id          = _guidGenerator.Create(),
                Name        = "Test book 2",
                Type        = BookType.Science,
                PublishDate = new DateTime(2014, 02, 11),
                Price       = 15
            }
                );

            await _bookRepository.InsertAsync(
                new Book
            {
                Id          = _guidGenerator.Create(),
                Name        = "Test book 3",
                Type        = BookType.Poetry,
                PublishDate = new DateTime(2014, 02, 11),
                Price       = 20
            }
                );
        }
예제 #10
0
        public virtual async Task HandleEventAsync(WeChatPayRefundEto eventData)
        {
            // Todo: Handle errors and rollback
            using (_currentTenant.Change(eventData.TenantId))
            {
                var payment = await _paymentRepository.GetAsync(eventData.PaymentId);

                var paymentRecord = await _paymentRecordRepository.GetByPaymentId(eventData.PaymentId);

                var refundRecordId = _guidGenerator.Create();

                var dict = await RequestWeChatPayRefundAsync(payment, paymentRecord, eventData, refundRecordId.ToString());

                var externalTradingCode = dict.GetOrDefault("refund_id");

                foreach (var refund in eventData.Refunds)
                {
                    refund.SetExternalTradingCode(externalTradingCode);

                    await _refundRepository.UpdateAsync(refund, true);
                }

                if (dict.GetOrDefault("result_code") != "SUCCESS")
                {
                    await _paymentManager.RollbackRefundAsync(payment, eventData.Refunds);
                }
            }
        }
예제 #11
0
    public async Task BuildAsync()
    {
        await _settingRepository.InsertAsync(
            new Setting(
                _testData.SettingId,
                "MySetting1",
                "42",
                GlobalSettingValueProvider.ProviderName
                )
            );

        await _settingRepository.InsertAsync(
            new Setting(
                _guidGenerator.Create(),
                "MySetting2",
                "default-store-value",
                GlobalSettingValueProvider.ProviderName
                )
            );

        await _settingRepository.InsertAsync(
            new Setting(
                _guidGenerator.Create(),
                "MySetting2",
                "user1-store-value",
                UserSettingValueProvider.ProviderName,
                _testData.User1Id.ToString()
                )
            );

        await _settingRepository.InsertAsync(
            new Setting(
                _guidGenerator.Create(),
                "MySetting2",
                "user2-store-value",
                UserSettingValueProvider.ProviderName,
                _testData.User2Id.ToString()
                )
            );

        await _settingRepository.InsertAsync(
            new Setting(
                _guidGenerator.Create(),
                "MySettingWithoutInherit",
                "default-store-value",
                GlobalSettingValueProvider.ProviderName
                )
            );

        await _settingRepository.InsertAsync(
            new Setting(
                _guidGenerator.Create(),
                "MySettingWithoutInherit",
                "user1-store-value",
                UserSettingValueProvider.ProviderName,
                _testData.User1Id.ToString()
                )
            );
    }
        public void Build()
        {
            _settingRepository.Insert(
                new Setting(
                    _testData.SettingId,
                    "MySetting1",
                    "42",
                    GlobalSettingValueProvider.ProviderName
                    )
                );

            _settingRepository.Insert(
                new Setting(
                    _guidGenerator.Create(),
                    "MySetting2",
                    "default-store-value",
                    GlobalSettingValueProvider.ProviderName
                    )
                );

            _settingRepository.Insert(
                new Setting(
                    _guidGenerator.Create(),
                    "MySetting2",
                    "user1-store-value",
                    "User",
                    _testData.User1Id.ToString()
                    )
                );

            _settingRepository.Insert(
                new Setting(
                    _guidGenerator.Create(),
                    "MySetting2",
                    "user2-store-value",
                    "User",
                    _testData.User2Id.ToString()
                    )
                );

            _settingRepository.Insert(
                new Setting(
                    _guidGenerator.Create(),
                    "MySettingWithoutInherit",
                    "default-store-value",
                    GlobalSettingValueProvider.ProviderName
                    )
                );

            _settingRepository.Insert(
                new Setting(
                    _guidGenerator.Create(),
                    "MySettingWithoutInherit",
                    "user1-store-value",
                    "User",
                    _testData.User1Id.ToString()
                    )
                );
        }
        public async Task SeedAsync(DataSeedContext context)
        {
            await _bookRepository.InsertAsync(
                new Book(_guidGenerator.Create(), "Test book 1", BookType.Fantastic, new DateTime(2015, 05, 24), 21));

            await _bookRepository.InsertAsync(
                new Book(_guidGenerator.Create(), "Test book 2", BookType.Science, new DateTime(2014, 02, 11), 15));
        }
        public virtual async Task <string> CreateEventSubscription(EventSubscription subscription)
        {
            subscription.Id = _guidGenerator.Create().ToString();
            var persistable = subscription.ToPersistable();
            await _eventSubscriptionRepository.InsertAsync(persistable);

            return(subscription.Id);
        }
예제 #15
0
        public virtual async Task <IdentityDataSeedResult> SeedAsync(
            string adminEmail,
            string adminPassword,
            Guid?tenantId = null)
        {
            Check.NotNullOrWhiteSpace(adminEmail, nameof(adminEmail));
            Check.NotNullOrWhiteSpace(adminPassword, nameof(adminPassword));

            var result = new IdentityDataSeedResult();

            //"admin" user
            const string adminUserName = "******";
            var          adminUser     = await _userRepository.FindByNormalizedUserNameAsync(
                _lookupNormalizer.NormalizeName(adminUserName)
                );

            if (adminUser != null)
            {
                return(result);
            }

            adminUser = new IdentityUser(
                _guidGenerator.Create(),
                adminUserName,
                adminEmail,
                tenantId
                )
            {
                Name = adminUserName
            };

            (await _userManager.CreateAsync(adminUser, adminPassword)).CheckErrors();
            result.CreatedAdminUser = true;

            //"admin" role
            const string adminRoleName = "admin";
            var          adminRole     = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName(adminRoleName));

            if (adminRole == null)
            {
                adminRole = new IdentityRole(
                    _guidGenerator.Create(),
                    adminRoleName,
                    tenantId
                    )
                {
                    IsStatic = true,
                    IsPublic = true
                };

                (await _roleManager.CreateAsync(adminRole)).CheckErrors();
                result.CreatedAdminRole = true;
            }

            (await _userManager.AddToRoleAsync(adminUser, adminRoleName)).CheckErrors();

            return(result);
        }
예제 #16
0
        public virtual async Task PublishAsync(
            string notificationName,
            NotificationData data             = null,
            EntityIdentifier entityIdentifier = null,
            NotificationSeverity severity     = NotificationSeverity.Info,
            UserIdentifier[] userIds          = null,
            UserIdentifier[] excludedUserIds  = null,
            int?[] tenantIds = null)
        {
            if (notificationName.IsNullOrEmpty())
            {
                throw new ArgumentException("NotificationName can not be null or whitespace!", nameof(notificationName));
            }

            if (!tenantIds.IsNullOrEmpty() && !userIds.IsNullOrEmpty())
            {
                throw new ArgumentException("tenantIds can be set only if userIds is not set!", nameof(tenantIds));
            }

            if (tenantIds.IsNullOrEmpty() && userIds.IsNullOrEmpty())
            {
                tenantIds = new[] { AbpSession.TenantId };
            }

            var notificationInfo = new NotificationInfo(_guidGenerator.Create())
            {
                NotificationName = notificationName,
                EntityTypeName   = entityIdentifier?.Type.FullName,
                EntityTypeAssemblyQualifiedName = entityIdentifier?.Type.AssemblyQualifiedName,
                EntityId        = entityIdentifier?.Id.ToJsonString(),
                Severity        = severity,
                UserIds         = userIds.IsNullOrEmpty() ? null : userIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                ExcludedUserIds = excludedUserIds.IsNullOrEmpty() ? null : excludedUserIds.Select(uid => uid.ToUserIdentifierString()).JoinAsString(","),
                TenantIds       = GetTenantIdsAsStr(tenantIds),
                Data            = data?.ToJsonString(),
                DataTypeName    = data?.GetType().AssemblyQualifiedName
            };

            await _store.InsertNotificationAsync(notificationInfo);

            await CurrentUnitOfWork.SaveChangesAsync(); //To get Id of the notification

            if (userIds != null && userIds.Length <= MaxUserCountToDirectlyDistributeANotification)
            {
                //We can directly distribute the notification since there are not much receivers
                await _notificationDistributer.DistributeAsync(notificationInfo.Id);
            }
            else
            {
                //We enqueue a background job since distributing may get a long time
                await _backgroundJobManager.EnqueueAsync <NotificationDistributionJob, NotificationDistributionJobArgs>(
                    new NotificationDistributionJobArgs(
                        notificationInfo.Id
                        )
                    );
            }
        }
        public override async Task OnPaymentStartedAsync(Payment payment, ExtraPropertyDictionary configurations)
        {
            if (payment.ActualPaymentAmount <= decimal.Zero)
            {
                throw new PaymentAmountInvalidException(payment.ActualPaymentAmount, PaymentMethod);
            }

            if (!Guid.TryParse(configurations.GetOrDefault("AccountId") as string, out var accountId))
            {
                throw new ArgumentNullException("AccountId");
            }

            var account = await _accountRepository.GetAsync(accountId);

            if (account.UserId != _currentUser.GetId())
            {
                throw new UserIsNotAccountOwnerException(_currentUser.GetId(), accountId);
            }

            payment.SetProperty("AccountId", accountId);

            var accountGroupConfiguration = _accountGroupConfigurationProvider.Get(account.AccountGroupName);

            if (!accountGroupConfiguration.AllowedUsingToTopUpOtherAccounts &&
                payment.PaymentItems.Any(x => x.ItemType == PrepaymentConsts.TopUpPaymentItemType))
            {
                throw new AccountTopingUpOtherAccountsIsNotAllowedException(account.AccountGroupName);
            }

            if (payment.PaymentItems.Any(x =>
                                         x.ItemType == PrepaymentConsts.TopUpPaymentItemType && x.ItemKey == accountId.ToString()))
            {
                throw new SelfTopUpException();
            }

            if (payment.Currency != accountGroupConfiguration.Currency)
            {
                throw new CurrencyNotSupportedException(payment.Currency);
            }

            var accountChangedBalance = -1 * payment.ActualPaymentAmount;

            var transaction = new Transaction(_guidGenerator.Create(), _currentTenant.Id, account.Id, account.UserId,
                                              payment.Id, TransactionType.Credit, PrepaymentConsts.PaymentActionName, payment.PaymentMethod,
                                              payment.ExternalTradingCode, accountGroupConfiguration.Currency, accountChangedBalance,
                                              account.Balance);

            await _transactionRepository.InsertAsync(transaction, true);

            account.ChangeBalance(accountChangedBalance);

            await _accountRepository.UpdateAsync(account, true);

            await _paymentManager.CompletePaymentAsync(payment);

            await _paymentRepository.UpdateAsync(payment, true);
        }
 private async Task CreateGuildsAsync()
 {
     var guild = new AppGuild(_guidGenerator.Create(), "someone foo")
     {
         Compacity = 200,
         Desc      = "guild tester created"
     };
     await _guilds.InsertAsync(guild, true);
 }
예제 #19
0
        private async Task CreateWeChatClaimTypeAsync()
        {
            if (!await _identityClaimTypeRepository.AnyAsync(WeChatValidatorConsts.ClaimTypes.OpenId))
            {
                var wechatClaimType = new IdentityClaimType(_guidGenerator.Create(), WeChatValidatorConsts.ClaimTypes.OpenId,
                                                            isStatic: true, description: "适用于微信认证的用户标识");

                await _identityClaimTypeRepository.InsertAsync(wechatClaimType);
            }
        }
        private void AddPersistedGrants()
        {
            _persistentGrantRepository.Insert(new PersistedGrant(_guidGenerator.Create())
            {
                Key       = "PersistedGrantKey1",
                SubjectId = "PersistedGrantSubjectId1",
                ClientId  = "PersistedGrantClientId1",
                Type      = "PersistedGrantType1",
                Data      = ""
            });

            _persistentGrantRepository.Insert(new PersistedGrant(_guidGenerator.Create())
            {
                Key       = "PersistedGrantKey2",
                SubjectId = "PersistedGrantSubjectId2",
                ClientId  = "c1",
                Type      = "c1type",
                Data      = ""
            });

            _persistentGrantRepository.Insert(new PersistedGrant(_guidGenerator.Create())
            {
                Key       = "PersistedGrantKey3",
                SubjectId = "PersistedGrantSubjectId3",
                ClientId  = "c1",
                Type      = "c1type",
                Data      = ""
            });
        }
예제 #21
0
        private async Task AddRoles()
        {
            _adminRole = await _roleRepository.FindByNormalizedNameAsync(_lookupNormalizer.NormalizeName("admin")).ConfigureAwait(false);

            _moderator = new IdentityRole(_testData.RoleModeratorId, "moderator");
            _moderator.AddClaim(_guidGenerator, new Claim("test-claim", "test-value"));
            await _roleRepository.InsertAsync(_moderator).ConfigureAwait(false);

            _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter");
            await _roleRepository.InsertAsync(_supporterRole).ConfigureAwait(false);
        }
예제 #22
0
        private void AddRoles()
        {
            _adminRole = _roleRepository.FindByNormalizedName(_lookupNormalizer.NormalizeName("admin"));

            _moderator = new IdentityRole(_testData.RoleModeratorId, "moderator");
            _moderator.AddClaim(_guidGenerator, new Claim("test-claim", "test-value"));
            _roleRepository.Insert(_moderator);

            _supporterRole = new IdentityRole(_guidGenerator.Create(), "supporter");
            _roleRepository.Insert(_supporterRole);
        }
예제 #23
0
        public virtual async Task HandleEventAsync(CreateSmsNotificationEto eventData)
        {
            var notificationInfo = new NotificationInfo(_guidGenerator.Create(), _currentTenant.Id);

            notificationInfo.SetSmsData(eventData.Text, eventData.Properties);

            await _notificationInfoRepository.InsertAsync(notificationInfo, true);

            var notifications = await CreateNotificationsAsync(notificationInfo, eventData.UserIds);

            await SendNotificationsAsync(notifications);
        }
예제 #24
0
        public virtual async Task HandleEventAsync(CreateEmailNotificationEto eventData)
        {
            var notificationInfo = new NotificationInfo(_guidGenerator.Create(), _currentTenant.Id);

            notificationInfo.SetMailingData(eventData.Subject, eventData.Body);

            await _notificationInfoRepository.InsertAsync(notificationInfo, true);

            var notifications = await CreateNotificationsAsync(notificationInfo, eventData.UserIds);

            await SendNotificationsAsync(notifications);
        }
예제 #25
0
파일: AuditLog.cs 프로젝트: zjc-china/abp
        public AuditLog(IGuidGenerator guidGenerator, AuditLogInfo auditInfo)
            : base(guidGenerator.Create())
        {
            ApplicationName   = auditInfo.ApplicationName.Truncate(AuditLogConsts.MaxApplicationNameLength);
            TenantId          = auditInfo.TenantId;
            TenantName        = auditInfo.TenantName.Truncate(AuditLogConsts.MaxTenantNameLength);
            UserId            = auditInfo.UserId;
            UserName          = auditInfo.UserName.Truncate(AuditLogConsts.MaxUserNameLength);
            ExecutionTime     = auditInfo.ExecutionTime;
            ExecutionDuration = auditInfo.ExecutionDuration;
            ClientIpAddress   = auditInfo.ClientIpAddress.Truncate(AuditLogConsts.MaxClientIpAddressLength);
            ClientName        = auditInfo.ClientName.Truncate(AuditLogConsts.MaxClientNameLength);
            ClientId          = auditInfo.ClientId.Truncate(AuditLogConsts.MaxClientIdLength);
            CorrelationId     = auditInfo.CorrelationId.Truncate(AuditLogConsts.MaxCorrelationIdLength);
            BrowserInfo       = auditInfo.BrowserInfo.Truncate(AuditLogConsts.MaxBrowserInfoLength);
            HttpMethod        = auditInfo.HttpMethod.Truncate(AuditLogConsts.MaxHttpMethodLength);
            Url                  = auditInfo.Url.Truncate(AuditLogConsts.MaxUrlLength);
            HttpStatusCode       = auditInfo.HttpStatusCode;
            ImpersonatorUserId   = auditInfo.ImpersonatorUserId;
            ImpersonatorTenantId = auditInfo.ImpersonatorTenantId;

            ExtraProperties = new ExtraPropertyDictionary();
            if (auditInfo.ExtraProperties != null)
            {
                foreach (var pair in auditInfo.ExtraProperties)
                {
                    ExtraProperties.Add(pair.Key, pair.Value);
                }
            }

            EntityChanges = auditInfo
                            .EntityChanges?
                            .Select(entityChangeInfo => new EntityChange(guidGenerator, Id, entityChangeInfo, tenantId: auditInfo.TenantId))
                            .ToList()
                            ?? new List <EntityChange>();

            Actions = auditInfo
                      .Actions?
                      .Select(auditLogActionInfo => new AuditLogAction(guidGenerator.Create(), Id, auditLogActionInfo, tenantId: auditInfo.TenantId))
                      .ToList()
                      ?? new List <AuditLogAction>();

            Exceptions = auditInfo
                         .Exceptions?
                         .JoinAsString(Environment.NewLine)
                         .Truncate(AuditLogConsts.MaxExceptionsLengthValue);

            Comments = auditInfo
                       .Comments?
                       .JoinAsString(Environment.NewLine)
                       .Truncate(AuditLogConsts.MaxCommentsLength);
        }
예제 #26
0
        public async Task SeedAsync(DataSeedContext context)
        {
            var fdPrice = await _fieldDefinitionRepository.FindAsync(fd => fd.Name == "price");

            if (fdPrice == null)
            {
                fdPrice = await _fieldDefinitionRepository.InsertAsync(new FieldDefinition(_guidGenerator.Create(), "price", "Price", "number"));
            }

            var fdCpu = await _fieldDefinitionRepository.FindAsync(fd => fd.Name == "CPU");

            if (fdCpu == null)
            {
                fdCpu = await _fieldDefinitionRepository.InsertAsync(new FieldDefinition(_guidGenerator.Create(), "cpu", "CPU", "string"));
            }

            var fdRam = await _fieldDefinitionRepository.FindAsync(fd => fd.Name == "ram");

            if (fdRam == null)
            {
                fdRam = await _fieldDefinitionRepository.InsertAsync(new FieldDefinition(_guidGenerator.Create(), "ram", "RAM", "string"));
            }

            var mdComputer = await _modelDefinitionRepository.FindAsync(md => md.Name == "computer");

            if (mdComputer == null)
            {
                mdComputer = new ModelDefinition(_guidGenerator.Create(), "computer", "Computer", "DynamicEntitySample.Computer");
                mdComputer.AddField(fdCpu.Id, 1);
                mdComputer.AddField(fdRam.Id, 2);
                mdComputer.AddField(fdPrice.Id, 3);
                await _modelDefinitionRepository.InsertAsync(mdComputer);
            }

            var deComputer = await _dynamicEntityRepository.FindAsync(de => de.ModelDefinitionId == mdComputer.Id);

            if (deComputer == null)
            {
                var cpus   = new[] { "Intel I3", "Intel I5", "Intel I7", "Intel I9" };
                var rams   = new[] { "4GB", "8GB", "16GB", "32GB" };
                var prices = new[] { "999", "1999", "2999", "3999" };
                var rnd    = new Random();
                for (int i = 0; i < 30000; i++)
                {
                    var entity = new DynamicEntity(_guidGenerator.Create()).SetModelDefinition(mdComputer.Id);
                    entity.SetProperty("cpu", cpus[rnd.Next() % cpus.Length]);
                    entity.SetProperty("ram", rams[rnd.Next() % rams.Length]);
                    entity.SetProperty("price", prices[rnd.Next() % prices.Length]);
                    await _dynamicEntityRepository.InsertAsync(entity);
                }
            }
        }
예제 #27
0
        /// <summary>
        /// 初始化角色
        /// </summary>
        /// <returns></returns>
        private async Task CreateRoleAsync()
        {
            var roles = new[] {
                "admin",
                "teacher",
                "student"
            };

            for (int i = 0; i < roles.Length; i++)
            {
                await _appRoles.InsertAsync(entity : new Role(_guidGenerator.Create(), roles[i]), autoSave : true);
            }
        }
예제 #28
0
        public async Task <ApiResult> CreateAsync(CreateDataDictionaryDto input)
        {
            var count = await _dataDictionaryRepository.Where(e => e.Name == input.Name.Trim()).CountAsync();

            if (count > 0)
            {
                return(ApiResult.Error($"{input.Name} {_localizer["DataExistence"]}"));
            }
            var entity = new DataDictionary(_guidGenerator.Create(), input.Name, _currentUser.TenantId, input.Description);
            await _dataDictionaryRepository.InsertAsync(entity);

            return(ApiResult.Ok());
        }
예제 #29
0
        public async Task <object> SumbitOrder(ProductOrderRequestDto input)
        {
            var shopId = input.Skus[0].ShopId;

            if (input.Address == null)
            {
                throw new UserFriendlyException("请选择地址");
            }

            var order = new ProductOrder(_guidGenerator.Create(), shopId, CurrentTenant.Id)
            {
                Comment                = input.Comment,
                BuyerId                = CurrentUser.Id,
                AddressId              = input.Address.Id,
                AddressRealName        = input.Address.RealName,
                AddressNickName        = input.Address.NickName,
                AddressPhone           = input.Address.Phone,
                AddressLocationLabel   = input.Address.LocationLabel,
                AddressLocationAddress = input.Address.LocationAddress,
            };

            var orderItemList = new List <ProductOrderItem>();

            foreach (var sku in input.Skus)
            {
                orderItemList.Add(new ProductOrderItem(
                                      _guidGenerator.Create(),
                                      order.Id,
                                      sku.SpuId,
                                      sku.Id,
                                      sku.Price,
                                      sku.Num,
                                      CurrentTenant.Id
                                      )
                {
                    SkuName          = sku.Name,
                    SkuCoverImageUrl = sku.CoverImageUrls[0],
                    SkuUnit          = sku.Unit,
                    SpuName          = sku.SpuName
                                       //Comment = sku.Comment
                });

                order.PriceOriginal += (sku.Price * (decimal)sku.Num);
            }

            order.OrderItems = orderItemList;

            var result = await _orderRepository.InsertAsync(order);

            return(await Task.FromResult(result.Id));
        }
        private async Task CreateTestUserAsync()
        {
            var testUser = await _identityUserRepository.FindByNormalizedUserNameAsync("TEST");

            if (testUser == null)
            {
                testUser = new IdentityUser(_guidGenerator.Create(), "test", "*****@*****.**");
                await _identityUserManager.CreateAsync(testUser);
            }

            await _identityUserManager.RemovePasswordAsync(testUser);

            await _identityUserManager.AddPasswordAsync(testUser, "1q2w3E*");
        }