diff --git a/app/permissions.ts b/app/permissions.ts index ee79929ce..44cff55bc 100644 --- a/app/permissions.ts +++ b/app/permissions.ts @@ -46,7 +46,11 @@ interface CanDeleteCommentArgs { } export function canDeleteComment(args: CanDeleteCommentArgs) { if (isFirstSuggestion(args)) { - return allTruthy([!isVotingActive(), isOwnComment(args)]); + return allTruthy([ + !isVotingActive(), + isOwnComment(args), + suggestionHasNoOtherComments(args), + ]); } return isOwnComment(args); @@ -106,6 +110,21 @@ function isOwnComment({ author, user }: CanDeleteCommentArgs) { return author.id === user?.id; } +function suggestionHasNoOtherComments({ + suggestions, + suggestionId, +}: Pick) { + for (const suggestedUser of Object.values(suggestions).flat()) { + for (const suggestion of suggestedUser.suggestions) { + if (suggestion.id !== suggestionId) continue; + + return suggestedUser.suggestions.length === 1; + } + } + + throw new Error(`Invalid suggestion id: ${suggestionId}`); +} + interface CanSuggestNewUserFEArgs { user?: Pick; suggestions: plusSuggestions.FindVisibleForUser; diff --git a/app/utils/arrays.ts b/app/utils/arrays.ts index fd025a626..c57bc7a48 100644 --- a/app/utils/arrays.ts +++ b/app/utils/arrays.ts @@ -1,3 +1,4 @@ +// xxx: should instead take array of functions to improve efficiency (not run them all if not necessary) export function allTruthy(arr: unknown[]) { return arr.every(Boolean); }