From 68a042cdb97bf00b496328a79660be97d150b660 Mon Sep 17 00:00:00 2001 From: Keith Holliday Date: Mon, 27 Feb 2017 13:58:30 -0700 Subject: [PATCH] Leaving a group (#8517) * Leaving a group or a guild no longer removes the user from the challenges of that group or guild. * Updating api docs for leaving group to take into account the default path no longer leaving challenges when leaving a group. * Updating api docs for leaving group to take into account the default path no longer leaving challenges when leaving a group. * refactored according to blade's comments to not be a breaking change. The api now accepts a body parameter to specify wether the user should remain in the groups challenges or leave them. The change also adds more tests around this behavior to confirm that it works as expected. --- .../groups/POST-groups_groupId_leave.js | 19 +- .../v3/integration/user/DELETE-user.test.js | 25 + .../client-old/js/controllers/guildsCtrl.js | 2 +- .../client-old/js/controllers/partyCtrl.js | 4 +- .../client-old/js/services/groupServices.js | 3 +- website/common/locales/en/groups.json | 515 +++++++++--------- .../server/controllers/api-v3/challenges.js | 2 - website/server/controllers/api-v3/groups.js | 6 +- website/server/models/challenge.js | 5 +- website/server/models/group.js | 22 +- 10 files changed, 324 insertions(+), 279 deletions(-) diff --git a/test/api/v3/integration/groups/POST-groups_groupId_leave.js b/test/api/v3/integration/groups/POST-groups_groupId_leave.js index 60d6ee6bd2..8ef0651d40 100644 --- a/test/api/v3/integration/groups/POST-groups_groupId_leave.js +++ b/test/api/v3/integration/groups/POST-groups_groupId_leave.js @@ -78,7 +78,7 @@ describe('POST /groups/:groupId/leave', () => { expect(leader.newMessages[groupToLeave._id]).to.be.empty; }); - context('With challenges', () => { + context('with challenges', () => { let challenge; beforeEach(async () => { @@ -106,10 +106,25 @@ describe('POST /groups/:groupId/leave', () => { let userWithChallengeTasks = await leader.get('/user'); - expect(userWithChallengeTasks.challenges).to.not.include(challenge._id); // @TODO find elegant way to assert against the task existing expect(userWithChallengeTasks.tasksOrder.habits).to.not.be.empty; }); + + it('keeps the user in the challenge when the keepChallenges parameter is set to remain-in-challenges', async () => { + await leader.post(`/groups/${groupToLeave._id}/leave`, {keepChallenges: 'remain-in-challenges'}); + + let userWithChallengeTasks = await leader.get('/user'); + + expect(userWithChallengeTasks.challenges).to.include(challenge._id); + }); + + it('drops the user in the challenge when the keepChallenges parameter isn\'t set', async () => { + await leader.post(`/groups/${groupToLeave._id}/leave`); + + let userWithChallengeTasks = await leader.get('/user'); + + expect(userWithChallengeTasks.challenges).to.not.include(challenge._id); + }); }); it('prevents quest leader from leaving a groupToLeave'); diff --git a/test/api/v3/integration/user/DELETE-user.test.js b/test/api/v3/integration/user/DELETE-user.test.js index d0e4504135..de559c430d 100644 --- a/test/api/v3/integration/user/DELETE-user.test.js +++ b/test/api/v3/integration/user/DELETE-user.test.js @@ -3,6 +3,7 @@ import { createAndPopulateGroup, generateGroup, generateUser, + generateChallenge, translate as t, } from '../../../../helpers/api-integration/v3'; import { @@ -64,6 +65,30 @@ describe('DELETE /user', () => { })); }); + it('reduces memberCount in challenges user is linked to', async () => { + let populatedGroup = await createAndPopulateGroup({ + members: 2, + }); + + let group = populatedGroup.group; + let authorizedUser = populatedGroup.members[1]; + + let challenge = await generateChallenge(populatedGroup.groupLeader, group); + await authorizedUser.post(`/challenges/${challenge._id}/join`); + + await challenge.sync(); + + expect(challenge.memberCount).to.eql(2); + + await authorizedUser.del('/user', { + password, + }); + + await challenge.sync(); + + expect(challenge.memberCount).to.eql(1); + }); + it('deletes the user', async () => { await user.del('/user', { password, diff --git a/website/client-old/js/controllers/guildsCtrl.js b/website/client-old/js/controllers/guildsCtrl.js index 3cba1aa6e1..16cb39dde1 100644 --- a/website/client-old/js/controllers/guildsCtrl.js +++ b/website/client-old/js/controllers/guildsCtrl.js @@ -71,7 +71,7 @@ habitrpg.controller("GuildsCtrl", ['$scope', 'Groups', 'User', 'Challenges', '$r $scope.selectedGroup = undefined; $scope.popoverEl.popover('destroy'); } else { - Groups.Group.leave($scope.selectedGroup._id, keep) + Groups.Group.leave($scope.selectedGroup._id, keep, 'remain-in-challenges') .success(function (data) { var index = User.user.guilds.indexOf($scope.selectedGroup._id); delete User.user.guilds[index]; diff --git a/website/client-old/js/controllers/partyCtrl.js b/website/client-old/js/controllers/partyCtrl.js index 8e3f760cd3..829546184b 100644 --- a/website/client-old/js/controllers/partyCtrl.js +++ b/website/client-old/js/controllers/partyCtrl.js @@ -134,7 +134,7 @@ habitrpg.controller("PartyCtrl", ['$rootScope','$scope','Groups','Chat','User',' $scope.selectedGroup = undefined; $scope.popoverEl.popover('destroy'); } else { - Groups.Group.leave($scope.selectedGroup._id, keep) + Groups.Group.leave($scope.selectedGroup._id, keep, 'remain-in-challenges') .then(function (response) { Analytics.updateUser({'partySize':null,'partyID':null}); User.sync().then(function () { @@ -197,7 +197,7 @@ habitrpg.controller("PartyCtrl", ['$rootScope','$scope','Groups','Chat','User',' $scope.leaveOldPartyAndJoinNewParty = function(newPartyId, newPartyName) { if (confirm('Are you sure you want to delete your party and join ' + newPartyName + '?')) { - Groups.Group.leave(Groups.data.party._id, false) + Groups.Group.leave(Groups.data.party._id, false, 'remain-in-challenges') .then(function() { $rootScope.party = $scope.group = { loadingParty: true diff --git a/website/client-old/js/services/groupServices.js b/website/client-old/js/services/groupServices.js index 65f24cf6c3..88883f5900 100644 --- a/website/client-old/js/services/groupServices.js +++ b/website/client-old/js/services/groupServices.js @@ -69,12 +69,13 @@ angular.module('habitrpg') }); }; - Group.leave = function(gid, keep) { + Group.leave = function(gid, keep, keepChallenges) { return $http({ method: "POST", url: groupApiURLPrefix + '/' + gid + '/leave', data: { keep: keep, + keepChallenges: keepChallenges, } }); }; diff --git a/website/common/locales/en/groups.json b/website/common/locales/en/groups.json index 5dbae2e062..19eb5b3f18 100644 --- a/website/common/locales/en/groups.json +++ b/website/common/locales/en/groups.json @@ -1,257 +1,258 @@ -{ - "tavern": "Tavern Chat", - "innCheckOut": "Check Out of Inn", - "innCheckIn": "Rest in the Inn", - "innText": "You're resting in the Inn! While checked-in, your Dailies won't hurt you at the day's end, but they will still refresh every day. Be warned: If you are participating in a Boss Quest, the Boss will still damage you for your party mates' missed Dailies unless they are also in the Inn! Also, your own damage to the Boss (or items collected) will not be applied until you check out of the Inn.", - "innTextBroken": "You're resting in the Inn, I guess... While checked-in, your Dailies won't hurt you at the day's end, but they will still refresh every day... If you are participating in a Boss Quest, the Boss will still damage you for your party mates' missed Dailies... unless they are also in the Inn... Also, your own damage to the Boss (or items collected) will not be applied until you check out of the Inn... so tired...", - "lfgPosts": "Looking for Group (Party Wanted) Posts", - "tutorial": "Tutorial", - "glossary": "Glossary", - "wiki": "Wiki", - "wikiLink": "Wiki", - "reportAP": "Report a Problem", - "requestAF": "Request a Feature", - "community": "Community Forum", - "dataTool": "Data Display Tool", - "resources": "Resources", - "askQuestionNewbiesGuild": "Ask a Question (Habitica Help guild)", - "tavernAlert1": "To report a bug, visit", - "tavernAlert2": "the Report a Bug Guild", - "moderatorIntro1": "Tavern and guild moderators are: ", - "communityGuidelines": "Community Guidelines", - "communityGuidelinesRead1": "Please read our", - "communityGuidelinesRead2": "before chatting.", - "party": "Party", - "createAParty": "Create A Party", - "updatedParty": "Party settings updated.", - "noPartyText": "You are either not in a party or your party is taking a while to load. You can either create one and invite friends, or if you want to join an existing party, have them enter your Unique User ID below and then come back here to look for the invitation:", - "LFG": "To advertise your new party or find one to join, go to the <%= linkStart %>Party Wanted (Looking for Group)<%= linkEnd %> Guild.", - "wantExistingParty": "Want to join an existing party? Go to the <%= linkStart %>Party Wanted Guild<%= linkEnd %> and post this User ID:", - "joinExistingParty": "Join Someone Else's Party", - "needPartyToStartQuest": "Whoops! You need to create or join a party before you can start a quest!", - "create": "Create", - "userId": "User ID", - "invite": "Invite", - "leave": "Leave", - "invitedTo": "Invited to <%= name %>", - "invitedToNewParty": "You were invited to join a party! Do you want to leave this party and join <%= partyName %>?", - "invitationAcceptedHeader": "Your Invitation has been Accepted", - "invitationAcceptedBody": "<%= username %> accepted your invitation to <%= groupName %>!", - "joinNewParty": "Join New Party", - "declineInvitation": "Decline Invitation", - "partyLoading1": "Your party is being summoned. Please wait...", - "partyLoading2": "Your party is coming in from battle. Please wait...", - "partyLoading3": "Your party is gathering. Please wait...", - "partyLoading4": "Your party is materializing. Please wait...", - "systemMessage": "System Message", - "newMsg": "New message in \"<%= name %>\"", - "chat": "Chat", - "sendChat": "Send Chat", - "toolTipMsg": "Fetch Recent Messages", - "sendChatToolTip": "You can send a chat from the keyboard by tabbing to the 'Send Chat' button and pressing Enter or by pressing Control (Command on a Mac) + Enter.", - "syncPartyAndChat": "Sync Party and Chat", - "guildBankPop1": "Guild Bank", - "guildBankPop2": "Gems which your guild leader can use for challenge prizes.", - "guildGems": "Guild Gems", - "editGroup": "Edit Group", - "newGroupName": "<%= groupType %> Name", - "groupName": "Group Name", - "groupLeader": "Group Leader", - "groupID": "Group ID", - "groupDescr": "Description shown in public Guilds list (Markdown OK)", - "logoUrl": "Logo URL", - "assignLeader": "Assign Group Leader", - "members": "Members", - "partyList": "Order for party members in header", - "banTip": "Boot Member", - "moreMembers": "more members", - "invited": "Invited", - "leaderMsg": "Message from group leader (Markdown OK)", - "name": "Name", - "description": "Description", - "public": "Public", - "inviteOnly": "Invite Only", - "gemCost": "The Gem cost promotes high quality Guilds, and is transferred into your Guild's bank for use as prizes in Guild Challenges!", - "search": "Search", - "publicGuilds": "Public Guilds", - "createGuild": "Create Guild", - "guild": "Guild", - "guilds": "Guilds", - "guildsLink": "Guilds", - "sureKick": "Do you really want to remove this member from the party/guild?", - "optionalMessage": "Optional message", - "yesRemove": "Yes, remove them", - "foreverAlone": "Can't like your own message. Don't be that person.", - "sortLevel": "Sort by level", - "sortRandom": "Sort randomly", - "sortPets": "Sort by number of pets", - "sortName": "Sort by avatar name", - "sortBackgrounds": "Sort by background", - "sortHabitrpgJoined": "Sort by Habitica date joined", - "sortHabitrpgLastLoggedIn": "Sort by last time user logged in", - "ascendingSort": "Sort Ascending", - "descendingSort": "Sort Descending", - "confirmGuild": "Create Guild for 4 Gems?", - "leaveGroupCha": "Leave Guild challenges and...", - "confirm": "Confirm", - "leaveGroup": "Leave Guild?", - "leavePartyCha": "Leave party challenges and...", - "leaveParty": "Leave party?", - "sendPM": "Send private message", - "send": "Send", - "messageSentAlert": "Message sent", - "pmHeading": "Private message to <%= name %>", - "pmsMarkedRead": "Your private messages have been marked as read", - "clearAll": "Delete All Messages", - "confirmDeleteAllMessages": "Are you sure you want to delete all messages in your inbox? Other users will still see messages you have sent to them.", - "optOutPopover": "Don't like private messages? Click to completely opt out", - "block": "Block", - "unblock": "Un-block", - "pm-reply": "Send a reply", - "inbox": "Inbox", - "messageRequired": "A message is required.", - "toUserIDRequired": "A User ID is required", - "gemAmountRequired": "A number of gems is required", - "notAuthorizedToSendMessageToThisUser": "Can't send message to this user.", - "privateMessageGiftGemsMessage": "Hello <%= receiverName %>, <%= senderName %> has sent you <%= gemAmount %> gems!", - "privateMessageGiftSubscriptionMessage": "<%= numberOfMonths %> months of subscription! ", - "cannotSendGemsToYourself": "Cannot send gems to yourself. Try a subscription instead.", - "badAmountOfGemsToSend": "Amount must be within 1 and your current number of gems.", - "abuseFlag": "Report violation of Community Guidelines", - "abuseFlagModalHeading": "Report <%= name %> for violation?", - "abuseFlagModalBody": "Are you sure you want to report this post? You should ONLY report a post that violates the <%= firstLinkStart %>Community Guidelines<%= linkEnd %> and/or <%= secondLinkStart %>Terms of Service<%= linkEnd %>. Inappropriately reporting a post is a violation of the Community Guidelines and may give you an infraction. Appropriate reasons to flag a post include but are not limited to:

", - "abuseFlagModalButton": "Report Violation", - "abuseReported": "Thank you for reporting this violation. The moderators have been notified.", - "abuseAlreadyReported": "You have already reported this message.", - "needsText": "Please type a message.", - "needsTextPlaceholder": "Type your message here.", - "copyMessageAsToDo": "Copy message as To-Do", - "messageAddedAsToDo": "Message copied as To-Do.", - "messageWroteIn": "<%= user %> wrote in <%= group %>", - "taskFromInbox": "<%= from %> wrote '<%= message %>'", - "taskTextFromInbox": "Message from <%= from %>", - "msgPreviewHeading": "Message Preview", - "leaderOnlyChallenges": "Only group leader can create challenges", - "sendGift": "Send Gift", - "inviteFriends": "Invite Friends", - "inviteByEmail": "Invite by Email", - "inviteByEmailExplanation": "If a friend joins Habitica via your email, they'll automatically be invited to your party!", - "inviteFriendsNow": "Invite Friends Now", - "inviteFriendsLater": "Invite Friends Later", - "inviteAlertInfo": "If you have friends already using Habitica, invite them by User ID here.", - "inviteExistUser": "Invite Existing Users", - "byColon": "By:", - "inviteNewUsers": "Invite New Users", - "sendInvitations": "Send Invitations", - "invitationsSent": "Invitations sent!", - "invitationSent": "Invitation sent!", - "inviteAlertInfo2": "Or share this link (copy/paste):", - "sendGiftHeading": "Send Gift to <%= name %>", - "sendGiftGemsBalance": "From <%= number %> Gems", - "sendGiftCost": "Total: $<%= cost %> USD", - "sendGiftFromBalance": "From Balance", - "sendGiftPurchase": "Purchase", - "sendGiftMessagePlaceholder": "Personal message (optional)", - "sendGiftSubscription": "<%= months %> Month(s): $<%= price %> USD", - "battleWithFriends": "Battle Monsters With Friends", - "startPartyWithFriends": "Start a Party with your friends!", - "startAParty": "Start a Party", - "addToParty": "Add someone to your party", - "likePost": "Click if you like this post!", - "partyExplanation1": "Play Habitica with friends to stay accountable!", - "partyExplanation2": "Battle monsters and create Challenges!", - "partyExplanation3": "Invite friends now to earn a Quest Scroll!", - "wantToStartParty": "Do you want to start a party?", - "exclusiveQuestScroll": "Inviting a friend to your party will grant you an exclusive Quest Scroll to battle the Basi-List together!", - "nameYourParty": "Name your new party!", - "partyEmpty": "You're the only one in your party. Invite your friends!", - "partyChatEmpty": "Your party chat is empty! Type a message in the box above to start chatting.", - "guildChatEmpty": "This guild's chat is empty! Type a message in the box above to start chatting.", - "possessiveParty": "<%= name %>'s Party", - "requestAcceptGuidelines": "If you would like to post messages in the Tavern or any party or guild chat, please first read our <%= linkStart %>Community Guidelines<%= linkEnd %> and then click the button below to indicate that you accept them.", - "partyUpName": "Party Up", - "partyOnName": "Party On", - "partyUpText": "Joined a Party with another person! Have fun battling monsters and supporting each other.", - "partyOnText": "Joined a Party with at least four people! Enjoy your increased accountability as you unite with your friends to vanquish your foes!", - "largeGroupNote": "Note: This Guild is now too large to support notifications! Be sure to check back every day to see new messages.", - "groupIdRequired": "\"groupId\" must be a valid UUID", - "groupNotFound": "Group not found or you don't have access.", - "groupTypesRequired": "You must supply a valid \"type\" query string.", - "questLeaderCannotLeaveGroup": "You cannot leave your party when you have started a quest. Abort the quest first.", - "cannotLeaveWhileActiveQuest": "You cannot leave party during an active quest. Please leave the quest first.", - "onlyLeaderCanRemoveMember": "Only group leader can remove a member!", - "memberCannotRemoveYourself": "You cannot remove yourself!", - "groupMemberNotFound": "User not found among group's members", - "mustBeGroupMember": "Must be member of the group.", - "keepOrRemoveAll": "req.query.keep must be either \"keep-all\" or \"remove-all\"", - "keepOrRemove": "req.query.keep must be either \"keep\" or \"remove\"", - "canOnlyInviteEmailUuid": "Can only invite using uuids or emails.", - "inviteMissingEmail": "Missing email address in invite.", - "inviteMissingUuid": "Missing user id in invite", - "inviteMustNotBeEmpty": "Invite must not be empty.", - "partyMustbePrivate": "Parties must be private", - "userAlreadyInGroup": "User already in that group.", - "cannotInviteSelfToGroup": "You cannot invite yourself to a group.", - "userAlreadyInvitedToGroup": "User already invited to that group.", - "userAlreadyPendingInvitation": "User already pending invitation.", - "userAlreadyInAParty": "User already in a party.", - "userWithIDNotFound": "User with id \"<%= userId %>\" not found.", - "userHasNoLocalRegistration": "User does not have a local registration (username, email, password).", - "uuidsMustBeAnArray": "User ID invites must be an array.", - "emailsMustBeAnArray": "Email address invites must be an array.", - "canOnlyInviteMaxInvites": "You can only invite \"<%= maxInvites %>\" at a time", - "onlyCreatorOrAdminCanDeleteChat": "Not authorized to delete this message!", - "onlyGroupLeaderCanEditTasks": "Not authorized to manage tasks!", - "onlyGroupTasksCanBeAssigned": "Only group tasks can be assigned", - "newChatMessagePlainNotification": "New message in <%= groupName %> by <%= authorName %>. Click here to open the chat page!", - "newChatMessageTitle": "New message in <%= groupName %>", - "exportInbox": "Export Messages", - "exportInboxPopoverTitle": "Export your messages as HTML", - "exportInboxPopoverBody": "HTML allows easy reading of messages in a browser. For a machine-readable format, use Data > Export Data", - "to": "To:", - "from": "From:", - "desktopNotificationsText": "We need your permission to enable desktop notifications for new messages in party chat! Follow your browser's instructions to turn them on.

You'll receive these notifications only while you have Habitica open. If you decide you don't like them, they can be disabled in your browser's settings.

This box will close automatically when a decision is made.", - "confirmAddTag": "Do you want to assign this task to \"<%= tag %>\"?", - "confirmRemoveTag": "Do you really want to remove \"<%= tag %>\"?", - - "groupHomeTitle": "Home", - "assignTask": "Assign Task", - "desktopNotificationsText": "We need your permission to enable desktop notifications for new messages in party chat! Follow your browser's instructions to turn them on.

You'll receive these notifications only while you have Habitica open. If you decide you don't like them, they can be disabled in your browser's settings.

This box will close automatically when a decision is made.", - "claim": "Claim", - "onlyGroupLeaderCanManageSubscription": "Only the group leader can manage the group's subscription", - "yourTaskHasBeenApproved": "Your task \"<%= taskText %>\" has been approved", - "userHasRequestedTaskApproval": "<%= user %> has requested task approval for <%= taskName %>", - "approve": "Approve", - "approvalTitle": "<%= text %> for user: <%= userName %>", - "confirmTaskApproval": "Do you want to reward <%= username %> for completing this task?", - "groupSubscriptionPrice": "$9 every month + $3 a month for every additional group member", - "groupAdditionalUserCost": " +$3.00/month/user", - - "groupBenefitsTitle": "How a group plan can help you", - "groupBenefitsDescription": "We've just launched the beta version of our group plans! Upgrading to a group plan unlocks some unique features to optimize the social side of Habitica.", - "groupBenefitOneTitle": "Create a shared task list", - "groupBenefitOneDescription": "Set up a shared task list for the group that everyone can easily view and edit.", - "groupBenefitTwoTitle": "Assign tasks to group members", - "groupBenefitTwoDescription": "Want a coworker to answer a critical email? Need your roommate to pick up the groceries? Just assign them the tasks you create, and they'll automatically appear in that person's task dashboard.", - "groupBenefitThreeTitle": "Claim a task that you are working on", - "groupBenefitThreeDescription": "Stake your claim on any group task with a simple click. Make it clear what everybody is working on!", - "groupBenefitFourTitle": "Mark tasks that require special approval", - "groupBenefitFourDescription": "Need to verify that a task really did get done before that user gets their rewards? Just adjust the approval settings for added control.", - "groupBenefitFiveTitle": "Chat privately with your group", - "groupBenefitFiveDescription": "Stay in the loop about important decisions in our easy-to-use chatroom!", - "createAGroup": "Create a Group", - "assignFieldPlaceholder": "Type a group member's profile name", - "cannotDeleteActiveGroup": "You cannot remove a group with an active subscription", - "groupTasksTitle": "Group Tasks List", - "approvalsTitle": "Tasks Awaiting Approval", - "upgradeTitle": "Upgrade", - "blankApprovalsDescription": "When your group completes tasks that need your approval, they'll appear here! Adjust approval requirement settings under task editing.", - "userIsClamingTask": "`<%= username %> has claimed \"<%= task %>\"`", - "approvalRequested": "Approval Requested", - "refreshApprovals": "Refresh Approvals", - "refreshGroupTasks": "Refresh Group Tasks", - "claimedBy": "\n\nClaimed by: <%= claimingUsers %>", - "cantDeleteAssignedGroupTasks": "Can't delete group tasks that are assigned to you.", - "confirmGuildPlanCreation": "Create this group?", - "onlyGroupLeaderCanInviteToGroupPlan": "Only the group leader can invite users to a group with a subscription." -} +{ + "tavern": "Tavern Chat", + "innCheckOut": "Check Out of Inn", + "innCheckIn": "Rest in the Inn", + "innText": "You're resting in the Inn! While checked-in, your Dailies won't hurt you at the day's end, but they will still refresh every day. Be warned: If you are participating in a Boss Quest, the Boss will still damage you for your party mates' missed Dailies unless they are also in the Inn! Also, your own damage to the Boss (or items collected) will not be applied until you check out of the Inn.", + "innTextBroken": "You're resting in the Inn, I guess... While checked-in, your Dailies won't hurt you at the day's end, but they will still refresh every day... If you are participating in a Boss Quest, the Boss will still damage you for your party mates' missed Dailies... unless they are also in the Inn... Also, your own damage to the Boss (or items collected) will not be applied until you check out of the Inn... so tired...", + "lfgPosts": "Looking for Group (Party Wanted) Posts", + "tutorial": "Tutorial", + "glossary": "Glossary", + "wiki": "Wiki", + "wikiLink": "Wiki", + "reportAP": "Report a Problem", + "requestAF": "Request a Feature", + "community": "Community Forum", + "dataTool": "Data Display Tool", + "resources": "Resources", + "askQuestionNewbiesGuild": "Ask a Question (Habitica Help guild)", + "tavernAlert1": "To report a bug, visit", + "tavernAlert2": "the Report a Bug Guild", + "moderatorIntro1": "Tavern and guild moderators are: ", + "communityGuidelines": "Community Guidelines", + "communityGuidelinesRead1": "Please read our", + "communityGuidelinesRead2": "before chatting.", + "party": "Party", + "createAParty": "Create A Party", + "updatedParty": "Party settings updated.", + "noPartyText": "You are either not in a party or your party is taking a while to load. You can either create one and invite friends, or if you want to join an existing party, have them enter your Unique User ID below and then come back here to look for the invitation:", + "LFG": "To advertise your new party or find one to join, go to the <%= linkStart %>Party Wanted (Looking for Group)<%= linkEnd %> Guild.", + "wantExistingParty": "Want to join an existing party? Go to the <%= linkStart %>Party Wanted Guild<%= linkEnd %> and post this User ID:", + "joinExistingParty": "Join Someone Else's Party", + "needPartyToStartQuest": "Whoops! You need to create or join a party before you can start a quest!", + "create": "Create", + "userId": "User ID", + "invite": "Invite", + "leave": "Leave", + "invitedTo": "Invited to <%= name %>", + "invitedToNewParty": "You were invited to join a party! Do you want to leave this party and join <%= partyName %>?", + "invitationAcceptedHeader": "Your Invitation has been Accepted", + "invitationAcceptedBody": "<%= username %> accepted your invitation to <%= groupName %>!", + "joinNewParty": "Join New Party", + "declineInvitation": "Decline Invitation", + "partyLoading1": "Your party is being summoned. Please wait...", + "partyLoading2": "Your party is coming in from battle. Please wait...", + "partyLoading3": "Your party is gathering. Please wait...", + "partyLoading4": "Your party is materializing. Please wait...", + "systemMessage": "System Message", + "newMsg": "New message in \"<%= name %>\"", + "chat": "Chat", + "sendChat": "Send Chat", + "toolTipMsg": "Fetch Recent Messages", + "sendChatToolTip": "You can send a chat from the keyboard by tabbing to the 'Send Chat' button and pressing Enter or by pressing Control (Command on a Mac) + Enter.", + "syncPartyAndChat": "Sync Party and Chat", + "guildBankPop1": "Guild Bank", + "guildBankPop2": "Gems which your guild leader can use for challenge prizes.", + "guildGems": "Guild Gems", + "editGroup": "Edit Group", + "newGroupName": "<%= groupType %> Name", + "groupName": "Group Name", + "groupLeader": "Group Leader", + "groupID": "Group ID", + "groupDescr": "Description shown in public Guilds list (Markdown OK)", + "logoUrl": "Logo URL", + "assignLeader": "Assign Group Leader", + "members": "Members", + "partyList": "Order for party members in header", + "banTip": "Boot Member", + "moreMembers": "more members", + "invited": "Invited", + "leaderMsg": "Message from group leader (Markdown OK)", + "name": "Name", + "description": "Description", + "public": "Public", + "inviteOnly": "Invite Only", + "gemCost": "The Gem cost promotes high quality Guilds, and is transferred into your Guild's bank for use as prizes in Guild Challenges!", + "search": "Search", + "publicGuilds": "Public Guilds", + "createGuild": "Create Guild", + "guild": "Guild", + "guilds": "Guilds", + "guildsLink": "Guilds", + "sureKick": "Do you really want to remove this member from the party/guild?", + "optionalMessage": "Optional message", + "yesRemove": "Yes, remove them", + "foreverAlone": "Can't like your own message. Don't be that person.", + "sortLevel": "Sort by level", + "sortRandom": "Sort randomly", + "sortPets": "Sort by number of pets", + "sortName": "Sort by avatar name", + "sortBackgrounds": "Sort by background", + "sortHabitrpgJoined": "Sort by Habitica date joined", + "sortHabitrpgLastLoggedIn": "Sort by last time user logged in", + "ascendingSort": "Sort Ascending", + "descendingSort": "Sort Descending", + "confirmGuild": "Create Guild for 4 Gems?", + "leaveGroupCha": "Leave Guild challenges and...", + "confirm": "Confirm", + "leaveGroup": "Leave Guild?", + "leavePartyCha": "Leave party challenges and...", + "leaveParty": "Leave party?", + "sendPM": "Send private message", + "send": "Send", + "messageSentAlert": "Message sent", + "pmHeading": "Private message to <%= name %>", + "pmsMarkedRead": "Your private messages have been marked as read", + "possessiveParty": "<%= name %>'s Party", + "clearAll": "Delete All Messages", + "confirmDeleteAllMessages": "Are you sure you want to delete all messages in your inbox? Other users will still see messages you have sent to them.", + "optOutPopover": "Don't like private messages? Click to completely opt out", + "block": "Block", + "unblock": "Un-block", + "pm-reply": "Send a reply", + "inbox": "Inbox", + "messageRequired": "A message is required.", + "toUserIDRequired": "A User ID is required", + "gemAmountRequired": "A number of gems is required", + "notAuthorizedToSendMessageToThisUser": "Can't send message to this user.", + "privateMessageGiftGemsMessage": "Hello <%= receiverName %>, <%= senderName %> has sent you <%= gemAmount %> gems!", + "privateMessageGiftSubscriptionMessage": "<%= numberOfMonths %> months of subscription! ", + "cannotSendGemsToYourself": "Cannot send gems to yourself. Try a subscription instead.", + "badAmountOfGemsToSend": "Amount must be within 1 and your current number of gems.", + "abuseFlag": "Report violation of Community Guidelines", + "abuseFlagModalHeading": "Report <%= name %> for violation?", + "abuseFlagModalBody": "Are you sure you want to report this post? You should ONLY report a post that violates the <%= firstLinkStart %>Community Guidelines<%= linkEnd %> and/or <%= secondLinkStart %>Terms of Service<%= linkEnd %>. Inappropriately reporting a post is a violation of the Community Guidelines and may give you an infraction. Appropriate reasons to flag a post include but are not limited to:

", + "abuseFlagModalButton": "Report Violation", + "abuseReported": "Thank you for reporting this violation. The moderators have been notified.", + "abuseAlreadyReported": "You have already reported this message.", + "needsText": "Please type a message.", + "needsTextPlaceholder": "Type your message here.", + "copyMessageAsToDo": "Copy message as To-Do", + "messageAddedAsToDo": "Message copied as To-Do.", + "messageWroteIn": "<%= user %> wrote in <%= group %>", + "taskFromInbox": "<%= from %> wrote '<%= message %>'", + "taskTextFromInbox": "Message from <%= from %>", + "msgPreviewHeading": "Message Preview", + "leaderOnlyChallenges": "Only group leader can create challenges", + "sendGift": "Send Gift", + "inviteFriends": "Invite Friends", + "inviteByEmail": "Invite by Email", + "inviteByEmailExplanation": "If a friend joins Habitica via your email, they'll automatically be invited to your party!", + "inviteFriendsNow": "Invite Friends Now", + "inviteFriendsLater": "Invite Friends Later", + "inviteAlertInfo": "If you have friends already using Habitica, invite them by User ID here.", + "inviteExistUser": "Invite Existing Users", + "byColon": "By:", + "inviteNewUsers": "Invite New Users", + "sendInvitations": "Send Invitations", + "invitationsSent": "Invitations sent!", + "invitationSent": "Invitation sent!", + "inviteAlertInfo2": "Or share this link (copy/paste):", + "sendGiftHeading": "Send Gift to <%= name %>", + "sendGiftGemsBalance": "From <%= number %> Gems", + "sendGiftCost": "Total: $<%= cost %> USD", + "sendGiftFromBalance": "From Balance", + "sendGiftPurchase": "Purchase", + "sendGiftMessagePlaceholder": "Personal message (optional)", + "sendGiftSubscription": "<%= months %> Month(s): $<%= price %> USD", + "battleWithFriends": "Battle Monsters With Friends", + "startPartyWithFriends": "Start a Party with your friends!", + "startAParty": "Start a Party", + "addToParty": "Add someone to your party", + "likePost": "Click if you like this post!", + "partyExplanation1": "Play Habitica with friends to stay accountable!", + "partyExplanation2": "Battle monsters and create Challenges!", + "partyExplanation3": "Invite friends now to earn a Quest Scroll!", + "wantToStartParty": "Do you want to start a party?", + "exclusiveQuestScroll": "Inviting a friend to your party will grant you an exclusive Quest Scroll to battle the Basi-List together!", + "nameYourParty": "Name your new party!", + "partyEmpty": "You're the only one in your party. Invite your friends!", + "partyChatEmpty": "Your party chat is empty! Type a message in the box above to start chatting.", + "guildChatEmpty": "This guild's chat is empty! Type a message in the box above to start chatting.", + "possessiveParty": "<%= name %>'s Party", + "requestAcceptGuidelines": "If you would like to post messages in the Tavern or any party or guild chat, please first read our <%= linkStart %>Community Guidelines<%= linkEnd %> and then click the button below to indicate that you accept them.", + "partyUpName": "Party Up", + "partyOnName": "Party On", + "partyUpText": "Joined a Party with another person! Have fun battling monsters and supporting each other.", + "partyOnText": "Joined a Party with at least four people! Enjoy your increased accountability as you unite with your friends to vanquish your foes!", + "largeGroupNote": "Note: This Guild is now too large to support notifications! Be sure to check back every day to see new messages.", + "groupIdRequired": "\"groupId\" must be a valid UUID", + "groupNotFound": "Group not found or you don't have access.", + "groupTypesRequired": "You must supply a valid \"type\" query string.", + "questLeaderCannotLeaveGroup": "You cannot leave your party when you have started a quest. Abort the quest first.", + "cannotLeaveWhileActiveQuest": "You cannot leave party during an active quest. Please leave the quest first.", + "onlyLeaderCanRemoveMember": "Only group leader can remove a member!", + "memberCannotRemoveYourself": "You cannot remove yourself!", + "groupMemberNotFound": "User not found among group's members", + "mustBeGroupMember": "Must be member of the group.", + "keepOrRemoveAll": "req.query.keep must be either \"keep-all\" or \"remove-all\"", + "keepOrRemove": "req.query.keep must be either \"keep\" or \"remove\"", + "canOnlyInviteEmailUuid": "Can only invite using uuids or emails.", + "inviteMissingEmail": "Missing email address in invite.", + "inviteMissingUuid": "Missing user id in invite", + "inviteMustNotBeEmpty": "Invite must not be empty.", + "partyMustbePrivate": "Parties must be private", + "userAlreadyInGroup": "User already in that group.", + "cannotInviteSelfToGroup": "You cannot invite yourself to a group.", + "userAlreadyInvitedToGroup": "User already invited to that group.", + "userAlreadyPendingInvitation": "User already pending invitation.", + "userAlreadyInAParty": "User already in a party.", + "userWithIDNotFound": "User with id \"<%= userId %>\" not found.", + "userHasNoLocalRegistration": "User does not have a local registration (username, email, password).", + "uuidsMustBeAnArray": "User ID invites must be an array.", + "emailsMustBeAnArray": "Email address invites must be an array.", + "canOnlyInviteMaxInvites": "You can only invite \"<%= maxInvites %>\" at a time", + "onlyCreatorOrAdminCanDeleteChat": "Not authorized to delete this message!", + "onlyGroupLeaderCanEditTasks": "Not authorized to manage tasks!", + "onlyGroupTasksCanBeAssigned": "Only group tasks can be assigned", + "newChatMessagePlainNotification": "New message in <%= groupName %> by <%= authorName %>. Click here to open the chat page!", + "newChatMessageTitle": "New message in <%= groupName %>", + "exportInbox": "Export Messages", + "exportInboxPopoverTitle": "Export your messages as HTML", + "exportInboxPopoverBody": "HTML allows easy reading of messages in a browser. For a machine-readable format, use Data > Export Data", + "to": "To:", + "from": "From:", + "desktopNotificationsText": "We need your permission to enable desktop notifications for new messages in party chat! Follow your browser's instructions to turn them on.

You'll receive these notifications only while you have Habitica open. If you decide you don't like them, they can be disabled in your browser's settings.

This box will close automatically when a decision is made.", + "confirmAddTag": "Do you want to assign this task to \"<%= tag %>\"?", + "confirmRemoveTag": "Do you really want to remove \"<%= tag %>\"?", + "groupHomeTitle": "Home", + "assignTask": "Assign Task", + "desktopNotificationsText": "We need your permission to enable desktop notifications for new messages in party chat! Follow your browser's instructions to turn them on.

You'll receive these notifications only while you have Habitica open. If you decide you don't like them, they can be disabled in your browser's settings.

This box will close automatically when a decision is made.", + "claim": "Claim", + "onlyGroupLeaderCanManageSubscription": "Only the group leader can manage the group's subscription", + "yourTaskHasBeenApproved": "Your task \"<%= taskText %>\" has been approved", + "userHasRequestedTaskApproval": "<%= user %> has requested task approval for <%= taskName %>", + "approve": "Approve", + "approvalTitle": "<%= text %> for user: <%= userName %>", + "confirmTaskApproval": "Do you want to reward <%= username %> for completing this task?", + "groupSubscriptionPrice": "$9 every month + $3 a month for every additional group member", + "groupAdditionalUserCost": " +$3.00/month/user", + + "groupBenefitsTitle": "How a group plan can help you", + "groupBenefitsDescription": "We've just launched the beta version of our group plans! Upgrading to a group plan unlocks some unique features to optimize the social side of Habitica.", + "groupBenefitOneTitle": "Create a shared task list", + "groupBenefitOneDescription": "Set up a shared task list for the group that everyone can easily view and edit.", + "groupBenefitTwoTitle": "Assign tasks to group members", + "groupBenefitTwoDescription": "Want a coworker to answer a critical email? Need your roommate to pick up the groceries? Just assign them the tasks you create, and they'll automatically appear in that person's task dashboard.", + "groupBenefitThreeTitle": "Claim a task that you are working on", + "groupBenefitThreeDescription": "Stake your claim on any group task with a simple click. Make it clear what everybody is working on!", + "groupBenefitFourTitle": "Mark tasks that require special approval", + "groupBenefitFourDescription": "Need to verify that a task really did get done before that user gets their rewards? Just adjust the approval settings for added control.", + "groupBenefitFiveTitle": "Chat privately with your group", + "groupBenefitFiveDescription": "Stay in the loop about important decisions in our easy-to-use chatroom!", + "createAGroup": "Create a Group", + "assignFieldPlaceholder": "Type a group member's profile name", + "cannotDeleteActiveGroup": "You cannot remove a group with an active subscription", + "groupTasksTitle": "Group Tasks List", + "approvalsTitle": "Tasks Awaiting Approval", + "upgradeTitle": "Upgrade", + "blankApprovalsDescription": "When your group completes tasks that need your approval, they'll appear here! Adjust approval requirement settings under task editing.", + "userIsClamingTask": "`<%= username %> has claimed \"<%= task %>\"`", + "approvalRequested": "Approval Requested", + "refreshApprovals": "Refresh Approvals", + "refreshGroupTasks": "Refresh Group Tasks", + "claimedBy": "\n\nClaimed by: <%= claimingUsers %>", + "cantDeleteAssignedGroupTasks": "Can't delete group tasks that are assigned to you.", + "confirmGuildPlanCreation": "Create this group?", + "onlyGroupLeaderCanInviteToGroupPlan": "Only the group leader can invite users to a group with a subscription.", + "remainOrLeaveChallenges": "req.query.keep must be either 'remain-in-challenges' or 'leave-challenges'" +} diff --git a/website/server/controllers/api-v3/challenges.js b/website/server/controllers/api-v3/challenges.js index f948e49b39..c19158f38c 100644 --- a/website/server/controllers/api-v3/challenges.js +++ b/website/server/controllers/api-v3/challenges.js @@ -195,8 +195,6 @@ api.leaveChallenge = { if (!challenge.isMember(user)) throw new NotAuthorized(res.t('challengeMemberNotFound')); - challenge.memberCount -= 1; - // Unlink challenge's tasks from user's tasks and save the challenge await Bluebird.all([challenge.unlinkTasks(user, keep), challenge.save()]); res.respond(200, {}); diff --git a/website/server/controllers/api-v3/groups.js b/website/server/controllers/api-v3/groups.js index bbda981787..3b468c72eb 100644 --- a/website/server/controllers/api-v3/groups.js +++ b/website/server/controllers/api-v3/groups.js @@ -524,7 +524,8 @@ function _removeMessagesFromMember (member, groupId) { * @apiGroup Group * * @apiParam {String} groupId The group _id ('party' for the user party and 'habitrpg' for tavern are accepted) - * @apiParam {String="remove-all","keep-all"} keep Query parameter - Whether to keep or not challenges' tasks. Defaults to keep-all + * @apiParam (Query) {String="remove-all","keep-all"} keep=keep-all Whether or not to keep challenge tasks belonging to the group being left. + * @apiParam (Body) {String="remain-in-challenges","leave-challenges"} [keepChallenges=leave-challenges] Whether or not to remain in the challenges of the group being left. * * @apiSuccess {Object} data An empty object * @@ -539,6 +540,7 @@ api.leaveGroup = { req.checkParams('groupId', res.t('groupIdRequired')).notEmpty(); // When removing the user from challenges, should we keep the tasks? req.checkQuery('keep', res.t('keepOrRemoveAll')).optional().isIn(['keep-all', 'remove-all']); + req.checkBody('keepChallenges', res.t('remainOrLeaveChallenges')).optional().isIn(['remain-in-challenges', 'leave-challenges']); let validationErrors = req.validationErrors(); if (validationErrors) throw validationErrors; @@ -560,7 +562,7 @@ api.leaveGroup = { } } - await group.leave(user, req.query.keep); + await group.leave(user, req.query.keep, req.body.keepChallenges); if (group.purchased.plan && group.purchased.plan.customerId) await payments.updateStripeGroupPlan(group); diff --git a/website/server/models/challenge.js b/website/server/models/challenge.js index 2aabbd66ec..c820f3a695 100644 --- a/website/server/models/challenge.js +++ b/website/server/models/challenge.js @@ -237,13 +237,14 @@ schema.methods.unlinkTasks = async function challengeUnlinkTasks (user, keep) { }; removeFromArray(user.challenges, challengeId); + this.memberCount--; if (keep === 'keep-all') { await Tasks.Task.update(findQuery, { $set: {challenge: {}}, }, {multi: true}).exec(); - await user.save(); + return Bluebird.all([user.save(), this.save()]); } else { // keep = 'remove-all' let tasks = await Tasks.Task.find(findQuery).select('_id type completed').exec(); let taskPromises = tasks.map(task => { @@ -255,7 +256,7 @@ schema.methods.unlinkTasks = async function challengeUnlinkTasks (user, keep) { return task.remove(); }); user.markModified('tasksOrder'); - taskPromises.push(user.save()); + taskPromises.push(user.save(), this.save()); return Bluebird.all(taskPromises); } }; diff --git a/website/server/models/group.js b/website/server/models/group.js index 5551d10656..a38bae42de 100644 --- a/website/server/models/group.js +++ b/website/server/models/group.js @@ -900,7 +900,7 @@ schema.statics.tavernBoss = async function tavernBoss (user, progress) { } }; -schema.methods.leave = async function leaveGroup (user, keep = 'keep-all') { +schema.methods.leave = async function leaveGroup (user, keep = 'keep-all', keepChallenges = 'leave-challenges') { let group = this; let update = {}; @@ -908,16 +908,18 @@ schema.methods.leave = async function leaveGroup (user, keep = 'keep-all') { throw new NotAuthorized(shared.i18n.t('cannotDeleteActiveGroup')); } - // Unlink user challenge tasks - let challenges = await Challenge.find({ - _id: {$in: user.challenges}, - group: group._id, - }).exec(); + // only remove user from challenges if it's set to leave-challenges + if (keepChallenges === 'leave-challenges') { + let challenges = await Challenge.find({ + _id: {$in: user.challenges}, + group: group._id, + }).exec(); - let challengesToRemoveUserFrom = challenges.map(chal => { - return chal.unlinkTasks(user, keep); - }); - await Bluebird.all(challengesToRemoveUserFrom); + let challengesToRemoveUserFrom = challenges.map(chal => { + return chal.unlinkTasks(user, keep); + }); + await Bluebird.all(challengesToRemoveUserFrom); + } // Unlink group tasks) let assignedTasks = await Tasks.Task.find({