Source

cciw-website / cciw / officers / views.py

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
import datetime
import itertools

from django import forms
from django import template
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.admin import widgets
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db import models
from django.core.validators import email_re
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template.loader import render_to_string
from django.template.defaultfilters import wordwrap
from django.views.decorators.cache import never_cache

from cciw.cciwmain import common
from cciw.cciwmain.decorators import json_response
from cciw.cciwmain.models import Camp
from cciw.cciwmain.utils import python_to_json
from cciw.mail.lists import address_for_camp_officers, address_for_camp_slackers
from cciw.officers.applications import application_to_text, application_to_rtf, application_rtf_filename, application_txt_filename, thisyears_applications, applications_for_camp
from cciw.officers import create
from cciw.officers.email_utils import send_mail_with_attachments, formatted_email
from cciw.officers.email import make_update_email_hash, send_reference_request_email, make_ref_form_url, make_ref_form_url_hash, send_leaders_reference_email, send_nag_by_officer
from cciw.officers.widgets import ExplicitBooleanFieldSelect
from cciw.officers.models import Application, Reference, ReferenceForm, Invitation, CRBApplication
from cciw.officers.utils import camp_officer_list, camp_slacker_list
from cciw.officers.references import reference_form_info
from cciw.utils.views import close_window_response
from securedownload.views import access_folder_securely
import smtplib


def _copy_application(application):
    new_obj = Application(id=None)
    for field in Application._meta.fields:
        if field.attname != 'id':
            setattr(new_obj, field.attname, getattr(application, field.attname))
    new_obj.youth_work_declined = None
    new_obj.relevant_illness = None
    new_obj.crime_declaration = None
    new_obj.court_declaration = None
    new_obj.concern_declaration = None
    new_obj.allegation_declaration = None
    new_obj.crb_check_consent = None
    new_obj.finished = False
    new_obj.date_submitted = None
    return new_obj


def _is_camp_admin(user):
    """
    Returns True if the user is an admin for any camp.
    """
    return (user.groups.filter(name='Leaders').exists()) \
        or user.camps_as_admin.exists() > 0


camp_admin_required = user_passes_test(_is_camp_admin)


def _is_camp_officer(user):
    return user.is_authenticated() and \
        (user.groups.filter(name='Officers') |
         user.groups.filter(name='Leaders')).exists()


def _camps_as_admin_or_leader(user):
    """
    Returns all the camps for which the user is an admin or leader.
    """
    # If the user is am 'admin' for some camps:
    camps = user.camps_as_admin.all()
    # Find the 'Person' object that corresponds to this user
    leaders = list(user.person_set.all())
    # Find the camps for this leader
    # (We could do:
    #    Person.objects.get(user=user.id).camps_as_leader.all(),
    #  but we also must we handle the possibility that two Person
    #  objects have the same User objects, which could happen in the
    #  case where a leader leads by themselves and as part of a couple)
    for leader in leaders:
        camps = camps | leader.camps_as_leader.all()

    return camps.distinct()

def close_window_and_update_ref(ref_id):
    """
    HttpResponse that closes the current window, and updates the reference
    in the parent window. Applies to popup from manage_references view.
    """
    return HttpResponse("""<!DOCTYPE HTML><html><head><title>Close</title><script type="text/javascript">window.opener.refreshReferenceSection(%s); window.close()</script></head><body></body></html>""" % ref_id)


# /officers/
@staff_member_required
@never_cache
def index(request):
    """Displays a list of links/buttons for various actions."""
    user = request.user
    context = template.RequestContext(request)
    if _is_camp_admin(user):
        context['show_leader_links'] = True
        context['show_admin_link'] = True

    return render_to_response('cciw/officers/index.html',
                              context_instance=context)


@staff_member_required
@camp_admin_required
def leaders_index(request):
    """Displays a list of links for actions for leaders"""
    user = request.user
    context = template.RequestContext(request)
    thisyear = common.get_thisyear()
    context['current_camps'] = _camps_as_admin_or_leader(user).filter(year=thisyear)
    context['old_camps'] = _camps_as_admin_or_leader(user).filter(year__lt=thisyear)
    context['statsyears'] = [thisyear, thisyear - 1, thisyear - 2]

    return render_to_response('cciw/officers/leaders_index.html', context_instance=context)


@staff_member_required
@never_cache
def applications(request):
    """Displays a list of tasks related to applications."""
    user = request.user
    context = template.RequestContext(request)
    finished_applications = user.application_set\
        .filter(finished=True)\
        .order_by('-date_submitted')
    unfinished_applications = user.application_set\
        .filter(finished=False)\
        .order_by('-date_submitted')
    has_thisyears_app = thisyears_applications(user).exists()
    has_completed_app = thisyears_applications(user).filter(finished=True).exists()

    context['finished_applications'] = finished_applications
    context['unfinished_applications'] = unfinished_applications
    context['has_thisyears_app'] = has_thisyears_app
    context['has_completed_app'] = has_completed_app

    if request.POST.has_key('edit'):
        # Edit existing application
        id = request.POST.get('edit_application', None)
        if id is not None:
            return HttpResponseRedirect('/admin/officers/application/%s/' % id)
    elif not has_thisyears_app and request.POST.has_key('new'):
        # Create new application based on old one
        obj = None
        try:
            obj = finished_applications[0]
        except IndexError:
            # should never get here
            obj = None
        if obj is not None:
            # Create a copy
            new_obj = _copy_application(obj)
            new_obj.save()
            return HttpResponseRedirect('/admin/officers/application/%s/' % \
                                            new_obj.id)

    elif request.POST.has_key('delete'):
        # Delete an unfinished application
        pass

    return render_to_response('cciw/officers/applications.html',
                              context_instance=context)


@staff_member_required
def view_application(request):
    try:
        application_id = int(request.POST['application'])
    except:
        raise Http404

    try:
        app = Application.objects.get(id=application_id)
    except Application.DoesNotExist:
        raise Http404

    if app.officer_id != request.user.id and \
            not _is_camp_admin(request.user):
        raise PermissionDenied

    # NB, this is is called by both normal users and leaders.
    # In the latter case, request.user != app.officer

    format = request.POST.get('format', '')
    if format == 'txt':
        resp = HttpResponse(application_to_text(app), mimetype="text/plain")
        resp['Content-Disposition'] = 'attachment; filename=%s;' % \
                                      application_txt_filename(app)
        return resp
    elif format == 'rtf':
        resp = HttpResponse(application_to_rtf(app), mimetype="text/rtf")
        resp['Content-Disposition'] = 'attachment; filename=%s;' % \
                                      application_rtf_filename(app)
        return resp
    elif format == 'send':
        application_text = application_to_text(app)
        application_rtf = application_to_rtf(app)
        rtf_attachment = (application_rtf_filename(app),
                          application_rtf, 'text/rtf')

        msg = \
u"""Dear %s,

Please find attached a copy of the application you requested
 -- in plain text below and an RTF version attached.

""" % request.user.first_name
        msg = msg + application_text

        send_mail_with_attachments("Copy of CCIW application - %s" % app.full_name,
                                   msg, settings.SERVER_EMAIL,
                                   [formatted_email(request.user)],
                                   attachments=[rtf_attachment])
        messages.info(request, "E-mail sent.")

        # Redirect back where we came from
        return HttpResponseRedirect(request.POST.get('to', '/officers/'))

    else:
        raise Http404

    return resp


def _thisyears_camp_for_leader(user):
    leaders = list(user.person_set.all())
    try:
        return leaders[0].camps_as_leader.get(year=common.get_thisyear(),
                                              online_applications=True)
    except (ObjectDoesNotExist, IndexError):
        return None


@staff_member_required
@camp_admin_required
@never_cache
def manage_applications(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)
    context = template.RequestContext(request)
    context['finished_applications'] = applications_for_camp(camp).order_by('officer__first_name', 'officer__last_name')
    context['camp'] = camp

    return render_to_response('cciw/officers/manage_applications.html',
                              context_instance=context)


def _get_camp_or_404(year, number):
    try:
        return Camp.objects.get(year=int(year), number=int(number))
    except Camp.DoesNotExist, ValueError:
        raise Http404


def get_previous_references(ref, camp):
    """
    Returns a tuple of:
     (possible previous References ordered by relevance,
      exact match for previous Reference or None if it doesn't exist)
    """
    # Look for ReferenceForms for same officer, within the previous five
    # years.  Don't look for references from this year's
    # application (which will be the other referee).
    cutoffdate = camp.start_date - datetime.timedelta(365*5)
    prev = list(ReferenceForm.objects\
                .filter(reference_info__application__officer=ref.application.officer,
                        reference_info__application__finished=True,
                        reference_info__received=True,
                        date_created__gte=cutoffdate)\
                .exclude(reference_info__application=ref.application)\
                .order_by('-reference_info__application__date_submitted'))

    # Sort by relevance
    def relevance_key(refform):
        # Matching name or e-mail address is better, so has lower value,
        # so it comes first.
        return -(int(refform.reference_info.referee.email==ref.referee.email) +
                 int(refform.reference_info.referee.name ==ref.referee.name))
    prev.sort(key=relevance_key) # sort is stable, so previous sort by date should be kept

    exact = None
    for refform in prev:
        if refform.reference_info.referee == ref.referee:
            exact = refform.reference_info
            break
    return ([rf.reference_info for rf in prev], exact)


@staff_member_required
@camp_admin_required # we don't care which camp they are admin for.
@never_cache
def manage_references(request, year=None, number=None):
    c = template.RequestContext(request)

    # If ref_id is set, we just want to update part of the page.
    ref_id = request.GET.get('ref_id')

    camp = _get_camp_or_404(year, number)
    c['camp'] = camp

    if ref_id is None:
        apps = applications_for_camp(camp)
        app_ids = [app.id for app in apps]
        # force creation of Reference objects.
        if Reference.objects.filter(application__in=app_ids).count() < len(apps) * 2:
            [a.references for a in apps]

        refinfo = Reference.objects\
            .filter(application__in=app_ids)\
            .order_by('application__officer__first_name', 'application__officer__last_name',
                      'referee_number')

    else:
        refinfo = Reference.objects.filter(pk=ref_id).order_by()

    received = refinfo.filter(received=True)
    requested = refinfo.filter(received=False, requested=True)
    notrequested = refinfo.filter(received=False, requested=False)

    for l in (received, requested, notrequested):
        # decorate each Reference with suggested previous ReferenceForms.
        for curref in l:
            (prev, exact) = get_previous_references(curref, camp)
            if exact is not None:
                curref.previous_reference = exact
            else:
                curref.possible_previous_references = prev

    if ref_id is None:
        c['notrequested'] = notrequested
        c['requested'] = requested
        c['received'] = received
        template_name = 'cciw/officers/manage_references.html'
    else:
        if received:
            c['mode'] = 'received'
            c['ref'] = received[0]
        elif requested:
            c['mode'] = 'requested'
            c['ref'] = requested[0]
        else:
            c['mode'] = 'notrequested'
            c['ref'] = notrequested[0]
        template_name = 'cciw/officers/manage_reference.html'

    return render_to_response(template_name, context_instance=c)


def email_sending_failed_response():
    return HttpResponse("""<p>E-mail failed to send.  This is likely a temporary
    error, please press back in your browser and try again.</p>""")


class SetEmailForm(forms.Form):
    email = forms.EmailField(widget=forms.TextInput(attrs={'size':'50'}))


class SendMessageForm(forms.Form):
    message = forms.CharField(widget=forms.Textarea(attrs={'cols':80, 'rows':20}))

    def __init__(self, *args, **kwargs):
        message_info = kwargs.pop('message_info', {})
        self.message_info = message_info
        msg_template = self.get_message_template()
        msg = render_to_string(msg_template, message_info)
        initial = kwargs.pop('initial', {})
        initial['message'] = msg
        kwargs['initial'] = initial
        return super(SendMessageForm, self).__init__(*args, **kwargs)

    def get_message_template(self):
        raise NotImplementedError


class SendReferenceRequestForm(SendMessageForm):

    def get_message_template(self):
        if self.message_info['update']:
            return 'cciw/officers/request_reference_update.txt'
        else:
            return 'cciw/officers/request_reference_new.txt'

    def clean(self):
        cleaned_data = self.cleaned_data
        url = self.message_info['url']
        if url not in cleaned_data.setdefault('message', ''):
            errmsg = "You removed the link %s from the message.  This link is needed for the referee to be able to submit their reference" % url
            self._errors.setdefault('message', self.error_class([])).append(errmsg)
            del cleaned_data['message']
        return cleaned_data


@staff_member_required
@camp_admin_required # we don't care which camp they are admin for.
def request_reference(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)
    try:
        ref_id = int(request.GET.get('ref_id'))
    except ValueError, TypeError:
        raise Http404
    ref = get_object_or_404(Reference.objects.filter(id=ref_id))
    app = ref.application

    if 'manual' in request.GET:
        return manage_reference_manually(request, ref)

    c = template.RequestContext(request)

    # Need to handle any changes to the referees first, for correctness of what
    # follows
    if request.method == "POST" and 'setemail' in request.POST:
        emailform = SetEmailForm(request.POST)
        if emailform.is_valid():
            app.referees[ref.referee_number-1].email = emailform.cleaned_data['email']
            app.save()
            messages.info(request, "E-mail address updated.")

    # Work out 'old_referee' or 'known_email_address', and the URL to use in the
    # message.
    update = 'update' in request.GET
    if update:
        (possible, exact) = get_previous_references(ref, camp)
        prev_ref_id = int(request.GET['prev_ref_id'])
        if exact is not None:
            # the prev_ref_id must be the same as exact.id by the logic of the
            # buttons available on the manage_references page. If not true, we
            # close the page and update the parent page, in case the parent is
            # out of date.
            if exact.id != prev_ref_id:
                return close_window_and_update_ref(ref_id)
            c['known_email_address'] = True
        else:
            # Get old referee data
            refs = [r for r in possible if r.id == prev_ref_id]
            assert len(refs) == 1
            c['old_referee'] = refs[0].referee
        url = make_ref_form_url(ref.id, prev_ref_id)
    else:
        url = make_ref_form_url(ref.id, None)

    messageform_info = dict(referee=ref.referee,
                            applicant=app.officer,
                            camp=camp,
                            url=url,
                            update=update)
    emailform = None
    messageform = None

    if request.method == 'POST':
        if 'send' in request.POST:
            messageform = SendReferenceRequestForm(request.POST, message_info=messageform_info)
            if messageform.is_valid():
                try:
                    send_reference_request_email(wordwrap(messageform.cleaned_data['message'], 70), ref)
                except smtplib.SMTPException:
                    return email_sending_failed_response()
                ref.requested = True
                ref.log_request_made(request.user, datetime.datetime.now())
                ref.save()
                return close_window_and_update_ref(ref_id)
        elif 'cancel' in request.POST:
            return close_window_response()

    if emailform is None:
        emailform = SetEmailForm(initial={'email': ref.referee.email})
    if messageform is None:
        messageform = SendReferenceRequestForm(message_info=messageform_info)

    if not email_re.match(ref.referee.email.strip()):
        c['bad_email'] = True
    c['is_popup'] = True
    c['already_requested'] = ref.requested
    c['referee'] = ref.referee
    c['app'] = app
    c['is_update'] = update
    c['emailform'] = emailform
    c['messageform'] = messageform
    return render_to_response('cciw/officers/request_reference.html',
                              context_instance=c)


class SendNagByOfficerForm(SendMessageForm):
    def get_message_template(self):
        return 'cciw/officers/nag_by_officer_email.txt'


@staff_member_required
@camp_admin_required # we don't care which camp they are admin for.
def nag_by_officer(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)
    try:
        ref_id = int(request.GET.get('ref_id'))
    except ValueError, TypeError:
        raise Http404
    ref = get_object_or_404(Reference.objects.filter(id=ref_id))
    app = ref.application
    officer = app.officer

    c = template.RequestContext(request)
    messageform_info = dict(referee=ref.referee,
                            officer=officer,
                            camp=camp)

    if request.method == 'POST':
        if 'send' in request.POST:
            messageform = SendNagByOfficerForm(request.POST, message_info=messageform_info)
            # It's impossible for the form to be invalid, so assume valid
            messageform.is_valid()
            send_nag_by_officer(wordwrap(messageform.cleaned_data['message'], 70), officer, ref)
            return close_window_response()
        else:
            # cancel
            return close_window_response()

    messageform = SendNagByOfficerForm(message_info=messageform_info)

    c['referee'] = ref.referee
    c['app'] = app
    c['officer'] = officer
    c['messageform'] = messageform
    c['is_popup'] = True
    return render_to_response('cciw/officers/nag_by_officer.html',
                              context_instance=c)


class ReferenceFormForm(forms.ModelForm):
    class Meta:
        model = ReferenceForm
        fields = ('referee_name',
                  'how_long_known',
                  'capacity_known',
                  'known_offences',
                  'known_offences_details',
                  'capability_children',
                  'character',
                  'concerns',
                  'comments')


normal_textarea = forms.Textarea(attrs={'cols':80, 'rows':10})
small_textarea = forms.Textarea(attrs={'cols':80, 'rows':5})
ReferenceFormForm.base_fields['capacity_known'].widget = small_textarea
ReferenceFormForm.base_fields['known_offences'].widget = ExplicitBooleanFieldSelect()
ReferenceFormForm.base_fields['known_offences_details'].widget = normal_textarea
ReferenceFormForm.base_fields['capability_children'].widget = normal_textarea
ReferenceFormForm.base_fields['character'].widget = normal_textarea
ReferenceFormForm.base_fields['concerns'].widget = normal_textarea
ReferenceFormForm.base_fields['comments'].widget = normal_textarea


# I have models called Reference and ReferenceForm.  What do I call a Form
# for model Reference? I'm a loser...
class ReferenceEditForm(forms.ModelForm):
    class Meta:
        model = Reference
        fields = ('requested', 'received', 'comments')


def manage_reference_manually(request, ref):
    """
    Returns page for manually editing Reference and ReferenceForm details.
    """
    c = template.RequestContext(request)
    c['ref'] = ref
    c['referee'] = ref.referee
    c['officer'] = ref.application.officer
    if request.method == 'POST':
        if 'save' in request.POST:
            form = ReferenceEditForm(request.POST, instance=ref)
            if form.is_valid():
                form.save()
                return close_window_and_update_ref(ref.id)
        else:
            return close_window_response()
    else:
        form = ReferenceEditForm(instance=ref)
    c['form'] = form
    c['is_popup'] = True
    return render_to_response("cciw/officers/manage_reference_manual.html",
                              context_instance=c)


@staff_member_required
@camp_admin_required # we don't care which camp they are admin for.
def edit_reference_form_manually(request, ref_id=None):
    """
    Create ReferenceForm if necessary, then launch normal admin popup for
    editing it.
    """
    ref = get_object_or_404(Reference.objects.filter(id=int(ref_id)))
    if ref.reference_form is None:
        # Create it
        ReferenceForm.objects.create(reference_info=ref,
                                     referee_name=ref.referee.name,
                                     date_created=datetime.date.today(),
                                     known_offences=False)
    return HttpResponseRedirect(reverse("admin:officers_referenceform_change",
                                        args=(ref.reference_form.id,)) + \
                                "?_popup=1")


def initial_reference_form_data(ref, prev_ref_form):
    """
    Return the initial data to be used for ReferenceFormForm, given the current
    Reference objects and the ReferenceForm object with data to be copied.
    """
    retval =  {}
    if prev_ref_form is not None:
        # Copy data over
        for f in ReferenceFormForm._meta.fields:
            retval[f] = getattr(prev_ref_form, f)
    retval['referee_name'] = ref.referee.name
    retval.pop('date_created', None)
    return retval


def empty_reference(ref_form):
    return ref_form.how_long_known.strip() == ""


def create_reference_form(request, ref_id="", prev_ref_id="", hash=""):
    """
    View for allowing referee to submit reference (create the ReferenceForm object)
    """
    c = template.RequestContext(request)
    if hash != make_ref_form_url_hash(ref_id, prev_ref_id):
        c['incorrect_url'] = True
    else:
        ref = get_object_or_404(Reference.objects.filter(id=int(ref_id)))
        prev_ref = None
        if prev_ref_id != "":
            prev_ref = get_object_or_404(Reference.objects.filter(id=int(prev_ref_id)))

        if prev_ref is not None:
            prev_ref_form = prev_ref.reference_form
            c['update'] = True
            c['last_form_date'] = prev_ref_form.date_created
        else:
            prev_ref_form = None

        ref_form = ref.reference_form
        if ref_form is not None:
            # For the case where a ReferenceForm has been created (accidentally)
            # by an admin, we need to re-use it, rather than create another.
            instance = ref_form
        else:
            instance = None

        if ref_form is not None and ref.received and not empty_reference(ref_form):
            # It's possible, if an admin has done 'Manage reference manually'
            # and clicked "Create/edit reference form" but then cancelled, that
            # the ReferenceForm will exist but be empty.  So we check both that
            # it exists and that the 'ref.received' is True, otherwise a referee
            # will be unable to fill out the form.
            c['already_submitted'] = True
        else:
            if request.method == 'POST':
                form = ReferenceFormForm(request.POST, instance=instance) # A form bound to the POST data
                if form.is_valid():
                    obj = form.save(commit=False)
                    obj.reference_info = ref
                    obj.date_created = datetime.date.today()
                    obj.save()
                    ref.received = True
                    ref.comments = ref.comments + \
                                   ("\nReference received via online system on %s\n" % \
                                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    ref.save()
                    # Send e-mails
                    send_leaders_reference_email(obj)
                    return HttpResponseRedirect(reverse('cciw.officers.views.create_reference_thanks'))
            else:
                initial_data = initial_reference_form_data(ref, prev_ref_form)
                if instance is not None:
                    if empty_reference(instance):
                        # Need to fill data
                        for k, v in initial_data.items():
                            setattr(instance, k, v)
                    form = ReferenceFormForm(instance=instance)
                else:
                    form = ReferenceFormForm(initial=initial_data)
            c['form'] = form
        c['officer'] = ref.application.officer
    return render_to_response('cciw/officers/create_reference.html',
                              context_instance=c)


def create_reference_thanks(request):
    return render_to_response('cciw/officers/create_reference_thanks.html',
                              context_instance=template.RequestContext(request))


@staff_member_required
@camp_admin_required
def view_reference(request, ref_id=None):
    ref = get_object_or_404(Reference.objects.filter(id=ref_id))
    ref_form = ref.reference_form
    c = template.RequestContext(request)
    if ref_form is not None:
        c['refform'] = ref_form
        c['info'] = reference_form_info(ref_form)
    c['ref'] = ref
    c['officer'] = ref.application.officer
    c['referee'] = ref.referee
    c['is_popup'] = True

    return render_to_response("cciw/officers/view_reference_form.html",
                              context_instance=c)


@staff_member_required
@camp_admin_required
def officer_list(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)

    c = template.RequestContext(request)
    c['camp'] = camp
    # Make sure these queries come after the above data modification
    officer_list = camp_officer_list(camp)
    officer_list_ids = set(u.id for u in officer_list)
    c['officers_all'] = officer_list
    c['officers_noapplicationform'] = camp_slacker_list(camp)
    c['address_all'] = address_for_camp_officers(camp)
    c['address_noapplicationform'] = address_for_camp_slackers(camp)

    # List for select
    available_officers = list(User.objects.filter(is_staff=True).order_by('first_name', 'last_name', 'email'))
    # decorate with info about previous camp
    prev_camp = camp.previous_camp
    if prev_camp is not None:
        prev_officer_list_ids = set(u.id for u in prev_camp.officers.all())
        for u in available_officers:
            if u.id in prev_officer_list_ids:
                u.on_previous_camp = True
    # Filter out officers who are already chosen for this camp.
    # Since the total number of officers >> officers chosen for a camp
    # there is no need to do this filtering in the database.
    available_officers = [u for u in available_officers if u.id not in officer_list_ids]
    available_officers.sort(key=lambda u: not getattr(u, 'on_previous_camp', False))
    c['available_officers'] = available_officers

    # Different templates allow us to render just parts of the page, for AJAX calls
    if 'sections' in request.GET:
        tnames = [("chosen", "cciw/officers/officer_list_table_editable.html"),
                  ("available", "cciw/officers/officer_list_available.html"),
                  ("noapplicationform", "cciw/officers/officer_list_noapplicationform.html")]
        retval = {}
        for section, tname in tnames:
            retval[section] = render_to_string(tname, context_instance=c)
        return HttpResponse(python_to_json(retval),
                            mimetype="text/javascript")
    else:
        return render_to_response("cciw/officers/officer_list.html", context_instance=c)


@staff_member_required
@camp_admin_required
@json_response
def remove_officer(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)
    officer_id = request.POST['officer_id']
    Invitation.objects.filter(camp=camp.id, officer=int(officer_id)).delete()
    return {'status':'success'}


@staff_member_required
@camp_admin_required
@json_response
def add_officers(request, year=None, number=None):
    camp = _get_camp_or_404(year, number)
    for officer_id in request.POST['officer_ids'].split(','):
        Invitation.objects.get_or_create(camp=camp, officer=User.objects.get(id=int(officer_id)))
    return {'status':'success'}


@staff_member_required
@camp_admin_required
@json_response
def officer_details(request):
    user = User.objects.get(pk=int(request.GET['officer_id']))
    return {'username': user.username,
            'first_name': user.first_name,
            'last_name': user.last_name,
            'email': user.email,
            'id': user.id,
            }


@staff_member_required
@camp_admin_required
@json_response
def update_officer(request):
    User.objects.filter(pk=int(request.POST['officer_id'])).update(first_name=request.POST['first_name'],
                                                                   last_name=request.POST['last_name'],
                                                                   email=request.POST['email']
                                                                   )
    return {'status':'success'}


def update_email(request, username=''):
    c = {}
    u = get_object_or_404(User.objects.filter(username=username))
    email = request.GET.get('email', '')
    hash = request.GET.get('hash', '')

    if email == u.email:
        c['message'] = "The e-mail address has already been updated, thanks."
    else:
        if make_update_email_hash(u.email, email) != hash:
            c['message'] = "The URL was invalid. Please ensure you copied the URL from the e-mail correctly"
        else:
            c['message'] = "Your e-mail address has been updated, thanks."
            c['success'] = True
            u.email = email
            u.save()

    return render_to_response('cciw/officers/email_update.html',
                              context_instance=template.RequestContext(request, c))


class StripStringsMixin(object):
    def clean(self):
        for field,value in self.cleaned_data.items():
            if isinstance(value, basestring):
                self.cleaned_data[field] = value.strip()
        return self.cleaned_data


class BaseForm(StripStringsMixin, forms.Form):
    pass


class CreateOfficerForm(BaseForm):
    first_name = forms.CharField()
    last_name = forms.CharField()
    email = forms.EmailField()

    def save(self):
        return create.create_officer(None, self.cleaned_data['first_name'],
                                     self.cleaned_data['last_name'],
                                     self.cleaned_data['email'])


@staff_member_required
@camp_admin_required
def create_officer(request):
    allow_confirm = True
    duplicate_message = ""
    existing_users = None
    message = ""
    if request.method == "POST":
        form = CreateOfficerForm(request.POST)
        process_form = False
        if form.is_valid():
            if "add" in request.POST:
                same_name_users = User.objects.filter(first_name__iexact=form.cleaned_data['first_name'],
                                                      last_name__iexact=form.cleaned_data['last_name'])
                same_email_users = User.objects.filter(email__iexact=form.cleaned_data['email'])
                same_user = same_name_users & same_email_users
                if same_user.exists():
                    allow_confirm = False
                    duplicate_message = "A user with that name and e-mail address already exists. You can change the details above and try again."
                elif len(same_name_users) > 0:
                    existing_users = same_name_users
                    if len(existing_users) == 1:
                        duplicate_message = "A user with that first name and last name " + \
                                            "already exists:"
                    else:
                        duplicate_message = "%d users with that first name and last name " + \
                                            "already exist:" % len(existing_users)
                elif len(same_email_users):
                    existing_users = same_email_users
                    if len(existing_users) == 1:
                        duplicate_message = "A user with that e-mail address already exists:"
                    else:
                        duplicate_message = "%d users with that e-mail address already exist:"\
                                            % len(existing_users)
                else:
                    process_form = True

            elif "confirm" in request.POST:
                process_form = True

            if process_form:
                try:
                    u = form.save()
                    form = CreateOfficerForm()
                    messages.info(request, "Officer %s has been added and e-mailed.  You can add another if required, or close this popup to continue." % u.username)
                    camp_id = request.GET.get('camp_id')
                    if camp_id is not None:
                        Invitation.objects.get_or_create(camp=Camp.objects.get(id=camp_id), officer=u)
                except create.EmailError:
                    messages.error(request, "Due to a problem sending e-mail, the officer has not been added to the system.  Please try again later.")

    else:
        form = CreateOfficerForm()

    c = {'form': form,
         'duplicate_message': duplicate_message,
         'existing_users': existing_users,
         'allow_confirm': allow_confirm,
         'message': message,
         'is_popup': True,
         }
    return render_to_response('cciw/officers/create_officer.html',
                              context_instance=template.RequestContext(request, c))


@staff_member_required
@camp_admin_required
@json_response
def resend_email(request):
    u = User.objects.get(pk=int(request.POST['officer_id']))
    password = User.objects.make_random_password()
    u.set_password(password)
    u.save()
    create.email_officer(u.username, u.first_name, u.email, password, is_leader=False, update=True)
    return {'status':'success'}


officer_files = access_folder_securely("officers",
                                       lambda request: _is_camp_officer(request.user))


def date_to_js_ts(d):
    """
    Converts a date object to the timestamp required by the flot library
    """
    return int(d.strftime('%s'))*1000


def rank_data(data, key):
    """
    Given a list of data and a key function, returns a list of the ranks of the
    data, where equal data are given equal ranks, starting with 1.
    """
    # Decorate, keeping original order information
    combined = [[key(d), i, d] for i, d in enumerate(data)]
    # Sort by the key
    combined.sort(key=lambda x:x[0])
    # Calculate the ranks using already calculated keys
    current_rank = 0
    prev_row = None
    ranks = [None] * len(data)
    for row in combined:
        if prev_row is None or prev_row[0] != row[0]:
            # Different keys (or first time through)
            current_rank += 1
        ranks[row[1]] = current_rank
        prev_row = row
    return ranks, current_rank

@staff_member_required
@camp_admin_required
def stats(request, year=None):
    year = int(year)
    thisyear = common.get_thisyear()
    stats = []
    all_past = True
    for c in Camp.objects.filter(year=year).order_by('number'):
        stat = {}
        if not c.is_past():
            all_past = False
        stat['camp'] = c
        invited_officers_count = c.invitation_set.count()
        stat['invited_officers_count'] = invited_officers_count
        application_forms = applications_for_camp(c)
        app_ids = [a.id for a in application_forms]

        application_forms_count = len(app_ids)
        stat['application_forms_count'] = application_forms_count
        received_reference_set = Reference.objects.filter(received=True, application__in=app_ids)
        received_references_count = received_reference_set.count()
        expected_references = 2 * application_forms_count
        stat['received_references_count'] = received_references_count
        missing_references_count = expected_references - received_references_count
        stat['missing_references_count'] = missing_references_count
        if expected_references == 0:
            missing_references_percent = 0
        else:
            missing_references_percent = float(missing_references_count) / expected_references * 100.0
        stat['missing_references_percent'] = missing_references_percent
        # Officers with no references - trying not to do O(n) queries...
        r = set([r.application_id for r in received_reference_set])
        applications_no_reference = [a for a in application_forms if a.id not in r]
        stat['officers_no_reference'] = len(applications_no_reference)

        # Stats for graphs
        app_dates = [a.date_submitted for a in application_forms]
        app_dates.sort()
        reference_forms = ReferenceForm.objects.filter(reference_info__application__in=app_ids)
        ref_dates = [r.date_created for r in reference_forms]
        ref_dates.sort()

        # Make a plot by going through each day in the year before the camp and
        # incrementing a counter.
        graph_start_date = c.start_date - datetime.timedelta(365)
        graph_end_date = min(c.start_date, datetime.date.today())
        a = 0 # applications
        r = 0 # references
        app_dates_data = []
        ref_dates_data = []
        d = graph_start_date
        while d <= graph_end_date:
            # Application forms
            while a < len(app_dates) and app_dates[a] <= d:
                a += 1
            while r < len(ref_dates) and ref_dates[r] <= d:
                r += 1
            # Formats are those needed by 'flot' library
            ts = date_to_js_ts(d)
            app_dates_data.append([ts, a])
            ref_dates_data.append([ts, r/2.0])
            d = d + datetime.timedelta(1)
        stat['application_dates_data'] = app_dates_data
        stat['reference_dates_data'] = ref_dates_data
        stat['officer_list_data'] = [[date_to_js_ts(graph_start_date), invited_officers_count],
                                     [date_to_js_ts(graph_end_date), invited_officers_count]]
        stats.append(stat)

    # Those with no application forms yet are losing, then it goes on the
    # fraction of references that are missing.
    ranks, max_rank = rank_data(stats, lambda d: (d['application_forms_count'] == 0,
                                                  d['missing_references_percent']))
    for stat, rank in zip(stats, ranks):
        stat['rank'] = rank
        stat['lowest_rank'] = max_rank

    d = {}
    d['stats'] = stats
    d['year'] = year
    d['all_past'] = all_past
    return render_to_response('cciw/officers/stats.html',
                              context_instance=template.RequestContext(request, d))


class AddCrbForm(forms.ModelForm):
    class Meta:
        model = CRBApplication
        fields = ('crb_number',
                  'completed',
                  )
AddCrbForm.base_fields['completed'].widget = widgets.AdminDateWidget()

@staff_member_required
def add_crb(request):
    """
    Form for an officer to add info about their CRB applications
    """
    if request.method == "POST":
        form = AddCrbForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.officer = request.user
            obj.save()
            messages.info(request, "CRB information added, thank you.")
            return HttpResponseRedirect(reverse('cciw.officers.views.index'))
    else:
        form = AddCrbForm()
    c = {'form': form}

    return render_to_response('cciw/officers/add_crb.html',
                              context_instance=template.RequestContext(request, c))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.