def rank_requirements(request, scoutrank_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)
    scouter_role = scouter.role

    scouts = service.get_scouts(scouter.role, scouter.patrol)

    if scoutrank_id:
        scout_rank = ScoutRank.objects.get(id=scoutrank_id)
        scout = scout_rank.scout
        rank = scout_rank.rank
    else:
        scout_id = request.GET.get('scout_id')
        scout = Scouter.objects.get(id=scout_id)
        rank_id = request.GET.get('rank_id')
        rank = Rank.objects.get(id=rank_id)
        scout_rank, created = ScoutRank.objects.get_or_create(scout=scout,
                                                              rank=rank)

    rank_type = ContentType.objects.get_for_model(Rank)
    rank_requirements = Requirement.objects.filter(content_type=rank_type,
                                                   object_id=rank.id)
    rank_requirements_dict = rank_requirements.values()

    scout_rankreqs = ScoutRequirement.objects.filter(
        scout=scout, requirement__in=rank_requirements)

    scout_rankreq_dict = {}
    for scout_rankreq in scout_rankreqs:
        scout_rankreq_dict[
            scout_rankreq.requirement.id] = scout_rankreq.date_completed

    rank_requirements_list = []
    for rank_requirement in rank_requirements_dict:
        rank_requirement['date_completed'] = scout_rankreq_dict.get(
            rank_requirement['id'], None)
        rank_requirements_list.append(rank_requirement)

    if request.method == 'POST':
        # Loop over form fields
        for key, value in request.POST.dict().items():
            if 'rankreq-date-name' in key:
                scout_id = key.split('-')[-2]
                rank_requirement_id = key.split('-')[-1]

                # Update each scout requirement
                scout_rankreq, created = ScoutRequirement.objects.get_or_create(
                    scout_id=scout_id, requirement_id=rank_requirement_id)
                if value:
                    scout_rankreq.date_completed = datetime.strptime(
                        value, '%m/%d/%Y')
                else:
                    scout_rankreq.date_completed = None
                scout_rankreq.leader = scouter
                scout_rankreq.save()
        return HttpResponseRedirect('/home/scout/' + str(scout.id))

    return render_to_response('rank-requirements.html',
                              locals(),
                              context_instance=RequestContext(request))
def rank_requirements(request, scoutrank_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)
    scouter_role = scouter.role

    scouts = service.get_scouts(scouter.role, scouter.patrol)

    if scoutrank_id:
        scout_rank = ScoutRank.objects.get(id=scoutrank_id)
        scout = scout_rank.scout
        rank = scout_rank.rank
    else:
        scout_id = request.GET.get('scout_id')
        scout = Scouter.objects.get(id=scout_id)
        rank_id = request.GET.get('rank_id')
        rank = Rank.objects.get(id=rank_id)
        scout_rank, created = ScoutRank.objects.get_or_create(scout=scout, rank=rank)

    rank_type = ContentType.objects.get_for_model(Rank)
    rank_requirements = Requirement.objects.filter(content_type=rank_type, object_id=rank.id)
    rank_requirements_dict = rank_requirements.values()

    scout_rankreqs = ScoutRequirement.objects.filter(scout=scout, requirement__in=rank_requirements)

    scout_rankreq_dict = {}
    for scout_rankreq in scout_rankreqs:
        scout_rankreq_dict[scout_rankreq.requirement.id] = scout_rankreq.date_completed

    rank_requirements_list = []
    for rank_requirement in rank_requirements_dict:
        rank_requirement['date_completed'] = scout_rankreq_dict.get(rank_requirement['id'], None)
        rank_requirements_list.append(rank_requirement)

    if request.method == 'POST':
        # Loop over form fields
        for key, value in request.POST.dict().items():
            if 'rankreq-date-name' in key:
                scout_id = key.split('-')[-2]
                rank_requirement_id = key.split('-')[-1]

                # Update each scout requirement
                scout_rankreq, created = ScoutRequirement.objects.get_or_create(scout_id=scout_id, requirement_id=rank_requirement_id) 
                if value:
                    scout_rankreq.date_completed = datetime.strptime(value, '%m/%d/%Y')
                else:
                    scout_rankreq.date_completed = None
                scout_rankreq.leader = scouter
                scout_rankreq.save()
        return HttpResponseRedirect('/home/scout/' + str(scout.id))

    return render_to_response('rank-requirements.html', locals(), context_instance=RequestContext(request))
def report_list(request):
    user = request.user
    scouter = Scouter.objects.get(user=user)

    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by(
        'birth_date')  # Need to fix this so the order_by doesn't happen twice

    response = HttpResponse(content_type='application/pdf')
    # Uncommenting this line downloads the pdf rather than displaying it in the browser
    # response['Content-Disposition'] = 'attachment; filename="Scout List.pdf"'

    p = canvas.Canvas(response)

    # -------------------------------------------------------------------------
    # Draw the pdf report
    x = 1 * inch
    y = 10.5 * inch

    for scout in scouts_by_age:
        scout_name = '%s %s' % (scout.user.first_name, scout.user.last_name)
        scout_birth_date = ''
        if scout.birth_date:
            scout_birth_date = scout.birth_date.strftime("%B %d, %Y")

        scout_rank = ''
        if scout.rank:
            scout_rank = scout.rank

        p.drawString(x, y, scout_name)
        p.drawString(3 * x, y, scout_rank)
        p.drawString(5 * x, y, scout_birth_date)

        y -= 0.2 * inch

    p.showPage()
    p.save()

    return response
def report_list(request):
    user = request.user
    scouter = Scouter.objects.get(user=user)

    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by('birth_date') # Need to fix this so the order_by doesn't happen twice

    response = HttpResponse(content_type='application/pdf')
    # Uncommenting this line downloads the pdf rather than displaying it in the browser
    # response['Content-Disposition'] = 'attachment; filename="Scout List.pdf"'

    p = canvas.Canvas(response)

    # -------------------------------------------------------------------------
    # Draw the pdf report
    x = 1 * inch
    y = 10.5 * inch

    for scout in scouts_by_age:
        scout_name = '%s %s' % (scout.user.first_name, scout.user.last_name)
        scout_birth_date = ''
        if scout.birth_date:
            scout_birth_date = scout.birth_date.strftime("%B %d, %Y")

        scout_rank = ''
        if scout.rank:
            scout_rank = scout.rank

        p.drawString(x, y, scout_name)
        p.drawString(3 * x, y, scout_rank)
        p.drawString(5 * x, y, scout_birth_date) 

        y -= 0.2 * inch

    p.showPage()
    p.save()

    return response
def report_scout(request, scouter_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)

    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by('birth_date')
    if scouter_id:
        scouts_by_age = scouts_by_age.filter(id=scouter_id)

    response = HttpResponse(content_type='application/pdf')
    # Uncommenting this line downloads the pdf rather than displaying it in the browser
    # response['Content-Disposition'] = 'attachment; filename="Scout List.pdf"'

    p = canvas.Canvas(response)

    # -------------------------------------------------------------------------
    # Draw the pdf report
    for scout in scouts_by_age:
        x = 1 * inch
        y = 10.5 * inch
        scout_name = '%s %s' % (scout.user.first_name, scout.user.last_name)
        scout_birth_date = ''
        if scout.birth_date:
            scout_birth_date = scout.birth_date.strftime("%B %d, %Y")

        p.drawString(x, y, scout_name)
        p.drawString(5 * x, y, scout_birth_date) 

        y -= 0.4 * inch

        # ---------------------------------------------------------------------
        # List Ranks
        p.drawString(x, y, '------ Ranks ------')
        y -= 0.2 * inch
        scout_ranks = ScoutRank.objects.filter(scout=scout)
        if not scout_ranks:
            p.drawString(x, y, 'No ranks found')
            y -= 0.2 * inch
            
        for scout_rank in scout_ranks:
            p.drawString(x, y, scout_rank.rank.name)
            if scout_rank.date_earned:
                p.drawString(5 * x, y, scout_rank.date_earned.strftime("%B %d, %Y"))
            y -= 0.2 * inch

        y -= 0.2 * inch

        # ---------------------------------------------------------------------
        # List Merit Badges
        p.drawString(x, y, '------ Merit Badges ------')
        y -= 0.2 * inch
        scout_merit_badges = ScoutMeritBadge.objects.filter(scout=scout)
        if not scout_merit_badges:
            p.drawString(x, y, 'No merit badges found')
            y -= 0.2 * inch
            
        for scout_merit_badge in scout_merit_badges:
            p.drawString(x, y, scout_merit_badge.merit_badge.name)
            if scout_merit_badge.date_earned:
                p.drawString(5 * x, y, scout_merit_badge.date_earned.strftime("%B %d, %Y"))
            y -= 0.2 * inch

        y -= 0.4 * inch

        p.showPage()
    p.save()

    return response
def home(request, scouter_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)
    scout = None
    if scouter_id:
        scout = Scouter.objects.get(id=scouter_id)

    # -------------------------------------------------------------------------
    # Get list of scouts for leaders or parents
    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by('birth_date')

    if scout not in scouts:
        scout = None

    scout_list = []
    for scout_item in scouts_by_age:
        scout_ranks = ScoutRank.objects.filter(scout=scout_item).order_by('-rank__weight')
        if scout_ranks:
            rank = scout_ranks[0].rank
        else:
            rank = '-'

        if scout_item.birth_date:
            age = service.get_birth_info(scout_item.birth_date, 'age')
        else:
            age = None

        mb_goals = ScoutMeritBadge.objects.filter(scout=scout_item, goal_date__gt='1901-01-01').order_by('-merit_badge__required', 'merit_badge__name').values_list('merit_badge__name', flat=True)
        
        scout_notes = ScoutNote.objects.filter(scout=scout_item).order_by('-note_date')
        if scout_notes:
            status = scout_notes[0]
        else:
            status = None
        scout_dict = {'id': scout_item.id,
                      'first_name': scout_item.user.first_name,
                      'last_name': scout_item.user.last_name,
                      'patrol': scout_item.patrol,
                      'rank': rank,
                      'age': age,
                      'birth_date': scout_item.birth_date,
                      'phone_number': scout_item.phone_number,
                      'mb_goals': 'Set' if mb_goals else '', # Change this if merit badges should appear in list
                      'status': status}
        scout_list.append(scout_dict)
            
    # -------------------------------------------------------------------------
    # Get other info if a scout is logged in
    if scouter.role == 'scout':
        scout_list = []
        scout = scouter

    # -------------------------------------------------------------------------
    # Get ranks
    ranks = Rank.objects.all()
    scout_ranks = ScoutRank.objects.filter(scout=scout)

    scout_ranks_list = []
    for rank in ranks:
        scout_rank_dict = {'image_name': rank.image_name,
                           'image_ph_name': rank.image_ph_name,
                           'rank_id': rank.id,
                           'rank_name': rank.name}
        for scout_rank in scout_ranks:
            if rank == scout_rank.rank:
                scout_rank_dict['id'] = scout_rank.id
                scout_rank_dict['date_earned'] = scout_rank.date_earned
                break
            
            else:
                scout_rank_dict['date_earned'] = None
        
        scout_ranks_list.append(scout_rank_dict)
    
    # -------------------------------------------------------------------------
    # Get merit badges
    scout_merit_badges_earned = ScoutMeritBadge.objects.filter(scout=scout, date_earned__gt='1901-01-01').order_by('-merit_badge__required', 'merit_badge__name')
    scout_merit_badges_planned = ScoutMeritBadge.objects.filter(scout=scout, goal_date__gt='1901-01-01').order_by('-merit_badge__required', 'merit_badge__name')

    # -------------------------------------------------------------------------
    # Get individual scout info
    scout_dict = {}
    if scout:
        scout_dict['name'] = '{0} {1}'.format(scout.user.first_name, scout.user.last_name)
        scout_dict['username'] = scout.user.username
        scout_dict['phone_number'] = scout.phone_number
        if scout.birth_date:
            age = service.get_birth_info(scout.birth_date, 'age')
            scout_dict['age'] = age
            scout_dict['turns_age'] = age + 1
            scout_dict['turns_month'] = service.get_birth_info(scout.birth_date, 'next_birthday').strftime('%b %d, %Y')

        scout_notes = []
        if scouter.role == 'leader':
            scout_notes = ScoutNote.objects.filter(scout=scout).order_by('-note_date')

    # -------------------------------------------------------------------------
    # Get merit-badge book info
    scout_merit_badge_books = ScoutMeritBadgeBook.objects.filter(scout=scout).exclude(date_returned__gt='1901-01-01')
    scout_merit_badges_planned_mbs = scout_merit_badges_planned.values_list('merit_badge', flat=True)

    scout_merit_badge_books_planned = []
    scout_merit_badge_books_unplanned = []
    for scout_merit_badge_book in scout_merit_badge_books:
        if scout_merit_badge_book.merit_badge_book.merit_badge.id in scout_merit_badges_planned_mbs:
            scout_merit_badge_books_planned.append(scout_merit_badge_book)
        
        elif scout_merit_badge_book.date_borrowed:
            scout_merit_badge_books_unplanned.append(scout_merit_badge_book)

    scout_merit_badges_planned_list = []
    for scout_merit_badge_planned in scout_merit_badges_planned:
        scout_merit_badge_planned_dict = {'id': scout_merit_badge_planned.id,
                                          'merit_badge': scout_merit_badge_planned.merit_badge,
                                          'goal_date': scout_merit_badge_planned.goal_date}
        try:
            merit_badge_book = MeritBadgeBook.objects.get(merit_badge=scout_merit_badge_planned.merit_badge)
            scout_merit_badge_planned_dict['book_in_library'] = merit_badge_book.in_library
        except:
            scout_merit_badge_planned_dict['book_in_library'] = False
        
        for scout_merit_badge_book_planned in scout_merit_badge_books_planned:
            if scout_merit_badge_book_planned.merit_badge_book.merit_badge == scout_merit_badge_planned.merit_badge:
                scout_merit_badge_planned_dict['book_date_requested'] = scout_merit_badge_book_planned.date_requested
                scout_merit_badge_planned_dict['book_date_borrowed'] = scout_merit_badge_book_planned.date_borrowed
                scout_merit_badge_planned_dict['book_date_due'] = scout_merit_badge_book_planned.date_due

            else:
                scout_merit_badge_planned_dict['book_date_requested'] = None
                scout_merit_badge_planned_dict['book_date_borrowed'] = None
                scout_merit_badge_planned_dict['book_date_due'] = None

        scout_merit_badges_planned_list.append(scout_merit_badge_planned_dict)

    return render_to_response('home.html', locals(), context_instance=RequestContext(request))
def report_scout(request, scouter_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)

    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by('birth_date')
    if scouter_id:
        scouts_by_age = scouts_by_age.filter(id=scouter_id)

    response = HttpResponse(content_type='application/pdf')
    # Uncommenting this line downloads the pdf rather than displaying it in the browser
    # response['Content-Disposition'] = 'attachment; filename="Scout List.pdf"'

    p = canvas.Canvas(response)

    # -------------------------------------------------------------------------
    # Draw the pdf report
    for scout in scouts_by_age:
        x = 1 * inch
        y = 10.5 * inch
        scout_name = '%s %s' % (scout.user.first_name, scout.user.last_name)
        scout_birth_date = ''
        if scout.birth_date:
            scout_birth_date = scout.birth_date.strftime("%B %d, %Y")

        p.drawString(x, y, scout_name)
        p.drawString(5 * x, y, scout_birth_date)

        y -= 0.4 * inch

        # ---------------------------------------------------------------------
        # List Ranks
        p.drawString(x, y, '------ Ranks ------')
        y -= 0.2 * inch
        scout_ranks = ScoutRank.objects.filter(scout=scout)
        if not scout_ranks:
            p.drawString(x, y, 'No ranks found')
            y -= 0.2 * inch

        for scout_rank in scout_ranks:
            p.drawString(x, y, scout_rank.rank.name)
            if scout_rank.date_earned:
                p.drawString(5 * x, y,
                             scout_rank.date_earned.strftime("%B %d, %Y"))
            y -= 0.2 * inch

        y -= 0.2 * inch

        # ---------------------------------------------------------------------
        # List Merit Badges
        p.drawString(x, y, '------ Merit Badges ------')
        y -= 0.2 * inch
        scout_merit_badges = ScoutMeritBadge.objects.filter(scout=scout)
        if not scout_merit_badges:
            p.drawString(x, y, 'No merit badges found')
            y -= 0.2 * inch

        for scout_merit_badge in scout_merit_badges:
            p.drawString(x, y, scout_merit_badge.merit_badge.name)
            if scout_merit_badge.date_earned:
                p.drawString(
                    5 * x, y,
                    scout_merit_badge.date_earned.strftime("%B %d, %Y"))
            y -= 0.2 * inch

        y -= 0.4 * inch

        p.showPage()
    p.save()

    return response
def home(request, scouter_id=None):
    user = request.user
    scouter = Scouter.objects.get(user=user)
    scout = None
    if scouter_id:
        scout = Scouter.objects.get(id=scouter_id)

    # -------------------------------------------------------------------------
    # Get list of scouts for leaders or parents
    scouts = service.get_scouts(scouter.role, scouter.patrol)
    scouts_by_age = scouts.order_by('birth_date')

    if scout not in scouts:
        scout = None

    scout_list = []
    for scout_item in scouts_by_age:
        scout_ranks = ScoutRank.objects.filter(
            scout=scout_item).order_by('-rank__weight')
        if scout_ranks:
            rank = scout_ranks[0].rank
        else:
            rank = '-'

        if scout_item.birth_date:
            age = service.get_birth_info(scout_item.birth_date, 'age')
        else:
            age = None

        mb_goals = ScoutMeritBadge.objects.filter(
            scout=scout_item, goal_date__gt='1901-01-01').order_by(
                '-merit_badge__required',
                'merit_badge__name').values_list('merit_badge__name',
                                                 flat=True)

        scout_notes = ScoutNote.objects.filter(
            scout=scout_item).order_by('-note_date')
        if scout_notes:
            status = scout_notes[0]
        else:
            status = None
        scout_dict = {
            'id': scout_item.id,
            'first_name': scout_item.user.first_name,
            'last_name': scout_item.user.last_name,
            'patrol': scout_item.patrol,
            'rank': rank,
            'age': age,
            'birth_date': scout_item.birth_date,
            'phone_number': scout_item.phone_number,
            'mb_goals': 'Set' if mb_goals else
            '',  # Change this if merit badges should appear in list
            'status': status
        }
        scout_list.append(scout_dict)

    # -------------------------------------------------------------------------
    # Get other info if a scout is logged in
    if scouter.role == 'scout':
        scout_list = []
        scout = scouter

    # -------------------------------------------------------------------------
    # Get ranks
    ranks = Rank.objects.all()
    scout_ranks = ScoutRank.objects.filter(scout=scout)

    scout_ranks_list = []
    for rank in ranks:
        scout_rank_dict = {
            'image_name': rank.image_name,
            'image_ph_name': rank.image_ph_name,
            'rank_id': rank.id,
            'rank_name': rank.name
        }
        for scout_rank in scout_ranks:
            if rank == scout_rank.rank:
                scout_rank_dict['id'] = scout_rank.id
                scout_rank_dict['date_earned'] = scout_rank.date_earned
                break

            else:
                scout_rank_dict['date_earned'] = None

        scout_ranks_list.append(scout_rank_dict)

    # -------------------------------------------------------------------------
    # Get merit badges
    scout_merit_badges_earned = ScoutMeritBadge.objects.filter(
        scout=scout,
        date_earned__gt='1901-01-01').order_by('-merit_badge__required',
                                               'merit_badge__name')
    scout_merit_badges_planned = ScoutMeritBadge.objects.filter(
        scout=scout,
        goal_date__gt='1901-01-01').order_by('-merit_badge__required',
                                             'merit_badge__name')

    # -------------------------------------------------------------------------
    # Get individual scout info
    scout_dict = {}
    if scout:
        scout_dict['name'] = '{0} {1}'.format(scout.user.first_name,
                                              scout.user.last_name)
        scout_dict['username'] = scout.user.username
        scout_dict['phone_number'] = scout.phone_number
        if scout.birth_date:
            age = service.get_birth_info(scout.birth_date, 'age')
            scout_dict['age'] = age
            scout_dict['turns_age'] = age + 1
            scout_dict['turns_month'] = service.get_birth_info(
                scout.birth_date, 'next_birthday').strftime('%b %d, %Y')

        scout_notes = []
        if scouter.role == 'leader':
            scout_notes = ScoutNote.objects.filter(
                scout=scout).order_by('-note_date')

    # -------------------------------------------------------------------------
    # Get merit-badge book info
    scout_merit_badge_books = ScoutMeritBadgeBook.objects.filter(
        scout=scout).exclude(date_returned__gt='1901-01-01')
    scout_merit_badges_planned_mbs = scout_merit_badges_planned.values_list(
        'merit_badge', flat=True)

    scout_merit_badge_books_planned = []
    scout_merit_badge_books_unplanned = []
    for scout_merit_badge_book in scout_merit_badge_books:
        if scout_merit_badge_book.merit_badge_book.merit_badge.id in scout_merit_badges_planned_mbs:
            scout_merit_badge_books_planned.append(scout_merit_badge_book)

        elif scout_merit_badge_book.date_borrowed:
            scout_merit_badge_books_unplanned.append(scout_merit_badge_book)

    scout_merit_badges_planned_list = []
    for scout_merit_badge_planned in scout_merit_badges_planned:
        scout_merit_badge_planned_dict = {
            'id': scout_merit_badge_planned.id,
            'merit_badge': scout_merit_badge_planned.merit_badge,
            'goal_date': scout_merit_badge_planned.goal_date
        }
        try:
            merit_badge_book = MeritBadgeBook.objects.get(
                merit_badge=scout_merit_badge_planned.merit_badge)
            scout_merit_badge_planned_dict[
                'book_in_library'] = merit_badge_book.in_library
        except:
            scout_merit_badge_planned_dict['book_in_library'] = False

        for scout_merit_badge_book_planned in scout_merit_badge_books_planned:
            if scout_merit_badge_book_planned.merit_badge_book.merit_badge == scout_merit_badge_planned.merit_badge:
                scout_merit_badge_planned_dict[
                    'book_date_requested'] = scout_merit_badge_book_planned.date_requested
                scout_merit_badge_planned_dict[
                    'book_date_borrowed'] = scout_merit_badge_book_planned.date_borrowed
                scout_merit_badge_planned_dict[
                    'book_date_due'] = scout_merit_badge_book_planned.date_due

            else:
                scout_merit_badge_planned_dict['book_date_requested'] = None
                scout_merit_badge_planned_dict['book_date_borrowed'] = None
                scout_merit_badge_planned_dict['book_date_due'] = None

        scout_merit_badges_planned_list.append(scout_merit_badge_planned_dict)

    return render_to_response('home.html',
                              locals(),
                              context_instance=RequestContext(request))