2022-02-17 18:18:02 +00:00
|
|
|
import * as functions from 'firebase-functions'
|
|
|
|
import * as admin from 'firebase-admin'
|
|
|
|
|
2022-05-15 17:39:42 +00:00
|
|
|
import { Contract } from '../../common/contract'
|
2022-02-17 18:18:02 +00:00
|
|
|
import { getPrivateUser, getUserByUsername } from './utils'
|
2022-06-10 22:48:28 +00:00
|
|
|
import { createNotification } from './create-notification'
|
2022-02-17 18:18:02 +00:00
|
|
|
|
2022-06-10 22:48:28 +00:00
|
|
|
export const marketCloseNotifications = functions
|
2022-06-07 20:31:08 +00:00
|
|
|
.runWith({ secrets: ['MAILGUN_KEY'] })
|
|
|
|
.pubsub.schedule('every 1 hours')
|
2022-02-17 18:18:02 +00:00
|
|
|
.onRun(async () => {
|
|
|
|
await sendMarketCloseEmails()
|
|
|
|
})
|
|
|
|
|
|
|
|
const firestore = admin.firestore()
|
|
|
|
|
|
|
|
async function sendMarketCloseEmails() {
|
|
|
|
const contracts = await firestore.runTransaction(async (transaction) => {
|
|
|
|
const snap = await transaction.get(
|
|
|
|
firestore.collection('contracts').where('isResolved', '!=', true)
|
|
|
|
)
|
|
|
|
|
|
|
|
return snap.docs
|
|
|
|
.map((doc) => {
|
|
|
|
const contract = doc.data() as Contract
|
|
|
|
|
|
|
|
if (
|
|
|
|
contract.resolution ||
|
|
|
|
(contract.closeEmailsSent ?? 0) >= 1 ||
|
2022-02-17 18:34:57 +00:00
|
|
|
contract.closeTime === undefined ||
|
2022-02-17 18:18:02 +00:00
|
|
|
(contract.closeTime ?? 0) > Date.now()
|
|
|
|
)
|
|
|
|
return undefined
|
|
|
|
|
|
|
|
transaction.update(doc.ref, {
|
|
|
|
closeEmailsSent: (contract.closeEmailsSent ?? 0) + 1,
|
|
|
|
})
|
|
|
|
|
|
|
|
return contract
|
|
|
|
})
|
|
|
|
.filter((x) => !!x) as Contract[]
|
|
|
|
})
|
|
|
|
|
2022-06-06 05:50:27 +00:00
|
|
|
for (const contract of contracts) {
|
2022-02-17 18:18:02 +00:00
|
|
|
console.log(
|
|
|
|
'sending close email for',
|
|
|
|
contract.slug,
|
|
|
|
'closed',
|
|
|
|
contract.closeTime
|
|
|
|
)
|
|
|
|
|
|
|
|
const user = await getUserByUsername(contract.creatorUsername)
|
|
|
|
if (!user) continue
|
|
|
|
|
|
|
|
const privateUser = await getPrivateUser(user.id)
|
|
|
|
if (!privateUser) continue
|
|
|
|
|
2022-06-10 22:48:28 +00:00
|
|
|
await createNotification(
|
|
|
|
contract.id,
|
|
|
|
'contract',
|
|
|
|
'closed',
|
|
|
|
user,
|
2022-09-26 22:13:15 +00:00
|
|
|
contract.id + '-closed-at-' + contract.closeTime,
|
2022-06-10 22:48:28 +00:00
|
|
|
contract.closeTime?.toString() ?? new Date().toString(),
|
2022-07-22 00:08:09 +00:00
|
|
|
{ contract }
|
2022-06-10 22:48:28 +00:00
|
|
|
)
|
2022-02-17 18:18:02 +00:00
|
|
|
}
|
|
|
|
}
|