Пример #1
0
def userViewBooking():
    userVoucher = int(raw_input("Voucher ID: "))
    Booking.printSingleRecord(userVoucher)

    choice = option("Press any key to go back!")
    if choice == "Y":
        menuselect()
    else:
        menuselect()
Пример #2
0
def book():

    date = request.form.get('date')
    time = request.form.get('time')
    booking = Booking(date, time)

    booking.booked_tables()
    available_times = booking.available_tables()

    return jsonify({'available_times': available_times})
Пример #3
0
def index():
    roomList = []
    for room in mongoRooms.getAll():
        roomList += [room['name']]
    bookingList = []
    for room in roomList:
        booking = Booking(roomId=room, lockDays = mongo.getBookedDays(room))
        # booking = Booking(roomId=room, name=room[0:3], mail=room[0:3]+'@gmail.com', phone='0781828688', lockDays = mongo.getBookedDays(room))
        bookingList += [booking]

    if request.method == "POST":
        print('Form was posted')
        print(request.form)
        # Retrieve the booking by roomId
        for booking in bookingList:
            if booking.roomId == request.form["roomId"]: break
        booking.name = request.form["name"]
        booking.mail = request.form["mail"]
        booking.phone = request.form["phone"]
        booking.startDate = request.form["stayDate"]  # Validate will assign startDate/endDate using it
        booking.yScroll = request.form["yScroll"]  # To keep the scroll position
        if booking.validate():
            registerNewBooking(booking)
            return render_template('confirm.html', booking=booking)
        else:
            print(booking.phone, booking.startDate, booking.endDate)
            return render_template('calendar.html', bookingList=bookingList)
    else: print('Not a post')
    return render_template('calendar.html', bookingList=bookingList)
Пример #4
0
def userBooking():
    User.printUserRecords()
    userID = int(raw_input("Please enter the id of the user to book: "))
    Services.printServices()
    servicesID = int(
        raw_input(
            "Please enter the id of the service chosen by the customer: "))

    userObject = User.getbyID(userID)
    serviceObject = Services.getbyID(servicesID)
    bookingObject = Booking()
    bookingObject.customerID = userObject.userid
    bookingObject.serviceID = serviceObject.servicesid
    bookingObject.voucher_id = Booking.generateVoucher()

    choice = option("Would you like to save changes")
    if choice == "Y":
        bookingObject.save()
        print("Event records successfully saved!")
        print("Voucher ID: {}".format(bookingObject.voucher_id))
        print("Please keep the voucher number for booking reference! ")
    else:
        start()
    choice = option("Would you like to add more booking")
    if choice == "Y":
        userBooking()
    else:
        userMenuArgs()
Пример #5
0
    def make_booking(self, customer, car, period, location):
        self._nbooking += 1
        self._customers.append(customer)
        self._cars.append(car)
        new_booking = Booking(customer, car, period, location)
        new_booking.calculate_fee()
        self._bookings.append(new_booking)

        print('~~~ Make ' + num2words(self._nbooking, to='ordinal') +
              ' booking ~~~')
        print('=== Booking Successful! ===')
        print('Booking details:')
        print(new_booking)
        print('=== Thank you for using Affordable Rentals ===')
        print('\n')
Пример #6
0
def AddBooking(userid):
    source = input("Enter Source Location : ")
    destination = input("Enter Destination Location : ")
    flights = list(
        filter(
            lambda x: x.GetSource() == source and x.GetDestination() ==
            destination, dl.GetFlightDetails()))

    print("Available Flights from ", source, " to ", destination, " are:")
    print()
    print(
        "Flight No.\t\tName\t\tSource\t\tDestination\t\tFare\t\tAvailability")
    print("-" * 100)
    for flight in flights:
        print(flight.GetFlightNo(), end="\t\t\t")
        print(flight.GetName(), end="\t\t")
        print(flight.GetSource(), end="\t\t")
        print(flight.GetDestination(), end="\t\t\t")
        print(flight.GetFare(), end="\t\t")
        availability = flight.GetAvailability().split(',')
        days = ['S', 'M', 'T', 'W', 'T', 'F', 'S']
        for i in range(availability.__len__()):
            if (availability[i] == '1'):
                print(days[i], end=' ')

    bookingid = int(input("Enter Booking Id : "))
    flightno = int(input("Enter Flight Number : "))
    bookingdate = input("Enter Booking Date (Y-M-D) : ")

    booking = Booking(bookingid, userid, flightno, bookingdate)
    if (dl.SaveBooking(booking)):
        print("Flight Booked Successfull")
    else:
        print("Please Try Again!!")
Пример #7
0
def add_b():
    try:
        if request.method=='POST':
            tid=request.form['tid']
            sid=request.form['sid']
            cemail=request.form['cemail']
            Session = sessionmaker(bind=eng)
            ses = Session()
            x=datetime.datetime.now()
            bdate=x.date()
            time=x.time()
           
            rb=ses.query(Booking).filter(and_(Booking.bdate==bdate,Booking.sid==sid)).count()
            
            print(rb)
            
            QueueNo=0            
            
            if rb==0:
                QueueNo=1
            elif rb>0:
                QueueNo=rb+1
            su = Booking(bdate,QueueNo,time,tid,sid,cemail)
            ses.add_all([su])
            ses.commit()           

           

            response={'status':1,"statusMessage":"Booking Successful","QueueNo":QueueNo}
    except Exception as e:
        response = {'status': 0, 'statusMessage': str(e)}
    return jsonify(response)
Пример #8
0
    def make_booking(self, customer, car, period, location):
        booking = Booking(customer, car, period, location)
        self._bookings.append(booking)

        print("=== Booking Successful! ===")
        print(booking)
        print("=== Thank you for using Affordable Rentals ===")
Пример #9
0
    def bookCab(self, usrid, src, dst):
        if usrid in self.users.keys():
            cab = self.searchCab(src)
            if (cab == None):
                print("All Cabs are busy, plz try in some time")
                return None
            else:
                fare = cab.getCost()
                dis = self.distance(src, dst)
                cost = fare * dis
                now = datetime.now()

                current_time = now.strftime("%H:%M:%S")
                ride = Booking(cab.getDriver(), current_time, src, dst, cost)

                #usr params
                usr = self.users[usrid]
                usr.setPay(cost)
                usr.setBookings(ride)

                #driver info
                driver = cab.getDriver()
                driver.addRide(ride)

                cab.setAvailability(False)
                return ride

        else:
            print("Not a valid user")
            return
    def create_booking(self, venueid, userid, startDate, endDate):
        """
        Create a new booking object and insert it into the database.
        startDate, endDate should be type `datetime.date`
        """

        # Verify the booking is allowed
        # -----------------------------

        # Check that the booking is allowed for the venue.
        venue_avails = db.venues.get_overlapping_availability(
            venueid, startDate, endDate)
        if not venue_avails:
            # No availabilities exist for that period
            raise BookingError(
                "Venue is not available for the requested date range.")

        # Check that the venue is not booked for the requested period.
        clashes = db.bookings.get_for_venue_overlapping(
            venueid, startDate, endDate)
        if clashes:
            raise BookingError(
                "The venue is already booked for the requested period.")

        # Booking is valid, insert into system
        # ------------------------------------

        new_bookingid = db.bookings.insert(venueid, userid, startDate, endDate)
        new_booking = Booking(venueid, userid, startDate, endDate)
        self.add_booking(new_bookingid, new_booking)

        return new_bookingid
Пример #11
0
    def init_synthethic_dataset(self):
        self.database = {}
        passengers  = [Passenger(name) for name in ["john green", \
                   "louie anderson", \
                   "liza koshy"]]
        bookings = [Booking(*booking) for booking in
            [("AMS", "ZRH", "10-Dec-2018"), \
              ("LHR", "AMS", "01-Jan-2019"), \
              ("BER", "ARN", "02-Mar-2019")]]
        flights = [Flight(*flight) for flight in \
            [("KLM", "AMS", "BSL", "10-Dec-2018", 200), \
             ("SWISS", "BSL", "ZRH", "10-Dec-2018", 100), \
             ("KLM", "LHR", "AMS", "01-Jan-2019", 300), \
             ("Eurowings", "BER", "ARN", "02-Mar-2019", 300)]]
        tickets = [Ticket(*ticket) for ticket in \
            [(passengers[0], flights[0], "economy"),
             (passengers[0], flights[1], "economy"),
             (passengers[1], flights[2], "business"), \
             (passengers[2], flights[3], "economy")]]
        bookings[0].add_ticket(tickets[0])
        bookings[0].add_ticket(tickets[1])
        bookings[1].add_ticket(tickets[2])
        bookings[2].add_ticket(tickets[3])

        self.database["passengers"] = passengers
        self.database["bookings"] = bookings
        self.database["flights"] = flights
        self.database["tickets"] = tickets
        self.database["name_to_tickets"] = {
            passenger.name: []
            for passenger in passengers
        }
        for ticket in tickets:
            self.database["name_to_tickets"][ticket.client.name] += [ticket]
Пример #12
0
def _checkMachineReservation(user, machine, dateTime):
  
  # set the time format to UTC time
   now = datetime.utcnow().isoformat() + 'Z'
   list_calendar = []
   for i in range(len(bookings["Records"])):
       bookid = bookings["Records"][i]["ResourceId"]
       bookname = bookings["Records"][i]["ResourceName"]
       userid = bookings["Records"][i]["CoworkerId"]
       userfullname = bookings["Records"][i]["CoworkerFullName"]
       bookfromtime = bookings["Records"][i]["FromTime"]
       booktotime = bookings["Records"][i]["ToTime"]
       
	   #create a Booking object
       book=Booking(bookid, bookname, usererid, userfullname,bookfromtime, booktotime)
       
	   #add the Booking object to the list
       list_calendar.append(booking)
  
   # compare the user, machine and dateTime with the Booking object
   for i in range(len(list_calendar)):
       book1=list_calendar[i]
       if book1.bookname==machine && book1.userfullname==user && now >book1.bookfromtime && now <booktotime:
	      return book1.resourceid
	    else:
		  return false
Пример #13
0
 def get_bookings(self):
     """
     Return a sorted list of all the bookings for this venue.
     """
     booking_rows = db.bookings.get_for_venue(self._id)
     return sorted([Booking(*row[1:]) for row in booking_rows],
                   key=lambda x: x.start_date)
Пример #14
0
def index_old():
    bookedDays = getBookedDays()
    form = getBookingForm()
    if form.validate_on_submit():
        booking = Booking(form.startDate.data[0:12], form.endDate.data[0:12], "Room to manage later", form.name.data, form.mail.data, form.phone.data)
        return render_template('confirmation.html', booking=booking)
    print(f'index bookedDays={bookedDays}')
    return render_template('index.html', form=form, bookedDays=bookedDays)
Пример #15
0
def bookinglist():
    bookingList = []
    roomColor = {'Elodie': '#9090E3', 'Léonie': '#7070E3', 'Mélodie': '#0A0AE3'}
    for bookingRecord in mongo.get({}):  #{'roomName': 'Elodie'}
        booking = Booking(roomId=bookingRecord['roomName'], startDate=bookingRecord['startDate'].strftime('%Y-%m-%d')+'T14:00:00', endDate=bookingRecord['endDate'].strftime('%Y-%m-%d')+'T10:00:00', name=bookingRecord['customerName'], mail=bookingRecord['customerMail'], phone=bookingRecord['customerPhone'], color=roomColor[bookingRecord['roomName']])
        bookingList += [booking]
    # return render_template('bookinglist.html', bookingList=bookingList)
    return render_template('bookingcalendar.html', bookingList=bookingList)
    def build(self):
        b = Booking()
        b.first_name = self.first_name
        b.last_name = self.last_name
        b.total_price = self.total_price
        b.deposit_paid = self.deposit_paid
        b.booking_dates = self.booking_dates
        b.additional_needs = self.additional_needs

        return b
Пример #17
0
 def __init__(self, booking: Booking):
     classrooms_source = booking.get_classroom_source()
     self._buildings_dict = {}  # type: Dict
     keys = []
     for building in classrooms_source.get_all_buildings():
         building_command = building.get_name().lower().replace(" ", "_")
         keys.append(building_command)
         self._buildings_dict[building_command] = building.get_identifier()
     super().__init__(booking, keys, False, exact_match=True)
Пример #18
0
 def __init__(self, booking: Booking):
     classrooms_source = booking.get_classroom_source()
     self._classrooms_dict = {}  # type: Dict
     keys = []
     for classroom in classrooms_source.get_all_classrooms():
         classroom_command = classroom.get_name().lower().replace(" ", "_")
         keys.append(classroom_command)
         self._classrooms_dict[classroom_command] = classroom.get_identifier()
     super().__init__(booking, keys, case_sensitive=False, exact_match=True)
Пример #19
0
def GetBookingDetail(bookingid):
    cur = con.cursor()
    cur.execute("SELECT * FROM BOOKING WHERE bookingid=" + bookingid)
    data = cur.fetchone()

    if (data == None):
        return None

    booking = Booking(data[0], data[1], data[2], data[3])
    return booking
Пример #20
0
 def __init__(self, booking: Booking):
     classrooms_source = booking.get_classroom_source()
     keys = []
     self._keyboard = None
     for building in classrooms_source.get_all_buildings():
         building_command = "/" + building.get_name().lower().replace(" ", "_")
         keys.append([KeyboardButton(building_command)])
     if len(keys) > 0:
         self._keyboard = ReplyKeyboardMarkup(keys)
     super().__init__(booking, ["buildings"], False, exact_match=True)
Пример #21
0
def GetBookingDetails():
    cur = con.cursor()
    cur.execute("SELECT * FROM BOOKING")
    data = con.fetchall()

    bookings = []
    for record in data:
        booking = Booking(data[0], data[1], data[2], data[3])
        bookings.append(user)
    return bookings
Пример #22
0
    def generate_alternatives(self, slot, booking):
        current_pax = booking.pax
        alternatives = []

        while ((not alternatives) and (current_pax > 0)):
            for alt_slot in range(max(0, slot - 1), min(slot + 2, 12)):
                alt_booking = Booking(booking.customer_number, current_pax)
                alternatives.append((alt_slot, alt_booking))
            alternatives = self.__filter_unavailable(alternatives)
            current_pax -= 1

        self.__sort_slot_closer_to_init(alternatives, slot)
        return alternatives
Пример #23
0
    def test_booking(self):
        class _CarStub:
            def calculatePrice(self, *_, **__):
                return 999

        carStub = _CarStub()
        booking = Booking(1, carStub, 3, 4)

        assert (booking.customer == 1)
        assert (booking.car == carStub)
        assert (booking.period == 3)
        assert (booking.location == 4)
        assert (booking.price == 999)
Пример #24
0
    def make_booking(self, customer, car, start_date,end_date, start_location, end_location):
        
        try:
            Check = check_booking_error(start_date,end_date, start_location, end_location)
        except BookingError as err:
            return err
        else:
            
            location = Location(start_location, end_location)
            
            d1 = datetime.strptime(start_date, "%Y-%m-%d")
            d2 = datetime.strptime(end_date, "%Y-%m-%d")
            period = abs((d2 - d1).days) + 1
        
            new_booking = Booking(customer, car, period, location)
            new_booking.apply()
            print('=== Booking Successful! ===')
            print('Booking details:')
            print(new_booking)
            print('=== Thank you for using Affordable Rentals ===')
        
            self._bookings.append(new_booking)

            return new_booking
Пример #25
0
    def ParseRawData(self, reader):
        for line in reader:
            # Ignore lines that arent booked yet
            if line[16] == "Umsatz vorgemerkt":
                continue

            # Delete unnecessary whitespaces with a regex
            for i, element in enumerate(line):
                line[i] = re.sub(' +', ' ', element)

            booking = Booking(line[self.dateColumn], \
                              line[self.typeColumn], \
                              line[self.nameColumn], \
                              line[self.purposeColumn], \
                              line[self.valueColumn])
            self.bookings.append(booking)
 def create(self,destination,TimeOfFlight,TypeOfFlight,Price,SitNumber,name,flightno,PhoneNo):
     avalFlight = self.flightmg.find(flightno)
     avalpassanger = self.passangermg.find(PhoneNo)
     
     if avalpassanger == None:
         print("Passanger Not available")
         return False
     else:
         if avalFlight == None:
             print("Flight Not available")
             return False
     
         else:
             info = Booking(destination,TimeOfFlight,TypeOfFlight,SitNumber,name,avalFlight)
             self.Bookings.append(info)
             return True
    def get_booking(self, bookid):
        """
        Find a booking in the stored bookings or from the database.

        Returns `None` if a booking cannot be found in the system nor database
        """
        if bookid in self._bookings:
            return self._bookings[bookid]
        else:
            b = db.bookings.get(bookid)
            if b is not None:
                book = Booking(*b[1:])
                self.add_booking(bookid, book)
                return book
            else:
                return None
Пример #28
0
    def check_fee(self, customer, car, date1, date2, location1, location2):
        '''
        Task 4
        '''
        start_date = datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.strptime(end_date, "%Y-%m-%d")
       
        try:
          check_booking_error(start_date, end_date, start_location, end_location)
        except BookingError as err:
          print(err)
          return

        period = end_date - start_date
        booking = Booking(customer, car, period.days, Location(start_location, end_location))
        
        return booking.fee
Пример #29
0
    def book(self, hour, pax, customer_number, alternatives):
        """Returns true if booking was successful, otherwise returns false and
        populates alternatives list with alternative free bookings

        hour - booking start hour in 24h system
        pax - number of people in booking
        customer_number - customer telephone number
        alternatives - list variable to store alternative booking options"""

        slot = self.hour_to_slot(hour)
        initial_booking = Booking(customer_number, pax)

        if self.tables.check_available(slot, initial_booking):
            self.tables.book(slot, initial_booking)
            return True
        else:
            alt = self.generate_alternatives(slot, initial_booking)
            self.__copy_list(alt, alternatives)
            return False
Пример #30
0
    def make_booking(self, customer, car, start_date, end_date, start_location, end_location):
        '''
        Task 3
        '''
        try:
          start_date = datetime.strptime(start_date, "%Y-%m-%d")
        except:
          raise BookingError({'start_date': 'Invalid start date'})
        
        try:
          end_date = datetime.strptime(end_date, "%Y-%m-%d")
        except:
          raise BookingError({'end_date': 'Invalid end date'})
          
        errors = check_booking_error(start_date, end_date, start_location, end_location)
        if errors:
          raise BookingError(errors)

        period = (end_date - start_date).days + 1
        booking = Booking(customer, car, period, Location(start_location, end_location))
        car.add_booking(booking)
        self._bookings.append(booking)
        return [booking]
Пример #31
0
def parse_bookings(csv_file, offset_header, index_date, index_recipient,
                   index_reference, index_amount, date_format):
    with open(csv_file, newline='') as csvfile:
        csv_reader = csv.reader(csvfile, delimiter=';')

        rows = []
        for row in csv_reader:
            rows.append(row)

        # Skip Header Lines
        rows = rows[offset_header:]

        bookings = []
        for row in rows:
            bookings.append(
                Booking(
                    datetime.strptime(row[index_date], date_format),
                    row[index_recipient], row[index_reference],
                    float(row[index_amount].replace(".", "").replace(",",
                                                                     "."))))

        print(f"Parsed {len(bookings)} bookings from {csv_file}")
        return bookings
Пример #32
0

class PriceCalculator:
    def __init__(self, booking, strategy):
        self.booking = booking
        self.strategy = strategy

    def prepare_passengers(self):
        self.strategy.process_passengers(self.booking)

if __name__ == '__main__':
    passanger1 = Passanger('adult')
    passanger2 = Passanger('infant')
    passanger3 = Passanger('child')

    booking1 = Booking(100.0, 10.0, 20.0, [passanger1, passanger2, passanger3])
    strategy1 = EqualPriceStrategy()

    PriceCalculator(booking1, strategy1).prepare_passengers()
    print(booking1.get_passangers())

    passanger4 = Passanger('adult')
    passanger5 = Passanger('infant')
    passanger6 = Passanger('child')

    booking2 = Booking(100.0, 10.0, 20.0, [passanger4, passanger5, passanger6])
    strategy2 = AgeBasedStrategy()

    PriceCalculator(booking2, strategy2).prepare_passengers()
    print(booking2.get_passangers())