diff --git a/app/api/Data/ProductModels.cs b/app/api/Data/ProductModels.cs index 384505b..70be73b 100644 --- a/app/api/Data/ProductModels.cs +++ b/app/api/Data/ProductModels.cs @@ -115,6 +115,35 @@ public sealed class RequirementEvidence public DateTime RefreshedAt { get; set; } } +// A comment on a requirement, or a reply to one (ADR-059). Comments are discussion: they never +// change the requirement, its version, its evidence, or its review status. ParentId is null for a +// top-level comment; a reply's parent is always top-level. Deleting keeps the row, so replies stay +// in place, but clears Body: removed text is not kept. +public sealed class RequirementComment +{ + public Guid Id { get; set; } + public Guid RequirementId { get; set; } + public Guid? ParentId { get; set; } + public required string AuthorId { get; set; } + public required string Body { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime? EditedAt { get; set; } + public DateTime? DeletedAt { get; set; } + public string? DeletedBy { get; set; } +} + +// Who created, edited, or deleted a comment, and when (ADR-059). Action is "created", "edited", +// or "deleted". Earlier text is not recorded. Rows are only ever added. +public sealed class RequirementCommentEvent +{ + public Guid Id { get; set; } + public Guid RequirementId { get; set; } + public Guid CommentId { get; set; } + public required string Action { get; set; } + public required string Actor { get; set; } + public DateTime OccurredAt { get; set; } +} + // One requirement marked as a follow-up of another in the same project (ADR-052). Linking does // not change either requirement's version. public sealed class RequirementFollowUp diff --git a/app/api/Data/SpecThreadDbContext.cs b/app/api/Data/SpecThreadDbContext.cs index 63de68a..fdf5588 100644 --- a/app/api/Data/SpecThreadDbContext.cs +++ b/app/api/Data/SpecThreadDbContext.cs @@ -24,6 +24,8 @@ public sealed class SpecThreadDbContext(DbContextOptions op public DbSet RequirementDocuments => Set(); public DbSet RequirementFollowUps => Set(); public DbSet RequirementFollowUpEvents => Set(); + public DbSet RequirementComments => Set(); + public DbSet RequirementCommentEvents => Set(); protected override void OnModelCreating(ModelBuilder model) { @@ -413,5 +415,45 @@ protected override void OnModelCreating(ModelBuilder model) followUpEvent.HasOne().WithMany().HasForeignKey(x => x.RequirementId).OnDelete(DeleteBehavior.Restrict); followUpEvent.HasOne().WithMany().HasForeignKey(x => x.OriginalRequirementId).OnDelete(DeleteBehavior.Restrict); followUpEvent.HasOne().WithMany().HasForeignKey(x => x.Actor).OnDelete(DeleteBehavior.Restrict); + + var comment = model.Entity(); + comment.ToTable("requirement_comments", table => + { + table.HasCheckConstraint("ck_requirement_comments_body", "char_length(body) <= 5000"); + table.HasCheckConstraint("ck_requirement_comments_deleted", "(deleted_at IS NULL) = (deleted_by IS NULL) AND (deleted_at IS NULL OR body = '')"); + table.HasCheckConstraint("ck_requirement_comments_parent", "parent_id IS NULL OR parent_id <> id"); + }); + comment.HasKey(x => x.Id); + comment.Property(x => x.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()"); + comment.Property(x => x.RequirementId).HasColumnName("requirement_id"); + comment.Property(x => x.ParentId).HasColumnName("parent_id"); + comment.Property(x => x.AuthorId).HasColumnName("author_id"); + comment.Property(x => x.Body).HasColumnName("body"); + comment.Property(x => x.CreatedAt).HasColumnName("created_at").HasDefaultValueSql("now()"); + comment.Property(x => x.EditedAt).HasColumnName("edited_at"); + comment.Property(x => x.DeletedAt).HasColumnName("deleted_at"); + comment.Property(x => x.DeletedBy).HasColumnName("deleted_by"); + comment.HasIndex(x => new { x.RequirementId, x.CreatedAt }); + comment.HasIndex(x => x.ParentId); + comment.HasOne().WithMany().HasForeignKey(x => x.RequirementId).OnDelete(DeleteBehavior.Restrict); + comment.HasOne().WithMany().HasForeignKey(x => x.ParentId).OnDelete(DeleteBehavior.Restrict); + comment.HasOne().WithMany().HasForeignKey(x => x.AuthorId).OnDelete(DeleteBehavior.Restrict); + comment.HasOne().WithMany().HasForeignKey(x => x.DeletedBy).OnDelete(DeleteBehavior.Restrict); + + var commentEvent = model.Entity(); + commentEvent.ToTable("requirement_comment_events", table => + table.HasCheckConstraint("ck_requirement_comment_events_action", "action IN ('created', 'edited', 'deleted')")); + commentEvent.HasKey(x => x.Id); + commentEvent.Property(x => x.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()"); + commentEvent.Property(x => x.RequirementId).HasColumnName("requirement_id"); + commentEvent.Property(x => x.CommentId).HasColumnName("comment_id"); + commentEvent.Property(x => x.Action).HasColumnName("action"); + commentEvent.Property(x => x.Actor).HasColumnName("actor"); + commentEvent.Property(x => x.OccurredAt).HasColumnName("occurred_at").HasDefaultValueSql("now()"); + commentEvent.HasIndex(x => x.RequirementId); + commentEvent.HasIndex(x => x.CommentId); + commentEvent.HasOne().WithMany().HasForeignKey(x => x.RequirementId).OnDelete(DeleteBehavior.Restrict); + commentEvent.HasOne().WithMany().HasForeignKey(x => x.CommentId).OnDelete(DeleteBehavior.Restrict); + commentEvent.HasOne().WithMany().HasForeignKey(x => x.Actor).OnDelete(DeleteBehavior.Restrict); } } diff --git a/app/api/Migrations/20261118144936_RequirementComments.Designer.cs b/app/api/Migrations/20261118144936_RequirementComments.Designer.cs new file mode 100644 index 0000000..a55db1c --- /dev/null +++ b/app/api/Migrations/20261118144936_RequirementComments.Designer.cs @@ -0,0 +1,1800 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SpecThread.Api.Data; + +#nullable disable + +namespace SpecThread.Api.Migrations +{ + [DbContext(typeof(SpecThreadDbContext))] + [Migration("20261118144936_RequirementComments")] + partial class RequirementComments + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("public") + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("SpecThread.Api.Data.AcceptanceCriterion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Position") + .HasColumnType("integer") + .HasColumnName("position"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("Text") + .IsRequired() + .HasColumnType("text") + .HasColumnName("text"); + + b.HasKey("Id"); + + b.HasIndex("RequirementId", "Position") + .IsUnique(); + + b.ToTable("acceptance_criteria", "public", t => + { + t.HasCheckConstraint("ck_criteria_position", "position >= 0"); + + t.HasCheckConstraint("ck_criteria_text", "length(btrim(text)) > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthAccount", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("AccessToken") + .HasColumnType("text") + .HasColumnName("accessToken"); + + b.Property("AccessTokenExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("accessTokenExpiresAt"); + + b.Property("AccountId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("accountId"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("createdAt"); + + b.Property("IdToken") + .HasColumnType("text") + .HasColumnName("idToken"); + + b.Property("Password") + .HasColumnType("text") + .HasColumnName("password"); + + b.Property("ProviderId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("providerId"); + + b.Property("RefreshToken") + .HasColumnType("text") + .HasColumnName("refreshToken"); + + b.Property("RefreshTokenExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("refreshTokenExpiresAt"); + + b.Property("Scope") + .HasColumnType("text") + .HasColumnName("scope"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updatedAt"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("userId"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("ProviderId", "AccountId") + .IsUnique(); + + b.ToTable("account", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthRateLimit", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("Count") + .HasColumnType("integer") + .HasColumnName("count"); + + b.Property("Key") + .IsRequired() + .HasColumnType("text") + .HasColumnName("key"); + + b.Property("LastRequest") + .HasColumnType("bigint") + .HasColumnName("lastRequest"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.HasIndex("LastRequest"); + + b.ToTable("rateLimit", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthSession", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("createdAt"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiresAt"); + + b.Property("IpAddress") + .HasColumnType("text") + .HasColumnName("ipAddress"); + + b.Property("Token") + .IsRequired() + .HasColumnType("text") + .HasColumnName("token"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updatedAt"); + + b.Property("UserAgent") + .HasColumnType("text") + .HasColumnName("userAgent"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("userId"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("session", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthSigningKey", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("Alg") + .HasColumnType("text") + .HasColumnName("alg"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("createdAt"); + + b.Property("Crv") + .HasColumnType("text") + .HasColumnName("crv"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiresAt"); + + b.Property("PrivateKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("privateKey"); + + b.Property("PublicKey") + .IsRequired() + .HasColumnType("text") + .HasColumnName("publicKey"); + + b.HasKey("Id"); + + b.ToTable("jwks", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthUser", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("createdAt"); + + b.Property("Email") + .IsRequired() + .HasColumnType("text") + .HasColumnName("email"); + + b.Property("EmailVerified") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("emailVerified"); + + b.Property("Image") + .HasColumnType("text") + .HasColumnName("image"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updatedAt"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("user", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthVerification", b => + { + b.Property("Id") + .HasColumnType("text") + .HasColumnName("id"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("createdAt"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiresAt"); + + b.Property("Identifier") + .IsRequired() + .HasColumnType("text") + .HasColumnName("identifier"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updatedAt"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("Identifier"); + + b.ToTable("verification", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("archived_at"); + + b.Property("ContentType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("content_type"); + + b.Property("FileName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("file_name"); + + b.Property("ProjectId") + .HasColumnType("uuid") + .HasColumnName("project_id"); + + b.Property("SizeBytes") + .HasColumnType("bigint") + .HasColumnName("size_bytes"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("UploadedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("uploaded_at") + .HasDefaultValueSql("now()"); + + b.Property("UploadedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("uploaded_by"); + + b.HasKey("Id"); + + b.HasIndex("ProjectId"); + + b.HasIndex("UploadedBy"); + + b.ToTable("documents", "public", t => + { + t.HasCheckConstraint("ck_documents_content_type", "content_type IN ('application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')"); + + t.HasCheckConstraint("ck_documents_file_name", "length(btrim(file_name)) > 0"); + + t.HasCheckConstraint("ck_documents_size", "size_bytes BETWEEN 1 AND 4194304"); + + t.HasCheckConstraint("ck_documents_title", "length(btrim(title)) > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.DocumentContent", b => + { + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("Content") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("content"); + + b.HasKey("DocumentId"); + + b.ToTable("document_contents", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Project", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("archived_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("OwnerUserId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("owner_user_id"); + + b.Property("TeamId") + .HasColumnType("uuid") + .HasColumnName("team_id"); + + b.HasKey("Id"); + + b.HasIndex("OwnerUserId"); + + b.HasIndex("TeamId"); + + b.ToTable("projects", "public", t => + { + t.HasCheckConstraint("ck_projects_name", "length(btrim(name)) > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.ProjectMember", b => + { + b.Property("ProjectId") + .HasColumnType("uuid") + .HasColumnName("project_id"); + + b.Property("UserId") + .HasColumnType("text") + .HasColumnName("user_id"); + + b.Property("JoinedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("joined_at") + .HasDefaultValueSql("now()"); + + b.HasKey("ProjectId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("project_members", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.ProjectRepository", b => + { + b.Property("ProjectId") + .HasColumnType("uuid") + .HasColumnName("project_id"); + + b.Property("ConnectedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("connected_at") + .HasDefaultValueSql("now()"); + + b.Property("ConnectedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("connected_by"); + + b.Property("InstallationId") + .HasColumnType("bigint") + .HasColumnName("installation_id"); + + b.Property("IsPrivate") + .HasColumnType("boolean") + .HasColumnName("is_private"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("Owner") + .IsRequired() + .HasColumnType("text") + .HasColumnName("owner"); + + b.Property("RepositoryId") + .HasColumnType("bigint") + .HasColumnName("repository_id"); + + b.HasKey("ProjectId"); + + b.HasIndex("ConnectedBy"); + + b.ToTable("project_repositories", "public", t => + { + t.HasCheckConstraint("ck_project_repositories_ids", "installation_id > 0 AND repository_id > 0"); + + t.HasCheckConstraint("ck_project_repositories_name", "length(btrim(owner)) > 0 AND length(btrim(name)) > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Requirement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("ArchivedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("archived_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("created_by"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("Milestone") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("milestone"); + + b.Property("ProjectId") + .HasColumnType("uuid") + .HasColumnName("project_id"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at") + .HasDefaultValueSql("now()"); + + b.Property("UpdatedBy") + .HasColumnType("text") + .HasColumnName("updated_by"); + + b.Property("Version") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("version"); + + b.HasKey("Id"); + + b.HasIndex("CreatedBy"); + + b.HasIndex("ProjectId"); + + b.HasIndex("UpdatedBy"); + + b.ToTable("requirements", "public", t => + { + t.HasCheckConstraint("ck_requirements_milestone", "milestone IS NULL OR (btrim(milestone) = milestone AND length(milestone) BETWEEN 1 AND 100)"); + + t.HasCheckConstraint("ck_requirements_title", "length(btrim(title)) > 0"); + + t.HasCheckConstraint("ck_requirements_version", "version > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementComment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AuthorId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("author_id"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text") + .HasColumnName("body"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at"); + + b.Property("DeletedBy") + .HasColumnType("text") + .HasColumnName("deleted_by"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("edited_at"); + + b.Property("ParentId") + .HasColumnType("uuid") + .HasColumnName("parent_id"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("DeletedBy"); + + b.HasIndex("ParentId"); + + b.HasIndex("RequirementId", "CreatedAt"); + + b.ToTable("requirement_comments", "public", t => + { + t.HasCheckConstraint("ck_requirement_comments_body", "char_length(body) <= 5000"); + + t.HasCheckConstraint("ck_requirement_comments_deleted", "(deleted_at IS NULL) = (deleted_by IS NULL) AND (deleted_at IS NULL OR body = '')"); + + t.HasCheckConstraint("ck_requirement_comments_parent", "parent_id IS NULL OR parent_id <> id"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCommentEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .IsRequired() + .HasColumnType("text") + .HasColumnName("action"); + + b.Property("Actor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("actor"); + + b.Property("CommentId") + .HasColumnType("uuid") + .HasColumnName("comment_id"); + + b.Property("OccurredAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("occurred_at") + .HasDefaultValueSql("now()"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("Actor"); + + b.HasIndex("CommentId"); + + b.HasIndex("RequirementId"); + + b.ToTable("requirement_comment_events", "public", t => + { + t.HasCheckConstraint("ck_requirement_comment_events_action", "action IN ('created', 'edited', 'deleted')"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCriteriaVersion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("CreatedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("created_by"); + + b.Property("Criteria") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("criteria"); + + b.Property("Number") + .HasColumnType("integer") + .HasColumnName("number"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("CreatedBy"); + + b.HasIndex("RequirementId", "Number") + .IsUnique(); + + b.ToTable("requirement_criteria_versions", "public", t => + { + t.HasCheckConstraint("ck_requirement_criteria_versions_criteria", "jsonb_typeof(criteria) = 'array' AND NOT jsonb_path_exists(criteria, 'strict $[*] ? (@.type() != \"string\")')"); + + t.HasCheckConstraint("ck_requirement_criteria_versions_number", "number > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementDocument", b => + { + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("LinkedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("linked_at") + .HasDefaultValueSql("now()"); + + b.Property("LinkedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("linked_by"); + + b.HasKey("RequirementId", "DocumentId"); + + b.HasIndex("DocumentId"); + + b.HasIndex("LinkedBy"); + + b.ToTable("requirement_documents", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidence", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Additions") + .HasColumnType("integer") + .HasColumnName("additions"); + + b.Property("Author") + .HasColumnType("text") + .HasColumnName("author"); + + b.Property("ChangedFiles") + .HasColumnType("integer") + .HasColumnName("changed_files"); + + b.Property("CheckCount") + .HasColumnType("integer") + .HasColumnName("check_count"); + + b.Property("Checks") + .HasColumnType("jsonb") + .HasColumnName("checks"); + + b.Property("ChecksReadAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("checks_read_at"); + + b.Property("CommitCount") + .HasColumnType("integer") + .HasColumnName("commit_count"); + + b.Property("Commits") + .HasColumnType("jsonb") + .HasColumnName("commits"); + + b.Property("Contains") + .HasColumnType("jsonb") + .HasColumnName("contains"); + + b.Property("Deletions") + .HasColumnType("integer") + .HasColumnName("deletions"); + + b.Property("GitHubClosedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("github_closed_at"); + + b.Property("GitHubCreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("github_created_at"); + + b.Property("GitHubUpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("github_updated_at"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text") + .HasColumnName("kind"); + + b.Property("LinkedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("linked_at") + .HasDefaultValueSql("now()"); + + b.Property("LinkedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("linked_by"); + + b.Property("MergeSha") + .HasColumnType("text") + .HasColumnName("merge_sha"); + + b.Property("Number") + .HasColumnType("integer") + .HasColumnName("number"); + + b.Property("Prerelease") + .HasColumnType("boolean") + .HasColumnName("prerelease"); + + b.Property("RefreshedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("refreshed_at") + .HasDefaultValueSql("now()"); + + b.Property("RepositoryId") + .HasColumnType("bigint") + .HasColumnName("repository_id"); + + b.Property("RepositoryName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("repository_name"); + + b.Property("RepositoryOwner") + .IsRequired() + .HasColumnType("text") + .HasColumnName("repository_owner"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("Sha") + .HasColumnType("text") + .HasColumnName("sha"); + + b.Property("Source") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("manual") + .HasColumnName("source"); + + b.Property("State") + .HasColumnType("text") + .HasColumnName("state"); + + b.Property("Tag") + .HasColumnType("text") + .HasColumnName("tag"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text") + .HasColumnName("url"); + + b.HasKey("Id"); + + b.HasIndex("LinkedBy"); + + b.HasIndex("RequirementId", "RepositoryId", "Number") + .IsUnique(); + + b.HasIndex("RequirementId", "RepositoryId", "Sha") + .IsUnique() + .HasFilter("kind = 'commit'"); + + b.HasIndex("RequirementId", "RepositoryId", "Tag") + .IsUnique() + .HasFilter("kind = 'release'"); + + b.ToTable("requirement_evidence", "public", t => + { + t.HasCheckConstraint("ck_requirement_evidence_changes", "COALESCE(additions, 0) >= 0 AND COALESCE(deletions, 0) >= 0 AND COALESCE(changed_files, 0) >= 0 AND COALESCE(commit_count, 0) >= 0"); + + t.HasCheckConstraint("ck_requirement_evidence_checks", "COALESCE(check_count, 0) >= 0"); + + t.HasCheckConstraint("ck_requirement_evidence_identity", "(kind = 'commit' AND sha IS NOT NULL AND sha ~ '^[0-9a-f]{40}$' AND number IS NULL AND state IS NULL AND tag IS NULL) OR (kind IN ('issue', 'pull_request') AND number IS NOT NULL AND number > 0 AND state IS NOT NULL AND tag IS NULL) OR (kind = 'release' AND tag IS NOT NULL AND length(btrim(tag)) > 0 AND number IS NULL AND state IS NULL)"); + + t.HasCheckConstraint("ck_requirement_evidence_kind", "kind IN ('issue', 'pull_request', 'commit', 'release')"); + + t.HasCheckConstraint("ck_requirement_evidence_repository", "repository_id > 0"); + + t.HasCheckConstraint("ck_requirement_evidence_source", "source IN ('manual', 'suggested')"); + + t.HasCheckConstraint("ck_requirement_evidence_state", "state IS NULL OR state IN ('open', 'closed', 'merged')"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidenceEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .IsRequired() + .HasColumnType("text") + .HasColumnName("action"); + + b.Property("Actor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("actor"); + + b.Property("EvidenceId") + .HasColumnType("uuid") + .HasColumnName("evidence_id"); + + b.Property("Kind") + .IsRequired() + .HasColumnType("text") + .HasColumnName("kind"); + + b.Property("Label") + .IsRequired() + .HasColumnType("text") + .HasColumnName("label"); + + b.Property("OccurredAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("occurred_at") + .HasDefaultValueSql("now()"); + + b.Property("OtherRequirementId") + .HasColumnType("uuid") + .HasColumnName("other_requirement_id"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.HasKey("Id"); + + b.HasIndex("Actor"); + + b.HasIndex("OtherRequirementId"); + + b.HasIndex("RequirementId", "OccurredAt"); + + b.ToTable("requirement_evidence_events", "public", t => + { + t.HasCheckConstraint("ck_requirement_evidence_events_action", "action IN ('added', 'removed', 'confirmed', 'rejected', 'moved_in', 'moved_out')"); + + t.HasCheckConstraint("ck_requirement_evidence_events_kind", "kind IN ('issue', 'pull_request', 'commit', 'release')"); + + t.HasCheckConstraint("ck_requirement_evidence_events_label", "length(btrim(label)) > 0"); + + t.HasCheckConstraint("ck_requirement_evidence_events_move", "(action IN ('moved_in', 'moved_out')) = (other_requirement_id IS NOT NULL)"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidenceSuggestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Author") + .HasColumnType("text") + .HasColumnName("author"); + + b.Property("DecidedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("decided_at"); + + b.Property("DecidedBy") + .HasColumnType("text") + .HasColumnName("decided_by"); + + b.Property("FoundAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("found_at") + .HasDefaultValueSql("now()"); + + b.Property("Number") + .HasColumnType("integer") + .HasColumnName("number"); + + b.Property("Reference") + .IsRequired() + .HasColumnType("text") + .HasColumnName("reference"); + + b.Property("RepositoryId") + .HasColumnType("bigint") + .HasColumnName("repository_id"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("State") + .IsRequired() + .HasColumnType("text") + .HasColumnName("state"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("pending") + .HasColumnName("status"); + + b.Property("Title") + .IsRequired() + .HasColumnType("text") + .HasColumnName("title"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text") + .HasColumnName("url"); + + b.HasKey("Id"); + + b.HasIndex("DecidedBy"); + + b.HasIndex("RequirementId", "RepositoryId", "Number") + .IsUnique(); + + b.ToTable("requirement_evidence_suggestions", "public", t => + { + t.HasCheckConstraint("ck_requirement_evidence_suggestions_decision", "(status = 'pending') = (decided_by IS NULL) AND (decided_by IS NULL) = (decided_at IS NULL)"); + + t.HasCheckConstraint("ck_requirement_evidence_suggestions_number", "number > 0 AND repository_id > 0"); + + t.HasCheckConstraint("ck_requirement_evidence_suggestions_state", "state IN ('open', 'closed', 'merged')"); + + t.HasCheckConstraint("ck_requirement_evidence_suggestions_status", "status IN ('pending', 'confirmed', 'rejected')"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementFollowUp", b => + { + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("OriginalRequirementId") + .HasColumnType("uuid") + .HasColumnName("original_requirement_id"); + + b.Property("LinkedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("linked_at") + .HasDefaultValueSql("now()"); + + b.Property("LinkedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("linked_by"); + + b.HasKey("RequirementId", "OriginalRequirementId"); + + b.HasIndex("LinkedBy"); + + b.HasIndex("OriginalRequirementId"); + + b.ToTable("requirement_follow_ups", "public", t => + { + t.HasCheckConstraint("ck_requirement_follow_ups_distinct", "requirement_id <> original_requirement_id"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementFollowUpEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .IsRequired() + .HasColumnType("text") + .HasColumnName("action"); + + b.Property("Actor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("actor"); + + b.Property("OccurredAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("occurred_at") + .HasDefaultValueSql("now()"); + + b.Property("OriginalRequirementId") + .HasColumnType("uuid") + .HasColumnName("original_requirement_id"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("Actor"); + + b.HasIndex("OriginalRequirementId"); + + b.HasIndex("RequirementId"); + + b.ToTable("requirement_follow_up_events", "public", t => + { + t.HasCheckConstraint("ck_requirement_follow_up_events_action", "action IN ('added', 'removed')"); + + t.HasCheckConstraint("ck_requirement_follow_up_events_distinct", "requirement_id <> original_requirement_id"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementReview", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CriteriaVersion") + .HasColumnType("integer") + .HasColumnName("criteria_version"); + + b.Property("DecidedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("decided_at") + .HasDefaultValueSql("now()"); + + b.Property("DecidedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("decided_by"); + + b.Property("Decision") + .IsRequired() + .HasColumnType("text") + .HasColumnName("decision"); + + b.Property("Evidence") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("evidence"); + + b.Property("Note") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("") + .HasColumnName("note"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.Property("RequirementVersion") + .HasColumnType("integer") + .HasColumnName("requirement_version"); + + b.HasKey("Id"); + + b.HasIndex("DecidedBy"); + + b.HasIndex("RequirementId", "DecidedAt"); + + b.ToTable("requirement_reviews", "public", t => + { + t.HasCheckConstraint("ck_requirement_reviews_criteria_version", "criteria_version IS NULL OR criteria_version > 0"); + + t.HasCheckConstraint("ck_requirement_reviews_decision", "decision IN ('accepted', 'rejected', 'more_evidence')"); + + t.HasCheckConstraint("ck_requirement_reviews_evidence", "jsonb_typeof(evidence) = 'array'"); + + t.HasCheckConstraint("ck_requirement_reviews_note", "decision = 'accepted' OR length(btrim(note)) > 0"); + + t.HasCheckConstraint("ck_requirement_reviews_version", "requirement_version > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Team", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(10000) + .HasColumnType("character varying(10000)") + .HasColumnName("description"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.Property("OwnerUserId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("owner_user_id"); + + b.HasKey("Id"); + + b.HasIndex("OwnerUserId"); + + b.ToTable("teams", "public", t => + { + t.HasCheckConstraint("ck_teams_name", "length(btrim(name)) > 0"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.TeamInvitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AcceptedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("accepted_at"); + + b.Property("AcceptedBy") + .HasColumnType("text") + .HasColumnName("accepted_by"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("character varying(254)") + .HasColumnName("email"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("InvitedBy") + .IsRequired() + .HasColumnType("text") + .HasColumnName("invited_by"); + + b.Property("IssuedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("issued_at"); + + b.Property("RevokedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("revoked_at"); + + b.Property("Role") + .IsRequired() + .HasColumnType("text") + .HasColumnName("role"); + + b.Property("TeamId") + .HasColumnType("uuid") + .HasColumnName("team_id"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash"); + + b.HasKey("Id"); + + b.HasIndex("AcceptedBy"); + + b.HasIndex("InvitedBy"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("TeamId", "Email") + .IsUnique() + .HasFilter("accepted_at IS NULL AND revoked_at IS NULL"); + + b.ToTable("team_invitations", "public", t => + { + t.HasCheckConstraint("ck_team_invitations_expiry", "expires_at > issued_at"); + + t.HasCheckConstraint("ck_team_invitations_resolution", "accepted_at IS NULL OR revoked_at IS NULL"); + + t.HasCheckConstraint("ck_team_invitations_role", "role IN ('admin', 'member', 'reviewer', 'observer')"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.TeamMember", b => + { + b.Property("TeamId") + .HasColumnType("uuid") + .HasColumnName("team_id"); + + b.Property("UserId") + .HasColumnType("text") + .HasColumnName("user_id"); + + b.Property("IsExpanded") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("is_expanded"); + + b.Property("IsFavorite") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_favorite"); + + b.Property("JoinedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("joined_at") + .HasDefaultValueSql("now()"); + + b.Property("Role") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("member") + .HasColumnName("role"); + + b.HasKey("TeamId", "UserId"); + + b.HasIndex("UserId"); + + b.ToTable("team_members", "public", t => + { + t.HasCheckConstraint("ck_team_members_role", "role IN ('admin', 'member', 'reviewer', 'observer')"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.UserOnboarding", b => + { + b.Property("UserId") + .HasColumnType("text") + .HasColumnName("user_id"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at"); + + b.HasKey("UserId"); + + b.ToTable("user_onboarding", "public"); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AcceptanceCriterion", b => + { + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthAccount", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.AuthSession", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Document", b => + { + b.HasOne("SpecThread.Api.Data.Project", null) + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UploadedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.DocumentContent", b => + { + b.HasOne("SpecThread.Api.Data.Document", null) + .WithOne() + .HasForeignKey("SpecThread.Api.Data.DocumentContent", "DocumentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Project", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Team", null) + .WithMany() + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.ProjectMember", b => + { + b.HasOne("SpecThread.Api.Data.Project", null) + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.ProjectRepository", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("ConnectedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Project", null) + .WithOne() + .HasForeignKey("SpecThread.Api.Data.ProjectRepository", "ProjectId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Requirement", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("CreatedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Project", null) + .WithMany() + .HasForeignKey("ProjectId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UpdatedBy") + .OnDelete(DeleteBehavior.Restrict); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementComment", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("DeletedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.RequirementComment", null) + .WithMany() + .HasForeignKey("ParentId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCommentEvent", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("Actor") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.RequirementComment", null) + .WithMany() + .HasForeignKey("CommentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCriteriaVersion", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("CreatedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementDocument", b => + { + b.HasOne("SpecThread.Api.Data.Document", null) + .WithMany() + .HasForeignKey("DocumentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("LinkedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidence", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("LinkedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidenceEvent", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("Actor") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("OtherRequirementId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementEvidenceSuggestion", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("DecidedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementFollowUp", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("LinkedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("OriginalRequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementFollowUpEvent", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("Actor") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("OriginalRequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementReview", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("DecidedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.Team", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.TeamInvitation", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("AcceptedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("InvitedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Team", null) + .WithMany() + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.TeamMember", b => + { + b.HasOne("SpecThread.Api.Data.Team", null) + .WithMany() + .HasForeignKey("TeamId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.UserOnboarding", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/app/api/Migrations/20261118144936_RequirementComments.cs b/app/api/Migrations/20261118144936_RequirementComments.cs new file mode 100644 index 0000000..48af2dc --- /dev/null +++ b/app/api/Migrations/20261118144936_RequirementComments.cs @@ -0,0 +1,187 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SpecThread.Api.Migrations +{ + /// + public partial class RequirementComments : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "requirement_comments", + schema: "public", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + requirement_id = table.Column(type: "uuid", nullable: false), + parent_id = table.Column(type: "uuid", nullable: true), + author_id = table.Column(type: "text", nullable: false), + body = table.Column(type: "text", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"), + edited_at = table.Column(type: "timestamp with time zone", nullable: true), + deleted_at = table.Column(type: "timestamp with time zone", nullable: true), + deleted_by = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_requirement_comments", x => x.id); + table.CheckConstraint("ck_requirement_comments_body", "char_length(body) <= 5000"); + table.CheckConstraint("ck_requirement_comments_deleted", "(deleted_at IS NULL) = (deleted_by IS NULL) AND (deleted_at IS NULL OR body = '')"); + table.CheckConstraint("ck_requirement_comments_parent", "parent_id IS NULL OR parent_id <> id"); + table.ForeignKey( + name: "FK_requirement_comments_requirement_comments_parent_id", + column: x => x.parent_id, + principalSchema: "public", + principalTable: "requirement_comments", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_requirement_comments_requirements_requirement_id", + column: x => x.requirement_id, + principalSchema: "public", + principalTable: "requirements", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_requirement_comments_user_author_id", + column: x => x.author_id, + principalSchema: "public", + principalTable: "user", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_requirement_comments_user_deleted_by", + column: x => x.deleted_by, + principalSchema: "public", + principalTable: "user", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "requirement_comment_events", + schema: "public", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + requirement_id = table.Column(type: "uuid", nullable: false), + comment_id = table.Column(type: "uuid", nullable: false), + action = table.Column(type: "text", nullable: false), + actor = table.Column(type: "text", nullable: false), + occurred_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()") + }, + constraints: table => + { + table.PrimaryKey("PK_requirement_comment_events", x => x.id); + table.CheckConstraint("ck_requirement_comment_events_action", "action IN ('created', 'edited', 'deleted')"); + table.ForeignKey( + name: "FK_requirement_comment_events_requirement_comments_comment_id", + column: x => x.comment_id, + principalSchema: "public", + principalTable: "requirement_comments", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_requirement_comment_events_requirements_requirement_id", + column: x => x.requirement_id, + principalSchema: "public", + principalTable: "requirements", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_requirement_comment_events_user_actor", + column: x => x.actor, + principalSchema: "public", + principalTable: "user", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comment_events_actor", + schema: "public", + table: "requirement_comment_events", + column: "actor"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comment_events_comment_id", + schema: "public", + table: "requirement_comment_events", + column: "comment_id"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comment_events_requirement_id", + schema: "public", + table: "requirement_comment_events", + column: "requirement_id"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comments_author_id", + schema: "public", + table: "requirement_comments", + column: "author_id"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comments_deleted_by", + schema: "public", + table: "requirement_comments", + column: "deleted_by"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comments_parent_id", + schema: "public", + table: "requirement_comments", + column: "parent_id"); + + migrationBuilder.CreateIndex( + name: "IX_requirement_comments_requirement_id_created_at", + schema: "public", + table: "requirement_comments", + columns: new[] { "requirement_id", "created_at" }); + + migrationBuilder.Sql(""" + ALTER TABLE public."requirement_comments" ENABLE ROW LEVEL SECURITY; + REVOKE ALL ON TABLE public."requirement_comments" FROM PUBLIC; + DO $security$ + BEGIN + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'anon') THEN + REVOKE ALL ON TABLE public."requirement_comments" FROM anon; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN + REVOKE ALL ON TABLE public."requirement_comments" FROM authenticated; + END IF; + END $security$; + """); + + migrationBuilder.Sql(""" + ALTER TABLE public."requirement_comment_events" ENABLE ROW LEVEL SECURITY; + REVOKE ALL ON TABLE public."requirement_comment_events" FROM PUBLIC; + DO $security$ + BEGIN + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'anon') THEN + REVOKE ALL ON TABLE public."requirement_comment_events" FROM anon; + END IF; + IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'authenticated') THEN + REVOKE ALL ON TABLE public."requirement_comment_events" FROM authenticated; + END IF; + END $security$; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "requirement_comment_events", + schema: "public"); + + migrationBuilder.DropTable( + name: "requirement_comments", + schema: "public"); + } + } +} diff --git a/app/api/Migrations/SpecThreadDbContextModelSnapshot.cs b/app/api/Migrations/SpecThreadDbContextModelSnapshot.cs index 290f7a5..7b662b9 100644 --- a/app/api/Migrations/SpecThreadDbContextModelSnapshot.cs +++ b/app/api/Migrations/SpecThreadDbContextModelSnapshot.cs @@ -588,6 +588,116 @@ protected override void BuildModel(ModelBuilder modelBuilder) }); }); + modelBuilder.Entity("SpecThread.Api.Data.RequirementComment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AuthorId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("author_id"); + + b.Property("Body") + .IsRequired() + .HasColumnType("text") + .HasColumnName("body"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("now()"); + + b.Property("DeletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deleted_at"); + + b.Property("DeletedBy") + .HasColumnType("text") + .HasColumnName("deleted_by"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("edited_at"); + + b.Property("ParentId") + .HasColumnType("uuid") + .HasColumnName("parent_id"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("AuthorId"); + + b.HasIndex("DeletedBy"); + + b.HasIndex("ParentId"); + + b.HasIndex("RequirementId", "CreatedAt"); + + b.ToTable("requirement_comments", "public", t => + { + t.HasCheckConstraint("ck_requirement_comments_body", "char_length(body) <= 5000"); + + t.HasCheckConstraint("ck_requirement_comments_deleted", "(deleted_at IS NULL) = (deleted_by IS NULL) AND (deleted_at IS NULL OR body = '')"); + + t.HasCheckConstraint("ck_requirement_comments_parent", "parent_id IS NULL OR parent_id <> id"); + }); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCommentEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Action") + .IsRequired() + .HasColumnType("text") + .HasColumnName("action"); + + b.Property("Actor") + .IsRequired() + .HasColumnType("text") + .HasColumnName("actor"); + + b.Property("CommentId") + .HasColumnType("uuid") + .HasColumnName("comment_id"); + + b.Property("OccurredAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("occurred_at") + .HasDefaultValueSql("now()"); + + b.Property("RequirementId") + .HasColumnType("uuid") + .HasColumnName("requirement_id"); + + b.HasKey("Id"); + + b.HasIndex("Actor"); + + b.HasIndex("CommentId"); + + b.HasIndex("RequirementId"); + + b.ToTable("requirement_comment_events", "public", t => + { + t.HasCheckConstraint("ck_requirement_comment_events_action", "action IN ('created', 'edited', 'deleted')"); + }); + }); + modelBuilder.Entity("SpecThread.Api.Data.RequirementCriteriaVersion", b => { b.Property("Id") @@ -1441,6 +1551,52 @@ protected override void BuildModel(ModelBuilder modelBuilder) .OnDelete(DeleteBehavior.Restrict); }); + modelBuilder.Entity("SpecThread.Api.Data.RequirementComment", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("AuthorId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("DeletedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.RequirementComment", null) + .WithMany() + .HasForeignKey("ParentId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("SpecThread.Api.Data.RequirementCommentEvent", b => + { + b.HasOne("SpecThread.Api.Data.AuthUser", null) + .WithMany() + .HasForeignKey("Actor") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.RequirementComment", null) + .WithMany() + .HasForeignKey("CommentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("SpecThread.Api.Data.Requirement", null) + .WithMany() + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + modelBuilder.Entity("SpecThread.Api.Data.RequirementCriteriaVersion", b => { b.HasOne("SpecThread.Api.Data.AuthUser", null) diff --git a/app/api/Program.cs b/app/api/Program.cs index b9388e5..e421a3f 100644 --- a/app/api/Program.cs +++ b/app/api/Program.cs @@ -70,6 +70,7 @@ app.MapReviewEndpoints(); app.MapCriteriaVersionEndpoints(); app.MapFollowUpEndpoints(); +app.MapCommentEndpoints(); app.MapMilestoneEndpoints(); app.MapTeamEndpoints(); app.MapTeamManagementEndpoints(); diff --git a/app/api/Projects/ProjectAccess.cs b/app/api/Projects/ProjectAccess.cs index 8252243..2973044 100644 --- a/app/api/Projects/ProjectAccess.cs +++ b/app/api/Projects/ProjectAccess.cs @@ -47,6 +47,9 @@ internal static class TeamRoles // Recording a review decision. Reviewers decide without editing; Observers only read. public static bool CanReview(string? role) => role is Owner or Admin or Member or Reviewer; + + // Managing the team, including removing anyone's comment (ADR-059). + public static bool CanManage(string? role) => role is Owner or Admin; } // Boundary validation for user-supplied text. Limits are recorded in ADR-024. @@ -59,6 +62,7 @@ internal sealed class InputErrors public const int MaxRequirementDocuments = 20; // ADR-049 public const int MaxEmailLength = 254; public const int MaxMilestoneLength = 100; // ADR-053 + public const int MaxCommentLength = 5_000; // ADR-059 private readonly Dictionary errors = []; diff --git a/app/api/Requirements/CommentEndpoints.cs b/app/api/Requirements/CommentEndpoints.cs new file mode 100644 index 0000000..9389ebc --- /dev/null +++ b/app/api/Requirements/CommentEndpoints.cs @@ -0,0 +1,184 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.EntityFrameworkCore; +using SpecThread.Api.Data; +using SpecThread.Api.Projects; + +namespace SpecThread.Api.Requirements; + +// Discussion on a requirement (ADR-059). Every team member, Observers included, reads and adds +// comments and replies; comments never change the requirement, its evidence, or its review status. +// Authors edit their own comments. Authors, the Owner, and Admins delete them. Each creation, +// edit, and deletion is recorded with who did it and when, without the earlier text. +internal static class CommentEndpoints +{ + public static void MapCommentEndpoints(this IEndpointRouteBuilder app) + { + var comments = app.MapGroup("/requirements/{requirementId:guid}/comments").WithTags("Requirements") + .WithMetadata(ProjectEndpoints.Unauthorized); + comments.MapGet("/", List).WithName("ListComments"); + comments.MapPost("/", Add).WithName("AddComment").ProducesProblem(StatusCodes.Status409Conflict); + comments.MapPatch("/{commentId:guid}", Edit).WithName("EditComment") + .ProducesProblem(StatusCodes.Status403Forbidden).ProducesProblem(StatusCodes.Status409Conflict); + comments.MapDelete("/{commentId:guid}", Delete).WithName("DeleteComment") + .ProducesProblem(StatusCodes.Status403Forbidden).ProducesProblem(StatusCodes.Status409Conflict); + } + + private static async Task, NotFound>> List( + Guid requirementId, ClaimsPrincipal user, SpecThreadDbContext db, CancellationToken cancel) + { + var member = await db.Requirements.Where(r => r.Id == requirementId) + .Join(db.ProjectsFor(user.CallerId()), r => r.ProjectId, p => p.Id, (r, p) => r.Id).AnyAsync(cancel); + if (!member) return TypedResults.NotFound(); + + // One snapshot for both reads, so a deletion in between can't show in one list and not the other. + await using var snapshot = await db.Database.BeginTransactionAsync(System.Data.IsolationLevel.RepeatableRead, cancel); + var comments = await db.RequirementComments.AsNoTracking().Where(c => c.RequirementId == requirementId) + .OrderBy(c => c.CreatedAt).ThenBy(c => c.Id) + .Select(c => new CommentResponse(c.Id, c.ParentId, c.AuthorId, c.Body, c.CreatedAt, c.EditedAt, c.DeletedAt, c.DeletedBy)) + .ToListAsync(cancel); + var history = await db.RequirementCommentEvents.AsNoTracking().Where(e => e.RequirementId == requirementId) + .Join(db.RequirementComments, e => e.CommentId, c => c.Id, (e, c) => new { Event = e, c.AuthorId, c.ParentId }) + .OrderByDescending(x => x.Event.OccurredAt).ThenByDescending(x => x.Event.Id) + .Select(x => new CommentEventResponse(x.Event.Id, x.Event.CommentId, x.ParentId, x.AuthorId, x.Event.Action, x.Event.Actor, x.Event.OccurredAt)) + .ToListAsync(cancel); + return TypedResults.Ok(new CommentsResponse(comments, history)); + } + + private static async Task, ValidationProblem, NotFound, ProblemHttpResult>> Add( + Guid requirementId, AddCommentRequest request, ClaimsPrincipal user, SpecThreadDbContext db, CancellationToken cancel) + { + var errors = new InputErrors(); + var body = Body(errors, request.Body); + if (request.ParentId == Guid.Empty) errors.Add("parentId", "Choose a comment to reply to."); + if (errors.Any) return TypedResults.ValidationProblem(errors.ToDictionary()); + + var userId = user.CallerId(); + // Serialize with archiving and membership changes in this project's team. + await using var transaction = await db.Database.BeginTransactionAsync(cancel); + var found = await RequirementEndpoints.LockForMember(db, userId, requirementId, cancel); + if (found is null) return TypedResults.NotFound(); + if (found.Archived) return ProjectEndpoints.Archived(); + if (request.ParentId is Guid parentId) + { + var parent = await db.RequirementComments.AsNoTracking() + .SingleOrDefaultAsync(c => c.Id == parentId && c.RequirementId == requirementId, cancel); + if (parent is null) + { + return TypedResults.ValidationProblem(new Dictionary { ["parentId"] = ["Choose a comment on this requirement."] }); + } + // One level of replies keeps each topic in one place. + if (parent.ParentId is not null) + { + return TypedResults.ValidationProblem(new Dictionary { ["parentId"] = ["Reply to the original comment instead."] }); + } + if (parent.DeletedAt is not null) return Conflict("That comment was deleted, so it can't be replied to."); + } + + var comment = new RequirementComment + { + Id = Guid.NewGuid(), + RequirementId = requirementId, + ParentId = request.ParentId, + AuthorId = userId, + Body = body!, + CreatedAt = Clock.UtcNow(), + }; + db.RequirementComments.Add(comment); + Record(db, comment, "created", userId, comment.CreatedAt); + await db.SaveChangesAsync(cancel); + await transaction.CommitAsync(cancel); + return TypedResults.Created($"/requirements/{requirementId}/comments/{comment.Id}", Response(comment)); + } + + private static async Task, ValidationProblem, NotFound, ProblemHttpResult>> Edit( + Guid requirementId, Guid commentId, EditCommentRequest request, ClaimsPrincipal user, SpecThreadDbContext db, CancellationToken cancel) + { + var errors = new InputErrors(); + var body = Body(errors, request.Body); + if (errors.Any) return TypedResults.ValidationProblem(errors.ToDictionary()); + + var userId = user.CallerId(); + await using var transaction = await db.Database.BeginTransactionAsync(cancel); + var found = await RequirementEndpoints.LockForMember(db, userId, requirementId, cancel); + if (found is null) return TypedResults.NotFound(); + var comment = await db.RequirementComments.SingleOrDefaultAsync(c => c.Id == commentId && c.RequirementId == requirementId, cancel); + if (comment is null) return TypedResults.NotFound(); + if (comment.AuthorId != userId) + { + return TypedResults.Problem("Only the author can edit a comment.", statusCode: StatusCodes.Status403Forbidden); + } + if (comment.DeletedAt is not null) return Conflict("A deleted comment can't be edited."); + if (found.Archived) return ProjectEndpoints.Archived(); + // Saving the same text is not an edit, so nothing is recorded. + if (comment.Body == body) return TypedResults.Ok(Response(comment)); + + var now = Clock.UtcNow(); + comment.Body = body!; + comment.EditedAt = now; + Record(db, comment, "edited", userId, now); + await db.SaveChangesAsync(cancel); + await transaction.CommitAsync(cancel); + return TypedResults.Ok(Response(comment)); + } + + private static async Task> Delete( + Guid requirementId, Guid commentId, ClaimsPrincipal user, SpecThreadDbContext db, CancellationToken cancel) + { + var userId = user.CallerId(); + await using var transaction = await db.Database.BeginTransactionAsync(cancel); + var found = await RequirementEndpoints.LockForMember(db, userId, requirementId, cancel); + if (found is null) return TypedResults.NotFound(); + var comment = await db.RequirementComments.SingleOrDefaultAsync(c => c.Id == commentId && c.RequirementId == requirementId, cancel); + // Already deleted, for example by someone else, reads as gone. + if (comment is null || comment.DeletedAt is not null) return TypedResults.NotFound(); + if (comment.AuthorId != userId && !TeamRoles.CanManage(found.Role)) + { + return TypedResults.Problem("Only the author, the Owner, or an Admin can delete a comment.", statusCode: StatusCodes.Status403Forbidden); + } + if (found.Archived) return ProjectEndpoints.Archived(); + + var now = Clock.UtcNow(); + comment.Body = ""; + comment.DeletedAt = now; + comment.DeletedBy = userId; + Record(db, comment, "deleted", userId, now); + await db.SaveChangesAsync(cancel); + await transaction.CommitAsync(cancel); + return TypedResults.NoContent(); + } + + // PostgreSQL text can't hold a NUL character, so it is refused here rather than failing the save. + private static string? Body(InputErrors errors, string? value) => + value?.Contains('\0') == true ? errors.Add("body", "Remove the invalid character.") : errors.Required("body", value, InputErrors.MaxCommentLength); + + private static void Record(SpecThreadDbContext db, RequirementComment comment, string action, string userId, DateTime at) => + db.RequirementCommentEvents.Add(new RequirementCommentEvent + { + Id = Guid.NewGuid(), + RequirementId = comment.RequirementId, + CommentId = comment.Id, + Action = action, + Actor = userId, + OccurredAt = at, + }); + + private static CommentResponse Response(RequirementComment c) => + new(c.Id, c.ParentId, c.AuthorId, c.Body, c.CreatedAt, c.EditedAt, c.DeletedAt, c.DeletedBy); + + private static ProblemHttpResult Conflict(string detail) => TypedResults.Problem(detail, statusCode: StatusCodes.Status409Conflict); +} + +internal sealed record AddCommentRequest(string? Body, Guid? ParentId); + +internal sealed record EditCommentRequest(string? Body); + +// A comment or reply. A deleted comment has an empty Body and keeps its place, so replies stay under it. +internal sealed record CommentResponse( + Guid Id, Guid? ParentId, string AuthorId, string Body, DateTime CreatedAt, DateTime? EditedAt, DateTime? DeletedAt, string? DeletedBy); + +// One created, edited, or deleted comment. ParentId and AuthorId describe the comment, Actor who acted. +internal sealed record CommentEventResponse( + Guid Id, Guid CommentId, Guid? ParentId, string AuthorId, string Action, string Actor, DateTime OccurredAt); + +internal sealed record CommentsResponse(List Comments, List History); diff --git a/app/web/src/app/app-shell.css b/app/web/src/app/app-shell.css index d680001..23f429b 100644 --- a/app/web/src/app/app-shell.css +++ b/app/web/src/app/app-shell.css @@ -507,3 +507,21 @@ a.row:focus-visible { outline-offset: -2px; } .suggestion-actions { display: flex; flex: none; gap: 6px; } .evidence-rows li > .evidence-move { margin: 8px 14px 10px 44px; } .evidence-move .muted { margin: 6px 0 0; font-size: 13px; } + +/* Requirement comments (ADR-059) */ +.comment-list, .comment-replies { display: grid; gap: 10px; margin: 0; padding: 0; list-style: none; } +.comment-list { margin-bottom: 14px; } +.comment-replies { margin-top: 10px; padding-left: 18px; border-left: 2px solid var(--app-line); } +.comment { display: grid; gap: 6px; padding: 10px 14px; border: 1px solid var(--app-line); border-radius: 10px; background: var(--app-surface); } +.comment.is-deleted { border-style: dashed; background: none; } +.comment p { margin: 0; } +.comment-meta { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; font-size: 13px; color: var(--app-text-2); } +.comment-meta strong { color: var(--app-text); } +.comment-body { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.5; } +.comment-actions { display: flex; flex-wrap: wrap; gap: 4px 14px; } +.comment form { display: grid; gap: 8px; } +.comment-form { display: grid; gap: 8px; justify-items: start; } +.comment-form .field { width: 100%; } +.app-main .link-button { padding: 0; border: 0; background: none; color: var(--app-text-2); font: inherit; font-size: 13px; text-decoration: underline; text-underline-offset: 3px; cursor: pointer; } +.app-main .link-button:hover { color: var(--app-text); } +.app-main .link-button:focus-visible { outline: 2px solid #ffffff80; outline-offset: 2px; border-radius: 2px; } diff --git a/app/web/src/app/projects/[projectId]/requirements/[requirementId]/history/page.tsx b/app/web/src/app/projects/[projectId]/requirements/[requirementId]/history/page.tsx index 1aed58d..b519451 100644 --- a/app/web/src/app/projects/[projectId]/requirements/[requirementId]/history/page.tsx +++ b/app/web/src/app/projects/[projectId]/requirements/[requirementId]/history/page.tsx @@ -3,10 +3,11 @@ import Link from "next/link"; import { ArrowLeft } from "lucide-react"; import { EvidenceHistory } from "@/components/evidence-panel"; import { FollowUpHistory } from "@/components/requirement-follow-ups"; +import { commentEventText } from "@/lib/comments"; import { - listCriteriaVersions, listEvidenceHistory, listFollowUps, listMembers, listReviews, requireProject, requireRequirement, + listComments, listCriteriaVersions, listEvidenceHistory, listFollowUps, listMembers, listReviews, requireProject, requireRequirement, } from "@/lib/project-data"; -import { formatDate } from "@/lib/projects"; +import { formatDate, formatDateTime } from "@/lib/projects"; import { decisionText } from "@/lib/reviews"; export const metadata: Metadata = { title: "Requirement history" }; @@ -14,13 +15,15 @@ export const metadata: Metadata = { title: "Requirement history" }; /** * Shows how a requirement changed: every version of its acceptance criteria with who saved it, * when, and the decisions made against it (ADR-051), every follow-up link added or removed - * (ADR-052), and every evidence link added or removed (ADR-054). Earlier versions open read-only. + * (ADR-052), every evidence link added or removed (ADR-054), and every comment posted, edited, or + * deleted (ADR-059). Earlier versions open read-only. */ export default async function Page({ params }: PageProps<"/projects/[projectId]/requirements/[requirementId]/history">) { const { projectId, requirementId } = await params; - const [project, requirement, versions, followUps, reviews, members, evidenceHistory] = await Promise.all([ + const [project, requirement, versions, followUps, reviews, members, evidenceHistory, comments] = await Promise.all([ requireProject(projectId), requireRequirement(projectId, requirementId), listCriteriaVersions(requirementId), listFollowUps(requirementId), listReviews(requirementId), listMembers(projectId), listEvidenceHistory(requirementId), + listComments(requirementId), ]); const people = Object.fromEntries(members.map(member => [member.userId, member.name])); const nameOf = (userId: string) => people[userId] ?? "a former member"; @@ -82,6 +85,25 @@ export default async function Page({ params }: PageProps<"/projects/[projectId]/ ?

No follow-up links have been added or removed.

:
} +
+

Comments

+ {comments === null + ?

Comment changes can't be shown right now. Try again in a few minutes.

+ : comments.history.length === 0 + ?

No comments have been posted.

+ : ( +
+
    + {comments.history.map(event => ( +
  1. + {commentEventText(event, userId => people[userId] ?? "A former member")}{" "} + on +
  2. + ))} +
+
+ )} +
); } diff --git a/app/web/src/app/projects/[projectId]/requirements/[requirementId]/page.tsx b/app/web/src/app/projects/[projectId]/requirements/[requirementId]/page.tsx index f9ba38c..56d327d 100644 --- a/app/web/src/app/projects/[projectId]/requirements/[requirementId]/page.tsx +++ b/app/web/src/app/projects/[projectId]/requirements/[requirementId]/page.tsx @@ -4,15 +4,18 @@ import { ArrowLeft, FileText, Pencil } from "lucide-react"; import { EvidenceHistory, EvidencePanel } from "@/components/evidence-panel"; import { EvidenceStatus } from "@/components/evidence-status"; import { RequirementArchive, RequirementRestore } from "@/components/requirement-archive"; +import { RequirementComments } from "@/components/requirement-comments"; import { RequirementFollowUps } from "@/components/requirement-follow-ups"; import { RequirementMilestone } from "@/components/requirement-milestone"; import { ReviewPanel } from "@/components/review-panel"; import { documentTypeLabel } from "@/lib/documents"; import { getProjectRepository } from "@/lib/github-data"; import { - listEvidence, listEvidenceHistory, listEvidenceSuggestions, listFollowUps, listMembers, listMilestones, listRequirements, listReviews, requireProject, requireRequirement, + listComments, listEvidence, listEvidenceHistory, listEvidenceSuggestions, listFollowUps, listMembers, listMilestones, listRequirements, listReviews, + requireProject, requireRequirement, } from "@/lib/project-data"; import { canEditProject, canReviewProject, formatDate } from "@/lib/projects"; +import { requireTeamSession } from "@/lib/teams"; type Props = PageProps<"/projects/[projectId]/requirements/[requirementId]">; @@ -27,18 +30,19 @@ export async function generateMetadata({ params }: Props): Promise { /** * Shows who created a requirement and when, its description, ordered acceptance criteria and their * version, milestone, linked documents, follow-up links, evidence and its Evidence complete status, - * and review decisions, with + * review decisions, and the discussion (ADR-059), with * edit and archive while it can change and the viewer's team role allows it (ADR-058). */ export default async function Page({ params }: Props) { const { projectId, requirementId } = await params; // One round of parallel reads. Each is authorized by the API, and requireRequirement still // shows the not-found page before anything renders when the requirement is in another project. - const [project, requirement, members, repository, evidence, reviews, followUps, requirements, milestones, evidenceHistory, suggestions] = await Promise.all([ + const [project, requirement, members, repository, evidence, reviews, followUps, requirements, milestones, evidenceHistory, suggestions, comments, session] = await Promise.all([ requireProject(projectId), requireRequirement(projectId, requirementId), listMembers(projectId), getProjectRepository(projectId), listEvidence(requirementId), listReviews(requirementId), listFollowUps(requirementId), listRequirements(projectId), listMilestones(projectId), listEvidenceHistory(requirementId), - listEvidenceSuggestions(requirementId), + listEvidenceSuggestions(requirementId), listComments(requirementId), + requireTeamSession(`/projects/${projectId}/requirements/${requirementId}`), ]); const people = Object.fromEntries(members.map(member => [member.userId, member.name])); const nameOf = (userId: string) => people[userId] ?? "a former member"; @@ -153,6 +157,11 @@ export default async function Page({ params }: Props) { evidenceIds={evidence.map(link => link.id)} people={people} canReview={changeable && canReviewProject(project)} /> +
+

Comments

+ +
{editable && } {requirement.archivedAt && !project.archivedAt && canEditProject(project) && } diff --git a/app/web/src/app/projects/comment-actions.ts b/app/web/src/app/projects/comment-actions.ts new file mode 100644 index 0000000..13c330b --- /dev/null +++ b/app/web/src/app/projects/comment-actions.ts @@ -0,0 +1,139 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { apiFetch } from "@/lib/api"; +import { readAuthConfig } from "@/lib/auth-config"; +import { commentNotificationEmail, commentRecipients, parseComment, parseComments, type Comment } from "@/lib/comments"; +import { createEmailSender } from "@/lib/email"; +import { problemDetail } from "@/lib/evidence"; +import { fieldError, isUuid, parseMembers, parseProject } from "@/lib/projects"; +import { parseRequirement } from "@/lib/requirements"; +import { requireTeamSession } from "@/lib/teams"; + +/** `changed` counts successful saves, so a form can reset itself; `notice` reports a saved comment whose emails failed. */ +export type CommentState = { error: string | null; changed: number; notice?: string }; + +const detailPath = (projectId: string, requirementId: string) => `/projects/${projectId}/requirements/${requirementId}`; + +async function readJson(path: `/${string}`): Promise { + const response = await apiFetch(path); + if (!response.ok) throw new Error(`GET ${path.split("/").slice(0, 2).join("/")} returned ${response.status}.`); + return response.json(); +} + +/** + * Emails the people following a requirement's discussion about a new comment (ADR-059). Best effort: + * the comment is already saved, so a failure is reported, never retried. Returns whether every email went. + */ +async function notify(projectId: string, requirementId: string, comment: Comment): Promise { + try { + const [project, requirement, members, comments] = await Promise.all([ + readJson(`/projects/${projectId}`).then(parseProject), readJson(`/requirements/${requirementId}`).then(parseRequirement), + readJson(`/projects/${projectId}/members`).then(parseMembers), readJson(`/requirements/${requirementId}/comments`).then(parseComments), + ]); + const recipients = commentRecipients({ + requirementAuthorId: requirement.createdBy, comments: comments.comments, parentId: comment.parentId, + writerId: comment.authorId, members, + }); + if (recipients.length === 0) return true; + const config = readAuthConfig(process.env); + const send = createEmailSender(config.email); + const url = `${config.baseURL}${detailPath(projectId, requirementId)}#comments`; + const writerName = members.find(member => member.userId === comment.authorId)?.name ?? "A team member"; + const results = await Promise.allSettled(recipients.map(recipient => send(commentNotificationEmail({ + to: recipient.email, writerName, requirementTitle: requirement.title, projectName: project.name, url, reply: comment.parentId !== null, + })))); + const failed = results.filter(result => result.status === "rejected").length; + // Counts only: addresses and comment text stay out of logs. + if (failed > 0) console.error(`Comment notification: ${failed} of ${results.length} emails failed.`); + return failed === 0; + } catch { + // A fixed message: error text could carry provider responses or addresses. + console.error("Comment notification: the recipients could not be looked up."); + return false; + } +} + +/** Adds a comment, or a reply when the form carries `parentId`, and emails the discussion's participants. */ +export async function addComment( + projectId: string, requirementId: string, previous: CommentState, formData: FormData, +): Promise { + const failed = "The comment could not be posted. Please try again."; + const fail = (error: string): CommentState => ({ error, changed: previous.changed }); + await requireTeamSession(detailPath(projectId, requirementId)); + const body = String(formData.get("body") ?? ""); + const parentId = String(formData.get("parentId") ?? "") || null; + if (!body.trim()) return fail("Write a comment first."); + if (!isUuid(projectId) || !isUuid(requirementId) || (parentId !== null && !isUuid(parentId))) return fail(failed); + let response: Response; + try { + response = await apiFetch(`/requirements/${requirementId}/comments`, { method: "POST", body: JSON.stringify({ body, parentId }) }); + if (response.status === 400) { + const problem = await response.json(); + return fail(fieldError(problem, "body") ?? fieldError(problem, "parentId") ?? failed); + } + // 409 explains itself: archived, or the comment being answered was deleted. + if (response.status === 409) return fail(problemDetail(await response.json()) ?? failed); + if (!response.ok) throw new Error(`Add comment returned ${response.status}.`); + } catch (error) { + console.error("Add comment failed", error); + return fail(failed); + } + // The comment is saved from here on, so nothing below may report it as failed, which would invite a duplicate. + let comment: Comment | null = null; + try { comment = parseComment(await response.json()); } + catch { console.error("Add comment: the saved comment could not be read back."); } + const delivered = comment !== null && await notify(projectId, requirementId, comment); + revalidatePath(detailPath(projectId, requirementId), "layout"); + return { + error: null, changed: previous.changed + 1, + notice: delivered ? undefined : "Your comment was posted, but notification emails couldn’t be sent.", + }; +} + +/** Saves new text for a comment the signed-in user wrote. */ +export async function editComment( + projectId: string, requirementId: string, previous: CommentState, formData: FormData, +): Promise { + const failed = "The comment could not be saved. Please try again."; + const fail = (error: string): CommentState => ({ error, changed: previous.changed }); + await requireTeamSession(detailPath(projectId, requirementId)); + const body = String(formData.get("body") ?? ""); + const commentId = String(formData.get("commentId") ?? ""); + if (!body.trim()) return fail("A comment can’t be empty. Delete it instead."); + if (!isUuid(projectId) || !isUuid(requirementId) || !isUuid(commentId)) return fail(failed); + try { + const response = await apiFetch(`/requirements/${requirementId}/comments/${commentId}`, { method: "PATCH", body: JSON.stringify({ body }) }); + if (response.status === 400) return fail(fieldError(await response.json(), "body") ?? failed); + if (response.status === 403 || response.status === 409) return fail(problemDetail(await response.json()) ?? failed); + if (response.status === 404) return fail("This comment is no longer available."); + if (!response.ok) throw new Error(`Edit comment returned ${response.status}.`); + } catch (error) { + console.error("Edit comment failed", error); + return fail(failed); + } + revalidatePath(detailPath(projectId, requirementId), "layout"); + return { error: null, changed: previous.changed + 1 }; +} + +/** Deletes a comment. Its replies stay; the deletion is kept in the requirement's history. */ +export async function deleteComment( + projectId: string, requirementId: string, previous: CommentState, formData: FormData, +): Promise { + const failed = "The comment could not be deleted. Please try again."; + const fail = (error: string): CommentState => ({ error, changed: previous.changed }); + await requireTeamSession(detailPath(projectId, requirementId)); + const commentId = String(formData.get("commentId") ?? ""); + if (!isUuid(projectId) || !isUuid(requirementId) || !isUuid(commentId)) return fail(failed); + try { + const response = await apiFetch(`/requirements/${requirementId}/comments/${commentId}`, { method: "DELETE" }); + if (response.status === 403 || response.status === 409) return fail(problemDetail(await response.json()) ?? failed); + // Already deleted, for example by someone else: show the thread as it is now. + if (!response.ok && response.status !== 404) throw new Error(`Delete comment returned ${response.status}.`); + } catch (error) { + console.error("Delete comment failed", error); + return fail(failed); + } + revalidatePath(detailPath(projectId, requirementId), "layout"); + return { error: null, changed: previous.changed + 1 }; +} diff --git a/app/web/src/components/requirement-comments.tsx b/app/web/src/components/requirement-comments.tsx new file mode 100644 index 0000000..0f69fd1 --- /dev/null +++ b/app/web/src/components/requirement-comments.tsx @@ -0,0 +1,169 @@ +"use client"; + +import { useActionState, useState } from "react"; +import { addComment, deleteComment, editComment, type CommentState } from "@/app/projects/comment-actions"; +import { COMMENT_MAX, canDeleteComment, canEditComment, threadComments, type Comment, type Comments } from "@/lib/comments"; +import { formatDateTime } from "@/lib/projects"; +import type { TeamRole } from "@/lib/team-types"; + +type Context = { + projectId: string; + requirementId: string; + viewerId: string; + role: TeamRole; + /** Names of the project's members by user ID. */ + people: Record; + /** False while the requirement or project is archived: the discussion is read-only. */ + open: boolean; +}; + +const initial: CommentState = { error: null, changed: 0 }; + +/** + * The requirement's discussion (ADR-059): top-level comments oldest first, each with its replies. + * Every team member, Observers included, can comment and reply while the requirement is open. + * Comments never change the requirement, its evidence, or its review status. + */ +export function RequirementComments({ comments, ...context }: Context & { comments: Comments | null }) { + const [added, add, adding] = useActionState(addComment.bind(null, context.projectId, context.requirementId), initial); + // Controlled, because React resets a form's uncontrolled fields after every action, even a failed one. + const [draft, setDraft] = useState(""); + const [posted, setPosted] = useState(0); + if (added.changed !== posted) { + setPosted(added.changed); + setDraft(""); + } + if (comments === null) return

Comments can't be shown right now. Try again in a few minutes.

; + const threads = threadComments(comments.comments); + + return ( + <> + {threads.length === 0 + ?

No comments yet.

+ : ( +
    + {threads.map(thread => ( +
  1. + + {thread.replies.length > 0 && ( +
      + {thread.replies.map(reply =>
    1. )} +
    + )} +
  2. + ))} +
+ )} + {context.open ? ( +
+
+ +