Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the next renewal date of a subscription plan?

I have setup a subscription plan which will automatically charge the users every month, every three months and every year. The problem is, how can I calculate the exact date to charge the user? We can't charge every 30 days right? Because not all months have 30 days. If we charge on the date bought, people who bought the plan on January 30 won't be billed on February because there's no 30 in February. It's a bit of a complex problem. How can I solve this?

PS : Im using ruby on rails

like image 840
THpubs Avatar asked Dec 14 '22 15:12

THpubs


1 Answers

You could store the subscribed_on date and the number_of_payments the user already made. Then calculate the next payment date by increasing the number_of_months and using the >> method on date. >> takes the number of days in a month into account:

# at subscription date and first payment
subscribed_on      = Date.today # in this example: 2015-01-30
number_of_payments = 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-02-28

# after next payment (on 2015-02-28)
number_of_payments = number_of_payments + 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-03-30

# after next payment (on 2015-03-30)
number_of_payments = number_of_payments + 1
next_payment_date  = subscribed_on >> number_of_payments
#=> 2015-04-30

From the documentation of Date#>>

d >> ndate

Returns a date object pointing n months after self. The n should be a numeric value.

This does not only return correct dates, it also allows optimized queries for next_payment_date and statistics like the average length of subscription time in months.

like image 127
spickermann Avatar answered Feb 01 '23 23:02

spickermann