From 7e77afa4fc47c8c727a22fb2b84d6cdf7fb877c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Casaj=C3=BAs?= Date: Fri, 21 Feb 2025 14:44:31 +0100 Subject: [PATCH] Fix: if there's an expired manual sub, extend it (#2393) --- app/coupon_utils.py | 19 ++++++++++++------- tests/test_coupon_utils.py | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/app/coupon_utils.py b/app/coupon_utils.py index 3aded1f8..c1bf71b9 100644 --- a/app/coupon_utils.py +++ b/app/coupon_utils.py @@ -71,13 +71,18 @@ def redeem_coupon(coupon_code: str, user: User) -> Optional[Coupon]: else: sub.end_at = arrow.now().shift(years=coupon.nb_year, days=1) else: - sub = ManualSubscription.create( - user_id=user.id, - end_at=arrow.now().shift(years=coupon.nb_year, days=1), - comment="using coupon code", - is_giveaway=coupon.is_giveaway, - commit=True, - ) + # There may be an expired manual subscription + sub = ManualSubscription.get_by(user_id=user.id) + end_at = arrow.now().shift(years=coupon.nb_year, days=1) + if sub: + sub.end_at = end_at + else: + sub = ManualSubscription.create( + user_id=user.id, + end_at=end_at, + comment="using coupon code", + is_giveaway=coupon.is_giveaway, + ) emit_user_audit_log( user=user, action=UserAuditLogAction.Upgrade, diff --git a/tests/test_coupon_utils.py b/tests/test_coupon_utils.py index 743f4ef0..12fc2d24 100644 --- a/tests/test_coupon_utils.py +++ b/tests/test_coupon_utils.py @@ -66,6 +66,31 @@ def test_use_coupon_extend_manual_sub(): assert left.days > 364 +def test_use_coupon_extend_expired_manual_sub(): + user = create_new_user() + initial_end = arrow.now().shift(days=-15) + ManualSubscription.create( + user_id=user.id, + end_at=initial_end, + flush=True, + ) + code = random_string(10) + Coupon.create(code=code, nb_year=1, commit=True) + + coupon = redeem_coupon(code, user) + assert coupon + + coupon = Coupon.get_by(code=code) + assert coupon + assert coupon.used + assert coupon.used_by_user_id == user.id + + sub = user.get_active_subscription() + assert isinstance(sub, ManualSubscription) + left = sub.end_at - initial_end + assert left.days > 364 + + def test_coupon_with_subscription(): user = create_new_user() end_at = arrow.utcnow().shift(days=1).replace(hour=0, minute=0, second=0)