Beispiel #1
0
def configuration_agenda(request, time_period='today'):
	tools = Tool.objects.exclude(configuration__isnull=True).exclude(configuration__exclude_from_configuration_agenda=True).values_list('id', flat=True)
	start = None
	end = None
	if time_period == 'today':
		start = naive_local_current_datetime().replace(tzinfo=None)
		end = naive_local_current_datetime().replace(hour=23, minute=59, second=59, microsecond=999, tzinfo=None)
	elif time_period == 'near_future':
		start = naive_local_current_datetime().replace(hour=23, minute=59, second=59, microsecond=999, tzinfo=None)
		if start.weekday() == 4:  # If it's Friday, then the 'near future' is Saturday, Sunday, and Monday
			end = start + timedelta(days=3)
		else:  # If it's not Friday, then the 'near future' is the next day
			end = start + timedelta(days=1)
	start = localize(start)
	end = localize(end)
	reservations = Reservation.objects.filter(start__gt=start, start__lt=end, tool__id__in=tools, self_configuration=False, cancelled=False, missed=False, shortened=False).exclude(additional_information='').order_by('start')
	tools = Tool.objects.filter(id__in=reservations.values_list('tool', flat=True))
	configuration_widgets = {}
	for tool in tools:
		configuration_widgets[tool.id] = tool.configuration_widget(request.user)
	dictionary = {
		'time_period': time_period,
		'tools': tools,
		'reservations': reservations,
		'configuration_widgets': configuration_widgets
	}
	return render(request, 'configuration_agenda.html', dictionary)
Beispiel #2
0
def reserve_tool(request):
    tool = Tool.objects.get(id=request.POST["tool_id"])
    customer = User.objects.get(id=request.POST["customer_id"])
    project = Project.objects.get(id=request.POST["project_id"])
    back = request.POST["back"]

    error_dictionary = {
        "back": back,
        "tool": tool,
        "project": project,
        "customer": customer
    }
    """ Create a reservation for a user. """
    try:
        date = parse_date(request.POST["date"])
        start = localize(
            datetime.combine(date, parse_time(request.POST["start"])))
        end = localize(datetime.combine(date, parse_time(request.POST["end"])))
    except:
        error_dictionary[
            "message"] = "Please enter a valid date, start time, and end time for the reservation."
        return render(request, "kiosk/error.html", error_dictionary)
    # Create the new reservation:
    reservation = Reservation()
    reservation.project = project
    reservation.user = customer
    reservation.creator = customer
    reservation.reservation_item = tool
    reservation.start = start
    reservation.end = end
    reservation.short_notice = determine_insufficient_notice(tool, start)
    policy_problems, overridable = check_policy_to_save_reservation(
        cancelled_reservation=None,
        new_reservation=reservation,
        user_creating_reservation=customer,
        explicit_policy_override=False,
    )

    # If there was a problem in saving the reservation then return the error...
    if policy_problems:
        error_dictionary["message"] = policy_problems[0]
        return render(request, "kiosk/error.html", error_dictionary)

    # All policy checks have passed.
    if project is None and not customer.is_staff:
        error_dictionary[
            "message"] = "You must specify a project for your reservation"
        return render(request, "kiosk/error.html", error_dictionary)

    reservation.additional_information, reservation.self_configuration = extract_configuration(
        request)
    # Reservation can't be short notice if the user is configuring the tool themselves.
    if reservation.self_configuration:
        reservation.short_notice = False
    reservation.save_and_notify()
    return render(request, "kiosk/success.html", {
        "new_reservation": reservation,
        "customer": customer
    })
Beispiel #3
0
def make_reservation(request):
    """ Create a reservation for a user. """
    try:
        date = parse_date(request.POST['date'])
        start = localize(
            datetime.combine(date, parse_time(request.POST['start'])))
        end = localize(datetime.combine(date, parse_time(request.POST['end'])))
    except:
        return render(
            request, 'mobile/error.html', {
                'message':
                'Please enter a valid date, start time, and end time for the reservation.'
            })
    item_type = ReservationItemType(request.POST['item_type'])
    item = get_object_or_404(item_type.get_object_class(),
                             id=request.POST.get('item_id'))
    # Create the new reservation:
    reservation = Reservation()
    reservation.user = request.user
    reservation.creator = request.user
    reservation.reservation_item = item
    reservation.start = start
    reservation.end = end
    if item_type == ReservationItemType.TOOL:
        reservation.short_notice = determine_insufficient_notice(item, start)
    else:
        reservation.short_notice = False
    policy_problems, overridable = check_policy_to_save_reservation(
        cancelled_reservation=None,
        new_reservation=reservation,
        user_creating_reservation=request.user,
        explicit_policy_override=False)

    # If there was a problem in saving the reservation then return the error...
    if policy_problems:
        return render(request, 'mobile/error.html',
                      {'message': policy_problems[0]})

    # All policy checks have passed.
    try:
        reservation.project = Project.objects.get(
            id=request.POST['project_id'])
    except:
        if not request.user.is_staff:
            return render(
                request, 'mobile/error.html',
                {'message': 'You must specify a project for your reservation'})

    reservation.additional_information, reservation.self_configuration = extract_configuration(
        request)
    # Reservation can't be short notice if the user is configuring the tool themselves.
    if reservation.self_configuration:
        reservation.short_notice = False
    reservation.save_and_notify()
    return render(request, 'mobile/reservation_success.html',
                  {'new_reservation': reservation})
Beispiel #4
0
def reserve_tool(request):
    tool = Tool.objects.get(id=request.POST['tool_id'])
    customer = User.objects.get(id=request.POST['customer_id'])
    project = Project.objects.get(id=request.POST['project_id'])
    back = request.POST['back']

    error_dictionary = {
        'back': back,
        'tool': tool,
        'project': project,
        'customer': customer,
    }
    """ Create a reservation for a user. """
    try:
        date = parse_date(request.POST['date'])
        start = localize(
            datetime.combine(date, parse_time(request.POST['start'])))
        end = localize(datetime.combine(date, parse_time(request.POST['end'])))
    except:
        error_dictionary[
            'message'] = 'Please enter a valid date, start time, and end time for the reservation.'
        return render(request, 'kiosk/error.html', error_dictionary)
    # Create the new reservation:
    reservation = Reservation()
    reservation.project = project
    reservation.user = customer
    reservation.creator = customer
    reservation.tool = tool
    reservation.start = start
    reservation.end = end
    reservation.short_notice = determine_insufficient_notice(tool, start)
    policy_problems, overridable = check_policy_to_save_reservation(
        None, reservation, customer, False)

    # If there was a problem in saving the reservation then return the error...
    if policy_problems:
        error_dictionary['message'] = policy_problems[0]
        return render(request, 'kiosk/error.html', error_dictionary)

    # All policy checks have passed.
    if project is None and not customer.is_staff:
        error_dictionary[
            'message'] = 'You must specify a project for your reservation'
        return render(request, 'kiosk/error.html', error_dictionary)

    reservation.additional_information, reservation.self_configuration = extract_configuration(
        request)
    # Reservation can't be short notice if the user is configuring the tool themselves.
    if reservation.self_configuration:
        reservation.short_notice = False
    reservation.save_and_notify()
    return render(request, 'kiosk/success.html', {
        'new_reservation': reservation,
        'customer': customer
    })
Beispiel #5
0
 def get_outage_data(
         title='',
         start: datetime = None,
         end: datetime = None,
         item_id: int = '',
         item_type: ReservationItemType = ReservationItemType.TOOL,
         outage: bool = False,
         frequency: str = '',
         interval: int = '',
         until: datetime = None):
     if not start:
         start = datetime.now()
     if not end:
         end = start.replace(hour=start.hour + 1)
     data = {
         'title':
         title,
         'start':
         calendar.timegm(start.utctimetuple()),
         'end':
         calendar.timegm(end.utctimetuple()),
         'item_id':
         item_id if item_id else '',
         'item_type':
         item_type.value,
         'recurring_outage':
         'on' if outage else '',
         'recurrence_frequency':
         frequency,
         'recurrence_interval':
         interval,
         'recurrence_until':
         localize(until).strftime('%m/%d/%Y') if until else ''
     }
     return data
Beispiel #6
0
	def get_end_date(self):
		return localize(datetime.combine(self.cleaned_data['end'], datetime.max.time()))
Beispiel #7
0
	def get_start_date(self):
		return localize(datetime.combine(self.cleaned_data['start'], datetime.min.time()))
Beispiel #8
0
def create_outage(request):
	""" Create an outage. """
	try:
		start, end = extract_times(request.POST)
		item_type = ReservationItemType(request.POST['item_type'])
		item_id = request.POST.get('item_id')
	except Exception as e:
		return HttpResponseBadRequest(str(e))
	item = get_object_or_404(item_type.get_object_class(), id=item_id)
	# Create the new reservation:
	outage = ScheduledOutage()
	outage.creator = request.user
	outage.category = request.POST.get('category', '')[:200]
	outage.outage_item = item
	outage.start = start
	outage.end = end

	# If there is a policy problem for the outage then return the error...
	policy_problem = check_policy_to_create_outage(outage)
	if policy_problem:
		return HttpResponseBadRequest(policy_problem)

	# Make sure there is at least an outage title
	if not request.POST.get('title'):
		dictionary = {
			'categories': ScheduledOutageCategory.objects.all(),
			'recurrence_intervals': recurrence_frequency_display,
			'recurrence_date_start': start.date(),
		}
		return render(request, 'calendar/scheduled_outage_information.html', dictionary)

	outage.title = request.POST['title']
	outage.details = request.POST.get('details', '')

	if request.POST.get('recurring_outage') == 'on':
		# we have to remove tz before creating rules otherwise 8am would become 7am after DST change for example.
		start_no_tz = outage.start.replace(tzinfo=None)
		end_no_tz = outage.end.replace(tzinfo=None)

		submitted_frequency = request.POST.get('recurrence_frequency')
		submitted_date_until = request.POST.get('recurrence_until', None)
		date_until = end.replace(hour=0, minute=0, second=0)
		if submitted_date_until:
			date_until = localize(datetime.strptime(submitted_date_until, '%m/%d/%Y'))
		date_until += timedelta(days=1, seconds=-1) # set at the end of the day
		by_week_day = None
		if submitted_frequency == 'DAILY_WEEKDAYS':
			by_week_day = (rrule.MO, rrule.TU, rrule.WE, rrule.TH, rrule.FR)
		elif submitted_frequency == 'DAILY_WEEKENDS':
			by_week_day = (rrule.SA, rrule.SU)
		frequency = recurrence_frequencies.get(submitted_frequency, rrule.DAILY)
		rules: Iterable[datetime] = rrule.rrule(dtstart=start, freq=frequency, interval=int(request.POST.get('recurrence_interval',1)), until=date_until, byweekday=by_week_day)
		for rule in list(rules):
			recurring_outage = ScheduledOutage()
			recurring_outage.creator = outage.creator
			recurring_outage.category = outage.category
			recurring_outage.outage_item = outage.outage_item
			recurring_outage.title = outage.title
			recurring_outage.details = outage.details
			recurring_outage.start = localize(start_no_tz.replace(year=rule.year, month=rule.month, day=rule.day))
			recurring_outage.end = localize(end_no_tz.replace(year=rule.year, month=rule.month, day=rule.day))
			recurring_outage.save()
	else:
		outage.save()

	return HttpResponse()
Beispiel #9
0
def make_reservation(request):
    # due to unexplained CSRF failures for users try a workaround
    http_origins = [
        'https://rea-demo.mri.psu.edu:8080',
        'https://rea-demo.mri.psu.edu:8888', 'https://leo.psu.edu'
    ]

    if request.META.get('HTTP_ORIGIN') in http_origins:
        origin = request.META.get('HTTP_ORIGIN')
        referer = str(origin) + "/new_reservation/" + str(
            request.POST.get('tool_id')) + "/" + str(
                request.POST['date']) + "/"

        if referer != request.META.get('HTTP_REFERER'):
            return render(request, 'mobile/error.html',
                          {'message': 'Unknown referer - request rejected'})
    else:
        return render(request, 'mobile/error.html',
                      {'message': 'Unknown origin - request rejected'})

    # Create a reservation for a user.
    try:
        date = parse_date(request.POST['date'])
        start = localize(
            datetime.combine(date, parse_time(request.POST['start'])))
        end = localize(datetime.combine(date, parse_time(request.POST['end'])))
    except:
        return render(
            request, 'mobile/error.html', {
                'message':
                'Please enter a valid date, start time, and end time for the reservation.'
            })
    tool = get_object_or_404(Tool, id=request.POST.get('tool_id'))
    # Create the new reservation:
    reservation = Reservation()
    reservation.user = request.user
    reservation.creator = request.user
    reservation.tool = tool
    reservation.start = start
    reservation.end = end
    reservation.short_notice = determine_insufficient_notice(tool, start)
    policy_problems, overridable = check_policy_to_save_reservation(
        request, None, reservation, request.user, False)

    # If there was a problem in saving the reservation then return the error...
    if policy_problems:
        return render(request, 'mobile/error.html',
                      {'message': policy_problems[0]})

    # All policy checks have passed.

    if request.user.is_staff:
        mode = request.POST['staff_charge']

        if mode == "self":
            # make a reservation for the user and don't add a record to the ReservationProject table
            active_projects = request.user.active_projects()

            if len(active_projects) == 1:
                reservation.project = active_projects[0]
            else:
                try:
                    reservation.project = Project.objects.get(
                        id=request.POST['project_id'])
                except:
                    msg = 'No project was selected.  Please return to the <a href="/calendar/">calendar</a> to try again.'
                    return render(request, 'mobile/error.html',
                                  {'message': msg})

        else:
            # add ReservationProject entries for the customers submitted by the staff member
            reservation_projects = {}
            reservation.save()

            for key, value in request.POST.items():
                if is_valid_field(key):
                    attribute, separator, index = key.partition("__")
                    index = int(index)
                    if index not in reservation_projects:
                        reservation_projects[index] = ReservationProject()
                        reservation_projects[index].reservation = reservation
                        reservation_projects[index].created = timezone.now()
                        reservation_projects[index].updated = timezone.now()
                    if attribute == "chosen_user":
                        if value is not None and value != "":
                            reservation_projects[
                                index].customer = User.objects.get(id=value)
                        else:
                            reservation.delete()
                            return HttpResponseBadRequest(
                                'Please choose a user for whom the tool will be run.'
                            )
                    if attribute == "chosen_project":
                        if value is not None and value != "" and value != "-1":
                            reservation_projects[
                                index].project = Project.objects.get(id=value)
                        else:
                            reservation.delete()
                            return HttpResponseBadRequest(
                                'Please choose a project for charges made during this run.'
                            )

            for r in reservation_projects.values():
                r.full_clean()
                r.save()

    else:
        try:
            reservation.project = Project.objects.get(
                id=request.POST['project_id'])
        except:
            if not request.user.is_staff:
                return render(request, 'mobile/error.html', {
                    'message':
                    'You must specify a project for your reservation'
                })

    reservation.additional_information, reservation.self_configuration, res_conf = extract_configuration(
        request)
    # Reservation can't be short notice if the user is configuring the tool themselves.
    if reservation.self_configuration:
        reservation.short_notice = False
    policy_problems, overridable = check_policy_to_save_reservation(
        request, None, reservation, request.user, False)
    reservation.save()
    for rc in res_conf:
        rc.reservation = reservation
        rc.save()
    return render(request, 'mobile/reservation_success.html',
                  {'new_reservation': reservation})