Esempio n. 1
0
def index(request):
  if not request.user.is_authenticated():
    return HttpResponseRedirect(reverse(user_login))

  context = {}
  if request.method == 'POST':
    form = ShiftForm(request.POST)
    context['form'] = form
    if form.is_valid():
      if form.cleaned_data['clear']:
        Shift.objects.filter(date=datetime.strptime(form.cleaned_data['date'],
                             "%Y-%m-%d")).delete()

      shift = Shift(
        person=form.cleaned_data['person'],
        date=datetime.strptime(form.cleaned_data['date'], "%Y-%m-%d"))
      shift.save()
      return HttpResponseRedirect(
        reverse(index))
  else:
    form = ShiftForm(initial={ "person": request.user.id })
    context['form'] = form

  template = 'index.html'
  return render_to_response(template, context_instance=RequestContext(request, context))
Esempio n. 2
0
def create_shift():
    # print request.
    shift_data = json.loads(request.data)
    shift = Shift()
    for k, v in shift_data.iteritems():
        if k == 'id': continue
        shift.__setattr__(k, v)
    db.session.add(shift)
    db.session.commit()
    return make_response()
Esempio n. 3
0
def create_shift():
    # Creates a new shift object within the database
    session = sc.Sqlite.get_session(url=SQLITE_URI)
    request_body = request.get_json()
    user_id = None
    start_time_epoch = None
    end_time_epoch = None

    if request_body.get('user_id'):
        user_id = request_body['user_id']
    if request_body.get('start_time'):
        start_time_epoch = request_body['start_time']
    if request_body.get('end_time'):
        end_time_epoch = request_body['end_time']

    user = session.query(User).filter(User.id == user_id).first()

    shift = Shift(user_id=user_id,
                  start_time=arrow.get(start_time_epoch).datetime,
                  end_time=arrow.get(end_time_epoch).datetime)

    input_start_time = int(start_time_epoch)
    input_end_time = int(end_time_epoch)

    for user_shift in user.shifts:
        if Helpers.check_shift_overlap(input_start_time,
                                       input_end_time,
                                       user_shift,
                                       shift_id=None):
            session.close()
            resp = Response(json.dumps({
                'error':
                'Start Time or End Time overlaps with existing shift'
            }),
                            status=400,
                            mimetype='application/json')
            return resp

    if not start_time_epoch or not end_time_epoch:
        session.close()
        resp = Response(json.dumps({
            'error':
            'Shift was not created, No start time or end time was provided'
        }),
                        status=400,
                        mimetype='application/json')
    elif not user_id:
        session.close()
        resp = Response(json.dumps(
            {'error': 'Shift was not created, No user id was provided'}),
                        status=400,
                        mimetype='application/json')
    else:
        session.add(shift)
        session.commit()
        session.close()
        resp = Response(json.dumps({'message': "Shift Created"}),
                        status=201,
                        mimetype='application/json')
    return resp
Esempio n. 4
0
 async def get(self):
     if not self.app.get('is_admin'):
         redirect(self.request, 'main')
     shifts = []
     shifts_db = await self.db.execute(Shift.select())
     for shift_db in shifts_db:
         shifts.append(await shift_db_to_dict(shift_db, self.db))
     return {'shifts': shifts}
def create_shifts(N):
    if not Shift.query.first():
        for _ in range(N):
            name = stringgenerator(20)
            shortname = "_" + name[:5]
            starttime = timegenerator()
            duration = durationgenerator()
            Sh = Shift(name=name,
                       shortname=shortname,
                       starttime=starttime,
                       duration=duration)
            db.session.add(Sh)
        db.session.commit()
Esempio n. 6
0
def makewholemonth():
    listOfShifts = []
    for i in range(7):
        listOfShifts.append(int(request.form[str(i)]))
    template = []
    days = [
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
        "Saturday"
    ]
    for i in range(len(listOfShifts)):
        thisDaysShifts = []
        for j in range(listOfShifts[i]):
            thisShift = []
            thisShiftRole = request.form[str(days[i] + "role" + str(j))]
            thisShiftStart = request.form[str(days[i] + "start" + str(j))]
            thisShiftEnd = request.form[str(days[i] + "end" + str(j))]
            thisShift.append(thisShiftRole)
            thisShift.append(thisShiftStart)
            thisShift.append(
                thisShiftEnd
            )  #Add the List of Role, Start, and End to a small list
            thisDaysShifts.append(
                thisShift
            )  #Add that small list to a list of all shifts for the day
        template.append(
            thisDaysShifts)  #Add the day's worth of shifts to the template
    year = request.form['year']
    month = request.form['month']
    listOfDays = makeCalendarList(int(year), int(month))
    roles = ['M', 'MA', 'A', 'C', 'R']
    for rowOfDays in listOfDays:
        for i in range(len(
                rowOfDays)):  #i represents the numerical equivalent of the day
            if rowOfDays[i] == "":
                continue
            else:
                for j in range(
                        listOfShifts[i]
                ):  #j represents each shift of each day, listOfShifts has each days number of shifts indexed
                    todayRole = roles.index(template[i][j][0])
                    todayStart = template[i][j][1]
                    todayEnd = template[i][j][2]
                    day = rowOfDays[i]
                    newShift = Shift(day, month, year, todayRole, todayStart,
                                     todayEnd)
                    db.session.add(newShift)
                    db.session.commit()

    table = makeWholeMonthShifts(template, int(year), int(month))
    return render_template("month.html", table=table)
Esempio n. 7
0
    def trigger_alert_to_user(self, service, user):
        """
        Clear out all service users and duty shifts, and disable all fallback users.
        Then add a single shift for this user, and add this user to users-to-notify.

        This should ensure we never alert anyone except the user triggering the alert test.
        """
        service.users_to_notify.clear()
        service.users_to_notify.add(user)
        Shift.objects.update(deleted=True)
        UserProfile.objects.update(fallback_alert_user=False)
        Shift(start=timezone.now() - timedelta(days=1),
              end=timezone.now() + timedelta(days=1),
              uid='test-shift',
              last_modified=timezone.now(),
              user=user).save()
        service.alert()
Esempio n. 8
0
    def trigger_alert_to_user(self, service, user, old_status, new_status):
        """
        Clear out all service users and duty shifts, and disable all fallback users.
        Then add a single shift for this user, and add this user to users-to-notify.

        This should ensure we never alert anyone except the user triggering the alert test.
        """
        with transaction.atomic():
            sid = transaction.savepoint()
            service.update_status()
            service.status_checks.update(active=False)
            service.overall_status = new_status
            service.old_overall_status = old_status
            service.last_alert_sent = None

            check = StatusCheck(name='ALERT_TEST')
            check.save()
            StatusCheckResult.objects.create(
                status_check=check,
                time=timezone.now(),
                time_complete=timezone.now(),
                succeeded=new_status == Service.PASSING_STATUS)
            check.last_run = timezone.now()
            check.save()
            service.status_checks.add(check)
            service.users_to_notify.clear()
            service.users_to_notify.add(user)
            service.unexpired_acknowledgements().delete()
            Shift.objects.update(deleted=True)
            UserProfile.objects.update(fallback_alert_user=False)
            Shift(
                start=timezone.now() - timedelta(days=1),
                end=timezone.now() + timedelta(days=1),
                uid='test-shift',
                last_modified=timezone.now(),
                user=user
            ).save()
            service.alert()
            transaction.savepoint_rollback(sid)
Esempio n. 9
0
def get_shifts(rshifts: List[Dict], timezone: str) -> List[Shift]:
    """Creates the necessary shift dict format
    Arguments:
        rshifts: rshifts
        timezone: timezone name
    Returns:
        list of Shifts
    """
    shifts = list()
    for shift in rshifts:
        begin = datetime.fromtimestamp(int(float(shift['begin']))).astimezone(pytz.timezone(timezone))
        end = datetime.fromtimestamp(int(float(shift['end']))).astimezone(pytz.timezone(timezone))
        shifts.append(
            Shift(
                id=int(shift['id']),
                begin=begin,
                end=end,
                capacity=shift['capacity'],
                position=shift['position']
            )
        )
    return shifts