Esempio n. 1
0
 def test_not_admin_or_user(self):
     message_data = {
         'message_type': 'email',
         'subject': 'Subscription Failure Notice',
         'body': "Hi {{ first_name }},\nIt looks like we ran into "
                 "some trouble processing your subscription payment. "
                 "Please verify your billing information is correct "
                 "and we'll automatically retry to process the payment. "
                 "If the payment continues to fail we'll automatically "
                 "move you over to a free account. If you believe "
                 "there has been a mistake please respond to this "
                 "email and we'd be happy to help!\n\nBest Regards,"
                 "\n\nDevon",
         'template': 'personal',
         'from_user': {
             'type': 'test',
             'id': 69989
         },
         'to_user': {
             'type': 'user',
             'user_id': self.pleb.username
         }
     }
     res = IntercomMessageSerializer(data=message_data)
     valid = res.is_valid()
     self.assertFalse(valid)
     self.assertEqual(
         res.errors,
         {
             'from_user': ["The only valid values for "
                           "'type' are 'user' and 'admin'"]}
     )
Esempio n. 2
0
    def complete_order(self, request, object_uuid=None):
        if request.user.username != "tyler_wiersing" \
                and request.user.username != "devon_bleibtrey":
            return Response({"detail": "You do not have permission to "
                                       "perform this action.",
                             "status_code": status.HTTP_403_FORBIDDEN},
                            status=status.HTTP_403_FORBIDDEN)
        order = self.get_object()
        tracking_url = request.data.get("tracking_url", None)
        if tracking_url:
            order.tracking_url = tracking_url
            order.completed = True
            order.save()
            order_owner = Pleb.get(order.owner_username)
            message_data = {
                'message_type': 'email',
                'subject': 'Sagebrew Order Processed',
                'body': 'Hi %s,\nYour Order has been processed and you '
                        'can track the delivery here:\n\n%s '
                        % (order_owner.first_name, tracking_url),
                'template': "personal",
                'from_user': {
                    'type': "admin",
                    'id': settings.INTERCOM_ADMIN_ID_DEVON},
                'to_user': {
                    'type': "user",
                    'user_id': order.owner_username}
            }
            serializer = IntercomMessageSerializer(data=message_data)
            if serializer.is_valid():
                serializer.save()

            mission = order.get_mission()
            mission_owner = Pleb.get(mission.owner_username)
            message_data = {
                'message_type': 'email',
                'subject': 'Someone has given you a Gift!',
                'body': 'Hi %s,\nSomeone has sent you a Gift from your '
                        'Giftlist!\nYou can track the delivery here:\n\n'
                        '%s'
                        % (mission_owner.first_name, tracking_url),
                'template': "personal",
                'from_user': {
                    'type': "admin",
                    'id': settings.INTERCOM_ADMIN_ID_DEVON},
                'to_user': {
                    'type': "user",
                    'user_id': mission.owner_username}
            }
            serializer = IntercomMessageSerializer(data=message_data)
            if serializer.is_valid():
                serializer.save()
        return Response(OrderSerializer(order).data, status=status.HTTP_200_OK)
Esempio n. 3
0
 def test_pleb_doesnt_exist(self, m):
     admin_data = {
         "type": "admin.list",
         "admins": [
             {
                 "type": "admin",
                 "id": 69989,
                 "name": "Devon Bleibtrey",
                 "email": "*****@*****.**"
             }
         ]
     }
     m.get(self.intercom_url, json=admin_data,
           status_code=status.HTTP_200_OK)
     message_data = {
         'message_type': 'email',
         'subject': 'Subscription Failure Notice',
         'body': "Hi {{ first_name }},\nIt looks like we ran into "
                 "some trouble processing your subscription payment. "
                 "Please verify your billing information is correct "
                 "and we'll automatically retry to process the payment. "
                 "If the payment continues to fail we'll automatically "
                 "move you over to a free account. If you believe "
                 "there has been a mistake please respond to this "
                 "email and we'd be happy to help!\n\nBest Regards,"
                 "\n\nDevon",
         'template': 'personal',
         'from_user': {
             'type': 'admin',
             'id': 69989
         },
         'to_user': {
             'type': 'user',
             'user_id': str(uuid1())
         }
     }
     res = IntercomMessageSerializer(data=message_data)
     valid = res.is_valid()
     self.assertFalse(valid)
     self.assertEqual(
         res.errors,
         {'to_user':
             ["Profile %s Does Not Exist"
              % message_data['to_user']['user_id']]})
Esempio n. 4
0
    def create(self, validated_data):
        request, _, _, _, _ = gather_request_data(self.context)
        product_ids = validated_data.get('product_ids', [])
        mission = validated_data.get('mission', None)
        total = validated_data.get('total', 0)
        owner = Pleb.get(request.user.username)
        order = Order(total=total, owner_username=owner.username).save()
        order.owner.connect(owner)
        order.mission.connect(mission)
        for product_id in product_ids:
            product = Product.nodes.get(object_uuid=product_id)
            product.orders.connect(order)

        message_data = {
            'message_type':
            'email',
            'subject':
            'Submit Mission For Review',
            'body':
            'Hi Team,\n%s has submitted an Order. '
            'Please review it in the <a href="%s">'
            'council area</a>. ' %
            (order.owner_username,
             reverse('council_orders', request=self.context.get('request'))),
            'template':
            "personal",
            'from_user': {
                'type': "admin",
                'id': settings.INTERCOM_ADMIN_ID_DEVON
            },
            'to_user': {
                'type': "user",
                'user_id': settings.INTERCOM_USER_ID_DEVON
            }
        }
        serializer = IntercomMessageSerializer(data=message_data)
        if serializer.is_valid():
            serializer.save()

        return order
Esempio n. 5
0
 def create(self, validated_data):
     user = validated_data['user']
     current_site = get_current_site(self.context.get('request'))
     site_name = current_site.name
     context = {
         'email': validated_data['email'],
         'domain': current_site.domain,
         'site_name': site_name,
         'first_name': user.first_name,
         'uid': urlsafe_base64_encode(force_bytes(user.pk)),
         'user': user,
         'token': default_token_generator.make_token(user)
     }
     message_data = {
         'message_type': 'email',
         'subject': 'Sagebrew Reset Password Request',
         'body': get_template('email_templates/password_reset.html').render(
             Context(context)),
         'template': "personal",
         'from_user': {
             'type': "admin",
             'id': settings.INTERCOM_ADMIN_ID_DEVON
         },
         'to_user': {
             'type': "user",
             'user_id': user.username
         }
     }
     serializer = IntercomMessageSerializer(data=message_data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return {"detail": "Reset email successfully sent",
             "status": status.HTTP_200_OK,
             "email": validated_data['email']}
Esempio n. 6
0
    def update(self, instance, validated_data):
        request, _, _, _, _ = gather_request_data(self.context)
        stripe.api_key = settings.STRIPE_SECRET_KEY
        stripe.api_version = settings.STRIPE_API_VERSION
        mission = validated_data.pop('mission', None)
        quest = validated_data.pop('quest', None)
        payment_method = validated_data.pop('payment_method', None)

        donor = Pleb.get(instance.owner_username)
        quest_desc = quest.title \
            if quest.title else "%s %s" % (quest.first_name, quest.last_name)
        mission_desc = mission.get_mission_title()
        description = "Gift purchase to %s's mission for %s" % (quest_desc,
                                                                mission_desc)
        payment_method = payment_method if payment_method is not None \
            else donor.stripe_default_card_id
        stripe_res = stripe.Charge.create(customer=donor.stripe_customer_id,
                                          amount=instance.total,
                                          currency="usd",
                                          description=description,
                                          receipt_email=donor.email,
                                          source=payment_method)
        instance.stripe_charge_id = stripe_res['id']
        instance.paid = True
        instance.save()

        message_data = {
            'message_type':
            'email',
            'subject':
            'New Gift',
            'body':
            get_template('orders/email/new_order.html').render(
                Context({
                    'first_name': quest.first_name,
                    'mission_title': mission_desc,
                    "donor_first_name": donor.first_name,
                    "donor_last_name": donor.last_name,
                })),
            'template':
            "personal",
            'from_user': {
                'type': "admin",
                'id': settings.INTERCOM_ADMIN_ID_DEVON
            },
            'to_user': {
                'type': "user",
                'user_id': quest.owner_username
            }
        }
        serializer = IntercomMessageSerializer(data=message_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return instance
Esempio n. 7
0
 def create(self, validated_data):
     volunteer = validated_data.pop('volunteer', None)
     mission = validated_data.pop('mission', None)
     activity = Volunteer(mission_id=mission.object_uuid,
                          **validated_data).save()
     activity.volunteer.connect(volunteer)
     activity.mission.connect(mission)
     mission_owner = Pleb.get(username=mission.owner_username)
     message_data = {
         'message_type':
         'email',
         'subject':
         'New Volunteer',
         'body':
         get_template('volunteer/email/new_volunteer.html').render(
             Context({
                 'first_name':
                 mission_owner.first_name,
                 'mission_title':
                 mission.get_mission_title(),
                 "activities": [
                     dict(settings.VOLUNTEER_ACTIVITIES)[item]
                     for item in validated_data['activities']
                 ],
                 "volunteer_first_name":
                 volunteer.first_name,
                 "volunteer_last_name":
                 volunteer.last_name,
                 "mission_volunteers":
                 reverse('mission_volunteers',
                         kwargs={
                             'object_uuid': mission.object_uuid,
                             'slug': slugify(mission.get_mission_title())
                         },
                         request=self.context.get('request'))
             })),
         'template':
         "personal",
         'from_user': {
             'type': "admin",
             'id': settings.INTERCOM_ADMIN_ID_DEVON
         },
         'to_user': {
             'type': "user",
             'user_id': mission.owner_username
         }
     }
     serializer = IntercomMessageSerializer(data=message_data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return activity
Esempio n. 8
0
 def create(self, validated_data):
     request = self.context.get('request')
     profile = self.context.get('profile')
     user = self.context.get('user')
     if request is None:
         raise ValidationError("Verification email must be "
                               "requested from application")
     if user is None:
         user = request.user
     if profile is None:
         profile = Pleb.get(
             username=user.username, cache_buster=True)
     token_gen = EmailAuthTokenGenerator()
     message_data = {
         'message_type': 'email',
         'subject': 'Sagebrew Email Verification',
         'body': get_template('email_templates/verification.html').render(
             Context({
                 'first_name': user.first_name,
                 'verification_url': "%s%s%s" % (
                     settings.EMAIL_VERIFICATION_URL,
                     token_gen.make_token(user, profile), '/')
             })),
         'template': "personal",
         'from_user': {
             'type': "admin",
             'id': settings.INTERCOM_ADMIN_ID_DEVON
         },
         'to_user': {
             'type': "user",
             'user_id': user.username
         }
     }
     serializer = IntercomMessageSerializer(
         data=message_data, context={'profile': profile,
                                     'user': user})
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return {}
Esempio n. 9
0
    def create(self, validated_data):
        request = self.context.get('request')
        response_dict = {
            "id": validated_data['id'],
            "type": validated_data['type'],
            'data': validated_data['data']
        }
        Intercom.app_id = settings.INTERCOM_APP_ID
        Intercom.app_api_key = settings.INTERCOM_API_KEY
        stripe.api_key = settings.STRIPE_SECRET_KEY
        stripe.api_version = settings.STRIPE_API_VERSION
        event_type = validated_data['type']
        if event_type == "invoice.payment_failed":
            try:
                customer = stripe.Customer.retrieve(
                    validated_data['data']['object']['customer'])
            except stripe.InvalidRequestError:
                raise serializers.ValidationError("Ran into some issues")
            try:
                pleb = Pleb.nodes.get(email=customer['email'])
            except (DoesNotExist, Pleb.DoesNotExist):
                return response_dict

            message_data = {
                'message_type':
                'email',
                'subject':
                'Subscription Failure Notice',
                'body':
                "Hi {{ first_name }},\nIt looks like we ran into "
                "some trouble processing your subscription payment. "
                "Please verify your billing information is correct "
                "and we'll automatically retry to process the payment. "
                "If the payment continues to fail we'll automatically "
                "move you over to a free account. If you believe "
                "there has been a mistake please respond to this "
                "email and we'd be happy to help!\n\nBest Regards,"
                "\n\nDevon",
                'template':
                'personal',
                'from_user': {
                    'type': 'admin',
                    'id': settings.INTERCOM_ADMIN_ID_DEVON
                },
                'to_user': {
                    'type': 'user',
                    'user_id': pleb.username
                }
            }
            serializer = IntercomMessageSerializer(data=message_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            response_dict["detail"] = "Invoice Payment Failed"
            return response_dict
        if event_type == "account.updated":
            try:
                account = stripe.Account.retrieve(
                    validated_data['data']['object']['id'])
            except (stripe.InvalidRequestError,
                    stripe.APIConnectionError) as e:
                logger.exception(e)
                raise serializers.ValidationError(e)
            except stripe.AuthenticationError:
                # Just return silently here so that Stripe stops sending us the
                # unauthenticatable user
                return response_dict
            if account.get('deleted', False):
                return response_dict
            try:
                pleb = Pleb.nodes.get(email=account.email)
            except (DoesNotExist, Pleb.DoesNotExist):
                return response_dict
            quest = Quest.nodes.get(owner_username=pleb.username)

            if quest.account_verified != "verified" \
                    and account.legal_entity.verification.status == "verified":
                # Need this to ensure the notification is only sent once if
                # Stripe sends a subsequent message before we've saved the
                # verification off.
                query = 'MATCH (a:Notification {action_name: ' \
                        '"Your Quest has been verified!"})' \
                        '-[:NOTIFICATION_TO]->(pleb:Pleb {username: "******"}) ' \
                        'RETURN a' % pleb.username
                res, _ = db.cypher_query(query)
                if res.one is None:
                    create_system_notification(
                        to_plebs=[pleb],
                        notification_id=str(uuid1()),
                        url=reverse('quest_manage_banking',
                                    kwargs={'username': pleb.username}),
                        action_name="Your Quest has been verified!")
                quest_ser = QuestSerializer(instance=quest,
                                            data={'active': True},
                                            context={
                                                "secret": settings.SECRET_KEY,
                                                "request": request
                                            })
                quest_ser.is_valid(raise_exception=True)
                quest_ser.save()
                cache.delete("%s_quest" % quest.owner_username)
                # Update quest after saving from serializer so we're not working
                # with a stale instance.
                quest = Quest.nodes.get(owner_username=pleb.username)
                # Need this because the serializer doesn't get into the area
                # where verification is updated unless a new external account
                # is added.
                quest.account_verified = \
                    account.legal_entity.verification.status
                quest.account_verified_date = datetime.now(pytz.utc)
                # When a quest is verified it automatically becomes active
                # If a user wants to take their quest inactive they have the
                # option but to reactivate they have to reach out to us and
                # explain because we don't want people just going active,
                # inactive and screwing with donors.
                quest.active = True
                message_data = {
                    'message_type':
                    'email',
                    'subject':
                    'Quest Verified',
                    'body':
                    "Hi Team,\n%s's Quest has been verified by Stripe. "
                    "Please review it in the <a href='%s'>"
                    "council area</a>." %
                    (quest.owner_username,
                     reverse('council_missions', request=request)),
                    'template':
                    "personal",
                    'from_user': {
                        'type': "admin",
                        'id': settings.INTERCOM_ADMIN_ID_DEVON
                    },
                    'to_user': {
                        'type': "user",
                        'user_id': settings.INTERCOM_USER_ID_DEVON
                    }
                }
                serializer = IntercomMessageSerializer(data=message_data)
                if serializer.is_valid():
                    serializer.save()

            if account.verification.fields_needed:
                quest.account_verification_fields_needed = \
                    account.verification.fields_needed
            quest.account_verified = \
                account.legal_entity.verification.status
            quest.account_verification_details = \
                str(account.legal_entity.verification.details)
            if quest.account_first_updated is None:
                quest.account_first_updated = datetime.now(pytz.utc)

            verify = account.verification

            # Determine if we need Quest to upload identification documentation
            if 'legal_entity.verification.document' in verify.fields_needed:
                quest.verification_document_needed = True

            # Save off when the additional information is due by
            if hasattr(verify, 'due_by') and verify.due_by is not None:
                quest.verification_due_date = datetime.fromtimestamp(
                    account.verification.due_by)
            else:
                quest.verification_due_date = None

            # Indicate why the account was disabled by the payment processing
            # platform
            if verify.disabled_reason is not None:
                quest.verification_disabled_reason = \
                    account.verification.disabled_reason\
                    .replace('_', " ").title()
            else:
                quest.verification_disabled_reason = None

            quest.save()
            cache.delete("%s_quest" % quest.owner_username)
            response_dict["detail"] = "Account Updated"
            return response_dict
        if event_type == "transfer.failed":
            try:
                transfer = stripe.Transfer.retrieve(
                    validated_data['data']['object']['id'])
                if transfer.type == 'stripe_account':
                    account = stripe.Account.retrieve(transfer.destination)
                    if account.get('deleted', False):
                        return response_dict
                else:
                    raise serializers.ValidationError('An error occurred')
            except (stripe.InvalidRequestError,
                    stripe.APIConnectionError) as e:
                logger.exception(e)
                raise serializers.ValidationError(e)
            except stripe.AuthenticationError:
                # Just return silently here so that Stripe stops sending us the
                # unauthenticatable user
                return response_dict
            try:
                pleb = Pleb.nodes.get(email=account.email)
            except (DoesNotExist, Pleb.DoesNotExist):
                return response_dict
            create_system_notification(
                to_plebs=[pleb],
                notification_id=str(uuid1()),
                url=reverse('quest_manage_banking',
                            kwargs={'username': pleb.username}),
                action_name="A transfer to your bank account has "
                "failed! Please review that your "
                "Quest Banking information is correct.")
            Event.create(event_name="stripe-transfer-failed",
                         user_id=pleb.username,
                         created=calendar.timegm(
                             datetime.now(pytz.utc).utctimetuple()))
            response_dict["detail"] = "Transfer Failed"
            return response_dict
        if event_type == 'customer.subscription.trial_will_end':
            try:
                customer = stripe.Customer.retrieve(
                    validated_data['data']['object']['customer'])
            except (stripe.InvalidRequestError,
                    stripe.APIConnectionError) as e:
                logger.exception(e)
                raise serializers.ValidationError(e)
            try:
                pleb = Pleb.nodes.get(email=customer.email)
            except (DoesNotExist, Pleb.DoesNotExist):
                return response_dict
            create_system_notification(
                to_plebs=[pleb],
                notification_id=str(uuid1()),
                url=reverse('quest_manage_billing',
                            kwargs={'username': pleb.username}),
                action_name="Your Pro Trial will "
                "be ending soon, add a payment method to "
                "keep your Pro Account features.")
            response_dict["detail"] = "Trail Will End"
            return response_dict
        response_dict["detail"] = "No updates"
        return response_dict
Esempio n. 10
0
    def update(self, instance, validated_data):
        from plebs.neo_models import Pleb
        owner = Pleb.get(instance.owner_username)
        prev_feedback = instance.review_feedback
        instance.review_feedback = validated_data.pop('review_feedback',
                                                      instance.review_feedback)
        if prev_feedback != instance.review_feedback and not instance.active:
            problem_list = [dict(settings.REVIEW_FEEDBACK_OPTIONS)[item]
                            for item in instance.review_feedback]
            message_subject = "Mission Review: Completed"
            message_body = render_to_string(
                'email_templates/mission_review_success.html',
                context={"first_name": owner.first_name,
                         "title": instance.get_mission_title(),
                         "conversation_url":
                             reverse('question-create',
                                     request=self.context.get('request')),
                         "update_url": reverse(
                             'mission_update_create',
                             kwargs={
                                 'object_uuid': instance.object_uuid,
                                 'slug': slugify(instance.get_mission_title())
                             }, request=self.context.get('request')
                         )})
            if problem_list:
                message_subject = "Mission Review: Action Needed"
                message_body = render_to_string(
                    'email_templates/mission_review_errors.html',
                    context=dict(
                        first_name=owner.first_name,
                        title=instance.get_mission_title(),
                        problems=problem_list,
                        epic_link=reverse(
                            'mission_edit_epic',
                            kwargs={
                                'object_uuid': instance.object_uuid,
                                "slug": slugify(instance.get_mission_title())
                            }, request=self.context.get('request'))))
            else:
                instance.active = True

            message_data = {
                'message_type': 'email',
                'subject': message_subject,
                'body': message_body,
                'template': "personal",
                'from_user': {
                    'type': "admin",
                    'id': settings.INTERCOM_ADMIN_ID_DEVON},
                'to_user': {
                    'type': "user",
                    'user_id': instance.owner_username}
            }
            serializer = IntercomMessageSerializer(data=message_data)
            if serializer.is_valid():
                serializer.save()
        if not instance.review_feedback:
            instance.active = True
            serializer = IntercomEventSerializer(
                data={'event_name': "take-mission-live",
                      'username': instance.owner_username})
            # Don't raise an error because we rather not notify intercom than
            # hold up the mission activation process
            if serializer.is_valid():
                serializer.save()
        instance.save()
        cache.delete("%s_mission" % instance.object_uuid)
        if instance.active:
            return super(MissionReviewSerializer, self).update(
                instance, validated_data)
        return instance
Esempio n. 11
0
    def update(self, instance, validated_data):
        from sb_base.serializers import validate_is_owner
        validate_is_owner(self.context.get('request', None), instance)
        instance.completed = validated_data.pop(
            'completed', instance.completed)

        initial_review_state = instance.submitted_for_review
        instance.submitted_for_review = validated_data.pop(
            'submitted_for_review', instance.submitted_for_review)
        instance.shared_on_facebook = validated_data.get(
            'shared_on_facebook', instance.shared_on_facebook)
        instance.shared_on_twitter = validated_data.get(
            'shared_on_twitter', instance.shared_on_twitter)
        instance.saved_for_later = validated_data.get('saved_for_later',
                                                      instance.saved_for_later)
        if instance.submitted_for_review and not initial_review_state and not \
                instance.saved_for_later:
            serializer = IntercomEventSerializer(
                data={'event_name': "submit-mission-for-review",
                      'username': instance.owner_username})
            if serializer.is_valid():
                serializer.save()
            message_data = {
                'message_type': 'email',
                'subject': 'Submit Mission For Review',
                'body': 'Hi Team,\n%s has submitted their %s Mission. '
                        'Please review it in the <a href="%s">'
                        'council area</a>. '
                        % (instance.owner_username, instance.title,
                           reverse('council_missions',
                                   request=self.context.get('request'))),
                'template': "personal",
                'from_user': {
                    'type': "admin",
                    'id': settings.INTERCOM_ADMIN_ID_DEVON},
                'to_user': {
                    'type': "user",
                    'user_id': settings.INTERCOM_USER_ID_DEVON}
            }
            serializer = IntercomMessageSerializer(data=message_data)
            if serializer.is_valid():
                serializer.save()
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.SUBMIT_FOR_REVIEW))
        title = validated_data.pop('title', instance.title)
        if instance.submitted_for_review and instance.review_feedback \
                and validated_data.get('epic', '') and not instance.active:
            message_data = {
                'message_type': 'email',
                'subject': 'Problem Mission Updated',
                'body': render_to_string(
                    "email_templates/problem_mission_updates.html",
                    context={"username": instance.owner_username,
                             "council_url":
                                 reverse('council_missions',
                                         request=self.context.get('request')),
                             "title": instance.title},
                    request=self.context.get('request')),
                'template': "personal",
                'from_user': {
                    'type': "admin",
                    'id': settings.INTERCOM_ADMIN_ID_DEVON},
                'to_user': {
                    'type': "user",
                    'user_id': settings.INTERCOM_USER_ID_DEVON}
            }
            serializer = IntercomMessageSerializer(data=message_data)
            if serializer.is_valid():
                serializer.save()
        if empty_text_to_none(title) is not None:
            instance.title = title
        instance.about = empty_text_to_none(
            validated_data.get('about', instance.about))
        if instance.about is not None:
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.MISSION_ABOUT_TITLE))
        instance.epic = remove_smart_quotes(
            validated_data.pop('epic', instance.epic))
        # We expect the epic to be set to None and not "" so that None
        # can be used in this function for checks and the templates.
        instance.epic = empty_text_to_none(render_content(instance.epic))
        prev_temp_epic = instance.temp_epic
        instance.temp_epic = remove_smart_quotes(validated_data.pop(
            'temp_epic', instance.temp_epic))
        instance.temp_epic = empty_text_to_none(
            render_content(instance.temp_epic))
        if prev_temp_epic != instance.temp_epic:
            instance.epic_last_autosaved = datetime.now(pytz.utc)
        if instance.epic is not None:
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.EPIC_TITLE))
        instance.facebook = clean_url(
            validated_data.get('facebook', instance.facebook))
        instance.linkedin = clean_url(
            validated_data.get('linkedin', instance.linkedin))
        instance.youtube = clean_url(
            validated_data.get('youtube', instance.youtube))
        instance.twitter = clean_url(
            validated_data.get('twitter', instance.twitter))
        instance.website = clean_url(
            validated_data.get('website', instance.website))
        instance.wallpaper_pic = validated_data.pop('wallpaper_pic',
                                                    instance.wallpaper_pic)
        if instance.shared_on_facebook:
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.SHARE_ON_FACEBOOK))
        if instance.shared_on_twitter:
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.SHARE_ON_TWITTER))
        if settings.DEFAULT_WALLPAPER not in instance.wallpaper_pic:
            db.cypher_query(
                'MATCH (mission:Mission {object_uuid: "%s"})-'
                '[:MUST_COMPLETE]->(task:OnboardingTask {title: "%s"}) '
                'SET task.completed=true RETURN task' % (
                    instance.object_uuid, settings.MISSION_WALLPAPER_TITLE))
        instance.save()
        cache.set("%s_mission" % instance.object_uuid, instance)
        if instance.active:
            return super(MissionSerializer, self).update(
                instance, validated_data)
        return instance
Esempio n. 12
0
    def create(self, validated_data):
        request, _, _, _, _ = gather_request_data(self.context)
        stripe.api_key = settings.STRIPE_SECRET_KEY
        stripe.api_version = settings.STRIPE_API_VERSION
        mission = validated_data.pop('mission', None)
        quest = validated_data.pop('quest', None)
        donor = validated_data.pop('donor', None)
        payment_method = validated_data.pop('payment_method', None)
        validated_data['mission_type'] = mission.focus_on_type
        donation = Donation(**validated_data).save()

        donor.donations.connect(donation)
        donation.mission.connect(mission)

        quest_desc = quest.title \
            if quest.title else "%s %s" % (quest.first_name, quest.last_name)
        mission_desc = mission.get_mission_title()
        description = "Donation to %s's mission for %s" % (quest_desc,
                                                           mission_desc)
        payment_method = payment_method if payment_method is not None \
            else donor.stripe_default_card_id
        stripe_res = stripe.Charge.create(
            customer=donor.stripe_customer_id,
            amount=donation.amount,
            currency="usd",
            description=description,
            destination=quest.stripe_id,
            receipt_email=donor.email,
            source=payment_method,
            application_fee=int(
                (donation.amount * (quest.application_fee +
                                    settings.STRIPE_TRANSACTION_PERCENT)) + 30)
        )
        donation.stripe_charge_id = stripe_res['id']
        donation.completed = True
        donation.save()
        message_data = {
            'message_type': 'email',
            'subject': 'New Donation',
            'body': get_template('donations/email/new_donation.html').render(
                Context({
                    'first_name': quest.first_name,
                    'mission_title': mission_desc,
                    "amount": "%0.2f" % (donation.amount / 100.0),
                    "donor_first_name": donor.first_name,
                    "donor_last_name": donor.last_name,
                    "quest_donation_page": reverse(
                        'quest_stats',
                        kwargs={'username': quest.owner_username},
                        request=self.context.get('request'))
                })),
            'template': "personal",
            'from_user': {
                'type': "admin",
                'id': settings.INTERCOM_ADMIN_ID_DEVON
            },
            'to_user': {
                'type': "user",
                'user_id': quest.owner_username
            }
        }
        serializer = IntercomMessageSerializer(data=message_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        cache.delete("%s_total_donated" % mission.object_uuid)
        cache.delete("%s_total_donated" % quest.object_uuid)
        cache.delete("%s_average_donation_amount" % mission.object_uuid)
        return donation