Exemplo n.º 1
0
def confirm_user_subscription(token):
    secret_key = ConfigValues.get_config_value(
        'EMAIL_PASSWORD_RESET_SECRET_KEY')

    confirm_serializer = URLSafeTimedSerializer(secret_key)
    try:
        email = confirm_serializer.loads(token,
                                         salt='email-confirm',
                                         max_age=3600)
    except SignatureExpired:
        return Responses.TOKEN_EXPIRED()
    json_dict = request.json
    email = json_dict['email']
    user = User.get_user_by_email(email)
    if not user:
        return Responses.NOT_EXIST()

    subscription_type = json_dict['subscription_type']
    subscription = SubscriptionType.get_items(subscription_type)

    start_date = date.today()
    end_date = start_date + relativedelta(months=int(1))
    #end_date = start_date + relativedelta(months=int(subscription.plan))

    user_subscription = UserSubscription(user.id, end_date, subscription.id)
    error = user_subscription.update()
    if len(error) > 0:
        Responses.OPERATION_FAILED()

    user.subscribed = True
    user_error = user.update()
    if len(user_error) > 0:
        Responses.OPERATION_FAILED()
    return Responses.SUCCESS()
Exemplo n.º 2
0
def new_subscription():
    subscription = UserSubscription()
    subscription.subscription_type_id = '1'
    subscription.start_date = datetime.datetime.strptime(
        '2020-7-1 00:00:00', '%Y-%m-%d %H:%M:%S')
    subscription.end_date = datetime.datetime.strptime('2020-8-1 00:00:00',
                                                       '%Y-%m-%d %H:%M:%S')
    return subscription
Exemplo n.º 3
0
def add_subscription():
    json_dict = request.json

    item = UserSubscription(
        user_id=json_dict['user_id'],
        end_date=json_dict['end_date'],
        subscription_type_id=json_dict['subscription_type_id'])
    error = item.insert_as_new_item(json_dict)
    if len(error) > 0:
        return Responses.OPERATION_FAILED(error)
    return res(item.as_dict())
Exemplo n.º 4
0
def validate_order():
    json_dict = request.json
    item = Order()
    item.user_id = json_dict['user_id']

    order_items_dict = json_dict['order_items']
    for order_item_dict in order_items_dict:
        order_item = OrderItem()
        if order_item.update_from_dict(order_item_dict):
            item.order_items.append(order_item)

    item.update_from_dict(json_dict)

    if not item.check_stock():
        return Responses.NO_STOCK()

    user = User.query.get(item.user_id)
    #check if user is blacklisted
    if user.blacklist:
        return Responses.BLACKLISTED()

    if user.subscribed:
        if not UserSubscription.check_subscription_active(user.id):
            user.update({'subscribed': 0})
            #return Responses.SUBSCRIPTION_INACTIVE()
        userSub = UserSubscription.get_subscription(user_id=item.user_id)
        userSubscription = {}
        if len(userSub) > 0:
            userSubscription = userSub[0]
            max_per_order_for_lifestyle = int(
                ConfigValues.get_config_value(
                    'max_no_of_items_per_order_adayalifestyle'))
            subscriptionType = SubscriptionType.query.get(
                userSubscription.subscription_type_id)
            if (subscriptionType.plan == 'Adaya Lifestyle'
                ):  #AdayaLifestyle plan
                if item.check_quantity_products(max_per_order_for_lifestyle):
                    return Responses.OPERATION_FAILED()

    details = Order.calculate_cost_for_users(item)

    if details == -1:
        return Responses.OPERATION_FAILED()

    return res(details)
Exemplo n.º 5
0
def get_user_subscription(id=None):
    """
    get_subscriptions gets all user subscriptions
    
    """
    item = UserSubscription.get_subscription(user_id=id)
    response = {}
    if (len(item) > 0):
        response = item[0]

    return res(response.as_dict())
Exemplo n.º 6
0
def get_subscriptions(id=None):
    """
    get_subscriptions gets all user subscriptions
    
    """
    page, per_page = get_page_from_args()
    sort_by = request.args.get('sort_by')
    is_desc = parse_int(request.args.get('is_desc'))

    items = UserSubscription.get_items(id=id,
                                       page=page,
                                       per_page=per_page,
                                       sort_by=sort_by,
                                       is_desc=is_desc)

    return res([item.as_dict() for item in items])
Exemplo n.º 7
0
def cancel_subscription():
    json_dict = request.json
    user_id = json_dict['user_id']
    userSub = UserSubscription.get_subscription(user_id=user_id)
    userSubscription = {}
    if len(userSub) > 0:
        userSubscription = userSub[0]
    subscriptionId = userSubscription.subscription_id
    user = User.query.get(user_id)

    stripe.api_key =  ConfigValues.get_config_value('STRIPE_SK')

    try:
         # Cancel the subscription by deleting it
        deletedSubscription = stripe.Subscription.delete(subscriptionId)
        print(deletedSubscription)
        
        user_subscription_dict = {}
        
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_id'] = deletedSubscription['id']
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(deletedSubscription['current_period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(deletedSubscription['current_period_end'])
        user_subscription_dict['current_end_date'] = e_date
        user_subscription_dict['application_fee_percent'] = deletedSubscription['application_fee_percent']
        user_subscription_dict['billing_cycle_anchor'] = deletedSubscription['billing_cycle_anchor']
        user_subscription_dict['billing_thresholds'] = deletedSubscription['billing_thresholds']
        user_subscription_dict['cancel_at'] = deletedSubscription['cancel_at']
        user_subscription_dict['cancel_at_period_end'] = deletedSubscription['cancel_at_period_end']
        ca_date = datetime.fromtimestamp(deletedSubscription['canceled_at'])
        user_subscription_dict['canceled_at'] = ca_date
        user_subscription_dict['collection_method'] = deletedSubscription['collection_method']
       
        userSubscription.update(user_subscription_dict)
        Payment.send_subscription_cancelled_email(user_email=user.email)

        if datetime.now() > userSubscription.current_end_date:  # else, there is another check when user makes an order and sets to 0 if it fails this validation
            user.update({'subscribed':0})
           

        return jsonify(deletedSubscription).json
    except Exception as e:
        return jsonify(error=str(e)), 403
Exemplo n.º 8
0
def get_subscription_pages(id=None):  # pagination details for all products
    """
    get_subscriptions gets all user subscriptions
    
    """
    page, per_page = get_page_from_args()
    sort_by = request.args.get('sort_by')
    is_desc = parse_int(request.args.get('is_desc'))

    page_details = UserSubscription.get_items_pages(id=id,
                                                    page=page,
                                                    per_page=per_page,
                                                    sort_by=sort_by,
                                                    is_desc=is_desc)

    return res({
        "total_items": page_details.total,
        "no_of_pages": page_details.pages,
        "per_page": page_details.per_page
    })
Exemplo n.º 9
0
def test_check_all_user_subscriptions(test_client, init_database):
    UserSubscription.Check_all_user_subsriptions()
    users = User.query.all()
    assert users[0].subscribed == False
    assert users[1].subscribed == True
Exemplo n.º 10
0
def test_check_subscription_active(test_client, init_database):
    isactive = UserSubscription.check_subscription_active(2)
    assert isactive == True
Exemplo n.º 11
0
 ACCESS_TOKEN = ConfigValues(
     'ACCESS_TOKEN', '9dae131233c5e028255318571703a409a524583e')
 BEARER_REFRESH_TOKEN = ConfigValues(
     'REFRESH_TOKEN', '86a42f98ad7a1703e7619d7c1abace0fd43288af')
 IMGUR_ACCOUNT_ID = ConfigValues('IMGUR_ACCOUNT_ID', '127525815')
 IMGUR_ACCOUNT_USERNAME = ConfigValues('IMGUR_ACCOUNT_USERNAME',
                                       'adayahouse')
 STRIPE_PUBLISHABLE_KEY = ConfigValues('STRIPE_PK', '')
 STRIPE_S_KEY = ConfigValues('STRIPE_SK', '')
 subtype = SubscriptionType(plan='Adaya Lite', price=10)
 subtype2 = SubscriptionType(plan='Adaya Lifestyle', price=40)
 subtype.stripe_subscription_product = 'prod_HKKYExqtgZlZ0R'
 subtype.stripe_price = 'price_HKKb1y8VgSax36'
 subtype2.stripe_subscription_product = 'prod_HKKboFqONk8aba'
 subtype2.stripe_price = 'price_HKKcUelIoiOo5m'
 usersubscription = UserSubscription()
 usersubscription.user_id = 2
 usersubscription.start_date = datetime.now()
 usersubscription.end_date = datetime.strptime('06-02-2020 05:58:00',
                                               '%d-%m-%Y %H:%M:%S')
 usersubscription.subscription_type = subtype
 food_category = ProductCategory('food')
 clothes_category = ProductCategory('cloth')
 food_article = ArticleCategory('food-article')
 clothes_article = ArticleCategory('cloth-article')
 status = ArticleStatus('draft')
 order_status = OrderStatus('completed')
 db.session.add(order_status)
 db.session.add(food_article)
 db.session.add(clothes_article)
 db.session.add(food_category)
Exemplo n.º 12
0
def webhook_received():

    # You can use webhooks to receive information about asynchronous payment events.
    # For more about our webhook events check out https://stripe.com/docs/webhooks.
    webhook_secret = ConfigValues.get_config_value('STRIPE_WHS') #"whsec_Z5rqV5EyWqGAcsGVsf1id7kfCk8hQXkI" #os.getenv('STRIPE_WEBHOOK_SECRET')
    request_data = json.loads(request.data)

    if webhook_secret:
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        signature = request.headers.get('stripe-signature')
        try:
            event = stripe.Webhook.construct_event(
                payload=request.data, sig_header=signature, secret=webhook_secret)
            data = event['data']
        except Exception as e:
            return e
        # Get the type of webhook event sent - used to check the status of PaymentIntents.
        event_type = event['type']
    else:
        data = request_data['data']
        event_type = request_data['type']

    data_object = data['object']

    if event_type == 'invoice.payment_succeeded':
        # Used to provision services after the trial has ended.
        # The status of the invoice will show up as paid. Store the status in your
        # database to reference when a user accesses your service to avoid hitting rate
        # limits.
        print(data)
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        Payment.send_subscription_renewal_success_email(user_email=email)
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        user.update({'subscribed': 1, 'number_of_items_ordered_this_month' : 0})

    if event_type == 'invoice.payment_failed':
        # If the payment fails or the customer does not have a valid payment method,
        # an invoice.payment_failed event is sent, the subscription becomes past_due.
        # Use this webhook to notify your user that their payment has
        # failed and to retrieve new card details.
        print(data)
        
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        Payment.send_subscription_renewal_failure_email(user_email=email)
                
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0})

    if event_type == 'invoice.finalized':
        # If you want to manually send out invoices to your customers
        # or store them locally to reference to avoid hitting Stripe rate limits.
        print(data)

    if event_type == 'customer.subscription.deleted':
        # handle subscription cancelled automatically based
        # upon your subscription settings. Or if the user cancels it.
        print(data)
        sid = request_data['data']['object']['customer']
        user = User.get_user_by_stripe_id(stripe_id=sid)
        email = user.email
        
        userSub = UserSubscription.get_subscription(user_id=user.id)
        userSubscription = {}
        if len(userSub > 0):
            userSubscription = userSub[0]

        user_subscription_dict = {}
        user_subscription_dict['user_id'] = user.id
        user_subscription_dict['subscription_type_id'] = userSubscription.subscription_type_id
        s_date = datetime.fromtimestamp(data['object']['period_start'])
        user_subscription_dict['current_start_date'] = s_date
        e_date = datetime.fromtimestamp(data['object']['period_end'])
        user_subscription_dict['current_end_date'] = e_date

        userSubscription.update(user_subscription_dict)
        Payment.send_subscription_cancelled_email(user_email=email)
        if datetime.now() > userSubscription.current_end_date:  # else, there is another check when user makes an order and sets to 0 if it fails this validation
            user.update({'subscribed': 0, 'number_of_items_ordered_this_month' : 0})
          

    if event_type == 'customer.subscription.trial_will_end':
        # Send notification to your user that the trial will end
        print(data)

    return jsonify({'status': 'success'})
Exemplo n.º 13
0
def create_subscription():
    json_dict = request.json
    subscription_type = json_dict['subscription_type']
    subType = SubscriptionType.get_items(plan=subscription_type)
    subscriptionType = {}
    if(len(subType) > 0):
        subscriptionType = subType[0]
    subscription_type_id = subscriptionType.id
    subscription_price = subscriptionType.stripe_price

    user_id = json_dict['user_id']
    user = User.query.get(user_id)

    try:
        stripe.PaymentMethod.attach(
            json_dict['paymentMethodId'],
            customer=json_dict['customer_id'],
        )
        # Set the default payment method on the customer
        stripe.Customer.modify(json_dict['customer_id'], invoice_settings={
                'default_payment_method': json_dict['paymentMethodId'],
            }, email=user.email, name=user.firstname
        )
       
        # Create the subscription
        subscription = stripe.Subscription.create(
            customer=json_dict['customer_id'],
            items=[
                {
                    'price': subscription_price
                }
            ],
            expand=['latest_invoice.payment_intent'],
        )
        print("Subscription object")
        
        user_subscription_dict = {}
        if(subscription.latest_invoice.payment_intent.status == 'succeeded'):
            subscription_dict = jsonify(subscription).json
            user_subscription_dict['user_id'] = json_dict['user_id']
            user_subscription_dict['subscription_id'] = subscription_dict['id']
            user_subscription_dict['subscription_type_id'] = subscription_type_id
            s_date = datetime.fromtimestamp(subscription_dict['current_period_start'])
            user_subscription_dict['current_start_date'] = s_date
            e_date = datetime.fromtimestamp(subscription_dict['current_period_end'])
            user_subscription_dict['current_end_date'] = e_date
            user_subscription_dict['type_object'] = subscription_dict['object']
            user_subscription_dict['application_fee_percent'] = subscription_dict['application_fee_percent']
            user_subscription_dict['billing_cycle_anchor'] = subscription_dict['billing_cycle_anchor']
            user_subscription_dict['billing_thresholds'] = subscription_dict['billing_thresholds']
            user_subscription_dict['cancel_at'] = subscription_dict['cancel_at']
            user_subscription_dict['cancel_at_period_end'] = subscription_dict['cancel_at_period_end']
            user_subscription_dict['canceled_at'] = subscription_dict['canceled_at']
            user_subscription_dict['collection_method'] = subscription_dict['collection_method']
            
            userSubscription = UserSubscription.get_subscription(user_id=user_id)
            if len(userSubscription) > 0:
                userSubscription[0].update(user_subscription_dict)
            else:
                newUserSubscription = UserSubscription()
                newUserSubscription.update(user_subscription_dict)
            user.update({'subscribed':1})

        start_date = userSubscription.current_start_date.strftime('%Y-%m-%d %H:%M:%S')
        if subscriptionType.plan == 'Adaya Lite': #adayalite
            Payment.send_subscription_confirmation_email_adayalite(user_email=user.email, user_name=user.firstname, subscription_start=start_date)
        if subscriptionType.plan == 'Adaya Lifestyle': #adayalifestyle
            Payment.send_subscription_confirmation_email_adayalifestyle(user_email=user.email, user_name=user.firstname, subscription_start=start_date)
        
        return jsonify(subscription).json

    except Exception as e:
        return jsonify(error={'message': str(e)}), 200
Exemplo n.º 14
0
def init_database():
    db = AC().db
    # Create the database and the database table
    db.create_all()
    member = Role("member")
    admin = Role("admin")
    user = User("*****@*****.**", "1q2w3e4r")
    user.email_confirmed = True
    user2 = User("*****@*****.**", "1q2w3e4r")
    user3 = User("*****@*****.**", "1q2w3e4r")
    user4 = User("*****@*****.**", "1q2w3e4r")
    user.role = admin
    user2.email_confirmed = True
    user2.subscribed = True
    user3.email_confirmed = True
    user3.subscribed = True
    user4.email_confirmed = False
    max_no_products_per_month = ConfigValues('max_no_products_per_month', 20)
    max_no_free_products_adayalite_user = ConfigValues(
        'max_no_free_products_adayalite_user', 4)
    max_no_of_items_per_order_adayalifestyle = ConfigValues(
        'max_no_of_items_per_order_adayalifestyle', 4)
    max_no_products_per_order = ConfigValues('max_no_products_per_order', 4)
    min_duration_of_rental = ConfigValues('min_duration_of_rental', 4)
    max_duration_of_rental = ConfigValues('max_duration_of_rental', 7)
    max_no_of_vouchers = ConfigValues('max_no_of_vouchers', 2)
    MAIL_USERNAME = ConfigValues('MAIL_USERNAME', '*****@*****.**')
    MAIL_PASSWORD = ConfigValues('MAIL_PASSWORD', 'adaya1234')
    MAIL_SERVER = ConfigValues('MAIL_SERVER', 'smtp.gmail.com')
    MAIL_PORT = ConfigValues('MAIL_PORT', 465)
    MAIL_DEFAULT_SENDER = ConfigValues('MAIL_DEFAULT_SENDER',
                                       '*****@*****.**')
    EMAIL_PASSWORD_RESET_SECRET_KEY = ConfigValues(
        'EMAIL_PASSWORD_RESET_SECRET_KEY', 'Thisisasecret!')
    SIB_KEY = ConfigValues('SIB_KEY', 'gzryVUPZHa1GW7n6')
    subtype = SubscriptionType(plan='Adaya Lite', price=10)
    subtype2 = SubscriptionType(plan='Adaya Premium', price=40)
    usersubscription = UserSubscription()
    usersubscription.user_id = 2
    usersubscription.current_start_date = datetime.now()
    usersubscription.current_end_date = datetime.strptime(
        '2020-09-06 05:58:00', '%Y-%m-%d %H:%M:%S')
    usersubscription.subscription_type = subtype
    usersubscription2 = UserSubscription()
    usersubscription2.user_id = 3
    usersubscription2.current_start_date = datetime.now()
    usersubscription2.current_end_date = datetime.strptime(
        '2020-08-06 05:58:00', '%Y-%m-%d %H:%M:%S')
    usersubscription2.subscription_type = subtype2
    voucher = Voucher('HAO20')
    voucher.discount_fixed_amount = 100
    voucher.product_id = 3
    voucher.redeem_by = datetime.strptime('2020-8-13 00:00:00',
                                          '%Y-%m-%d %H:%M:%S')
    voucher2 = Voucher('LUO20')
    voucher2.discount_fixed_amount = 8.00
    voucher2.product_id = 1
    voucher2.redeem_by = datetime.strptime('2020-8-13 00:00:00',
                                           '%Y-%m-%d %H:%M:%S')
    for x in range(1, 11):
        variation = Variation('S')
        variation.product_id = x
        variation.price = 10
        variation.stock = 1
        variation1 = Variation('M')
        variation1.product_id = x
        variation1.price = 20
        variation1.stock = 1
        variation2 = Variation('L')
        variation2.product_id = x
        variation2.price = 30
        variation2.stock = 1
        variation3 = Variation('XL')
        variation3.product_id = x
        variation3.price = 40
        variation3.stock = 1
        db.session.add(variation)
        db.session.add(variation1)
        db.session.add(variation2)
        db.session.add(variation3)
    db.session.add(max_no_products_per_order)
    db.session.add(max_no_products_per_month)
    db.session.add(max_no_free_products_adayalite_user)
    db.session.add(max_no_of_items_per_order_adayalifestyle)
    db.session.add(min_duration_of_rental)
    db.session.add(max_duration_of_rental)
    db.session.add(max_no_of_vouchers)
    db.session.add(MAIL_USERNAME)
    db.session.add(MAIL_PASSWORD)
    db.session.add(MAIL_SERVER)
    db.session.add(MAIL_PORT)
    db.session.add(MAIL_DEFAULT_SENDER)
    db.session.add(EMAIL_PASSWORD_RESET_SECRET_KEY)
    db.session.add(SIB_KEY)
    db.session.add(voucher)
    db.session.add(voucher2)
    db.session.add(member)
    db.session.add(user)
    db.session.add(user2)
    db.session.add(user3)
    db.session.add(user4)
    db.session.add(subtype)
    db.session.add(subtype2)
    db.session.add(usersubscription)
    db.session.add(usersubscription2)
    food_category = ProductCategory('food')
    clothes_category = ProductCategory('cloth')
    food_article = ArticleCategory('food-article')
    clothes_article = ArticleCategory('cloth-article')
    status = ArticleStatus('draft')
    order_status = OrderStatus('completed')
    db.session.add(order_status)
    db.session.add(food_article)
    db.session.add(clothes_article)
    db.session.add(food_category)
    db.session.add(clothes_category)
    for x in range(10):
        product = Product('Haoluo')
        article = Article(randomString(10))
        order = Order()
        order_item = OrderItem()
        order_item.quantity = 1
        order_item.variation_id = 2
        order_item.start_date = datetime.strptime('2020-4-1 00:00:00',
                                                  '%Y-%m-%d %H:%M:%S')
        order_item.end_date = datetime.strptime('2020-4-8 00:00:00',
                                                '%Y-%m-%d %H:%M:%S')
        order.order_items = []
        order.order_items.append(order_item)
        article_category = food_article
        category = food_category
        if x % 2 == 0:
            category = clothes_category
            article_category = clothes_article
        product.category = category
        article.category = article_category
        article.status = status
        db.session.add(order)
        db.session.add(product)
        db.session.add(order_item)
        db.session.add(article)
    db.session.commit()
    yield db
    db.drop_all()