Skip to content

Social: Fix friends list, update requests, add notifications - refs BT#21101 #5692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions assets/vue/components/basecomponents/BaseButton.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
:severity="primeSeverityProperty"
:size="size"
:text="onlyIcon"
:title="onlyIcon ? label : undefined"
:title="tooltip || (onlyIcon ? label : undefined)"
:type="isSubmit ? 'submit' : 'button'"
:loading="isLoading"
@click="$emit('click', $event)"
Expand Down Expand Up @@ -44,8 +44,7 @@ const props = defineProps({
required: true,
validator: buttonTypeValidator,
},
// associate this button to a popup through its identifier, this will make this button toggle the popup
popupIdentifier: {
tooltip: {
type: String,
default: "",
},
Expand All @@ -67,6 +66,10 @@ const props = defineProps({
type: Boolean,
default: false,
},
popupIdentifier: {
type: String,
default: "", // This ensures that popupIdentifier is still present
},
})

defineEmits(["click"])
Expand Down
8 changes: 7 additions & 1 deletion assets/vue/components/userreluser/Layout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
</BaseCard>
</div>
<div class="md:basis-3/4 lg:basis-5/6 2xl:basis-7/8">
<router-view></router-view>
<router-view @friend-request-sent="reloadRequestsList"></router-view>
</div>
</div>
</template>
Expand Down Expand Up @@ -81,6 +81,12 @@ const reloadHandler = async () => {
}
}

const reloadRequestsList = () => {
if (requestList.value) {
requestList.value.loadRequests();
}
}

onMounted(async () => {
await loadUser()
await reloadHandler()
Expand Down
44 changes: 28 additions & 16 deletions assets/vue/components/userreluser/UserRelUserRequestsList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,16 @@
icon="user-add"
only-icon
type="black"
@click="addFriend(request)"
:tooltip="t('Accept invitation')"
@click="acceptFriendRequest(request)"
/>
<BaseButton
class="ml-2"
icon="user-delete"
only-icon
type="danger"
:tooltip="t('Reject invitation')"
@click="rejectFriendRequest(request)"
/>
</div>

Expand Down Expand Up @@ -100,15 +109,11 @@ const loadRequests = () => {
waitingRequests.value = []

Promise.all([
userRelUserService.findAll({
params: friendRequestFilter,
}),
userRelUserService.findAll({
params: waitingFilter,
}),
userRelUserService.findAll({ params: friendRequestFilter }),
userRelUserService.findAll({ params: waitingFilter }),
])
.then(([sentRequestsResponse, waitingRequestsRespose]) =>
Promise.all([sentRequestsResponse.json(), waitingRequestsRespose.json()]),
Promise.all([sentRequestsResponse.json(), waitingRequestsRespose.json()])
)
.then(([sentRequestsJson, waitingRequestsJson]) => {
friendRequests.value = sentRequestsJson["hydra:member"]
Expand All @@ -118,19 +123,26 @@ const loadRequests = () => {
.finally(() => (loading.value = false))
}

function addFriend(friend) {
// Change from request to friend
function acceptFriendRequest(request) {
axios
.put(friend["@id"], {
relationType: 3,
.put(request["@id"], { relationType: 3 })
.then(() => {
emit("accept-friend", request)
notification.showSuccessNotification(t("Friend added successfully"))
loadRequests()
})
.catch((e) => notification.showErrorNotification(e))
}

function rejectFriendRequest(request) {
axios
.delete(request["@id"])
.then(() => {
emit("accept-friend", friend)
notification.showSuccessNotification(t("Friend request rejected"))
loadRequests()
})
.catch((e) => notification.showErrorNotification(e))
}

defineExpose({
loadRequests,
})
defineExpose({ loadRequests })
</script>
43 changes: 42 additions & 1 deletion assets/vue/views/userreluser/UserRelUserAdd.vue
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
</div>
</template>
<script setup>
import { onMounted, ref } from "vue"
import { onMounted, ref, defineEmits } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useI18n } from "vue-i18n"
import { useNotification } from "../../composables/notification"
Expand All @@ -48,6 +48,8 @@ import userService from "../../services/userService"
import userRelUserService from "../../services/userRelUserService"
import { useSecurityStore } from "../../store/securityStore"

const emit = defineEmits(["friend-request-sent"])

const securityStore = useSecurityStore()
const router = useRouter()
const route = useRoute()
Expand All @@ -72,13 +74,20 @@ const asyncFind = (query) => {
})
}

const extractIdFromPath = (path) => {
const parts = path.split("/")
return parts[parts.length - 1]
}

const addFriend = (friend) => {
isLoadingSelect.value = true

userRelUserService
.sendFriendRequest(securityStore.user["@id"], friend["@id"])
.then(() => {
showSuccessNotification(t("Friend request sent successfully"))
emit('friend-request-sent')
sendNotificationMessage(friend)
})
.catch((error) => {
showErrorNotification(t("Failed to send friend request"))
Expand All @@ -89,6 +98,38 @@ const addFriend = (friend) => {
})
}

const sendNotificationMessage = async (friend) => {
const userId = extractIdFromPath(securityStore.user["@id"])
const targetUserId = extractIdFromPath(friend["@id"])

const messageData = {
userId: userId,
targetUserId: targetUserId,
action: 'send_message',
subject: t('You have a new friend request'),
content: t('You have received a new friend request. Visit the invitations page to accept or reject the request.') + ` <a href="/resources/friends">${t('here')}</a>`
}

try {
const response = await fetch('/social-network/user-action', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(messageData)
})
const result = await response.json()
if (result.success) {
showSuccessNotification(t('Notification message sent successfully'))
} else {
showErrorNotification(t('Failed to send notification message'))
}
} catch (error) {
showErrorNotification(t('An error occurred while sending the notification message'))
console.error('Error sending notification message:', error)
}
}

const goToBack = () => {
router.push({ name: "UserRelUserList" })
}
Expand Down
48 changes: 37 additions & 11 deletions assets/vue/views/userreluser/UserRelUserList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@
</template>

<script setup>
import { inject, ref, onMounted } from "vue"
import { ref, onMounted, watch } from "vue"
import BaseToolbar from "../../components/basecomponents/BaseToolbar.vue"
import BaseButton from "../../components/basecomponents/BaseButton.vue"
import Skeleton from "primevue/skeleton"
Expand All @@ -84,10 +84,10 @@ import { useConfirm } from "primevue/useconfirm"
import userRelUserService from "../../services/userreluser"
import { useFormatDate } from "../../composables/formatDate"
import { useNotification } from "../../composables/notification"
import { useSocialInfo } from "../../composables/useSocialInfo"

const { user, isCurrentUser } = useSocialInfo()
const { t } = useI18n()
const user = inject('social-user')
const isCurrentUser = inject('is-current-user')
const items = ref([])
const loadingFriends = ref(true)
const notification = useNotification()
Expand All @@ -98,20 +98,38 @@ const confirm = useConfirm()
const requestList = ref()

function reloadHandler() {
if (!user.value) {
console.log('User not defined yet');
return;
}

loadingFriends.value = true
items.value = []

Promise.all([
userRelUserService.findAll({ params: { user: user.id, relationType: 3 } }),
userRelUserService.findAll({ params: { friend: user.id, relationType: 3 } }),
userRelUserService.findAll({ params: { user: user.value.id, relationType: 3 } }),
userRelUserService.findAll({ params: { friend: user.value.id, relationType: 3 } }),
])
.then(([friendshipResponse, friendshipBackResponse]) =>
Promise.all([friendshipResponse.json(), friendshipBackResponse.json()])
)
.then(([friendshipResponse, friendshipBackResponse]) => {
return Promise.all([friendshipResponse.json(), friendshipBackResponse.json()])
})
.then(([friendshipJson, friendshipBackJson]) => {
items.value.push(...friendshipJson["hydra:member"], ...friendshipBackJson["hydra:member"])
const friendsSet = new Set()
items.value = [...friendshipJson["hydra:member"], ...friendshipBackJson["hydra:member"]]
.filter(friend => {
const friendId = friend.user['@id'] === user.value['@id'] ? friend.friend['@id'] : friend.user['@id']
if (friendsSet.has(friendId)) {
return false
} else {
friendsSet.add(friendId)
return true
}
})
})
.catch((e) => {
console.error('Error occurred', e);
notification.showErrorNotification(e);
})
.catch((e) => notification.showErrorNotification(e))
.finally(() => {
loadingFriends.value = false
if (requestList.value) {
Expand All @@ -120,8 +138,16 @@ function reloadHandler() {
})
}

watch(user, (newValue) => {
if (newValue && newValue.id) {
reloadHandler()
}
})

onMounted(() => {
reloadHandler()
if (user.value && user.value.id) {
reloadHandler()
}
})

const goToAdd = () => {
Expand Down
Loading