def register(self): form = Form(RegistrationForm().bind(request=self.request), buttons=('Save', )) if self.request.method == 'POST': data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: self.request.session.flash( _(u"Please fix the highlighted errors below"), "error") else: try: new_user = User() new_user.update(values) self.request.session.flash( _(u"Success! {} user created".format( new_user.profile.username)), 'success') return HTTPFound( self.request.route_url('admin', traverse=(new_user.id, 'edit'))) except IntegrityError: transaction.abort() self.request.session.flash(_("Username already in use"), "error") return {'form': form, 'period': get_period_from_request(self.request)}
class UserForm(colander.MappingSchema): group = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Role"), widget=user_role_widget) clinics = colander.SchemaNode(colander.Set(), title=_(u"Clinic"), missing='', widget=clinic_selection_widget) municipality = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Municipality"), missing='', widget=municipality_selection_widget) state = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"State"), missing='', widget=state_selection_widget) password = colander.SchemaNode(colander.String(encoding='utf-8'), validator=colander.Length(min=5), widget=CheckedPasswordWidget(), missing='', title=_(u"Change Password")) def validator(self, node, value): exc = colander.Invalid(node, "") valid = True if value['group'] not in GROUPS: valid = False if not valid: raise exc
def delete(self): period = self.request.context if not period.reports: DBSession.delete(period) self.request.session.flash( _(u"Reporting period successfully deleted"), "success") else: self.request.session.flash( _(u"Cannot delete reporting period with data"), "error") return HTTPFound(self.request.route_url('periods', traverse=('list')))
def delete(self): location = self.request.context if not location.children(): DBSession.delete(location) self.request.session.flash( _("Location deleted successfully"), 'success') else: self.request.session.flash( _("Cannot delete location with Children"), 'error') return HTTPFound( self.request.route_url('locations', traverse=('')))
def delete(self): user = self.request.context if self.request.user == user: self.request.session.flash(_(u"You cannot delete yourself"), "error") return HTTPFound(self.request.route_url('admin', traverse=())) DBSession.delete(user) self.request.session.flash(_(u"User successfully deleted"), "success") return HTTPFound(self.request.route_url('admin', traverse=()))
def edit(self): location = self.request.context form = Form( LocationForm().bind( request=self.request, location=location), buttons=('Save', Button(name='cancel', type='button')), appstruct=location.appstruct) if self.request.method == 'POST': data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: pass else: location.update(**values) self.request.session.flash( _("Your changes have been saved"), 'success') return HTTPFound( self.request.route_url( 'locations', traverse=(location.id, 'edit'))) return { 'form': form, 'location': location, 'period': self.period }
def edit(self): user = self.request.context dashboard_user = user if user.ona_user is not None: dashboard_user = dashboard_user.ona_user form = Form(UserForm().bind(request=self.request, user=dashboard_user), buttons=('Save', Button(name='cancel', type='button')), appstruct=user.appstruct) if self.request.method == 'POST': data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: pass else: dashboard_user.update(values) self.request.session.flash(_("Your changes have been saved"), 'success') return HTTPFound( self.request.route_url('admin', traverse=(dashboard_user.id, 'edit'))) period = get_period_from_request(self.request) return {'form': form, 'user': dashboard_user, 'period': period}
def delete(self): clinic = self.request.context DBSession.delete(clinic) self.request.session.flash(_(u"Clinic successfully deleted"), "success") return HTTPFound( location=self.request.route_url('clinics', traverse=('manage')))
def set_locale(request): user = request.user user_settings = user.settings available_languages = constants.AVAILABLE_LANGUAGES period = get_period_from_request(request) if request.method == "POST": locale = request.POST.get("locale", "") request._LOCALE_ = locale if locale and locale in available_languages: user_settings.language = locale user_settings.save() referrer = request.cookies.get('referrer') headers = request.response.headers request.response.set_cookie('_LOCALE_', locale) request.session.flash(_("Language changed successfully"), "success") if referrer: return HTTPFound(location=referrer, headers=headers) if request.method == "GET": referrer = request.referrer request.response.set_cookie('referrer', referrer) return { "available_languages": available_languages, "period": period, "user_settings": user_settings }
class State(Location): __mapper_args__ = {'polymorphic_identity': Location.STATE} child_type = _('State') @property def __acl__(self): acl = [ (Allow, groups.SUPER_USER, ALL_PERMISSIONS), (Allow, groups.NATIONAL_OFFICIAL, perms.CAN_VIEW_STATE), ] if self.user is not None: children_perms = [(Allow, "u:{}".format(self.user.id), perms.CAN_VIEW_MUNICIPALITY), (Allow, "u:{}".format(self.user.id), perms.CAN_LIST_MUNICIPALITY)] acl.append( (Allow, "u:{}".format(self.user.id), perms.CAN_VIEW_STATE)) acl.extend(children_perms) return acl def children(self): return Municipality.all(Municipality.parent_id == self.id) @property def clinics(self): municipalities = self.children() clinics = [clinic for m in municipalities for clinic in m.clinics] return clinics def get_url(self, request, period): return request.route_url('states', traverse=(self.id), _query={'period': period.id})
class ClinicForm(colander.MappingSchema): name = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Clinic Name")) code = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"CNES Number")) municipality = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Municipality"), widget=municipality_widget) def validator(self, node, value): exc = colander.Invalid(node, "") valid = True if not value['name'] or not value['code']: valid = False if not valid: raise exc
def serialize(self, node, appstruct): if appstruct is colander.null: return colander.null if not isinstance(appstruct, datetime.date): raise colander.Invalid( node, _(u"{} is not a valid date".format(appstruct))) return appstruct.strftime(DATE_FORMAT)
class LocationForm(colander.MappingSchema): name = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Name")) location_type = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Location Type"), widget=location_type_widget) parent_id = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Parent Location"), widget=parent_widget, missing=None) def validator(self, node, value): exc = colander.Invalid(node, "") valid = True if not value['name']: valid = False if not valid: raise exc
def register_clinic(self): clinic = Clinic() period = get_period_from_request(self.request) form = Form(ClinicForm().bind(request=self.request, clinic=clinic), button=('Save', Button(name='cancel', type='button')), appstruct=clinic.appstruct) if self.request.method == 'POST': data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: pass else: try: municipality = Municipality.get( Municipality.id == values.get('municipality')) clinic.update(values.get('name'), values.get('code'), municipality) self.request.session.flash( _("{} saved.".format(clinic.name)), "success") return HTTPFound( self.request.route_url('clinics', traverse=(clinic.id, 'edit_clinic'))) except NoResultFound: self.request.session.flash( _("Cannot find selected municipality."), "error") except IntegrityError: DBSession.rollback() self.request.session.flash( _("A clinic already exists with the \ provided CNES."), "error") return {'form': form, 'clinic': clinic, 'period': period}
def add(self): location = Location() form = Form( LocationForm().bind( request=self.request), buttons=('Save', Button(name='cancel', type='button'))) if self.request.method == "POST": data = self.request.POST.items() try: values = form.validate(data) except ValidationFailure: self.request.session.flash( _(u"Please fix the errors indicated below."), "error") else: # add location if values['parent_id'] is None: values['parent_id'] = None location = Location(**values) location.save() self.request.session.flash( _("{} {} saved").format( location.name, location.location_type), 'success') # Create new location return HTTPFound( self.request.route_url( 'locations', traverse=(location.id, 'edit'))) # return form return { 'form': form, 'location': location, 'period': self.period }
def edit(self): period = self.request.context form = Form(ReportingPeriodForm().bind(request=self.request, period=period), buttons=('Save', ), css_class='form-horizontal', appstruct=period.appstruct) if self.request.method == "POST": post = self.request.POST.items() try: payload = form.validate(post) except ValidationFailure: self.request.session.flash( _(u"Please fix the errors indicated below."), 'error') else: if payload['form_xpath'] not in ALLOWED_XPATHS and \ valid_year(payload['form_xpath']) is None: self.request.session.flash( _(u"Form Xpath Only allows numeric values 1-5 and" " calendar years (YYYY)."), 'error') elif DBSession.query(ReportingPeriod).filter_by( form_xpath=payload['form_xpath']).first(): self.request.session.flash(_(u"Form Xpath Exists"), 'error') else: period.update(**payload) self.request.session.flash( _(u"Your changes have been saved"), 'success') return HTTPFound( self.request.route_url('periods', traverse=('list'))) # render form return {'form': form, 'period': period}
def create(self): form = Form(ReportingPeriodForm().bind(), buttons=('Save', ), css_class='form-horizontal') if self.request.method == "POST": post = self.request.POST.items() try: payload = form.validate(post) except ValidationFailure: pass else: if payload['form_xpath'] not in ALLOWED_XPATHS and \ valid_year(payload['form_xpath']) is None: self.request.session.flash( _(u"Only numeric values 1-5 and calendar " "years (YYYY) allowed For Form Xpath"), 'error') elif DBSession.query(ReportingPeriod).filter_by( form_xpath=payload['form_xpath']).first(): self.request.session.flash(_(u"Form Xpath Exists"), 'error') else: period = ReportingPeriod(title=payload['title'], form_xpath=payload['form_xpath'], start_date=payload['start_date'], end_date=payload['end_date']) DBSession.add(period) DBSession.flush() self.request.session.flash(_(u"Reporting period created"), 'success') return HTTPFound( self.request.route_url('periods', traverse=('list'))) # render form return {'form': form, 'period': ReportingPeriod.get_current_period()}
class ReportingPeriodForm(colander.MappingSchema): validator = StartEndDateValidator() title = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Name"), description=_( u"Give the reporting period a name", )) form_xpath = colander.SchemaNode( colander.String(encoding='utf-8'), title=_(u"Form Xpath"), description=_(u"The identifier located in the XLSForms", )) start_date = colander.SchemaNode(MonthYearDate(), title=_(u"Start Date"), widget=TextInputWidget(), missing_msg=_(u"Start date is required")) end_date = colander.SchemaNode(MonthYearDate(), title=_(u"End Date"), widget=TextInputWidget(), missing_msg=_(u"End date is required"))
class Municipality(Location): __mapper_args__ = {'polymorphic_identity': Location.MUNICIPALITY} child_type = _('Municipality') @property def __acl__(self): acl = [ (Allow, groups.SUPER_USER, ALL_PERMISSIONS), ] if self.user is not None: acl.append((Allow, "u:{}".format(self.user.id), perms.CAN_VIEW_MUNICIPALITY)) return acl def get_url(self, request, period): return request.route_url('municipalities', traverse=(self.id), _query={'period': period.id}) def children(self): return self.clinics
def __call__(self, node, value): if value['start_date'] >= value['end_date']: raise colander.Invalid( node['start_date'], _(u"Start date must be earlier than end date"))
class RegistrationForm(colander.MappingSchema): group = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Role"), widget=new_user_role_widget) clinics = colander.SchemaNode(colander.Set(), title=_(u"Clinic"), missing='', widget=clinic_selection_widget) municipality = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"Municipality"), missing='', widget=municipality_selection_widget) state = colander.SchemaNode(colander.String(encoding='utf-8'), title=_(u"State"), missing='', widget=state_selection_widget) username = colander.SchemaNode( colander.String(encoding='utf-8'), validator=colander.Length(max=25, max_err=_(u'Longer than maximum length 25')), widget=TextInputWidget(), title=_(u"Username"), description=_(u"Type the username of the clinic")) password = colander.SchemaNode( colander.String(encoding='utf-8'), validator=colander.Length(min=5, min_err=_(u'Shorter than minimum length 5')), widget=CheckedPasswordWidget(subject=_(u"Password"), confirm_subject=_(u"Confirm Password")), title=_(u"Password")) def validator(self, node, value): exc = colander.Invalid(node, "") valid = True if value['group'] not in GROUPS: valid = False if not valid: raise exc
COMMUNITY_MEMBER = 'community_member_V3' ADOLESCENT_IN_COMMUNITY = 'adolescent_in_community_V3' OBSERVATION_GUIDE = 'observation_guide_V3' ADOLESCENT_CLIENT_V2 = 'adolescent_client_V2' HEALTH_CARE_PROVIDER_V2 = 'health_care_provider_V2' SUPPORT_STAFF_V2 = 'support_staff_V2' HEALTH_FACILITY_MANAGER_V2 = 'health_facility_manager_V2' OUTREACH_WORKER_V2 = 'outreach_worker_V2' COMMUNITY_MEMBER_V2 = 'community_member_V2' ADOLESCENT_IN_COMMUNITY_V2 = 'adolescent_in_community_V2' OBSERVATION_GUIDE_V2 = 'observation_guide_V2' # Clinic registration CLINIC_REGISTRATION = 'clinic_registration' CLIENT_TOOLS = [(ADOLESCENT_CLIENT, _("Adolescent Client")), (HEALTH_CARE_PROVIDER, _("Health-care Provider")), (SUPPORT_STAFF, _("Support Staff")), (HEALTH_FACILITY_MANAGER, _("Health Facility Manager")), (OUTREACH_WORKER, _("Outreach Worker")), (COMMUNITY_MEMBER, _("Community Member")), (ADOLESCENT_IN_COMMUNITY, _("Adolescent in Community")), (OBSERVATION_GUIDE, _("Observation Guide"))] CLIENT_TOOLS_V2 = [(ADOLESCENT_CLIENT_V2, _("Adolescent Client")), (HEALTH_CARE_PROVIDER_V2, _("Health-care Provider")), (SUPPORT_STAFF_V2, _("Support Staff")), (HEALTH_FACILITY_MANAGER_V2, _("Health Facility Manager")), (OUTREACH_WORKER_V2, _("Outreach Worker")), (COMMUNITY_MEMBER_V2, _("Community Member")), (ADOLESCENT_IN_COMMUNITY_V2, _("Adolescent in Community")),