def _create_client(): if request.method == 'GET': try: clients = services.get_clients() except NoResultFound: abort(404) resp = jsonify({'clients': clients}) resp.headers['Location'] = 'localhost:5000/clients' resp.status_code = 200 return resp elif request.method == 'POST': client = models.Client() name = request.form['name'] nickname = request.form['nickname'] email = request.form['email'] home = request.form['home'] mobile = request.form['mobile'] work = request.form['work'] result = services.create_client(name=name, nickname=nickname, email=email, home=home, mobile=mobile, work=work) resp = jsonify({'client': result.data}) resp.status_code = 200 resp.headers['Location'] = '/cah/api/v1.0/clients/{0}'.format(result.id) resp.autocorrect_location_header = False return resp
def post(self): args = self.reqparse.parse_args() client_id = models.Client.query.with_entities( models.Client.id).filter_by(name=args['name']).scalar() if client_id is not None: abort(400, 'Client already exists') client = models.Client(name=args['name']) db.session.add(client) db.session.commit() return {'client': marshal(client, client_fields)}, 201
def create_database(): agent = models.Agent(username="******", name="Bartosz", surname="Krol", password="******") number = models.TwilioNumber(number="+441414960198") client = models.Client(name="Bartosz", surname="Krol", email="*****@*****.**", phone="+447700900685") agent.clients.append(client) models.add(agent) models.add(number) models.commit()
def populate(): print "Populating Database with Fake Data" agent = models.Agent(username="******", name="John", surname="Dee", password="******") number = models.TwilioNumber(number="+441458570066") client = models.Client(name="Tony", surname="Stark", email="*****@*****.**", phone="+443069990650") agent.clients.append(client) client = models.Client(name="Bruce", surname="Wayne", email="*****@*****.**", phone="+443069990884") agent.clients.append(client) client = models.Client(name="Hermione", surname="Granger", email="*****@*****.**", phone="+443069990642") agent.clients.append(client) models.add(agent) models.add(number) models.commit()
def create_database(): agent = models.Agent(username="******", name="Bruce", surname="Wayne", password="******") number = models.TwilioNumber(number="+442079460083") client = models.Client(name="Bruce", surname="Banner", email="*****@*****.**", phone="+441914980954") agent.clients.append(client) models.add(agent) models.add(number) models.commit()
def create_client(name, nickname, email, home, mobile=None, work=None): client = models.Client() client.name = name client.nickname = nickname client.email = email client.home_phone = home client.work_phone = work client.mobile_phone = mobile db.session.add(client) db.session.commit() client_schema = models.ClientSchema() client_tuple = collections.namedtuple('ClientData', ['id', 'data']) result = client_tuple(id=client.id, data=client_schema.dump(client).data) return result
async def create_client( # current_user: models.Client = Depends(oauth2.get_current_user), username: str = Form(...), password: str = Form(...), db: Session = Depends(database.get_db), ): logger.debug({"username": username}) try: input_data = sch.ClientSchema(username=username, password=password) except sch.ValidationError as e: raise utils.ValidationException(e) hashed_password = hashing.bcrypt(input_data.password) client_id = str(uuid.uuid4()) client_secret = shortuuid.ShortUUID().random(length=30) data = { "client_id": client_id, "client_secret": client_secret, } client_data = models.Client( username=username, hashed_password=hashed_password, client_id=client_id, client_secret=client_secret, ) db.add(client_data) db.commit() db.refresh(client_data) return JSONResponse({"data": data, "status": "success"}, status_code=200)
def getItinerary(): """Calculate the intinerary and present it to the TA Args: startDate: start date of the trip endDate: end date of the trip presenceOfKids: boolean that indicates the presence of kids needsFreeTime: boolean that indicates the need for free time exclude: list of locations to be excluded include: list of locations to be included existingClient: identifier of the customer (if is a new customer, this equals zero) clientName: name of the client clientAge: age of the client clientQuiet: the preference of the client towards quiet environment preferenceShopping: preference towards shopping activities, in a range from 1 to 5 preferenceCulture: preference towards cultural activities, in a range from 1 to 5 preferenceGastronomy: preference towards gastronomy, in a range from 1 to 5 preferenceNightLife: preference towards nightlife activities, in a range from 1 to 5 Returns: The HTML page with the calculated itinerary """ # Handle the data from the request form, parsing the strings to obtain manageable data types. month,day,year = request.form['startDate'].split('/') startDate = datetime.date(int(year), int(month), int(day)) month,day,year = request.form['endDate'].split('/') endDate = datetime.date(int(year), int(month), int(day)) delta = endDate - startDate needsFreeTime = True if request.form.get('needsFreeTime', False) == "yes" else False presenceOfKids = True if request.form.get('presenceOfKids', False) == "yes" else False excludeList = request.form.get('exclude').replace('["', "").replace('"]', "").split('","') includeList = request.form.get('include').replace('["', "").replace('"]', "").split('","') if excludeList[0] == "[]": excludeList = [] if includeList[0] == "[]": includeList = [] #if the request comes from a new customer, insert them into the database if request.form['existingClient'] == '0': ageInput = int(request.form.get('clientAge', 18)) category = "young" if ageInput > 30 and ageInput < 40: category = "adult" elif ageInput >= 40 and ageInput < 60: category = "middleAged" elif ageInput >= 60: category = "elderly" clientQuiet = request.form.get('clientQuiet', False) if clientQuiet == 'yes': clientQuiet = True client = models.Client(request.form['clientName'], clientQuiet, category) db.session.add(client) db.session.commit() else: client = models.Client.query.get(request.form['existingClient']) # Divide coherently the initial request calling operationalize r = Request() r.operationalize(startDate, delta.days, presenceOfKids, needsFreeTime, excludeList, includeList, client, request.form['preferenceShopping'], request.form['preferenceCulture'], request.form['preferenceGastronomy'], request.form['preferenceNightLife']) # Create the initial skeletal design sketal_design = r.specify() # Compose the itinerary according to the knowledge rules eA = easyAround() proposal = eA.propose(r.requirements, r.preferences, sketal_design, r.constraints) # Hand out the first version of the itinerary to the client, to allow modifications verify = eA.verify(proposal) return verify
def insert_auth(new_auth, client_id): ''' Handles processed Auth information as an dict. Inserts and updates appropriate information as needed. Returns tuple of Client and Comment on actions taken. ''' comments = ['Found authorization for {} {} - Auth No: {}'.format(new_auth['client']['first_name'], new_auth['client']['last_name'], new_auth['auth']['auth_id'])] company_id = current_user.company_id if client_id == None: clients = models.Client.query.filter(models.Client.uci_id==new_auth['client']['uci_id'],\ models.Client.regional_center.has(company_id=company_id)).all() if len(clients) == 0: clients = models.Client.query.filter(or_(func.lower(models.Client.first_name).like(new_auth['client']['first_name'][:5].lower() + "%"), func.lower(models.Client.last_name).like(new_auth['client']['last_name'][:5].lower() + "%")), models.Client.regional_center.has(company_id = company_id), models.Client.uci_id == 0).all() if len(clients) == 0: return [None, ['No client found for Authorization Number: {}'.format(new_auth['auth']['auth_id'])]] elif len(clients) > 1: return [None, ['Multiple clients found for Authorization Number: {}. Which one is it?.'.format(new_auth['auth']['auth_id'])]] else: client = clients[0] else: if client_id == 0: regional_center = models.RegionalCenter.query.filter(func.lower(models.RegionalCenter.name) == new_auth['regional_center'].lower(), models.RegionalCenter.company_id == company_id).first() client = models.Client.query.filter(func.lower(models.Client.first_name) == 'new').first() if client == None: client = models.Client(first_name = new_auth['client']['first_name'], last_name = new_auth['client']['last_name'], regional_center = regional_center, therapist = current_user.therapist) else: client.first_name = new_auth['client']['first_name'] client.last_name = new_auth['client']['last_name'] client.regional_center = regional_center client.therapist = current_user.therapist client.status = 'active' db.session.add(client) comments.append('Created New Client: {} {}.'.format(new_auth['client']['first_name'], new_auth['client']['last_name'])) else: client = models.Client.query.get(client_id) case_worker = models.CaseWorker.query.filter(func.lower(models.CaseWorker.first_name).like(new_auth['case_worker']['first_name'][:3].lower() + '%'),\ func.lower(models.CaseWorker.last_name).like(new_auth['case_worker']['last_name'][:5].lower() + '%'),\ models.CaseWorker.regional_center.has(company_id = company_id)).first() if case_worker == None: case_worker = models.CaseWorker(**new_auth['case_worker']) case_worker.regional_center = client.regional_center comments.append('Added New Case Worker: {} {} for {}.'.format(case_worker.first_name, case_worker.last_name, case_worker.regional_center.name)) db.session.add(case_worker) existing_auth = client.auths.filter_by(auth_id = new_auth['auth']['auth_id']).order_by(desc(models.ClientAuth.created_date)).first() if existing_auth != None: existing_end_date = existing_auth.auth_end_date.strftime('%b %Y') for obj, update_values in new_auth.items(): if obj == 'client': update_obj = client elif obj == 'auth': if existing_auth == None: continue update_obj = existing_auth else: continue for key, value in update_values.items(): attr = getattr(update_obj, key, 'SKIP') if attr == 'SKIP' or attr == value: continue else: if key in ['created_date']: continue key_name = ' '.join([k.capitalize() for k in key.split('_')]) name = client.first_name + ' ' + client.last_name if obj == 'client' else existing_auth.auth_id comments.append('Updated {} from {} to {} for {}: {}'.format(key_name, attr, value, obj, name)) setattr(update_obj, key, value) if client.case_worker != case_worker: client.case_worker = case_worker comments.append('Updated Case Worker for {} to {}'.format(client.first_name + ' ' + client.last_name, case_worker.first_name + ' ' + case_worker.last_name)) if existing_auth == None: existing_auth = models.ClientAuth(**new_auth['auth']) comments.append('Created New Auth for {}.'.format(client.first_name + ' ' + client.last_name)) db.session.add(existing_auth) if not new_auth['auth']['is_eval_only']: for auth in client.auths: auth.status = 'inactive' else: existing_auth.status = 'inactive' client.auths.append(existing_auth) insert_auth_reminder(existing_auth) flash('Auth Reminder for %s inserted into Google Calendar' % (client.first_name + ' ' + client.last_name)) else: existing_auth.status = 'active' new_auth_end_date = existing_auth.auth_end_date.strftime('%b %Y') if not existing_auth.is_eval_only and existing_end_date != new_auth_end_date: move_auth_reminder(existing_auth) flash('Auth Reminder moved for %s from %s to %s.' % (client.first_name + ' ' + client.last_name, existing_end_date, new_auth_end_date)) db.session.commit() return [client, comments]
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_cors import CORS app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) cors = CORS(app, resources={r"/*": {"origins": "*"}}) from app import routes, models c = models.Client(phone='89745612321', passport='4568789456', name='IlyaGreen') c2 = models.Client(phone='89741234567', passport='4589621234', name='KarolGreen') d = models.Delivery(client=c, user_code=123456) d2 = models.Delivery(client=c2, user_code=123457) d3 = models.Delivery(client=c2, user_code=123458) cell = models.Cell(capacity=3) cell1 = models.Cell(capacity=3) cell2 = models.Cell(capacity=3) cell3 = models.Cell(capacity=3) cell4 = models.Cell(capacity=3) cell5 = models.Cell(capacity=3) cell6 = models.Cell(capacity=3) it_cel = models.Items_cell(cell=cell) i = models.Item(barcode=12, delivery=d, cell=it_cel) it = models.Item(barcode=14, delivery=d) it1 = models.Item(barcode=15, delivery=d2) it2 = models.Item(barcode=16, delivery=d3)
def enter_appts_to_db(therapist, start_time, end_time): '''Needs dates use standard datetime.datetime python format, and Therapist Object from the query return of models.Therapist''' service = get_calendar_credentials(therapist) eventsResults = service.events().list( calendarId='primary', orderBy='startTime', singleEvents=True, q='source: ', timeMin=start_time.isoformat(), timeMax=end_time.isoformat()).execute() appts = eventsResults.get('items', []) new_appts = [] for appt in appts: appt['description'] = re.sub('<[^<]+?>', ' ', appt['description']) appt['description'] = appt['description'].replace(' ', ' ').strip() rc_from_appt = re.match('source:\s\w+', appt['description']).group(0)[8:] time_format = '%Y-%m-%dT%H:%M:%S' if rc_from_appt == 'MEETING': start_time = datetime.datetime.strptime( appt['start']['dateTime'][:-6], time_format) end_time = datetime.datetime.strptime(appt['end']['dateTime'][:-6], time_format) meeting = models.CompanyMeeting.query.filter_by( start_datetime=start_time, end_datetime=end_time, company_id=therapist.user.company_id).first() if meeting == None: meeting = models.CompanyMeeting( start_datetime=start_time, end_datetime=end_time, company_id=therapist.user.company_id, description=appt['description'][15:].strip()) meeting.users.append(therapist.user) db.session.add(meeting) db.session.commit() meeting_user = models.MeetingUserLookup.query.filter_by( meeting_id=meeting.id, user_id=therapist.user.id).first() meeting_user.attended = 1 db.session.add(meeting_user) db.session.commit() continue client_id_match = re.match('.*\nclient_id:\s[0-9]+', appt['description']) if client_id_match: appt_client_id = client_id_match.group(0).split('\n')[1].split( ' ')[1] client = models.Client.query.get(appt_client_id) else: client = models.Client.query.filter( func.lower( func.concat(models.Client.first_name, ' ', models.Client.last_name)).like( appt['summary'].strip().lower()), models.Client.regional_center.has( company_id=therapist.user.company_id)).first() rc = models.RegionalCenter.query.filter( models.RegionalCenter.appt_reference_name == rc_from_appt, models.RegionalCenter.company_id == therapist.user.company_id).first() if client == None: client_name = appt['summary'].strip().split() # parse address for input new_client = models.Client(first_name=client_name[0], last_name=' '.join(client_name[1:]), therapist=therapist, regional_center=rc) db.session.add(new_client) client = new_client update_appt = False if not client_id_match: appt_desc = appt['description'].split('\n') appt_desc[0] += '\nclient_id: %s' % client.id appt['description'] = '\n'.join(appt_desc) update_appt = True if client_id_match and ' '.join( [client.first_name.lower(), client.last_name.lower()]) != appt['summary'].strip().lower(): appt['summary'] = ' '.join([client.first_name, client.last_name]) update_appt = True if client.status != 'active': client.status = 'active' db.session.add(client) if client.therapist != therapist: client.therapist = therapist db.session.add(client) if client.address: client_address = client.address + ' ' + client.city + ', ' + client.state + ' ' + client.zipcode if appt.get('location', '') != client_address and not rc_from_appt in appt.get( 'location', ''): appt['location'] = client_address update_appt = True if update_appt: service.events().update(calendarId='primary', eventId=appt['id'], body=appt).execute() if appt.get('location', '') == rc_from_appt: location = rc.address + ' ' + rc.city + ', ' + rc.state + ' ' + rc.zipcode elif appt.get('location', '').replace(' ', '').lower() == 'lbhrc': location = '1155 E San Antonio Dr, Long Beach, CA 90807' else: location = appt.get('location', None) start_time = datetime.datetime.strptime(appt['start']['dateTime'][:-6], time_format) end_time = datetime.datetime.strptime(appt['end']['dateTime'][:-6], time_format) appointment_type = 'treatment' if ((end_time - start_time).seconds / 60) == 60 else 'evaluation' appt_type_id = db.session.query(models.ApptType.id)\ .join(models.RegionalCenter)\ .filter(models.RegionalCenter.appt_reference_name == rc_from_appt,\ models.RegionalCenter.company_id == therapist.user.company_id,\ func.lower(models.ApptType.name) == appointment_type).first()[0] new_appt = models.ClientAppt( therapist=therapist, client=client, start_datetime=start_time, end_datetime=end_time, cancelled=1 if 'CNX' in appt['description'] else 0, appointment_type=appointment_type, appt_type_id=appt_type_id, location=location) db.session.add(new_appt) new_appts.append(new_appt) if 'CNX' not in appt['description']: client.needs_appt_scheduled = 0 db.session.add(client) if new_appt.appointment_type == 'evaluation': note = models.ClientApptNote( user=therapist.user, approved=1, appt=new_appt, note='{} - {} {}'.format( new_appt.appointment_type.capitalize(), therapist.user.first_name, therapist.user.last_name)) db.session.add(note) # print(client) db.session.commit() return new_appts