Esempio n. 1
0
def promotions(request):
    """Record a promotion, by getting promo code,
    finding any matching promotion document,
    and updating the views."""
    try:
        data = loads(request.body)
        promo_code = data['promo_code']
        matches = get_collection('promos/events/promo_stats',
                                 filters=[
                                     {
                                         'key': 'hash',
                                         'operation': '>=',
                                         'value': promo_code
                                     },
                                     {
                                         'key': 'hash',
                                         'operation': '<=',
                                         'value': '\uf8ff'
                                     },
                                 ])
        match = matches[0]
        promo_hash = match['hash']
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        increment_value(f'promos/events/promo_stats/{promo_hash}', 'views')
        add_to_array(f'promos/events/promo_stats/{promo_hash}', 'viewed_at',
                     timestamp)
        # Optional: If user has an account,
        # record which user visited in viewed_by collection.
        return JsonResponse({'message': {'success': True}})
    except:
        return JsonResponse({'message': {'success': False}})
Esempio n. 2
0
def update_totals(model_type, organization_id, doc_id):
    """Update the total count of a given model type for the day
    the document ID was created."""
    digits = sub('[^0-9]', '', doc_id)
    year = digits[:2]
    month = digits[2:4]
    day = digits[4:6]
    date = f'20{year}-{month}-{day}'
    ref = f'organizations/{organization_id}/stats/organization_settings/daily_totals/{date}'
    add_to_array(ref, f'total_{model_type}', doc_id)
def subscribe(request):
    """Subscribe a user to newsletters, sending them a notification with the
    ability to unsubscribe. Creates a Cannlytics account and sends a welcome
    email if the user does not have an account yet.
    """

    # Ensure that the user has a valid email.
    data = loads(request.body)
    try:
        user_email = data['email']
        validate_email(user_email)
    except ValidationError:
        response = {
            'success': False,
            'message': 'Invalid email in request body.'
        }
        return JsonResponse(response)

    # Create a promo code that can be used to download data.
    promo_code = get_promo_code(8)
    add_to_array('promos/data', 'promo_codes', promo_code)

    # Record the subscription in Firestore.
    now = datetime.now()
    iso_time = now.isoformat()
    data['created_at'] = iso_time
    data['updated_at'] = iso_time
    data['promo_code'] = promo_code
    update_document(f'subscribers/{user_email}', data)

    # Save the user's subscription.
    plan_name = data['plan_name']
    try:
        claims = authenticate_request(request)
        uid = claims['uid']
        user_data = {'support': True}
        if plan_name == 'newsletter':
            user_data['newsletter'] = True
        else:
            user_data[f'{plan_name}_subscription_id'] = data['id']
        update_document(f'users/{uid}', user_data)
    except KeyError:
        pass

    # Create an account if one does not exist.
    # Optional: Load messages from state?
    try:
        name = (data.get('first_name', '') + data.get('last_name', '')).strip()
        _, password = create_user(name, user_email)
        message = f'Congratulations,\n\nYou can now login to the Cannlytics console (https://console.cannlytics.com) with the following credentials.\n\nEmail: {user_email}\nPassword: {password}\n\nAlways here to help,\nThe Cannlytics Team'  #pylint: disable=line-too-long
        subject = 'Welcome to the Cannlytics Platform'
    except:
        message = f'Congratulations,\n\nYou are now subscribed to Cannlytics.\n\nPlease stay tuned for more material or email {DEFAULT_FROM_EMAIL} to begin.\n\nAlways here to help,\nThe Cannlytics Team'  #pylint: disable=line-too-long
        subject = 'Welcome to the Cannlytics Newsletter'

    # Send a welcome / thank you email.
    # (Optional: Use HTML template.)
    # template_url = 'website/emails/newsletter_subscription_thank_you.html'
    send_mail(
        subject=subject,
        message=message,
        from_email=DEFAULT_FROM_EMAIL,
        recipient_list=[user_email, DEFAULT_FROM_EMAIL],
        fail_silently=False,
        # html_message = render_to_string(template_url, {'context': 'values'})
    )

    # Create an activity log.
    create_log(
        ref='logs/website/subscriptions',
        claims=claims,
        action=f'User ({user_email}) subscribed to {plan_name}.',
        log_type='subscription',
        key='subscribe',
        changes=data,
    )

    # Return a success message.
    response = {'success': True, 'message': 'User successfully subscribed.'}
    return JsonResponse(response)
def test_firestore():
    """Test Firestore functions by managing a test document."""

    # Initialize Firebase.
    env = environ.Env()
    env.read_env('../.env')
    credentials = env('GOOGLE_APPLICATION_CREDENTIALS')
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials
    db = firebase.initialize_firebase()

    # Create a collection reference.
    col_ref = firebase.create_reference(db, 'tests')
    assert isinstance(col_ref, CollectionReference) == True

    # Create a document reference.
    doc_ref = firebase.create_reference(db, 'tests/firebase_test')
    assert isinstance(doc_ref, DocumentReference) == True

    # Create a document.
    firebase.update_document('tests/firebase_test', {'user': '******'})

    # Update a document.
    firebase.update_document('tests/firebase_test', {'test': 'firebase_test'})

    # Get the document.
    data = firebase.get_document('tests/firebase_test')
    assert data['user'] == 'CannBot'
    assert data['test'] == 'firebase_test'

    # Get a collection.
    filters = [{'key': 'test', 'operation': '==', 'value': 'firebase_test'}]
    docs = firebase.get_collection('tests', filters=filters)
    assert docs[0]['test'] == 'firebase_test'

    # Add an element to an array in a document.
    firebase.add_to_array('tests/firebase_test', 'likes', 'Testing')
    data = firebase.get_document('tests/firebase_test')
    assert 'Testing' in data['likes']

    # Remove an element from an array in a document.
    firebase.remove_from_array('tests/firebase_test', 'likes', 'Testing')
    data = firebase.get_document('tests/firebase_test')
    assert 'Testing' not in data['likes']

    # Increment a value in a document.
    firebase.increment_value('tests/firebase_test', 'runs')
    data = firebase.get_document('tests/firebase_test')
    assert data['runs'] > 0

    # Import .csv data to Firestore.
    ref = 'tests/test_collections/licensees'
    data_file = './assets/data/licensees_partial.csv'
    firebase.import_data(db, ref, data_file)
    
    # TODO: Test import .xlsx data to Firestore.
    
    # TODO: Test import .txt data to Firestore.
    
    # Export data to .csv from Firestore.
    output_csv_file = './assets/data/licensees_test.csv'
    output_xlsx_file = './assets/data/licensees_test.xlsx'
    firebase.export_data(db, ref, output_csv_file)
    
    # Export data to .xlsx from Firestore.
    firebase.export_data(db, ref, output_xlsx_file)