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 add_volunteer_submission(): # adds a new volunteer with data from volunteer_form and redirects to # the dashboard form = VolunteerForm() if not form.validate_on_submit(): # if the form has errors, display error messages and resend the # current page flash('Task could not be created because one or more data fields' ' were invalid:') for field, message in form.errors.items(): flash(message[0]) return render_template('volunteer_form.html', form=form, title="Add a New Volunteer") # the form is valid name = request.form['name'] address = request.form['address'] city = request.form['city'] state = request.form['state'] zip_code = request.form['zip_code'] phone_number = request.form['phone_number'] new_volunteer = Volunteer(name, address, city, state, zip_code, phone_number) try: new_volunteer.insert() flash('Volunteer ' + name + ' was successfully added') except Exception as e: flash('An error occurred. The Volunteer could not be added') abort(422) return redirect('/dashboard')
def POST(self): web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Credentials', 'true') volunteerItem = simplejson.loads(web.data()) existingVolunteer = Volunteer.GetByEmail(volunteerItem['volunteer_email']) if (existingVolunteer): return "{ status: 'Error - Volunteer Exists'}" else: # not existing, create new database record newVolunteer = Volunteer( volunteer_name = volunteerItem['volunteer_name'], volunteer_email = volunteerItem['volunteer_email'], volunteer_phone = volunteerItem['volunteer_phone'], address_street = volunteerItem['address_street'], address_street2 = volunteerItem['address_street2'], address_city = volunteerItem['address_city'], address_state = volunteerItem['address_state'], address_zipcode = volunteerItem['address_zipcode'] ) newVolunteer.put() return "{ status: 'Success'}"
def post(self, post_code): v = simple_validate({'post_code': post_code}) if v['valid']: f = VolunteerForm(self.request.POST) if f.validate(): new_v = Volunteer( first_name=f.first_name.data, last_name=f.last_name.data, phone=f.phone.data, email=f.email.data, project=f.project.data, sitelocation=f.sitelocation.data, notes=f.notes.data, cos=f.cos.data, trainee_input="", ) new_v.put() new_kit = MedKit( date_issued=datetime.now(), in_use=True, delivery_events=[], volunteer=new_v, post_default=v["post_default"], ) new_kit.put() v['Volunteer'] = new_v v['MedKit'] = new_kit html = render.page(self, "templates/postadmin/confirmation.html", v) self.response.out.write(html) else: self.response.out.write( "invalid entry for one of the form items") else: render.not_found(self)
def POST(self): web.header('Content-Type', 'application/json') web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') volunteerItem = simplejson.loads(web.data()) existingVolunteer = Volunteer.GetByEmail(volunteerItem['volunteer_email']) if (existingVolunteer): return "{ status: 'Error - Volunteer Exists'}" else: # not existing, create new database record newVolunteer = Volunteer( volunteer_name = volunteerItem['volunteer_name'], volunteer_email = volunteerItem['volunteer_email'], volunteer_phone = volunteerItem['volunteer_phone'], address_street = volunteerItem['address_street'], address_street2 = volunteerItem['address_street2'], address_city = volunteerItem['address_city'], address_state = volunteerItem['address_state'], address_zipcode = volunteerItem['address_zipcode'] ) newVolunteer.put() return '{ "status": "Success"}'
def post(self, post_code): v = simple_validate({"post_code": post_code}) if v["valid"]: f = VolunteerForm(self.request.POST) if f.validate(): new_v = Volunteer( first_name=f.first_name.data, last_name=f.last_name.data, phone=f.phone.data, email=f.email.data, project=f.project.data, sitelocation=f.sitelocation.data, notes=f.notes.data, cos=f.cos.data, trainee_input="", ) new_v.put() new_kit = MedKit( date_issued=datetime.now(), in_use=True, delivery_events=[], volunteer=new_v, post_default=v["post_default"], ) new_kit.put() v["Volunteer"] = new_v v["MedKit"] = new_kit html = render.page(self, "templates/postadmin/confirmation.html", v) self.response.out.write(html) else: self.response.out.write("invalid entry for one of the form items") else: render.not_found(self)
def create_volunteer(): # creates a new volunteer and returns it to the api body = request.get_json() if not body: abort(400) name = body.get('name', None) address = body.get('address', None) city = body.get('city', None) state = body.get('state', None) zip_code = body.get('zip_code', None) phone_number = body.get('phone_number', None) # all fields are required if name and address and city and state and zip_code and phone_number: try: new_volunteer = Volunteer(name, address, city, state, zip_code, phone_number) new_volunteer.insert() return {'success': True, 'volunteer': new_volunteer.format()} except Exception: abort(422) else: # request did not contain one or more required fields abort(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))
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 insert_test_data(): all_objects = [] with open('test_data/volunteers.json', encoding='utf8') as volunteers_file: volunteers_data = json.load(volunteers_file) volunteers = [ Volunteer(id=int(id_), name=vol['name'], userpic=vol['userpic'], phone=vol['phone']) for id_, vol in volunteers_data.items() ] all_objects.extend(volunteers) with open('test_data/streets.json', encoding='utf8') as streets_file: streets_data = json.load(streets_file) streets = [ Street(id=int(id_), title=st['title'], volunteers=list(filter(lambda x: x.id in st['volunteer'], volunteers))) for id_, st in streets_data.items() ] all_objects.extend(streets) with open('test_data/districts.json', encoding='utf8') as districts_file: districts_data = json.load(districts_file) districts = [ District(id=int(id_), title=ds['title'], streets=list(filter(lambda x: x.id in ds['streets'], streets))) for id_, ds in districts_data.items() ] all_objects.extend(districts) db.session.add_all(all_objects) db.session.commit()
def ajax(request): if request.method == "POST": volunteer = Volunteer() volunteer.first_name = request.POST['first_name'] volunteer.save() volunteer_list = list(Volunteer.objects.all()) ajax_list = [] for item in volunteer_list: ajax_list.append({ "first_name": item.first_name, "last_name": item.last_name, "email": item.email, }) return HttpResponse(dumps(ajax_list), content_type="application/json")
def get(self): if not onTeam(): return self.redirect('/') user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return def formatter(person): JSON = {} key = getattr(person, 'key') JSON['id'] = key.urlsafe() JSON['kind'] = key.kind() JSON.update(person.asDict(['email', 'name', 'checked_in'])) return JSON from models import Volunteer, Rep source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch()) source += map(formatter, Rep.query(Rep.checked_in == False).fetch()) source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch()) total_checked_in = getTotal() session = models.CheckInSession() session.user = user.email() session.put() token = channel.create_channel(session.key.urlsafe()) self.response.write(template("checkin.html", {"source" : json.dumps(source), 'total_checked_in' : total_checked_in, 'token' : token}))
def add_volunteer(): email = request.form.get('email') volunteer = Volunteer(email) DB.session.add(volunteer) DB.session.commit() flash('Successfully added volunteer', 'success') return redirect(url_for('volunteer-list'))
def create_volunteer(userN,passW,zip,types,phoneN,address_): try: user = Volunteer(username=userN,password=passW,zipCode=zip,phone_number=phoneN,typesPref=types,address=address_) db.session.add(user) db.session.commit() db.session.remove() return {"Success":"Signup was Successful"} except: return {"Failure": "Signup Failed"}
def post_volunteer(payload): try: body = request.get_json() name = body['name'] email = body['email'] phone = body['phone'] except Exception as e: print(e) abort(400) try: volunteer = Volunteer(name=name, email=email, phone=phone) db.session.add(volunteer) db.session.commit() return jsonify({'success': True, 'volunteer': volunteer.format()}) except Exception as e: db.session.rollback() abort(422) finally: db.session.close()
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 create_volunteer(*args, **kwargs): """Creates a Volunteer. Returns: response: json, status_code """ try: body = request.get_json() volunteer = Volunteer( name=body.get('name'), phone_number=body.get('phone_number'), email=body.get('email'), event=body.get('event'), ) volunteer.insert() return jsonify({ 'success': True, 'volunteers': volunteer.format() }), 201 except Exception as e: app.logger.error(e) abort(422)
def register_volunteer(): try: body = request.get_json() volunteer = Volunteer(name=body['name'], age=util.compute_int(body['age']), gender=body.get('gender', 'NA'), email=body['email'], image_link=body.get('image_link', ''), profile_link=util.compute_profile_link(), seeking_student=util.compute_boolean( body['seeking_student']), seeking_description=body['seeking_description']) volunteer.insert() return jsonify({"success": True}), 200 except GenericException as e: raise e except Exception: raise APIException("Bad Request", 400)
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 register_volunteer(request_json, created_by): """Creates and persists a new volunteer into database. Parameters ---------- request_json : dict A dictionary representing the volunteer profile details. created_by : str A string representing either name of user who is going to create a new volunteer, or the token Returns ------- 200: If the volunteer was successful created and saved. 400: If the volunteer wasn't created or saved, and there was raised some exception. """ log.debug("Relay offer for req:%s from ", request_json) try: if not vu.is_email(created_by): user = Operator.verify_auth_token(created_by) created_by = user.get().clean_data()['email'] if created_by == os.getenv("COVID_BACKEND_USER"): vu.exists_by_telegram_chat_id(request_json["chat_id"]) new_volunteer_data = process_volunteer_data_from_telegram(request_json) else: vu.exists_by_email(request_json["email"]) new_volunteer_data = request_json new_volunteer_data["password"] = PassHash.hash(new_volunteer_data["password"]) new_volunteer_data['created_by'] = created_by new_volunteer = Volunteer(**new_volunteer_data) new_volunteer.save() return jsonify({"response": "success", 'user': new_volunteer.clean_data()}) except Exception as error: return jsonify({"error": str(error)}), 400
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_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 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"
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 get(self): if not onTeam(): return self.redirect('/') user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return def formatter(person): JSON = {} key = getattr(person, 'key') JSON['id'] = key.urlsafe() JSON['kind'] = key.kind() JSON.update(person.asDict(['email', 'name', 'checked_in'])) return JSON from models import Volunteer, Rep source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch()) source += map(formatter, Rep.query(Rep.checked_in == False).fetch()) source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch()) total_checked_in = getTotal() session = models.CheckInSession() session.user = user.email() session.put() token = channel.create_channel(session.key.urlsafe()) self.response.write( template( "checkin.html", { "source": json.dumps(source), 'total_checked_in': total_checked_in, 'token': token }))
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)
def getTotalFromDB(): from models import Volunteer, Rep total_checked_in = Hacker.query(Hacker.checked_in == True).count() total_checked_in += Rep.query(Rep.checked_in == True).count() total_checked_in += Volunteer.query(Volunteer.checked_in == True).count() return total_checked_in
def __init__(self, user, factory=None): if not factory: self.factory = Volunteer.Factory() super(Controller, self).__init__(user, factory)
def put(event, context): """Lambda facade for Volunteer.Controller.update method""" controller = _get_controller(event, context) obj = controller.update(event['data']) VolunteerModel.Persister().save(obj) return obj.to_dict()
def getUnconfirmedVolunteers(self, query): """Returns a list of unconfirmed volunteers.""" query = Volunteer.query(Volunteer.confirmed == False) return query
def getConfirmedVolunteers(self, query): """Returns a list of confirmed volunteers.""" query = Volunteer.query(Volunteer.confirmed == True) return query
def signup(request, pk): do_coordinator = False if is_coordinator(request.user) : template_name='signup/signup-coordinator.html' form = SignupFormCoordinator do_coordinator = True else: template_name='signup/signup.html' form = SignupFormUser job = Job.objects.get(pk=pk) if job == None : raise Http404("Job does not exist") # TODO: Check perimssions if request.method=='POST': form = form(request.POST) if form.is_valid() : try: with transaction.atomic() : signup_user = request.user if do_coordinator : # Check if the form has another user's email in it. other_user = form.cleaned_data.get('email', None) if other_user is not None and other_user != u'': for user in User.objects.filter(email__exact=other_user) : signup_user = user break # Create a Volunteer with form data # We need the natural key from the job... this way # if the job changes in a non-meaningful way this volunteer # continues to be valid. v = Volunteer( user = signup_user, comment = form.cleaned_data['comment'], source = job.source.pk, title = job.title, start = job.start, end = job.end, ) # NB: This feature requires discussion: Doing this will make it # impossible for people to sign up their friends for shifts. # # Before we commit this to the database let's check to see if the # user is already signed up for a shift at this time... #shifts = Volunteer.objects.filter(user__exact=request.user) #for s in shifts : # if s.start == v.start \ # or ( v.start < s.start and s.end < v.end ) \ # or ( v.start > s.start and v.start < s.end ) : # raise ValueError("Overlap!") # Now add the row, so the count query works... v.save() # Now check if there are too many volunteers. This has to # be done atomically. If we're overbooked, rollback. volcount = Volunteer.objects.filter(source__exact=job.source.pk, title__exact=job.title, start__exact=job.start).count() if volcount > job.needs : raise IntegrityError("f**k! nabbed!") except IntegrityError: return HttpResponse('Oh no! This signup was nabbed!', status=450) except ValueError: return HttpResponse('Wait a second!', status=451) return redirect('jobs', job.source.pk) else: return render(request, template_name, {'form':form, 'ret':job.source.pk, 'job':job}) else: form = form() return render(request, template_name, {'form':form, 'ret':job.source.pk, 'job':job})
artist = Artist(name="Justin Beiberlake", phone_number='555-555-5556', email='*****@*****.**', event=1, website='https://www.youtube.com/watch?v=dQw4w9WgXcQ', instagram_link='https://www.facebook.com/joeexotic', image_link="https://images.unsplash.com/photo-14") artist2 = Artist(name="Gnarfunkel", phone_number='555-555-5557', email='*****@*****.**', event=1, website='https://www.youtube.com/watch?v=dQw4w9WgXcQ', instagram_link='https://www.facebook.com/joeexotic', image_link="https://images.unsplash.com/photo-15") volunteer = Volunteer(name="Tyler", phone_number='555-555-5558', email='*****@*****.**', event=1) volunteer2 = Volunteer(name="Annie", phone_number='555-555-5559', email='*****@*****.**', event=1) add_list = [volunteer, volunteer2, artist, artist2] [db.session.add(item) for item in add_list] db.session.commit() db.session.close()