Exemple #1
0
    def test_too_close_to_another_article_title(self):
        test_file = settings.PROJECT_DIR + \
            "/sb_news/tests/sample_json/" \
            "too_close_to_another_article_title.json"
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        self.assertEqual(len(NewsArticle.nodes.all()), 2)

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "862248ce467c25d9fa20d66e43f13d7f0800882b"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)
        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "682408ea92f61d5a44de67ed2aaef7369c401bce"}) ' \
                'RETURN a'

        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)
Exemple #2
0
    def test_unique_uuid(self):
        test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                           "uuid_unique.json"
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        self.assertEqual(len(NewsArticle.nodes.all()), 2)

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "862248ce467c25d9fa20d66e43f13d7f0800882b"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)
        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c11407c888ddbfedca4a56b1aac482d153ad6039"}) ' \
                'RETURN a'

        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)
Exemple #3
0
    def test_title_unique(self):
        test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                           "title_unique.json"
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        query = 'MATCH (a:NewsArticle {title: ' \
                '"Sanders\' American Dream Is In Denmark"}) RETURN a'
        res, _ = db.cypher_query(query)
        self.assertEqual(len(res), 1)
        query = 'MATCH (a:NewsArticle {title: ' \
                '"ISIS Inc: How Oil Fuels The Jihadi Terrorists - ' \
                'ft.com"}) RETURN a'
        res, _ = db.cypher_query(query)
        self.assertEqual(len(res), 1)
        query = 'MATCH (a:NewsArticle {title: ' \
                '"Breaking: Donald Trump Stuns With ' \
                'Announcement Of Foreign Policy Dream Team"}) RETURN a'

        res, _ = db.cypher_query(query)
        self.assertEqual(len(res), 1)
Exemple #4
0
    def test_too_close_to_another_article_content(self):
        test_file = settings.PROJECT_DIR + \
            "/sb_news/tests/sample_json/" \
            "too_close_to_another_article_content.json"
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        self.assertEqual(len(NewsArticle.nodes.all()), 2)

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "188ed9cfc6e2214c067ad8e46ec6cd10e392646e"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c11407c888ddbfedca4a56b1aac482d153ad6039"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c11407c888ddbfedca4a56b1aac482d153ad6039"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertIsNotNone(res.one)
Exemple #5
0
    def create(self, validated_data):
        request = self.context["request"]
        # Note that DRF requires us to use the source as the key here but
        # tags prior to serializing
        mission = None
        tags = validated_data.pop('get_tags', [])
        owner = Pleb.get(request.user.username)
        mission_id = validated_data.get('mission', '')
        if mission_id:
            mission = Mission.get(mission_id)
        validated_data['owner_username'] = owner.username
        uuid = str(uuid1())
        validated_data['content'] = render_content(
            validated_data.get('content', ""))
        url = reverse('question_detail_page',
                      kwargs={
                          'question_uuid': uuid,
                          "slug": slugify(validated_data['title'])
                      },
                      request=request)
        href = reverse('question-detail',
                       kwargs={'object_uuid': uuid},
                       request=request)
        soup = BeautifulSoup(validated_data['content'], "lxml").get_text()
        question = Question(url=url,
                            href=href,
                            object_uuid=uuid,
                            summary=smart_truncate(soup),
                            **validated_data).save()
        question.owned_by.connect(owner)
        if mission is not None:
            mission.associated_with.connect(question)
        for tag in tags:
            query = 'MATCH (t:Tag {name:"%s"}) WHERE NOT t:AutoTag ' \
                    'RETURN t' % slugify(tag)
            res, _ = db.cypher_query(query)
            if not res.one:
                if (request.user.username == "devon_bleibtrey"
                        or request.user.username == "tyler_wiersing"
                        or owner.reputation >= 1250):
                    tag_obj = Tag(name=slugify(tag)).save()
                    question.tags.connect(tag_obj)
                else:
                    continue
            else:
                tag_obj = Tag.inflate(res.one)
                question.tags.connect(tag_obj)

        spawn_task(task_func=update_tags, task_param={"tags": tags})
        if validated_data.get('external_location_id', None) is not None:
            spawn_task(
                task_func=create_location_tree,
                task_param={"external_id": question.external_location_id})
        spawn_task(task_func=add_auto_tags_to_question_task,
                   task_param={"object_uuid": question.object_uuid})
        spawn_task(task_func=create_question_summary_task,
                   task_param={'object_uuid': question.object_uuid})
        question.refresh()
        cache.set(question.object_uuid, question)
        return question
Exemple #6
0
 def setUp(self):
     self.unit_under_test_name = 'pleb'
     self.email = "*****@*****.**"
     self.email = "*****@*****.**"
     self.email2 = "*****@*****.**"
     self.pleb = create_user_util_test(self.email)
     self.user = User.objects.get(email=self.email)
     self.pleb2 = create_user_util_test(self.email2)
     self.user2 = User.objects.get(email=self.email2)
     self.title = str(uuid1())
     self.question = Question(content="Hey I'm a question",
                              title=self.title,
                              owner_username=self.pleb.username).save()
     self.solution = Solution(content="This is a test solution",
                              owner_username=self.pleb.username,
                              parent_id=self.question.object_uuid).save()
     self.solution.owned_by.connect(self.pleb)
     self.question.owned_by.connect(self.pleb)
     try:
         Tag.nodes.get(name='taxes')
     except DoesNotExist:
         Tag(name='taxes').save()
     try:
         Tag.nodes.get(name='fiscal')
     except DoesNotExist:
         Tag(name='fiscal').save()
     try:
         Tag.nodes.get(name='environment')
     except DoesNotExist:
         Tag(name='environment').save()
 def populate_base_tags(self):
     es = Elasticsearch(settings.ELASTIC_SEARCH_HOST)
     with open(
             '%s/sb_tags/management/commands'
             '/initial_tags.json' % settings.PROJECT_DIR, 'r') as data_file:
         data = loads(data_file.read())
         for tag in data['tags']:
             try:
                 tag_node = Tag.nodes.get(name=slugify(tag['name']))
             except (Tag.DoesNotExist, DoesNotExist):
                 tag_node = Tag(name=slugify(tag['name']), base=True).save()
             except (CypherException, IOError):
                 logger.exception(
                     dumps({
                         "detail":
                         "Cypher exception, "
                         "failed to create "
                         "tag %s" % tag['name']
                     }))
                 continue
             es.index(index="tags",
                      doc_type="tag",
                      body={"name": tag['name']})
             for sub_tag in tag['sub_tags']:
                 try:
                     sub_tag_node = Tag.nodes.get(name=slugify(sub_tag))
                 except (Tag.DoesNotExist, DoesNotExist):
                     sub_tag_node = Tag(name=slugify(sub_tag),
                                        base=False).save()
                 except (CypherException, IOError):
                     logger.exception(
                         dumps({
                             "detail":
                             "Cypher exception, "
                             "failed to create tag "
                             "%s" % tag['name']
                         }))
                     continue
                 es.index(index='tags',
                          doc_type='tag',
                          body={"name": sub_tag})
                 try:
                     rel = tag_node.frequently_tagged_with.connect(
                         sub_tag_node)
                     rel.in_sphere = True
                     rel.save()
                     rel = sub_tag_node.frequently_tagged_with.connect(
                         tag_node)
                     rel.in_sphere = True
                     rel.save()
                 except (CypherException, IOError):
                     logger.exception(
                         dumps({
                             "detail":
                             "Cypher exception, failed to create "
                             "tag %s" % tag['name']
                         }))
                     continue
Exemple #8
0
    def test_find_tag_news_one_tag(self):
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'

        db.cypher_query(query)
        tag = Tag(name="science").save()
        res = find_tag_news.apply_async()
        tag.delete()
        self.assertTrue(res.result)
 def test_empty_get_multiple_tag_string(self):
     tag = Tag(name=str(uuid1())).save()
     tag2 = Tag(name=str(uuid1())).save()
     self.question.tags.connect(tag)
     self.question.tags.connect(tag2)
     res = self.question.get_tags_string()
     self.question.tags.disconnect(tag)
     self.question.tags.disconnect(tag2)
     self.assertIn(tag.name, res)
     self.assertIn(tag2.name, res)
     self.assertIn(',', res)
 def setUp(self):
     query = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() DELETE a, r'
     db.cypher_query(query)
     self.unit_under_test_name = 'pleb'
     self.email = "*****@*****.**"
     create_user_util_test(self.email)
     self.pleb = Pleb.nodes.get(email=self.email)
     self.user = User.objects.get(email=self.email)
     self.url = "http://testserver"
     self.tag = Tag(name='test_tag',
                    owner_username=self.pleb.username).save()
     self.base_tag = Tag(name='test_base_tag',
                         base=True,
                         owner_username=self.pleb.username).save()
Exemple #11
0
 def test_excluded_titles(self):
     test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                        "exclude_titles.json"
     query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
             'DELETE a, r'
     query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
              'DELETE a, r'
     query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
              'DELETE a, r'
     db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
     tag = Tag(name="science").save()
     results = gather_news_results(None, test_file)
     query_webhose(results, tag)
     tag.delete()
     self.assertEqual(len(NewsArticle.nodes.all()), 0)
Exemple #12
0
 def get_focused_on(self, request=None):
     from api.neo_models import SBObject
     from sb_quests.neo_models import Position
     from sb_quests.serializers import PositionSerializer
     from sb_tags.neo_models import Tag
     from sb_tags.serializers import TagSerializer
     from sb_questions.neo_models import Question
     from sb_questions.serializers import QuestionSerializerNeo
     query = 'MATCH (a:Mission {object_uuid: "%s"})-[:FOCUSED_ON]->(b)' \
             'RETURN b' % self.object_uuid
     res, _ = db.cypher_query(query)
     if res.one:
         child_label = SBObject.inflate(res.one).get_child_label()
         if child_label == "Position":
             return PositionSerializer(Position.inflate(res.one),
                                       context={
                                           'request': request
                                       }).data
         elif child_label == "Tag":
             return TagSerializer(Tag.inflate(res.one),
                                  context={
                                      'request': request
                                  }).data
         elif child_label == "Question":
             return QuestionSerializerNeo(Question.inflate(res.one),
                                          context={
                                              'request': request
                                          }).data
     else:
         return None
Exemple #13
0
    def test_title_reformat(self):
        test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                           "title_reformat.json"
        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c7dd81cf775476d17fd9effe3a43d13d060eb2c8"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertEqual(
            res.one['title'], "Obama's Team Welcomes Castro "
            "& Cuba To America & To Receive "
            "Criticism: 'Wouldn't Disagree'..."
            "DNC; DNC: DNC. Dncabc DNC")
        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c294037cba0aad280b655614c5c776f1c5b453ce"}) ' \
                'RETURN a'

        res, _ = db.cypher_query(query)
        self.assertEqual(res.one['title'], "Friends Of Israel - "
                         "The New Yorker")

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c6dd81cf775476d17fd9effe3a43d13d060eb2c8"}) ' \
                'RETURN a'

        res, _ = db.cypher_query(query)
        self.assertEqual(
            res.one['title'], "What's This Another New "
            "US USA U.S. U.S.A. Title It's A "
            "Miracle...")

        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c8dd81cf775476d17fd9effe3a43d13d060eb2c8"}) ' \
                'RETURN a'

        res, _ = db.cypher_query(query)
        self.assertEqual(res.one['title'], "Yet Another Title! What Is This!")
Exemple #14
0
 def test_site_not_supported(self):
     test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                        "site_not_supported.json"
     query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
             'DELETE a, r'
     query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
              'DELETE a, r'
     query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
              'DELETE a, r'
     db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
     tag = Tag(name="science").save()
     results = gather_news_results(None, test_file)
     query_webhose(results, tag)
     tag.delete()
     query = 'MATCH (a:NewsArticle) RETURN a'
     res, _ = db.cypher_query(query)
     self.assertIsNone(res.one)
 def test_update_tags(self):
     query = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
             'DELETE a, r'
     db.cypher_query(query)
     econ_tag = Tag(name="economy").save()
     space_tag = Tag(name="space").save()
     res = update_tags.apply_async(
         kwargs={"tags": ["economy", "space"]})
     self.assertIsInstance(res.result, list)
     query = 'MATCH (a:Tag {object_uuid: "%s"}) RETURN a' % (
         econ_tag.object_uuid)
     res, _ = db.cypher_query(query)
     self.assertEqual(res.one['tag_used'], 1)
     query = 'MATCH (a:Tag {object_uuid: "%s"}) RETURN a' % (
         space_tag.object_uuid)
     res, _ = db.cypher_query(query)
     self.assertEqual(res.one['tag_used'], 1)
 def test_list_non_url_friendly(self):
     name = ' 112@#$%^&*()_+~`1234567890-=[]\{}|;:",./<>?qwer  lsls., '
     tag2 = Tag(name=slugify(name),
                owner_username=self.pleb.username).save()
     self.client.force_authenticate(user=self.user)
     url = reverse('tag-detail', kwargs={"name": slugify(tag2.name)})
     response = self.client.get(url)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data['name'], slugify(name))
Exemple #17
0
    def test_quote_query(self):
        test_file = settings.PROJECT_DIR + "/sb_news/tests/sample_json/" \
                                           "quote_query.json"

        query = 'MATCH (a:NewsArticle) OPTIONAL MATCH (a)-[r]-() ' \
                'DELETE a, r'
        query2 = 'MATCH (a:Tag) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        query3 = 'MATCH (a:UploadedObject) OPTIONAL MATCH (a)-[r]-() ' \
                 'DELETE a, r'
        db.cypher_batch_query([(query, {}), (query2, {}), (query3, {})])
        tag = Tag(name="science").save()
        results = gather_news_results(None, test_file)
        query_webhose(results, tag)
        tag.delete()
        query = 'MATCH (a:NewsArticle ' \
                '{external_id: "c8a3179934b6d4609632383add7fb27ddf3d3842"}) ' \
                'RETURN a'
        res, _ = db.cypher_query(query)
        self.assertEqual(
            res.one['title'], "Breaking: Donald Trump Stuns "
            "With Announcement Of Foreign "
            "Policy Dream Team")
Exemple #18
0
 def create(self, validated_data):
     from sb_tags.neo_models import Tag
     from sb_tags.serializers import TagSerializer
     request, _, _, _, _ = gather_request_data(self.context)
     generated_tags = []
     if request is None:
         raise serializers.ValidationError(
             "Must perform creation from web request")
     for tag in validated_data['interests']:
         try:
             query = 'MATCH (profile:Pleb {username: "******"}), ' \
                     '(tag:Tag {name: "%s"}) ' \
                     'CREATE UNIQUE (profile)-[:INTERESTED_IN]->(tag) ' \
                     'RETURN tag' % (request.user.username, slugify(tag))
             res, _ = db.cypher_query(query)
             generated_tags.append(TagSerializer(Tag.inflate(res.one)).data)
         except(ConstraintViolation, Exception):
             pass
     cache.delete(request.user.username)
     return generated_tags
Exemple #19
0
def limit_offset_query(skip, limit):
    query = 'MATCH (tag:Tag) WHERE NOT tag:AutoTag ' \
            'RETURN tag SKIP %s LIMIT %s' % (skip, limit)
    res, _ = db.cypher_query(query)
    return [Tag.inflate(row[0]) for row in res]
 def test_empty_get_one_tag_string(self):
     tag = Tag(name=str(uuid1())).save()
     self.question.tags.connect(tag)
     res = self.question.get_tags_string()
     self.question.tags.disconnect(tag)
     self.assertEqual(res, "%s" % tag.name)
Exemple #21
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
Exemple #22
0
 def test_get_focus_on_tag(self):
     tag = Tag(name=str(uuid1())).save()
     self.mission.tag.connect(tag)
     res = self.mission.get_focused_on()
     self.assertIn(tag.object_uuid, res['id'])