Exemplo n.º 1
0
        public async Task<IActionResult> Test2()
        {
            await _domainRepository
                .WithElevatedPermissions()
                .ExecuteQueryAsync(new GetCustomEntityDataModelSchemaDetailsByDefinitionCodeQuery(""));

            var entity = await _contentRepository
                .WithElevatedPermissions()
                .CustomEntities()
                .GetById(1)
                .AsRenderSummary(PublishStatusQuery.Published)
                .ExecuteAsync();

            var entities = await _contentRepository
                .CustomEntities()
                .GetByDefinitionCode("")
                .AsRenderSummary(PublishStatusQuery.Published)
                .MapItem(e => new
                {
                    e.Title
                })
                .ExecuteAsync();

            var enity2 = await _contentRepository
                .CustomEntities()
                .GetById(1)
                .AsRenderSummary(PublishStatusQuery.Published)
                .Map(e => new Dictionary<string, string>())
                .ExecuteAsync();

            var ids = new int[] { 1 };
            var catCustomEntities = await _contentRepository
                .CustomEntities()
                .GetByIdRange(ids)
                .AsRenderSummaries()
                //.MapItem(i => new { i.UrlSlug, i.Title })
                .MapItem(MapCatAsync)
                .FilterAndOrderByKeys(ids)
                .Map(v => v.OrderBy(v => v.Title))
                .ExecuteAsync();

            var customExecution = await _domainRepository
                .WithQuery(new SearchCustomEntityRenderSummariesQuery())
                .MapItem(b => new { b.CreateDate })
                .ExecuteAsync();

            return Json(entity);
        }
        protected async Task EnsureCacheLoaded()
        {
            await CacheSemaphore.WaitAsync();

            bool doPostProcess = false;

            try
            {
                if (Cache == null)
                {
                    var allEntities = await ContentRepository
                                      .WithElevatedPermissions()
                                      .CustomEntities()
                                      .GetByDefinitionCode(CustomEntityDefinitionCode)
                                      .AsRenderSummary()
                                      .ExecuteAsync();

                    Cache         = allEntities.Select(e => MapEntity(e)).ToList();
                    doPostProcess = true;
                }
            }
            finally
            {
                CacheSemaphore.Release();
            }

            // Post processing may involved a callback to EnsureCacheLoad, which will block on the semaphore,
            // so wait until semaphore is released.
            if (doPostProcess)
            {
                await PostProcessCache();
            }
        }
Exemplo n.º 3
0
        public async Task ExecuteAsync(BookingRequestCommand command, IExecutionContext executionContext)
        {
            using (var scope = DomainRepository.Transactions().CreateScope())
            {
                var tenantCategory = await TenantCategoryProvider.GetTenantCategoryById(command.TenantCategoryId.Value);

                DateTime lastAllowedArrivalDate = DateTime.Now.AddMonths(tenantCategory.AllowedBookingFutureMonths);
                if (command.ArrivalDate.Value >= lastAllowedArrivalDate || command.DepartureDate.Value >= lastAllowedArrivalDate)
                {
                    throw new ValidationErrorException(new ValidationError($"Den valgte lejertype kan ikke reservere mere end {tenantCategory.AllowedBookingFutureMonths} måneder ud i fremtiden. Dvs. senest {lastAllowedArrivalDate.ToShortDateString()}.", nameof(command.ArrivalDate)));
                }

                int bookingNumber = await SequenceNumberGenerator.NextNumber("BookingNumber");

                var booking = new BookingDataModel
                {
                    BookingNumber        = bookingNumber,
                    ArrivalDate          = command.ArrivalDate.Value,
                    DepartureDate        = command.DepartureDate.Value,
                    OnlySelectedWeekdays = command.OnlySelectedWeekdays,
                    SelectedWeekdays     = command.SelectedWeekdays,
                    TenantCategoryId     = command.TenantCategoryId.Value,
                    TenantName           = command.TenantName,
                    Purpose        = command.Purpose,
                    ContactName    = command.ContactName,
                    ContactPhone   = command.ContactPhone,
                    ContactAddress = command.ContactAddress,
                    ContactCity    = command.ContactCity,
                    ContactEMail   = command.ContactEMail,
                    Comments       = command.Comments,
                    RentalPrice    = null, // To be set later
                    Deposit        = BookingSettings.StandardDeposit,
                    BookingState   = BookingDataModel.BookingStateType.Requested
                };

                await booking.AddLogEntry(CurrentUserProvider, "Reservationen blev indsendt af lejer.");

                await SendConfirmationMail(booking);
                await SendNotificationMail(booking);

                var addCommand = new AddCustomEntityCommand
                {
                    CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
                    Model   = booking,
                    Title   = booking.MakeTitle(),
                    Publish = true,
                };

                await DomainRepository.WithElevatedPermissions().CustomEntities().AddAsync(addCommand);

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 4
0
        public async Task ExecuteAsync(CheckoutBookingCommand command, IExecutionContext executionContext)
        {
            using (var scope = DomainRepository.Transactions().CreateScope())
            {
                BookingDataModel booking = await BookingProvider.GetBookingById(command.Id);

                if (command.Token != booking.TenantSelfServiceToken)
                {
                    throw new AuthenticationFailedException("Ugyldigt eller manglende adgangsnøgle");
                }

                if (booking.BookingState == BookingDataModel.BookingStateType.Requested)
                {
                    throw new ValidationErrorException("Det er ikke muligt at indberette slutafregning, da reservationen endnu ikke er godkendt.");
                }
                else if (booking.BookingState == BookingDataModel.BookingStateType.Closed)
                {
                    throw new ValidationErrorException("Det er ikke muligt at indberette slutafregning, da reservationen allerede er afsluttet.");
                }

                booking.IsCheckedOut            = true;
                booking.ElectricityReadingStart = command.StartReading;
                booking.ElectricityReadingEnd   = command.EndReading;
                booking.ElectricityPriceUnit    = BookingSettings.ElectricityPrice;

                if (!string.IsNullOrEmpty(command.Comments))
                {
                    booking.Comments += $"\n\n=== Kommentarer til slutregnskab [{DateTime.Now}] ===\n{command.Comments}";
                }

                await booking.AddLogEntry(CurrentUserProvider, "Elforbrug blev indmeldt af lejer.");

                // Do not use BookingSummary for mails as it will be the old version of the booking, from before readings were updated.
                // Also make sure mails are sent before updating the entity, as sent mail will be refered by the model.
                await SendCheckoutConfirmationMail(booking);
                await SendAdminNotificationMail(booking);

                UpdateCustomEntityDraftVersionCommand updateCmd = new UpdateCustomEntityDraftVersionCommand
                {
                    CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
                    CustomEntityId             = command.Id,
                    Title   = booking.MakeTitle(),
                    Publish = true,
                    Model   = booking
                };

                await DomainRepository.WithElevatedPermissions().CustomEntities().Versions().UpdateDraftAsync(updateCmd);

                await scope.CompleteAsync();
            }
        }
Exemplo n.º 5
0
        public async Task ExecuteAsync(RegisterMemberAndLogInCommand command, IExecutionContext executionContext)
        {
            var roleId = await GetMemberRoleId();

            var addUserCommand = MapAddUserCommand(command, roleId);

            // Because we're not logged in, we'll need to elevate permissions to add a new user account.
            await _contentRepository
            .WithElevatedPermissions()
            .Users()
            .AddAsync(addUserCommand);

            await SendWelcomeNotification(command);

            // Log the user in. Note that the new user id is set in the OutputUserId which is a
            // convention used by the CQS framework (see https://www.cofoundry.org/docs/framework/cqs)
            await _loginService.LogAuthenticatedUserInAsync(addUserCommand.UserAreaCode, addUserCommand.OutputUserId, true);
        }
Exemplo n.º 6
0
    public async Task ExecuteAsync(RegisterMemberAndLogInCommand command, IExecutionContext executionContext)
    {
        var addUserCommand = MapAddUserCommand(command);

        // Because the user is not signed in, we'll need to elevate
        // permissions to be able add a new user account.
        var userId = await _contentRepository
                     .WithElevatedPermissions()
                     .Users()
                     .AddAsync(addUserCommand);

        await SendWelcomeNotification(command);

        await _contentRepository
        .Users()
        .Authentication()
        .SignInAuthenticatedUserAsync(new SignInAuthenticatedUserCommand()
        {
            UserId       = userId,
            RememberUser = true
        });
    }
Exemplo n.º 7
0
        public async Task ExecuteAsync(ImportBookingsCommand command, IExecutionContext executionContext)
        {
            PermissionValidationService.EnforceCustomEntityPermission <CustomEntityUpdatePermission>(BookingCustomEntityDefinition.DefinitionCode, executionContext.UserContext);

            DataSet bookings = new DataSet();

            bookings.ReadXml(command.ReadyToReadInput);

            var groupedBookings = bookings.Tables[0].Rows
                                  .Cast <DataRow>()
                                  .GroupBy(row => row["AftaleID"].ToString());

            int count = 0;

            foreach (var bookingGroup in groupedBookings)
            {
                try
                {
                    int bookingNumber = Convert.ToInt32(bookingGroup.Key);

                    string   startStr    = bookingGroup.Min(b => b["Dato"].ToString());
                    DateTime arrivalDate = DateTime.SpecifyKind(DateTime.Parse(startStr), DateTimeKind.Utc);

                    string   endStr        = bookingGroup.Max(b => b["Dato"].ToString());
                    DateTime departureDate = DateTime.SpecifyKind(DateTime.Parse(endStr), DateTimeKind.Utc);

                    DataRow row            = bookingGroup.First();
                    string  status         = row["Status"].ToString();
                    string  origin1        = row["HvorDuFra"].ToString();
                    string  origin2        = row["Fra"].ToString();
                    string  purpose        = row["Formaal"].ToString();
                    string  contactName    = row["KontaktPerson"].ToString();
                    string  contactEmail   = row["Email"].ToString();
                    string  contactAddress = row["Adresse"].ToString();
                    string  comments       = row["Bem"].ToString();
                    decimal.TryParse(row["AftaltLeje"].ToString(), out decimal rentalPrice);

                    int tenantCategoryId = GetTenantCategory(origin1);

                    BookingDataModel booking = new BookingDataModel
                    {
                        BookingNumber        = bookingNumber,
                        ArrivalDate          = arrivalDate,
                        DepartureDate        = departureDate,
                        OnlySelectedWeekdays = false,
                        SelectedWeekdays     = new List <WeekdayType>(),
                        TenantCategoryId     = tenantCategoryId,
                        TenantName           = origin2,
                        Purpose             = purpose,
                        ContactName         = contactName,
                        ContactPhone        = "",
                        ContactAddress      = contactAddress,
                        ContactCity         = "",
                        ContactEMail        = contactEmail,
                        Comments            = "Importeret i 2021 fra gammelt bookingsystem\n\n" + comments,
                        RentalPrice         = Math.Abs(rentalPrice),
                        Deposit             = 0,
                        BookingState        = BookingDataModel.BookingStateType.Closed,
                        IsApproved          = true,
                        IsCheckedOut        = true,
                        WelcomeLetterIsSent = true
                    };

                    if (booking.ArrivalDate.Value.Year >= 2021)
                    {
                        if (status == "Forespørgsel")
                        {
                            booking.BookingState        = BookingDataModel.BookingStateType.Requested;
                            booking.IsApproved          = false;
                            booking.WelcomeLetterIsSent = false;
                            booking.IsCheckedOut        = false;
                        }
                        else if (status == "Bekræftet")
                        {
                            booking.BookingState        = BookingDataModel.BookingStateType.Approved;
                            booking.IsApproved          = true;
                            booking.WelcomeLetterIsSent = false;
                            booking.IsCheckedOut        = false;
                        }
                        else if (status == "Nøgle sendt")
                        {
                            booking.BookingState        = BookingDataModel.BookingStateType.Approved;
                            booking.IsApproved          = true;
                            booking.WelcomeLetterIsSent = true;
                            booking.IsCheckedOut        = false;
                        }
                    }

                    var addCommand = new AddCustomEntityCommand
                    {
                        CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
                        Model   = booking,
                        Title   = booking.MakeTitle(),
                        Publish = true
                    };

                    await DomainRepository.WithElevatedPermissions().CustomEntities().AddAsync(addCommand);

                    if (++count >= 10000)
                    {
                        break;
                    }
                }
                catch (ValidationException ex)
                {
                    if (ex.ValidationResult is CompositeValidationResult vres)
                    {
                        throw new Exception($"Failed to validate booking number {bookingGroup.Key}: {vres.Results?.FirstOrDefault()}.", ex);
                    }
                    else
                    {
                        throw new Exception($"Failed to validate booking number {bookingGroup.Key}: {ex.ValidationResult?.ErrorMessage} ({ex.ValidationResult?.MemberNames?.FirstOrDefault()}).", ex);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Failed to import booking number {bookingGroup.Key}.", ex);
                }
            }

            //return Task.CompletedTask;
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Test()
        {
            var user = await _contentRepository
                       .WithElevatedPermissions()
                       .Users()
                       .GetById(2)
                       .AsMicroSummaryAsync();

            var image = await _contentRepository
                        .ImageAssets()
                        .GetById(2)
                        .AsRenderDetailsAsync();

            var page = await _contentRepository
                       .Pages()
                       .Search()
                       .AsRenderSummariesAsync(new SearchPageRenderSummariesQuery()
            {
                PageSize        = 20,
                PageDirectoryId = 2
            });

            var page2 = await _contentRepository
                        .Pages()
                        .GetById(1)
                        .AsRenderSummaryAsync();

            // Perhaps NotFound should look like this:
            await _contentRepository
            .Pages()
            .NotFound()
            .GetByPathAsync(new GetNotFoundPageRouteByPathQuery());

            var regions = await _contentRepository
                          .Pages()
                          .Versions()
                          .Regions()
                          .Blocks()
                          .GetById(2)
                          .AsRenderDetailsAsync(PublishStatusQuery.Latest);

            await _contentRepository
            .Pages()
            .GetByPath()
            .AsRoutingInfo(new GetPageRoutingInfoByPathQuery());

            //.PublishAsync(new PublishPageCommand() { PageId = 2 });

            var isUnique = await _contentRepository
                           .Users()
                           .IsUsernameUniqueAsync(new IsUsernameUniqueQuery()
            {
                UserAreaCode = CofoundryAdminUserArea.AreaCode,
                Username     = "******"
            });

            int userId;

            using (var scope = _contentRepository.Transactions().CreateScope())
            {
                var adminRole = await _contentRepository
                                .Roles()
                                .GetByCode(SuperAdminRole.SuperAdminRoleCode)
                                .AsDetailsAsync();

                userId = await _contentRepository
                         .WithElevatedPermissions()
                         .Users()
                         .AddAsync(new AddUserCommand()
                {
                    Email        = Guid.NewGuid().ToString() + "@cofoundry.org",
                    Password     = "******",
                    UserAreaCode = CofoundryAdminUserArea.AreaCode,
                    RoleId       = adminRole.RoleId
                });

                //await _contentRepository
                //    .WithElevatedPermissions()
                //    .ImageAssets()
                //    .DeleteAsync(2);

                await _contentRepository
                .CustomEntities()
                .Definitions()
                .GetByCode(BlogPostCustomEntityDefinition.DefinitionCode)
                .AsSummaryAsync();

                await _contentRepository
                .CustomEntities()
                .DataModelSchemas()
                .GetByCustomEntityDefinitionCode(BlogPostCustomEntityDefinition.DefinitionCode)
                .AsDetailsAsync();

                await _contentRepository
                .CustomEntities()
                .GetById(1)
                .AsRenderSummaryAsync();

                var permissions = await _contentRepository
                                  .Roles()
                                  .Permissions()
                                  .GetAll()
                                  .AsIPermissionAsync();

                var directoryTree = await _contentRepository
                                    .PageDirectories()
                                    .GetAll()
                                    .AsTreeAsync();

                var rewriteRules = await _contentRepository
                                   .RewriteRules()
                                   .GetAll()
                                   .AsSummariesAsync();

                var blockTypes = await _contentRepository
                                 .PageBlockTypes()
                                 .GetAll()
                                 .AsSummariesAsync();

                await scope.CompleteAsync();
            }

            await _contentRepository
            .WithElevatedPermissions()
            .Users()
            .DeleteUserAsync(userId);

            return(View());
        }