This repository was archived by the owner on Mar 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsendPaymentReminders.js
83 lines (76 loc) · 2.02 KB
/
sendPaymentReminders.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const Roles = require('../../../lib/Roles')
const logger = require('../../../lib/logger')
const sendMailTemplate = require('../../../lib/sendMailTemplate')
const {formatPrice} = require('../../../lib/formats')
module.exports = async (_, args, {pgdb, req, t}) => {
Roles.ensureUserHasRole(req.user, 'supporter')
const {
paymentIds,
emailSubject
} = args
if (!paymentIds.length) {
return 0
}
const now = new Date()
const transaction = await pgdb.transactionBegin()
try {
const payments = await transaction.query(`
SELECT
u.email,
pay.total,
pay.hrid
FROM
payments pay
JOIN
"pledgePayments" pp
ON pay.id=pp."paymentId"
JOIN
pledges p
ON pp."pledgeId"=p.id
JOIN
users u
ON p."userId"=u.id
WHERE
pay.status = 'WAITING' AND
pay.method = 'PAYMENTSLIP' AND
pay."dueDate" < :now AND
ARRAY[pay.id] && :paymentIds
`, {
now,
paymentIds
})
for (let payment of payments) {
await sendMailTemplate({
to: payment.email,
fromEmail: process.env.DEFAULT_MAIL_FROM_ADDRESS,
subject: emailSubject || t('api/email/payment/reminder/subject'),
templateName: 'cf_payment_reminder',
globalMergeVars: [
{ name: 'TOTAL',
content: formatPrice(payment.total)
},
{ name: 'HRID',
content: payment.hrid
}
]
})
}
await transaction.query(`
UPDATE
payments pay
SET
"remindersSentAt" = COALESCE("remindersSentAt", '[]'::jsonb)::jsonb || :now::jsonb
WHERE
ARRAY[pay.id] && :paymentIds
`, {
now: JSON.stringify([now]),
paymentIds
})
await transaction.transactionCommit()
return payments.length
} catch (e) {
await transaction.transactionRollback()
logger.error('error in transaction', { req: req._log(), args, error: e })
throw e
}
}