2021-10-08 13:23:40 +03:00
|
|
|
const ValueObject = require('./shared/ValueObject');
|
2021-10-08 13:31:11 +03:00
|
|
|
const InvalidOfferDuration = require('../errors').InvalidOfferDuration;
|
2021-10-07 18:10:44 +03:00
|
|
|
|
|
|
|
/**
|
2021-10-08 13:10:36 +03:00
|
|
|
* @typedef {object} BasicDuration
|
2022-08-09 12:09:27 +03:00
|
|
|
* @prop {'once'|'forever'|'trial'} type
|
2021-10-08 13:10:36 +03:00
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {object} RepeatingDuration
|
|
|
|
* @prop {'repeating'} type
|
|
|
|
* @prop {number} months
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @extends ValueObject<BasicDuration|RepeatingDuration>
|
2021-10-07 18:10:44 +03:00
|
|
|
*/
|
|
|
|
class OfferDuration extends ValueObject {
|
2021-10-08 13:10:36 +03:00
|
|
|
/**
|
|
|
|
* @param {unknown} type
|
|
|
|
* @param {unknown} months
|
|
|
|
*/
|
|
|
|
static create(type, months) {
|
|
|
|
if (!type || typeof type !== 'string') {
|
2021-10-07 18:10:44 +03:00
|
|
|
throw new InvalidOfferDuration({
|
|
|
|
message: 'Offer `duration` must be a string.'
|
|
|
|
});
|
|
|
|
}
|
2022-08-09 12:09:27 +03:00
|
|
|
if (type !== 'once' && type !== 'repeating' && type !== 'forever' && type !== 'trial') {
|
2021-10-07 18:10:44 +03:00
|
|
|
throw new InvalidOfferDuration({
|
2022-08-09 12:09:27 +03:00
|
|
|
message: 'Offer `duration` must be one of "once", "repeating", "forever" or "trial.'
|
2021-10-07 18:10:44 +03:00
|
|
|
});
|
|
|
|
}
|
2021-10-08 13:10:36 +03:00
|
|
|
if (type !== 'repeating') {
|
|
|
|
return new OfferDuration({type});
|
|
|
|
}
|
|
|
|
if (typeof months !== 'number') {
|
|
|
|
throw new InvalidOfferDuration({
|
|
|
|
message: 'Offer `duration` must have include `duration_in_months` when "repeating".'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (!Number.isInteger(months)) {
|
|
|
|
throw new InvalidOfferDuration({
|
2021-11-04 20:52:20 +03:00
|
|
|
message: 'Offer `duration_in_months` must be an integer greater than 0.'
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (months < 1) {
|
|
|
|
throw new InvalidOfferDuration({
|
|
|
|
message: 'Offer `duration_in_months` must be an integer greater than 0.'
|
2021-10-08 13:10:36 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return new OfferDuration({type, months});
|
2021-10-07 18:10:44 +03:00
|
|
|
}
|
2021-11-04 20:52:20 +03:00
|
|
|
|
|
|
|
static InvalidOfferDuration = InvalidOfferDuration;
|
2021-10-07 18:10:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = OfferDuration;
|
|
|
|
|