def setUpClass(cls): super(TestVisit, cls).setUpClass() EmailTemplateType.set_defaults() School.create_defaults() (cls.unittype, c) = OrganizationalUnitType.objects.get_or_create( name="Fakultet" ) (cls.unit, c) = OrganizationalUnit.objects.get_or_create( name="testunit", type=cls.unittype ) cls.admin.userprofile.organizationalunit = cls.unit cls.admin.userprofile.save() Locality.create_defaults() (cls.locality, c) = Locality.objects.get_or_create( name='TestPlace', description="Place for testing", address_line="SomeRoad 2", zip_city="1234 SomeCity", organizationalunit=cls.unit ) (cls.roomresponsible, c) = RoomResponsible.objects.get_or_create( name='TestResponsible', email='*****@*****.**', phone='12345678', organizationalunit=cls.unit )
def setUpClass(cls): super(TestEmail, cls).setUpClass() EmailTemplateType.set_defaults() UserRole.create_defaults() ResourceType.create_defaults() GrundskoleLevel.create_defaults() cls.unittype = OrganizationalUnitType.objects.create(name="Fakultet") cls.unit = OrganizationalUnit.objects.create(name="testunit", type=cls.unittype) cls.admin.userprofile.organizationalunit = cls.unit cls.admin.userprofile.save() """
def test_template_edit_ui(self): template = self.create_emailtemplate( key=EmailTemplateType.NOTIFY_GUEST__BOOKING_CREATED) self.login("/emailtemplate/%d/edit" % template.id, self.admin) form_data = { 'type': EmailTemplateType.get( EmailTemplateType.NOTIFY_GUEST__BOOKING_CREATED).id, 'organizationalunit': self.unit.id, 'subject': 'Test subject', 'body': 'Test body' } fields = {'subject': None, 'body': None} for (key, value) in fields.items(): if type(value) != list: value = [value] for v in value: data = {} data.update(form_data) if v is None: del data[key] else: data[key] = v response = self.client.post( "/emailtemplate/%d/edit" % template.id, data) self.assertEquals(200, response.status_code) query = pq(response.content) errors = query("[name=\"%s\"]" % key) \ .closest("div.form-group").find("ul.errorlist li") self.assertEquals(1, len(errors)) response = self.client.post("/emailtemplate/%d/edit" % template.id, form_data) self.assertEquals(302, response.status_code) self.assertEquals("/emailtemplate", response['Location']) for (key, value) in form_data.items(): self.assertEquals( 1, EmailTemplate.objects.filter(**{ key: value }).count()) template = EmailTemplate.objects.get(**form_data) self.assertEquals( EmailTemplateType.get( EmailTemplateType.NOTIFY_GUEST__BOOKING_CREATED), template.type) self.assertEquals(self.unit, template.organizationalunit) self.assertEquals('Test subject', template.subject) self.assertEquals('Test body', template.body)
def setup_defaults(overwrite_templates=False): EmailTemplateType.set_defaults() Region.create_defaults() Locality.create_defaults() Municipality.create_defaults() PostCode.create_defaults() School.create_defaults() GymnasieLevel.create_defaults() GrundskoleLevel.create_defaults() KUEmailMessage.migrate() Guide.create_defaults() ExercisePresentation.create_defaults() if overwrite_templates: import_all()
def get_context_data(self, **kwargs): context = {} context['inherited'] = { item.template_key: { 'template_key': item.template_key, 'enabled': item.enabled, 'days': item.days } for item in chain.from_iterable( product.productautosend_set.all() for product in self.object.real.products ) } context['template_keys'] = list(set( template.key for template in chain.from_iterable( EmailTemplate.get_templates(product.organizationalunit) for product in self.object.real.products ) )) if hasattr(self.object, 'product') and self.object.product is not None: context['organizationalunit'] = \ self.object.product.organizationalunit context['autosend_enable_days'] = EmailTemplateType.get_keys( enable_days=True ) context.update(kwargs) return super(ChangeVisitAutosendView, self).\ get_context_data(**context)
def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) initial.update({'active': self.get_active_value(kwargs)}) kwargs['initial'] = initial super(VisitAutosendForm, self).__init__(*args, **kwargs) template_key = None if 'instance' in kwargs: template_key = kwargs['instance'].template_key elif 'initial' in kwargs: template_key = kwargs['initial']['template_key'] if template_key is not None: template_type = EmailTemplateType.get(template_key) if not template_type.enable_days: self.fields['days'].widget = forms.HiddenInput() elif template_key == \ EmailTemplateType.NOTITY_ALL__BOOKING_REMINDER: self.fields['days'].help_text = _(u'Notifikation vil blive ' u'afsendt dette antal dage ' u'før besøget') elif template_key == EmailTemplateType.NOTIFY_HOST__HOSTROLE_IDLE: self.fields['days'].help_text = _(u'Notifikation vil blive ' u'afsendt dette antal dage ' u'efter første booking ' u'er foretaget')
def create_emailtemplate(self, key=1, type=None, subject="", body="", unit=None): if key is not None and type is None: type = EmailTemplateType.get(key) template = EmailTemplate(key=key, type=type, subject=subject, body=body, organizationalunit=unit) template.save() return template
def test_template_list_ui(self): self.login("/emailtemplate", self.admin) self.create_emailtemplate( key=EmailTemplateType.NOTIFY_GUEST__BOOKING_CREATED) response = self.client.get("/emailtemplate") self.assertTemplateUsed(response, "email/list.html") query = pq(response.content) items = query("table tbody tr") found = [ tuple([cell.text.strip() for cell in query(i).find("td")]) for i in items ] self.assertEquals(1, len(found)) self.assertEquals( EmailTemplateType.get( EmailTemplateType.NOTIFY_GUEST__BOOKING_CREATED).name, found[0][0]) self.assertEquals("Grundskabelon", found[0][1])
def get_context_data(self, **kwargs): context = {} context['comments'] = { user.id: [ { 'text': comment.text, 'time': formats.date_format( timezone.localtime(comment.time), "DATETIME_FORMAT" ) } for comment in self.object.get_comments(user).all() ] for user in self.get_form().base_fields['hosts'].queryset.all() } context['can_send_emails'] = self.object.autosend_enabled( EmailTemplateType.NOTIFY_HOST__ASSOCIATED ) context['email_template_name'] = EmailTemplateType.get_name( EmailTemplateType.NOTIFY_HOST__ASSOCIATED ) context.update(kwargs) return super(ChangeVisitHostsView, self).\ get_context_data(**context)
def test_email_recipients(self): # setup products with users in different roles # test that get_recipients returns the correct users EmailTemplateType.set_defaults() ResourceType.create_defaults() UserRole.create_defaults() teacher = self.create_default_teacher(unit=self.unit) host = self.create_default_host(unit=self.unit) coordinator = self.create_default_coordinator(unit=self.unit) roomguy = self.create_default_roomresponsible(unit=self.unit) teacher_pool = self.create_resourcepool( ResourceType.RESOURCE_TYPE_TEACHER, self.unit, 'test_teacher_pool', teacher.userprofile.get_resource()) host_pool = self.create_resourcepool( ResourceType.RESOURCE_TYPE_HOST, self.unit, 'test_host_pool', teacher.userprofile.get_resource()) products = [] for product_type, label in Product.resource_type_choices: for time_mode in [ Product.TIME_MODE_NONE, Product.TIME_MODE_SPECIFIC, Product.TIME_MODE_GUEST_SUGGESTED, Product.TIME_MODE_NO_BOOKING ]: product = self.create_product(self.unit, time_mode=time_mode, potential_teachers=[teacher], potential_hosts=[host], state=Product.CREATED, product_type=product_type) product.tilbudsansvarlig = coordinator product.roomresponsible.add(roomguy) product.save() products.append(product) for time_mode in [ Product.TIME_MODE_RESOURCE_CONTROLLED, Product.TIME_MODE_RESOURCE_CONTROLLED_AUTOASSIGN ]: product = self.create_product(self.unit, time_mode=time_mode, state=Product.CREATED, product_type=product_type) product.tilbudsansvarlig = coordinator product.roomresponsible.add(roomguy) self.create_resourcerequirement(product, teacher_pool, 1) self.create_resourcerequirement(product, host_pool, 1) product.save() # products.append(product) expected = { EmailTemplateType.NOTIFY_EDITORS__BOOKING_CREATED: [(KUEmailRecipient.TYPE_PRODUCT_RESPONSIBLE, coordinator)], EmailTemplateType.NOTIFY_HOST__REQ_TEACHER_VOLUNTEER: [(KUEmailRecipient.TYPE_TEACHER, teacher)], EmailTemplateType.NOTIFY_HOST__REQ_HOST_VOLUNTEER: [(KUEmailRecipient.TYPE_HOST, host)], EmailTemplateType.NOTIFY_HOST__REQ_ROOM: [(KUEmailRecipient.TYPE_ROOM_RESPONSIBLE, roomguy)], EmailTemplateType.NOTIFY_ALL__BOOKING_COMPLETE: [ (KUEmailRecipient.TYPE_PRODUCT_RESPONSIBLE, coordinator), (KUEmailRecipient.TYPE_ROOM_RESPONSIBLE, roomguy) ], EmailTemplateType.NOTIFY_ALL__BOOKING_CANCELED: [ (KUEmailRecipient.TYPE_PRODUCT_RESPONSIBLE, coordinator), (KUEmailRecipient.TYPE_ROOM_RESPONSIBLE, roomguy) ], EmailTemplateType.NOTITY_ALL__BOOKING_REMINDER: [ (KUEmailRecipient.TYPE_PRODUCT_RESPONSIBLE, coordinator), (KUEmailRecipient.TYPE_ROOM_RESPONSIBLE, roomguy) ], EmailTemplateType.NOTIFY_HOST__HOSTROLE_IDLE: [ (KUEmailRecipient.TYPE_EDITOR, coordinator) ], EmailTemplateType.NOTIFY_EDITORS__SPOT_REJECTED: [ (KUEmailRecipient.TYPE_PRODUCT_RESPONSIBLE, coordinator), ], } expected.update({ template_type.key: [] for template_type in EmailTemplateType.objects.all() if template_type.key not in expected.keys() }) def unpack(item): if isinstance(item, User): return (item.get_full_name(), item.email) if isinstance(item, RoomResponsible): return (item.name, item.email) for product in products: for template_type_key, expected_recipients in expected.items(): actual_recipients = product.get_recipients( EmailTemplateType.get(template_type_key)) self.assertEquals( len(expected_recipients), len(actual_recipients), "Expected number of recipients not " "matching for template type %d" % template_type_key) expected_recipients = [(t, unpack(r)) for (t, r) in expected_recipients] for r in actual_recipients: self.assertTrue( (r.type, (r.name, r.email)) in expected_recipients, "did not expect (%d, (%s, %s)) " "for template type %d, expected %s" % (r.type, r.name, r.email, template_type_key, str(expected_recipients)))
def test_evaluation(self): EmailTemplateType.set_defaults() template1 = self.create_emailtemplate( key=EmailTemplateType.NOTIFY_GUEST__EVALUATION_FIRST, unit=self.unit, subject="Test evaluation", body="This is a test. " "Link: {{ recipient.guest.evaluationguest_teacher.link }}") product = self.create_product(unit=self.unit, time_mode=Product.TIME_MODE_SPECIFIC) evaluation = self.create_evaluation(product, surveyId=12345) visit = self.create_visit(product, start=datetime.now() + timedelta(days=3), end=datetime.now() + timedelta(days=3, hours=1)) self.create_autosend(visit, template1.type) booking = self.create_booking(visit, self.create_guest()) evaluation.save() self.set_visit_workflow_status(visit, Visit.WORKFLOW_STATUS_PLANNED) # Let visit "expire", so status changes to "executed" # and messages are sent out count_before = KUEmailMessage.objects.count() visit.on_expire() self.assertEquals(1, KUEmailMessage.objects.count() - count_before) message = KUEmailMessage.objects.last() self.assertIsNotNone(message) self.assertEquals("Test evaluation", message.subject.strip()) self.assertTrue(message.body.strip().startswith("This is a test")) self.assertEquals( "\"%s\" <%s>" % (booking.booker.get_full_name(), booking.booker.email), message.recipients) m = re.search("Link: http://%s/e/(.*)" % settings.PUBLIC_URL_HOSTNAME, message.body.strip()) self.assertIsNotNone(m) shortlink_id = m.group(1) evalguest = SurveyXactEvaluationGuest.objects.get( shortlink_id=shortlink_id, ) self.assertEquals(evaluation, evalguest.evaluation) self.assertDictEqual( { u'opl\xe6g': 0, u'l\xe6rere': 0, u'undvm1': '', u'type1': 0, u'ID': product.id, u'skole_id': None, u'antal': None, u'rundvis': 0, u'akt1': u'testproduct', u'niveau': None, u'oenhed1': None, u'region': None, u'elever': 0, u'g\xe6st': u'Tester Testerson', u'enhed1': self.unit.id, u'postnr': None, u'undvn1': '', u'skole': None, u'tid': visit.start_datetime.strftime('%Y.%m.%d %H:%M:%S'), u'email': u'*****@*****.**' }, evalguest.get_surveyxact_data())
def setUpClass(cls): super(TestProduct, cls).setUpClass() EmailTemplateType.set_defaults() School.create_defaults() (cls.unittype, c) = OrganizationalUnitType.objects.get_or_create(name="Fakultet") (cls.unit, c) = OrganizationalUnit.objects.get_or_create(name="testunit", type=cls.unittype) cls.admin.userprofile.organizationalunit = cls.unit cls.admin.userprofile.save() Locality.create_defaults() (cls.locality, c) = Locality.objects.get_or_create(name='TestPlace', description="Place for testing", address_line="SomeRoad 2", zip_city="1234 SomeCity", organizationalunit=cls.unit) (cls.roomresponsible, c) = RoomResponsible.objects.get_or_create( name='TestResponsible', email='*****@*****.**', phone='12345678', organizationalunit=cls.unit) cls.field_definitions = { 'title': { 'success': ["This is a title", u"Blåbærgrød", 'x' * 80], 'fail': [None, '', 'x' * 81] }, 'teaser': { 'success': ["This is a teaser", u"Æblegrød", 'x' * 300], 'fail': [None, '', 'x' * 301] }, 'description': { 'success': ["This is a description", u"Rødgrød med fløde"], 'fail': ['', None] }, 'price': { 'success': [ 0, 1, 500, 10000, Decimal('12.34'), Decimal('1' * 8 + '.00'), (None, Decimal(0)) ], 'fail': [-1, -500, 'a', '1' * 11, Decimal('12.345')] }, 'state': { 'success': [Product.CREATED, Product.ACTIVE, Product.DISCONTINUED], 'fail': [None, 10, 'x'] }, 'institution_level': { 'success': [ Subject.SUBJECT_TYPE_GYMNASIE, Subject.SUBJECT_TYPE_GRUNDSKOLE, Subject.SUBJECT_TYPE_BOTH ], 'fail': [None, 10, 'x'] }, 'minimum_number_of_visitors': { 'success': [0, 1, 1000, None], 'fail': [-1, 'a'] }, 'maximum_number_of_visitors': { 'success': [1000, 0, 1, None], 'fail': [-1, 'a'] }, 'do_create_waiting_list': { 'success': [('on', True), ('', False)] }, 'waiting_list_length': { 'success': [0, 1, 1000, None], 'fail': [-1, 'a'] }, 'waiting_list_deadline_days': { 'success': [0, 1, 1000, None], 'fail': [-1, 'a'] }, 'waiting_list_deadline_hours': { 'success': [0, 1, 23, None], 'fail': [-1, 'a', '24', '36'] }, 'time_mode': { 'fail': [None, 10, 'x'] }, 'duration': { 'success': ['05:00', '00:15', '00:00', None], 'fail': ['00:01', 'x', 'some random text'] }, 'locality': { 'success': [(cls.locality.id, cls.locality)], 'fail': [5000] }, 'tour_available': { 'success': [('on', True), ('', False)] }, 'catering_available': { 'success': [('on', True), ('', False)] }, 'presentation_available': { 'success': [('on', True), ('', False)] }, 'custom_available': { 'success': [('on', True), ('', False)] }, 'custom_name': { 'success': ['some text', u'Jordbærgrød', None, ('', None), 'x' * 50], 'fail': ['x' * 51] }, 'tilbudsansvarlig': { 'success': [(cls.admin.id, cls.admin), None], 'fail': [5000] }, 'roomresponsible': { 'success': [(cls.roomresponsible.id, [cls.roomresponsible])], 'fail': [5000, 'a', -1] }, 'organizationalunit': { 'success': (cls.unit.id, cls.unit), 'fail': [None, '', 'x'] }, 'preparation_time': { 'success': ['some text', u'Hindbærgrød', None, ('', None), 'x' * 200], 'fail': 'x' * 201 }, 'comment': { 'success': ['some text', u'Jordbærgrød', (None, ''), ''] }, 'only_one_guest_per_visit': { 'success': [('on', True), ('', False)] }, 'booking_close_days_before': { 'success': [0, 7, 10, 30], 'fail': [None, -3, 'x'] }, 'booking_max_days_in_future': { 'success': [30, 10, 3, 0], 'fail': [None, -3, 'x'] }, 'inquire_enabled': { 'success': [('on', True), ('', False)] }, }
def label(self): return EmailTemplateType.get_name(self.template_key)