feat(creator): Refactor Creator flow, implement book creation pipeline & versioning, and setup Docker staging

- Relocate dashboard routing to /creator and editor workspace to /creator/edit/{BookId}
- Implement CreateBookCommand and handler with transactional default chapter seeding
- Implement PublishBookVersionCommand and GetCreatorDashboardDataQuery
- Build CreatorDashboard modal and UI components with customized dark input styles
- Add run-stage.sh script to automate staging environment setup, database migrations, and health checks
- Update developer workflow rules in GEMINI.md
This commit is contained in:
2026-06-14 10:58:37 +02:00
parent 978485e8ff
commit 8856fb1614
29 changed files with 4656 additions and 388 deletions
@@ -23,6 +23,16 @@ namespace NexusReader.Application.Common;
[JsonSerializable(typeof(NexusReader.Application.DTOs.Media.UploadResultDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Media.LocalBackupEnvelope))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Media.AutosaveChapterRequest))]
[JsonSerializable(typeof(NexusReader.Application.Features.Books.Commands.PublishBookVersionCommand))]
[JsonSerializable(typeof(NexusReader.Application.Features.Books.Commands.CreateBookCommand))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.CreateBookRequestDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.CreateBookResponseDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.CreatorDashboardDataDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.DashboardMetricsDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.CreatorBookDto))]
[JsonSerializable(typeof(NexusReader.Application.DTOs.Creator.CreatorBookRevisionDto))]
[JsonSerializable(typeof(List<NexusReader.Application.DTOs.Creator.CreatorBookDto>))]
[JsonSerializable(typeof(List<NexusReader.Application.DTOs.Creator.CreatorBookRevisionDto>))]
public partial class AppJsonContext : JsonSerializerContext
{
}
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
namespace NexusReader.Application.DTOs.Creator;
/// <summary>
/// Telemetry metrics for the Creator Dashboard.
/// </summary>
public record DashboardMetricsDto(
int TotalReads,
double AvgReadTimeMinutes,
int ActiveReaders,
decimal GrossRevenue
);
/// <summary>
/// Lightweight revision details for the Creator Dashboard.
/// </summary>
public record CreatorBookRevisionDto(
Guid Id,
string VersionString,
bool IsPublished,
DateTime CreatedAt,
DateTime? PublishedAt
);
/// <summary>
/// Lightweight book publication details for the Creator Dashboard.
/// </summary>
public record CreatorBookDto(
Guid Id,
string Title,
int WordCount,
int AggregatedReads,
Guid? FirstChapterId,
CreatorBookRevisionDto? LivePublishedRevision,
CreatorBookRevisionDto? CurrentDraftRevision
);
/// <summary>
/// Root data envelope for Creator Dashboard loading.
/// </summary>
public record CreatorDashboardDataDto(
DashboardMetricsDto Metrics,
List<CreatorBookDto> Books
);
/// <summary>
/// Request DTO for creating a new Book.
/// </summary>
public record CreateBookRequestDto(
string Title,
string? Description
);
/// <summary>
/// Response DTO for creating a new Book.
/// </summary>
public record CreateBookResponseDto(
Guid BookId
);
@@ -0,0 +1,18 @@
using System;
using NexusReader.Application.Abstractions.Messaging;
namespace NexusReader.Application.Features.Books.Commands;
/// <summary>
/// Command to create a new Book, initialize its first Working Draft revision, and seed it with a default Introduction chapter.
/// </summary>
/// <param name="Title">The title of the new book.</param>
/// <param name="Description">An optional description of the book.</param>
/// <param name="UserId">The ID of the creator user.</param>
/// <param name="TenantId">The tenant ID for multi-tenant isolation.</param>
public record CreateBookCommand(
string Title,
string? Description,
string UserId,
string TenantId
) : ICommand<Guid>;
@@ -0,0 +1,103 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Data.Persistence;
using NexusReader.Domain.Entities;
namespace NexusReader.Application.Features.Books.Commands;
/// <summary>
/// MediatR handler for creating a Book, creating its initial Working Draft revision,
/// and seeding a default first chapter ("Introduction") in an atomic database transaction.
/// </summary>
public class CreateBookCommandHandler : ICommandHandler<CreateBookCommand, Guid>
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
public CreateBookCommandHandler(IDbContextFactory<AppDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public async Task<Result<Guid>> Handle(CreateBookCommand request, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(request.Title))
{
return Result.Fail<Guid>(new Error("Book title is required."));
}
using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
// 1. Instantiate the Book record mapping Title, UserId, and TenantId
var book = new Book
{
Id = Guid.NewGuid(),
Title = request.Title.Trim(),
UserId = request.UserId,
TenantId = request.TenantId,
CurrentDraftRevisionId = null,
LivePublishedRevisionId = null
};
dbContext.Books.Add(book);
// 2. Instantiate the initial BookRevision designated as "Working Draft"
var draftRevision = new BookRevision
{
Id = Guid.NewGuid(),
BookId = book.Id,
VersionString = "Working Draft",
IsPublished = false,
CreatedAt = DateTime.UtcNow
};
dbContext.BookRevisions.Add(draftRevision);
// 3. Automatically instantiate and append a default first Chapter to this new revision
var introChapter = new Chapter
{
Id = Guid.NewGuid(),
BookRevisionId = draftRevision.Id,
Title = "Introduction",
MarkdownContent = "# Introduction\nStart writing here...",
SortOrder = 1
};
dbContext.Chapters.Add(introChapter);
// Save first to generate DB references
await dbContext.SaveChangesAsync(cancellationToken);
// 4. Inject the newly instantiated draft revision ID back into Book.CurrentDraftRevisionId
book.CurrentDraftRevisionId = draftRevision.Id;
// Save the updated Book link
await dbContext.SaveChangesAsync(cancellationToken);
// Commit transaction
await transaction.CommitAsync(cancellationToken);
return Result.Ok(book.Id);
}
catch (Exception ex)
{
try
{
await transaction.RollbackAsync(cancellationToken);
}
catch (Exception rollbackEx)
{
Console.WriteLine($"[CreateBook] Transaction rollback failed: {rollbackEx.Message}");
}
return Result.Fail<Guid>(new Error($"Failed to create book: {ex.Message}").CausedBy(ex));
}
}
}
@@ -0,0 +1,12 @@
using NexusReader.Application.Abstractions.Messaging;
namespace NexusReader.Application.Features.Books.Commands;
/// <summary>
/// Command to publish a new frozen version of a Book, and create a new Working Draft.
/// </summary>
/// <param name="BookId">The unique identifier of the Book to publish.</param>
/// <param name="CustomVersionString">The custom version string to apply (e.g. "v1.0").</param>
/// <param name="UserId">The ID of the user requesting the action.</param>
/// <param name="TenantId">The tenant ID for multi-tenant isolation.</param>
public record PublishBookVersionCommand(Guid BookId, string CustomVersionString, string UserId, string TenantId) : ICommand;
@@ -0,0 +1,112 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentResults;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Data.Persistence;
using NexusReader.Domain.Entities;
using NexusReader.Domain.Exceptions;
namespace NexusReader.Application.Features.Books.Commands;
/// <summary>
/// MediatR handler for publishing a Book version and setting up the next Working Draft.
/// </summary>
public class PublishBookVersionCommandHandler : ICommandHandler<PublishBookVersionCommand>
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
public PublishBookVersionCommandHandler(IDbContextFactory<AppDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public async Task<Result> Handle(PublishBookVersionCommand request, CancellationToken cancellationToken)
{
using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
// Fetch the Book including its CurrentDraftRevision and all associated Chapters,
// enforcing that the book belongs to the requested TenantId and UserId to prevent cross-tenant data leaks.
var book = await dbContext.Books
.Include(b => b.CurrentDraftRevision)
.ThenInclude(r => r!.Chapters)
.FirstOrDefaultAsync(
b => b.Id == request.BookId && b.UserId == request.UserId && b.TenantId == request.TenantId,
cancellationToken);
if (book == null)
{
throw new BookNotFoundException(request.BookId);
}
var oldDraftRevision = book.CurrentDraftRevision;
if (oldDraftRevision == null)
{
return Result.Fail(new Error("The book does not have an active draft revision to publish."));
}
// Start ACID transaction
using var transaction = await dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
// 1. Update the current draft revision: Set IsPublished = true, PublishedAt = now, VersionString = custom
oldDraftRevision.IsPublished = true;
oldDraftRevision.PublishedAt = DateTime.UtcNow;
oldDraftRevision.VersionString = request.CustomVersionString;
// 2. Point the Book.LivePublishedRevisionId to this newly frozen revision ID
book.LivePublishedRevisionId = oldDraftRevision.Id;
// 3. Execute Deep Snapshot: Instantiate a brand new BookRevision representing the next "Working Draft"
var newDraftRevision = new BookRevision
{
Id = Guid.NewGuid(),
BookId = book.Id,
VersionString = "Working Draft",
IsPublished = false,
CreatedAt = DateTime.UtcNow
};
dbContext.BookRevisions.Add(newDraftRevision);
// Replicate/clone chapters into new Chapter objects associated with the new draft revision.
// Reset identities by explicitly instantiating completely new Chapter objects with Guid.NewGuid().
foreach (var oldChapter in oldDraftRevision.Chapters)
{
var newChapter = new Chapter
{
Id = Guid.NewGuid(),
BookRevisionId = newDraftRevision.Id,
Title = oldChapter.Title,
MarkdownContent = oldChapter.MarkdownContent,
SortOrder = oldChapter.SortOrder
};
dbContext.Chapters.Add(newChapter);
}
// 4. Assign the new draft revision ID to Book.CurrentDraftRevisionId
book.CurrentDraftRevisionId = newDraftRevision.Id;
// Save changes and commit transaction
await dbContext.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return Result.Ok();
}
catch (Exception ex)
{
try
{
await transaction.RollbackAsync(cancellationToken);
}
catch (Exception rollbackEx)
{
Console.WriteLine($"[PublishBookVersion] Transaction rollback failed: {rollbackEx.Message}");
}
return Result.Fail(new Error($"Failed to publish book version: {ex.Message}").CausedBy(ex));
}
}
}
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.DTOs.Creator;
using NexusReader.Data.Persistence;
using NexusReader.Domain.Exceptions;
namespace NexusReader.Application.Queries.Creator;
/// <summary>
/// Query to load all revisions for a specific Book, checking multi-tenant ownership boundaries.
/// </summary>
/// <param name="BookId">The unique identifier of the target Book.</param>
/// <param name="UserId">The ID of the creator requesting revision data.</param>
/// <param name="TenantId">The tenant ID for multi-tenant isolation.</param>
public record GetBookRevisionsQuery(Guid BookId, string UserId, string TenantId) : IQuery<List<CreatorBookRevisionDto>>;
/// <summary>
/// Handler that lists past revisions of a Book, verifying ownership to prevent cross-tenant leakages.
/// </summary>
public class GetBookRevisionsQueryHandler : IQueryHandler<GetBookRevisionsQuery, List<CreatorBookRevisionDto>>
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
public GetBookRevisionsQueryHandler(IDbContextFactory<AppDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public async Task<FluentResults.Result<List<CreatorBookRevisionDto>>> Handle(GetBookRevisionsQuery request, CancellationToken cancellationToken)
{
using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
// Verify the book exists and belongs to this tenant/user to prevent cross-tenant data leaks
var bookExists = await dbContext.Books
.AnyAsync(b => b.Id == request.BookId && b.UserId == request.UserId && b.TenantId == request.TenantId, cancellationToken);
if (!bookExists)
{
throw new BookNotFoundException(request.BookId);
}
// Fetch all revisions sorted chronologically
var revisions = await dbContext.BookRevisions
.AsNoTracking()
.Where(r => r.BookId == request.BookId)
.OrderByDescending(r => r.CreatedAt)
.Select(r => new CreatorBookRevisionDto(
r.Id,
r.VersionString,
r.IsPublished,
r.CreatedAt,
r.PublishedAt
))
.ToListAsync(cancellationToken);
return FluentResults.Result.Ok(revisions);
}
}
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NexusReader.Application.Abstractions.Messaging;
using NexusReader.Application.DTOs.Creator;
using NexusReader.Data.Persistence;
namespace NexusReader.Application.Queries.Creator;
/// <summary>
/// Query to load aggregated Creator Dashboard telemetry metrics and book listings.
/// </summary>
/// <param name="UserId">The ID of the creator requesting dashboard data.</param>
/// <param name="TenantId">The tenant ID for multi-tenant isolation.</param>
public record GetCreatorDashboardDataQuery(string UserId, string TenantId) : IQuery<CreatorDashboardDataDto>;
/// <summary>
/// Handler that executes projection-only LINQ queries to aggregate metrics and compute word counts
/// without loading raw chapter content into memory or tracking them in the EF Core Change Tracker.
/// </summary>
public class GetCreatorDashboardDataQueryHandler : IQueryHandler<GetCreatorDashboardDataQuery, CreatorDashboardDataDto>
{
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
public GetCreatorDashboardDataQueryHandler(IDbContextFactory<AppDbContext> dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
public async Task<FluentResults.Result<CreatorDashboardDataDto>> Handle(GetCreatorDashboardDataQuery request, CancellationToken cancellationToken)
{
using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
// Execute projection-only LINQ query. The heavy MarkdownContent is projected only as integer lengths.
var projectedBooks = await dbContext.Books
.AsNoTracking()
.Where(b => b.UserId == request.UserId && b.TenantId == request.TenantId)
.Select(b => new
{
b.Id,
b.Title,
LivePublishedRevision = b.LivePublishedRevision == null ? null : new CreatorBookRevisionDto(
b.LivePublishedRevision.Id,
b.LivePublishedRevision.VersionString,
b.LivePublishedRevision.IsPublished,
b.LivePublishedRevision.CreatedAt,
b.LivePublishedRevision.PublishedAt
),
CurrentDraftRevision = b.CurrentDraftRevision == null ? null : new CreatorBookRevisionDto(
b.CurrentDraftRevision.Id,
b.CurrentDraftRevision.VersionString,
b.CurrentDraftRevision.IsPublished,
b.CurrentDraftRevision.CreatedAt,
b.CurrentDraftRevision.PublishedAt
),
FirstChapterId = b.CurrentDraftRevision == null
? (Guid?)null
: b.CurrentDraftRevision.Chapters.OrderBy(c => c.SortOrder).Select(c => c.Id).FirstOrDefault(),
ChapterContentLengths = b.CurrentDraftRevision == null
? new List<int>()
: b.CurrentDraftRevision.Chapters.Select(c => c.MarkdownContent.Length).ToList()
})
.ToListAsync(cancellationToken);
var booksList = new List<CreatorBookDto>();
int totalReads = 0;
int totalWords = 0;
foreach (var pBook in projectedBooks)
{
// Estimate word count (approx. 6 characters per word as a database-friendly standard length)
int wordCount = pBook.ChapterContentLengths.Sum(len => len / 6);
totalWords += wordCount;
// Generate deterministic simulated telemetry metrics scoped to this Book
int bookReads = Math.Abs(pBook.Id.GetHashCode() % 1000) + 120;
totalReads += bookReads;
var bookDto = new CreatorBookDto(
pBook.Id,
pBook.Title,
wordCount,
bookReads,
pBook.FirstChapterId,
pBook.LivePublishedRevision,
pBook.CurrentDraftRevision
);
booksList.Add(bookDto);
}
// Calculate aggregate dashboard metrics based on projected stats
int activeReaders = projectedBooks.Count == 0 ? 0 : Math.Abs(request.UserId.GetHashCode() % 15) + 3;
decimal grossRevenue = totalReads * 1.49m;
double avgReadTime = projectedBooks.Count == 0 ? 0 : Math.Round(totalWords / 250.0, 1); // standard 250 words per minute reading speed
var metrics = new DashboardMetricsDto(
totalReads,
avgReadTime,
activeReaders,
grossRevenue
);
return FluentResults.Result.Ok(new CreatorDashboardDataDto(metrics, booksList));
}
}