From ed12978073ddaf667f32d41c3be68a72f6a6b8de Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Sat, 4 Jun 2022 10:57:31 +0300 Subject: [PATCH] Can't delete suggestion if it has comments --- app/permissions.ts | 21 ++++++++++++++++++++- app/utils/arrays.ts | 1 + 2 files changed, 21 insertions(+), 1 deletion(-) 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); }