示例#1
0
class Contact(TendenciBaseModel):
    """
    Contact records are created when someone fills out a form.
    The form creates the contact with a message.
    Later the contact can be updated to include comments for
    further communication.
    """
    guid = models.CharField(max_length=40)
    timezone = TimeZoneField(verbose_name=_('Time Zone'),
                             default='US/Central',
                             choices=get_timezone_choices(),
                             max_length=100)
    user = models.ForeignKey(User,
                             null=True,
                             related_name='contact_user',
                             on_delete=models.CASCADE)

    first_name = models.CharField(max_length=100, blank=True)
    middle_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    suffix = models.CharField(max_length=5, blank=True)

    addresses = models.ManyToManyField(Address, blank=True)
    phones = models.ManyToManyField(Phone, blank=True)
    emails = models.ManyToManyField(Email, blank=True)
    urls = models.ManyToManyField(URL, blank=True)
    companies = models.ManyToManyField(Company, blank=True)

    message = models.TextField()

    perms = GenericRelation(ObjectPermission,
                            object_id_field="object_id",
                            content_type_field="content_type")

    # TODO: consider attachments

    objects = ContactManager()

    class Meta:
        #         permissions = (("view_contact", _("Can view contact")),)
        app_label = 'contacts'

    def get_absolute_url(self):
        return reverse('contact', args=[self.pk])

    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid4())

        super(Contact, self).save(*args, **kwargs)

    def __str__(self):
        if self.first_name:
            return '%s %s' % (self.first_name, self.last_name)
        else:
            return '%s' % self.user
class Migration(migrations.Migration):

    dependencies = [
        ('news', '0006_auto_20180315_0857'),
    ]

    operations = [
        migrations.AlterField(
            model_name='news',
            name='timezone',
            field=timezone_field.fields.TimeZoneField(choices=get_timezone_choices(), verbose_name='Time Zone', default='US/Central', max_length=100),
        ),
    ]
示例#3
0
class Migration(migrations.Migration):

    dependencies = [
        ('contacts', '0002_auto_20150804_1545'),
    ]

    operations = [
        migrations.AlterField(
            model_name='contact',
            name='timezone',
            field=timezone_field.fields.TimeZoneField(
                choices=get_timezone_choices(),
                verbose_name='Time Zone',
                default='US/Central',
                max_length=100),
        ),
    ]
示例#4
0
class Article(TendenciBaseModel):
    CONTRIBUTOR_AUTHOR = 1
    CONTRIBUTOR_PUBLISHER = 2
    CONTRIBUTOR_CHOICES = ((CONTRIBUTOR_AUTHOR, _('Author')),
                           (CONTRIBUTOR_PUBLISHER, _('Publisher')))

    guid = models.CharField(max_length=40)
    slug = SlugField(_('URL Path'), unique=True)
    timezone = TimeZoneField(verbose_name=_('Time Zone'), default='US/Central', choices=get_timezone_choices(), max_length=100)
    headline = models.CharField(max_length=200, blank=True)
    summary = models.TextField(blank=True)
    body = tinymce_models.HTMLField()
    source = models.CharField(max_length=300, blank=True)
    first_name = models.CharField(_('First Name'), max_length=100, blank=True)
    last_name = models.CharField(_('Last Name'), max_length=100, blank=True)
    contributor_type = models.IntegerField(choices=CONTRIBUTOR_CHOICES,
                                           default=CONTRIBUTOR_AUTHOR)
    phone = models.CharField(max_length=50, blank=True)
    fax = models.CharField(max_length=50, blank=True)
    email = models.CharField(max_length=120, blank=True)
    website = models.CharField(max_length=300, blank=True)
    thumbnail = models.ForeignKey(File, null=True,
                                  on_delete=models.SET_NULL,
                                  help_text=_('The thumbnail image can be used on your homepage ' +
                                 'or sidebar if it is setup in your theme. The thumbnail image ' +
                                 'will not display on the news page.'))
    release_dt = models.DateTimeField(_('Release Date/Time'), null=True, blank=True)
    # used for better performance when retrieving a list of released articles
    release_dt_local = models.DateTimeField(null=True, blank=True)
    syndicate = models.BooleanField(_('Include in RSS feed'), default=True)
    featured = models.BooleanField(default=False)
    design_notes = models.TextField(_('Design Notes'), blank=True)
    group = models.ForeignKey(Group, null=True, default=get_default_group, on_delete=models.SET_NULL)
    tags = TagField(blank=True)

    # for podcast feeds
    enclosure_url = models.CharField(_('Enclosure URL'), max_length=500, blank=True)
    enclosure_type = models.CharField(_('Enclosure Type'), max_length=120, blank=True)
    enclosure_length = models.IntegerField(_('Enclosure Length'), default=0)

    not_official_content = models.BooleanField(_('Official Content'), blank=True, default=True)

    # html-meta tags
    meta = models.OneToOneField(MetaTags, null=True, on_delete=models.SET_NULL)

    categories = GenericRelation(CategoryItem,
                                          object_id_field="object_id",
                                          content_type_field="content_type")
    perms = GenericRelation(ObjectPermission,
                                          object_id_field="object_id",
                                          content_type_field="content_type")

    objects = ArticleManager()

    class Meta:
#         permissions = (("view_article", _("Can view article")),)
        verbose_name = _("Article")
        verbose_name_plural = _("Articles")
        app_label = 'articles'

    def get_meta(self, name):
        """
        This method is standard across all models that are
        related to the Meta model.  Used to generate dynamic
        methods coupled to this instance.
        """
        return ArticleMeta().get_meta(self, name)

    def get_absolute_url(self):
        return reverse('article', args=[self.slug])

    def get_version_url(self, hash):
        return reverse('article.version', args=[hash])

    def __str__(self):
        return self.headline

    def get_thumbnail_url(self):
        if not self.thumbnail:
            return u''

        return reverse('file', args=[self.thumbnail.pk])

    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid4())
        self.assign_release_dt_local()
        super(Article, self).save(*args, **kwargs)

    def assign_release_dt_local(self):
        """
        convert release_dt to the corresponding local time

        example:

        if
            release_dt: 2014-05-09 03:30:00
            timezone: US/Pacific
            settings.TIME_ZONE: US/Central
        then
            the corresponding release_dt_local will be: 2014-05-09 05:30:00
        """
        now = datetime.now()
        now_with_tz = adjust_datetime_to_timezone(now, settings.TIME_ZONE)
        if self.timezone and self.release_dt and self.timezone.zone != settings.TIME_ZONE:
            time_diff = adjust_datetime_to_timezone(now, self.timezone) - now_with_tz
            self.release_dt_local = self.release_dt + time_diff
        else:
            self.release_dt_local = self.release_dt

    def age(self):
        return datetime.now() - self.create_dt

    @property
    def category_set(self):
        items = {}
        for cat in self.categories.select_related('category', 'parent'):
            if cat.category:
                items["category"] = cat.category
            elif cat.parent:
                items["sub_category"] = cat.parent
        return items

    @property
    def has_google_author(self):
        return self.contributor_type == self.CONTRIBUTOR_AUTHOR

    @property
    def has_google_publisher(self):
        return self.contributor_type == self.CONTRIBUTOR_PUBLISHER
示例#5
0
文件: forms.py 项目: zaid100/tendenci
def build_settings_form(user, settings):
    """
        Create a set of fields and builds a form class
        returns SettingForm class
    """
    fields = OrderedDict()
    for setting in settings:
        setting_label = mark_safe('{0} <a href="#id_{1}" title="Permalink to this setting"><i class="fa fa-link" aria-hidden="true"></i></a>'.format(
                                    setting.label, setting.name))

        # Do not display standard regform settings
        if setting.scope_category == 'events' and setting.name.startswith('regform_'):
            continue

        try:
            setting_value = force_text(setting.get_value())
        except DjangoUnicodeDecodeError:
            setting_value = ''

        if setting.input_type in ['text', 'textarea']:
            options = {
                'label': setting_label,
                'help_text': setting.description,
                'initial': setting_value,
                'required': False,
                'label_suffix': "",
            }
            if setting.input_type == 'textarea':
                options['widget'] = forms.Textarea(attrs={'rows': 5, 'cols': 30})

            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.CharField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.CharField(**options)})

        elif setting.input_type in ['select', 'selectmultiple']:
            if setting.input_value == '<form_list>':
                choices = get_form_list(user)
                required = False
            elif setting.input_value == '<box_list>':
                choices = get_box_list(user)
                required = False
            elif setting.input_value == '<group_list>':
                choices, initial = get_group_list(user)
                required = True
                if not setting_value:
                    setting_value = initial
            elif setting.input_value == '<timezone_list>':
                choices = get_timezone_choices()
                required = True
                if not setting_value:
                    setting_value = django_settings.TIME_ZONE
            elif setting.input_value == '<language_list>':
                choices = get_languages_with_local_name()
                required = True
            elif setting.input_value == '<country_list>':
                choices = (('', '-----------'),) + tuple(COUNTRIES)
                required = False
                if setting.get_value() and  setting.name == 'countrylistinitialchoices':
                    setting_value = literal_eval(setting.get_value())
            else:
                # Allow literal_eval in settings in order to pass a list from the setting
                # This is useful if you want different values and labels for the select options
                try:
                    choices = tuple([(k, v)for k, v in literal_eval(setting.input_value)])
                    required = False

                    # By adding #<box_list> on to the end of a setting, this will append the boxes
                    # as select items in the list as well.
                    if '<box_list>' in setting.input_value:
                        box_choices = get_box_list(user)[1:]
                        choices = (('Content', choices), ('Boxes', box_choices))
                except:
                    choices = tuple([(s.strip(), s.strip())for s in setting.input_value.split(',')])
                    required = True

            options = {
                'label': setting_label,
                'help_text': setting.description,
                'initial': setting_value,
                'choices': choices,
                'required': required,
                'label_suffix': "",
            }
            if setting.client_editable or user.is_superuser:
                if setting.input_type == 'selectmultiple':
                    fields.update({"%s" % setting.name: forms.MultipleChoiceField(**options)})
                else:
                    fields.update({"%s" % setting.name: forms.ChoiceField(**options)})

        elif setting.input_type == 'file':
            from tendenci.apps.files.models import File as TendenciFile
            file_display = ''
            try:
                try:
                    val = int(setting_value)
                except ValueError:
                    val = 0

                try:
                    tfile = TendenciFile.objects.get(pk=val)
                except Exception:
                    tfile = None

                if tfile:
                    if tfile.file.name.lower().endswith(('.jpg', '.jpe', '.png', '.gif', '.svg')):
                        tfile_alt = tfile.file.name.lower()[:-4]
                        file_display = '<img src="/files/%s/" alt="%s" title="%s">' % (tfile.pk, tfile_alt, tfile_alt)
                    else:
                        file_display = tfile.file.name
            except TendenciFile.DoesNotExist:
                file_display = "No file"
            options = {
                'label': setting_label,
                'help_text': "%s<br> Current File: %s" % (setting.description, file_display),
                #'initial': tfile and tfile.file, # Removed this so the file doesn't save over and over
                'required': False,
                'label_suffix': "",
            }
            if setting.client_editable:
                fields.update({"%s" % setting.name: forms.FileField(**options)})
            else:
                if user.is_superuser:
                    fields.update({"%s" % setting.name: forms.FileField(**options)})

    attributes = {
        'settings': settings,
        'base_fields': fields,
        'clean': clean_settings_form,
        'save': save_settings_form,
        'user': user,
    }
    return type('SettingForm', (forms.BaseForm,), attributes)
示例#6
0
class Directory(TendenciBaseModel):

    guid = models.CharField(max_length=40)
    slug = SlugField(_('URL Path'), unique=True)
    entity = models.OneToOneField(Entity, blank=True, null=True,
                                  on_delete=models.SET_NULL,)
    timezone = TimeZoneField(verbose_name=_('Time Zone'), default='US/Central', choices=get_timezone_choices(), max_length=100)
    headline = models.CharField(_('Name'), max_length=200, blank=True)
    summary = models.TextField(blank=True)
    body = tinymce_models.HTMLField(_('Description'))
    source = models.CharField(max_length=300, blank=True)
    # logo = models.FileField(max_length=260, upload_to=file_directory,
    #                         help_text=_('Company logo. Only jpg, gif, or png images.'),
    #                         blank=True)

    logo_file = models.ForeignKey(File, null=True, on_delete=models.CASCADE)

    first_name = models.CharField(_('First Name'), max_length=100, blank=True)
    last_name = models.CharField(_('Last Name'), max_length=100, blank=True)
    address = models.CharField(_('Address'), max_length=100, blank=True)
    address2 = models.CharField(_('Address 2'), max_length=100, blank=True)
    city = models.CharField(_('City'), max_length=50, blank=True)
    state = models.CharField(_('State'), max_length=50, blank=True)
    zip_code = models.CharField(_('Zip Code'), max_length=50, blank=True)
    country = models.CharField(_('Country'), max_length=50, blank=True)
    region = models.ForeignKey(Region, blank=True, null=True, on_delete=models.SET_NULL)
    phone = models.CharField(max_length=50, blank=True)
    phone2 = models.CharField(_('Phone 2'), max_length=50, blank=True)
    fax = models.CharField(_('Fax'), max_length=50, blank=True)
    email = models.CharField(_('Email'), max_length=120, blank=True)
    email2 = models.CharField(_('Email 2'), max_length=120, blank=True)
    website = models.CharField(max_length=300, blank=True)

    renewal_notice_sent = models.BooleanField(default=False)
    list_type = models.CharField(_('List Type'), max_length=50, blank=True)
    requested_duration = models.IntegerField(_('Requested Duration'), default=0)
    pricing = models.ForeignKey('DirectoryPricing', null=True, on_delete=models.CASCADE)
    activation_dt = models.DateTimeField(_('Activation Date/Time'), null=True, blank=True)
    expiration_dt = models.DateTimeField(_('Expiration Date/Time'), null=True, blank=True)
    invoice = models.ForeignKey(Invoice, blank=True, null=True, on_delete=models.CASCADE)
    payment_method = models.CharField(_('Payment Method'), max_length=50, blank=True)
    
    # social media links
    linkedin = models.URLField(_('LinkedIn'), blank=True, default='')
    facebook = models.URLField(_('Facebook'), blank=True, default='')
    twitter = models.URLField(_('Twitter'), blank=True, default='')
    instagram = models.URLField(_('Instagram'), blank=True, default='')
    youtube = models.URLField(_('YouTube'), blank=True, default='')

    syndicate = models.BooleanField(_('Include in RSS feed'), default=True)
    design_notes = models.TextField(_('Design Notes'), blank=True)
    admin_notes = models.TextField(_('Admin Notes'), blank=True)
    tags = TagField(blank=True)

    # for podcast feeds
    enclosure_url = models.CharField(_('Enclosure URL'), max_length=500, blank=True)
    enclosure_type = models.CharField(_('Enclosure Type'), max_length=120, blank=True)
    enclosure_length = models.IntegerField(_('Enclosure Length'), default=0)

    # html-meta tags
    meta = models.OneToOneField(MetaTags, null=True, on_delete=models.SET_NULL)

    cat = models.ForeignKey(Category, verbose_name=_("Category"),
                                 related_name="directory_cat", null=True, on_delete=models.SET_NULL)
    sub_cat = models.ForeignKey(Category, verbose_name=_("Sub Category"),
                                 related_name="directory_subcat", null=True, on_delete=models.SET_NULL)
    cats = models.ManyToManyField(Category, verbose_name=_("Categories"),
                                  related_name="directory_cats",)
    sub_cats = models.ManyToManyField(Category, verbose_name=_("Sub Categories"),
                                  related_name="directory_subcats",)
    # legacy categories needed for data migration
    categories = GenericRelation(CategoryItem,
                                          object_id_field="object_id",
                                          content_type_field="content_type")
    perms = GenericRelation(ObjectPermission,
                                          object_id_field="object_id",
                                          content_type_field="content_type")
    
    affiliates = models.ManyToManyField("Directory", through='Affiliateship')

    objects = DirectoryManager()

    class Meta:
#         permissions = (("view_directory",_("Can view directory")),)
        verbose_name = _("Directory")
        verbose_name_plural = _("Directories")
        app_label = 'directories'

    def get_meta(self, name):
        """
        This method is standard across all models that are
        related to the Meta model.  Used to generate dynamic
        methods coupled to this instance.
        """
        return DirectoryMeta().get_meta(self, name)

    def __str__(self):
        return self.headline

    def get_absolute_url(self):
        return reverse('directory', args=[self.slug])

    def get_renew_url(self):
        return reverse('directory.renew', args=[self.id])

    def set_slug(self):
        if not self.slug:
            slug = slugify(self.headline)
            count = str(Directory.objects.count())
            if len(slug) + len(count) >= 99:
                self.slug = '%s-%s' % (slug[:99-len(count)], count)
            else:
                self.slug = '%s-%s' % (slug, count)

    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid4())

        super(Directory, self).save(*args, **kwargs)
        if self.logo:
            if self.is_public():
                set_s3_file_permission(self.logo.name, public=True)
            else:
                set_s3_file_permission(self.logo.name, public=False)

    def is_public(self):
        return all([self.allow_anonymous_view,
                self.status,
                self.status_detail in ['active']])

    def has_social_media(self):
        return any([self.linkedin, self.facebook, self.twitter, self.instagram, self.youtube])

    @property
    def logo(self):
        """
        This represents the logo FileField

        Originally this was a FileField, but later
        we added the attribute logo_file to leverage
        the File model.  We then replaced the logo
        property with this convience method for
        backwards compatibility.
        """
        if self.logo_file:
            return self.logo_file.file

    def get_logo_url(self):
        if not self.logo_file:
            return u''

        return reverse('file', args=[self.logo_file.pk])

    # Called by payments_pop_by_invoice_user in Payment model.
    def get_payment_description(self, inv):
        """
        The description will be sent to payment gateway and displayed on invoice.
        If not supplied, the default description will be generated.
        """
        return 'Tendenci Invoice %d for Directory: %s (%d).' % (
            inv.id,
            self.headline,
            inv.object_id,
        )

    def make_acct_entries(self, user, inv, amount, **kwargs):
        """
        Make the accounting entries for the directory sale
        """
        from tendenci.apps.accountings.models import Acct, AcctEntry, AcctTran
        from tendenci.apps.accountings.utils import make_acct_entries_initial, make_acct_entries_closing

        ae = AcctEntry.objects.create_acct_entry(user, 'invoice', inv.id)
        if not inv.is_tendered:
            make_acct_entries_initial(user, ae, amount)
        else:
            # payment has now been received
            make_acct_entries_closing(user, ae, amount)

            # #CREDIT directory SALES
            acct_number = self.get_acct_number()
            acct = Acct.objects.get(account_number=acct_number)
            AcctTran.objects.create_acct_tran(user, ae, acct, amount*(-1))

    def get_acct_number(self, discount=False):
        if discount:
            return 464400
        else:
            return 404400

    def auto_update_paid_object(self, request, payment):
        """
        Update the object after online payment is received.
        """
        if not request.user.profile.is_superuser:
            self.status_detail = 'paid - pending approval'
            self.save()

    def age(self):
        return datetime.now() - self.create_dt
    
    def cats_list(self):
        items = []
        for cat in self.cats.all():
            sub_cats = self.sub_cats.filter(parent=cat)
            items.append((cat, list(sub_cats)))
        return items

    @property
    def category_set(self):
        items = {}
        for cat in self.categories.select_related('category', 'parent'):
            if cat.category:
                items["category"] = cat.category
            elif cat.parent:
                items["sub_category"] = cat.parent
        return items

    def renew_window(self):
        days = get_setting('module', 'directories', 'renewaldays')
        days = int(days)
        if self.expiration_dt and datetime.now() + timedelta(days) > self.expiration_dt:
            return True
        else:
            return False
        
    def has_membership_with(self, this_user):
        """
        Check if this directory is associated with a membership or a corporate membership
        that this user owns. 
        
        Return ``True`` if this directory is associated with an active membership
        or corporate membership, and this_user owns the membership or is a representative
        of the corporate membership, or is the ``creator`` or ``owner`` of this directory.
        """
        [m] = self.membershipdefault_set.filter(status_detail='active')[:1] or [None]
        if m:
            if any([this_user==self.creator,
                   this_user==self.owner,
                   this_user==m.user]):
                return True

        if hasattr(self, 'corpprofile'):
            corp_membership = self.corpprofile.corp_membership
            if corp_membership and corp_membership.status_detail == 'active':
                if any([this_user==self.creator,
                       this_user==self.owner,
                       self.corpprofile.is_rep(this_user)]):
                    return True
        return False

    def get_owner_emails_list(self):
        """
        Returns a list of owner's email addresses.
        
        It's tricky because directory doesn't have a clear owner. 
        Since the owner field can be changed to whoever last edited, we'll
        check the creator, the email address field, member or reps if 
        it is created from memberships and corp memberships, respectively.
        """
        emails_list = []
        # creator
        if self.creator and validate_email(self.creator.email):
            emails_list.append(self.creator.email)

        # the email field  
        if validate_email(self.email):
            emails_list.append(self.email)

        # member
        [m] = self.membershipdefault_set.filter(status_detail='active')[:1] or [None]
        if m and validate_email(m.user.email):
            emails_list.append(m.user.email)

        # corp reps
        if hasattr(self, 'corpprofile'):
            corp_reps = self.corpprofile.reps.all()
            for rep in corp_reps:
                if validate_email(rep.user.email):
                    emails_list.append(rep.user.email)

        return list(set(emails_list))

    def get_corp_profile(self):
        if hasattr(self, 'corpprofile'):
            return self.corpprofile

    def get_corp_type(self):
        """
        Returns the corporate membership type that associates with the directory.
        """
        corp_profile = self.get_corp_profile()
        if corp_profile:
            corp_membership = corp_profile.corp_membership
            if corp_membership:
                return corp_membership.corporate_membership_type

    def get_membership(self):
        [membership] = list(self.membershipdefault_set.filter(status_detail='active'))[:1] or [None]
        return membership

    def get_member_type(self):
        """
        Returns the membership type that associates with the directory.
        """
        membership = self.get_membership()
        if membership:
            return membership.membership_type

    def is_owner(self, user_this):
        if not user_this or not user_this.is_authenticated:
            return False

        # is creator or owner
        if user_this == self.creator or user_this == self.owner:
            return True

        # is corp rep
        if hasattr(self, 'corpprofile'):
            if self.corpprofile.reps.filter(user__in=[user_this]):
                return True
        
        # member
        membership = self.get_membership()
        if membership and membership.user == user_this:
            return True
        
        return False


    def can_connect_from(self, directory_from=None, directory_from_cat=None):
        """
        Check if this directory can be connected from ``directory_from``.
        """
        affliated_cats = self.get_affliated_cats()
        if directory_from_cat:
            return directory_from_cat in affliated_cats
        
        if directory_from:
            for cat in directory_from.cats.all():
                if cat in affliated_cats:
                    return True
        return False

    def get_affliated_cats(self):
        """
        Get a list of categories that are allowed to connect with the categories of this directory.
        """
        affliated_cats = []
        for cat in self.cats.all():
            if hasattr(cat, 'connections'):
                if cat.connections.affliated_cats.count() > 0:
                    affliated_cats += list(cat.connections.affliated_cats.all())
        return affliated_cats

    def get_parent_cats(self):
        """
        Get a list of parent categories that this directory can associate to.
        """
        parent_cats = []
        for cat in self.cats.all():
            connections = cat.allowed_connections.all()
            for c in connections:
                if not c.cat in parent_cats:
                    parent_cats.append(c.cat)
        return parent_cats

    def get_list_affiliates(self):
        """
        Return a sorted list of list of affiliate directories, 
        grouped by category.
        ex: [(category_name, [d1, d2, ..]),...]
        """
        affiliates_dict = {}
        affliated_cats = self.get_affliated_cats()
        for affiliateship in Affiliateship.objects.filter(directory=self):
            affiliate = affiliateship.affiliate
            if affiliate.status_detail =='active':
                cat = affiliateship.connected_as
                if cat in affliated_cats:
                    if cat in affiliates_dict:
                        affiliates_dict[cat].append(affiliate)
                    else:
                        affiliates_dict[cat] = [affiliate]

        return sorted(list(affiliates_dict.items()), key=lambda item: item[0].position)

    def get_list_parent_directories(self):
        """
        Return a sorted list of list of parent directories, 
        grouped by category, 
        ex: [(category_name, [d1, d2, ..]),...]
        """
        parents_dict = {}
        parent_cats = self.get_parent_cats()
        for affiliateship in Affiliateship.objects.filter(affiliate=self):
            parent_d = affiliateship.directory
            if parent_d.status_detail =='active':
                connected_cat = affiliateship.connected_as
                for cat in parent_d.cats.all():
                    if cat in parent_cats and connected_cat in cat.connections.affliated_cats.all():
                        if cat in parents_dict:
                            parents_dict[cat].append(parent_d)
                        else:
                            parents_dict[cat] = [parent_d]

        return sorted(list(parents_dict.items()), key=lambda item: item[0].position)

    def allow_associate_by(self, user_this):
        """
        Check if user_this is allowed to submit affiliate requests.
        
        If the connection is limited to the allowed connection, 
        this user will need to have a valid membership with the
        membership type is in the allowed types. 
        """
        affliated_cats = self.get_affliated_cats()

        if affliated_cats:
            if user_this.is_superuser:
                return True

            # check if user_this is the owner of a directory with the category in affliated_cats
            for directory in Directory.objects.filter(cats__in=affliated_cats):
                if directory.is_owner(user_this):
                    return True

    def allow_approve_affiliations_by(self, user_this):
        """
        Check if user_this is allowed to approve affiliate requests.
        
        Superuser or the directory owner can approve.
        The directory owners include creator, owner, and associated corp reps.
        """
        if not user_this or not user_this.is_authenticated:
            return False

        if user_this.is_superuser:
            return True

        # is creator or owner
        if user_this == self.creator or user_this == self.owner:
            return True

        # is a corp rep
        if hasattr(self, 'corpprofile'):
            if self.corpprofile.reps.filter(user__in=[user_this]):
                return True

        return False

    def allow_reject_affiliations_by(self, user_this):
        """
        Check if user_this is allowed to reject affiliate requests.
        
        Superuser or the directory owner can reject.
        The directory owners include creator, owner, and associated corp reps.
        """
        return self.allow_approve_affiliations_by(user_this)
示例#7
0
class Directory(TendenciBaseModel):

    guid = models.CharField(max_length=40)
    slug = SlugField(_('URL Path'), unique=True)
    timezone = TimeZoneField(verbose_name=_('Time Zone'), default='US/Central', choices=get_timezone_choices(), max_length=100)
    headline = models.CharField(_('Name'), max_length=200, blank=True)
    summary = models.TextField(blank=True)
    body = tinymce_models.HTMLField(_('Description'))
    source = models.CharField(max_length=300, blank=True)
    # logo = models.FileField(max_length=260, upload_to=file_directory,
    #                         help_text=_('Company logo. Only jpg, gif, or png images.'),
    #                         blank=True)

    logo_file = models.ForeignKey(File, null=True, on_delete=models.CASCADE)

    first_name = models.CharField(_('First Name'), max_length=100, blank=True)
    last_name = models.CharField(_('Last Name'), max_length=100, blank=True)
    address = models.CharField(_('Address'), max_length=100, blank=True)
    address2 = models.CharField(_('Address 2'), max_length=100, blank=True)
    city = models.CharField(_('City'), max_length=50, blank=True)
    state = models.CharField(_('State'), max_length=50, blank=True)
    zip_code = models.CharField(_('Zip Code'), max_length=50, blank=True)
    country = models.CharField(_('Country'), max_length=50, blank=True)
    region = models.ForeignKey(Region, blank=True, null=True, on_delete=models.SET_NULL)
    phone = models.CharField(max_length=50, blank=True)
    phone2 = models.CharField(_('Phone 2'), max_length=50, blank=True)
    fax = models.CharField(_('Fax'), max_length=50, blank=True)
    email = models.CharField(_('Email'), max_length=120, blank=True)
    email2 = models.CharField(_('Email 2'), max_length=120, blank=True)
    website = models.CharField(max_length=300, blank=True)

    renewal_notice_sent = models.BooleanField(default=False)
    list_type = models.CharField(_('List Type'), max_length=50, blank=True)
    requested_duration = models.IntegerField(_('Requested Duration'), default=0)
    pricing = models.ForeignKey('DirectoryPricing', null=True, on_delete=models.CASCADE)
    activation_dt = models.DateTimeField(_('Activation Date/Time'), null=True, blank=True)
    expiration_dt = models.DateTimeField(_('Expiration Date/Time'), null=True, blank=True)
    invoice = models.ForeignKey(Invoice, blank=True, null=True, on_delete=models.CASCADE)
    payment_method = models.CharField(_('Payment Method'), max_length=50, blank=True)
    
    # social media links
    linkedin = models.URLField(_('LinkedIn'), blank=True, default='')
    facebook = models.URLField(_('Facebook'), blank=True, default='')
    twitter = models.URLField(_('Twitter'), blank=True, default='')
    instagram = models.URLField(_('Instagram'), blank=True, default='')
    youtube = models.URLField(_('YouTube'), blank=True, default='')

    syndicate = models.BooleanField(_('Include in RSS feed'), default=True)
    design_notes = models.TextField(_('Design Notes'), blank=True)
    admin_notes = models.TextField(_('Admin Notes'), blank=True)
    tags = TagField(blank=True)

    # for podcast feeds
    enclosure_url = models.CharField(_('Enclosure URL'), max_length=500, blank=True)
    enclosure_type = models.CharField(_('Enclosure Type'), max_length=120, blank=True)
    enclosure_length = models.IntegerField(_('Enclosure Length'), default=0)

    # html-meta tags
    meta = models.OneToOneField(MetaTags, null=True, on_delete=models.SET_NULL)

    cat = models.ForeignKey(Category, verbose_name=_("Category"),
                                 related_name="directory_cat", null=True, on_delete=models.SET_NULL)
    sub_cat = models.ForeignKey(Category, verbose_name=_("Sub Category"),
                                 related_name="directory_subcat", null=True, on_delete=models.SET_NULL)
    # legacy categories needed for data migration
    categories = GenericRelation(CategoryItem,
                                          object_id_field="object_id",
                                          content_type_field="content_type")
    perms = GenericRelation(ObjectPermission,
                                          object_id_field="object_id",
                                          content_type_field="content_type")

    objects = DirectoryManager()

    class Meta:
#         permissions = (("view_directory",_("Can view directory")),)
        verbose_name = _("Directory")
        verbose_name_plural = _("Directories")
        app_label = 'directories'

    def get_meta(self, name):
        """
        This method is standard across all models that are
        related to the Meta model.  Used to generate dynamic
        methods coupled to this instance.
        """
        return DirectoryMeta().get_meta(self, name)

    def __str__(self):
        return self.headline

    def get_absolute_url(self):
        return reverse('directory', args=[self.slug])

    def get_renew_url(self):
        return reverse('directory.renew', args=[self.id])

    def set_slug(self):
        if not self.slug:
            slug = slugify(self.headline)
            count = str(Directory.objects.count())
            if len(slug) + len(count) >= 99:
                self.slug = '%s-%s' % (slug[:99-len(count)], count)
            else:
                self.slug = '%s-%s' % (slug, count)

    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid4())

        super(Directory, self).save(*args, **kwargs)
        if self.logo:
            if self.is_public():
                set_s3_file_permission(self.logo.name, public=True)
            else:
                set_s3_file_permission(self.logo.name, public=False)

    def is_public(self):
        return all([self.allow_anonymous_view,
                self.status,
                self.status_detail in ['active']])

    def has_social_media(self):
        return any([self.linkedin, self.facebook, self.twitter, self.instagram, self.youtube])

    @property
    def logo(self):
        """
        This represents the logo FileField

        Originally this was a FileField, but later
        we added the attribute logo_file to leverage
        the File model.  We then replaced the logo
        property with this convience method for
        backwards compatibility.
        """
        if self.logo_file:
            return self.logo_file.file

    def get_logo_url(self):
        if not self.logo_file:
            return u''

        return reverse('file', args=[self.logo_file.pk])

    # Called by payments_pop_by_invoice_user in Payment model.
    def get_payment_description(self, inv):
        """
        The description will be sent to payment gateway and displayed on invoice.
        If not supplied, the default description will be generated.
        """
        return 'Tendenci Invoice %d for Directory: %s (%d).' % (
            inv.id,
            self.headline,
            inv.object_id,
        )

    def make_acct_entries(self, user, inv, amount, **kwargs):
        """
        Make the accounting entries for the directory sale
        """
        from tendenci.apps.accountings.models import Acct, AcctEntry, AcctTran
        from tendenci.apps.accountings.utils import make_acct_entries_initial, make_acct_entries_closing

        ae = AcctEntry.objects.create_acct_entry(user, 'invoice', inv.id)
        if not inv.is_tendered:
            make_acct_entries_initial(user, ae, amount)
        else:
            # payment has now been received
            make_acct_entries_closing(user, ae, amount)

            # #CREDIT directory SALES
            acct_number = self.get_acct_number()
            acct = Acct.objects.get(account_number=acct_number)
            AcctTran.objects.create_acct_tran(user, ae, acct, amount*(-1))

    def get_acct_number(self, discount=False):
        if discount:
            return 464400
        else:
            return 404400

    def auto_update_paid_object(self, request, payment):
        """
        Update the object after online payment is received.
        """
        if not request.user.profile.is_superuser:
            self.status_detail = 'paid - pending approval'
            self.save()

    def age(self):
        return datetime.now() - self.create_dt

    @property
    def category_set(self):
        items = {}
        for cat in self.categories.select_related('category', 'parent'):
            if cat.category:
                items["category"] = cat.category
            elif cat.parent:
                items["sub_category"] = cat.parent
        return items

    def renew_window(self):
        days = get_setting('module', 'directories', 'renewaldays')
        days = int(days)
        if self.expiration_dt and datetime.now() + timedelta(days) > self.expiration_dt:
            return True
        else:
            return False
示例#8
0
文件: models.py 项目: moinnn/tendenci
class Person(TendenciBaseModel):
    user = UnsavedOneToOne(User,
                           related_name="profile",
                           verbose_name=_('user'),
                           on_delete=models.CASCADE)
    phone = models.CharField(_('phone'), max_length=50, blank=True)
    address = models.CharField(_('address'), max_length=150, blank=True)
    address2 = models.CharField(_('address2'),
                                max_length=100,
                                default='',
                                blank=True)
    member_number = models.CharField(_('member number'),
                                     max_length=50,
                                     blank=True)
    city = models.CharField(_('city'), max_length=50, blank=True)
    state = models.CharField(_('state'), max_length=50, blank=True)
    zipcode = models.CharField(_('zipcode'), max_length=50, blank=True)
    county = models.CharField(_('county'), max_length=50, blank=True)
    country = models.CharField(_('country'), max_length=255, blank=True)

    # fields to be used for the alternate address
    address_2 = models.CharField(_('address'), max_length=150, blank=True)
    address2_2 = models.CharField(_('address2'),
                                  max_length=100,
                                  default='',
                                  blank=True)
    member_number_2 = models.CharField(_('member number'),
                                       max_length=50,
                                       blank=True)
    city_2 = models.CharField(_('city'), max_length=50, blank=True)
    state_2 = models.CharField(_('state'), max_length=50, blank=True)
    zipcode_2 = models.CharField(_('zipcode'), max_length=50, blank=True)
    county_2 = models.CharField(_('county'), max_length=50, blank=True)
    country_2 = models.CharField(_('country'), max_length=255, blank=True)

    url = models.CharField(_('url'), max_length=100, blank=True)

    time_zone = TimeZoneField(verbose_name=_('timezone'),
                              default='US/Central',
                              choices=get_timezone_choices(),
                              max_length=100)
    language = models.CharField(_('language'),
                                max_length=10,
                                choices=settings.LANGUAGES,
                                default=settings.LANGUAGE_CODE)

    perms = GenericRelation(ObjectPermission,
                            object_id_field="object_id",
                            content_type_field="content_type")

    class Meta:
        abstract = True

    def get_address(self):
        """
        Returns full address depending on which attributes are available.
        """
        state_zip = ' '.join([s for s in (self.state, self.zipcode) if s])
        city_state_zip = ', '.join(
            [s for s in (self.city, state_zip, self.country) if s])

        return '%s %s %s' % (self.address, self.address2, city_state_zip)

    def get_alternate_address(self):
        """
        Returns full alternate address depending on which attributes are available.
        """
        state_zip = ' '.join([s for s in (self.state_2, self.zipcode_2) if s])
        city_state_zip = ', '.join(
            [s for s in (self.city_2, state_zip, self.country_2) if s])

        return '%s %s %s' % (self.address_2, self.address2_2, city_state_zip)
示例#9
0
class News(TendenciBaseModel):
    CONTRIBUTOR_AUTHOR = 1
    CONTRIBUTOR_PUBLISHER = 2
    CONTRIBUTOR_CHOICES = ((CONTRIBUTOR_AUTHOR, _('Author')),
                           (CONTRIBUTOR_PUBLISHER, _('Publisher')))

    guid = models.CharField(max_length=40)
    slug = SlugField(_('URL Path'), unique=True)
    timezone = TimeZoneField(verbose_name=_('Time Zone'),
                             default='US/Central',
                             choices=get_timezone_choices(),
                             max_length=100)
    headline = models.CharField(max_length=200, blank=True)
    summary = models.TextField(blank=True)
    body = tinymce_models.HTMLField()
    source = models.CharField(max_length=300, blank=True)
    first_name = models.CharField(_('First Name'), max_length=100, blank=True)
    last_name = models.CharField(_('Last Name'), max_length=100, blank=True)
    contributor_type = models.IntegerField(choices=CONTRIBUTOR_CHOICES,
                                           default=CONTRIBUTOR_AUTHOR)
    phone = models.CharField(max_length=50, blank=True)
    fax = models.CharField(max_length=50, blank=True)
    email = models.CharField(max_length=120, blank=True)
    website = models.CharField(max_length=300, blank=True)
    thumbnail = models.ForeignKey(
        NewsImage,
        default=None,
        null=True,
        on_delete=models.SET_NULL,
        help_text=
        _('The thumbnail image can be used on your homepage or sidebar if it is setup in your theme. The thumbnail image will not display on the news page.'
          ))
    release_dt = models.DateTimeField(_('Release Date/Time'),
                                      null=True,
                                      blank=True)
    # used for better performance when retrieving a list of released news
    release_dt_local = models.DateTimeField(null=True, blank=True)
    syndicate = models.BooleanField(_('Include in RSS feed'), default=True)
    design_notes = models.TextField(_('Design Notes'), blank=True)
    groups = models.ManyToManyField(Group,
                                    default=get_default_group,
                                    related_name='group_news')
    tags = TagField(blank=True)

    #for podcast feeds
    enclosure_url = models.CharField(_('Enclosure URL'),
                                     max_length=500,
                                     blank=True)  # for podcast feeds
    enclosure_type = models.CharField(_('Enclosure Type'),
                                      max_length=120,
                                      blank=True)  # for podcast feeds
    enclosure_length = models.IntegerField(_('Enclosure Length'),
                                           default=0)  # for podcast feeds

    use_auto_timestamp = models.BooleanField(_('Auto Timestamp'),
                                             default=False)

    # html-meta tags
    meta = models.OneToOneField(MetaTags, null=True, on_delete=models.SET_NULL)

    categories = GenericRelation(CategoryItem,
                                 object_id_field="object_id",
                                 content_type_field="content_type")

    perms = GenericRelation(ObjectPermission,
                            object_id_field="object_id",
                            content_type_field="content_type")

    objects = NewsManager()

    class Meta:
        permissions = (("view_news", _("Can view news")), )
        verbose_name_plural = _("News")
        app_label = 'news'

    def get_meta(self, name):
        """
        This method is standard across all models that are
        related to the Meta model.  Used to generate dynamic
        meta information niche to this model.
        """
        return NewsMeta().get_meta(self, name)

    def get_absolute_url(self):
        return reverse('news.detail', args=[self.slug])

    def __str__(self):
        return self.headline

    def save(self, *args, **kwargs):
        if not self.id:
            self.guid = str(uuid.uuid4())
        self.assign_release_dt_local()

        photo_upload = kwargs.pop('photo', None)
        super(News, self).save(*args, **kwargs)

        if photo_upload and self.pk:
            image = NewsImage(object_id=self.pk,
                              creator=self.creator,
                              creator_username=self.creator_username,
                              owner=self.owner,
                              owner_username=self.owner_username)
            photo_upload.file.seek(0)
            image.file.save(photo_upload.name, photo_upload)  # save file row
            image.save()  # save image row

            if self.thumbnail:
                self.thumbnail.delete()  # delete image and file row
            self.thumbnail = image  # set image

            self.save()

        if self.thumbnail:
            if self.is_public():
                set_s3_file_permission(self.thumbnail.file, public=True)
            else:
                set_s3_file_permission(self.thumbnail.file, public=False)

    @property
    def category_set(self):
        items = {}
        for cat in self.categories.select_related('category', 'parent'):
            if cat.category:
                items["category"] = cat.category
            elif cat.parent:
                items["sub_category"] = cat.parent
        return items

    def is_public(self):
        return all([
            self.allow_anonymous_view, self.status, self.status_detail
            in ['active']
        ])

    @property
    def is_released(self):
        return self.release_dt_local <= datetime.now()

    @property
    def has_google_author(self):
        return self.contributor_type == self.CONTRIBUTOR_AUTHOR

    @property
    def has_google_publisher(self):
        return self.contributor_type == self.CONTRIBUTOR_PUBLISHER

    def assign_release_dt_local(self):
        """
        convert release_dt to the corresponding local time

        example:

        if
            release_dt: 2014-05-09 03:30:00
            timezone: US/Pacific
            settings.TIME_ZONE: US/Central
        then
            the corresponding release_dt_local will be: 2014-05-09 05:30:00
        """
        now = datetime.now()
        now_with_tz = adjust_datetime_to_timezone(now, settings.TIME_ZONE)
        if self.timezone and self.release_dt and self.timezone.zone != settings.TIME_ZONE:
            time_diff = adjust_datetime_to_timezone(
                now, self.timezone) - now_with_tz
            self.release_dt_local = self.release_dt + time_diff
        else:
            self.release_dt_local = self.release_dt