Ejemplo n.º 1
0
def mission_updates(request, object_uuid, slug=None):
    # Only need to check that at least one update exists here to mark that
    # updates are available for this mission.
    query = 'MATCH (quest:Quest)-[:EMBARKS_ON]->' \
            '(mission:Mission {object_uuid: "%s"}) ' \
            'WITH quest, mission ' \
            'OPTIONAL MATCH (mission)<-[:ABOUT]-(updates:Update) ' \
            'RETURN quest, mission, ' \
            'CASE WHEN count(updates) > 0 ' \
            'THEN true ELSE false END AS update' % object_uuid
    res, _ = db.cypher_query(query)
    if res.one is None:
        return redirect("404_Error")
    # Instead of doing inflation and serialization of all the updates here
    # without pagination lets just indicate if we have any or not and then
    # hit the endpoint to gather the actual updates.
    quest = Quest.inflate(res.one.quest)
    mission_obj = Mission.inflate(res.one.mission)
    return render(
        request, 'mission/updates.html', {
            "updates":
            res.one.update,
            "mission":
            MissionSerializer(mission_obj, context={
                "request": request
            }).data,
            "slug":
            slugify(mission_obj.get_mission_title()),
            "quest":
            QuestSerializer(quest).data
        })
Ejemplo n.º 2
0
def mission_endorsements(request, object_uuid, slug=None):
    # Just check if there are any endorsements either from a Pleb or a Quest
    query = 'MATCH (quest:Quest)-[:EMBARKS_ON]->' \
            '(mission:Mission {object_uuid:"%s"}) ' \
            'WITH quest, mission ' \
            'OPTIONAL MATCH (mission)<-[:ENDORSES]-(endorsement) ' \
            'RETURN endorsement, quest, mission' % object_uuid
    res, _ = db.cypher_query(query)
    # Instead of doing inflation and serialization of all the updates here
    # without pagination lets just indicate if we have any or not and then
    # hit the endpoint to gather the actual updates.
    quest = Quest.inflate(res.one.quest)
    mission_obj = Mission.inflate(res.one.mission)
    return render(
        request, 'mission/endorsements.html', {
            "quest":
            QuestSerializer(quest).data,
            "mission":
            MissionSerializer(mission_obj, context={
                "request": request
            }).data,
            "slug":
            slugify(mission_obj.get_mission_title()),
            "endorsements":
            True if res.one.endorsement else False
        })
Ejemplo n.º 3
0
    def repopulate_elasticsearch(self):
        # Profiles
        skip = 0
        while True:
            query = 'MATCH (profile:Pleb) RETURN DISTINCT profile ' \
                    'SKIP %s LIMIT 25' % skip
            skip += 24
            res, _ = db.cypher_query(query)
            if not res.one:
                break
            for profile in [Pleb.inflate(row[0]) for row in res]:
                update_search_object.apply_async(kwargs={
                    "object_uuid": profile.object_uuid,
                    "label": "pleb"
                })

        # Questions
        skip = 0
        while True:
            query = 'MATCH (question:Question) RETURN DISTINCT question ' \
                    'SKIP %s LIMIT 25' % skip
            skip += 24
            res, _ = db.cypher_query(query)
            if not res.one:
                break
            for question in [Question.inflate(row[0]) for row in res]:
                update_search_object.apply_async(kwargs={
                    "object_uuid": question.object_uuid,
                    "label": "question"
                })

        # Quests
        skip = 0
        while True:
            query = 'MATCH (quest:Quest) RETURN DISTINCT quest ' \
                    'SKIP %s LIMIT 25' % skip
            skip += 24
            res, _ = db.cypher_query(query)
            if not res.one:
                break
            for quest in [Quest.inflate(row[0]) for row in res]:
                update_search_object.apply_async(kwargs={
                    "object_uuid": quest.object_uuid,
                    "label": "quest"
                })
        # Missions
        skip = 0
        while True:
            query = 'MATCH (mission:Mission) RETURN DISTINCT mission ' \
                    'SKIP %s LIMIT 25' % skip
            skip += 24
            res, _ = db.cypher_query(query)
            if not res.one:
                break
            for mission in [Mission.inflate(row[0]) for row in res]:
                update_search_object.apply_async(kwargs={
                    "object_uuid": mission.object_uuid,
                    "label": "mission"
                })
Ejemplo n.º 4
0
 def set_quest_titles(self):
     query = 'MATCH (a:Quest) WHERE a.title IS NULL RETURN a'
     res, _ = db.cypher_query(query)
     for quest in [Quest.inflate(row[0]) for row in res]:
         quest.title = "%s %s" % (quest.first_name, quest.last_name)
         quest.save()
         cache.delete("%s_quest" % quest.object_uuid)
     self.stdout.write("completed quest titles\n", ending='')
Ejemplo n.º 5
0
 def endorsements(self, request, object_uuid=None):
     serialized = []
     endorsements = Mission.get_endorsements(object_uuid)
     page = self.paginate_queryset(endorsements)
     for node in page:
         if "Pleb" in node.labels:
             serialized.append(PlebSerializerNeo(Pleb.inflate(node.e)).data)
         if "Quest" in node.labels:
             serialized.append(QuestSerializer(Quest.inflate(node.e)).data)
     return self.get_paginated_response(serialized)
Ejemplo n.º 6
0
 def get_quest(self, obj):
     from sb_quests.neo_models import Quest
     from sb_quests.serializers import QuestSerializer
     request, _, _, _, _ = gather_request_data(self.context)
     query = 'MATCH (quest:Quest)-[:EMBARKS_ON]->' \
             '(:Mission {object_uuid: "%s"}) RETURN quest' % obj.object_uuid
     res, _ = db.cypher_query(query)
     if res.one is None:
         return None
     return QuestSerializer(Quest.inflate(res.one),
                            context={'request': request}).data
Ejemplo n.º 7
0
 def convert_social_links(self):
     twitter_string = "https://www.twitter.com/"
     facebook_string = "https://www.facebook.com/"
     linkedin_string = "https://www.linkedin.com/in/"
     youtube_string = "https://www.youtube.com/user/"
     skip = 0
     while True:
         query = 'MATCH (q:Quest) RETURN q ' \
                 'SKIP %s LIMIT 25' % skip
         skip += 24
         res, _ = db.cypher_query(query)
         if not res.one:
             break
         try:
             for quest in [Quest.inflate(row[0]) for row in res]:
                 if quest.twitter and twitter_string not in quest.twitter:
                     quest.twitter = "%s%s" % (twitter_string,
                                               quest.twitter)
                 if quest.facebook and facebook_string not in quest.facebook:
                     quest.facebook = "%s%s" % (facebook_string,
                                                quest.facebook)
                 if quest.linkedin and linkedin_string not in quest.linkedin:
                     quest.linkedin = "%s%s" % (linkedin_string,
                                                quest.linkedin)
                 if quest.youtube and youtube_string not in quest.youtube:
                     quest.youtube = "%s%s" % (youtube_string,
                                               quest.youtube)
                 quest.save()
                 cache.delete("%s_quest" % quest.object_uuid)
         except (CypherException, Exception):
             logger.exception("Convert Social Links: ")
             pass
     try:
         res, _ = db.cypher_query('MATCH (a:Mission) RETURN a')
         for mission in [Mission.inflate(row[0]) for row in res]:
             if mission.twitter and twitter_string not in mission.twitter:
                 mission.twitter = "%s%s" % (twitter_string,
                                             mission.twitter)
             if mission.facebook and facebook_string not in mission.facebook:
                 mission.facebook = "%s%s" % (facebook_string,
                                              mission.facebook)
             if mission.linkedin and linkedin_string not in mission.linkedin:
                 mission.linkedin = "%s%s" % (linkedin_string,
                                              mission.linkedin)
             if mission.youtube and youtube_string not in mission.youtube:
                 mission.youtube = "%s%s" % (youtube_string,
                                             mission.youtube)
             mission.save()
             cache.delete("%s_mission" % mission.object_uuid)
     except (CypherException, Exception):
         logger.exception("Convert Social Links: ")
         pass
Ejemplo n.º 8
0
 def get_quest(self):
     from sb_quests.neo_models import Quest
     # DEPRECATED use get_mission or get_quest instead
     # Not adding a deprecation warning as we cover this with the migration
     # command. Once that is executed we'll need to fix or remove this
     query = 'MATCH (o:PublicOfficial {object_uuid:"%s"})-' \
             '[:IS_HOLDING]->(c:Quest) RETURN c' \
             % self.object_uuid
     res, _ = db.cypher_query(query)
     if res.one:
         return Quest.inflate(res.one)
     else:
         return None
Ejemplo n.º 9
0
 def get_actual_amount(self, obj):
     from sb_quests.neo_models import Quest
     query = 'MATCH (d:Donation {object_uuid: "%s"})-' \
             '[:CONTRIBUTED_TO]->' \
             '(mission:Mission)<-[:EMBARKS_ON]-(quest:Quest) ' \
             'RETURN quest' % obj.object_uuid
     res, _ = db.cypher_query(query)
     if res.one is None:
         return None
     quest = Quest.inflate(res.one)
     application_fee = obj.amount * (
         quest.application_fee +
         settings.STRIPE_TRANSACTION_PERCENT) + 30
     return '{:,.2f}'.format(float(obj.amount - application_fee) / 100)
Ejemplo n.º 10
0
def delete_account(request):
    """
    Delete account page.
    """
    try:
        query = 'MATCH (q:Quest {owner_username:"******"}) RETURN q' % (
            request.user.username)
        res, _ = db.cypher_query(query)
        quest = QuestSerializer(Quest.inflate(res[0][0]),
                                context={
                                    'request': request
                                }).data
    except (DoesNotExist, Quest.DoesNotExist, IndexError):
        quest = None
    return render(request, 'settings/delete_account.html', {"quest": quest})
Ejemplo n.º 11
0
 def get_quest(self, obj):
     from sb_quests.neo_models import Quest
     from sb_quests.serializers import QuestSerializer
     # We use object_uuid here instead of owner_username as none of the
     # public officials have a owner
     quest = None
     query = 'MATCH (o:PublicOfficial {object_uuid: "%s"})-' \
             '[:IS_HOLDING]->(quest:Quest) ' \
             'RETURN quest' % obj.object_uuid
     res, _ = db.cypher_query(query)
     if res.one:
         quest = res.one
     if quest is not None:
         quest = QuestSerializer(Quest.inflate(quest)).data
     return quest
 def remove_duplicate_quests(self):
     skip = 0
     while True:
         query = 'MATCH (q:Quest) ' \
                 'RETURN DISTINCT q ' \
                 'SKIP %s LIMIT 25' % skip
         skip += 24
         res, _ = db.cypher_query(query)
         if not res.one:
             break
         for quest in [Quest.inflate(row[0]) for row in res]:
             query = 'MATCH (q:Quest {object_uuid:"%s"}) WHERE NOT ' \
                     '(q)-[]-(:Pleb) AND NOT (q)-[]-(:PublicOfficial) ' \
                     'AND NOT (q)-[]-(:Mission) WITH q ' \
                     'OPTIONAL MATCH (q)-[r]-() ' \
                     'DELETE q, r' % (quest.object_uuid)
             res, _ = db.cypher_query(query)
     cache.set(self.cache_key, True)
Ejemplo n.º 13
0
def general_settings(request):
    """
    Displays the users profile_page. This is where we call the functions to
    determine who the senators are for the plebs state and which
    representative for the plebs district. Checks to see if the user
    currently accessing the page is the same user as the one who owns the page.
    If so it loads the page fully, if the user is a friend of the owner of the
    page then it allows them to see posts and comments on posts on the
    owners wall. If the user is neither the owner nor a friend then it only
    shows the users name, congressmen, reputation and profile pictures along
    with a button that allows them to send a friend request.

    :param request:
    :return:
    """
    address_key = settings.ADDRESS_AUTH_ID
    query = 'MATCH (person:Pleb {username: "******"})' \
            '-[r:LIVES_AT]->(house:Address) RETURN house' % (
                request.user.username)
    try:
        res, col = db.cypher_query(query)
        address = AddressSerializer(Address.inflate(res[0][0]),
                                    context={
                                        'request': request
                                    }).data
    except (CypherException, ClientError):
        return redirect("500_Error")
    except IndexError:
        address = False
    try:
        query = 'MATCH (q:Quest {owner_username:"******"}) RETURN q' % (
            request.user.username)
        res, _ = db.cypher_query(query)
        quest = QuestSerializer(Quest.inflate(res[0][0]),
                                context={
                                    'request': request
                                }).data
    except (DoesNotExist, Quest.DoesNotExist, IndexError):
        quest = None
    return render(request, 'settings/general_settings.html', {
        "address": address,
        "address_key": address_key,
        "quest": quest
    })
Ejemplo n.º 14
0
 def get_quest(self, obj):
     from sb_quests.neo_models import Quest
     from sb_quests.serializers import QuestSerializer
     request, expand, _, relation, _ = gather_request_data(self.context)
     query = 'MATCH (d:Donation {object_uuid: "%s"})-' \
             '[:CONTRIBUTED_TO]->' \
             '(mission:Mission)<-[:EMBARKS_ON]-(quest:Quest) ' \
             'RETURN quest' % obj.object_uuid
     res, _ = db.cypher_query(query)
     if res.one is None:
         return None
     quest = Quest.inflate(res.one)
     if expand == 'true':
         return QuestSerializer(quest).data
     if relation == "hyperlink":
         return reverse('quest-detail',
                        kwargs={"object_uuid": quest.object_uuid},
                        request=request)
     return quest.owner_username
Ejemplo n.º 15
0
def mission_edit_updates(request, object_uuid, slug=None, edit_id=None):
    query = 'MATCH (update:Update {object_uuid: "%s"})-[:ABOUT]->' \
            '(mission:Mission)<-[:EMBARKS_ON]-(quest:Quest)' \
            'WITH update, mission, quest ' \
            'MATCH (quest)-[:EMBARKS_ON]->(missions:Mission) ' \
            'RETURN mission, quest, update, missions ' \
            'ORDER BY missions.created DESC' % edit_id
    res, _ = db.cypher_query(query)
    if res.one is None:
        return redirect("select_mission")

    missions = [
        MissionSerializer(Mission.inflate(row.missions)).data for row in res
    ]
    mission_obj = Mission.inflate(res.one.mission)
    return render(
        request, 'updates/edit.html', {
            "update": UpdateSerializer(Update.inflate(res.one.update)).data,
            "mission": MissionSerializer(mission_obj).data,
            "slug": slugify(mission_obj.get_mission_title()),
            "quest": QuestSerializer(Quest.inflate(res.one.quest)).data,
            "missions": missions
        })
Ejemplo n.º 16
0
def contribute_settings(request):
    """
    This view provides the necessary information for rendering a user's
    Quest settings. If they have an ongoing Quest it provides the information
    for that and if not it returns nothing and the template is expected to
    provide a button for the user to start their Quest.

    :param request:
    :return:
    """
    try:
        query = 'MATCH (q:Quest {owner_username:"******"}) RETURN q' % (
            request.user.username)
        res, _ = db.cypher_query(query)
        quest = QuestSerializer(Quest.inflate(res[0][0]),
                                context={
                                    'request': request
                                }).data
    except (DoesNotExist, Quest.DoesNotExist, IndexError):
        quest = None
    return render(request, 'settings/contribute_settings.html', {
        "stripe_key": settings.STRIPE_PUBLIC_KEY,
        "quest": quest
    })
Ejemplo n.º 17
0
 def get(self, request):
     try:
         query = 'MATCH (q:Quest {owner_username:"******"}) RETURN q' % (
             request.user.username)
         res, _ = db.cypher_query(query)
         quest = QuestSerializer(Quest.inflate(res[0][0]),
                                 context={
                                     'request': request
                                 }).data
     except (DoesNotExist, Quest.DoesNotExist, IndexError):
         quest = None
     return render(
         request, self.template_name, {
             'page_profile':
             PlebSerializerNeo(Pleb.get(username=request.user.username),
                               context={
                                   'expand': True,
                                   'request': request
                               }).data,
             'page_user':
             User.objects.get(username=request.user.username),
             'quest':
             quest
         })
Ejemplo n.º 18
0
def update_search_object(object_uuid,
                         label=None,
                         object_data=None,
                         index="full-search-base"):
    from plebs.serializers import PlebSerializerNeo
    from sb_quests.serializers import QuestSerializer
    from sb_quests.neo_models import Quest
    from sb_missions.serializers import MissionSerializer
    from sb_missions.neo_models import Mission
    from sb_questions.serializers import QuestionSerializerNeo
    from sb_base.neo_models import get_parent_votable_content
    if label is None:
        label = get_parent_votable_content(
            object_uuid).get_child_label().lower()
    logger.critical("Updating Search Object")
    logger.critical({"object_uuid": object_uuid})
    query = 'MATCH (a:%s {object_uuid:"%s"}) RETURN a' % \
            (label.title(), object_uuid)
    res, _ = db.cypher_query(query)
    if res.one:
        res.one.pull()
    else:
        raise update_search_object.retry(exc=DoesNotExist(
            'Object with uuid: %s '
            'does not exist' % object_uuid),
                                         countdown=3,
                                         max_retries=None)
    if label == "question":
        instance = Question.inflate(res.one)
        object_data = QuestionSerializerNeo(instance).data
        if 'mission' in object_data:
            object_data.pop('mission')
        if 'profile' in object_data:
            object_data.pop('profile')
        logger.critical(object_data)
    elif label == "quest":
        instance = Quest.inflate(res.one)
        object_data = QuestSerializer(instance).data
        logger.critical(object_data)
    elif label == "mission":
        instance = Mission.inflate(res.one)
        object_data = MissionSerializer(instance).data
        # Need to pop review_feedback because ES's serializer cannot parse
        # set types.
        # If we don't pop it we receive
        # TypeError("Unable to serialize set([]) (type: <type 'set'>)",))
        # If we can submit a JSON serialized version we can get around this by
        # using:
        # from rest_framework.renderers import JSONRenderer
        # JSONRenderer().render(serializer.data)
        # Also please note python's json.dumps() function runs into this same
        # issue.
        if 'review_feedback' in object_data:
            object_data.pop('review_feedback', None)
        if 'quest' in object_data:
            object_data.pop('quest')
        logger.critical(object_data)
    elif label == "pleb":
        instance = Pleb.inflate(res.one)
        object_data = PlebSerializerNeo(instance).data
        if 'quest' in object_data:
            object_data.pop('quest')
        logger.critical(object_data)
    else:
        # Currently we only need this functionality for Questions as
        # they are the only objects in search that we display votes
        # for in the search interface.
        error_dict = {
            "message": "Search False setup. "
            "Object Data None, Instance not None",
            "instance_label": label,
            "instance_uuid": object_uuid,
        }
        logger.critical(error_dict)
        return False
    try:
        es = Elasticsearch(settings.ELASTIC_SEARCH_HOST)
        res = es.index(index=index,
                       doc_type=object_data['type'],
                       id=object_uuid,
                       body=object_data)
    except (ElasticsearchException, TransportError, ConflictError,
            RequestError) as e:
        logger.exception("Failed to connect to Elasticsearch")
        logger.critical(object_data)
        raise update_search_object.retry(exc=e, countdown=5, max_retries=None)
    except KeyError:
        error_dict = {
            "message": "Search: KeyError False creation",
            "instance_uuid": object_uuid,
            "object_data": object_data
        }
        logger.critical(error_dict)
        return False
    try:
        if instance.search_id is None:
            instance.search_id = res['_id']
            instance.populated_es_index = True
            instance.save()
    except AttributeError:
        pass

    cache.delete("%s_vote_search_update" % object_uuid)
    return res
Ejemplo n.º 19
0
    def create(self, validated_data):
        from sb_gifts.neo_models import Giftlist
        from sb_quests.neo_models import Quest, Position
        request, _, _, _, _ = gather_request_data(self.context)
        query = 'MATCH (quest:Quest {owner_username: "******"}) WITH quest ' \
                'OPTIONAL MATCH (quest)-[:EMBARKS_ON]->' \
                '(mission:Mission) RETURN quest, ' \
                'count(mission) as mission_count' % request.user.username
        res, _ = db.cypher_query(query)
        if res.one is not None:
            quest = Quest.inflate(res.one['quest'])
            if quest.account_type == "free":
                if res.one['mission_count'] >= settings.FREE_MISSIONS:
                    raise serializers.ValidationError(
                        {"detail": "Sorry free Quests can only "
                                   "have 5 Missions.",
                         "developer_message": "",
                         "status_code": status.HTTP_400_BAD_REQUEST})
        else:
            raise serializers.ValidationError(
                {"detail": "We couldn't find a Quest for this "
                           "Mission. Please contact us if this "
                           "problem continues.",
                 "developer_message": "",
                 "status_code": status.HTTP_404_NOT_FOUND})
        add_district = ""
        focus_type = validated_data.get('focus_on_type')
        level = validated_data.get('level')

        # Properly Title the case of the following words in the location name
        location = validated_data.get('location_name')
        if location is not None:
            location = location.replace(
                " Of", " of").replace(" And", " and").replace(" Or", " or")
        focused_on = validated_data.get('focus_name')
        if focus_type == "advocacy":
            focused_on = slugify(focused_on)
        else:
            focused_on = slugify(
                focused_on).title().replace('-', ' ').replace('_', ' ')
        district = validated_data.get('district')
        formatted_location_name = validated_data.get('formatted_location_name')
        # TODO what happens if a moderator makes the mission?
        owner_username = request.user.username
        title = focused_on.title().replace('-', ' ').replace('_', ' ')
        mission = Mission(owner_username=owner_username, level=level,
                          focus_on_type=focus_type,
                          focus_name=focused_on,
                          title=title,
                          wallpaper_pic=static(
                              'images/wallpaper_capitol_2.jpg'),
                          formatted_location_name=formatted_location_name)\
            .save()
        giftlist = Giftlist().save()
        giftlist.mission.connect(mission)
        if focus_type == "position":
            if level == "federal":
                if district:
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->(:Location {name: "%s"})' \
                                '-[:ENCOMPASSES]->(location:Location ' \
                                '{name: "%s", sector: "federal"})' % (
                                    location, district)
                elif location and focused_on != "President":
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->' \
                                '(location:Location {name: "%s"})' % location
                else:
                    loc_query = '(location:Location {name: ' \
                                '"United States of America"})'
            elif level == "state_upper" or level == "state_lower" \
                    or level == "state":
                parent_location = "location"
                if district:
                    add_district = '-[:ENCOMPASSES]->' \
                                   '(location:Location ' \
                                   '{name: "%s", sector: "%s"})' \
                                   '' % (district, level)
                    parent_location = "b"
                # use sector for level input since we're talking about
                # state_upper and state_lower with the position
                # and level input here only has state, federal, and local
                loc_query = '(a:Location {name: "United States of America"})' \
                            '-[:ENCOMPASSES]->' \
                            '(%s:Location {name: "%s"})%s' % (
                                parent_location, location, add_district)
            else:
                loc_query = '(location:Location {external_id:"%s"})' % location
            query = 'MATCH %s-' \
                    '[:POSITIONS_AVAILABLE]->(position:Position ' \
                    '{name:"%s", level:"%s"}) RETURN position' % \
                    (loc_query, focused_on, level)
            res, _ = db.cypher_query(query)
            if not res.one:
                focused_on = slugify(focused_on).title().replace('-', ' ')\
                    .replace('_', ' ')
                new_position = Position(verified=False, name=focused_on,
                                        level=level,
                                        user_created=True).save()
                query = 'MATCH %s, ' \
                        '(position:Position {object_uuid:"%s"}) ' \
                        'CREATE UNIQUE (position)' \
                        '<-[r:POSITIONS_AVAILABLE]-(location) ' \
                        'RETURN position' % (loc_query,
                                             new_position.object_uuid)
                res, _ = db.cypher_query(query)
            query = 'MATCH %s-' \
                    '[:POSITIONS_AVAILABLE]->' \
                    '(position:Position {name: "%s", level: "%s"}),' \
                    '(mission:Mission {object_uuid: "%s"}),' \
                    '(quest:Quest {owner_username: "******"}) ' \
                    'CREATE UNIQUE (position)<-[:FOCUSED_ON]-' \
                    '(mission)<-[:EMBARKS_ON]-(quest) ' \
                    'WITH quest, location, mission, position ' \
                    'CREATE UNIQUE (location)<-[:WITHIN]-(mission) ' \
                    'RETURN mission' % (
                        loc_query, focused_on, level, mission.object_uuid,
                        owner_username)
            res, _ = db.cypher_query(query)
            mission = Mission.inflate(res.one)
        elif focus_type == "advocacy":
            focused_on = slugify(focused_on)
            try:
                Tag.nodes.get(name=focused_on)
            except (DoesNotExist, Tag.DoesNotExist):
                Tag(name=focused_on).save()
            if level == "local":
                loc_query = '(location:Location {external_id: "%s"}) ' % (
                    location)
            elif level == "state":
                if district:
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->(:Location {name: "%s"})' \
                                '-[:ENCOMPASSES]->(location:Location ' \
                                '{name: "%s", sector: "federal"}) ' % (
                                    location, district)
                else:
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->' \
                                '(location:Location {name: "%s"}) ' % location
            elif level == "federal":
                if district:
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->(:Location {name: "%s"})' \
                                '-[:ENCOMPASSES]->(location:Location ' \
                                '{name: "%s", sector: "federal"}) ' % (
                                    location, district)
                elif location and focused_on != "President":
                    loc_query = '(:Location {name: ' \
                                '"United States of America"})' \
                                '-[:ENCOMPASSES]->' \
                                '(location:Location {name: "%s"}) ' % location
                else:
                    loc_query = '(location:Location {name: ' \
                                '"United States of America"}) '
            else:
                raise serializers.ValidationError(
                    {"detail": "Sorry Could Not Determine Where You're "
                               "advocating. Please try a different "
                               "location or contact us.",
                     "developer_message": "",
                     "status_code": status.HTTP_400_BAD_REQUEST})
            query = 'MATCH (tag:Tag {name: "%s"}), ' \
                    '(quest:Quest {owner_username: "******"}), ' \
                    '(mission:Mission {object_uuid: "%s"}), ' \
                    '%s WITH tag, quest, mission, location ' \
                    'CREATE UNIQUE (tag)<-[:FOCUSED_ON]-(mission)' \
                    '<-[:EMBARKS_ON]-(quest) WITH location, mission ' \
                    'CREATE UNIQUE (mission)-[:WITHIN]->(location) ' \
                    'RETURN mission' % (focused_on,
                                        owner_username, mission.object_uuid,
                                        loc_query)
            res, _ = db.cypher_query(query)
            if res.one is not None:
                mission = Mission.inflate(res.one)
        setup_onboarding(quest, mission)
        spawn_task(task_func=send_reengage_message,
                   task_param={"mission_uuid": mission.object_uuid,
                               "mission_type": focus_type},
                   countdown=900)
        return mission
Ejemplo n.º 20
0
    def get(self, request, object_uuid=None, slug=None):
        # Do a second optional match to get the list of missions,
        # the first is just to make sure we're dealing with the actual
        # owner of the Mission.
        query = 'MATCH (pleb:Pleb {username: "******"})-[:IS_WAGING]->' \
            '(quest:Quest) WITH quest ' \
            'OPTIONAL MATCH (quest)-[:EMBARKS_ON]->(missions:Mission) ' \
            'RETURN missions, quest ' \
            'ORDER BY missions.created DESC' % request.user.username
        res, _ = db.cypher_query(query)
        if res.one is None:
            return redirect("404_Error")
        if res.one.missions is None:
            return redirect("select_mission")
        if object_uuid is None:
            mission_obj = Mission.inflate(res[0].missions)
            return redirect('mission_settings',
                            object_uuid=mission_obj.object_uuid,
                            slug=slug)

        mission_obj = Mission.get(object_uuid)
        if self.template_name == "manage/epic.html" and \
                not mission_obj.saved_for_later and \
                not mission_obj.submitted_for_review:
            if mission_obj.epic is None:
                return redirect('must_finish_epic',
                                object_uuid=mission_obj.object_uuid,
                                slug=slug)
            return redirect("submit_mission_for_review",
                            object_uuid=mission_obj.object_uuid,
                            slug=slug)
        missions = [
            MissionSerializer(Mission.inflate(row.missions)).data
            for row in res
        ]
        quest = Quest.inflate(res.one.quest)
        if mission_obj.owner_username != quest.owner_username:
            return redirect("404_Error")
        onboarding_sort, completed_count = order_tasks(object_uuid)
        if len(onboarding_sort) != 0:
            onboarding_done = int(
                (float(completed_count) / float(len(onboarding_sort))) * 100)
        else:
            onboarding_done = 0
        return render(
            request, self.template_name, {
                "missions":
                missions,
                "mission":
                MissionSerializer(mission_obj, context={
                    "request": request
                }).data,
                "quest":
                QuestSerializer(quest, context={
                    "request": request
                }).data,
                "slug":
                slugify(mission_obj.get_mission_title()),
                "epic_template":
                render_to_string("manage/placeholder_epic.html"),
                "update_placeholder":
                render_to_string("updates/placeholder.html"),
                "onboarding_top_3":
                onboarding_sort[:3],
                "onboarding_rest":
                onboarding_sort[3:],
                "onboarding_done":
                onboarding_done
            })
Ejemplo n.º 21
0
 def remove_duplicate_quests(self):
     skip = 0
     while True:
         query = 'MATCH (official:PublicOfficial) ' \
                 'RETURN DISTINCT official ' \
                 'SKIP %s LIMIT 25' % skip
         skip += 24
         res, _ = db.cypher_query(query)
         if not res.one:
             break
         for official in [PublicOfficial.inflate(row[0]) for row in res]:
             new_query = 'MATCH (a:Quest {owner_username: "******"}) ' \
                         'RETURN a' % official.object_uuid
             new_res, _ = db.cypher_query(new_query)
             if not new_res.one:
                 quest = Quest(
                     about=official.bio,
                     youtube=official.youtube,
                     twitter=official.twitter,
                     website=official.website,
                     first_name=official.first_name,
                     last_name=official.last_name,
                     owner_username=official.object_uuid,
                     title="%s %s" %
                     (official.first_name, official.last_name),
                     profile_pic="%s/representative_images/225x275/"
                     "%s.jpg" % (settings.LONG_TERM_STATIC_DOMAIN,
                                 official.bioguideid)).save()
                 official.quest.connect(quest)
             duplicate_query = 'MATCH (a:PublicOfficial ' \
                               '{object_uuid:"%s"})-' \
                               '[:IS_HOLDING]->(q:Quest) ' \
                               'WHERE NOT q.owner_username="******" RETURN q' % \
                               (official.object_uuid, official.object_uuid)
             new_res, _ = db.cypher_query(duplicate_query)
             duplicate_quests = [
                 Quest.inflate(duplicate[0]) for duplicate in new_res
                 if duplicate[0] is not None
             ]
             if duplicate_quests:
                 skip = 0
                 for dup in duplicate_quests:
                     relationship_query = 'MATCH (a:Quest ' \
                                          '{object_uuid:"%s"})-[r]-' \
                                          '(p:Pleb) RETURN ' \
                                          'p.username as username, ' \
                                          'type(r) as type' \
                                          % dup.object_uuid
                     rel_res, _ = db.cypher_query(relationship_query)
                     if rel_res.one:
                         for row in rel_res:
                             try:
                                 re_query = 'MATCH (a:Quest ' \
                                            '{owner_username:"******"}), ' \
                                            '(p:Pleb {username:"******"}) ' \
                                            'CREATE UNIQUE (p)-[r:%s]->(a)' \
                                            % (official.object_uuid,
                                               row.username, row.type)
                                 db.cypher_query(re_query)
                             except ConstraintViolation:
                                 # handle potential constraint violations
                                 pass
                     query = 'MATCH (a:Quest {object_uuid: "%s"}) ' \
                             'OPTIONAL MATCH (a)-[r]-() ' \
                             'DELETE a, r' % dup.object_uuid
                     db.cypher_query(query)
     cache.set("removed_duplicate_quests", True)
Ejemplo n.º 22
0
 def get(self, request, username=None):
     from sb_missions.neo_models import Mission
     from sb_missions.serializers import MissionSerializer
     from sb_missions.utils import order_tasks
     query = 'MATCH (person:Pleb {username: "******"})' \
         '-[r:IS_WAGING]->(quest:Quest) WITH quest ' \
         'OPTIONAL MATCH (quest)-[:EMBARKS_ON]->(missions:Mission) ' \
         'RETURN quest, missions ORDER BY missions.created DESC' % (
             request.user.username)
     try:
         res, _ = db.cypher_query(query)
         if res.one is None:
             return redirect("404_Error")
     except (CypherException, ClientError):
         return redirect("500_Error")
     res.one.quest.pull()
     quest_obj = Quest.inflate(res.one.quest)
     quest_ser = QuestSerializer(quest_obj, context={
         'request': request
     }).data
     quest_ser['account_type'] = quest_obj.account_type
     if res.one.missions is None:
         mission_link = reverse('select_mission')
         mission_active = False
         onboarding_sort = []
         mission_obj = None
         onboarding_done = 0
     else:
         mission_obj = Mission.inflate(res[0].missions)
         mission_link = reverse('mission_settings',
                                kwargs={
                                    "object_uuid":
                                    mission_obj.object_uuid,
                                    "slug":
                                    slugify(mission_obj.get_mission_title())
                                })
         mission_active = mission_obj.active
         onboarding_sort, completed_count = order_tasks(
             mission_obj.object_uuid)
         onboarding_done = int(
             (float(completed_count) / float(len(onboarding_sort))) * 100)
     res, _ = db.cypher_query('MATCH (a:Quest {owner_username: "******"})'
                              '-[:LOCATED_AT]->(b:Address) '
                              'RETURN b' % quest_obj.owner_username)
     if res.one is not None:
         address = Address.inflate(res.one)
     else:
         address = None
     if self.template_name == "manage/quest_banking.html" \
             and address is None:
         return redirect('account_setup')
     if self.template_name == "manage/quest_settings.html":
         return redirect('general_settings')
     return render(
         request, self.template_name, {
             "quest":
             quest_ser,
             "mission_link":
             mission_link,
             "mission_active":
             mission_active,
             "mission":
             MissionSerializer(mission_obj, context={
                 "request": request
             }).data,
             "address":
             address,
             "onboarding_top_3":
             onboarding_sort[:3],
             "onboarding_rest":
             onboarding_sort[3:],
             "onboarding_done":
             onboarding_done
         })