class EventSchema(ma.Schema): slug = fields.Method("get_slugify") timestamp = fields.Method("get_timestamp") excerpts = fields.Nested('ExcerptSchema', allow_none=True, many=True, only=["id"]) items = fields.Nested('ItemSchema', allow_none=True, many=True, only=["id"]) actors = fields.Nested('PersonSchema', allow_none=True, many=True, only=["id"]) def get_slugify(self, obj): return (slugify(obj.name)) def get_timestamp(self, obj): return (obj.timestamp.strftime('%Y-%m-%dT%H:%M:%S')) class Meta: additional = ("id", "unique", "name", "phone", "description", "place_id")
class BaseTemplateSchema(BaseSchema): reply_to = fields.Method("get_reply_to", allow_none=True) reply_to_text = fields.Method("get_reply_to_text", allow_none=True) def get_reply_to(self, template): return template.reply_to def get_reply_to_text(self, template): return template.get_reply_to_text() class Meta: model = models.Template exclude = ("service_id", "jobs", "service_letter_contact_id") strict = True
class TemplateHistorySchema(BaseSchema): reply_to = fields.Method("get_reply_to", allow_none=True) reply_to_text = fields.Method("get_reply_to_text", allow_none=True) created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True) created_at = field_for(models.Template, 'created_at', format='%Y-%m-%d %H:%M:%S.%f') def get_reply_to(self, template): return template.reply_to def get_reply_to_text(self, template): return template.get_reply_to_text() class Meta: model = models.TemplateHistory
class JobSchema(BaseSchema): created_by_user = fields.Nested(UserSchema, attribute="created_by", dump_to="created_by", only=["id", "name"], dump_only=True) created_by = field_for(models.Job, 'created_by', required=True, load_only=True) job_status = field_for(models.JobStatus, 'name', required=False) scheduled_for = fields.DateTime() service_name = fields.Nested(ServiceSchema, attribute="service", dump_to="service_name", only=["name"], dump_only=True) template_name = fields.Method('get_template_name', dump_only=True) template_type = fields.Method('get_template_type', dump_only=True) contact_list_id = field_for(models.Job, 'contact_list_id') def get_template_name(self, job): return job.template.name def get_template_type(self, job): return job.template.template_type @validates('scheduled_for') def validate_scheduled_for(self, value): _validate_datetime_not_in_past(value) _validate_datetime_not_more_than_96_hours_in_future(value) class Meta(BaseSchema.Meta): model = models.Job exclude = ( 'notifications', 'notifications_delivered', 'notifications_failed', 'notifications_sent', ) strict = True
class UserSchema(ma.Schema): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'created_at', 'updated_at') id = fields.Method('hex') def hex(self, user): return user.id.hex()
class TemplateHistorySchema(BaseSchema): reply_to = fields.Method("get_reply_to", allow_none=True) reply_to_text = fields.Method("get_reply_to_text", allow_none=True) process_type = field_for(models.Template, 'process_type') created_by = fields.Nested(UserSchema, only=['id', 'name', 'email_address'], dump_only=True) created_at = field_for(models.Template, 'created_at', format=DATETIME_FORMAT_NO_TIMEZONE) def get_reply_to(self, template): return template.reply_to def get_reply_to_text(self, template): return template.get_reply_to_text() class Meta(BaseSchema.Meta): model = models.TemplateHistory
class UserSchema(BaseSchema): permissions = fields.Method("user_permissions", dump_only=True) password_changed_at = field_for(models.User, 'password_changed_at', format=DATETIME_FORMAT_NO_TIMEZONE) created_at = field_for(models.User, 'created_at', format=DATETIME_FORMAT_NO_TIMEZONE) auth_type = field_for(models.User, 'auth_type') def user_permissions(self, usr): retval = {} for x in permission_dao.get_permissions_by_user_id(usr.id): service_id = str(x.service_id) if service_id not in retval: retval[service_id] = [] retval[service_id].append(x.permission) return retval class Meta(BaseSchema.Meta): model = models.User exclude = ( "_password", "created_at", "email_access_validated_at", "updated_at", "user_to_organisation", "user_to_service", "verify_codes", ) strict = True @validates('name') def validate_name(self, value): if not value: raise ValidationError('Invalid name') @validates('email_address') def validate_email_address(self, value): try: validate_email_address(value) except InvalidEmailError as e: raise ValidationError(str(e)) @validates('mobile_number') def validate_mobile_number(self, value): try: if value is not None: validate_phone_number(value, international=True) except InvalidPhoneError as error: raise ValidationError('Invalid phone number: {}'.format(error))
class Location(MA.Schema): class Meta: fields = ('name', 'county', 'state', 'country', 'last_confirmed', 'last_deaths', 'chart_data') ordered = True name = fields.Str() county = fields.Str() state = fields.Str() country = fields.Str() chart_data = fields.Method('obj_chart_data') last_confirmed = fields.Method('obj_last_confirmed') last_deaths = fields.Method('obj_last_deaths') def obj_chart_data(self, obj): return formatters.format_chart_data([obj]) def obj_last_confirmed(self, obj): return formatters.last_confirmed([obj]) def obj_last_deaths(self, obj): return formatters.last_deaths([obj])
class TemplateSchema(BaseTemplateSchema): created_by = field_for(models.Template, 'created_by', required=True) process_type = field_for(models.Template, 'process_type') redact_personalisation = fields.Method("redact") def redact(self, template): return template.redact_personalisation @validates_schema def validate_type(self, data): if data.get('template_type') in [models.EMAIL_TYPE, models.LETTER_TYPE]: subject = data.get('subject') if not subject or subject.strip() == '': raise ValidationError('Invalid template subject', 'subject')
class GroupSchema(ma.Schema): slug = fields.Method("get_slugify") excerpts = fields.Nested('ExcerptSchema', allow_none=True, many=True, only=["id"]) members = fields.Nested('PersonSchema', allow_none=True, many=True, only=["id"]) def get_slugify(self, obj): return (slugify(obj.name)) class Meta: additional = ("id", "unique", "name")
class PersonSchema(ma.Schema): "Description" slug = fields.Method("get_slugify") excerpts = fields.Nested('ExcerptSchema', allow_none=True, many=True, only=["id"]) events = fields.Nested('EventSchema', allow_none=True, many=True, only=["id"]) places = fields.Nested('PlaceSchema', allow_none=True, many=True, only=["id"]) possessions = fields.Nested('ItemSchema', allow_none=True, many=True, only=["id"]) properties = fields.Nested('PlaceSchema', allow_none=True, many=True, only=["id"]) groups = fields.Nested('GroupSchema', allow_none=True, many=True, only=["id"]) acquaintances = fields.Nested('PersonSchema', allow_none=True, many=True, only=["id"]) # TODO: this is a nested query # "encounters": [i.id for e in self.events for i in e.items], def get_slugify(self, obj): return (slugify(obj.name)) class Meta: additional = ("id", "name", "alias", "unique")
class PlaceSchema(ma.Schema): "Description" slug = fields.Method("get_slugify") excerpts = fields.Nested('ExcerptSchema', allow_none=True, many=True, only=["id"]) events = fields.Nested('EventSchema', allow_none=True, many=True, only=["id"]) owners = fields.Nested('PersonSchema', allow_none=True, many=True, only=["id"]) def get_slugify(self, obj): return (slugify(obj.name)) class Meta: additional = ("id", "unique", "name", "description", "address", "lat", "lon")
class ServiceSchema(BaseSchema): created_by = field_for(models.Service, 'created_by', required=True) organisation_type = field_for(models.Service, 'organisation_type') letter_logo_filename = fields.Method(dump_only=True, serialize='get_letter_logo_filename') permissions = fields.Method("service_permissions") email_branding = field_for(models.Service, 'email_branding') organisation = field_for(models.Service, 'organisation') override_flag = False letter_contact_block = fields.Method(serialize="get_letter_contact") go_live_at = field_for(models.Service, 'go_live_at', format='%Y-%m-%d %H:%M:%S.%f') def get_letter_logo_filename(self, service): return service.letter_branding and service.letter_branding.filename def service_permissions(self, service): return [p.permission for p in service.permissions] def get_letter_contact(self, service): return service.get_default_letter_contact() class Meta: model = models.Service dump_only = ['letter_contact_block'] exclude = ( 'updated_at', 'created_at', 'api_keys', 'templates', 'jobs', 'old_id', 'template_statistics', 'service_provider_stats', 'service_notification_stats', 'service_sms_senders', 'reply_to_email_addresses', 'letter_contacts', 'complaints', ) strict = True @validates('permissions') def validate_permissions(self, value): permissions = [v.permission for v in value] for p in permissions: if p not in models.SERVICE_PERMISSION_TYPES: raise ValidationError( "Invalid Service Permission: '{}'".format(p)) if len(set(permissions)) != len(permissions): duplicates = list( set([x for x in permissions if permissions.count(x) > 1])) raise ValidationError( 'Duplicate Service Permission: {}'.format(duplicates)) @pre_load() def format_for_data_model(self, in_data): if isinstance(in_data, dict) and 'permissions' in in_data: str_permissions = in_data['permissions'] permissions = [] for p in str_permissions: permission = ServicePermission(service_id=in_data["id"], permission=p) permissions.append(permission) in_data['permissions'] = permissions
class ServiceSchema(BaseSchema, UUIDsAsStringsMixin): created_by = field_for(models.Service, 'created_by', required=True) organisation_type = field_for(models.Service, 'organisation_type') letter_logo_filename = fields.Method(dump_only=True, serialize='get_letter_logo_filename') permissions = fields.Method("service_permissions") email_branding = field_for(models.Service, 'email_branding') organisation = field_for(models.Service, 'organisation') override_flag = False go_live_at = field_for(models.Service, 'go_live_at', format=DATETIME_FORMAT_NO_TIMEZONE) allowed_broadcast_provider = fields.Method( dump_only=True, serialize='_get_allowed_broadcast_provider') broadcast_channel = fields.Method(dump_only=True, serialize='_get_broadcast_channel') def _get_allowed_broadcast_provider(self, service): return service.allowed_broadcast_provider def _get_broadcast_channel(self, service): return service.broadcast_channel def get_letter_logo_filename(self, service): return service.letter_branding and service.letter_branding.filename def service_permissions(self, service): return [p.permission for p in service.permissions] def get_letter_contact(self, service): return service.get_default_letter_contact() class Meta(BaseSchema.Meta): model = models.Service exclude = ( 'all_template_folders', 'annual_billing', 'api_keys', 'broadcast_messages', 'complaints', 'contact_list', 'created_at', 'crown', 'data_retention', 'guest_list', 'inbound_number', 'inbound_sms', 'jobs', 'letter_contacts', 'letter_logo_filename', 'old_id', 'reply_to_email_addresses', 'returned_letters', 'service_broadcast_provider_restriction', 'service_broadcast_settings', 'service_notification_stats', 'service_provider_stats', 'service_sms_senders', 'template_statistics', 'templates', 'updated_at', 'users', 'version', ) strict = True @validates('permissions') def validate_permissions(self, value): permissions = [v.permission for v in value] for p in permissions: if p not in models.SERVICE_PERMISSION_TYPES: raise ValidationError( "Invalid Service Permission: '{}'".format(p)) if len(set(permissions)) != len(permissions): duplicates = list( set([x for x in permissions if permissions.count(x) > 1])) raise ValidationError( 'Duplicate Service Permission: {}'.format(duplicates)) @pre_load() def format_for_data_model(self, in_data): if isinstance(in_data, dict) and 'permissions' in in_data: str_permissions = in_data['permissions'] permissions = [] for p in str_permissions: permission = ServicePermission(service_id=in_data["id"], permission=p) permissions.append(permission) in_data['permissions'] = permissions