Skip to content

Commit 5ebc0fb

Browse files
committed
Fix issue where posts that hadnt already started were showing as ending soon
Always show year in datetime strings if the year is not the current year Lint fixes
1 parent 3f3e559 commit 5ebc0fb

File tree

4 files changed

+67
-66
lines changed

4 files changed

+67
-66
lines changed

apps/backend/api/models/Post.js

Lines changed: 62 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
5050
requireFetch: false,
5151
hasTimestamps: true,
5252

53-
_localId: null, // Used to store the localId of the post coming from the client and passed back to the client, for optimistic updates
53+
_localId: null, // Used to store the localId of the post coming from the client and passed back to the client, for optimistic updates
5454

5555
// Instance Methods
5656

@@ -152,10 +152,12 @@ module.exports = bookshelf.Model.extend(Object.assign({
152152
},
153153

154154
comments: function () {
155-
return this.hasMany(Comment, 'post_id').query({ where: {
156-
'comments.active': true,
157-
'comments.comment_id': null
158-
}})
155+
return this.hasMany(Comment, 'post_id').query({
156+
where: {
157+
'comments.active': true,
158+
'comments.comment_id': null
159+
}
160+
})
159161
},
160162

161163
linkPreview: function () {
@@ -256,13 +258,13 @@ module.exports = bookshelf.Model.extend(Object.assign({
256258

257259
getCommentersTotal: function (currentUserId) {
258260
return countTotal(User.query(commentersQuery(null, this, currentUserId)).query(), 'users')
259-
.then(result => {
260-
if (isEmpty(result)) {
261-
return 0
262-
} else {
263-
return result[0].total
264-
}
265-
})
261+
.then(result => {
262+
if (isEmpty(result)) {
263+
return 0
264+
} else {
265+
return result[0].total
266+
}
267+
})
266268
},
267269

268270
// Emulate the graphql request for a post in the feed so the feed can be
@@ -272,8 +274,8 @@ module.exports = bookshelf.Model.extend(Object.assign({
272274
getNewPostSocketPayload: function () {
273275
const { media, groups, linkPreview, tags, user, proposalOptions } = this.relations
274276

275-
const creator = refineOne(user, [ 'id', 'name', 'avatar_url' ])
276-
const topics = refineMany(tags, [ 'id', 'name' ])
277+
const creator = refineOne(user, ['id', 'name', 'avatar_url'])
278+
const topics = refineMany(tags, ['id', 'name'])
277279

278280
// TODO: Sanitization -- sanitize details here if not passing through `text` getter
279281
return Object.assign({},
@@ -301,14 +303,14 @@ module.exports = bookshelf.Model.extend(Object.assign({
301303
{ name: 'title', num_people_reacts: 'peopleReactedTotal', num_votes: 'votesTotal' }
302304
),
303305
{
304-
attachments: refineMany(media, [ 'id', 'type', 'url' ]),
306+
attachments: refineMany(media, ['id', 'type', 'url']),
305307
// Shouldn't have commenters immediately after creation
306308
commenters: [],
307309
commentsTotal: 0,
308310
creator,
309311
details: this.details(),
310-
groups: refineMany(groups, [ 'id', 'name', 'slug' ]),
311-
linkPreview: refineOne(linkPreview, [ 'id', 'image_url', 'title', 'description', 'url' ]),
312+
groups: refineMany(groups, ['id', 'name', 'slug']),
313+
linkPreview: refineOne(linkPreview, ['id', 'image_url', 'title', 'description', 'url']),
312314
proposalOptions,
313315
proposalVotes: [],
314316
topics
@@ -369,11 +371,11 @@ module.exports = bookshelf.Model.extend(Object.assign({
369371

370372
unreadCountForUser: function (userId) {
371373
return this.lastReadAtForUser(userId)
372-
.then(date => {
373-
if (date > this.get('updated_at')) return 0
374-
return Aggregate.count(this.comments().query(q =>
375-
q.where('created_at', '>', date)))
376-
})
374+
.then(date => {
375+
if (date > this.get('updated_at')) return 0
376+
return Aggregate.count(this.comments().query(q =>
377+
q.where('created_at', '>', date)))
378+
})
377379
},
378380

379381
// ****** Setters ******//
@@ -391,11 +393,11 @@ module.exports = bookshelf.Model.extend(Object.assign({
391393
const newUserIds = difference(userIds, existingUserIds)
392394
const updatedFollowers = await this.updateFollowers(existingUserIds, updatedAttribs, { transacting })
393395
const newFollowers = []
394-
for (let id of newUserIds) {
396+
for (const id of newUserIds) {
395397
const follower = await this.postUsers().create(
396398
Object.assign({}, updatedAttribs, {
397399
user_id: id,
398-
created_at: new Date(),
400+
created_at: new Date()
399401
}), { transacting })
400402
newFollowers.push(follower)
401403
}
@@ -498,11 +500,11 @@ module.exports = bookshelf.Model.extend(Object.assign({
498500
},
499501

500502
pushTypingToSockets: function (userId, userName, isTyping, socketToExclude) {
501-
pushToSockets(postRoom(this.id), 'userTyping', {userId, userName, isTyping}, socketToExclude)
503+
pushToSockets(postRoom(this.id), 'userTyping', { userId, userName, isTyping }, socketToExclude)
502504
},
503505

504506
copy: function (attrs) {
505-
var that = this.clone()
507+
const that = this.clone()
506508
_.merge(that.attributes, Post.newPostAttrs(), attrs)
507509
delete that.id
508510
delete that.attributes.id
@@ -517,7 +519,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
517519
let activitiesToCreate = []
518520

519521
const mentions = RichText.getUserMentions(this.details())
520-
let mentioned = mentions.map(userId => ({
522+
const mentioned = mentions.map(userId => ({
521523
reader_id: userId,
522524
post_id: this.id,
523525
actor_id: this.get('user_id'),
@@ -534,20 +536,20 @@ module.exports = bookshelf.Model.extend(Object.assign({
534536
qb.whereIn('tag_id', tags.map('id'))
535537
qb.whereIn('tag_follows.group_id', groups.map('id'))
536538
})
537-
.fetchAll({ withRelated: ['tag'], transacting: trx })
539+
.fetchAll({ withRelated: ['tag'], transacting: trx })
538540

539541
const tagFollowers = tagFollows.map(tagFollow => ({
540542
reader_id: tagFollow.get('user_id'),
541543
post_id: this.id,
542-
actor_id: this.get('user_id'),
543-
group_id: tagFollow.get('group_id'),
544-
reason: `chat: ${tagFollow.relations.tag.get('name')}`
545-
}))
544+
actor_id: this.get('user_id'),
545+
group_id: tagFollow.get('group_id'),
546+
reason: `chat: ${tagFollow.relations.tag.get('name')}`
547+
}))
546548

547549
activitiesToCreate = activitiesToCreate.concat(tagFollowers)
548550
} else {
549551
// Non-chat posts are sent to all members of the groups the post is in
550-
let members = await Promise.all(groups.map(async group => {
552+
const members = await Promise.all(groups.map(async group => {
551553
const userIds = await group.members().fetch().then(u => u.pluck('id'))
552554
const newPosts = userIds.map(userId => ({
553555
reader_id: userId,
@@ -579,7 +581,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
579581
const eventInvitations = await EventInvitation.query(qb => {
580582
qb.where('event_id', this.id)
581583
})
582-
.fetchAll({transacting: trx})
584+
.fetchAll({ transacting: trx })
583585

584586
const invitees = eventInvitations.map(eventInvitation => ({
585587
reader_id: eventInvitation.get('user_id'),
@@ -683,7 +685,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
683685
},
684686

685687
updateProposalOutcome: function (proposalOutcome) {
686-
return Post.where({ id: this.id }).query().update({ proposal_outcome: proposalOutcome})
688+
return Post.where({ id: this.id }).query().update({ proposal_outcome: proposalOutcome })
687689
},
688690

689691
removeFromGroup: function (idOrSlug) {
@@ -738,7 +740,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
738740
},
739741

740742
countForUser: function (user, type) {
741-
const attrs = {user_id: user.id, 'posts.active': true}
743+
const attrs = { user_id: user.id, 'posts.active': true }
742744
if (type) attrs.type = type
743745
return this.query().count().where(attrs).then(rows => rows[0].count)
744746
},
@@ -749,13 +751,13 @@ module.exports = bookshelf.Model.extend(Object.assign({
749751
q.join('tags', 'tags.id', 'posts_tags.tag_id')
750752
q.whereIn('tags.name', ['request', 'offer', 'resource'])
751753
q.groupBy('tags.name')
752-
q.where({'posts.user_id': user.id, 'posts.active': true})
754+
q.where({ 'posts.user_id': user.id, 'posts.active': true })
753755
q.select('tags.name')
754756
}).query().count()
755-
.then(rows => rows.reduce((m, n) => {
756-
m[n.name] = n.count
757-
return m
758-
}, {}))
757+
.then(rows => rows.reduce((m, n) => {
758+
m[n.name] = n.count
759+
return m
760+
}, {}))
759761
},
760762

761763
havingExactFollowers (userIds) {
@@ -764,7 +766,7 @@ module.exports = bookshelf.Model.extend(Object.assign({
764766
q.join('posts_users', 'posts.id', 'posts_users.post_id')
765767
q.where('posts_users.active', true)
766768
q.groupBy('posts.id')
767-
q.having(bookshelf.knex.raw(`array_agg(posts_users.user_id order by posts_users.user_id) = ?`, [userIds]))
769+
q.having(bookshelf.knex.raw('array_agg(posts_users.user_id order by posts_users.user_id) = ?', [userIds]))
768770
})
769771
},
770772

@@ -821,16 +823,16 @@ module.exports = bookshelf.Model.extend(Object.assign({
821823
})
822824
},
823825

824-
upcomingPostReminders: function (collection, digestType) {
826+
upcomingPostReminders: async function (group, digestType) {
825827
const startTime = DateTime.now().setZone(defaultTimezone).toISO()
826828
// If daily digest show posts that have reminders in the next 2 days
827829
// If weekly digest show posts that have reminders in the next 7 days
828830
const endTime = digestType === 'daily'
829831
? DateTime.now().setZone(defaultTimezone).plus({ days: 2 }).endOf('day').toISO()
830832
: DateTime.now().setZone(defaultTimezone).plus({ days: 7 }).endOf('day').toISO()
831833

832-
const startingSoon = collection.query(function (qb) {
833-
qb.whereRaw('posts.start_time between ? and ?', [startTime, endTime])
834+
const startingSoon = await group.posts().query(function (qb) {
835+
qb.whereRaw('(posts.start_time between ? and ?)', [startTime, endTime])
834836
qb.whereIn('posts.type', ['event', 'offer', 'project', 'proposal', 'resource', 'request'])
835837
qb.where('posts.fulfilled_at', null)
836838
qb.where('posts.active', true)
@@ -839,9 +841,9 @@ module.exports = bookshelf.Model.extend(Object.assign({
839841
.fetch({ withRelated: ['user'] })
840842
.then(get('models'))
841843

842-
const endingSoon = collection.query(function (qb) {
843-
qb.whereRaw('posts.end_time between ? and ?', [startTime, endTime])
844-
qb.whereRaw('start_time < ?', [startTime]) // Only show posts as ending soon that have already started
844+
const endingSoon = await group.posts().query(function (qb) {
845+
qb.whereRaw('(posts.end_time between ? and ?)', [startTime, endTime])
846+
qb.whereRaw('(posts.start_time < ?)', startTime) // Explicitly cast to timestamp with time zone
845847
qb.whereIn('posts.type', ['event', 'offer', 'project', 'proposal', 'resource', 'request'])
846848
qb.where('posts.fulfilled_at', null)
847849
qb.where('posts.active', true)
@@ -850,10 +852,10 @@ module.exports = bookshelf.Model.extend(Object.assign({
850852
.fetch({ withRelated: ['user'] })
851853
.then(get('models'))
852854

853-
return Promise.all([startingSoon, endingSoon]).then(([startingSoon, endingSoon]) => ({
855+
return {
854856
startingSoon,
855857
endingSoon
856-
}))
858+
}
857859
},
858860

859861
newPostAttrs: () => ({
@@ -870,17 +872,17 @@ module.exports = bookshelf.Model.extend(Object.assign({
870872
},
871873

872874
async updateFromNewComment ({ postId, commentId }) {
873-
const where = {post_id: postId, 'comments.active': true}
875+
const where = { post_id: postId, 'comments.active': true }
874876
const now = new Date()
875877

876878
return Promise.all([
877879
Comment.query().where(where).orderBy('created_at', 'desc').limit(2)
878-
.pluck('id').then(ids => Promise.all([
879-
Comment.query().whereIn('id', ids).update('recent', true),
880-
Comment.query().whereNotIn('id', ids)
881-
.where({recent: true, post_id: postId})
882-
.update('recent', false)
883-
])),
880+
.pluck('id').then(ids => Promise.all([
881+
Comment.query().whereIn('id', ids).update('recent', true),
882+
Comment.query().whereNotIn('id', ids)
883+
.where({ recent: true, post_id: postId })
884+
.update('recent', false)
885+
])),
884886

885887
// update num_comments and updated_at (only update the latter when
886888
// creating a comment, not deleting one)
@@ -892,16 +894,16 @@ module.exports = bookshelf.Model.extend(Object.assign({
892894

893895
// when creating a comment, mark post as read for the commenter
894896
commentId && Comment.where('id', commentId).query().pluck('user_id')
895-
.then(([ userId ]) => Post.find(postId)
896-
.then(post => post.markAsRead(userId)))
897+
.then(([userId]) => Post.find(postId)
898+
.then(post => post.markAsRead(userId)))
897899
])
898900
},
899901

900902
deactivate: postId =>
901903
bookshelf.transaction(trx =>
902904
Promise.join(
903905
Activity.removeForPost(postId, trx),
904-
Post.where('id', postId).query().update({active: false}).transacting(trx)
906+
Post.where('id', postId).query().update({ active: false }).transacting(trx)
905907
)),
906908

907909
createActivities: (opts) =>

apps/backend/cron.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const savedSearches = require('./lib/group/digest2/savedSearches')
1111

1212
const sendAndLogDigests = type =>
1313
digest2.sendAllDigests(type)
14-
.then(results => { sails.log.debug(`Sent digests to: ${results}`); return results })
14+
.then(results => { sails.log.debug(`Sent digests for: ${results}`); return results })
1515

1616
const sendSavedSearchDigests = userId =>
1717
savedSearches.sendAllDigests(userId)

apps/backend/lib/group/digest2/util.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export const getPostsAndComments = async (group, startTime, endTime, digestType)
5050
})
5151
.then(get('models'))
5252

53-
const upcomingPostReminders = await Post.upcomingPostReminders(group.posts(), digestType)
53+
const upcomingPostReminders = await Post.upcomingPostReminders(group, digestType)
5454

5555
const comments = await Comment.createdInTimeRange(group.comments(), startTime, endTime)
5656
.query(q => {
@@ -68,7 +68,7 @@ export const getPostsAndComments = async (group, startTime, endTime, digestType)
6868
})
6969
.then(get('models'))
7070

71-
if (posts.length === 0 && comments.length === 0 && upcomingPostReminders.length === 0) {
71+
if (posts.length === 0 && comments.length === 0 && upcomingPostReminders?.startingSoon?.length === 0 && upcomingPostReminders?.endingSoon?.length === 0) {
7272
return false
7373
}
7474

packages/shared/src/TextHelpers.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,16 +161,15 @@ export const formatDatePair = (startTime, endTime, returnAsObj, timezone) => {
161161

162162
const now = DateTime.now()
163163

164-
const isPastYear = start.get('year') < now.get('year')
165164
const isSameDay = end && start.get('day') === end.get('day') &&
166165
start.get('month') === end.get('month') &&
167166
start.get('year') === end.get('year')
168167

169168
let to = ''
170169
let from = ''
171170

172-
// Format the start date - only include year if it's in the past
173-
if (isPastYear) {
171+
// Format the start date - only include year if it's not this year
172+
if (start.get('year') !== now.get('year')) {
174173
from = start.toFormat("ccc MMM d, yyyy '•' t")
175174
} else {
176175
from = start.toFormat("ccc MMM d '•' t")

0 commit comments

Comments
 (0)