Пример #1
0
    def test_portal02(self):
        "Not super-user."
        from creme import documents

        self.login(is_superuser=False, allowed_apps=['documents'])

        response = self.assertGET200(reverse('creme_config__hfilters'))
        self.assertCountEqual(
            self._ctype_labels_from_brick(response),
            [
                model._meta.verbose_name
                for model in (documents.get_document_model(), documents.get_folder_model())
            ],
        )
Пример #2
0
    def test_remove_image(self):
        user = self.login(
            is_superuser=False,
            allowed_apps=['documents', 'products'],
            creatable_models=[get_document_model()],
        )
        creds = SetCredentials.objects.create(
            role=self.role,
            value=EntityCredentials.VIEW | EntityCredentials.CHANGE
            | EntityCredentials.LINK,
            set_type=SetCredentials.ESET_ALL,
        )

        create_image = self._create_image
        img_1 = create_image(ident=1, user=user)
        img_2 = create_image(ident=2, user=user)

        sub_cat = SubCategory.objects.all()[0]
        product = Product.objects.create(
            user=user,
            name='Eva00',
            description='A fake god',
            unit_price=Decimal('1.23'),
            code=42,
            category=sub_cat.category,
            sub_category=sub_cat,
        )
        product.images.set([img_1, img_2])

        url = reverse('products__remove_image', args=(product.id, ))
        data = {'id': img_1.id}
        self.assertGET405(url, data=data)

        self.assertPOST200(url, data=data, follow=True)
        self.assertListEqual([img_2], [*product.images.all()])

        # Not a Product/Service ---
        rei = FakeContact.objects.create(user=user,
                                         first_name='Rei',
                                         last_name='Ayanami')
        self.assertPOST404(
            reverse('products__remove_image', args=(rei.id, )),
            data={'id': img_2.id},
        )

        # No CHANGE permission
        creds.value = EntityCredentials.VIEW | EntityCredentials.LINK
        creds.save()
        self.assertPOST403(url, data={'id': img_2.id})
Пример #3
0
    def test_ctype_for_swappable(self):
        from creme import documents

        Document = documents.get_document_model()

        with self.assertNoException():
            template = Template(
                r"{% load creme_ctype %}"
                r"{% ctype_for_swappable 'DOCUMENTS_DOCUMENT_MODEL' as doc_ctype %}"
                r"<h1>{{doc_ctype}} ({{doc_ctype.id}})</h1>")
            render = template.render(Context())

        self.assertEqual(
            '<h1>{vname} ({id})</h1>'.format(
                vname=Document._meta.verbose_name,
                id=ContentType.objects.get_for_model(Document).id,
            ), render.strip())
Пример #4
0
    def login_as_basic_user(self, creatable_model):
        user = self.login(is_superuser=False, allowed_apps=['products', 'documents'],
                          creatable_models=[creatable_model, get_document_model()],
                         )

        create_sc = partial(SetCredentials.objects.create, role=self.role)
        create_sc(value=EntityCredentials.VIEW   | EntityCredentials.CHANGE |
                        EntityCredentials.DELETE |
                        EntityCredentials.LINK   | EntityCredentials.UNLINK,
                  set_type=SetCredentials.ESET_OWN,
                 )
        create_sc(value=EntityCredentials.VIEW   | EntityCredentials.CHANGE |
                        EntityCredentials.DELETE |
                        # EntityCredentials.LINK   |
                        EntityCredentials.UNLINK,
                  set_type=SetCredentials.ESET_ALL,
                 )

        return user
Пример #5
0
class EmailTemplateAddAttachment(CremeForm):
    attachments = MultiCreatorEntityField(
        label=_('Attachments'),
        required=False,
        model=get_document_model(),
    )

    blocks = FieldBlockManager({
        'id': 'general',
        'label': _('Attachments'),
        'fields': '*',
    })

    def __init__(self, entity, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.template = entity

    def save(self):
        add = self.template.attachments.add

        for attachment in self.cleaned_data['attachments']:
            add(attachment)
Пример #6
0
from creme import emails, persons
from creme.creme_core.auth.entity_credentials import EntityCredentials
from creme.creme_core.forms import base as base_forms
from creme.creme_core.forms import fields as core_fields
from creme.creme_core.forms.widgets import CremeTextarea
from creme.creme_core.models import FieldsConfig, Relation
from creme.creme_core.utils.html import strip_html
from creme.documents import get_document_model

from ..constants import (  # MAIL_STATUS_SENDINGERROR
    REL_SUB_MAIL_RECEIVED, REL_SUB_MAIL_SENDED,
)
from ..creme_jobs import entity_emails_send_type

logger = logging.getLogger(__name__)
Document = get_document_model()
Contact = persons.get_contact_model()
Organisation = persons.get_organisation_model()
EntityEmail = emails.get_entityemail_model()
EmailTemplate = emails.get_emailtemplate_model()


class EntityEmailForm(base_forms.CremeEntityQuickForm):
    """Mails are related to the selected contacts/organisations & the 'current' entity.
    Mails are send to selected contacts/organisations.
    """
    sender = forms.EmailField(label=_('Sender'))

    c_recipients = core_fields.MultiCreatorEntityField(
        label=_('Contacts'),
        required=False,
Пример #7
0
try:
    from os.path import join
    from unittest import skipIf

    from django.conf import settings
    from django.urls import reverse

    from creme.creme_core.tests.base import CremeTestCase

    from creme import documents
    from creme.documents import constants

    skip_document_tests = documents.document_model_is_custom()
    skip_folder_tests = documents.folder_model_is_custom()

    Document = documents.get_document_model()
    Folder = documents.get_folder_model()
except Exception as e:
    print('Error in <{}>: {}'.format(__name__, e))

    skip_document_tests = skip_folder_tests = False


def skipIfCustomDocument(test_func):
    return skipIf(skip_document_tests,
                  'Custom document model in use')(test_func)


def skipIfCustomFolder(test_func):
    return skipIf(skip_folder_tests, 'Custom folder model in use')(test_func)
Пример #8
0
    def test_mass_import04(self):
        "Categories in CSV ; want to create Category but not it is allowed"
        user = self.login(
            is_superuser=False,
            allowed_apps=['products', 'documents'],
            creatable_models=[Product, get_document_model()],
        )
        count = Product.objects.count()

        SetCredentials.objects.create(
            role=self.role,
            value=EntityCredentials.VIEW | EntityCredentials.CHANGE
            | EntityCredentials.DELETE | EntityCredentials.LINK
            | EntityCredentials.UNLINK,
            set_type=SetCredentials.ESET_OWN,
        )

        cat1 = Category.objects.create(name='(Test) Video games')
        sub_cat11 = SubCategory.objects.create(name='Puzzle', category=cat1)

        cat2 = Category.objects.create(name='(Test) DVD')
        sub_cat21 = SubCategory.objects.create(name='Thriller', category=cat2)

        names = ['Product %2i' % i for i in range(1, 5)]
        lines = [
            (names[0], '', ''),
            (names[1], cat2.name, sub_cat21.name),
            (names[2], cat2.name, 'Action'),
            (names[3], 'Books', 'Sci-Fi'),
        ]

        doc = self._build_csv_doc(lines)
        url = self._build_import_url(Product)
        self.assertGET200(url)

        data = {
            'step': 1,
            'document': doc.id,
            # has_header
            'user': user.id,
            'name_colselect': 1,
            'description_colselect': 0,
            'description_defval': 'Imported from CSV',
            'unit_price_colselect': 0,
            'unit_price_defval': '12',
            'code_colselect': 0,
            'code_defval': 489,
            'categories_cat_colselect': 2,
            'categories_subcat_colselect': 3,
            'categories_subcat_defval': sub_cat11.pk,
            'unit_colselect': 0,
            'quantity_per_unit_colselect': 0,
            'weight_colselect': 0,
            'stock_colselect': 0,
            'web_site_colselect': 0,

            # 'property_types',
            # 'fixed_relations',
            # 'dyn_relations',
        }

        # Validation error -----------
        response = self.assertPOST200(url,
                                      follow=True,
                                      data={
                                          **data, 'categories_create': 'on'
                                      })
        self.assertFormError(response, 'form', 'categories',
                             'You cannot create Category or SubCategory')

        # OK --------------------------
        response = self.client.post(url, follow=True, data=data)
        self.assertNoFormError(response)

        self._execute_job(response)
        self.assertEqual(count + 2, Product.objects.count())
Пример #9
0
 def _get_document(self, POST):
     return get_document_model().objects.get(id=POST['document'])
Пример #10
0
    def test_mass_import05(self):
        "Creation credentials for Organisation & SalesPhase are forbidden."
        self.login(
            is_superuser=False,
            allowed_apps=['persons', 'documents', 'opportunities'],
            creatable_models=[Opportunity,
                              get_document_model()],  # Not Organisation
        )
        role = self.role
        SetCredentials.objects.create(
            role=role,
            value=EntityCredentials.VIEW | EntityCredentials.CHANGE
            | EntityCredentials.DELETE | EntityCredentials.LINK
            | EntityCredentials.UNLINK,
            set_type=SetCredentials.ESET_ALL,
        )
        # TODO: factorise
        emitter = Organisation.objects.filter(is_managed=True)[0]
        doc = self._build_csv_doc([('Opp01', '1000', '2000', 'Acme',
                                    'New phase')])
        url = self._build_import_url(Opportunity)
        data = {
            **self.lvimport_data,
            'document': doc.id,
            'user': self.user.id,
            'emitter': emitter.id,
            'name_colselect': 1,
            'estimated_sales_colselect': 2,
            'made_sales_colselect': 3,
            'sales_phase_colselect': 5,
            'sales_phase_subfield': 'name',
            'sales_phase_create': True,
            'target_persons_organisation_colselect': 4,
            # 'target_persons_organisation_create': True,
            'target_persons_contact_colselect': 0,
            'target_persons_contact_create': '',
        }

        response = self.assertPOST200(
            url,
            data={
                **data, 'target_persons_organisation_create': True
            },
        )
        self.assertFormError(
            response, 'form', 'target',
            _('You are not allowed to create: %(model)s') %
            {'model': _('Organisation')})
        self.assertFormError(response, 'form', 'sales_phase',
                             'You can not create instances')

        role.admin_4_apps = ['opportunities']
        role.save()
        response = self.client.post(url, follow=True, data=data)
        self.assertNoFormError(response)

        role.creatable_ctypes.add(
            ContentType.objects.get_for_model(Organisation))
        response = self.client.post(
            url,
            follow=True,
            data={
                **data, 'target_persons_organisation_create': True
            },
        )
        self.assertNoFormError(response)