class EmploymentClient(models.Model):
    volunteers = models.ManyToManyField(Volunteer)

    FirstName = models.CharField("First Name", max_length=50)
    LastName = models.CharField("Last Name", max_length=80)
    StreetAddress = models.CharField("Address", max_length=50)
    City = models.CharField(max_length=20)
    State = models.CharField(max_length=2)
    Zip = models.CharField(max_length=10)
    Phones = models.CharField(max_length=50, blank=True)
    Active = models.BooleanField(default=True)
    Other = models.TextField(blank=True)

    objects = CaseManager()  # re-use same volunteer-based logic as refugee Case

    class Meta:
        verbose_name = 'Employment Client'
        verbose_name_plural = 'Employment Clients'

    def __unicode__(self):
        return self.FirstName + ' ' + self.LastName class Job(models.Model):
    employment_client = models.ForeignKey(EmploymentClient)
    Company = models.CharField("Company", max_length=50)
    Title = models.CharField("Title", max_length=80)
    Description = models.CharField('Description', max_length=200, blank=True)
    StartDate = models.DateField('Start Date')
    EndDate = models.DateField('End Date') class Skill(models.Model):
    employment_client = models.ForeignKey(EmploymentClient)
    Description = models.CharField("Description", max_length=200) class Assesment(models.Model):
    employment_client = models.ForeignKey(EmploymentClient)
    Name = models.CharField("Name", max_length=20, blank=True)
    TakenDate = models.DateField('Taken')
    Score = models.IntegerField()

    def __unicode__(self):
        return 'Assessment'

    class Meta:
        verbose_name = 'Assessment'
        verbose_name_plural = 'Assessments' class Language(models.Model):
    employment_client = models.ForeignKey(EmploymentClient)
    Name = models.CharField("Language", max_length=20)
    # http://en.wikipedia.org/wiki/ILR_scale
    Scale = IntegerRangeField("ILR Scale", min_value=1, max_value=5) class ActivityNote(models.Model):
    employment_client = models.ForeignKey(EmploymentClient, related_name="activity")
    volunteer = models.ForeignKey(Volunteer, related_name='employment_activity')

    date = models.DateField(default=_date.today)
    description = models.TextField(max_length=10000)
    minutes = models.IntegerField("Time spent in minutes", null=True, blank=True)

    def __unicode__(self):
        return '%s %s' % (str(self.employment_client), self.date) class CaseOrClientAdmin(DeleteNotAllowedModelAdmin):
    '''
    Common functionality for EmploymentClients and refugee Cases which both have volunteer relations & security
    '''

    def volunteers_list(self, obj):
        return ', '.join(v.user.first_name + ' ' + v.user.last_name if v.user.first_name + v.user.last_name.strip() != "" else v.user.username for v in obj.volunteers.all())
    volunteers_list.short_description = 'Volunteers'

    def get_queryset(self, request):
        qs = super(CaseOrClientAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return self.order_qs(qs).filter(volunteers__user__exact=request.user)

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == 'volunteers':
            if request.user.is_superuser:
                kwargs['queryset'] = Volunteer.objects
            else:
                kwargs['queryset'] = Volunteer.objects.filter(user=request.user)
        return super(CaseOrClientAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) class VolunteerFilter(admin.SimpleListFilter):
    title = 'Volunteer'
    parameter_name = 'volunteer'

    def lookups(self, request, model_admin):
        if request.user.is_superuser:
            return [
                (v.user.username, '%s %s' % (v.user.first_name, v.user.last_name))
                for v in Volunteer.objects.order_by('user__first_name').all()
            ]
        else:
            return [
                (request.user.username, (request.user.first_name + ' ' + request.user.last_name))
            ]

    def queryset(self, request, queryset):
        if self.value():
            try:
                # for Cases (many-to-many)
                return queryset.filter(volunteers__user__username=self.value())
            except FieldError:
                # for one-to-many where its singular
                return queryset.filter(volunteer__user__username=self.value())
        else:
            return queryset class DeleteNotAllowedModelAdmin(admin.ModelAdmin):
    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser class MinuteTotallingChangeList(ChangeList):
    def get_results(self, request):
        super(MinuteTotallingChangeList, self).get_results(request)
        q = self.result_list.aggregate(minutes_total=Sum('minutes'))
        total = q['minutes_total'] or 0
        self.total_hours = total / 60
        self.total_minutes = total % 60 class Volunteer(models.Model):
    user = models.OneToOneField(User)

    phone = models.CharField(max_length=255)
    mailing_address = models.CharField(max_length=10000, blank=True)

    class Meta:
        verbose_name = 'Volunteer Info'
        verbose_name_plural = 'Volunteer Info'

    def __unicode__(self):
        if self.user.is_active:
            inactive = ''
        else:
            inactive = 'INACTIVE - '
        return '%s %s (%s%s)' % (self.user.first_name, self.user.last_name,
                                 inactive, self.user.username)
from django.contrib import admin
from django.db.models.fields import CharField, TextField
from django.template.defaultfilters import truncatechars
from employment_manager.models import EmploymentClient, Job, Skill, Assesment, Language, ActivityNote
from refugee_manager.admin import CaseOrClientAdmin, VolunteerFilter, DeleteNotAllowedModelAdmin, MinuteTotallingChangeList
from refugee_manager.models import Volunteer



class JobInline(admin.TabularInline):
    model = Job
    extra = 1


class SkillInline(admin.TabularInline):
    model = Skill
    extra = 1


class AssesmentInline(admin.TabularInline):
    model = Assesment
    extra = 1


class LanguageInline(admin.TabularInline):
    model = Language
    extra = 1


class EmploymentClientAdmin(CaseOrClientAdmin):
    fieldsets = [
        ('Volunteers', {'fields': ['volunteers']}),
        ('Name', {'fields': ['FirstName', 'LastName', 'Active']}),
        ('Address', {'fields': ['StreetAddress', 'City', 'State', 'Zip']}),
        ('Phones', {'fields': ['Phones']}),
        ('Other', {'fields': ['Other']}),
    ]
    inlines = [JobInline, SkillInline, AssesmentInline, LanguageInline]
    list_display = ('Active', 'FirstName', 'LastName', 'StreetAddress', 'Phones', 'volunteers_list')
    list_display_links = list_display
    list_filter = ['Active', VolunteerFilter, 'FirstName', 'LastName']
    search_fields = [f.name for f in EmploymentClient._meta.local_fields if isinstance(f, (CharField, TextField))]
    ordering = ('-Active', 'LastName', 'FirstName')

    def volunteers_list(self, obj):
        return ', '.join(v.user.first_name + ' ' + v.user.last_name if v.user.first_name + v.user.last_name.strip() != "" else v.user.username for v in obj.volunteers.all())
    volunteers_list.short_description = 'Volunteers'

    def order_qs(self, qs):
        return qs.order_by('LastName').order_by('FirstName')

admin.site.register(EmploymentClient, EmploymentClientAdmin)


class EmploymentClientFilter(admin.SimpleListFilter):
    title = 'Employment Client'
    parameter_name = 'employment_client'

    def lookups(self, request, model_admin):
        if request.user.is_superuser:
            return [
                (str(c.id), '%s' % (str(c)))
                for c in EmploymentClient.objects.order_by('LastName', 'FirstName').all()
            ]
        else:
            return [
                (str(c.id), '%s' % (str(c)))
                for c in EmploymentClient.objects.order_by('LastName', 'FirstName').filter(volunteers__user__exact=request.user)
            ]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(employment_client=self.value())
        else:
            return queryset



class ActivityNoteAdmin(DeleteNotAllowedModelAdmin):