2023-11-21 23:32:22 +00:00
|
|
|
import serialize from '../api/resolvers/serial'
|
|
|
|
import { paySubQueries } from '../api/resolvers/sub'
|
|
|
|
import { TERRITORY_GRACE_DAYS } from '../lib/constants'
|
|
|
|
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 () {
|
2023-11-21 23:32:22 +00:00
|
|
|
await models.sub.update({
|
|
|
|
where: {
|
|
|
|
name: subName
|
|
|
|
},
|
|
|
|
data: {
|
|
|
|
status: sub.billedLastAt >= datePivot(new Date(), { days: -TERRITORY_GRACE_DAYS }) ? 'GRACE' : 'STOPPED'
|
|
|
|
}
|
|
|
|
})
|
|
|
|
// 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
|
|
|
}
|