<commit_before>from py2neo import neo4j
from participantManager import _get_participant_node, _getIfContactRelationshipExists
from utils import getGraph, save_file
from flask import jsonify, render_template
import json, uuid
from datetime import datetime,date
from math import log

# class Idea:
#     def __init__(self, idea_dict):
#         self.concern = idea_dict['concern']
#         self.proposal = idea_dict['proposal']
#         self.image_url = idea_dict['image_url']
#         self.timestamp = idea_dict['timestamp']
#         self.moreinfo = idea_dict['moreinfo']
#         self.supporters_goal_num = idea_dict['supporters_goal_num']
#         self.volunteers_goal_num = idea_dict['volunteers_goal_num']


# Used By < add_idea_to_user >
def add_idea_to_user_aux(user_email, idea_dict):
    user = _get_participant_node(user_email)
    newidea_index = idea_dict.get('proposal')
    code_uuid = str(uuid.uuid4())
    image = idea_dict.get('image')
    if _getIdeaByIdeaIndex(newidea_index):
        return jsonify({"result": "Wrong", "result_msg": "proposal already exists"})
    timestamp = (datetime.now()).strftime("%d.%m.%Y %H:%M:%S")
    newidea, = getGraph().create({"concern": idea_dict.get('concern'), "proposal": idea_dict.get('proposal'),
                                  "image": image, "uuid": code_uuid,
                                  "moreinfo_concern": idea_dict.get('moreinfo_concern'),
                                  "moreinfo_proposal": idea_dict.get('moreinfo_proposal'),
                                  "supporters_goal_num": idea_dict.get('supporters_goal_num'),
                                  "volunteers_goal_num": idea_dict.get('volunteers_goal_num'),
                                  "if_author_public": idea_dict.get('if_author_public')})
    newidea.add_labels("idea")
    _addIdeaToIndex(newidea_index, newidea)
    getGraph().create((user, "CREATED", newidea, {"timestamp": timestamp}))
    # first receivers
    first_receivers = map(_get_participant_node, idea_dict.get('first_receivers_emails'))
    for participant in first_receivers:
        getGraph().create((newidea, "GOES_FIRST_TO", participant))
    #
    return jsonify({"result":"OK", "result_msg":"added idea to database"})


# Used By < modify_idea >
def modify_idea_aux(idea_dict):
    idea_index = idea_dict['current_proposal']
    idea = _getIdeaByIdeaIndex(idea_index)
    fields = ['concern','proposal','moreinfo_concern','moreinfo_proposal',
              'supporters_goal_num','volunteers_goal_num', 'image', 'if_author_public']
    data= {}
    if 'proposal' in idea_dict:
        idea_index = idea_dict['proposal']
        if _getIdeaByIdeaIndex(idea_index):
            return jsonify({"result":"Wrong", "result_msg": "Proposal already exists"})
        _removeFromIdeaIndex(idea_dict['current_proposal'], idea)
        _addIdeaToIndex(idea_dict['proposal'], idea)
        _do_tasks_for_idea_editedproposal(idea_index)
    for k,v in idea_dict.items():
        if k in fields:
            data[k]=v
    for k,v in data.items():
        idea[k]=v
    return jsonify({"result":"OK", "result_msg":"Idea was modified"})


# <Used by do_cron_tasks_aux>, <redflag_idea_aux>
def remove_idea_aux(idea_index) :
    idea = _getIdeaByIdeaIndex(idea_index)
    for rel in getGraph().match(start_node=idea, bidirectional=True):
        rel.delete()
    idea.delete()
    return jsonify({"result":"OK", "result_msg":"Idea was removed"})

def get_ideas_created_by_participant_aux(participant_email, user_email):
    user = _get_participant_node(user_email)
    participant = _get_participant_node(participant_email)
    ifpublicprofile = participant['ifpublicprofile']
    if user_email == participant_email or _getIfContactRelationshipExists(participant, user) is True \
            or ifpublicprofile is True:
        ifallowed = True
        response = _get_ideas_created_by_participant(participant_email)
        response['ifallowed'] = ifallowed
        return jsonify(response)
    else:
        ifallowed = False
    return jsonify({"result": "OK", "ifallowed": ifallowed})


def get_ideas_data_created_by_participant_aux(participant_email, user_email):
    user = _get_participant_node(user_email)
    participant = _get_participant_node(participant_email)
    ifpublicprofile = participant.get_properties()['ifpublicprofile']
    ideas_data = []
    if user_email == participant_email or _getIfContactRelationshipExists(participant, user) is True \
            or ifpublicprofile is True:
        ifallowed = True
        rels = list(getGraph().match(start_node=participant, rel_type="CREATED"))
        for rel in rels:
            idea_data = _get_idea_data(rel.end_node)
            ideas_data.append(idea_data)
    else:
        ifallowed = False
    return jsonify({'result': 'OK',"ifallowed": ifallowed,'ideas_data': ideas_data})


def get_vote_statistics_for_idea_aux(idea_index):
    return _get_vote_statistics_for_idea(idea_index)


def _get_supporters_emails_for_idea_aux(idea_index):
    idea=_getIdeaByIdeaIndex(idea_index)
    supporters_emails = []
    vote_rels = list(getGraph().match(end_node=idea, rel_type="VOTED_ON"))
    support_rels = [x for x in vote_rels if x["type"] == "supported"]
    supporters = [x.start_node for x in support_rels]
    for supporter in supporters:
        supporters_emails.append(supporter['email'])
    return supporters_emails


def _get_volunteers_emails_for_idea_aux(idea_index):
    idea=_getIdeaByIdeaIndex(idea_index)
    volunteers_emails = []
    vote_rels = list(getGraph().match(end_node=idea, rel_type="VOTED_ON"))
    volunteer_rels = [x for x in vote_rels if x["ifvolunteered"] == True]
    volunteers = [x.start_node for x in volunteer_rels]
    for volunteer in volunteers:
        volunteers_emails.append(volunteer['email'])
    return volunteers_emails


def get_voting_rel_between_user_and_idea_aux(user_email, idea_proposal):
    user = _get_participant_node(user_email)
    idea = _getIdeaByIdeaIndex(idea_proposal)
    if _if_voting_relationship_exists(user,idea):
        voting_rel = getGraph().match_one(start_node=user, rel_type="VOTED_ON", end_node=idea)
        vote_type= voting_rel["type"]
        vote_ifvolunteered = voting_rel["ifvolunteered"]
        return jsonify({"result": "OK", "vote_type":vote_type, "vote_ifvolunteered":vote_ifvolunteered})
    else:
        return jsonify({"result": "Wrong", "result_msg":"Voting relationship does not exist"})


def vote_on_idea_aux(user_email, inputdict):
    from app import SUPPORT_RATE_MIN
    user = _get_participant_node(user_email)
    idea_index=inputdict['idea_proposal']
    idea = _getIdeaByIdeaIndex(idea_index)
    vote_type=inputdict['vote_type']
    vote_ifvolunteered=inputdict['vote_ifvolunteered']
    vote_timestamp=(datetime.now()).strftime("%d.%m.%Y %H:%M:%S")
    previous_supporters_num= _get_vote_statistics_for_idea(idea_index)[0]
    previous_rejectors_num = _get_vote_statistics_for_idea(idea_index)[1]
    previous_activevoters_num = previous_supporters_num + previous_rejectors_num
    # previous support rate
    if previous_activevoters_num == 0:
        previous_support_rate = 100
    else:
        previous_support_rate = (previous_supporters_num / previous_activevoters_num)*100
    if previous_support_rate < SUPPORT_RATE_MIN:
        if_previous_support_rate_OK = False
    else:
        if_previous_support_rate_OK = True
    #
    if _if_voting_relationship_exists(user, idea):
        if _if_voting_relationship_exists_of_given_type(user, idea, vote_type, vote_ifvolunteered):
            return jsonify({"result": "Wrong: User vote exists of same type"})
    response = _create_or_modify_voting_relationship_to_given_type(user, idea, vote_type, vote_ifvolunteered, vote_timestamp)
    supporters_num = _get_vote_statistics_for_idea(idea_index)[0]
    rejectors_num =  _get_vote_statistics_for_idea(idea_index)[1]
    activevoters_num = supporters_num + rejectors_num
    volunteers_num = _get_vote_statistics_for_idea(idea_index)[3]
    support_rate = (supporters_num / activevoters_num)*100 if activevoters_num is not 0 else 100
    #time condition for failure warning notification: it should not be re-fired before three days from the previous one.
    if_time_condition_OK = False
    if 'if_failurewarning_timestamp' in idea:
        if_time_condition_OK = ((datetime.now() - idea['if_failurewarning_timestamp']).days >= 3)
    if support_rate < SUPPORT_RATE_MIN and if_previous_support_rate_OK is True and if_time_condition_OK is True:
        _do_tasks_for_idea_failurewarning(idea_index)
    if supporters_num >= (idea['supporters_goal_num']) and volunteers_num >= (idea['supporters_goal_num']):
        _do_tasks_for_idea_successful(idea_index)
    return response

def redflag_idea_aux(user_email, idea_index, reason):
    user = _get_participant_node(user_email)
    idea = _getIdeaByIdeaIndex(idea_index)
    if (_get_vote_statistics_for_idea(idea_index)[0]) > 0:
        _send_notification_emails_from_idea_to_supporters(idea_index, 'redflag', reason, user['fullname'])
    _send_notification_email_from_idea_to_author(idea_index, 'redflag', reason, user['fullname'])<commit_msg>after Alexis solved bug, restored functionality of failurewarning notification<commit_after>from py2neo import neo4j
from participantManager import _get_participant_node, _getIfContactRelationshipExists
from utils import getGraph, save_file
from flask import jsonify, render_template
import json, uuid
from datetime import datetime,date
from math import log

# class Idea:
#     def __init__(self, idea_dict):
#         self.concern = idea_dict['concern']
#         self.proposal = idea_dict['proposal']
#         self.image_url = idea_dict['image_url']
#         self.timestamp = idea_dict['timestamp']
#         self.moreinfo = idea_dict['moreinfo']
#         self.supporters_goal_num = idea_dict['supporters_goal_num']
#         self.volunteers_goal_num = idea_dict['volunteers_goal_num']


# Used By < add_idea_to_user >
def add_idea_to_user_aux(user_email, idea_dict):
    user = _get_participant_node(user_email)
    newidea_index = idea_dict.get('proposal')
    code_uuid = str(uuid.uuid4())
    image = idea_dict.get('image')
    if _getIdeaByIdeaIndex(newidea_index):
        return jsonify({"result": "Wrong", "result_msg": "proposal already exists"})
    timestamp = (datetime.now()).strftime("%d.%m.%Y %H:%M:%S")
    newidea, = getGraph().create({"concern": idea_dict.get('concern'), "proposal": idea_dict.get('proposal'),
                                  "image": image, "uuid": code_uuid,
                                  "moreinfo_concern": idea_dict.get('moreinfo_concern'),
                                  "moreinfo_proposal": idea_dict.get('moreinfo_proposal'),
                                  "supporters_goal_num": idea_dict.get('supporters_goal_num'),
                                  "volunteers_goal_num": idea_dict.get('volunteers_goal_num'),
                                  "if_author_public": idea_dict.get('if_author_public')})
    newidea.add_labels("idea")
    _addIdeaToIndex(newidea_index, newidea)
    getGraph().create((user, "CREATED", newidea, {"timestamp": timestamp}))
    # first receivers
    first_receivers = map(_get_participant_node, idea_dict.get('first_receivers_emails'))
    for participant in first_receivers:
        getGraph().create((newidea, "GOES_FIRST_TO", participant))
    #
    return jsonify({"result":"OK", "result_msg":"added idea to database"})


# Used By < modify_idea >
def modify_idea_aux(idea_dict):
    idea_index = idea_dict['current_proposal']
    idea = _getIdeaByIdeaIndex(idea_index)
    fields = ['concern','proposal','moreinfo_concern','moreinfo_proposal',
              'supporters_goal_num','volunteers_goal_num', 'image', 'if_author_public']
    data= {}
    if 'proposal' in idea_dict:
        idea_index = idea_dict['proposal']
        if _getIdeaByIdeaIndex(idea_index):
            return jsonify({"result":"Wrong", "result_msg": "Proposal already exists"})
        _removeFromIdeaIndex(idea_dict['current_proposal'], idea)
        _addIdeaToIndex(idea_dict['proposal'], idea)
        _do_tasks_for_idea_editedproposal(idea_index)
    for k,v in idea_dict.items():
        if k in fields:
            data[k]=v
    for k,v in data.items():
        idea[k]=v
    return jsonify({"result":"OK", "result_msg":"Idea was modified"})


# <Used by do_cron_tasks_aux>, <redflag_idea_aux>
def remove_idea_aux(idea_index) :
    idea = _getIdeaByIdeaIndex(idea_index)
    for rel in getGraph().match(start_node=idea, bidirectional=True):
        rel.delete()
    idea.delete()
    return jsonify({"result":"OK", "result_msg":"Idea was removed"})

def get_ideas_created_by_participant_aux(participant_email, user_email):
    user = _get_participant_node(user_email)
    participant = _get_participant_node(participant_email)
    ifpublicprofile = participant['ifpublicprofile']
    if user_email == participant_email or _getIfContactRelationshipExists(participant, user) is True \
            or ifpublicprofile is True:
        ifallowed = True
        response = _get_ideas_created_by_participant(participant_email)
        response['ifallowed'] = ifallowed
        return jsonify(response)
    else:
        ifallowed = False
    return jsonify({"result": "OK", "ifallowed": ifallowed})


def get_ideas_data_created_by_participant_aux(participant_email, user_email):
    user = _get_participant_node(user_email)
    participant = _get_participant_node(participant_email)
    ifpublicprofile = participant.get_properties()['ifpublicprofile']
    ideas_data = []
    if user_email == participant_email or _getIfContactRelationshipExists(participant, user) is True \
            or ifpublicprofile is True:
        ifallowed = True
        rels = list(getGraph().match(start_node=participant, rel_type="CREATED"))
        for rel in rels:
            idea_data = _get_idea_data(rel.end_node)
            ideas_data.append(idea_data)
    else:
        ifallowed = False
    return jsonify({'result': 'OK',"ifallowed": ifallowed,'ideas_data': ideas_data})


def get_vote_statistics_for_idea_aux(idea_index):
    return _get_vote_statistics_for_idea(idea_index)


def _get_supporters_emails_for_idea_aux(idea_index):
    idea=_getIdeaByIdeaIndex(idea_index)
    supporters_emails = []
    vote_rels = list(getGraph().match(end_node=idea, rel_type="VOTED_ON"))
    support_rels = [x for x in vote_rels if x["type"] == "supported"]
    supporters = [x.start_node for x in support_rels]
    for supporter in supporters:
        supporters_emails.append(supporter['email'])
    return supporters_emails


def _get_volunteers_emails_for_idea_aux(idea_index):
    idea=_getIdeaByIdeaIndex(idea_index)
    volunteers_emails = []
    vote_rels = list(getGraph().match(end_node=idea, rel_type="VOTED_ON"))
    volunteer_rels = [x for x in vote_rels if x["ifvolunteered"] == True]
    volunteers = [x.start_node for x in volunteer_rels]
    for volunteer in volunteers:
        volunteers_emails.append(volunteer['email'])
    return volunteers_emails


def get_voting_rel_between_user_and_idea_aux(user_email, idea_proposal):
    user = _get_participant_node(user_email)
    idea = _getIdeaByIdeaIndex(idea_proposal)
    if _if_voting_relationship_exists(user,idea):
        voting_rel = getGraph().match_one(start_node=user, rel_type="VOTED_ON", end_node=idea)
        vote_type= voting_rel["type"]
        vote_ifvolunteered = voting_rel["ifvolunteered"]
        return jsonify({"result": "OK", "vote_type":vote_type, "vote_ifvolunteered":vote_ifvolunteered})
    else:
        return jsonify({"result": "Wrong", "result_msg":"Voting relationship does not exist"})


def vote_on_idea_aux(user_email, inputdict):
    from app import SUPPORT_RATE_MIN
    user = _get_participant_node(user_email)
    idea_index=inputdict['idea_proposal']
    idea = _getIdeaByIdeaIndex(idea_index)
    vote_type=inputdict['vote_type']
    vote_ifvolunteered=inputdict['vote_ifvolunteered']
    vote_timestamp=(datetime.now()).strftime("%d.%m.%Y %H:%M:%S")
    previous_supporters_num= _get_vote_statistics_for_idea(idea_index)[0]
    previous_rejectors_num = _get_vote_statistics_for_idea(idea_index)[1]
    previous_activevoters_num = previous_supporters_num + previous_rejectors_num
    # previous support rate
    if previous_activevoters_num == 0:
        previous_support_rate = 100
    else:
        previous_support_rate = (previous_supporters_num / previous_activevoters_num)*100
    if previous_support_rate < SUPPORT_RATE_MIN:
        if_previous_support_rate_OK = False
    else:
        if_previous_support_rate_OK = True
    #
    if _if_voting_relationship_exists(user, idea):
        if _if_voting_relationship_exists_of_given_type(user, idea, vote_type, vote_ifvolunteered):
            return jsonify({"result": "Wrong: User vote exists of same type"})
    response = _create_or_modify_voting_relationship_to_given_type(user, idea, vote_type, vote_ifvolunteered, vote_timestamp)
    supporters_num = _get_vote_statistics_for_idea(idea_index)[0]
    rejectors_num =  _get_vote_statistics_for_idea(idea_index)[1]
    activevoters_num = supporters_num + rejectors_num
    volunteers_num = _get_vote_statistics_for_idea(idea_index)[3]
    support_rate = (supporters_num / activevoters_num)*100 if activevoters_num is not 0 else 100
    # failure warning notification
    if 'if_failurewarning_timestamp' in idea:
        # notification should not be re-fired before three days from the previous one.
        if_time_condition_for_failurewarning = ((datetime.now() - idea['if_failurewarning_timestamp']).days >= 3)
    else:
        if_time_condition_for_failurewarning = True
    if support_rate < SUPPORT_RATE_MIN and if_previous_support_rate_OK is True and if_time_condition_for_failurewarning is True:
        _do_tasks_for_idea_failurewarning(idea_index)
    # succesful idea notification
    if supporters_num >= (idea['supporters_goal_num']) and volunteers_num >= (idea['supporters_goal_num']):
        _do_tasks_for_idea_successful(idea_index)
    #
    return response

def redflag_idea_aux(user_email, idea_index, reason):
    user = _get_participant_node(user_email)
    idea = _getIdeaByIdeaIndex(idea_index)
    if (_get_vote_statistics_for_idea(idea_index)[0]) > 0:
        _send_notification_emails_from_idea_to_supporters(idea_index, 'redflag', reason, user['fullname'])
    _send_notification_email_from_idea_to_author(idea_index, 'redflag', reason, user['fullname'])
{'fraction_non_alphanumeric': 0.0999838039194515, 'fraction_numerical': 0.0026993467580845435, 'mean_word_length': 4.353757225433526, 'pattern_counts': {'":': 58, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '567079', 'n_tokens_mistral': 6127, 'n_tokens_neox': 5926, 'n_words': 1044}