stacker.news/worker/territory.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

2023-11-21 23:32:22 +00:00
import serialize from '../api/resolvers/serial'
import { paySubQueries } from '../api/resolvers/sub'
2024-01-03 02:05:49 +00:00
import { nextBillingWithGrace } from '../lib/territory'
2023-11-21 23:32:22 +00:00
import { datePivot } from '../lib/time'
export async function territoryBilling ({ data: { subName }, boss, models }) {
const sub = await models.sub.findUnique({
where: {
name: subName
}
})
2023-12-08 20:02:00 +00:00
async function territoryStatusUpdate () {
2024-01-03 02:05:49 +00:00
if (sub.status !== 'STOPPED') {
await models.sub.update({
where: {
name: subName
},
data: {
status: nextBillingWithGrace(sub) >= new Date() ? 'GRACE' : 'STOPPED',
statusUpdatedAt: new Date()
}
})
}
2023-11-21 23:32:22 +00:00
// retry billing in one day
await boss.send('territoryBilling', { subName }, { startAfter: datePivot(new Date(), { days: 1 }) })
}
2023-12-08 20:02:00 +00:00
if (!sub.billingAutoRenew) {
await territoryStatusUpdate()
return
}
try {
const queries = paySubQueries(sub, models)
await serialize(models, ...queries)
} catch (e) {
console.error(e)
await territoryStatusUpdate()
}
2023-11-21 23:32:22 +00:00
}