~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/admin/subject.py

  • Committer: William Grant
  • Date: 2009-06-23 12:21:45 UTC
  • Revision ID: grantw@unimelb.edu.au-20090623122145-wb0chy9qha8h9u9r
Define IVLEError.message explicitly, as BaseException.message is deprecated and generates warnings.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
import urlparse
29
29
import cgi
30
30
 
31
 
from storm.locals import Desc, Store
 
31
from storm.locals import Desc
32
32
import genshi
33
33
from genshi.filters import HTMLFormFiller
34
34
from genshi.template import Context, TemplateLoader
35
35
import formencode
36
 
import formencode.validators
37
36
 
38
 
from ivle.webapp.base.forms import BaseFormView, URLNameValidator
 
37
from ivle.webapp.base.xhtml import XHTMLView
39
38
from ivle.webapp.base.plugins import ViewPlugin, MediaPlugin
40
 
from ivle.webapp.base.xhtml import XHTMLView
41
 
from ivle.webapp.errors import BadRequest
42
 
from ivle.webapp import ApplicationRoot
 
39
from ivle.webapp.errors import NotFound
43
40
 
44
41
from ivle.database import Subject, Semester, Offering, Enrolment, User,\
45
42
                          ProjectSet, Project, ProjectSubmission
46
43
from ivle import util
47
44
import ivle.date
48
45
 
49
 
from ivle.webapp.admin.projectservice import ProjectSetRESTView
 
46
from ivle.webapp.admin.projectservice import ProjectSetRESTView,\
 
47
                                             ProjectRESTView
50
48
from ivle.webapp.admin.offeringservice import OfferingRESTView
51
 
from ivle.webapp.admin.publishing import (root_to_subject, root_to_semester,
52
 
            subject_to_offering, offering_to_projectset, offering_to_project,
53
 
            offering_to_enrolment, subject_url, semester_url, offering_url,
54
 
            projectset_url, project_url, enrolment_url)
55
 
from ivle.webapp.admin.breadcrumbs import (SubjectBreadcrumb,
56
 
            OfferingBreadcrumb, UserBreadcrumb, ProjectBreadcrumb,
57
 
            EnrolmentBreadcrumb)
58
 
from ivle.webapp.core import Plugin as CorePlugin
59
 
from ivle.webapp.groups import GroupsView
60
 
from ivle.webapp.media import media_url
61
 
from ivle.webapp.tutorial import Plugin as TutorialPlugin
 
49
 
62
50
 
63
51
class SubjectsView(XHTMLView):
64
52
    '''The view of the list of subjects.'''
65
53
    template = 'templates/subjects.html'
66
54
    tab = 'subjects'
67
 
    breadcrumb_text = "Subjects"
68
55
 
69
56
    def authorize(self, req):
70
57
        return req.user is not None
71
58
 
72
59
    def populate(self, req, ctx):
73
 
        ctx['req'] = req
74
60
        ctx['user'] = req.user
75
61
        ctx['semesters'] = []
76
 
 
77
62
        for semester in req.store.find(Semester).order_by(Desc(Semester.year),
78
63
                                                     Desc(Semester.semester)):
79
 
            if req.user.admin:
80
 
                # For admins, show all subjects in the system
81
 
                offerings = list(semester.offerings.find())
82
 
            else:
83
 
                offerings = [enrolment.offering for enrolment in
84
 
                                    semester.enrolments.find(user=req.user)]
85
 
            if len(offerings):
86
 
                ctx['semesters'].append((semester, offerings))
87
 
 
88
 
 
89
 
class SubjectsManage(XHTMLView):
90
 
    '''Subject management view.'''
91
 
    template = 'templates/subjects-manage.html'
92
 
    tab = 'subjects'
93
 
 
94
 
    def authorize(self, req):
95
 
        return req.user is not None and req.user.admin
96
 
 
97
 
    def populate(self, req, ctx):
98
 
        ctx['req'] = req
99
 
        ctx['mediapath'] = media_url(req, CorePlugin, 'images/')
100
 
        ctx['SubjectView'] = SubjectView
101
 
        ctx['SubjectEdit'] = SubjectEdit
102
 
        ctx['SemesterEdit'] = SemesterEdit
103
 
 
104
 
        ctx['subjects'] = req.store.find(Subject).order_by(Subject.name)
105
 
        ctx['semesters'] = req.store.find(Semester).order_by(
106
 
            Semester.year, Semester.semester)
107
 
 
108
 
 
109
 
class SubjectShortNameUniquenessValidator(formencode.FancyValidator):
110
 
    """A FormEncode validator that checks that a subject name is unused.
111
 
 
112
 
    The subject referenced by state.existing_subject is permitted
113
 
    to hold that name. If any other object holds it, the input is rejected.
114
 
    """
115
 
    def __init__(self, matching=None):
116
 
        self.matching = matching
117
 
 
118
 
    def _to_python(self, value, state):
119
 
        if (state.store.find(
120
 
                Subject, short_name=value).one() not in
121
 
                (None, state.existing_subject)):
122
 
            raise formencode.Invalid(
123
 
                'Short name already taken', value, state)
124
 
        return value
125
 
 
126
 
 
127
 
class SubjectSchema(formencode.Schema):
128
 
    short_name = formencode.All(
129
 
        SubjectShortNameUniquenessValidator(),
130
 
        URLNameValidator(not_empty=True))
131
 
    name = formencode.validators.UnicodeString(not_empty=True)
132
 
    code = formencode.validators.UnicodeString(not_empty=True)
133
 
 
134
 
 
135
 
class SubjectFormView(BaseFormView):
136
 
    """An abstract form to add or edit a subject."""
137
 
    tab = 'subjects'
138
 
 
139
 
    def authorize(self, req):
140
 
        return req.user is not None and req.user.admin
141
 
 
142
 
    def populate_state(self, state):
143
 
        state.existing_subject = None
144
 
 
145
 
    @property
146
 
    def validator(self):
147
 
        return SubjectSchema()
148
 
 
149
 
 
150
 
class SubjectNew(SubjectFormView):
151
 
    """A form to create a subject."""
152
 
    template = 'templates/subject-new.html'
153
 
 
154
 
    def get_default_data(self, req):
155
 
        return {}
156
 
 
157
 
    def save_object(self, req, data):
158
 
        new_subject = Subject()
159
 
        new_subject.short_name = data['short_name']
160
 
        new_subject.name = data['name']
161
 
        new_subject.code = data['code']
162
 
 
163
 
        req.store.add(new_subject)
164
 
        return new_subject
165
 
 
166
 
 
167
 
class SubjectEdit(SubjectFormView):
168
 
    """A form to edit a subject."""
169
 
    template = 'templates/subject-edit.html'
170
 
 
171
 
    def populate_state(self, state):
172
 
        state.existing_subject = self.context
173
 
 
174
 
    def get_default_data(self, req):
175
 
        return {
176
 
            'short_name': self.context.short_name,
177
 
            'name': self.context.name,
178
 
            'code': self.context.code,
179
 
            }
180
 
 
181
 
    def save_object(self, req, data):
182
 
        self.context.short_name = data['short_name']
183
 
        self.context.name = data['name']
184
 
        self.context.code = data['code']
185
 
 
186
 
        return self.context
187
 
 
188
 
 
189
 
class SemesterUniquenessValidator(formencode.FancyValidator):
190
 
    """A FormEncode validator that checks that a semester is unique.
191
 
 
192
 
    There cannot be more than one semester for the same year and semester.
193
 
    """
194
 
    def _to_python(self, value, state):
195
 
        if (state.store.find(
196
 
                Semester, year=value['year'], semester=value['semester']
197
 
                ).one() not in (None, state.existing_semester)):
198
 
            raise formencode.Invalid(
199
 
                'Semester already exists', value, state)
200
 
        return value
201
 
 
202
 
 
203
 
class SemesterSchema(formencode.Schema):
204
 
    year = URLNameValidator()
205
 
    semester = URLNameValidator()
206
 
    state = formencode.All(
207
 
        formencode.validators.OneOf(["past", "current", "future"]),
208
 
        formencode.validators.UnicodeString())
209
 
    chained_validators = [SemesterUniquenessValidator()]
210
 
 
211
 
 
212
 
class SemesterFormView(BaseFormView):
213
 
    tab = 'subjects'
214
 
 
215
 
    def authorize(self, req):
216
 
        return req.user is not None and req.user.admin
217
 
 
218
 
    @property
219
 
    def validator(self):
220
 
        return SemesterSchema()
221
 
 
222
 
    def get_return_url(self, obj):
223
 
        return '/subjects/+manage'
224
 
 
225
 
 
226
 
class SemesterNew(SemesterFormView):
227
 
    """A form to create a semester."""
228
 
    template = 'templates/semester-new.html'
229
 
    tab = 'subjects'
230
 
 
231
 
    def populate_state(self, state):
232
 
        state.existing_semester = None
233
 
 
234
 
    def get_default_data(self, req):
235
 
        return {}
236
 
 
237
 
    def save_object(self, req, data):
238
 
        new_semester = Semester()
239
 
        new_semester.year = data['year']
240
 
        new_semester.semester = data['semester']
241
 
        new_semester.state = data['state']
242
 
 
243
 
        req.store.add(new_semester)
244
 
        return new_semester
245
 
 
246
 
 
247
 
class SemesterEdit(SemesterFormView):
248
 
    """A form to edit a semester."""
249
 
    template = 'templates/semester-edit.html'
250
 
 
251
 
    def populate_state(self, state):
252
 
        state.existing_semester = self.context
253
 
 
254
 
    def get_default_data(self, req):
255
 
        return {
256
 
            'year': self.context.year,
257
 
            'semester': self.context.semester,
258
 
            'state': self.context.state,
259
 
            }
260
 
 
261
 
    def save_object(self, req, data):
262
 
        self.context.year = data['year']
263
 
        self.context.semester = data['semester']
264
 
        self.context.state = data['state']
265
 
 
266
 
        return self.context
267
 
 
268
 
class SubjectView(XHTMLView):
269
 
    '''The view of the list of offerings in a given subject.'''
270
 
    template = 'templates/subject.html'
271
 
    tab = 'subjects'
272
 
 
273
 
    def authorize(self, req):
274
 
        return req.user is not None
275
 
 
276
 
    def populate(self, req, ctx):
277
 
        ctx['context'] = self.context
278
 
        ctx['req'] = req
279
 
        ctx['user'] = req.user
280
 
        ctx['offerings'] = list(self.context.offerings)
281
 
        ctx['permissions'] = self.context.get_permissions(req.user,req.config)
282
 
        ctx['SubjectEdit'] = SubjectEdit
283
 
        ctx['SubjectOfferingNew'] = SubjectOfferingNew
284
 
 
285
 
 
286
 
class OfferingView(XHTMLView):
287
 
    """The home page of an offering."""
288
 
    template = 'templates/offering.html'
289
 
    tab = 'subjects'
290
 
    permission = 'view'
291
 
 
292
 
    def populate(self, req, ctx):
293
 
        # Need the worksheet result styles.
294
 
        self.plugin_styles[TutorialPlugin] = ['tutorial.css']
295
 
        ctx['context'] = self.context
296
 
        ctx['req'] = req
297
 
        ctx['permissions'] = self.context.get_permissions(req.user,req.config)
298
 
        ctx['format_submission_principal'] = util.format_submission_principal
299
 
        ctx['format_datetime'] = ivle.date.make_date_nice
300
 
        ctx['format_datetime_short'] = ivle.date.format_datetime_for_paragraph
301
 
        ctx['OfferingEdit'] = OfferingEdit
302
 
        ctx['OfferingCloneWorksheets'] = OfferingCloneWorksheets
303
 
        ctx['GroupsView'] = GroupsView
304
 
        ctx['EnrolmentsView'] = EnrolmentsView
305
 
 
306
 
        # As we go, calculate the total score for this subject
307
 
        # (Assessable worksheets only, mandatory problems only)
308
 
 
309
 
        ctx['worksheets'], problems_total, problems_done = (
310
 
            ivle.worksheet.utils.create_list_of_fake_worksheets_and_stats(
311
 
                req.store, req.user, self.context))
312
 
 
313
 
        ctx['exercises_total'] = problems_total
314
 
        ctx['exercises_done'] = problems_done
315
 
        if problems_total > 0:
316
 
            if problems_done >= problems_total:
317
 
                ctx['worksheets_complete_class'] = "complete"
318
 
            elif problems_done > 0:
319
 
                ctx['worksheets_complete_class'] = "semicomplete"
320
 
            else:
321
 
                ctx['worksheets_complete_class'] = "incomplete"
322
 
            # Calculate the final percentage and mark for the subject
323
 
            (ctx['exercises_pct'], ctx['worksheet_mark'],
324
 
             ctx['worksheet_max_mark']) = (
325
 
                ivle.worksheet.utils.calculate_mark(
326
 
                    problems_done, problems_total))
327
 
 
328
 
 
329
 
class SubjectValidator(formencode.FancyValidator):
330
 
    """A FormEncode validator that turns a subject name into a subject.
331
 
 
332
 
    The state must have a 'store' attribute, which is the Storm store
333
 
    to use.
334
 
    """
335
 
    def _to_python(self, value, state):
336
 
        subject = state.store.find(Subject, short_name=value).one()
337
 
        if subject:
338
 
            return subject
339
 
        else:
340
 
            raise formencode.Invalid('Subject does not exist', value, state)
341
 
 
342
 
 
343
 
class SemesterValidator(formencode.FancyValidator):
344
 
    """A FormEncode validator that turns a string into a semester.
345
 
 
346
 
    The string should be of the form 'year/semester', eg. '2009/1'.
347
 
 
348
 
    The state must have a 'store' attribute, which is the Storm store
349
 
    to use.
350
 
    """
351
 
    def _to_python(self, value, state):
352
 
        try:
353
 
            year, semester = value.split('/')
354
 
        except ValueError:
355
 
            year = semester = None
356
 
 
357
 
        semester = state.store.find(
358
 
            Semester, year=year, semester=semester).one()
359
 
        if semester:
360
 
            return semester
361
 
        else:
362
 
            raise formencode.Invalid('Semester does not exist', value, state)
363
 
 
364
 
 
365
 
class OfferingUniquenessValidator(formencode.FancyValidator):
366
 
    """A FormEncode validator that checks that an offering is unique.
367
 
 
368
 
    There cannot be more than one offering in the same year and semester.
369
 
 
370
 
    The offering referenced by state.existing_offering is permitted to
371
 
    hold that year and semester tuple. If any other object holds it, the
372
 
    input is rejected.
373
 
    """
374
 
    def _to_python(self, value, state):
375
 
        if (state.store.find(
376
 
                Offering, subject=value['subject'],
377
 
                semester=value['semester']).one() not in
378
 
                (None, state.existing_offering)):
379
 
            raise formencode.Invalid(
380
 
                'Offering already exists', value, state)
381
 
        return value
382
 
 
383
 
 
384
 
class OfferingSchema(formencode.Schema):
385
 
    description = formencode.validators.UnicodeString(
386
 
        if_missing=None, not_empty=False)
387
 
    url = formencode.validators.URL(if_missing=None, not_empty=False)
388
 
 
389
 
 
390
 
class OfferingAdminSchema(OfferingSchema):
391
 
    subject = formencode.All(
392
 
        SubjectValidator(), formencode.validators.UnicodeString())
393
 
    semester = formencode.All(
394
 
        SemesterValidator(), formencode.validators.UnicodeString())
395
 
    chained_validators = [OfferingUniquenessValidator()]
396
 
 
397
 
 
398
 
class OfferingEdit(BaseFormView):
399
 
    """A form to edit an offering's details."""
400
 
    template = 'templates/offering-edit.html'
401
 
    tab = 'subjects'
402
 
    permission = 'edit'
403
 
 
404
 
    @property
405
 
    def validator(self):
406
 
        if self.req.user.admin:
407
 
            return OfferingAdminSchema()
408
 
        else:
409
 
            return OfferingSchema()
410
 
 
411
 
    def populate(self, req, ctx):
412
 
        super(OfferingEdit, self).populate(req, ctx)
413
 
        ctx['subjects'] = req.store.find(Subject).order_by(Subject.name)
414
 
        ctx['semesters'] = req.store.find(Semester).order_by(
415
 
            Semester.year, Semester.semester)
416
 
        ctx['force_subject'] = None
417
 
 
418
 
    def populate_state(self, state):
419
 
        state.existing_offering = self.context
420
 
 
421
 
    def get_default_data(self, req):
422
 
        return {
423
 
            'subject': self.context.subject.short_name,
424
 
            'semester': self.context.semester.year + '/' +
425
 
                        self.context.semester.semester,
426
 
            'url': self.context.url,
427
 
            'description': self.context.description,
428
 
            }
429
 
 
430
 
    def save_object(self, req, data):
431
 
        if req.user.admin:
432
 
            self.context.subject = data['subject']
433
 
            self.context.semester = data['semester']
434
 
        self.context.description = data['description']
435
 
        self.context.url = unicode(data['url']) if data['url'] else None
436
 
        return self.context
437
 
 
438
 
 
439
 
class OfferingNew(BaseFormView):
440
 
    """A form to create an offering."""
441
 
    template = 'templates/offering-new.html'
442
 
    tab = 'subjects'
443
 
 
444
 
    def authorize(self, req):
445
 
        return req.user is not None and req.user.admin
446
 
 
447
 
    @property
448
 
    def validator(self):
449
 
        return OfferingAdminSchema()
450
 
 
451
 
    def populate(self, req, ctx):
452
 
        super(OfferingNew, self).populate(req, ctx)
453
 
        ctx['subjects'] = req.store.find(Subject).order_by(Subject.name)
454
 
        ctx['semesters'] = req.store.find(Semester).order_by(
455
 
            Semester.year, Semester.semester)
456
 
        ctx['force_subject'] = None
457
 
 
458
 
    def populate_state(self, state):
459
 
        state.existing_offering = None
460
 
 
461
 
    def get_default_data(self, req):
462
 
        return {}
463
 
 
464
 
    def save_object(self, req, data):
465
 
        new_offering = Offering()
466
 
        new_offering.subject = data['subject']
467
 
        new_offering.semester = data['semester']
468
 
        new_offering.description = data['description']
469
 
        new_offering.url = unicode(data['url']) if data['url'] else None
470
 
 
471
 
        req.store.add(new_offering)
472
 
        return new_offering
473
 
 
474
 
class SubjectOfferingNew(OfferingNew):
475
 
    """A form to create an offering for a given subject."""
476
 
    # Identical to OfferingNew, except it forces the subject to be the subject
477
 
    # in context
478
 
    def populate(self, req, ctx):
479
 
        super(SubjectOfferingNew, self).populate(req, ctx)
480
 
        ctx['force_subject'] = self.context
481
 
 
482
 
class OfferingCloneWorksheetsSchema(formencode.Schema):
483
 
    subject = formencode.All(
484
 
        SubjectValidator(), formencode.validators.UnicodeString())
485
 
    semester = formencode.All(
486
 
        SemesterValidator(), formencode.validators.UnicodeString())
487
 
 
488
 
 
489
 
class OfferingCloneWorksheets(BaseFormView):
490
 
    """A form to clone worksheets from one offering to another."""
491
 
    template = 'templates/offering-clone-worksheets.html'
492
 
    tab = 'subjects'
493
 
 
494
 
    def authorize(self, req):
495
 
        return req.user is not None and req.user.admin
496
 
 
497
 
    @property
498
 
    def validator(self):
499
 
        return OfferingCloneWorksheetsSchema()
500
 
 
501
 
    def populate(self, req, ctx):
502
 
        super(OfferingCloneWorksheets, self).populate(req, ctx)
503
 
        ctx['subjects'] = req.store.find(Subject).order_by(Subject.name)
504
 
        ctx['semesters'] = req.store.find(Semester).order_by(
505
 
            Semester.year, Semester.semester)
506
 
 
507
 
    def get_default_data(self, req):
508
 
        return {}
509
 
 
510
 
    def save_object(self, req, data):
511
 
        if self.context.worksheets.count() > 0:
512
 
            raise BadRequest(
513
 
                "Cannot clone to target with existing worksheets.")
514
 
        offering = req.store.find(
515
 
            Offering, subject=data['subject'], semester=data['semester']).one()
516
 
        if offering is None:
517
 
            raise BadRequest("No such offering.")
518
 
        if offering.worksheets.count() == 0:
519
 
            raise BadRequest("Source offering has no worksheets.")
520
 
 
521
 
        self.context.clone_worksheets(offering)
522
 
        return self.context
 
64
            enrolments = semester.enrolments.find(user=req.user)
 
65
            if enrolments.count():
 
66
                ctx['semesters'].append((semester, enrolments))
523
67
 
524
68
 
525
69
class UserValidator(formencode.FancyValidator):
546
90
        return value
547
91
 
548
92
 
549
 
class RoleEnrolmentValidator(formencode.FancyValidator):
550
 
    """A FormEncode validator that checks permission to enrol users with a
551
 
    particular role.
552
 
 
553
 
    The state must have an 'offering' attribute.
554
 
    """
555
 
    def _to_python(self, value, state):
556
 
        if (("enrol_" + value) not in
557
 
                state.offering.get_permissions(state.user, state.config)):
558
 
            raise formencode.Invalid('Not allowed to assign users that role',
559
 
                                     value, state)
560
 
        return value
561
 
 
562
 
 
563
93
class EnrolSchema(formencode.Schema):
564
94
    user = formencode.All(NoEnrolmentValidator(), UserValidator())
565
 
    role = formencode.All(formencode.validators.OneOf(
566
 
                                ["lecturer", "tutor", "student"]),
567
 
                          RoleEnrolmentValidator(),
568
 
                          formencode.validators.UnicodeString())
569
 
 
570
 
 
571
 
class EnrolmentsView(XHTMLView):
572
 
    """A page which displays all users enrolled in an offering."""
573
 
    template = 'templates/enrolments.html'
574
 
    tab = 'subjects'
575
 
    permission = 'edit'
576
 
    breadcrumb_text = 'Enrolments'
577
 
 
578
 
    def populate(self, req, ctx):
579
 
        ctx['req'] = req
580
 
        ctx['offering'] = self.context
581
 
        ctx['mediapath'] = media_url(req, CorePlugin, 'images/')
582
 
        ctx['offering_perms'] = self.context.get_permissions(
583
 
            req.user, req.config)
584
 
        ctx['EnrolView'] = EnrolView
585
 
        ctx['EnrolmentEdit'] = EnrolmentEdit
586
 
        ctx['EnrolmentDelete'] = EnrolmentDelete
587
95
 
588
96
 
589
97
class EnrolView(XHTMLView):
590
98
    """A form to enrol a user in an offering."""
591
99
    template = 'templates/enrol.html'
592
100
    tab = 'subjects'
593
 
    permission = 'enrol'
 
101
    permission = 'edit'
 
102
 
 
103
    def __init__(self, req, subject, year, semester):
 
104
        """Find the given offering by subject, year and semester."""
 
105
        self.context = req.store.find(Offering,
 
106
            Offering.subject_id == Subject.id,
 
107
            Subject.short_name == subject,
 
108
            Offering.semester_id == Semester.id,
 
109
            Semester.year == year,
 
110
            Semester.semester == semester).one()
 
111
 
 
112
        if not self.context:
 
113
            raise NotFound()
594
114
 
595
115
    def filter(self, stream, ctx):
596
116
        return stream | HTMLFormFiller(data=ctx['data'])
602
122
                validator = EnrolSchema()
603
123
                req.offering = self.context # XXX: Getting into state.
604
124
                data = validator.to_python(data, state=req)
605
 
                self.context.enrol(data['user'], data['role'])
 
125
                self.context.enrol(data['user'])
606
126
                req.store.commit()
607
127
                req.throw_redirect(req.uri)
608
128
            except formencode.Invalid, e:
613
133
 
614
134
        ctx['data'] = data or {}
615
135
        ctx['offering'] = self.context
616
 
        ctx['roles_auth'] = self.context.get_permissions(req.user, req.config)
617
136
        ctx['errors'] = errors
618
137
 
619
 
 
620
 
class EnrolmentEditSchema(formencode.Schema):
621
 
    role = formencode.All(formencode.validators.OneOf(
622
 
                                ["lecturer", "tutor", "student"]),
623
 
                          RoleEnrolmentValidator(),
624
 
                          formencode.validators.UnicodeString())
625
 
 
626
 
 
627
 
class EnrolmentEdit(BaseFormView):
628
 
    """A form to alter an enrolment's role."""
629
 
    template = 'templates/enrolment-edit.html'
630
 
    tab = 'subjects'
631
 
    permission = 'edit'
632
 
 
633
 
    def populate_state(self, state):
634
 
        state.offering = self.context.offering
635
 
 
636
 
    def get_default_data(self, req):
637
 
        return {'role': self.context.role}
638
 
 
639
 
    @property
640
 
    def validator(self):
641
 
        return EnrolmentEditSchema()
642
 
 
643
 
    def save_object(self, req, data):
644
 
        self.context.role = data['role']
645
 
 
646
 
    def get_return_url(self, obj):
647
 
        return self.req.publisher.generate(
648
 
            self.context.offering, EnrolmentsView)
649
 
 
650
 
    def populate(self, req, ctx):
651
 
        super(EnrolmentEdit, self).populate(req, ctx)
652
 
        ctx['offering_perms'] = self.context.offering.get_permissions(
653
 
            req.user, req.config)
654
 
 
655
 
 
656
 
class EnrolmentDelete(XHTMLView):
657
 
    """A form to alter an enrolment's role."""
658
 
    template = 'templates/enrolment-delete.html'
659
 
    tab = 'subjects'
660
 
    permission = 'edit'
661
 
 
662
 
    def populate(self, req, ctx):
663
 
        # If POSTing, delete delete delete.
664
 
        if req.method == 'POST':
665
 
            self.context.delete()
666
 
            req.store.commit()
667
 
            req.throw_redirect(req.publisher.generate(
668
 
                self.context.offering, EnrolmentsView))
669
 
 
670
 
        ctx['enrolment'] = self.context
671
 
 
672
 
 
673
138
class OfferingProjectsView(XHTMLView):
674
139
    """View the projects for an offering."""
675
140
    template = 'templates/offering_projects.html'
676
141
    permission = 'edit'
677
142
    tab = 'subjects'
678
 
    breadcrumb_text = 'Projects'
679
 
 
 
143
    
 
144
    def __init__(self, req, subject, year, semester):
 
145
        self.context = req.store.find(Offering,
 
146
            Offering.subject_id == Subject.id,
 
147
            Subject.short_name == subject,
 
148
            Offering.semester_id == Semester.id,
 
149
            Semester.year == year,
 
150
            Semester.semester == semester).one()
 
151
 
 
152
        if not self.context:
 
153
            raise NotFound()
 
154
 
 
155
    def project_url(self, projectset, project):
 
156
        return "/subjects/%s/%s/%s/+projects/%s" % (
 
157
                    self.context.subject.short_name,
 
158
                    self.context.semester.year,
 
159
                    self.context.semester.semester,
 
160
                    project.short_name
 
161
                    )
 
162
 
 
163
    def new_project_url(self, projectset):
 
164
        return "/api/subjects/" + self.context.subject.short_name + "/" +\
 
165
                self.context.semester.year + "/" + \
 
166
                self.context.semester.semester + "/+projectsets/" +\
 
167
                str(projectset.id) + "/+projects/+new"
 
168
    
680
169
    def populate(self, req, ctx):
681
170
        self.plugin_styles[Plugin] = ["project.css"]
682
171
        self.plugin_scripts[Plugin] = ["project.js"]
683
 
        ctx['req'] = req
684
172
        ctx['offering'] = self.context
685
173
        ctx['projectsets'] = []
686
 
        ctx['OfferingRESTView'] = OfferingRESTView
687
174
 
688
175
        #Open the projectset Fragment, and render it for inclusion
689
176
        #into the ProjectSets page
698
185
        for projectset in self.context.project_sets:
699
186
            settmpl = loader.load(set_fragment)
700
187
            setCtx = Context()
701
 
            setCtx['req'] = req
702
188
            setCtx['projectset'] = projectset
 
189
            setCtx['new_project_url'] = self.new_project_url(projectset)
703
190
            setCtx['projects'] = []
704
 
            setCtx['GroupsView'] = GroupsView
705
 
            setCtx['ProjectSetRESTView'] = ProjectSetRESTView
706
191
 
707
192
            for project in projectset.projects:
708
193
                projecttmpl = loader.load(project_fragment)
709
194
                projectCtx = Context()
710
 
                projectCtx['req'] = req
711
195
                projectCtx['project'] = project
 
196
                projectCtx['project_url'] = self.project_url(projectset, project)
712
197
 
713
198
                setCtx['projects'].append(
714
199
                        projecttmpl.generate(projectCtx))
719
204
class ProjectView(XHTMLView):
720
205
    """View the submissions for a ProjectSet"""
721
206
    template = "templates/project.html"
722
 
    permission = "view_project_submissions"
 
207
    permission = "edit"
723
208
    tab = 'subjects'
724
209
 
 
210
    def __init__(self, req, subject, year, semester, project):
 
211
        self.context = req.store.find(Project,
 
212
                Project.short_name == project,
 
213
                Project.project_set_id == ProjectSet.id,
 
214
                ProjectSet.offering_id == Offering.id,
 
215
                Offering.semester_id == Semester.id,
 
216
                Semester.year == year,
 
217
                Semester.semester == semester,
 
218
                Offering.subject_id == Subject.id,
 
219
                Subject.short_name == subject).one()
 
220
        if self.context is None:
 
221
            raise NotFound()
 
222
 
725
223
    def build_subversion_url(self, svnroot, submission):
726
224
        princ = submission.assessed.principal
727
225
 
743
241
    def populate(self, req, ctx):
744
242
        self.plugin_styles[Plugin] = ["project.css"]
745
243
 
746
 
        ctx['req'] = req
747
 
        ctx['GroupsView'] = GroupsView
748
 
        ctx['EnrolView'] = EnrolView
749
244
        ctx['format_datetime_short'] = ivle.date.format_datetime_for_paragraph
750
245
        ctx['build_subversion_url'] = self.build_subversion_url
751
246
        ctx['svn_addr'] = req.config['urls']['svn_addr']
753
248
        ctx['user'] = req.user
754
249
 
755
250
class Plugin(ViewPlugin, MediaPlugin):
756
 
    forward_routes = (root_to_subject, root_to_semester, subject_to_offering,
757
 
                      offering_to_project, offering_to_projectset,
758
 
                      offering_to_enrolment)
759
 
    reverse_routes = (
760
 
        subject_url, semester_url, offering_url, projectset_url, project_url,
761
 
        enrolment_url)
762
 
 
763
 
    views = [(ApplicationRoot, ('subjects', '+index'), SubjectsView),
764
 
             (ApplicationRoot, ('subjects', '+manage'), SubjectsManage),
765
 
             (ApplicationRoot, ('subjects', '+new'), SubjectNew),
766
 
             (ApplicationRoot, ('subjects', '+new-offering'), OfferingNew),
767
 
             (ApplicationRoot, ('+semesters', '+new'), SemesterNew),
768
 
             (Subject, '+index', SubjectView),
769
 
             (Subject, '+edit', SubjectEdit),
770
 
             (Subject, '+new-offering', SubjectOfferingNew),
771
 
             (Semester, '+edit', SemesterEdit),
772
 
             (Offering, '+index', OfferingView),
773
 
             (Offering, '+edit', OfferingEdit),
774
 
             (Offering, '+clone-worksheets', OfferingCloneWorksheets),
775
 
             (Offering, ('+enrolments', '+index'), EnrolmentsView),
776
 
             (Offering, ('+enrolments', '+new'), EnrolView),
777
 
             (Enrolment, '+edit', EnrolmentEdit),
778
 
             (Enrolment, '+delete', EnrolmentDelete),
779
 
             (Offering, ('+projects', '+index'), OfferingProjectsView),
780
 
             (Project, '+index', ProjectView),
781
 
 
782
 
             (Offering, ('+projectsets', '+new'), OfferingRESTView, 'api'),
783
 
             (ProjectSet, ('+projects', '+new'), ProjectSetRESTView, 'api'),
784
 
             ]
785
 
 
786
 
    breadcrumbs = {Subject: SubjectBreadcrumb,
787
 
                   Offering: OfferingBreadcrumb,
788
 
                   User: UserBreadcrumb,
789
 
                   Project: ProjectBreadcrumb,
790
 
                   Enrolment: EnrolmentBreadcrumb,
791
 
                   }
 
251
    urls = [
 
252
        ('subjects/', SubjectsView),
 
253
        ('subjects/:subject/:year/:semester/+enrolments/+new', EnrolView),
 
254
        ('subjects/:subject/:year/:semester/+projects', OfferingProjectsView),
 
255
        ('subjects/:subject/:year/:semester/+projects/:project', ProjectView),
 
256
        #API Views
 
257
        ('api/subjects/:subject/:year/:semester/+projectsets/+new',
 
258
            OfferingRESTView),
 
259
        ('api/subjects/:subject/:year/:semester/+projectsets/:projectset/+projects/+new',
 
260
            ProjectSetRESTView),
 
261
        ('api/subjects/:subject/:year/:semester/+projects/:project', 
 
262
            ProjectRESTView),
 
263
 
 
264
    ]
792
265
 
793
266
    tabs = [
794
267
        ('subjects', 'Subjects',