Beispiel #1
0
def create_model_list( model_schema, model_dict, total_items, iterate_over_key=None ):
    """Builds a list of models. Uses the Marshmallow schema and a dictionary.

    :param model_schema: Marshmallow schema for deserialization.
    :param model_dict: The dictionary to deserialize.
    :param total_items: Total items to build.
    :param iterate_over_key: A key to iterate over.
    :return: List of models.
    """

    # Create a list of models.
    models = []
    i = 1
    while i <= total_items:
        model_copy_dict = copy.deepcopy( model_dict )
        if 'searchable_id' in model_copy_dict:
            model_copy_dict[ 'searchable_id' ] = uuid.uuid4()
        elif 'gift_searchable_id' in model_copy_dict:
            model_copy_dict[ 'gift_searchable_id' ] = uuid.uuid4()
        if iterate_over_key:
            model_copy_dict[ iterate_over_key ] = i
            model = from_json( model_schema, model_copy_dict, create=True )
        else:
            model = from_json( model_schema, model_copy_dict, create=True )
        models.append( model.data )
        i += 1
    return models
    def test_get_gifts_by_given_to(self):
        """Gifts endpoint which retrieves all gifts by given_to list ( methods = [ POST ] )."""

        with self.app.app_context():
            url = '/donation/gifts/given-to'

            # The given_to field enums: [ 'ACTION', 'NERF', 'SUPPORT' ]
            given_tos = GiftModel.given_to.property.columns[0].type.enums

            # Ensure that with no database entries endpoint returns nothing.
            response = self.test_client.post(url,
                                             data=json.dumps(
                                                 {'given_to': given_tos[0]}),
                                             content_type='application/json',
                                             headers=self.headers)
            data_returned = json.loads(response.data.decode('utf-8'))
            self.assertEqual(len(data_returned), 0)

            # Create one gift for each given_to.
            gift_models = []
            for given_to in given_tos:
                gift_model = from_json(GiftSchema(),
                                       get_gift_dict({
                                           'searchable_id':
                                           uuid.uuid4(),
                                           'given_to':
                                           given_to
                                       }),
                                       create=True)
                gift_models.append(gift_model.data)

            # Create one gift with the same enumeration for return of multiple gifts.
            gift_model = from_json(GiftSchema(),
                                   get_gift_dict({
                                       'searchable_id': uuid.uuid4(),
                                       'given_to': given_tos[0]
                                   }),
                                   create=True)
            gift_models.append(gift_model.data)

            database.session.bulk_save_objects(gift_models)
            database.session.commit()

            # Ensure that with the one duplicated given_to two gifts are returned.
            response = self.test_client.post(url,
                                             data=json.dumps(
                                                 {'given_to': given_tos[0]}),
                                             content_type='application/json',
                                             headers=self.headers)
            data_returned = json.loads(response.data.decode('utf-8'))
            self.assertEqual(len(data_returned), 2)

            # Ensure that with 2 given_tos 3 gifts are returned.
            response = self.test_client.post(
                url,
                data=json.dumps({'given_to': [given_tos[0], given_tos[1]]}),
                content_type='application/json',
                headers=self.headers)
            data_returned = json.loads(response.data.decode('utf-8'))
            self.assertEqual(len(data_returned), 3)
    def test_update_campaign_with_image(
            self,
            mock_init_storage_function,
            mock_save_function,
            mock_delete_function
    ):  # pylint: disable=unused-argument, too-many-arguments
        """Update an image on the Campaign ( methods = [ POST ] )."""
        with self.app.app_context():

            amounts = get_campaign_amount_jsons()[ 0:3 ]

            # Get the model that will have some, but not all, fields updated.
            campaign_model = from_json( CampaignSchema(), get_campaign_dict() ).data

            database.session.add( campaign_model )

            amount_models = [ from_json( CampaignAmountsSchema(), amount ).data for amount in amounts ]
            database.session.bulk_save_objects( amount_models )

            database.session.commit()

            form_data = get_update_campaign_dict( { 'id': 1, 'photo_type': 'jpeg' } )
            form_data[ 'amounts' ] = json.dumps( amounts[ 0:1 ] )

            response = self.get_response( '/donation/campaigns', form_data )

            self.assertEqual( response.status_code, status.HTTP_200_OK )

            campaign_model_updated = CampaignModel.query.filter_by( id=1 ).one()

            # Make sure the fields that are to be updated actually get updated.
            self.assertEqual( campaign_model_updated.description, form_data[ 'description' ] )
            self.assertEqual( campaign_model_updated.message, form_data[ 'message' ] )
            self.assertEqual( campaign_model_updated.photo_type, form_data[ 'photo_type' ] )
            self.assertEqual( campaign_model_updated.background, int( form_data[ 'background' ] ) )

            # Make sure the fields that were not updated don't change.
            self.assertEqual( campaign_model.name, campaign_model_updated.name )
            self.assertEqual( campaign_model.date_from_utc, campaign_model_updated.date_from_utc )
            self.assertEqual( campaign_model.date_to_utc, campaign_model_updated.date_to_utc )
            self.assertEqual( campaign_model.video_name, campaign_model_updated.video_name )
            self.assertEqual( campaign_model.video_url, campaign_model_updated.video_url )
            self.assertEqual( campaign_model.is_active, campaign_model_updated.is_active )
            self.assertEqual( campaign_model.is_default, campaign_model_updated.is_default )

            for index, campaign_amount_model in enumerate( CampaignAmountsModel.query.all() ):
                self.assertEqual( campaign_amount_model.amount, Decimal( amounts[ index ][ 'amount' ] ) )
                self.assertEqual( campaign_amount_model.weight, int( amounts[ index ][ 'weight' ] ) )
                self.assertEqual( campaign_amount_model.campaign_id, int( amounts[ index ][ 'campaign_id' ] ) )
    def test_get_campaign_amounts( self ):
        """Retrieve the Campaign amounts given its ID ( methods = [ GET ] )."""
        with self.app.app_context():
            url = '/donation/campaigns/2/amounts'

            # Endpoint will check to see that the campaign exists before retrieving amounts and so create a few.
            total_campaigns = 4
            campaign_models = create_model_list(
                CampaignSchema(), get_campaign_dict(), total_campaigns
            )

            database.session.bulk_save_objects( campaign_models )

            campaign_amounts_dict = get_campaign_amount_jsons()
            campaign_amount_models = [ ]
            for amount in campaign_amounts_dict:
                campaign_amount_models.append( from_json( CampaignAmountsSchema(), amount ).data )

            database.session.bulk_save_objects( campaign_amount_models )
            database.session.commit()

            response = self.test_client.get( url, headers=self.headers )
            amounts_returned = json.loads( response.data.decode( 'utf-8' ) )

            self.assertEqual( len( amounts_returned ), 3 )
    def test_campaign_model(self):
        """A test to ensure that campaigns are saved correctly to the database."""

        with self.app.app_context():
            campaign_dict = get_campaign_dict()

            campaign_model = from_json(CampaignSchema(),
                                       campaign_dict,
                                       create=True)
            database.session.add(campaign_model.data)
            database.session.commit()

            campaign_query = CampaignModel.query.filter_by(
                name=campaign_dict['name']).one()
            campaign_session = database.session.query( CampaignModel )\
                .filter_by( name=campaign_dict[ 'name' ] ).one()

            kwargs = {
                'self': self,
                'model_dict': campaign_dict,
                'model': CampaignModel,
                'model_data': campaign_model.data,
                'model_query': campaign_query,
                'model_session': campaign_session
            }
            ensure_query_session_aligned(kwargs)
Beispiel #6
0
def build_transaction(transaction_dict):
    """Given a transaction dictionary method builds the model.

    :param transaction_dict: The transaction dictionary.
    :return: transaction.model.data: The Transaction model built from the given dictionary.
    """

    with app.app_context():
        transaction_model = from_json(TransactionSchema(),
                                      transaction_dict,
                                      create=True)
        database.session.add(transaction_model.data)
        database.session.commit()
        print()
        print(' Build TransactionModel')
        print('    transaction_model.id         : {}'.format(
            transaction_model.data.id))
        print('    transaction_model.date_in_utc: {}'.format(
            transaction_model.data.date_in_utc))
        print('    transaction_model.type       : {}'.format(
            transaction_model.data.type))
        print('    transaction_model.status     : {}'.format(
            transaction_model.data.status))
        print()
        return transaction_model.data
Beispiel #7
0
def create_gift_transactions_date(
        transaction_schema,
        transaction_dict,
        total_transactions,
        total_gifts ):
    """Builds a list of transactions with iterated gift ID's and dates.

    :param transaction_schema: Marshmallow schema for deseriazation.
    :param transaction_dict: Dictionary to deserialize.
    :param total_transactions: Number of transactions to attach to a gift ID.
    :param total_gifts: Number of gifts to attach transactions to.
    :return: List of transaction models.
    """

    # Create a set of transactions and attach to a specific gift.
    # Here are the time deltas: { gift 1: [ 0, -2, -4, -6 ], gift 2: [ -8, -10, -12, -14 ] }
    date_in_utc = datetime.utcnow().replace( hour=0, minute=0, second=0, microsecond=0 )
    iterate_dict = copy.deepcopy( transaction_dict )
    transaction_models = []
    i = 1
    while i <= total_gifts:
        j = 1
        while j <= total_transactions:
            iterate_dict[ 'gift_id' ] = i
            iterate_dict[ 'date_in_utc' ] = date_in_utc.strftime( '%Y-%m-%d %H:%M:%S' )
            transaction_model = from_json( transaction_schema, iterate_dict, create=True )
            transaction_models.append( transaction_model.data )
            date_in_utc = date_in_utc - timedelta( days=2 )
            j += 1
        i += 1
    return transaction_models
    def test_categorize_donor(self, ultsys_user_function):  # pylint: disable=unused-argument
        """The caging process categorizes donors as new, exists, cage, or caged. This function tests this process."""

        with self.app.app_context():
            # Use an existing user so category is exists.
            category = categorize_donor(
                flatten_user_dict(get_exists_donor_dict()))
            self.assertEqual(category[0], 'exists')

            # Use a caged donor so category is caged.
            caged_donor_dict = get_caged_donor_dict(
                {'gift_searchable_id': uuid.uuid4()})
            caged_donor = from_json(CagedDonorSchema(), caged_donor_dict)
            database.session.add(caged_donor.data)
            database.session.commit()
            category = categorize_donor(caged_donor_dict)
            self.assertEqual(category[0], 'caged')

            # Use the existing user, change the name so category is cage.
            cage_donor = copy.deepcopy(get_exists_donor_dict())
            cage_donor['user_address']['user_first_name'] = 'Sherry'
            category = categorize_donor(flatten_user_dict(cage_donor))
            self.assertEqual(category[0], 'cage')

            # Get a new donor so category is new.
            category = categorize_donor(flatten_user_dict(
                get_new_donor_dict()))
            self.assertEqual(category[0], 'new')
    def test_transaction_model(self):
        """A test to ensure that transactions are saved correctly to the database."""

        with self.app.app_context():
            transaction_dict = get_transaction_dict({'gift_id': 1})

            transaction_model = from_json(TransactionSchema(),
                                          transaction_dict,
                                          create=True)
            database.session.add(transaction_model.data)
            database.session.commit()

            transaction_query = TransactionModel.query.filter_by(
                gift_id=transaction_dict['gift_id']).one()
            transaction_session = database.session.query( TransactionModel )\
                .filter_by( gift_id=transaction_dict[ 'gift_id' ] )\
                .one()

            kwargs = {
                'self': self,
                'model_dict': transaction_dict,
                'model': TransactionModel,
                'model_data': transaction_model.data,
                'model_query': transaction_query,
                'model_session': transaction_session
            }
            ensure_query_session_aligned(kwargs)
    def test_campaign_amounts_model(self):
        """A test to ensure that campaign amounts are saved correctly to the database."""

        with self.app.app_context():
            # campaign_amounts_dict = get_campaign_amounts_dict()
            #
            # campaign_amounts_model = from_json( CampaignAmountsSchema(), campaign_amounts_dict, create=True )
            # database.session.add( campaign_amounts_model.data )
            # database.session.commit()

            campaign_amounts = get_campaign_amount_jsons()
            campaign_amount_dict = campaign_amounts[0]
            campaign_amount_model = from_json(CampaignAmountsSchema(),
                                              campaign_amount_dict,
                                              create=True)
            database.session.add(campaign_amount_model.data)
            database.session.commit()

            campaign_amount_query = CampaignAmountsModel.query\
                .filter_by( campaign_id=campaign_amount_dict[ 'campaign_id' ] ).one()
            campaign_amount_session = database.session.query( CampaignAmountsModel ) \
                .filter_by( campaign_id=campaign_amount_dict[ 'campaign_id' ] ).one()

            kwargs = {
                'self': self,
                'model_dict': campaign_amount_dict,
                'model': CampaignAmountsModel,
                'model_data': campaign_amount_model.data,
                'model_query': campaign_amount_query,
                'model_session': campaign_amount_session
            }
            ensure_query_session_aligned(kwargs)
    def test_queued_donor_model(self):
        """A test to ensure that caged donors are saved correctly to the database."""

        with self.app.app_context():
            queued_donor_dict = get_queued_donor_dict({
                'gift_id':
                1,
                'gift_searchable_id':
                uuid.uuid4(),
                'customer_id':
                'customer_id'
            })

            queued_donor_model = from_json(QueuedDonorSchema(),
                                           queued_donor_dict,
                                           create=True)
            database.session.add(queued_donor_model.data)
            database.session.commit()

            queued_donor_query = QueuedDonorModel.query \
                .filter_by( customer_id=queued_donor_dict[ 'customer_id' ] ).one()
            queued_donor_session = database.session.query( QueuedDonorModel ) \
                .filter_by( customer_id=queued_donor_dict[ 'customer_id' ] ).one()

            kwargs = {
                'self': self,
                'model_dict': queued_donor_dict,
                'model': QueuedDonorModel,
                'model_data': queued_donor_model.data,
                'model_query': queued_donor_query,
                'model_session': queued_donor_session
            }
            ensure_query_session_aligned(kwargs)
    def test_gift_thank_you_model(self):
        """A test to ensure that gifts are saved correctly to the database."""

        with self.app.app_context():

            gift_thank_you_dict = {'gift_id': 1}

            gift_thank_you_model = from_json(GiftThankYouLetterSchema(),
                                             gift_thank_you_dict,
                                             create=True)
            database.session.add(gift_thank_you_model.data)
            database.session.commit()

            gift_thank_you_query = GiftThankYouLetterModel.query\
                .filter_by( gift_id=gift_thank_you_dict[ 'gift_id' ] ).one()
            gift_thank_you_session = database.session.query( GiftThankYouLetterModel )\
                .filter_by( gift_id=gift_thank_you_dict[ 'gift_id' ] ).one()

            kwargs = {
                'self': self,
                'model_dict': gift_thank_you_dict,
                'model': GiftThankYouLetterModel,
                'model_data': gift_thank_you_model.data,
                'model_query': gift_thank_you_query,
                'model_session': gift_thank_you_session
            }
            ensure_query_session_aligned(kwargs)
    def test_gift_model(self):
        """A test to ensure that gifts are saved correctly to the database."""

        with self.app.app_context():

            gift_dict = get_gift_dict({
                'user_id': 1,
                'recurring_subscription_id': 'abcdefg'
            })

            gift_model = from_json(GiftSchema(), gift_dict, create=True)
            database.session.add(gift_model.data)
            database.session.commit()

            gift_query = GiftModel.query.filter_by(
                user_id=gift_dict['user_id']).one()
            gift_session = database.session.query(GiftModel).filter_by(
                user_id=gift_dict['user_id']).one()

            kwargs = {
                'self': self,
                'model_dict': gift_dict,
                'model': GiftModel,
                'model_data': gift_model.data,
                'model_query': gift_query,
                'model_session': gift_session
            }
            ensure_query_session_aligned(kwargs)
    def test_agent_model(self):
        """A test to ensure that gifts are saved correctly to the database."""

        with self.app.app_context():

            agent_dict = get_agent_jsons()[AGENT_INDEX]

            agent_model = from_json(AgentSchema(), agent_dict, create=True)
            database.session.add(agent_model.data)
            database.session.commit()

            agent_query = AgentModel.query\
                .filter_by( user_id=agent_dict[ 'user_id' ] ).one()
            agent_session = database.session.query( AgentModel )\
                .filter_by( user_id=agent_dict[ 'user_id' ] ).one()

            kwargs = {
                'self': self,
                'model_dict': agent_dict,
                'model': AgentModel,
                'model_data': agent_model.data,
                'model_query': agent_query,
                'model_session': agent_session
            }
            ensure_query_session_aligned(kwargs)
    def test_get_gifts_by_user_id_get(self):
        """Gifts endpoint which retrieves all gifts with given user_id ( methods = [ GET ] )."""

        with self.app.app_context():
            url = '/donation/gift/user/{}'

            # Ensure that with no database entries endpoint returns nothing.
            response = self.test_client.get(url.format(1),
                                            headers=self.headers)
            data_returned = json.loads(response.data.decode('utf-8'))
            self.assertEqual(len(data_returned), 0)

            # Create a gift with a user_id.
            gift_model = from_json(GiftSchema(),
                                   get_gift_dict({
                                       'searchable_id': uuid.uuid4(),
                                       'user_id': 1
                                   }),
                                   create=True)
            database.session.add(gift_model.data)
            database.session.commit()

            # Ensure that with a user_id on a gift it is returned
            response = self.test_client.get(url.format(1),
                                            headers=self.headers)
            data_returned = json.loads(response.data.decode('utf-8'))
            self.assertEqual(len(data_returned), 1)
Beispiel #16
0
def generate_caged_donor(row):
    """Generate caged donor."""

    user_email_address = row['from_email_address']
    user_first_name, user_last_name = process_name(row['name'])
    caged_donor_payload = {
        'user_email_address': user_email_address,
        'user_first_name': user_first_name,
        'user_last_name': user_last_name,
    }

    # The following columns/fields might be optional from CSV files:
    # - address_line_1 --> user_address
    # - state_province_region_county_territory_prefecture_republic --> user_state ( 2 )
    # - town_city --> user_city
    # - zip_postal_code( may have 5 or 9 ) --> user_zipcode ( 5 )

    user_address = row.get('address_line_1')
    user_state = row.get(
        'state_province_region_county_territory_prefecture_republic')
    user_city = row.get('town_city')
    user_zipcode = row.get('zip_postal_code')
    if user_address and user_address != 'NA':
        caged_donor_payload['user_address'] = user_address
    if user_state and user_state != 'NA':
        caged_donor_payload['user_state'] = user_state[:2]
    if user_city and user_city != 'NA':
        caged_donor_payload['user_city'] = user_city
    if user_zipcode and user_zipcode != 'NA':
        caged_donor_payload['user_zipcode'] = user_zipcode[:5]

    caged_donor_schema = from_json(CagedDonorSchema(), caged_donor_payload)
    caged_donor_model = caged_donor_schema.data
    return caged_donor_model
Beispiel #17
0
def generate_a_transaction(row, transaction_ids, transaction_params):
    """

    :param row: A row from the CSV.
    :param transaction_ids: The transaction IDs.
    :param transaction_params: agent_id, transaction type, notes, and the gift ID.
    :return:
    """

    if 'gift_id' not in transaction_params or not transaction_params['gift_id']:
        gift_id = transaction_ids.get(row['reference_txn_id'])
    else:
        gift_id = transaction_params['gift_id']

    if 'notes' not in transaction_params:
        notes = 'from csv upload'
    else:
        notes = transaction_params['notes']

    transaction_payload = {
        'gift_id': gift_id,
        'date_in_utc': process_date_time(row['date'], row['time']),
        'enacted_by_agent_id': transaction_params['agent_id'],
        'type': transaction_params['type'],
        'status': process_transaction_status(row['status']),
        'reference_number': row['transaction_id'],
        'gross_gift_amount': process_decimal_amount(row['gross']),
        'fee': process_decimal_amount(row['fee']),
        'notes': notes
    }
    transaction_schema = from_json(TransactionSchema(), transaction_payload)
    transaction_model = transaction_schema.data
    return transaction_model
def record_bounced_check( payload ):
    """A function for recording the details of a bounced check.

    The payload required for the bounced check has the following keys:

    payload = {
        "gift_id": 1,
        "user_id": 1234,
        "reference_number": "201",
        "amount": "10.00",
        "transaction_notes": "Some transaction notes."
    }

    The reference number will be most likely the check number.

    :param dict payload: A dictionary that provides information to make the reallocation.
    :return:
    """

    gift_searchable_id = payload[ 'gift_searchable_id' ]
    try:
        gift_model = GiftModel.query.filter_by( searchable_id=gift_searchable_id ).one()

        # The first transaction created has the check amount.
        # The last has the current balance.
        gross_gift_amount = \
            gift_model.transactions[ 0 ].gross_gift_amount - gift_model.transactions[ -1 ].gross_gift_amount
    except:
        raise AdminFindGiftPathError()

    # Make sure the gift exists and that it has method_used='Check'.
    # Do not modify the database if method_used is not cCheck. Handle with app.errorhandler().
    method_used = MethodUsedModel.get_method_used( 'name', 'Check' )
    if gift_model.method_used_id != method_used.id:
        raise ModelGiftImproperFieldError

    enacted_by_agent = AgentModel.get_agent( 'Staff Member', 'user_id', payload[ 'user_id' ] )

    try:
        # If gift exists and method_used is a check, record thet the check bounced.
        date_in_utc = datetime.datetime.utcnow().strftime( '%Y-%m-%d %H:%M:%S' )
        transaction_json = {
            'gift_id': gift_model.id,
            'date_in_utc': date_in_utc,
            'enacted_by_agent_id': enacted_by_agent.id,
            'type': 'Bounced',
            'status': 'Completed',
            'reference_number': payload[ 'reference_number' ],
            'gross_gift_amount': gross_gift_amount,
            'fee': Decimal( 0.00 ),
            'notes': payload[ 'transaction_notes' ]
        }

        transaction = from_json( TransactionSchema(), transaction_json )
        database.session.add( transaction.data )
        database.session.commit()
    except:
        database.session.rollback()
        raise AdminTransactionModelPathError( where='parent' )
Beispiel #19
0
def create_transaction(transaction_dict):
    """Given a gift searchable ID create a transaction.

    The implementation uses transaction_dict[ 'gross_gift_amount' ] to update the current gross_gift_amount on
    the gift. If it should not be updated leave the field off the transaction_dict or set it to 0.00.

    :param transaction_dict: The transaction to create.
    :return:
    """

    sql_query = query_gift_equal_uuid('id',
                                      transaction_dict['gift_searchable_id'])
    try:
        gift_model = database.session.execute(sql_query).fetchone()

        # Get all the transactions on the gift and grab the current gross_gift_amount.
        transactions = TransactionModel.query.filter_by( gift_id=gift_model.id )\
            .order_by( TransactionModel.date_in_utc.desc() ).all()
        current_gross_gift_amount = Decimal(0.00)
        if transactions:
            current_gross_gift_amount = transactions[0].gross_gift_amount

    except SQLAlchemyORMNoResultFoundError as error:
        raise error

    if gift_model:

        reference_number = None
        transaction = TransactionModel.query \
            .filter_by( gift_id=gift_model.id ).filter_by( type='Gift' ).filter_by( status='Completed' ).one_or_none()
        if transaction:
            reference_number = transaction.reference_number

        scrub_transaction_dict(transaction_dict)

        date_in_utc = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        transaction_dict['date_in_utc'] = date_in_utc
        transaction_dict['gift_id'] = gift_model.id
        transaction_dict[ 'gross_gift_amount' ] = \
            current_gross_gift_amount + Decimal( transaction_dict[ 'gross_gift_amount' ] )
        transaction_dict['reference_number'] = reference_number

        try:
            transaction_model = from_json(TransactionSchema(),
                                          transaction_dict,
                                          create=True)
            database.session.add(transaction_model.data)
            database.session.commit()
        except MarshmallowValidationError as error:
            raise error
        except SQLAlchemyError as error:
            database.session.rollback()
            raise error

        return transaction_model.data

    raise ModelGiftNotFoundError
def build_models_sale(user, gift, transactions):
    """Given the dictionaries for the models go ahead and build them.

    :param dict user: User dictionary with necessary model fields, and may have additional fields.
    :param dict gift: Gift dictionary with necessary model fields, and may have additional fields.
    :param transactions: The list of transactions. If this is a Braintree sale, for example, there will be one
           transaction in the list. On the other hand if this is an administrative sale where the method used is
           a check or money order there will be 2 transactions.
    :return:
    """

    # We are not caging at the front of the sale, and do that at the end.
    # The user is stored in QueuedDonorModel and the gift is given a user_id = -2
    user_id = -2

    # Build the gift model dictionary, and flush to get new auto-incremented gift_id.
    try:
        # Build the gift.
        if not gift['campaign_id']:
            gift['campaign_id'] = None
        elif not get_campaign_by_id(gift['campaign_id']):
            gift['campaign_id'] = get_campaigns_by_type('is_default', 1)[0].id

        gift['user_id'] = user_id
        gift_model = from_json(GiftSchema(), gift)
        database.session.add(gift_model.data)
        database.session.flush()
        gift_id = gift_model.data.id
        user['gift_id'] = gift_id
        user['gift_searchable_id'] = gift_model.data.searchable_id
        user['campaign_id'] = gift_model.data.campaign_id

        # Build the transactions.
        for transaction in transactions:
            transaction['gift_id'] = gift_id
            transaction_model = from_json(TransactionSchema(), transaction)
            database.session.add(transaction_model.data)
            database.session.flush()
            transaction['id'] = transaction_model.data.id
        database.session.commit()
    except:
        database.session.rollback()
        raise BuildModelsGiftTransactionsPathError()
def create_ultsys_users():
    """Create the ulytsys users.

    :return:
    """
    # Create some ultsys user data for the Ultsys endpoints wrapped in functions for mocking.
    user_models_data = []
    for user_dict in ULTSYS_USER_DATA:
        user_model = from_json(UltsysUserSchema(), user_dict, create=True)
        user_models_data.append(user_model.data)
    database.session.bulk_save_objects(user_models_data)
    database.session.commit()
Beispiel #22
0
def generate_unresolved_transaction(row, unresolved_transaction_ids, agent_id):
    """Generate an unresolved transaction."""

    if row['transaction_id'] not in unresolved_transaction_ids:
        unresolved_transaction_payload = row.copy(
        )  # shallow copy here is fine ( no nested structure )
        unresolved_transaction_payload['enacted_by_agent_id'] = agent_id
        unresolved_transaction_schema = from_json(
            UnresolvedPaypalETLTransactionSchema(),
            unresolved_transaction_payload)
        unresolved_transaction_model = unresolved_transaction_schema.data
        return unresolved_transaction_model
    return None
Beispiel #23
0
    def test_donation_new_donor(self, ultsys_user_function,
                                create_ultsys_user_function,
                                update_ultsys_user_function,
                                mock_caging_function):  # pylint: disable=unused-argument
        """Test Braintree sale for a new donor.

        :param ultsys_user_function: Argument for mocked function.
        :param ultsys_user_update_function: Argument for mocked function.
        :param ultsys_user_create_function: Argument for mocked function.
        :return:
        """
        with self.app.app_context():
            # Create agent ( Braintree ) for the online donation.

            agent_dict = get_agent_dict()
            agent_model = from_json(AgentSchema(), agent_dict, create=True)
            database.session.add(agent_model.data)

            # Flush to get the ID and set the database.
            database.session.flush()
            database.session.commit()
            agent_id = agent_model.data.id

            # Call the function to be tested.
            payload = get_donate_dict({
                'user': get_new_donor_dict(),
                'recurring_subscription': False
            })
            result = post_donation(payload)

            self.assertEqual(result['job_id'], 'redis-queue-job-id')

            # The function should create one transaction, a gift, and a user.
            transaction = TransactionModel.query.filter_by(id=1).one_or_none()
            gift = GiftModel.query.filter_by(id=1).one_or_none()

            self.assertEqual(transaction.gift_id, gift.id)
            self.assertEqual(transaction.enacted_by_agent_id, agent_id)
            self.assertEqual(transaction.type,
                             self.parameters['transaction_type'])
            self.assertEqual(transaction.status,
                             self.parameters['transaction_status'])
            self.assertEqual(transaction.reference_number,
                             self.parameters['reference_number'])
            self.assertEqual(transaction.gross_gift_amount,
                             self.parameters['gross_gift_amount'])
            self.assertEqual(transaction.fee, self.parameters['fee'])

            self.assertEqual(str(gift.user_id), self.parameters['user_new_id'])
            self.assertEqual(gift.method_used_id, self.method_used_id)
            self.assertEqual(gift.given_to, self.parameters['given_to'])
Beispiel #24
0
def resolve_user(gift_with_customer_id):
    """If the user is caged or queued then return the model.

    :param gift_with_customer_id: The gift.
    :return: The caged/queued donor models ( at least one will be None ).
    """
    donor_model = None
    try:
        if gift_with_customer_id.user_id == -1:
            caged_donor_model = CagedDonorModel.query.filter_by(
                gift_id=gift_with_customer_id.id).one()
            caged_donor_dict = to_json(CagedDonorSchema(), caged_donor_model)
            donor_model = from_json(CagedDonorSchema(), caged_donor_dict.data)
        if gift_with_customer_id.user_id == -2:
            queued_donor_model = QueuedDonorModel.query.filter_by(
                gift_id=gift_with_customer_id.id).one()
            queued_donor_dict = to_json(QueuedDonorSchema(),
                                        queued_donor_model)
            donor_model = from_json(QueuedDonorSchema(),
                                    queued_donor_dict.data)
        return donor_model
    except:  # noqa: E722
        raise BraintreeWebhooksIDPathError(
            type_id=gift_with_customer_id.customer_id)
def create_user(user_parameters):
    """A mock function to create a new user.

    :param dict user_parameters: The user dictionary to be created in the mocked ultsys user data.
    :return: The ID of the new user
    """

    user_model = from_json(UltsysUserSchema(), user_parameters, create=True)

    database.session.add(user_model.data)
    database.session.flush()

    # There are
    user_id = user_model.data.ID
    user_model.data.uid = user_id

    return user_id
    def test_put_gift_update_note(self):
        """Gifts endpoint to add a note to a gift with searchable_id ( methods = [ PUT ] )."""

        with self.app.app_context():
            # Parameter in URL is for a searchable_id_prefix.
            url = '/donation/gift/{}/notes'

            agent_dict = get_agent_dict({
                'name': 'Aaron Peters',
                'user_id': 3255162,
                'type': 'Staff Member'
            })
            agent_model = from_json(AgentSchema(), agent_dict, create=True)
            database.session.add(agent_model.data)

            gift_transactions = TransactionModel.query.all()
            # Ensure no transactions in the database.
            self.assertEqual(len(gift_transactions), 0)

            gift_json = get_gift_dict()
            del gift_json['id']
            gift_json['searchable_id'] = uuid.uuid4()
            gift_model = GiftSchema().load(gift_json).data
            database.session.add(gift_model)
            database.session.commit()

            transaction_note = {
                'enacted_by_agent_id': '5',
                'note': 'Add this to the Gift please.'
            }

            response = self.test_client.put(url.format(
                gift_model.searchable_id.hex),
                                            data=json.dumps(transaction_note),
                                            content_type='application/json',
                                            headers=self.headers)

            self.assertEqual(response.status_code, status.HTTP_200_OK)

            # Make sure a transaction was added.
            gift_transactions = TransactionModel.query.all()

            self.assertEqual(len(gift_transactions), 1)
            self.assertEqual(gift_transactions[0].notes,
                             transaction_note['note'])
def build_campaign_model(form_data, create):
    """Save the dictionary to the model.

    :param form_data: What to save to the model
    :param create: Whether a POST or PUT
    :return:
    """

    default_campaigns = []
    if 'is_default' in form_data and form_data['is_default']:
        # Get all campaigns where is_default is set.
        default_campaigns = CampaignModel.query.filter_by(is_default=1).all()

    # Handle toggling of the field is_default.
    if create and len(default_campaigns) == 1:
        default_campaigns[0].is_default = 0
    elif not create and len(default_campaigns) == 1:
        if default_campaigns[0].id != form_data['id']:
            default_campaigns[0].is_default = 0

    try:
        if create:
            campaign_model = from_json(CampaignSchema(), form_data)
            database.session.add(campaign_model.data)
            database.session.flush()
        else:
            campaign_model = CampaignModel.query.get(int(form_data['id']))
            # This is a PUT and the Campaign needs to exist.
            if campaign_model:
                # Make sure the photo_type gets put on the update.
                form_data['photo_type'] = campaign_model.photo_type
                campaign_model = CampaignSchema().load(form_data,
                                                       instance=campaign_model,
                                                       partial=True)
            else:
                raise ModelCampaignImproperFieldError
    except MarshmallowValidationError as error:
        raise error
    except SQLAlchemyError as error:
        database.session.rollback()
        raise error

    return campaign_model
Beispiel #28
0
    def test_donation_donor_update(self, ultsys_user_function,
                                   create_ultsys_user_function,
                                   update_ultsys_user_function,
                                   mock_caging_function):  # pylint: disable=unused-argument
        """Test Braintree sale where there is an update to Braintree customer address.

        :param ultsys_user_function: Argument for mocked function.
        :param ultsys_user_update_function: Argument for mocked function.
        :param ultsys_user_create_function: Argument for mocked function.
        :return:
        """
        with self.app.app_context():
            # Create agent ( Braintree ) for the online donation.
            agent_dict = get_agent_dict()
            agent_model = from_json(AgentSchema(), agent_dict, create=True)
            database.session.add(agent_model.data)
            database.session.commit()

            # Call function to be tested with new billing information.
            # See customer_details in TRANSACTION_SUCCESSFUL.
            new_info = {
                'user': {
                    'id': 5,
                    'user_address': {
                        'user_address': '126 Jackson Street',
                        'user_zipcode': '48336'
                    }
                }
            }

            payload = get_donate_dict(new_info)
            result = post_donation(payload)

            self.assertEqual(result['job_id'], 'redis-queue-job-id')

            # The function should NOT update the user.
            user = UltsysUserModel.query.filter_by(ID=5).one_or_none()
            self.assertNotEqual(
                user.email, new_info['user']['user_address']['user_address'])
            self.assertNotEqual(
                user.zip,
                int(new_info['user']['user_address']['user_zipcode']))
Beispiel #29
0
def build_gift(gift_dict):
    """Given a dictionary for the Gift builds, commits and returns the model.

    Uses flush() so we can get the Gift ID.

    :param gift_dict: The Gift dictionary.
    :return: gift_model.data: The Gift model built from the given dictionary and has the new auto-incremented ID.
    """

    with app.app_context():
        gift_model = from_json(GiftSchema(), gift_dict, create=True)
        database.session.add(gift_model.data)
        database.session.flush()
        database.session.commit()
        print()
        print('Build GiftModel')
        print('    gift_model.id      : {}'.format(gift_model.data.id))
        print('    gift_model.given_to: {}'.format(gift_model.data.given_to))
        print()
        return gift_model.data
Beispiel #30
0
    def test_build_transaction( self ):
        """Transactions endpoint to add a transaction to a gift with searchable_id ( methods = [ POST ] )."""

        with self.app.app_context():
            # Parameter in URL is for a searchable_id_prefix.
            url = '/donation/gift/transaction'

            agent_dict = get_agent_dict( { 'name': 'Aaron Peters', 'user_id': 3255162, 'type': 'Staff Member' } )
            agent_model = from_json( AgentSchema(), agent_dict, create=True )
            database.session.add( agent_model.data )

            # Create a gift to attach a transaction to.
            gift_json = get_gift_dict()
            del gift_json[ 'id' ]
            gift_json[ 'searchable_id' ] = uuid.uuid4()
            gift_model = GiftSchema().load( gift_json ).data
            database.session.add( gift_model )
            database.session.commit()

            gift = GiftModel.query.all()[ 0 ]

            # Ensure no transactions currently on gift.
            self.assertEqual( len( gift.transactions ), 0 )

            new_transaction = get_transaction_dict(
                {
                    'gift_searchable_id': gift_json[ 'searchable_id' ].hex,
                    'enacted_by_agent_id': None
                }
            )

            self.test_client.post(
                url,
                data=json.dumps( new_transaction ),
                content_type='application/json',
                headers=self.headers
            )

            # Ensure the new transactions is now on the gift.
            self.assertEqual( len( gift.transactions ), 1 )
            self.assertEqual( gift.transactions[ 0 ].gift_searchable_id.hex, gift_json[ 'searchable_id' ].hex )