Пример #1
0
def tutorTransferMoney(request):
    # Initialize message variables
    errno = -1
    msg = ''
    data = {}
    # Retrieving tutor information
    try:
        # Try retrieving the amount to be added to the wallet
        try:
            request_json = json.loads(request.body)
            amount = request_json['amount']
        except:
            raise Exception(1, 'Bad request')

        if not request.user.is_authenticated():
            # Raise bad request response by user not logged in
            raise Exception(2, 'User not logged in')

        # Try retrieving tutor user from logged in user
        tutor = Tutor.getByUsername(request.user.username)
        if tutor == None:
            # Raise bad request response by unknown user type
            raise Exception(3, 'Not a tutor')

        # Check if the wallet has enough amount for transfer
        old_balance = Wallet.getByUserID(tutor.user_profile.user.id).wallet_balance
        if old_balance - amount < 0:
            raise Exception(4, 'Not enough balance')
        # Increment the amount
        new_balance = Wallet.decrementBalance(tutor.user_profile.user.id, amount)
        # Create Transaction record for value transferred
        Transaction.createTransaction(tutor.user_profile.user.id, \
                                        -amount, \
                                        'Value transferred by tutor ' +\
                                        str(tutor) + "("+tutor.username+")")

        # Filling response body
        errno = 0
        msg = "Request succeeded"
        data = {
            "new_balance": new_balance
        }
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e

    # Generate response message
    message = {
        "errno": errno,
        "msg": msg,
        "data": data 
    }
    return JsonResponse(message)
Пример #2
0
 def retrieveTransactions(user_id, days):
     # Retrieve wallet object for specific user
     if not Admin.getByUserID(user_id):
         wallet = Wallet.getByUserID(user_id)
     else:
         wallet = Wallet.getByUserID(-1)
     # Retrieve time now
     now = datetime.now()
     # Retrieve the transactions
     transactions = Transaction.objects.filter(wallet = wallet, \
               time__lte = now, \
               time__gte = now-dt.timedelta(days=days))
     return transactions
Пример #3
0
    def createTransaction(user_id, amount, detail):
        # Retrieve wallet object for specific user
        wallet = Wallet.getByUserID(user_id)

        new_transaction = Transaction(amount = amount, \
               time = datetime.now(), \
               detail = detail, \
               wallet =wallet)
        new_transaction.save()
        return new_transaction
Пример #4
0
def getBalance(request):
    # Initialize message variables
    errno = -1
    msg = ''
    data = {}
    # Retrieving tutor information
    try:
        if not request.user.is_authenticated():
            # Raise bad request response by user not logged in
            raise Exception(2, 'User not logged in')

        # Retrieve wallet from logged in user
        if not Admin.getByUsername(request.user.username):
            wallet = Wallet.getByUserID(request.user.id)
        else:
            wallet = Wallet.getByUserID(-1)
        if wallet == None:
            # Raise bad request response by wallet not found
            raise Exception(3, 'Wallet not found')

        balance = wallet.wallet_balance

        # Filling response body
        errno = 0
        msg = "Request succeeded"
        data = {
            "balance": balance
        }
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e

    # Generate response message
    message = {
        "errno": errno,
        "msg": msg,
        "data": data 
    }
    return JsonResponse(message)
Пример #5
0
def studentAddValue(request):
    # Initialize message variables
    errno = -1
    msg = ''
    data = {}
    # Retrieving tutor information
    try:
        # Try retrieving the amount to be added to the wallet
        try:
            request_json = json.loads(request.body)
            amount = request_json['amount']
        except:
            raise Exception(1, 'Bad request')

        if not request.user.is_authenticated():
            # Raise bad request response by user not logged in
            raise Exception(2, 'User not logged in')

        # Try retrieving student user from logged in user
        student = Student.getByUsername(request.user.username)
        if student == None:
        	# Raise bad request response by unknown user type
        	raise Exception(3, 'Not a student')

        # Increment the amount
        new_balance = Wallet.incrementBalance(student.user_profile.user.id, amount)
        # Create Transaction record for value added
        Transaction.createTransaction(student.user_profile.user.id, \
                                        amount, \
                                        'Value added by student ' + \
                                        str(student) + "("+student.username+")")

        # Filling response body
        errno = 0
        msg = "Request succeeded"
        data = {
        	"new_balance": new_balance
        }
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e

    # Generate response message
    message = {
        "errno": errno,
        "msg": msg,
        "data": data 
    }
    return JsonResponse(message)
Пример #6
0
def endSession():
	# Get time of invoke
	now = datetime.now()
	# Get all ending sessions
	ending_sessions = Booking.filterByEndTime(now)
	for session in ending_sessions:
		# Gather information of each party in the booking
		tutor = session.time_slot.tutor
		student = session.student

		if not session.coupon:
			# Calculate the amounts to be transferred
			tutor_fee = round(session.book_fee / Decimal(1.05), 1)
			commission = round(session.book_fee - Decimal(tutor_fee), 1)
			# Transfer Money, log the transaction and send notification
			# Tutor
			tutor_new_balance = Wallet.incrementBalance(tutor.user_profile.user.id, tutor_fee)
			Transaction.createTransaction(-1, \
									-tutor_fee, \
									"Payment to tutor : tutor id = " + str(session.time_slot.tutor.user_profile.user.id) + \
									" time slot = " + str(session.time_slot))
			Transaction.createTransaction(session.time_slot.tutor.user_profile.user.id, \
									tutor_fee, \
									"Tutorial fee from MyTutor : time slot = " + \
									str(session.time_slot))
			print(
				'(Tutor) An amount of tutorial fee has been transferred to you:\n' + \
					'Booking ID: ' + str(session.booking_id) + '\n' + \
					'Transferred Tutorial Fee: ' + str(tutor_fee) + '\n'
					'New wallet balance: ' + str(tutor_new_balance) + '\n'
			)
			# MyTutor
			mytutor_new_balance = Wallet.incrementBalance(-1, commission)
			Transaction.createTransaction(-1, \
									commission, \
									"Commission : student id = " + str(session.student.user_profile.user.id) + \
									" book tutor id = " + str(session.time_slot.tutor.user_profile.user.id) + \
									" time slot = " + str(session.time_slot))
			print(
				'(MyTutor) An amount of commision has been transferred to you:\n' + \
					'Booking ID: ' + str(session.booking_id) + '\n' + \
					'Transferred Commssion: ' + str(commission) + '\n' + \
					'New wallet balance: ' + str(mytutor_new_balance) + '\n'
			)
		else:
			# Calculate the amounts to be transferred
			tutor_fee = session
			commission = 0
			# Transfer Money, log the transaction and send notification
			# Tutor
			tutor_new_balance = Wallet.incrementBalance(tutor.user_profile.user.id, tutor_fee)
			Transaction.createTransaction(-1, \
									-tutor_fee, \
									"Payment to tutor : tutor id = " + str(session.time_slot.tutor.user_profile.user.id) + \
									" time slot = " + str(session.time_slot))
			Transaction.createTransaction(session.time_slot.tutor.user_profile.user.id, \
									tutor_fee, \
									"Tutorial fee from MyTutor : time slot = " + \
									str(session.time_slot))
			print(
				'(Tutor) An amount of tutorial fee has been transferred to you:\n' + \
					'Booking ID: ' + str(session.booking_id) + '\n' + \
					'Transferred Tutorial Fee: ' + str(tutor_fee) + '\n'
					'New wallet balance: ' + str(tutor_new_balance) + '\n'
			)

		# Invite student to make review
		print(
			'(Student) You have completed a tutorial session with the following tutor:\n' + \
			str(session.time_slot.tutor) + '\n' + \
			'Please go to his/her profile to leave a review!\n'
		)
	# Summary of this end all session task
	print(now, ':', len(ending_sessions), 'sessions have ended.\n')
Пример #7
0
def removeBooking(request):
    errno = -1
    msg = ''
    data = []

    try:
        try:
            # Retrieve request information
            request_json = json.loads(request.body)
            booking_id = request_json['booking_id']
        except:
            # Raise bad request response
            raise Exception(1, 'Bad request')

        if not request.user.is_authenticated():
            # Raise bad request response by user not logged in
            raise Exception(2, 'User not logged in')

        student_id = request.user.id
        if student_id == '':
            # Raise bad request response by getting empty user id
            raise Exception(3, 'Interievable user id')

        # Retrieve booking object
        bookingObject = Booking.getBooking(booking_id)
        if not bookingObject:
            # Raise bad request response by in valid booking id
            raise Exception(4, 'Invalid booking id')

        # If a booking can be retrieved...
        tutor_id = bookingObject.time_slot.tutor.tutor_id
        start_time = bookingObject.time_slot.start_time
        end_time = bookingObject.time_slot.end_time
        fee = bookingObject.book_fee
        newBalance = -1

        # Checking 24 hours time
        now = datetime.now()
        beforeStart = start_time + dt.timedelta(hours=-24)
        if now >= beforeStart:
            # Raise bad request response by booking falling in 24 hour range
            raise Exception(
                5,
                'Booking cannot be cancelled within 24 hours before start time'
            )

        # Mark the booking as canceled
        success = Booking.removeBooking(student_id, booking_id)
        if success == False:
            # Raise bad request response by unable to remove booking
            raise Exception(6, 'Failed to remove booking record')

        # Mark time slot as available and retrieve corrisponding time slot
        time_slot = TimeSlot.markCalendar(tutor_id, start_time, end_time,
                                          'booked', 'available')
        if not time_slot:
            # Raise bad request response by release time slot
            raise Exception(7, 'Fail to release available time slot')

        # If removal succeeded, add the fee paid by the student back to his wallet
        new_balance = Wallet.incrementBalance(student_id, fee)

        # Create transaction record for student
        Transaction.createTransaction(student_id, \
                                        fee, \
                                        "Cancel Refund from MyTutor : time slot = " + \
                                        str(time_slot))
        # Create transaction record for mytutor
        Transaction.createTransaction(-1, \
                                        -fee, \
                                        "Cancel Session : student id = " + str(student_id) + \
                                        " cancel tutor id = " + str(tutor_id) + \
                                        " time slot = " + str(time_slot))

        # Send email to student
        print('(Student) You have cancelled a session:\n' + \
                'Booking ID: ' + str(booking_id) + '\n' + \
                'Start Time: ' + str(start_time) + '\n' + \
                'End Time: ' + str(end_time) + '\n' + \
                'Refund Fee: ' + str(fee) + '\n' + \
                'Wallet Remaining Balance: ' + str(new_balance) + '\n'
        )
        # Send email to tutor
        print('(Tutor) A session is cancelled:\n' + \
                'Booking ID: ' + str(booking_id) + '\n' + \
                'Start Time: ' + str(start_time) + '\n' + \
                'End Time: ' + str(end_time) + '\n' + \
                'Tutorial Fee: ' + str(fee) + '\n'
        )

        # Filling response body
        errno = 0
        msg = "Request succeeded"
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e
    # Generate response message
    message = {"errno": errno, "msg": msg, "data": data}
    return JsonResponse(message)
Пример #8
0
def createBooking(request):
    errno = -1
    msg = ''
    data = []

    try:
        try:
            # Retrieve request information
            request_json = json.loads(request.body)
            tutor_id = request_json['tutor_id']
            fee = request_json['fee']
            coupon_code = request_json['coupon_code']
        except:
            # Raise bad request response
            raise Exception(1, 'Bad request')

        if not request.user.is_authenticated():
            # Raise bad request response by user not logged in
            raise Exception(2, 'User not logged in')

        student_user_id = request.user.id
        if student_user_id == '':
            # Raise bad request response by getting empty user id
            raise Exception(3, 'Interievable user id')

        if coupon_code != "" and not Coupon.isValid(coupon_code):
            # Raise bad request response by invalid coupon
            raise Exception(4, 'Invalid coupon')

        # Define start and end time for the the booking
        start_time = datetime.strptime(request_json['start_time'][:24],
                                       '%a %b %d %Y %H:%M:%S')
        end_time = datetime.strptime(request_json['end_time'][:24],
                                     '%a %b %d %Y %H:%M:%S')

        # Check pre-conditions
        conditions = Booking.checkPreConditions(student_user_id, tutor_id, fee,
                                                start_time, end_time)
        if conditions['errno'] != 0:
            # Raise bad request response by unmet pre-conditions
            raise Exception(conditions['errno'], conditions['msg'])

        # Calculate fee with commission
        if coupon_code == "":
            fee = round(fee * decimal.Decimal(1.05), 1)
        else:
            fee = fee

        # Create new book record
        new_balance = Wallet.decrementBalance(student_user_id, fee)
        time_slot = TimeSlot.markCalendar(tutor_id, start_time, end_time,
                                          'available', 'booked')
        booking_id = Booking.createBooking(student_user_id, fee, time_slot,
                                           coupon_code)

        # Create transaction record for student
        Transaction.createTransaction(student_user_id, \
                                -fee, \
                                "Booking Payment to MyTutor : time slot = " + \
                                str(time_slot))
        # Create transaction record for mytutor
        Transaction.createTransaction(-1, \
                                fee, \
                                "Pending fee : student id = " + str(student_user_id) + \
                                " pay for tutor id = " + str(tutor_id) + \
                                " time slot = " + str(time_slot))

        # Send 'email' to student
        print('(Student) You have booked a session:\n' + \
                'Booking ID: ' + str(booking_id) + '\n' + \
                'Start Time: ' + str(start_time) + '\n' + \
                'End Time: ' + str(end_time) + '\n' + \
                'Tutorial Fee: ' + str(fee) + '\n' + \
                'Wallet Remaining Balance: ' + str(new_balance) + '\n'
        )
        # Send 'email' to tutor
        print('(Tutor) A session is booked:\n' + \
                'Booking ID: ' + str(booking_id) + '\n' + \
                'Start Time: ' + str(start_time) + '\n' + \
                'End Time: ' + str(end_time) + '\n' + \
                'Tutorial Fee: ' + str(fee) + '\n'
        )

        # Filling response body
        errno = 0
        msg = "Request succeeded"
        data = {"booking_id": booking_id}
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e
    # Generate response message
    message = {"errno": errno, "msg": msg, "data": data}
    return JsonResponse(message)
Пример #9
0
def signup(request):
    # Initialize message variables
    errno = -1
    msg = ''
    data = {}

    # Retrieving signup information
    try:
        try:
            # Retrieve request information 
            request_json = json.loads(request.body)
            username = request_json['username']
            email = request_json['email']
            password1 = request_json['password1']
            password2 = request_json['password2']
            first_name = request_json['first_name']
            last_name = request_json['last_name']
            phone_number = request_json['phone_number']
            is_student = request_json['is_student']
            is_tutor = request_json['is_tutor']
            is_contracted = request_json['is_contracted']
            is_private = request_json['is_private']
            tutor_id = request_json['tutor_id']
            university = request_json['university']
            hourly_rate = request_json['hourly_rate']

        except:
            # Raise bad request response
            raise Exception(1, 'Bad request')

        if username == '':
            # Raise bad request response caused by empty username
            raise Exception(2, 'Empty username')

        if email == '':
            #Raise bad request response caused by empty email
            raise Exception(3, 'Empty email')

        if password1 != password2:
            # Raise bad request response caused by mismatch passwords
            raise Exception(4, 'Password mismatch')

        if password1 == '':
            # Raise bad request responce caused by empty password
            raise Exception(5, 'Empty password')

        if first_name == '':
            # Raise bad request response caused by empty first name
            raise Exception(6, 'Empty first name')

        if last_name == '':
            # Raise bad request response caused by empty last name
            raise Exception(7, 'Empty last name')

        if phone_number == '':
            # Raise bad request response caused by enpty phone number
            raise Exception(8, 'Empty phone number')

        if (not is_student and not is_tutor) or (is_contracted and is_private):
            # Raise bad request response created by invaliad user type
            raise Exception(9, 'Invalid user type')

        try:
            # Create user
            user = User.objects.create_user(username, email, password1)
            user.first_name = first_name
            user.last_name = last_name
            user.save()

            # Create user profile
            if is_student:
                # Create user profile as student
                profile = Student.create(user=user, \
                                            phone_number=phone_number)
            if is_tutor:
                # Determine tutor type
                tutor_type = "contracted"
                if is_contracted:
                    tutor_type = "contracted"
                elif is_private:
                    tutor_type = "private"

                # Create user profile as contracted tutor
                profile = Tutor.create(user=user, \
                                        phone_number=phone_number, \
                                        tutor_type=tutor_type, \
                                        tutor_id=tutor_id, \
                                        university=university, \
                                        hourly_rate=float(hourly_rate))

                # Create time slots for the newly created tutor
                # Define start time
                start_time = datetime.now()
                start_time = start_time.replace(second=0, microsecond=0)
                # Define end time
                end_time = start_time + dt.timedelta(days=7)
                # Batch create time slots for all tutor
                TimeSlot.rangeCreate(Tutor.getByUsername(profile.username), start_time, end_time, 'available')

            # Create wallet
            Wallet.create(wallet_balance=0, user_profile=profile)

        except Exception as e:
            # Raise bad request response caused by unable to create and save user
            print(e)
            user.delete()
            raise Exception(11, 'Unable to save or create user')

        # Log in user
        user = authenticate(username=username, password=password1)
        defaultLogin(request, user)

        # Filling response body
        errno = 0
        msg = "Request succeeded"
        data = {}
    except Exception as e:
        # Catch error responses raised
        try:
            errno, msg = e.args
        except:
            raise e

    # Generate response message
    message = {
        "errno": errno,
        "msg": msg,
        "data": data 
    }
    return JsonResponse(message)