2022-02-23 01:35:25 +00:00
|
|
|
import * as functions from 'firebase-functions'
|
|
|
|
import * as admin from 'firebase-admin'
|
|
|
|
import * as _ from 'lodash'
|
|
|
|
|
|
|
|
import { getContract, getUser, getValues } from './utils'
|
|
|
|
import { Comment } from '../../common/comment'
|
|
|
|
import { sendNewCommentEmail } from './emails'
|
2022-02-24 00:52:19 +00:00
|
|
|
import { Bet } from '../../common/bet'
|
2022-02-23 01:35:25 +00:00
|
|
|
|
|
|
|
const firestore = admin.firestore()
|
|
|
|
|
|
|
|
export const onCreateComment = functions.firestore
|
|
|
|
.document('contracts/{contractId}/comments/{commentId}')
|
|
|
|
.onCreate(async (change, context) => {
|
|
|
|
const { contractId } = context.params as {
|
|
|
|
contractId: string
|
|
|
|
}
|
|
|
|
|
|
|
|
const contract = await getContract(contractId)
|
|
|
|
if (!contract) return
|
|
|
|
|
|
|
|
const comment = change.data() as Comment
|
|
|
|
|
|
|
|
const commentCreator = await getUser(comment.userId)
|
|
|
|
if (!commentCreator) return
|
|
|
|
|
2022-02-24 00:52:19 +00:00
|
|
|
const betSnapshot = await firestore
|
|
|
|
.collection('contracts')
|
|
|
|
.doc(contractId)
|
|
|
|
.collection('bets')
|
|
|
|
.doc(comment.betId)
|
|
|
|
.get()
|
|
|
|
const bet = betSnapshot.data() as Bet
|
|
|
|
|
2022-02-24 06:36:27 +00:00
|
|
|
const answer =
|
2022-03-15 22:27:51 +00:00
|
|
|
contract.outcomeType === 'FREE_RESPONSE' && contract.answers
|
|
|
|
? contract.answers.find((answer) => answer.id === bet.outcome)
|
|
|
|
: undefined
|
2022-02-24 06:36:27 +00:00
|
|
|
|
2022-02-23 01:35:25 +00:00
|
|
|
const comments = await getValues<Comment>(
|
|
|
|
firestore.collection('contracts').doc(contractId).collection('comments')
|
|
|
|
)
|
|
|
|
|
|
|
|
const recipientUserIds = _.uniq([
|
|
|
|
contract.creatorId,
|
|
|
|
...comments.map((comment) => comment.userId),
|
|
|
|
]).filter((id) => id !== comment.userId)
|
|
|
|
|
|
|
|
await Promise.all(
|
|
|
|
recipientUserIds.map((userId) =>
|
2022-02-24 06:36:27 +00:00
|
|
|
sendNewCommentEmail(
|
|
|
|
userId,
|
|
|
|
commentCreator,
|
|
|
|
contract,
|
|
|
|
comment,
|
|
|
|
bet,
|
|
|
|
answer
|
|
|
|
)
|
2022-02-23 01:35:25 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
})
|