count views of post teaser

This commit is contained in:
Moriz Wahl 2021-02-24 16:15:26 +01:00
parent ae61baadfb
commit 1c3f628fb2
19 changed files with 211 additions and 83 deletions

View File

@ -131,6 +131,7 @@ Factory.define('post')
imageBlurred: false,
imageAspectRatio: 1.333,
clickedCount: 0,
viewedTeaserCount: 0,
})
.attr('pinned', ['pinned'], (pinned) => {
// Convert false to null

View File

@ -0,0 +1,53 @@
import { getDriver } from '../../db/neo4j'
export const description = `
This migration adds the viewedTeaserCount property to all posts, setting it to 0.
`
module.exports.up = async function (next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(`
MATCH (p:Post)
SET p.viewedTeaserCount = 0
`)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}
module.exports.down = async function (next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(`
MATCH (p:Post)
REMOVE p.viewedTeaserCount
`)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}

View File

@ -168,6 +168,7 @@ export default shield(
UpdateDonations: isAdmin,
GenerateInviteCode: isAuthenticated,
switchUserRole: isAdmin,
markTeaserAsViewed: allow,
},
User: {
email: or(isMyOwn, isAdmin),

View File

@ -23,6 +23,7 @@ export default {
deleted: { type: 'boolean', default: false },
disabled: { type: 'boolean', default: false },
clickedCount: { type: 'int', default: 0 },
viewedTeaserCount: { type: 'int', default: 0 },
notified: {
type: 'relationship',
relationship: 'NOTIFIED',

View File

@ -89,6 +89,7 @@ export default {
SET post.createdAt = toString(datetime())
SET post.updatedAt = toString(datetime())
SET post.clickedCount = 0
SET post.viewedTeaserCount = 0
WITH post
MATCH (author:User {id: $userId})
MERGE (post)<-[:WROTE]-(author)
@ -316,6 +317,30 @@ export default {
}
return unpinnedPost
},
markTeaserAsViewed: async (_parent, params, context, _resolveInfo) => {
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const transactionResponse = await transaction.run(
`
MATCH (post:Post { id: $params.id })
MATCH (user:User { id: $userId })
MERGE (user)-[relation:VIEWED_TEASER { }]->(post)
ON CREATE
SET relation.createdAt = toString(datetime()),
post.viewedTeaserCount = post.viewedTeaserCount + 1
RETURN post
`,
{ userId: context.user.id, params },
)
return transactionResponse.records.map((record) => record.get('post').properties)
})
try {
const [post] = await writeTxResultPromise
return post
} finally {
session.close()
}
},
},
Post: {
...Resolver('Post', {
@ -342,6 +367,8 @@ export default {
boolean: {
shoutedByCurrentUser:
'MATCH(this)<-[:SHOUTED]-(related:User {id: $cypherParams.currentUserId}) RETURN COUNT(related) >= 1',
viewedTeaserByCurrentUser:
'MATCH (this)<-[:VIEWED_TEASER]-(u:User {id: $cypherParams.currentUserId}) RETURN COUNT(u) >= 1',
},
}),
relatedContributions: async (parent, params, context, resolveInfo) => {

View File

@ -40,6 +40,7 @@ const searchPostsSetup = {
commentsCount: toString(size(comments)),
shoutedCount: toString(size(shouter)),
clickedCount: toString(resource.clickedCount)
viewedTeaserCount: toString(resource.viewedTeaserCount)
}`,
limit: 'LIMIT $limit',
}

View File

@ -158,6 +158,12 @@ type Post {
clickedCount: Int!
viewedTeaserCount: Int!
viewedTeaserByCurrentUser: Boolean!
@cypher(
statement: "MATCH (this)<-[:VIEWED_TEASER]-(u:User {id: $cypherParams.currentUserId}) RETURN COUNT(u) >= 1"
)
emotions: [EMOTED]
emotionsCount: Int!
@cypher(statement: "MATCH (this)<-[emoted:EMOTED]-(:User) RETURN COUNT(DISTINCT emoted)")
@ -195,6 +201,7 @@ type Mutation {
RemovePostEmotions(to: _PostInput!, data: _EMOTEDInput!): EMOTED
pinPost(id: ID!): Post
unpinPost(id: ID!): Post
markTeaserAsViewed(id: ID!): Post
}
type Query {

View File

@ -26,6 +26,7 @@ describe('PostTeaser', () => {
shoutedCount: 0,
commentsCount: 0,
clickedCount: 0,
viewedTeaserCount: 0,
name: 'It is a post',
author: {
id: 'u1',

View File

@ -44,6 +44,7 @@ export const post = {
commentsCount: 12,
categories: [],
shoutedCount: 421,
viewedTeaserCount: 1584,
__typename: 'Post',
}

View File

@ -6,9 +6,9 @@
<base-card
:lang="post.language"
:class="{
'disabled-content': post.disabled,
'--blur-image': post.image && post.image.sensitive,
}"
'disabled-content': post.disabled,
'--blur-image': post.image && post.image.sensitive,
}"
:highlight="isPinned"
v-observe-visibility="(isVisible, entry) => visibilityChanged(isVisible, entry, post.id)"
>
@ -39,6 +39,11 @@
icon="hand-pointer"
:count="post.clickedCount"
:title="$t('contribution.amount-clicks', { amount: post.clickedCount })"
</counter-icon>
<counter-icon
icon="eye"
:count="post.viewedTeaserCount"
:title="$t('contribution.amount-views', { amount: post.viewedTeaserCount })"
/>
<client-only>
<content-menu
@ -60,87 +65,97 @@
</template>
<script>
import UserTeaser from '~/components/UserTeaser/UserTeaser'
import ContentMenu from '~/components/ContentMenu/ContentMenu'
import HcRibbon from '~/components/Ribbon'
import CounterIcon from '~/components/_new/generic/CounterIcon/CounterIcon'
import { mapGetters } from 'vuex'
import { postMenuModalsData, deletePostMutation } from '~/components/utils/PostHelpers'
import UserTeaser from '~/components/UserTeaser/UserTeaser'
import ContentMenu from '~/components/ContentMenu/ContentMenu'
import HcRibbon from '~/components/Ribbon'
import CounterIcon from '~/components/_new/generic/CounterIcon/CounterIcon'
import { mapGetters } from 'vuex'
import PostMutations from '~/graphql/PostMutations'
import { postMenuModalsData, deletePostMutation } from '~/components/utils/PostHelpers'
export default {
name: 'PostTeaser',
components: {
UserTeaser,
HcRibbon,
ContentMenu,
CounterIcon,
},
props: {
post: {
type: Object,
required: true,
},
width: {
type: Object,
default: () => {},
},
},
mounted() {
const { image } = this.post
if (!image) return
const width = this.$el.offsetWidth
const height = Math.min(width / image.aspectRatio, 2000)
const imageElement = this.$el.querySelector('.hero-image')
if (imageElement) {
imageElement.style.height = `${height}px`
}
},
computed: {
...mapGetters({
user: 'auth/user',
}),
excerpt() {
return this.$filters.removeLinks(this.post.contentExcerpt)
},
isAuthor() {
const { author } = this.post
if (!author) return false
return this.user.id === this.post.author.id
},
menuModalsData() {
return postMenuModalsData(
// "this.post" may not always be defined at the beginning
this.post ? this.$filters.truncate(this.post.title, 30) : '',
this.deletePostCallback,
)
},
isPinned() {
return this.post && this.post.pinned
},
},
methods: {
async deletePostCallback() {
try {
const {
data: { DeletePost },
} = await this.$apollo.mutate(deletePostMutation(this.post.id))
this.$toast.success(this.$t('delete.contribution.success'))
this.$emit('removePostFromList', DeletePost)
} catch (err) {
this.$toast.error(err.message)
}
},
pinPost(post) {
this.$emit('pinPost', post)
},
unpinPost(post) {
this.$emit('unpinPost', post)
},
visibilityChanged(isVisible, entry, id) {
console.log('--', isVisible, id)
},
},
}
export default {
name: 'PostTeaser',
components: {
UserTeaser,
HcRibbon,
ContentMenu,
CounterIcon,
},
props: {
post: {
type: Object,
required: true,
},
width: {
type: Object,
default: () => {},
},
},
mounted() {
const { image } = this.post
if (!image) return
const width = this.$el.offsetWidth
const height = Math.min(width / image.aspectRatio, 2000)
const imageElement = this.$el.querySelector('.hero-image')
if (imageElement) {
imageElement.style.height = `${height}px`
}
},
computed: {
...mapGetters({
user: 'auth/user',
}),
excerpt() {
return this.$filters.removeLinks(this.post.contentExcerpt)
},
isAuthor() {
const { author } = this.post
if (!author) return false
return this.user.id === this.post.author.id
},
menuModalsData() {
return postMenuModalsData(
// "this.post" may not always be defined at the beginning
this.post ? this.$filters.truncate(this.post.title, 30) : '',
this.deletePostCallback,
)
},
isPinned() {
return this.post && this.post.pinned
},
},
methods: {
async deletePostCallback() {
try {
const {
data: { DeletePost },
} = await this.$apollo.mutate(deletePostMutation(this.post.id))
this.$toast.success(this.$t('delete.contribution.success'))
this.$emit('removePostFromList', DeletePost)
} catch (err) {
this.$toast.error(err.message)
}
},
pinPost(post) {
this.$emit('pinPost', post)
},
unpinPost(post) {
this.$emit('unpinPost', post)
},
visibilityChanged(isVisible, entry, id) {
if (!this.post.viewedTeaserByCurrentUser && isVisible) {
this.$apollo
.mutate({
mutation: PostMutations().markTeaserAsViewed,
variables: { id },
})
.catch((error) => this.$toast.error(error.message))
this.post.viewedTeaserByCurrentUser = true
this.post.viewedTeaserCount++
}
},
},
}
</script>
<style lang="scss">
.post-teaser,

View File

@ -16,6 +16,7 @@ describe('SearchPost.vue', () => {
commentsCount: 3,
shoutedCount: 6,
clickedCount: 5,
viewedTeaserCount: 15,
createdAt: '23.08.2019',
author: {
name: 'Post Author',

View File

@ -6,6 +6,7 @@
<counter-icon icon="comments" :count="option.commentsCount" soft />
<counter-icon icon="bullhorn" :count="option.shoutedCount" soft />
<counter-icon icon="hand-pointer" :count="option.clickedCount" soft />
<counter-icon icon="eye" :count="option.viewedTeaserCount" soft />
</span>
{{ option.author.name | truncate(32) }} - {{ option.createdAt | dateTime('dd.MM.yyyy') }}
</div>

View File

@ -15,6 +15,7 @@ export const searchResults = [
shoutedCount: 0,
commentsCount: 4,
clickedCount: 8,
viewedTeaserCount: 15,
createdAt: '2019-11-13T03:03:16.155Z',
author: {
id: 'u3',
@ -31,6 +32,7 @@ export const searchResults = [
shoutedCount: 0,
commentsCount: 0,
clickedCount: 9,
viewedTeaserCount: 2,
createdAt: '2019-11-13T03:00:45.478Z',
author: {
id: 'u6',
@ -47,6 +49,7 @@ export const searchResults = [
shoutedCount: 1,
commentsCount: 1,
clickedCount: 1,
viewedTeaserCount: 4,
createdAt: '2019-11-13T03:00:23.098Z',
author: {
id: 'u6',
@ -63,6 +66,7 @@ export const searchResults = [
shoutedCount: 0,
commentsCount: 12,
clickedCount: 14,
viewedTeaserCount: 58,
createdAt: '2019-11-13T03:00:23.098Z',
author: {
id: 'u6',

View File

@ -68,6 +68,8 @@ export const postCountsFragment = gql`
shoutedByCurrentUser
emotionsCount
clickedCount
viewedTeaserCount
viewedTeaserByCurrentUser
}
`

View File

@ -118,5 +118,12 @@ export default () => {
}
}
`,
markTeaserAsViewed: gql`
mutation($id: ID!) {
markTeaserAsViewed(id: $id) {
id
}
}
`,
}
}

View File

@ -13,6 +13,7 @@ export const searchQuery = gql`
commentsCount
shoutedCount
clickedCount
viewedTeaserCount
author {
...user
}
@ -42,6 +43,7 @@ export const searchPosts = gql`
commentsCount
shoutedCount
clickedCount
viewedTeaserCount
author {
...user
}

View File

@ -177,6 +177,7 @@
"amount-clicks": "{amount} clicks",
"amount-comments": "{amount} comments",
"amount-shouts": "{amount} recommendations",
"amount-views": "{amount} views",
"categories": {
"infoSelectedNoOfMaxCategories": "{chosen} von {max} Kategorien ausgewählt"
},

View File

@ -177,6 +177,7 @@
"amount-clicks": "{amount} clicks",
"amount-comments": "{amount} comments",
"amount-shouts": "{amount} recommendations",
"amount-views": "{amount} views",
"categories": {
"infoSelectedNoOfMaxCategories": "{chosen} of {max} categories selected"
},

View File

@ -82,6 +82,7 @@ const helpers = {
shoutedCount: faker.random.number(),
commentsCount: faker.random.number(),
clickedCount: faker.random.number(),
viewedTeaserCount: faker.random.number(),
}
})
},