2022-08-30 15:38:59 +00:00
|
|
|
import { collection, deleteDoc, doc, setDoc } from 'firebase/firestore'
|
|
|
|
import { db } from 'web/lib/firebase/init'
|
|
|
|
import toast from 'react-hot-toast'
|
|
|
|
import { transact } from 'web/lib/firebase/api'
|
|
|
|
import { removeUndefinedProps } from 'common/util/object'
|
|
|
|
import { Like, LIKE_TIP_AMOUNT } from 'common/like'
|
|
|
|
import { track } from '@amplitude/analytics-browser'
|
|
|
|
import { User } from 'common/user'
|
2022-10-14 12:05:07 +00:00
|
|
|
import { Post } from 'common/post'
|
2022-08-30 15:38:59 +00:00
|
|
|
import { Contract } from 'common/contract'
|
|
|
|
|
|
|
|
function getLikesCollection(userId: string) {
|
|
|
|
return collection(db, 'users', userId, 'likes')
|
|
|
|
}
|
|
|
|
|
2022-10-14 12:05:07 +00:00
|
|
|
export const unLikeItem = async (userId: string, itemId: string) => {
|
|
|
|
const ref = await doc(getLikesCollection(userId), itemId)
|
2022-08-30 15:38:59 +00:00
|
|
|
return await deleteDoc(ref)
|
|
|
|
}
|
|
|
|
|
2022-10-14 12:05:07 +00:00
|
|
|
export const likeItem = async (
|
|
|
|
user: User,
|
|
|
|
item: Contract | Post,
|
|
|
|
itemType: string
|
|
|
|
) => {
|
2022-08-30 15:38:59 +00:00
|
|
|
if (user.balance < LIKE_TIP_AMOUNT) {
|
|
|
|
toast('You do not have enough M$ to like this market!')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
let result: any = {}
|
|
|
|
if (LIKE_TIP_AMOUNT > 0) {
|
|
|
|
result = await transact({
|
|
|
|
amount: LIKE_TIP_AMOUNT,
|
|
|
|
fromId: user.id,
|
|
|
|
fromType: 'USER',
|
2022-10-14 12:05:07 +00:00
|
|
|
toId: item.creatorId,
|
2022-08-30 15:38:59 +00:00
|
|
|
toType: 'USER',
|
|
|
|
token: 'M$',
|
|
|
|
category: 'TIP',
|
2022-10-14 12:05:07 +00:00
|
|
|
data: { contractId: item.id },
|
|
|
|
description: `${user.name} liked ${itemType}${item.id} for M$ ${LIKE_TIP_AMOUNT} to ${item.creatorId} `,
|
2022-08-30 15:38:59 +00:00
|
|
|
})
|
|
|
|
console.log('result', result)
|
|
|
|
}
|
|
|
|
// create new like in db under users collection
|
2022-10-14 12:05:07 +00:00
|
|
|
const ref = doc(getLikesCollection(user.id), item.id)
|
2022-08-30 15:38:59 +00:00
|
|
|
// contract slug and question are set via trigger
|
|
|
|
const like = removeUndefinedProps({
|
|
|
|
id: ref.id,
|
|
|
|
userId: user.id,
|
|
|
|
createdTime: Date.now(),
|
2022-10-14 12:05:07 +00:00
|
|
|
type: itemType,
|
2022-08-30 15:38:59 +00:00
|
|
|
tipTxnId: result.txn.id,
|
|
|
|
} as Like)
|
|
|
|
track('like', {
|
2022-10-14 12:05:07 +00:00
|
|
|
itemId: item.id,
|
2022-08-30 15:38:59 +00:00
|
|
|
})
|
|
|
|
await setDoc(ref, like)
|
|
|
|
}
|