示例#1
0
def render_request():
    if request.method == 'POST':
        form = RequestForm()

        goal = form.goals.data
        hour = form.hours.data
        name = form.name.data
        phone = form.phone.data

        with app.app_context():
            new_client = Client(name=name, phone=phone)
            db.session.add(new_client)

            new_request = Request(
                client=new_client,
                hour=Hour.query.filter(Hour.code == hour).first(),
                goal=Goal.query.filter(Goal.code == goal).first())
            db.session.add(new_request)

            db.session.commit()

        return render_template('request_done.html',
                               goal=goals[goal],
                               hours=hours[hour],
                               name=name,
                               phone=phone)
    else:
        form = RequestForm()

        return render_template('request.html', form=form)
示例#2
0
def create_request(data, current_user: User, project_id):
    """Crea una request."""
    project = Project.query.filter_by(project_id=project_id).first()

    if not project:
        return jsonify({'message': 'No project found!'}), 404

    if current_user != project.user:
        return jsonify({
            'message':
            'You don\'t have permission to create a request in that project!'
        }), 403

    if create_request_validator.validate(data):
        for req in project.requests:
            if req.name == data['name']:
                return jsonify(
                    {'message':
                     'A request with that name already exists'}), 409
        one_request = Request(**data)
        db.session.add(one_request)
        project.requests.append(one_request)
        db.session.commit()
        return jsonify({
            'message': 'New request created!',
            'request': request_schema.dump(one_request).data
        })
    else:
        return jsonify({
            'message': 'Request not created!',
            'errors': create_request_validator.errors
        }), 400
示例#3
0
def admin():  # admin view pending request list
    statement = """SELECT * FROM Request r INNER JOIN BaseProperty bp ON bp.PropertyID = r.PropertyID WHERE bp.OwnershipID = '7EE30661-80AD-4862-966B-7279D0F80D22'"""
    request_list = []
    records = Get.read_all(statement=statement)
    for record in records:
        request_list.append(vars(Request.Request(record)))
    return request_list
示例#4
0
def add_connection_request(current_user_id, other_user_id):
    """Adds a connection request to the db"""

    new_request = Request(requester_id=current_user_id,
                          requestee_id=other_user_id)
    db.session.add(new_request)
    db.session.commit()
    return new_request.request_id
def create_request(connection, borrower, lender, lent=False):
    """Creates a book request"""

    req = Request(connection_id=connection.id,
                  borrower=borrower,
                  lender=lender,
                  lent=lent)

    db.session.add(req)
    db.session.commit()
示例#6
0
def handle(event, context):

    new_requests = Request.get_new_requests()

    response = {
        'statusCode': 200,
        'body': json.dumps(new_requests),
    }

    return response
示例#7
0
def Makerequest(id):
    user = session.query(User).filter_by(id=id).first()
    if request.method=='POST':
        location=request.form['location']
        if location=="" or request.form['meal_type']==""or request.form['date']=="" or request.form['time']=="":
           flash('this two input should not be empty')
           return render_template('RequestPage.html',user=user)
        latitude,longitude=getGeocodeLocation(location)
        if latitude=="zero":
           flash('Sorry,can not find your location')
           return render_template('RequestPage.html',user=user)
        restaurant_info=findARestaurant(request.form['meal_type'],location)
        if restaurant_info=="No Restaurants Found":
           flash('Sorry,can not find the target restaurant according your meal type')
           return render_template('RequestPage.html',user=user)
        meal_time=request.form['date']+request.form['time']
        Re=Request(user_id=id)
        Re.meal_type=request.form['meal_type']
        Re.latitude=latitude
        Re.longitude=longitude
        Re.location_string=location
        session.add(Re)
        session.commit()
        return render_template('RequestPage.html',user=user)
    else:
        return render_template('RequestPage.html',user=user)
示例#8
0
def handle(event, context):

    new_requests = Request.get_requests_in_evaluation()

    response = {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': True
        },
        'body': json.dumps(new_requests),
    }

    return response
示例#9
0
def submission_form():
    """Display previous selections, collect phone number, and commit to db"""
    if request.method == "GET":
        list_of_objs = []
        available_list = []
        avail_num = []
        totals = []
        for campsite in session["campsites"]:
            site_obj = Campsite.query.filter_by(id=campsite).one()
            list_of_objs.append(site_obj)
            resp = check_availability(session["date_start_dt"],
                                      session["date_end_dt"], campsite)
            available = get_num_available_sites(resp, session["date_start_dt"],
                                                session["date_end_dt"])
            available_list.append(available)
            avail_num.append(available[0])
        for item in available_list:
            chars = item.split()
            totals.append(chars[5])

        return render_template(
            "submission_form.html",
            campsites=session["campsites"],
            list_of_objs=list_of_objs,
            date_start=session["date_start"],
            date_end=session["date_end"],
            available=available_list,
            avail_num=avail_num,
            totals=totals,
        )
    else:
        phone = request.form["phone"]
        valid = is_valid_number(phone)
        if is_valid_number(phone) is True:
            new_user = User(phone=phone)
            db.session.add(new_user)
            db.session.commit()
            user_id = new_user.user_id
            session["user_id"] = user_id
            for site in session["campsites"]:
                new_request = Request(
                    user_id=session["user_id"],
                    campsite_id=site,
                    date_start=session["date_start_dt"],
                    date_end=session["date_end_dt"],
                )
                db.session.add(new_request)
                db.session.commit()
            return render_template("confirm.html")
示例#10
0
def create_request(user_id, mask_id):
    # healthcare_center,
    # address,
    # num_packs):
    """Create and return a request instance"""

    request = Request(user_id=user_id, mask_id=mask_id)
    # healthcare_center=healthcare_center,
    # address=address,
    # num_packs=num_packs)

    db.session.add(request)
    db.session.commit()

    return request
示例#11
0
def put(feature_request_id):

    feature_request = Request.find_by(id=feature_request_id)

    if feature_request is None:
        return jsonify({'status': 'fail', 'reason': 'Resource not found'}), 404

    feature_request_response = json.loads(request.data)
    feature_request = feature_request.update_request(feature_request,
                                                     feature_request_response)
    feature_request.save()

    return jsonify({
        'status': 'success',
        'reason': 'Feature request updated',
        'feature_request': feature_request.to_json(feature_request)
    })
示例#12
0
def request_seats():
    """ Add request for a seat to database """

    # Retrieve number of seats, ride_id from form
    seats = request.form.get('seats')
    ride_id = request.form.get('ride_id')

    requester = session['current_user']
    print '\n\nuser_id: {}, seats: {}, ride_id: {}\n\n'.format(
        requester, seats, ride_id)

    # Request instance
    new_request = Request(ride_id=ride_id, requester=requester, seats=seats)

    db.session.add(new_request)
    db.session.commit()

    return redirect('/profile/{}'.format(requester))
示例#13
0
def post():
    feature_request_response = json.loads(request.data)
    feature_request = Request(feature_request_response['title'],
                              feature_request_response['description'],
                              feature_request_response['client_id'],
                              feature_request_response['client_priority'],
                              feature_request_response['target_date'],
                              feature_request_response['product_id'])

    feature_request.insert(feature_request)
    feature_request.save()

    return jsonify({
        'status': 'success',
        'reason': 'Feature request added',
        'feature_request': feature_request.to_json(feature_request)
    }), 201
示例#14
0
def Makerequest(id):
    user = session.query(User).filter_by(id=id).first()
    if request.method == 'POST':
        location = request.form['location']
        latitude, longitude = getGeocodeLocation(location)
        meal_time = request.form['location']
        Re = Request(user_id=id)
        Re.meal_type = request.form['meal_type']
        Re.latitude = latitude
        Re.longitude = longitude
        Re.location_string = location
        session.add(Re)
        session.commit()
        return render_template('RequestPage.html', user=user)
    else:
        return render_template('RequestPage.html', user=user)
示例#15
0
def participateUserOrder():
    # if True or not request.form or not 'orderId' in request.form:
    #     abort(400)
    # else:
    try:
        data = json.loads(request.get_data(as_text=True))
        requestid = Request.query.count()
        order = Order.query.filter(Order.id == data['orderId']).first()
        user = User.query.filter(User.id == data['userId']).first()
        times = ''
        for time in data['timelist']:
            times = times + time['day'] + " " + time['time'] + ";"

        oldRequest = Request.query.filter(
            and_(Request.orderid == data['orderId'],
                 Request.userid == data['userId'])).first()
        if not oldRequest:
            newRequest = Request(
                int(requestid), int(data['orderId']), int(data['userId']),
                str(user.latitude) + "," + str(user.longitude), times, "",
                data['description'], order.price)
            db.session.add(newRequest)
        else:
            db.session.query(Request).filter(
                and_(Request.orderid == data['orderId'],
                     Request.userid == data['userId'])).update({
                         "timeproposed":
                         oldRequest.timeproposed + times,
                         "description":
                         oldRequest.description + ";" + data['description']
                     })
        oldorder = Order.query.filter(Order.id == data['orderId']).first()
        db.session.query(Order).filter(Order.id == data['orderId']).update(
            {"requestlist": oldorder.requestlist + str(requestid) + ","})
        db.session.commit()
        db.session.close()
    except:
        abort(500)
    else:
        return jsonify(request.get_data(as_text=True)), 201
示例#16
0
文件: server.py 项目: telle1/Joyride
def request_ride():
    #tried using fetch
    data = request.get_json()
    print(data)
    print(data['ride_id'])
    ride_id = data['ride_id']
    rider_msg = data['rider_msg']
    # ride_id = request.form.get('ride_id')
    # rider_msg = request.form.get('rider_msg')
    # print('tHIS IS THE RIDE_ID', ride_id)
    ride = crud.get_ride_by_id(ride_id)
    driver_id = ride.driver_id

    req = crud.get_request(rider_id=session['user_id'], ride_id=ride_id)

    print('THIS IS THE REQUEST INFORMATION:', req)
    print('THIS IS THE RIDER MESSAGE', rider_msg)
    print('THIS IS THE RIDE ID', ride, 'THIS IS THE DRIVER ID', driver_id)
    if req is None:
        if driver_id != session['user_id']:
            add_req = Request(ride_id=ride_id,
                              rider_id=session['user_id'],
                              status='Pending')
            db.session.add(add_req)
            db.session.commit()
            resp = jsonify({'msg': "Ride successfully requested."})
            #print('THIS IS THE DRIVERs FIRST NAME', add_req.ride.user.first_name)
            #print('THIS IS THE RIDERS PHONE NUM', add_req.user.phone_num)
            # send_twilio_message = client.messages.create(
            #     to= add_req.ride.user.phone_num,
            #     from_= twilio_phone_num , #(rider aka session['user_id']) add_req.user.phone_num
            #     body= rider_msg)
        else:
            resp = jsonify({'msg': "You cannot request your own ride."})
    else:
        resp = jsonify({'msg': "You already requested this ride."})
        print('THIS IS THE DRIVER ID', req.ride.driver_id)

    return resp
示例#17
0
def addRequest():
    # if not request.form or not 'userid' in request.form:
    #     abort(400)
    # else:
    try:
        data = json.loads(request.get_data(as_text=True))
        user = User.query.filter(User.id == data['userId']).first()
        userlocation = str(user.latitude) + "," + str(user.longitude)
        requstList = Request.query.all()
        nb = Request.query.count()
        requestid = int(requstList[nb - 1].id) + 1
        desttime = ''

        for time in data['deliveryTime']:
            desttime = desttime + time['day'] + " " + time['time'] + ";"

        volunteertime = ''
        if int(data['volunteer']['do']) == 1:
            for time in data['volunteer']['timelist']:
                volunteertime = volunteertime + time['day'] + " " + time[
                    'time'] + ";"
        requestorderid = 0

        existingorder = Order.query.filter(
            and_(Order.ownerid == data['farmOwnerId'],
                 Order.description == "")).first()
        if not existingorder:
            orderid = Order.query.count()
            farm = Farm.query.filter(
                Farm.userid == data['farmOwnerId']).first()
            neworder = Order(int(orderid), int(data['farmOwnerId']),
                             str(farm.latitude) + "," + str(farm.longitude),
                             "", "", "", 0, "", 0, 0, "", "")
            db.session.add(neworder)
            requestorderid = orderid
        else:
            requestorderid = existingorder.id

        description = ''
        carbon = 0
        for item in data['cart']:
            description = description + item['productName'] + "_" + str(
                item['amount']) + ";"
            product = Product.query.filter(
                Product.name == item['productName']).first()
            carbon += int(product.carbonredu) * int(item['amount'])
            nbr = int(product.quantity) - int(item['amount'])
            db.session.query(Product).filter(
                Product.name == item['productName']).update(
                    {"quantity": nbr if nbr > 0 else 0})

            db.session.commit()
        actual = carbon + user.carbonactual
        if (actual >= 100):
            actual = actual - 100
            count = Coupon.query.count()
            coupon = Coupon(int(count), int(user.id), 5)
            db.session.add(coupon)
        db.session.query(User).filter(User.id == user.id).update({
            "carbonactual":
            int(actual),
            "carbontotal":
            int(carbon) + int(user.carbontotal)
        })
        db.session.commit()
        db.session.add(
            Request(int(requestid), int(requestorderid), int(data['userId']),
                    userlocation, desttime, volunteertime, description,
                    float(data['totalPrice'])))
        oldorder = Order.query.filter(
            Order.ownerid == data['farmOwnerId']).first()
        db.session.query(Order).filter(
            Order.ownerid == data['farmOwnerId']).update(
                {"requestlist": oldorder.requestlist + str(requestid) + ","})
        db.session.commit()
    except:
        abort(500)
    else:
        return jsonify(request.get_data(as_text=True)), 201
示例#18
0
def load_requests_offers(num_of_users, num_requests):
    """ Function to load requests into the DB: arbitrary first half are 
        requesters, second half are volunteers"""
    print(f"num of users {num_of_users}")
    requesters = round(num_of_users / 2)
    volunteers = num_of_users - requesters
    print("**** CREATING REQUESTS ****")
    print(f"Requesters = {requesters}")
    print(f"Volunteers = {volunteers}")
    boolean_choice = [True, False]

    i = 0
    requester_id = 0
    volunteer_id = num_of_users
    # volunteer_index = num_of_users
    # print(f"volunteer index {volunteer_index}")
    for i in range(requesters):
        requester_id = requester_id + 1
        volunteer_id = volunteer_id - 1
        print(f"Requester: {requester_id} Volunteer: {volunteer_id}")

        notes = faker.text()
        print(f"Notes: {notes}")

        fulfilled = random.choice(boolean_choice)
        print(f"fulfilled = {fulfilled}")

        created_on = faker.date()
        print(f"created_on: {created_on}")

        modified_on = created_on
        #service is being requested by the requester - which because
        # of the way we are seeding the database - the requester's address id
        # is the same as their id.
        service_needed_at = requester_id

        request = Request(requester_user_id=requester_id,
                          volunteer_user_id=volunteer_id,
                          notes=notes,
                          fulfilled=fulfilled,
                          created_on=created_on,
                          modified_on=modified_on,
                          service_needed_at=service_needed_at)
        print(request)
        i += 1
        # volunteer_index -+ 1

        # Add the request instance to the session so it will be stored.
        db.session.add(request)

    # Once we're done inserting all the users, commit the changes to the
    # database
    db.session.commit()

    print("**** CREATING VOLUNTEER OFFERS***")
    j = requesters
    print("######## j = ", j)
    offerer_uid = requesters
    for j in range(num_of_users):
        print("######## j = ", j)
        # create a volunteer offer for each of the second half of the users
        # created with load_users(amount_to_generate)
        if offerer_uid != num_of_users:
            offerer_uid = offerer_uid + 1
        expiration_date = faker.date_this_month()
        print(f"expiration_date: {expiration_date}")

        create_on = faker.date_between()
        print(f"create_on: {created_on} ")

        modified_on = create_on

        recurring = random.choice(boolean_choice)
        print(f"recurring: {recurring}")

        description = faker.text()
        print(f"description: {description}")

        offer = Offer(offerer_uid=offerer_uid,
                      expiration_date=expiration_date,
                      created_on=created_on,
                      modified_on=modified_on,
                      recurring=recurring,
                      description=description)
        j += 1

        # Add the offer instance to the session so it will be stored.
        db.session.add(offer)

    # Once we're done inserting all the offers, commit the changes to the
    # database
    db.session.commit()
示例#19
0
 def insert(uri):
     add = Request(uri, None)
     session.add(add)
     session.commit()
示例#20
0
def requestInit():

    Request.query.delete()

    users = User.query.all()

    for i in range(len(orderList)):
        index = 0
        for j in range(len(orderList[i]["requestlist"])):

            id = orderList[i]["requestlist"][j]
            orderid = i
            userindex = randint(0, len(users) - 1)
            userid = users[userindex].id
            userlocation = str(users[userindex].latitude) + "," + str(
                users[userindex].longitude)
            timeproposed = ""
            for nb in range(randint(1, 3)):
                day = dayList[randint(0, 6)]
                start = randint(8, 14)
                end = start + randint(1, 5)
                timeproposed = timeproposed + day + " " + str(
                    start) + "-" + str(end) + ";"

            volunteertime = ""
            # if randint(0,1) == 1:
            # 	for nb in range(randint(1,3)):
            # 		day = dayList[randint(0,6)]
            # 		start = randint(8, 14)
            # 		end = start + randint(1, 5)
            # 		volunteertime = volunteertime + day + " " + str(start) + "-" + str(end) + ";"

            description = "xxxxxxxxxxx"
            price = randint(100, 1000) / 100

            if index == 0:
                db.session.add(
                    Request(id, orderid, 100, userlocation, timeproposed,
                            volunteertime, description, price))
                index = index + 1
                continue

            db.session.add(
                Request(id, orderid, userid, userlocation, timeproposed,
                        volunteertime, description, price))

    id = 10
    orderid = len(orderList)
    nb = 0

    for request in farmRequests:
        nb = nb + len(request)

    for i in range(len(farmRequests)):
        index = 0
        products = Product.query.filter(Product.farmid == i)
        productsTotalNb = Product.query.filter(Product.farmid == i).count()
        for j in range(len(farmRequests[i])):
            userid = farmRequests[i][j]
            userlocation = str(users[userid].latitude) + "," + str(
                users[userid].longitude)
            timeproposed = ""
            for nb in range(randint(1, 3)):
                day = dayList[randint(0, 6)]
                start = randint(8, 14)
                end = start + randint(1, 5)
                timeproposed = timeproposed + day + " " + str(
                    start) + "-" + str(end) + ";"

            volunteertime = ""
            if randint(0, 1) == 1:
                for nb in range(randint(1, 3)):
                    day = dayList[randint(0, 6)]
                    start = randint(8, 14)
                    end = start + randint(1, 5)
                    volunteertime = volunteertime + day + " " + str(
                        start) + "-" + str(end) + ";"

            description = ""
            productSelected = []
            for index in range(randint(1, 5)):
                productId = randint(0, productsTotalNb - 1)
                while (productId in productSelected):
                    productId = randint(0, productsTotalNb - 1)
                productSelected.append(productId)
                if products[productId].quantity > 2:
                    productNb = randint(1,
                                        int(products[productId].quantity / 2))
                    products[productId].quantity = products[
                        productId].quantity - productNb
                else:
                    productNb = 1
                    products[productId].quantity = products[
                        productId].quantity - productNb
                description = description + products[
                    productId].name + "_" + str(productNb) + ";"

            price = randint(100, 1000) / 100

            if index == 0:
                db.session.add(
                    Request(id, orderid, 100, userlocation, timeproposed,
                            volunteertime, description, price))
                index = index + 1
                id = id + 1
                continue

            db.session.add(
                Request(id, orderid, userid, userlocation, timeproposed,
                        volunteertime, description, price))
            id = id + 1

        orderid = orderid + 1
示例#21
0
 def test_request_repr(self):
     r = Request('1234-5678')
     s = eval(r.__repr__())
     assert r.url_id == s.url_id == '1234-5678'
示例#22
0
                            skipinitialspace=True)
        reader.next()
        for row in reader:
            rider = Rider(ride_id=row[0], user_id=row[1], seats=row[2])
            db.session.add(rider)
            db.session.commit()

    with open('seed-data/requests_seed.csv', 'rb') as ride_data:
        reader = csv.reader(ride_data,
                            quotechar="'",
                            delimiter=',',
                            quoting=csv.QUOTE_ALL,
                            skipinitialspace=True)
        reader.next()
        for row in reader:
            request = Request(ride_id=row[0], requester=row[1], seats=row[2])
            db.session.add(request)
            db.session.commit()
    print "adding data"


def example_data():
    # In case this is run more than once, empty out existing data

    day_offset = {
        '1': 1,
        '2': 1,
        '3': 1,
        '4': 1,
        '5': 2,
        '6': 2,
示例#23
0
def ask(question, lang, sid, query=False, request_id=None, **kwargs):
    response = Response()
    response.Datetime = str(dt.datetime.utcnow())
    response.Rate = ''
    response.Lang = lang
    response.Location = LOCATION
    response.ServerIP = IP
    response.RequestId = request_id
    response.Revision = REVISION

    #response = {'text': '', 'emotion': '', 'botid': '', 'botname': ''}

    session = session_manager.get_session(sid)
    if session is None:
        response.ret = codes.INVALID_SESSION
        return response

    if not question or not question.strip():
        response.ret = codes.INVALID_QUESTION
        return response

    botname = session.session_context.botname
    if not botname:
        logger.error("No botname is specified")
    user = session.session_context.user
    client_id = session.session_context.client_id
    response.BotName = botname
    response.User = user
    response.ClientId = client_id
    response.OriginalQuestion = question

    input_translated = False
    output_translated = False
    fallback_mode = False
    responding_characters = get_responding_characters(lang, sid)
    if not responding_characters and lang != FALLBACK_LANG:
        fallback_mode = True
        logger.warn("Use %s medium language, in fallback mode", FALLBACK_LANG)
        responding_characters = get_responding_characters(FALLBACK_LANG, sid)
        try:
            input_translated, question = do_translate(question, FALLBACK_LANG)
        except Exception as ex:
            logger.error(ex)
            logger.error(traceback.format_exc())
            response.ret = codes.TRANSLATE_ERROR
            return response

    if not responding_characters:
        logger.error("Wrong characer name")
        response.ret = codes.WRONG_CHARACTER_NAME
        return response

    # Handle commands
    if question == ':reset':
        session_manager.dump(sid)
        session_manager.reset_session(sid)
        logger.warn("Session {} is reset by :reset".format(sid))
    for c in responding_characters:
        if c.is_command(question):
            response.update(c.respond(question, lang, session, query, request_id))
            return response

    response['yousaid'] = question

    session.set_characters(responding_characters)
    logger.info("Responding characters %s", responding_characters)
    
    request = Request()
    request.id = request_id
    request.lang = lang
    request.sid = sid
    request.question = question
    request.query = query

    _question = preprocessing(request.question, request.lang)
    request.question = _question
    response['ModQuestion'] = _question
    response.Question = response.get('OriginalQuestion')
    response.Marker = kwargs.get('marker')
    response.RunId = kwargs.get('run_id')

    if fallback_mode:
        request.lang = FALLBACK_LANG
        _ask_characters(
            responding_characters, request, response)
    else:
        _ask_characters(
            responding_characters, request, response)

    #if not query:
        # Sync session data
        #if session.last_used_character is not None:
        #    context = session.last_used_character.get_context(session)
        #    for c in responding_characters:
        #        if c.id == session.last_used_character.id:
        #            continue
        #        try:
        #            c.set_context(session, context)
        #        except NotImplementedError:
        #            pass

        #    for c in responding_characters:
        #        if c.type != TYPE_AIML:
        #            continue
        #        try:
        #            c.check_reset_topic(sid)
        #        except Exception:
        #            continue

    record = OrderedDict()
    record['Datetime'] = dt.datetime.utcnow()
    record['Question'] = response.Question
    record['Rate'] = ''
    record['Lang'] = lang
    record['Location'] = LOCATION
    record['ServerIP'] = IP
    record['RequestId'] = request_id
    record['Revision'] = REVISION
    record['ClientId'] = client_id
    record['User'] = user
    record['Marker'] = response.Marker
    record['BotName'] = botname
    record['RunId'] = response.RunId

    if response.answered:
        answer = response.default_response.get('text')
        response['OriginalAnswer'] = answer
        response['AnsweredBy'] = response.default_response.get('botid')
        if fallback_mode:
            try:
                output_translated, answer = do_translate(answer, lang)
                response.default_response['text'] = answer
            except Exception as ex:
                logger.error(ex)
                logger.error(traceback.format_exc())
                response.ret = codes.TRANSLATE_ERROR
                return response

        record['Answer'] = response.default_response.get('text')
        record['LineNO'] = response.default_response.get('lineno')
        record['OriginalAnswer'] = response.get('OriginalAnswer')
        record['TranslatedQuestion'] = question
        record['Topic'] = response.default_response.get('topic')
        record['ModQuestion'] = response.get('ModQuestion')
        record['Trace'] = response.get('trace')
        record['AnsweredBy'] = response.get('AnsweredBy')
        record['TranslateOutput'] = output_translated
        record['TranslateInput'] = input_translated
        record['NormQuestion'] = norm2(response.get('OriginalQuestion'))
        record['NormAnswer'] = norm2(response.default_response.get('text'))
        session.add(record)
        #logger.info("Ask {}, response {}".format(response['OriginalQuestion'], response))
        #response.update(record)
        #response['Datetime'] = str(response['Datetime'])
        return response
    else:
        logger.error("No pattern match")
        response.ret = codes.NO_PATTERN_MATCH
        return response
示例#24
0
def response():
	action = cgi_get("action", choices=["view", "pay", "service", "commitment", "request", "invite", "expense", "verify", "unverify", "apply", "join", "pod", "membership", "person", "enroll", "manage", "confcode", "mint", "balance", "responsibilities"])
	if action == "view":
		ip = local("response").ip
		user = cgi_get("user", required=False) # key
		if user:
			user = db.get(user)
		else:
			user = Person.query(Person.ip == ip).get()
		if not user:
			user = Person()
			user.ip = ip
			user.put()
		views(user)
	elif action == "mint":
		user = db.get(cgi_get("user"))
		amount = cgi_get("amount")
		user.wallet.get().mint(amount)
	elif action == "balance":
		user = db.get(cgi_get("user"))
		succeed(user.wallet.get().balance())
	elif action == "pay":
		payer = db.get(cgi_get("payer"))
		memship = db.get(cgi_get("membership"))
		person = memship.person.get()
		pod = memship.pod.get()
		pment = Payment()
		pment.membership = memship.key
		pment.payer = payer.key
		pment.amount = cgi_get("amount")
		pment.notes = cgi_get("notes")
		if payer.key.urlsafe() == person.key.urlsafe():
			fail("pay yourself?")
		if payer.wallet.get().outstanding < pment.amount:
			fail("you don't have enough in your account!")
		pment.put()
		pkey = pment.key.urlsafe()
		pment.notify("confirm payment", lambda signer : PAYMENT%(pment.amount,
			person.firstName, pod.name, pment.notes, pkey, signer.urlsafe()))
		succeed(pkey)
	elif action == "service":
		succeed(reg_act(cgi_get("membership"), cgi_get("service"),
			cgi_get("workers"), cgi_get("beneficiaries"), cgi_get("notes")))
	elif action == "commitment":
		comm = Commitment()
		comm.membership = cgi_get("membership")
		comm.service = cgi_get("service")
		comm.estimate = cgi_get("estimate")
		comm.notes = cgi_get("notes")
		comm.put()
		comm.verify(comm.membership.get().person) # (submitter already agrees)
		ckey = comm.key.urlsafe()
		service = comm.service.get()
		memship = comm.membership.get()
		person = memship.person.get()
		pod = memship.pod.get()
		comm.notify("affirm commitment", lambda signer : COMMITMENT%(person.email,
			pod.name, comm.estimate, service.name, comm.notes, ckey, signer.urlsafe()))
		succeed(ckey)
	elif action == "request":
		req = Request()
		req.membership = cgi_get("membership")
		req.change = cgi_get("change")
		req.person = cgi_get("person", required=False)
		req.notes = cgi_get("notes")
		req.put()
		req.remind()
		succeed(req.key.urlsafe())
	elif action == "invite":
		inv = Invitation()
		inv.membership = cgi_get("membership")
		inv.email = cgi_get("email").lower()
		inv.notes = cgi_get("notes")
		inv.put()
		inv.invite()
	elif action == "expense":
		exp = Expense()
		exp.membership = cgi_get("membership")
		exp.executor = cgi_get("executor", required=False)
		exp.variety = cgi_get("variety", choices=["dividend", "reimbursement"])
		exp.amount = cgi_get("amount")
		exp.recurring = cgi_get("recurring")
		exp.notes = cgi_get("notes")
		exp.put()
		memship = exp.membership.get()
		mpmail = memship.person.get().email
		pod = memship.pod.get()
		variety = exp.variety
		amount = exp.amount
		if exp.executor:
			variety = "%s - executor: %s"%(variety, exp.executor.get().email)
		else:
			amount = "%s%%"%(amount * 100,)
		exp.notify("approve expense", lambda signer: EXPENSE%(mpmail, pod.name,
			variety, amount, exp.recurring, exp.notes, signer.urlsafe()))
		succeed(exp.key.urlsafe())
	elif action == "verify":
		verifiable = db.get(cgi_get("verifiable")) # act/request/commitment/expense/appointment
		verifiable.verify(db.KeyWrapper(cgi_get("person")))
		redirect("/comp/pods.html", "you did it!")
	elif action == "unverify": # commitment only!!!!??!
		vkey = cgi_get("verifiable")
		verifiable = db.get(vkey)
		verifiable.unverify()
		service = verifiable.service.get()
		memship = verifiable.membership.get()
		person = memship.person.get()
		pod = memship.pod.get()
		for signer in pod.members():
			send_mail(to=signer.get().email, subject="affirm commitment - estimate adjustment",
				body=COMMITMENT%(person.email, pod.name, verifiable.estimate,
					service.name, vkey, signer.urlsafe()))
	elif action == "apply":
		db.get(cgi_get("request")).apply()
		redirect("/comp/pods.html", "you did it!")
	elif action == "join": # support only
		pod = db.get(cgi_get("pod"))
		if pod.variety != "support":
			fail()
		person = db.get(cgi_get("person"))
		succeed(person.enroll(pod).urlsafe())
	elif action == "pod":
		pod = db.get(cgi_get("pod"))
		succeed({
			"services": [a.data() for a in pod.acts()],
			"requests": [r.data() for r in pod.requests()],
			"proposals": [p.data() for p in db.get_multi(pod.proposals())],
			"commitments": [c.data() for c in pod.commitments()],
			"memberships": [m.data() for m in pod.members(True)],
			"people": [p.data() for p in db.get_multi(pod.members())],
			"codebases": [c.data() for c in pod.codebases()],
			"expenses": [e.data() for e in pod.expenses()]
		})
	elif action == "membership":
		memship = db.get(cgi_get("membership"))
		succeed({
			"content": [c.data() for c in Content.query(Content.membership == memship.key).fetch()],
			"products": [p.data() for p in db.get_multi(memship.products)]
		})
	elif action == "person":
		person = db.get(cgi_get("person"))
		succeed({
			"services": len(person.acts()), # more efficient way?
			"memberships": [m.data() for m in person.memberships()],
			"commitments": sum([c.estimate for c in person.commitments()])
		})
	elif action == "responsibilities":
		person = db.get(cgi_get("person"))
		succeed([t.data() for t in person.tasks()])
	elif action == "enroll":
		succeed(enroll(cgi_get("agent"), cgi_get("pod"), cgi_get("person")).urlsafe())
	elif action == "manage":
		succeed(manage(cgi_get("agent"), cgi_get("membership"), cgi_get("content")).key.urlsafe())
	elif action == "confcode":
		send_mail(to=cgi_get("email"), subject="carecoin confirmation code",
			body=CONFCODE%(cgi_get("code"),))
示例#25
0
def view(statement, user_id):
    request_list = []
    records = Get.read_multiple(statement=statement, row_id=user_id)
    for record in records:
        request_list.append(vars(Request.Request(record)))
    return request_list