def rental_revenue():
    """
    Defines URL/route '/dashboard/data/revenue' which displays the daily
    revenue from renting cars. Retrieves booking history from cloud database
    and calculates amount of time cars have been rented for and resultant
    revenue. 

    :return: revenue data in json form
    :rtype: flask response object
    """
    bk_svc = BookingService()
    bookings = bk_svc.get_all_with_cars()
    counter = Counter()
    for bk in bookings:
        bk_svc.transform_date(bk)
        bk_svc.transform_time(bk)
        delta = bk["date_return"] - bk["date_booking"] + bk["time_return"] - bk["time_booking"]
        hours = delta.seconds / timedelta(hours=1).seconds
        date_s = bk_svc.gen_date_str(bk["date_return"])
        counter[date_s] += hours * bk["cost_hour"]
    data = []
    for k, n in counter.items():
        data.append({"date": k, "revenue": n})
    data.sort(key=lambda d: d["date"])
    # accumulative
    for i in range(1, len(data)):
        data[i]['revenue'] += data[i-1]["revenue"]
    return jsonify(data)
def rental_history(car_id):
    """
    Defines URL/route: '/cars/car ID/bookings' and retrieves booking 
    history for car associated with Car ID, to display rental history.

    :param car_id: ID/primary key of cars in car table
    :type car_id: int
    :return: html for rental history of car
    :rtype: flask template
    """
    '''display all bookings made for specific car'''
    service = BookingService()
    bookings = service.get_bookings_for_car(car_id)
    return render_template('carHistory.html', car_id=car_id, bookings=bookings)
    def get_detail(self, columns=None, value=None):
        if columns == "error":
            return self.create_response({
                'code': 400,
                'messages': 'Bad Request'
            })

        data = {'code': 200, 'message': 'Success', 'data': {}, 'total_data': 0}

        data_sql = BookingService().generate_booking_detail(columns, value)

        data['data'] = data_sql.get('data')
        data['total_data'] = data_sql.get('total_rows')

        return self.create_response(data)
    def get_list(self):
        data = {'code': 200, 'message': 'Success', 'data': [], 'total_data': 0}

        data_model = {
            'type': 'list',
            'pagination': True,
            'filter': self.request.args
        }

        data_sql = BookingService().generate_booking_list(data_model)

        data['data'] = data_sql.get('data')
        data['total_data'] = data_sql.get('total_rows')

        return self.create_response(data)
    def get_booking_code(self):
        data = {'code': 200, 'message': 'Success', 'data': {}}

        data['data'] = {
            'booking_code': BookingService().generate_booking_code()
        }

        return self.create_response(data)
 def test_get_bookings_for_car(self):
     '''test that POST is used and correct values are returned
     '''
     from app.services.booking_service import BookingService
     expected = [self.bookings[0], self.bookings[3]]
     with patch.object(BookingService, "post",
                       return_value=expected) as mock_post:
         result = BookingService().get_bookings_for_car(1)
         self.assertEqual(expected, result)
 def test_transform_date(self):
     '''confirm that date string is tranformed into date object
     '''
     from app.services.booking_service import BookingService
     booking = {**self.bookings[0]}
     booking['date_booking'] = "2020-02-02"
     booking["date_return"] = '2020-03-03'
     BookingService().transform_date(booking)
     self.assertEqual(date(2020, 2, 2), booking["date_booking"])
     self.assertEqual(date(2020, 3, 3), booking["date_return"])
 def test_search_bookings(self):
     '''confirm that correct query is passed to `post` and return value is propagated
     '''
     from app.services.booking_service import BookingService
     with patch.object(BookingService,
                       "post",
                       return_value=self.bookings[:2]):
         result = BookingService().search_bookings(
             {"username": "******"})
         self.assertEqual(self.bookings[:2], result)
 def test_get_all_with_cars(self):
     '''confirm that car info is returned along with booking info
     '''
     from app.services.booking_service import BookingService
     bookings = [self.bookings[0], self.bookings[3]]
     for b in bookings:
         b.update(self.cars[0])
     with patch.object(BookingService, "get", return_value=bookings):
         result = BookingService().get_all_with_cars()
         self.assertEqual(bookings, result)
 def test_transform_time(self):
     '''confirm that time string is converted into timedelta object
     '''
     from app.services.booking_service import BookingService
     booking = {**self.bookings[0]}
     booking["time_booking"] = "00:02:00"
     booking["time_return"] = "03:00:01"
     BookingService().transform_time(booking)
     self.assertEqual(timedelta(seconds=2 * 60), booking['time_booking'])
     self.assertEqual(timedelta(seconds=3 * 3600 + 1),
                      booking["time_return"])
    def get_availability_code(self, value=None):
        if not value:
            return self.create_response({
                'code': 400,
                'messages': 'Bad Request'
            })

        data = {'code': 200, 'message': 'Success', 'data': {}, 'total_data': 0}

        # Check availability booking code
        availability = BookingService().check_availability_booking_code(value)

        data['data'] = availability['data']
        data['total_data'] = availability['total_data']

        return self.create_response(data)
    def update_data(self, booking_code=None):
        if not booking_code:
            return self.create_response({
                'code': 400,
                'messages': 'Bad Request'
            })

        data = {'code': 200, 'message': 'Success', 'total_data': 0}

        request_data = self.request.json

        payment_status = request_data.get('payment_status')

        queries = "payment_status='{}'".format(payment_status)

        data_model = {'code': booking_code, 'data': queries}

        BookingService().update_booking(data_model)

        return self.create_response(data)
    def create_data(self):
        data = {'code': 200, 'message': 'Success', 'total_data': 0}

        request_data = self.request.json

        booking_type = request_data.get('type')
        booking_code = request_data.get('code')
        user_id = request_data.get('user_id')
        item = request_data.get('item')
        checkin_date = request_data.get('checkin_date')
        checkout_date = request_data.get('checkout_date')
        price = request_data.get('price')
        quantity = request_data.get('quantity')
        price_total = request_data.get('price_total')
        payment_type = request_data.get('payment_type')
        payment_code = request_data.get('payment_code')
        payment_status = request_data.get('payment_status')
        passenger_manifest = request_data.get('passenger_manifest')

        if passenger_manifest:
            passenger_manifest = json.dumps(passenger_manifest)

        data_model = {
            'type': booking_type,
            'code': booking_code,
            'user_id': user_id,
            'item': item,
            'checkin_date': checkin_date,
            'checkout_date': checkout_date,
            'price': price,
            'payment_type': payment_type,
            'payment_code': payment_code,
            'payment_status': payment_status,
            'quantity': quantity,
            'price_total': price_total,
            'passenger_manifest': passenger_manifest
        }

        BookingService().create_booking(data_model)

        return self.create_response(data)
def car_usage():
    """
    Defines URL/route '/dashboard/data/car_usage' which displays number 
    of cars being used each day. Retrieves bookings data from cloud 
    database and transforms for display in graph.

    :return: car usage data in json form
    :rtype: flask Response object 
    """
    bk_svc = BookingService()
    bookings = bk_svc.search_bookings({})
    counter = Counter()
    for bk in bookings:
        bk_svc.transform_date(bk)
        curr = bk["date_booking"]
        while curr <= bk["date_return"]:
            date_s = bk_svc.gen_date_str(curr)
            counter[date_s] += 1
            curr += timedelta(days=1)
    data = []
    for k, n in counter.items():
        data.append({"date": k, "n_cars": n})
    return jsonify(data)
 def test_gen_date_str(self):
     '''confirm that the method generates the correct date string from date object
     '''
     from app.services.booking_service import BookingService
     result = BookingService().gen_date_str(date(2020, 1, 2))
     self.assertEqual("2020-01-02", result)