def choices(self): """Get a list of the possible choices for report activities.""" result = { 'name': _('Choose a report activity'), 'value': '', } results = [result] root = IGradebookRoot(ISchoolToolApplication(None)) term = self.context schoolyear = ISchoolYear(term) deployedKey = '%s_%s' % (schoolyear.__name__, term.__name__) for key in root.deployed: if key.startswith(deployedKey): deployedWorksheet = root.deployed[key] for activity in deployedWorksheet.values(): if ICommentScoreSystem.providedBy(activity.scoresystem): continue name = '%s - %s - %s' % (term.title, deployedWorksheet.title, activity.title) value = '%s|%s|%s' % (term.__name__, deployedWorksheet.__name__, activity.__name__) result = { 'name': name, 'value': value, } results.append(result) return results
def createTerms(self, term): result = [] result.append(self.createTerm( None, z3c.form.widget.SequenceWidget.noValueToken, _("Select a source"), )) root = IGradebookRoot(ISchoolToolApplication(None)) schoolyear = ISchoolYear(term) deployedKey = '%s_%s' % (schoolyear.__name__, term.__name__) for key in root.deployed: if key.startswith(deployedKey): deployedWorksheet = root.deployed[key] for activity in deployedWorksheet.values(): if ICommentScoreSystem.providedBy(activity.scoresystem): continue title = '%s - %s - %s' % (term.title, deployedWorksheet.title, activity.title) token = '%s-%s-%s' % (term.__name__, deployedWorksheet.__name__, activity.__name__) token=unicode(token).encode('punycode') result.append(self.createTerm( (deployedWorksheet, activity,), token, title, )) return result
def script(self): zc.resourcelibrary.need("ckeditor") config = self.config app_url = absoluteURL(ISchoolToolApplication(None), self.request) config_path = '%s%s' % (app_url, config.path) # XXX: using some values that may be not JS safe return ''' <script type="text/javascript" language="JavaScript"> var %(variable)s = new CKEDITOR.replace("%(id)s", { height: %(height)s, width: %(width)s, customConfig: "%(customConfigPath)s" } ); </script> ''' % { 'id': self.element_id, 'variable': self.editor_var_name, 'width': config.width, 'height': config.height, 'toolbar': config.toolbar, 'customConfigPath': config_path, }
def __call__(self): app = ISchoolToolApplication(None) person = IPerson(self.request.principal, None) if not person: raise Unauthorized("Only logged in users can book resources.") cal = ISchoolToolCalendar(person) if self.request.has_key('event_id'): event = cal.find(self.request['event_id']) else: start_date = self.request.get('start_date') start_time = self.request.get('start_time') title = self.request.get('title') start_datetime = "%s %s" % (start_date, start_time) start_datetime = datetime(*strptime(start_datetime, "%Y-%m-%d %H:%M")[0:6]) start_datetime = self.timezone.localize(start_datetime) start_datetime = start_datetime.astimezone(pytz.UTC) duration = timedelta(seconds=int(self.request.get('duration'))) event = CalendarEvent(dtstart = start_datetime, duration = duration, title = title) cal.addEvent(event) if event: resource = app["resources"].get(self.request['resource_id']) if resource is not None: resource_calendar = ISchoolToolCalendar(resource) if not canAccess(resource_calendar, "addEvent"): raise Unauthorized("You don't have the right to" " book this resource!") event.bookResource(resource) self.request.response.redirect(self.nextURL(event))
def add(self, contact): """Add `contact` to the container and assign it to the person.""" contact_container = IContactContainer(ISchoolToolApplication(None)) name = INameChooser(contact_container).chooseName('', contact) contact_container[name] = contact self.added = contact return contact
def getResourceDemographics(resource): app = ISchoolToolApplication(None) rdc = app[RESOURCE_DEMO_DATA_KEY] demographics = rdc.get(resource.__name__, None) if demographics is None: rdc[resource.__name__] = demographics = ResourceDemographicsData() return demographics
def getPersonDemographics(person): app = ISchoolToolApplication(None) pdc = app['schooltool.basicperson.demographics_data'] demographics = pdc.get(person.username, None) if demographics is None: pdc[person.username] = demographics = PersonDemographicsData() return demographics
def createAndAdd(self, data, dry_run=True): """Create objects and add them to the container.""" if len(data) < 1: self.errors.fields.append(_('Insufficient data provided.')) return if not data[0]: self.errors.fields.append(_('User names must not be empty.')) return app = ISchoolToolApplication(None) person_container = app['persons'] username = data[0] if username not in person_container: self.errors.fields.append( _('"${username}" is not a valid username.', mapping={'username': username})) return user = person_container[username] if not dry_run: removeSecurityProxy(self.container.members).add( removeSecurityProxy(user))
def __iter__(self): gc = IGroupContainer(ISchoolToolApplication(None), None) if gc is None: return persons = gc['teachers'].members for person in sorted(persons, key=lambda p: p.__name__): yield PersonTerm(person)
def getSourceObj(source): if source is None: return None items = source.split('_') scid = items[0] ws_hash = items[-2] act_hash = items[-1] sid = '_'.join(items[1:-2]) app = ISchoolToolApplication(None) sectionContainer = app['schooltool.course.section'].get(scid, None) if sectionContainer is None: return None section = sectionContainer.get(sid, None) if section is None: return None for worksheet in interfaces.IActivities(section).values(): if ws_hash == unicode(hash(IKeyReference(worksheet))): break else: return None if act_hash == 'ave': return worksheet for key, activity in worksheet.items(): if act_hash == unicode(hash(IKeyReference(activity))): return activity return None
def setUpTimetables(): app = ISchoolToolApplication(None) TimetableStartUp(app)() syc = ISchoolYearContainer(app) sy = syc.getActiveSchoolYear() timetables = ITimetableContainer(sy) timetables[u'rotating'] = tt_rot = Timetable(sy.first, sy.last, title=u"Rotating") tt_rot.periods = CalendarDayTemplates() initTemplates(tt_rot.periods) tt_rot.time_slots = CalendarDayTemplates() initTemplates(tt_rot.time_slots) addTimetableDays(tt_rot, [('1', 'Day 1'), ('2', 'Day 2'), ('3', 'Day 3')], ['A', 'B', 'C']) timetables[u'weekly'] = tt_week = Timetable(sy.first, sy.last, title=u"Weekly") tt_week.periods = WeekDayTemplates() initTemplates(tt_week.periods) tt_week.time_slots = WeekDayTemplates() initTemplates(tt_week.time_slots) dows = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] week_days = [(unicode(n), title) for n, title in enumerate(dows)] addTimetableDays(tt_week, week_days, ['A', 'B', 'C'])
def format_persons(self): fields = [('User Name', Text, attrgetter('__name__')), ('Prefix', Text, attrgetter('prefix')), ('First Name', Text, attrgetter('first_name')), ('Middle Name', Text, attrgetter('middle_name')), ('Last Name', Text, attrgetter('last_name')), ('Suffix', Text, attrgetter('suffix')), ('Preferred Name', Text, attrgetter('preferred_name')), ('Birth Date', Date, attrgetter('birth_date')), ('Gender', Text, attrgetter('gender')), ('Password', Text, lambda p: None)] def demographics_getter(attribute): def getter(person): demographics = IDemographics(person) return demographics[attribute] return getter app = ISchoolToolApplication(None) demographics_fields = IDemographicsFields(app) for field in demographics_fields.values(): title = field.title format = Text if isinstance(field, DateFieldDescription): format = Date getter = demographics_getter(field.name) fields.append((title, format, getter)) items = self.context['persons'].values() return self.format_table(fields, items, importer='export_persons')
def setUpCourses(names): app = ISchoolToolApplication(None) CourseInit(app)() SectionInit(app)() courses = ICourseContainer(app) for name in names: courses[name.lower()] = Course(title=name)
def app_states(self): app = ISchoolToolApplication(None) container = IRelationshipStateContainer(app) states = container.get(self.view.app_states_name, None) if states is None: return {} return states
def getTermByToken(self, token): gc = IGroupContainer(ISchoolToolApplication(None)) if gc is None: raise LookupError(token) if token not in gc: raise LookupError(token) return GroupTerm(gc[token])
def done_link(self): schoolyear = ISchoolYear(self.context.__parent__) url = '%s/%s?schoolyear_id=%s' % ( absoluteURL(ISchoolToolApplication(None), self.request), 'courses', schoolyear.__name__) return url
def setUp(self): layeredTestSetup() app = ISchoolToolApplication(None) self.person = app['persons']['person'] = Person('person') # set up schoolyear from schooltool.schoolyear.schoolyear import SchoolYear from schooltool.schoolyear.interfaces import ISchoolYearContainer ISchoolYearContainer(app)['2004'] = SchoolYear("2004", date(2004, 9, 1), date(2004, 12, 31)) # set up the timetable schema days = ['A', 'B', 'C'] schema = self.createSchema(days, ['1', '2', '3', '4'], ['1', '2', '3', '4'], ['1', '2', '3', '4']) schema.timezone = 'Europe/London' template = SchooldayTemplate() template.add(SchooldaySlot(time(8, 0), timedelta(hours=1))) template.add(SchooldaySlot(time(10, 15), timedelta(hours=1))) template.add(SchooldaySlot(time(11, 30), timedelta(hours=1))) template.add(SchooldaySlot(time(12, 30), timedelta(hours=2))) schema.model = SequentialDaysTimetableModel(days, {None: template}) ITimetableSchemaContainer(app)['default'] = schema # set up terms from schooltool.term.term import Term terms = ITermContainer(app) terms['term'] = term = Term("Some term", date(2004, 9, 1), date(2004, 12, 31)) term.add(date(2004, 11, 5))
def types(self): app = ISchoolToolApplication(None) types = set() for resource in app['resources'].values(): if self.interface.providedBy(resource): types.add(resource.type) return list(types)
def getSectionContainer(term): int_ids = getUtility(IIntIds) term_id = str(int_ids.getId(term)) app = ISchoolToolApplication(None) sc = app[SECTION_CONTAINERS_KEY].get(term_id, None) if sc is None: sc = app[SECTION_CONTAINERS_KEY][term_id] = SectionContainer() return sc
def contains(self, principal): from schooltool.app.browser import same # XXX from schooltool.app.interfaces import ISchoolToolApplication from schooltool.person.interfaces import IPerson app = ISchoolToolApplication(None) persons = app['persons'] person = IPerson(principal, None) return person is not None and same(person, persons.super_user)
def handle_cancel_action(self, action): if 'camefrom' in self.request: url = self.request['camefrom'] self.request.response.redirect(url) return app = ISchoolToolApplication(None) url = self.url_with_schoolyear_id(app, view_name='groups') self.request.response.redirect(url)
def __call__(self): app = ISchoolToolApplication(None) syc = ISchoolYearContainer(app) activeSchoolyear = syc.getActiveSchoolYear() if activeSchoolyear is not None: self.importDefaultGroups(activeSchoolyear) else: self.initializeGroupContainer()
def getScheduleContainer(obj): int_ids = getUtility(IIntIds) obj_id = str(int_ids.getId(obj)) app = ISchoolToolApplication(None) container = app[SCHEDULES_KEY].get(obj_id, None) if container is None: container = app[SCHEDULES_KEY][obj_id] = ScheduleContainer() return container
def getTimetableContainer(obj): int_ids = getUtility(IIntIds) obj_id = str(int_ids.getId(obj)) app = ISchoolToolApplication(None) container = app[TIMETABLES_KEY].get(obj_id, None) if container is None: container = app[TIMETABLES_KEY][obj_id] = TimetableContainer() return container
def getApplicationCalendar(self): if self.user is None: return None app = ISchoolToolApplication(None) calendar = ISchoolToolCalendar(app) if not canAccess(calendar, '__iter__'): return None return calendar
def schoolyears(self): app = ISchoolToolApplication(None) schoolyears = ISchoolYearContainer(app) active_schoolyear = schoolyears.getActiveSchoolYear() return [ schoolyear for schoolyear in schoolyears.values() if schoolyear.first >= active_schoolyear.first ]
def getActivities(self): activities = [] root = IGradebookRoot(ISchoolToolApplication(None)) prefix = '%s_%s_' % (self.schoolyear.__name__, self.term.__name__) for key, sheet in root.deployed.items(): if key.startswith(prefix) and key[len(prefix):].isdigit(): activities.extend(sheet.values()) return activities
def getCourseContainer(sy): int_ids = getUtility(IIntIds) sy_id = str(int_ids.getId(sy)) app = ISchoolToolApplication(None) cc = app[COURSE_CONTAINER_KEY].get(sy_id, None) if cc is None: cc = app[COURSE_CONTAINER_KEY][sy_id] = CourseContainer() return cc
def renderPersonTable(self): persons = ISchoolToolApplication(None)['persons'] formatter = getMultiAdapter((persons, self.request), table.interfaces.ITableFormatter) formatter.setUp(table_formatter=zc.table.table.StandaloneFullFormatter, items=self.getPersons(), batch_size=0) return formatter.render()
def nextURL(self): if 'CONFIRM' in self.request: schoolyear = ISchoolYear(self.context) url = '%s/%s?schoolyear_id=%s' % (absoluteURL( ISchoolToolApplication(None), self.request), 'groups', schoolyear.__name__) return url return flourish.containers.ContainerDeleteView.nextURL(self)