コード例 #1
0
    def post(self):
        data = json_decode(self.request.body)
        schema = {
            # TODO get customer_id from session
            # and set like an additional(not required) field
            # if auth user is booking a room for third-part person
            'customer_id': {
                'type': 'integer',
                'required': True},
            'room_id': {
                'type': 'integer',
                'required': True},
            'from_date': {
                'type': 'string',
                'required': True},
            'to_date': {
                'type': 'string',
                'required': True},
        }
        if not self.valid_data(schema, data):
            return

        customer_id = data['customer_id']
        room_id = data['room_id']
        from_date = parse_date(data['from_date'])
        to_date = parse_date(data['to_date'])

        room = Room.get_available_between_dates_by_id(room_id, from_date.isoformat(), to_date.isoformat())

        if not room:
            self.set_response(
                content={'message': ('The room with id {} is not available '
                                     'for booking from {} to {}').format(room_id, from_date, to_date)},
                status=404)
            return

        # TODO add payment system
        # change on next step with payment system
        status = Status.get(name='reserved')

        # TODO get customer_id from session
        try:
            customer = Customer.get(id=customer_id)
        except Customer.DoesNotExist:
            self.set_response(
                {'message': 'Customer with id {} not found'.format(customer_id)},
                status=400)
            return

        booking = Booking.create(
            room=room,
            customer=customer,
            from_date=from_date,
            to_date=to_date,
            status=status)
        self.set_response(
            content=dict(booking=model_to_dict(booking)),
            status=201,
            headers={'Location': self.reverse_url('booking', booking.id)}
        )