Ejemplo n.º 1
0
def get_quiz(request):
    if request.method == 'GET':
        recent_score = get_curr_profile(request).menu_score
        if recent_score is not None:
            logger.warning('recent score detected: %d', recent_score)
            return HttpResponseBadRequest(
                'You\'ve recently done menu test with score %d.' %
                recent_score)
        if request.user.profile.role == 'MA':
            quiz = Quiz.objects.filter(
                business=get_curr_business(request)).first()
            is_preview = True
            if not quiz:
                return HttpResponse(status=503)
        else:
            quiz = Quiz.objects.filter(business=get_curr_business(request), role=get_curr_profile(request).role). \
                first()
            is_preview = False
            if not quiz:
                return HttpResponseNotFound(
                    'There are not any quizzes for %s yet' %
                    get_curr_profile(request).get_role_display())
        response = quiz.serialize(is_preview)

        logger.info('data is ' + str(response))
        return JsonResponse(response)

    return wrong_method(request)
Ejemplo n.º 2
0
def generate_shifts(request):
    def execute_shift_generation(business):

        business.set_shift_generation_pending()
        business.save()

        if settings.CELERY:
            tasks.generate_next_week_shifts.delay(
                business.business_name,
                settings.SHIFT_GENERATION_ALGORITHM_LEVEL)
        else:
            tasks.generate_next_week_shifts(
                business.business_name,
                settings.SHIFT_GENERATION_ALGORITHM_LEVEL)

    if request.method == 'POST':
        next_week_slots = ShiftSlot.objects.filter(
            week=get_next_week_num(), business=get_curr_business(request))
        if not len(next_week_slots):
            messages.error(request, 'No slots next week !')
            return HttpResponseBadRequest('No slots next week !')
        else:
            execute_shift_generation(get_curr_business(request))

            create_manager_msg(
                recipients=get_curr_business(request).get_employees(),
                subject='New Shifts',
                text='Your manager has generated shifts for next week',
                wait_for_mail_results=False)
            messages.success(request,
                             'Shifts generation requested successfully')
            return HttpResponse('Request triggered')

    return wrong_method(request)
Ejemplo n.º 3
0
def manager_home(request):

    curr_manager = request.user.profile

    pending_requests_cnt = get_employee_requests_with_status(
        curr_manager, 'P').count()

    curr_week_string = get_current_week_string()
    next_week_sunday = get_next_week_sunday()

    deadline_date = get_current_deadline_date_string(
        curr_manager.business.deadline_day)
    logger.info('deadline date is %s', deadline_date)

    is_finish_slots = curr_manager.business.slot_request_enabled
    logger.info('are slot adding is finished? %s', is_finish_slots)

    context = {
        'requests_cnt': pending_requests_cnt,
        'curr_week_str': curr_week_string,
        'start_date': next_week_sunday,
        'current_start_date': get_curr_week_sunday(),
        'deadline_date': deadline_date,
        'shifts_generated': get_curr_business(request).shifts_generated,
        'logo_conf': get_logo_conf()
    }
    return render(request, "manager/home.html", context)
Ejemplo n.º 4
0
def get_leader_board(request):
    curr_business = get_curr_business(request)

    logger.info('fetching leaders of business %s', curr_business.pk)
    current_leaders = LeaderBoardHandler(curr_business).fetch()

    return JsonResponse(current_leaders, safe=False)
Ejemplo n.º 5
0
def get_calendar_current_week_shifts(request):
    if request.method == 'GET':
        shifts_json = []

        current_week_slots = ShiftSlot.objects.filter(
            week=get_curr_week_num(), business=get_curr_business(request))

        for slot in current_week_slots:
            if not slot.was_shift_generated():
                continue

            bg_color, text_color = slot.get_calendar_colors(
                get_curr_profile(request))

            jsoned_shift = json.dumps({
                'id': str(slot.id),
                'title': slot.name,
                'start': slot.start_time_str(),
                'end': slot.end_time_str(),
                'backgroundColor': bg_color,
                'textColor': text_color
            })
            shifts_json.append(jsoned_shift)
        return JsonResponse(json.dumps(shifts_json), safe=False)

    return wrong_method(request)
Ejemplo n.º 6
0
def get_next_week_slots_calendar(request):
    shifts_json = []
    slot_id_to_constraints_dict = {}

    next_week_slots = ShiftSlot.objects.filter(
        week=get_next_week_num(),
        business=get_curr_business(request)).select_related('shift')
    for slot in next_week_slots:
        text_color, title = slot.get_color_and_title()
        jsoned_shift = json.dumps({
            'id':
            str(slot.id),
            'title':
            title,
            'start':
            slot.start_time_str(),
            'end':
            slot.end_time_str(),
            'backgroundColor':
            '#205067' if not slot.was_shift_generated() else 'blue',
            'textColor':
            text_color
        })
        shifts_json.append(jsoned_shift)
        slot_id_to_constraints_dict[slot.id] = slot.constraints
    shifts_json.append(json.dumps(slot_id_to_constraints_dict))
    logger.debug('jsoned shifts are %s', shifts_json)
    return JsonResponse(shifts_json, safe=False)
Ejemplo n.º 7
0
def broadcast_message(request):
    if request.method == 'POST':
        broadcast_form = BroadcastMessageForm(request.POST)

        if broadcast_form.is_valid():
            recipients = get_curr_business(request).get_employees()

            new_manager_msg = broadcast_form.save(commit=False)

            try:
                create_manager_msg(recipients=recipients,
                                   subject=new_manager_msg.subject,
                                   text=new_manager_msg.text,
                                   wait_for_mail_results=False)
            except EmailWaitError as e:
                return HttpResponseServerError(e.message)

            messages.success(request, message='Broadcast message created')
            return HttpResponseRedirect('/')
        else:
            logger.error('broadcast form is not valid')
            form = BroadcastMessageForm()
            messages.error(request,
                           message='couldn\'t send broadcast message: %s' %
                           str(form.errors.as_text()))
            return HttpResponseRedirect('/')
    else:  # method is GET
        form = BroadcastMessageForm()
        return render(request, 'ajax_form.html', {'form': form})
Ejemplo n.º 8
0
def get_quiz_roles(request):
    roles_response = dict(
        business_name=get_curr_business(request).business_name)
    roles_list = []
    for role in EmployeeProfile.get_employee_roles():
        roles_list.append(dict(name=role, imageUrl=static('imgs/bt.jpeg')))
    roles_response['roles'] = roles_list
    return JsonResponse(roles_response)
Ejemplo n.º 9
0
def get_specific_quiz(request, role):
    if request.method == 'GET':
        try:
            short_role = EmployeeProfile.get_roles_reversed()[role]
        except KeyError:
            return HttpResponseBadRequest('no such role: %s' % role)

        quiz = Quiz.objects.filter(business=get_curr_business(request),
                                   role=short_role).first()

        if not quiz:
            quiz = Quiz.objects.create(role=short_role,
                                       business=get_curr_business(request))

        response = quiz.serialize(True)
        logger.info('data is ' + str(response))
        return JsonResponse(response)
    return wrong_method(request)
Ejemplo n.º 10
0
def add_shift_slot(request):
    business = get_curr_business(request)

    slot_names_generator = ((name, name)
                            for name in get_business_slot_names(business))

    if request.method == 'POST':
        slot_form = ShiftSlotForm(request.POST,
                                  business=business,
                                  names=slot_names_generator)
        if slot_form.is_valid():
            data = slot_form.cleaned_data
            constraint_creator = SlotConstraintCreator(data)
            slot_creator = SlotCreator(business, data, constraint_creator)

            try:
                slot_creator.create()
                messages.success(request, 'slot form was ok')
                return HttpResponseRedirect('/')
            except ObjectDoesNotExist as e:
                logger.error('object does not exist: %s', e)
                return HttpResponseBadRequest('object does not exist: %s' %
                                              str(e))
        else:
            day = request.POST.get('day')
            slot_holiday = get_holiday(get_curr_year(), day,
                                       get_next_week_num())
            return render(request,
                          'manager/new_shift.html', {
                              'form': slot_form,
                              'week_range': get_next_week_string(),
                              'holiday': slot_holiday
                          },
                          status=400)
    else:
        day = request.GET.get('day', '')
        start_hour = request.GET.get('startTime', '')

        slot_holiday = get_holiday(get_curr_year(), day, get_next_week_num())

        form = ShiftSlotForm(initial={
            'day': day,
            'start_hour': start_hour.replace('-', ':')
        },
                             business=business,
                             names=slot_names_generator)

        return render(
            request, 'manager/new_shift.html', {
                'form': form,
                'week_range': get_next_week_string(),
                'holiday': slot_holiday,
                'logo_conf': get_logo_conf()
            })
Ejemplo n.º 11
0
def get_prev_shifts(request):
    curr_emp = get_curr_profile(request)
    curr_business = get_curr_business(request)
    is_manager = request.user.groups.filter(name='Managers').exists()
    if is_manager:
        prev_shifts = curr_business.get_previous_shifts()
    else:
        prev_shifts = curr_emp.get_previous_shifts()
    if len(prev_shifts) == 0:
        logger.warning('no previous shifts for emp %s', request.user.username)
        return HttpResponseBadRequest('No previous shifts was found...')
    logger.info('Found %d previous shifts', len(prev_shifts))

    return render(request, 'previous_shifts.html', {
        'prev_shifts': prev_shifts,
        'manager': is_manager
    })
Ejemplo n.º 12
0
def is_finish_slots(request):
    curr_business = get_curr_business(request)
    if request.method == 'POST':
        action = request.POST.get('isFinished')
        curr_business.slot_request_enabled = True if action == 'true' else False
        curr_business.save()

        recp = curr_business.get_employees()
        is_enabled = 'enabled' if curr_business.slot_request_enabled else 'disabled'
        text = 'Your manager has %s shifts requests for next week.' % is_enabled
        create_manager_msg(recipients=recp,
                           subject='Shift requests are now %s' % is_enabled,
                           text=text,
                           wait_for_mail_results=False)

        logger.info('saved business finished slots status to: %s',
                    curr_business.slot_request_enabled)
        return HttpResponse('ok')
    logger.info('returning the business finished slots status which is: %s',
                curr_business.slot_request_enabled)
    return HttpResponse(curr_business.slot_request_enabled)
Ejemplo n.º 13
0
def submit_slots_request(request):
    next_week_no = get_next_week_num()
    curr_business = get_curr_business(request)
    curr_profile = get_curr_profile(request)
    start_week, end_week = get_current_week_range()
    existing_request = ShiftRequest.objects.filter(
        employee=curr_profile, submission_time__range=[start_week,
                                                       end_week]).last()
    if request.method == 'GET':
        form = SelectSlotsForm(instance=existing_request,
                               business=curr_business,
                               week=next_week_no)
        existing_slots = existing_request.requested_slots.all(
        ) if existing_request else []
        request_enabled = curr_business.slot_request_enabled
        return render(
            request, 'employee/slot_list.html', {
                'form': form,
                'existing_slots': existing_slots,
                'request_enabled': request_enabled
            })
    else:
        form = SelectSlotsForm(request.POST,
                               business=curr_business,
                               week=next_week_no,
                               instance=existing_request)
        if form.is_valid():
            shifts_request = save_shifts_request(form, curr_profile)

            logger.info('slots chosen are: %s',
                        str(shifts_request.requested_slots.all()))
            messages.success(request, 'request saved')
        else:
            logger.error('couldn\'t save slots request: %s',
                         str(form.errors.as_text()))
            messages.error(request,
                           message='couldn\'t save slots request: %s' %
                           str(form.errors.as_text()))
        return HttpResponseRedirect('/')
Ejemplo n.º 14
0
def handle_employee_request(request):
    if request.method == 'POST':
        emp_request_id = request.POST.get('emp_request_id')
        new_status = request.POST.get('new_status')

        emp_request = EmployeeRequest.objects.get(id=emp_request_id)
        emp_request.status = new_status
        emp_request.save()

        logger.info('creating manager msg in response to the employee request')
        try:
            create_manager_msg(
                recipients=emp_request.issuers.select_related('user').exclude(
                    user=get_curr_business(request).manager),
                subject='Your request status has been changed',
                text='Your following request has been %s by your manager:\n %s'
                % (emp_request.get_status_display(), emp_request.text))
        except EmailWaitError as e:
            return HttpResponseServerError(e.message)

        messages.success(request,
                         message='request approved'
                         if new_status == 'A' else 'request rejected')
        return HttpResponse('ok')
Ejemplo n.º 15
0
def get_work_duration_data(request):
    curr_profile = get_curr_profile(request)
    curr_business = get_curr_business(request)
    key = curr_profile.get_eta_cache_key()

    if key not in cache:
        home_address = curr_profile.home_address
        work_address = curr_business.address
        arrival_method = curr_profile.arriving_method
        duration_client = DurationApiClient(home_address, work_address)

        if not home_address or not work_address:
            return HttpResponseBadRequest(
                'can\'t get distance data - work address or home address are not set'
            )

        duration_data = duration_client.get_dist_data(arrival_method)
        driving_duration = duration_data['driving']
        walking_duration = duration_data['walking']

        if not walking_duration and not driving_duration:
            return HttpResponseBadRequest(
                'cant find home to work durations - make sure both business'
                'and home addresses are available')
        logger.debug('getting duration from API service')
        cache.set(key, duration_data, settings.DURATION_CACHE_TTL)
    else:
        logger.debug('getting duration from cache')
        duration_data = cache.get(key)
        driving_duration = duration_data['driving']
        walking_duration = duration_data['walking']

    logger.info(
        'found distance data: driving duration is %s and walking duration is %s',
        driving_duration, walking_duration)
    return JsonResponse(duration_data)
Ejemplo n.º 16
0
def saved_slot_exist(request, slot_name):
    curr_business = get_curr_business(request)
    if SavedSlot.objects.filter(name=slot_name,
                                shiftslot__business=curr_business).exists():
        return HttpResponse('')
    return HttpResponseNotFound('')