def processCheckCart(booking_id): # 2. Send booking id to cart microservice to retrieve all cart items # Invoke cart microservice print('\n-----Invoking cart microservice-----') cart_result = invoke_http(cart_URL + "/booking/" + booking_id) print('cart_result:', cart_result) code = cart_result["code"] if code not in range(200, 300): # if there are no bookings, return message return {"code": 404, "data": {"cart_result": cart_result}} # 4. get all facilities & roomservices all_facilities = invoke_http(facility_URL) all_room_services = invoke_http(room_service_URL) # 5. Put into dictionary for item_names facility_names = {} for facility in all_facilities['data']['facilities']: facility_names[facility['item_id']] = facility['item_name'] room_service_names = {} for room_service in all_room_services['data']['room_services']: room_service_names[room_service['item_id']] = room_service['item_name'] # 6. return all cart purchases with item_name for booking in cart_result['data']['bookings']: if 'rs' in booking['item_id']: booking['item_name'] = room_service_names[booking['item_id']] else: booking['item_name'] = facility_names[booking['item_id']] return {"code": 201, "all_bookings": cart_result['data']}
def create_itinerary(): try: userID = request.args.get("userID") if userID == None: return jsonify({"code": 400, "data": "UserID not found"}), 400 except: return jsonify({"code": 400, "data": "UserID not found"}), 400 if request.is_json: try: itinerary = request.get_json() itr_url = itinerary_URL + "itinerary" # print("\nReceived an hidden_gem in JSON:", hidden_gem) creation_result = invoke_http(itr_url, method='POST', json=itinerary) # print('creation_result:', creation_result) if creation_result["code"] not in range(200, 300): logging(userID, "createItinerary", creation_result, "error") return jsonify(creation_result), creation_result["code"] else: theme = creation_result["data"]["theme"] reco_url = recommendation_URL + theme reco_results = invoke_http(reco_url) results = { "code": 200, "data": { "itrDetails": creation_result["data"], "recoDetails": reco_results["data"] } } logging(userID, "createItinerary", results, "success") return jsonify(results), 200 except Exception as e: pass # do nothing. # if reached here, not a JSON request. results = { "code": 400, "message": "Invalid JSON input: " + str(request.get_data()) } logging(userID, "createItinerary", results, "error") return jsonify(results), 400
def send_hotel_facilities(booking_details): item_name = booking_details['item_name'] guest_name = booking_details['name'] booking_id = booking_details['booking_id'] email = booking_details['email'] item_id = booking_details['item_id'] order_datetime = booking_details['order_datetime'][:10] + " " + booking_details['order_datetime'][11:19] f_order = { "item_id": item_id, "order_datetime": order_datetime } add_fb_result = invoke_http(cart_URL + "/add_fb/" + booking_id, method='POST', json=f_order) if add_fb_result['code'] not in range(200, 300): return { 'code': 404, 'status': 'failed to add facility booking' } print("add_fb_result", add_fb_result) email_details = { "email": email, "guest_name": guest_name, "quantity": add_fb_result["data"]['rs_quantity'], "price": add_fb_result["data"]['price'], "item_name" : item_name, "date_time": add_fb_result["data"]["order_datetime"], "order_id": add_fb_result["data"]["order_id"], "booking_id": add_fb_result["data"]["booking_id"], "type": "facility" } print('email_details:', email_details) message = json.dumps(email_details) amqp_setup.check_setup() print('\n\n-----Publishing the (facility notification) message with routing_key=facility.notification-----') amqp_setup.channel.basic_publish(exchange=amqp_setup.exchangename, routing_key="facility.notification", body=message, properties=pika.BasicProperties(delivery_mode=2)) # make message persistent within the matching queues until it is received by some receiver # (the matching queues have to exist and be durable and bound to the exchange) # - reply from the invocation is not used; # continue even if this invocation fails print("\nOrder status ({:d}) published to the RabbitMQ Exchange:".format( add_fb_result['code']), message) return { "code": 201, "booking_result": { "email": email, "guest_name": guest_name, "status": "success" } }
def addTimeSlotIDtoPatientAppt(pID, dID, timeSlotIDArg, timeSlotDetails): print('\n-----Invoking appt microservice add timeSlotID via POST-----') addTS_URL = appt_URL add_appt_result = invoke_http(addTS_URL, method='POST', json={ "pID": pID, "dID": dID, "timeSlotID": timeSlotIDArg, "apptDateTime": timeSlotDetails }) print('add_appt_result:', add_appt_result) code = add_appt_result["code"] if code not in range(200, 300): return {"code": 400, "message": "Appt add failure"} return { "code": 201, "data": { "add_appt_result": add_appt_result }, "message": "Successfully add Timeslot into patient account" }
def findDoctorAvailability(): print('\n-----Invoking doctor microservice-----') doctoravail_result = invoke_http(doctor_URL, method='GET') # dID = doctoravail_result['dID'] # timeSlot = doctoravail_result['timeSlot'] # bookingStatus = doctoravail_result['bookingStatus'] print('doctoravail_result:', doctoravail_result) code = doctoravail_result["code"] # code = 200 if code not in range(200, 300): return { "code": 400, "message": "Doctor is not available at this time slot findDoctorAvailability" } return { "code": 201, "data": { "doctoravail_result": doctoravail_result }, "message": "Successfully retrieved doctor's availability" }
def show_existingorders(): # tb adding code to verify login print(session) if 'acctType' in session: if session['acctType'] == 'customer': result = invoke_http( checkorder_cust_URL+'/'+str(session['data']['cid']), method='GET') return render_template('myorders.html',data=[result['data']]) elif session['acctType'] == 'business': result = invoke_http( checkorder_biz_URL+'/'+str(session['data']['bid']), method='GET') return render_template('myorders.html',data=[result['data']]) return redirect(url_for('.login',msg='Please log in'))
def upload(): if session.get('loggedin') == True: if session.get('acctType') == 'business': if request.method == 'POST': # save the file img = request.files['imgfile'] fileext = img.filename.split('.')[-1] timestr = time.strftime("%Y%m%d-%H%M%S") newfilename = str(timestr)+'.'+fileext img.save(os.path.join(uploads_dir, secure_filename(newfilename))) sendjson = { "pname": request.form['pname'], "price": request.form['price'], "pdescription": request.form['pdesc'], "imgname": newfilename, "bid": session['data']['bid'] } result = invoke_http( product_URL, method='POST', json=sendjson) print(result) return render_template('product_listing.html',pid=result['data']['pid']) # for normal get to create product listing page return render_template('product_listing.html',msg='') # if not business return redirect(url_for('.home',msg='no such url')) # if not logged in return redirect(url_for('.login',msg='Please log in'))
def findTimeSlotIDtoStatus(timeSlotIDArg): print( '\n-----Invoking doctor microservice get via timeSlotID to change bookingstatus to Unavailable-----' ) rts_URL = doctor_URL + "/statuschange/" + timeSlotIDArg doctoravail_result = invoke_http(rts_URL, method='PUT', json={ "timeSlotID": timeSlotIDArg, "bookingStatus": "Unavailable" }) print('doctoravail_result:', doctoravail_result) code = doctoravail_result["code"] if code not in range(200, 300): return { "code": 400, "message": "Doctor is not available at this time slot" } return { "code": 201, "data": { "doctoravail_result": doctoravail_result }, "message": "Successfully altered Doctor's Timeslot availability" }
def create_hidden_gem(): try: userID = request.args.get("userID") if userID == None: return jsonify({"code": 400, "data": "UserID not found"}), 400 except: return jsonify({"code": 400, "data": "UserID not found"}), 400 if request.is_json: try: hidden_gem = request.get_json() creation_result = invoke_http(hg_URL, method='POST', json=hidden_gem) logging( userID, "createHG", creation_result["data"], "success" if creation_result["code"] in range(200, 300) else "error") return jsonify(creation_result), creation_result["code"] except Exception as e: pass # do nothing. result = { "code": 400, "data": "Invalid JSON input: " + str(request.get_data()) } logging(userID, "createHG", result, "error") # if reached here, not a JSON request. return jsonify({result}), 400
def add_event(): try: userID = request.args.get("userID") if userID == None: return jsonify({"code": 400, "data": "UserID not found"}), 400 except: return jsonify({"code": 400, "data": "UserID not found"}), 400 if request.is_json: try: itinerary = request.get_json() itr_url = itinerary_URL + "event" creation_result = invoke_http(itr_url, method='POST', json=itinerary) logging( userID, "addEvent", creation_result["data"], "success" if creation_result["code"] in range(200, 300) else "error") return jsonify(creation_result), creation_result["code"] except Exception as e: pass # do nothing. # if reached here, not a JSON request. results = { "code": 400, "message": "Invalid JSON input: " + str(request.get_data()) } logging(userID, "createItinerary", results, "error") return jsonify(results), 4000
def checkTiming(data): order_id = str(data["order_id"]) print('\n-----Invoking Cart microservice-----') order_result = invoke_http( cart_URL + "/order/" + order_id, method='GET') code = order_result['code'] if order_result['code'] not in range(200, 300): return { 'code': 404, 'status': 'failed to get order' } delivered = order_result["data"]["rs_delivered_status"] if not delivered: email_details = { "email": data['email'], "guest_name": data['guest_name'], "quantity": order_result["data"]['rs_quantity'], "price": order_result["data"]['price'], "item_name" : data["item_name"], "date_time": order_result["data"]["order_datetime"], "order_id": order_result["data"]["order_id"], "booking_id": order_result["data"]["booking_id"], "type": "delay" } update_discount = invoke_http(booking_URL + "/" + str(order_result["data"]["booking_id"]), method='PUT') print('email_details:', email_details) message = json.dumps(email_details) amqp_setup.check_setup() print('\n\n-----Publishing the (delay notification) message with routing_key=delay.notification-----') amqp_setup.channel.basic_publish(exchange=amqp_setup.exchangename, routing_key="delay.notification", body=message, properties=pika.BasicProperties(delivery_mode=2)) # make message persistent within the matching queues until it is received by some receiver # (the matching queues have to exist and be durable and bound to the exchange) # - reply from the invocation is not used; # continue even if this invocation fails print("\nOrder status ({:d}) published to the RabbitMQ Exchange:".format( code), message)
def processNotifications(notificationMsg): print("Printing the notification:") try: notification = json.loads(notificationMsg) print("--JSON:", notification) #call the invoke(create_noti + admin/user, post, json=data) receiver = notification["data"]["receiver"] invoke_http("http://localhost:5007/notifications/" + receiver, method='POST', json=notification["data"]) except Exception as e: print("--NOT JSON:", e) print("--DATA:", notificationMsg) print()
def call_poiManager(data): temp = data url = poiManager_URL + data["locType"] + "/" + data[ "poiUUID"] + "/" + data["locCategory"] + "?userID=0" event_details = invoke_http(url) temp["POIDetails"] = event_details['data'] return temp
def processEditFacility(edit, facilities_URL): facility_id = edit["facility_id"] messages = edit["messages"] print('\n-----Invoking facilities microservice-----') facilities_URL = facilities_URL + facility_id facilities_result = invoke_http(facilities_URL, method='PUT', json=edit) facilities_result['data']['messages'] = messages facilities_result['data']['receiver'] = "user" return (facilities_result)
def processUpdateItinerary(itineraryid): print('\n-----Invoking itinerary microservice-----') searchid = str(itineraryid['itineraryid']) itinerary_info = invoke_http(itineraryapprove_URL + searchid, method='PUT') return { "code": 201, "data": { "itinerarycreator": itinerary_info['data']['itinerarycreator'] } }
def get_tuteeInfo(TuteeID_result): # Get tutee info # Invoke the tutee microservice print('\n-----Invoking tutee microservice-----') tutee_info_url = tutee_URL + '/' + str(TuteeID_result) print(tutee_info_url) tutee_result = invoke_http(tutee_info_url, method='GET', json=None) print('tutor_result:', tutee_result) return {"code": 200, "data": {"tutee_result": tutee_result}}
def configure_signup(): msg = '' account_type = request.form['acctType'] print(request.form, file=sys.stderr) if 'email' in request.form : email = request.form['email'] password=request.form['password'] if (account_type == "customer"): result = invoke_http( cuslogin_URL+'/'+email, method='GET', json={"email": email}) desc = '' elif(account_type == "business"): result = invoke_http( bizlogin_URL+'/business/'+email, method='GET', json={"email": email}) desc = request.form['description'] if result['code'] != 200: # Redirect to home page password = hashlib.md5(password.encode('utf-8')).hexdigest() mydict = { 'name':request.form['name'], 'email':email, 'password':password, 'paypal':request.form['paypalemail'], 'address':request.form['address'], 'description': desc, } app.logger.info(mydict) if (account_type == "customer"): registerresult = invoke_http(cuslogin_URL, method='POST', json=mydict) elif(account_type == "business"): registerresult = invoke_http(bizlogin_URL+'/business', method='POST', json=mydict) if registerresult['code'] == 200: app.logger.info(registerresult) return redirect(url_for('.login',msg ='Signup sucessfully Please login')) else: return redirect(url_for('.home',msg ='Signup is not sucessfull. Please try again later')) else: return redirect(url_for('.home',msg ='Customer exists'))
def add_customer(): new_url = url j = { "customer_id": 2, "customer_name": 'Cortana', "phone_number": 343, "credit_card": '4242424242424242', "tele_id": 'test' } results = invoke_http(new_url, method="POST", json=j) print(results)
def get_tutorInfo(TutorID_result): # Get tutor info # Invoke the tutor microservice print('\n-----Invoking tutor microservice-----') tutor_info_url = tutor_URL + '/' + str(TutorID_result) tutor_result = invoke_http(tutor_info_url, method='GET', json=None) print('tutor_result:', tutor_result) # code = tutor_result["code"] # if code not in range(200, 300): # #Return error return {"code": 200, "data": {"tutor_result": tutor_result}}
def processBookAppt(apptRequest): print('\n-----Invoking processBookAppt microservice-----') apptRequest_result = invoke_http(appt_URL, method='POST', json=apptRequest) print('apptRequest_result:', apptRequest_result) code = apptRequest_result["code"] if code not in range(200, 300): return {"code": 400, "message": "Fail to process booking"} return {"code": 201, "message": "Successfully added booking"}
def process_PostAssignment(assignment): # Send the assignment info # Invoke the assignment microservice postAsgmt_URL = assignment_URL + "/post" print(postAsgmt_URL) print('\n-----Invoking assignment microservice-----') assignment_result = invoke_http(postAsgmt_URL, method='POST', json=assignment) print('assignment_result:', assignment_result) # Return created assignment return {"code": 201, "data": {"assignment_result": assignment_result}}
def processConsultDetails(consultDetails, pid): # 2. Send the order info {cart items} # Invoke the order microservice print('\n-----Invoking patient microservice-----') medRec_result = invoke_http(patient_URL + "/" + pid + "/" + "medicalRecords", method='POST', json=consultDetails["MedicalRecords"]) print('medRec_result:', medRec_result) # 4. Record new order # record the activity log anyway print('\n\n-----Invoking prescription microservice-----') prescription_result = invoke_http(prescription_URL, method="POST", json=consultDetails["Prescription"]) print('prescription_result:', prescription_result) # - reply from the invocation is not used; # continue even if this invocation fails # Check the order result; if a failure, send it to the error microservice. medRecCode = medRec_result["code"] prescriptionCode = prescription_result["code"] if medRecCode and prescriptionCode in range(200, 300): # Inform the error microservice # print("Consult details added successfully!!!!!!") # 7. Return error return { "code": 201, "data": { "medRec_result": medRec_result, "prescription_result": prescription_result }, "message": "Consult details added successfully!!!!!!" }
def processDisplayItinerary(emailaddr): # Invoke the payment microservice print('\n-----Invoking payment microservice-----') searchid = str(emailaddr['emailaddr']) payment_info = invoke_http(payment_URL + searchid, method='GET') print('payment:', payment_info) itineraryidarray = [] payment_info = payment_info["data"]["payment"] for payment in payment_info: if (payment['isPaid'].lower() == "true"): for paymentitem in payment['paymentItems']: if (paymentitem['itineraryID'] not in itineraryidarray): itineraryidarray.append(paymentitem['itineraryID']) print('\n-----Invoking itinerary microservice-----') purchasearray = [] for itineraryid in itineraryidarray: itinerary_info = invoke_http(itinerary_URL + str(itineraryid), method='GET') print('itinerary_info:', itinerary_info["data"]) purchasearray.append(itinerary_info["data"]) return {"code": 201, "data": {"itinerary_info": purchasearray}}
def get_all_posted_asgmt(TuteeID): # Invoke the assignment microservice print('\n-----Invoking assignment microservice-----') posted_asgmt_URL = assignment_URL + "/all/" + TuteeID posted_asgmt_result = invoke_http(posted_asgmt_URL, method='GET', json=None) print('posted_asgmt_result:', posted_asgmt_result) # print(posted_asgmt_result.data.assignments.TutorID) # tutor_asgmt_URL = tutor_URL + "/" + str(tutorID) # Return all posted assignments return {"code": 200, "data": {"posted_asgmt_result": posted_asgmt_result}}
def view_all_assignment(): # Get all open assignment from assignment microservice # Invoke the assignment microservice print('\n-----Invoking assignment microservice-----') assignment_result = invoke_http(assignment_URL, method='GET', json=None) print('assignment_result:', assignment_result) # Return all open assignments return { "code": 200, "data": { "assignment_result": assignment_result, } }
def get_accepted_assignment(TutorID): # Get assignment info # Invoke the assignment microservice print('\n-----Invoking assignment microservice-----') assignment_update_URL = assignment_URL + "/accepted/" + TutorID print(assignment_update_URL) accepted_assignment = invoke_http(assignment_update_URL, method='GET', json=None) print('accepted_assignment:', accepted_assignment) accepted = accepted_assignment["data"]["assignments"] list_of_tuteeID = [] for a in accepted: list_of_tuteeID.append(a["TuteeID"]) print(list_of_tuteeID) list_of_tuteeInfo = [] for i in list_of_tuteeID: print('\n-----Invoking tutee microservice-----') tutee_update_URL = tutee_URL + "/" + str(i) print(tutee_update_URL) accepted_tutee_info = invoke_http(tutee_update_URL, method='GET', json=None) list_of_tuteeInfo.append(accepted_tutee_info) print('list_of_tuteeInfo:', list_of_tuteeInfo) # Return accepted assignment information return { "code": 200, "data": { "accepted_assignment": accepted_assignment, "list_of_tuteeInfo": list_of_tuteeInfo } }
def total_amount(booking_id): # 2. Send booking id to booking microservice to retrieve all booking items # Invoke booking microservice print('\n-----Invoking booking microservice-----') booking_result = invoke_http(booking_URL + "/" + str(booking_id)) print('booking_result:', booking_result) code = booking_result["code"] if code not in range(200, 300): # if there are no bookings, return message return { "code": 404, "data": {"booking_result": booking_result} } room_price = booking_result['data']['room_price'] discount = booking_result['data']['discount'] print(discount) # 3. get all facilities and room services from cart microservice print('\n-----Invoking cart microservice-----') cart_items = invoke_http(cart_URL + "/booking/" + booking_id) cart_items = cart_items['data']['bookings'] if len(cart_items): total = 0 for purchase in cart_items: if purchase['price'] != None: total += float(purchase['price']) * \ int(purchase['rs_quantity']) total = round((total + room_price) * (1 - discount), 2) return { "code": 200, "total": total }
def processMakeBooking(booking, booking_URL, booking_id, payment_URL): print("\n----Invoking Payment Microservice----") # print(booking) payment_URL = payment_URL + booking_id payment_result = invoke_http(payment_URL, method='POST', json=booking) print("payment_result:", payment_result) if payment_result['code'] == 201: print("\n-----Invoking Booking Microservice-----") print(booking) booking_URL = booking_URL + booking_id # print(booking_URL) booking_result = invoke_http(booking_URL, method='POST', json=booking) print("booking_result:", booking_result) code = booking_result['code'] message = json.dumps(booking_result) return ({ "code": 201, "data": { "booking_result from book_facility.py": booking_result['code'], "payment_result from payment.py": payment_result['code'] } }) elif payment_result['code'] == 500: return { "code": 500, "data": { "payment_result": payment_result }, "message": "Payment failed" }
def get_TuteeID(AssignmentID): # Get TutorID # Invoke the assignment microservice print('\n-----Invoking assignment microservice-----') assignment_info_url = assignment_URL + '/' + AssignmentID print(assignment_info_url) assignment_info_result = invoke_http(assignment_info_url, method='GET', json=None) print('assignment_info_result:', assignment_info_result) TuteeID_result = assignment_info_result["data"]["TuteeID"] print(TuteeID_result) tutee_info = get_tuteeInfo(TuteeID_result) return jsonify(tutee_info), 200
def configure_login(): msg = '' account_type = request.form['acctType'] print(request.form) if request.method == 'POST' and 'email' in request.form and 'password' in request.form: email = request.form['email'] password = hashlib.md5( request.form['password'].encode('utf-8')).hexdigest() if (account_type == "customer"): login_result = invoke_http( cuslogin_URL+'/'+email, method='POST', json={"email": email, "password": password}) elif(account_type == "business"): login_result = invoke_http( bizlogin_URL+'check/business', method='POST', json={"email": email, "password": password}) else: msg = 'Please select a account type!' return redirect(url_for('.login',msg =msg)) if login_result['code'] == 200: # Create session data, we can access this data in other routes session['loggedin'] = True session['acctType'] = account_type session['data'] = login_result['data'] # Redirect to home page msg = 'Logged in successfully!' return redirect(url_for('.home',msg =msg)) msg = 'Incorrect username/password!' return redirect(url_for('.login',msg =msg))