def updateVolunteerTG(requestjson, tg_id, phone):
    update1 = {}
    print(requestjson)
    log.debug("Relay offer for req:%s from ", requestjson)
    for key, value in requestjson.items():
        if key == 'phone':
            continue
        if key == 'telegram_chat_id' and 'phone' not in requestjson:
            continue
        update1[f"set__{key}"] = value
    try:
        if 'phone' in requestjson:#conection between tg and platofrm
            obj = Volunteer.objects(telegram_id=str(requestjson['phone']).replace('+','')).first()
            update = {'set__telegram_chat_id':str(requestjson['telegram_chat_id'])}
        else:
            #get offer from the volunteer
            obj = Volunteer.objects(telegram_chat_id=str(requestjson['telegram_chat_id']), is_active=True).first()
            data = obj.clean_data()
            item = {'id':requestjson['offer_beneficiary_id'], 'offer':requestjson['availability_day']}
            update={'offer_list':data['offer_list']+[item]}
        if obj:
            #obj = [i for i in obj.all()][0]
            obj.update(**update)
        else:
            jsonify({"response": "not found"})
        return jsonify({"response": "success",'l':update,'k':requestjson,'u':update1})
    except Exception as error:
        return jsonify({"error": str(error)}), 400
def update_volunteer(volunteer_id, updates):
    """Updates a volunteer by ID.

    Parameters
    ----------
    volunteer_id : str
        A string representing volunteer ID.
    updates : dict
        A dictionary including name of fields as key and their values for updating.
    """
    try:
        Volunteer.objects(id=volunteer_id).get().update(**updates)
    except Exception as error:
        log.error("An error occurred on updating Volunteers. {}".format(error.message))
Beispiel #3
0
def send_assign(beneficiary_id, volunteer_id):
    """Sends a POST request to telegram bot api to assign a request to a volunteer
    :param beneficiary_id: str, Beneficiary ID for whom will be performed a request
    :param volunteer_id: Volunteer ID who is going to perform a request
    :return: if the response is success then will return a json as {"request_id": "5e88845adcc1e3b2786c311e",
            "volunteer": "123456789", "time": "00:00"}, otherwise - {"error": "error message"}
    """

    volunteer = Volunteer.objects(id=volunteer_id).get()
    if "telegram_chat_id" in volunteer:
        time_s = '20:20'
        data = volunteer.clean_data()
        for i in data['offer_list']:
            if i['id'] == beneficiary_id:
                time_s = i['offer']
        payload = {
            'request_id': beneficiary_id,
            'volunteer': int(volunteer['telegram_chat_id']),
            'time':
            time_s  # utc_short_to_user_short(time_s)#volunteer['availability_day']
        }
        log.info("ASSIGN req:%s to vol:%s", time_s,
                 volunteer['telegram_chat_id'])
        try:
            requests.post(f'{BASE_URL}/assign_help_request', json=payload)
            return payload
        except Exception as error:
            jsonify({"error": str(error)}), 400
def sort_closest(id, topk, category):
    topk = int(topk)
    user = Beneficiary.objects(id=id).get().clean_data()
    filters = {}
    #get active volunteer with same activity type, with availability>0 and not bussy with other requests
    if 'offer' in user and user['offer']!='':
        category = user['offer']
        volunteers = sorted([makejson(v.clean_data(), user) for v in Volunteer.objects(is_active=True, #availability__gt=0,
                                                                                                         offer=category).all()\
                               # if not Beneficiary.objects(volunteer=str(v.clean_data()['_id']),status__ne='done')
                                ], key=lambda x: x['distance'])
    else:
        volunteers = sorted([makejson(v.clean_data(), user) for v in Volunteer.objects(is_active=True, #availability__gt=0,
                                                                                                         activity_types__in=user['activity_types']).all()\
                            ], key=lambda x: x['distance'])
    volunteers = [i for i in volunteers if i['distance']<100000]
    #todo: find the best threshhold!!!

    if 'volunteer' in user and user['volunteer']!='':
        volunteers = [makejson(Volunteer.objects(id=user['volunteer']).get().clean_data(), user)] + [i for i in volunteers if i['_id'] != user['volunteer']]
    return jsonify({'list':volunteers[:topk]})
def updateVolunteer(requestjson, volunteer_id, delete=False):
        """update a single user by id"""
        print(volunteer_id, '---')
        update = {}
        if not delete:
            for key, value in requestjson.items():
                if key == '_id':
                    continue
                if key == "telegram_id":
                    value = value.replace('+','').replace(' ','').strip()
                    if len(value)==0:
                        update['unset__telegram_chat_id'] = ''
                if key == "password":
                    value = PassHash.hash(value)
                update[f"set__{key}"] = value
        else:
            update["set__is_active"] = False

        try:
            Volunteer.objects(id=volunteer_id).get().update(**update)
            return jsonify({"response": "success"})
        except Exception as error:
            return jsonify({"error": str(error)}), 400
def getVolunteers(filters):
        try:
            if len(filters.getlist('id')) == 1 :
                volunteer_id = filters.get('id')
                volunteer = Volunteer.objects(id=volunteer_id).get().clean_data()

                return jsonify(volunteer)
            elif len(filters.getlist("telegram_chat_id")) == 1:
                telegram_id = filters.get("telegram_chat_id")
                if len(Volunteer.objects(telegram_chat_id=telegram_id)) == 0:
                    return jsonify({"exists": False})
                else:
                    return jsonify({"exists": True})
            elif len(filters.getlist('id')) > 1:
                volunteers = [Volunteer.objects(id=volunteer_id).get().clean_data() for volunteer_id in filters.getlist('id')]
                return jsonify({"list": volunteers})
            else:
                volunteers = [v.clean_data() for v in Volunteer.objects(is_active=True).order_by('-created_at').all()]
                for i,volunteer in enumerate(volunteers):
                    volunteers[i]['cases_solved'] =  Beneficiary.objects(volunteer=volunteer['_id']).count()
                return jsonify({"list": volunteers})
        except Exception as error:
            return jsonify({"error": str(error)}), 400
def exists_by_email(email):
    """Checks, if a volunteer with the given email, already exists in the database.

    Parameters
    ----------
    email : str
        Given email for validating.

    Raises
    -------
    AssertionError
        If volunteer with given email already exists in database.
    """
    assert not Volunteer.objects(
        email=email), "User with this email already exists"
def get_volunteers_by_filters(filters, pages=0, per_page=10000):
    try:
        item_per_age = int(per_page)
        offset = (int(pages) - 1) * item_per_age
        if len(filters) > 0:
            flt = {}
            toBool = {'true':True, 'false': False}
            caseS = ['first_name', 'last_name']
            for v,k in filters.items():
                flt[v+'__iexact' if v in caseS else v] = toBool[k.lower()] if k.lower() in toBool else k

            obj = Volunteer.objects(**flt)
            volunteers = [v.clean_data() for v in obj.order_by('-created_at').skip(offset).limit(item_per_age)]
            for i,volunteer in enumerate(volunteers):
                    volunteers[i]['cases_solved'] =  Beneficiary.objects(volunteer=volunteer['_id']).count()
            return jsonify({"list": volunteers, 'count':obj.count()})
        else:
            obj = Volunteer.objects().order_by('-created_at')
            volunteers = [v.clean_data() for v in obj.skip(offset).limit(item_per_age)]
            for i,volunteer in enumerate(volunteers):
                    volunteers[i]['cases_solved'] =  Beneficiary.objects(volunteer=volunteer['_id']).count()
            return jsonify({"list": volunteers, 'count':obj.count()})
    except Exception as error:
        return jsonify({"error": str(error)}), 400
def exists_by_telegram_chat_id(telegram_chat_id):
    """Checks, if a volunteer with the given telegram chat ID, already exists in the database.

    Parameters
    ----------
    telegram_chat_id : int
        Given telegram chat ID for validating.

    Raises
    -------
    AssertionError
        If volunteer with given telegram chat ID already exists in database.
    """
    assert not Volunteer.objects(
        telegram_chat_id=telegram_chat_id
    ), "User with this telegram account already exists"
Beispiel #10
0
def send_cancel_request(beneficiary_id, volunteer_id):
    """Sends a POST request to telegram bot api to cancel the request to assist
    :param beneficiary_id: str, Beneficiary ID for whom is going to cancel a request
    :param volunteer_id: str, Volunteer's ID, who is going to be prevented about a request canceling
    :return: if the response is success then will return a json as {"request_id": "5e88845adcc1e3b2786c311e",
            "volunteer": "123456789"}, otherwise - {"error": "error message"}
    """
    volunteer = Volunteer.objects(id=volunteer_id).get()
    payload = {
        'request_id': beneficiary_id,
        'volunteer': volunteer['telegram_chat_id']
    }
    try:
        requests.post(f'{BASE_URL}/cancel_help_request', json=payload)
        return payload
    except Exception as error:
        return jsonify({"error": str(error)}), 400
def volunteer_build_csv():
    includelist = ['first_name', 'last_name', 'phone' ,  'address', 'zone_address', 'age', 
                   'offer', 'comments',  'urgent','curator','has_disabilities','black_list', 'received_contract']

    tag2v = {'offer':'offer', 'age':'age', 'zone_address':'sector'}

    si = io.StringIO()
    writer = csv.writer(si)
    volunteers = [v.include_data(includelist) for v in Volunteer.objects().all()]

    # write header
    writer.writerow(includelist)

    # write data
    for doc in volunteers:
        writer.writerow([boolconv(doc[k], k, tag2v) for k in doc])

    output = make_response(si.getvalue())
    output.headers["Content-type"] = "text/csv"
    output.headers["Content-Disposition"] = "attachment; filename=volunteer.csv"
    return output
def parseFile(json_url, begin, end, args):
    resp = requests.get(url=json_url)
    data = resp.json()

    cols = max([int(i['gs$cell']['col']) for i in data['feed']['entry']])
    rows = max([int(i['gs$cell']['row']) for i in data['feed']['entry']])
    df = [['' for i in range(cols)] for j in range(rows)]
    for i in data['feed']['entry']:
        col = int(i['gs$cell']['col'])
        row = int(i['gs$cell']['row'])
        #print(i['gs$cell'])
        df[row - 1][col - 1] = i['gs$cell']['inputValue']

    lb = [df[1][i] if df[0][i] == '' else df[0][i] for i in range(cols)]
    lb = [i[:15] for i in lb]

    rr = [{lb[i]: v for i, v in enumerate(j)} for j in df[2:]]
    ids = []
    begin = int(begin)
    end = int(end)
    for row in rr[begin:end]:  #add
        item = parseRow(row)
        #if args.get('legitimatie') is not None and item['received_contract']:
        item['is_active'] = True
        ob = Volunteer.objects(phone=item['phone']).first()
        if not ob:
            comment = Volunteer(**item)
            comment.save()
            ids.append(comment.clean_data()['_id'])
            #return jsonify(comment.clean_data()['_id'])
        elif 'latitude' in item:
            data = ob.clean_data()
            if 'latitude' not in data or data['latitude'] == '':
                ob.update(latitude=item['latitude'],
                          longitude=item['longitude'],
                          address=item['address'])

    return jsonify(ids)