2021-05-07 13:41:52 +03:00
|
|
|
const {DateTime} = require('luxon');
|
2021-05-06 14:19:36 +03:00
|
|
|
|
2021-05-06 13:16:22 +03:00
|
|
|
const SUPPORTED_INTERVALS = ['month'];
|
2021-05-06 14:19:36 +03:00
|
|
|
/**
|
|
|
|
* Calculates the start of the last period (billing, cycle, etc.) based on the start date
|
|
|
|
* and the interval at which the cycle renews.
|
|
|
|
*
|
|
|
|
* @param {String} startDate - date in ISO 8601 format (https://en.wikipedia.org/wiki/ISO_8601)
|
|
|
|
* @param {('month')} interval - currently only supports 'month' value, in the future might support 'year', etc.
|
|
|
|
*
|
|
|
|
* @returns {String} - date in ISO 8601 format (https://en.wikipedia.org/wiki/ISO_8601) of the last period start
|
|
|
|
*/
|
|
|
|
const lastPeriodStart = (startDate, interval) => {
|
|
|
|
if (interval === 'month') {
|
2021-05-07 13:41:52 +03:00
|
|
|
const startDateISO = DateTime.fromISO(startDate, {zone: 'UTC'});
|
|
|
|
const now = DateTime.now().setZone('UTC');
|
|
|
|
const fullPeriodsPast = Math.floor(now.diff(startDateISO, 'months').months);
|
2021-05-06 14:19:36 +03:00
|
|
|
|
2021-05-07 13:41:52 +03:00
|
|
|
const lastPeriodStartDate = startDateISO.plus({months: fullPeriodsPast});
|
|
|
|
|
|
|
|
return lastPeriodStartDate.toISO();
|
2021-05-06 14:19:36 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error('Invalid interval specified. Only "month" value is accepted.');
|
|
|
|
};
|
2021-05-06 13:16:22 +03:00
|
|
|
|
|
|
|
module.exports = {
|
2021-05-06 14:19:36 +03:00
|
|
|
lastPeriodStart,
|
2021-05-06 13:16:22 +03:00
|
|
|
SUPPORTED_INTERVALS
|
|
|
|
};
|