/personal/admin.py
Python | 296 lines | 216 code | 18 blank | 62 comment | 27 complexity | 03187a38ba4dc81ec4fa2162dde085c7 MD5 | raw file
- # -*- coding: utf-8 -*-
- """ personal admin """
- from django.contrib import admin, messages
- from django.conf.urls.defaults import patterns, url
- from django.core.exceptions import ObjectDoesNotExist
- from django.core.urlresolvers import reverse
- from django.shortcuts import render_to_response, get_object_or_404, redirect
- from django.template import RequestContext
- from django.template.response import TemplateResponse
- #from django.utils.safestring import SafeString
- from common.utils import json_response
- from proyectos.forms import AdminSelectModeloContratoForm, \
- AdminEditModeloContratoForm, AdminAssureForm
- from aseguradoras.models import Poliza
- from proyectos.models import Proyecto
- from proyectos import settings as proyectos_settings
- from personal.models import Especialidad, Personal, PersonalEspecialidad
- from personal.forms import AdminEspecialidadForm, AdminPersonalForm, \
- MultiSelectEspecialidades
- from djcelery.models import PeriodicTask, IntervalSchedule, CrontabSchedule, \
- TaskState, WorkerState
- import djcelery
- class PersonalEspecialidadInline(admin.TabularInline):
- """ TabularInline of the PersonalEspecialidad model """
- model = PersonalEspecialidad
- extra = 1
- class EspecialidadAdmin(admin.ModelAdmin):
- """ Model Admin que gestiona las especialidades """
- form = AdminEspecialidadForm
- search_fields = ('nombre', )
- class PersonalAdmin(admin.ModelAdmin):
- """
- Model Admin que gestiona al personal
- """
- exclude = ('web', 'telefonos', 'observaciones', 'direcciones', 'user', )
- form = AdminPersonalForm
- # fields = ('id', 'nombres', 'apellidos', 'correo', 'ruc', 'dni',
- # 'id_direccion',
- # 'direccion', 'departamento', 'provincia', 'distrito',
- # 'sexo', 'grado_instruccion', 'estado_civil', 'ocupacion',
- # 'foto', 'fecha_nacimiento', 'sistema_de_pensiones', 'nro_cuspp',
- # 'nro_seguro_social', 'grupo_sanguineo',
- # 'antecedentes_policiales', 'tipo', 'valoracion', )
- fieldsets = (
- (u'Datos Básicos', {
- 'fields': ('id', ('nombres', 'apellidos', 'dni', ),
- 'id_direccion', 'direccion',
- ('departamento', 'provincia', 'distrito'),
- ('grupo_sanguineo', 'grado_instruccion',
- 'estado_civil'),
- ('sexo', 'tipo'), 'valoracion', ),
- 'description': u'Datos necesarios para realizar un contrato.',
- }),
- (u'Datos Extra', {
- 'classes': ('collapse', ),
- 'fields': (('fecha_nacimiento', 'ocupacion'),
- ('correo', 'ruc'),
- ('foto', 'antecedentes_policiales'),
- 'sistema_de_pensiones',
- ('nro_cuspp', 'nro_seguro_social'),
- ),
- 'description': u'Datos no extríctamente necesarios para realizar \
- un contrato.',
- })
- )
- list_display = ('__unicode__', 'disponibilidad', )
- list_filter = ('estado', 'tipo', 'valoracion', )
- search_fields = ('^user__last_name', )
- actions = ('delete_personal', 'hire', )
- inlines = (PersonalEspecialidadInline, )
- def queryset(self, request):
- """
- """
- # from django.http import QueryDict
- # exp_flag = False
- # if 'experience' in request.GET:
- # request.GET = request.GET.copy()
- # exp = request.GET.pop('experience')
- # exp_flag = True
- query_set = super(self.__class__, self).queryset(request)
- # if exp_flag:
- # experience_form = ExperienciaForm(QueryDict(
- # 'experience=%s' % exp[0]))
- # if experience_form.is_valid():
- # experience_form.save(query_set)
- return query_set
- def changelist_view(self, request, extra_context=None):
- """
- adds and additional filter using the form MultiSelectEspecialidades
- """
- extra_context = extra_context or {}
- extra_context['form_multiselect'] = MultiSelectEspecialidades(
- initial={
- 'especialidad': request.session.get('especialidades') or [],
- 'experiencia_minima': request.session.get(
- 'min_experience') or 0})
- res = super(self.__class__, self).changelist_view(
- request, extra_context)
- # for some reason it doesn't work using GET
- if isinstance(res, TemplateResponse):
- if request.method == 'POST':
- res.context_data['form_multiselect'] = \
- MultiSelectEspecialidades(request.POST)
- if res.context_data['form_multiselect'].is_valid():
- res.context_data['form_multiselect'].save(request)
- else:
- request.session['especialidades'] = []
- res.context_data['form_multiselect'].apply_filters(res, request)
- return res
- def get_actions(self, request):
- """ disables actions for this ModelAdmin """
- actions = super(self.__class__, self).get_actions(request)
- del actions['delete_selected']
- return actions
- def delete_personal(self, request, queryset):
- """ disables the selected Personal objects """
- for personal in queryset:
- personal.delete()
- self.message_user(request, u'El personal seleccionado fue eliminado.')
- delete_personal.short_description = u'Borrar al personal seleccionado.'
- # this action was deactivated cause enabling a person that is already
- # hired will cause problems when finishing the contract. Ex:
- # if a already hired person is reactivated and then hired, when the
- # first contract is closed this person will be reactivated one more time
- # despite of he should be with hired state.
- # def reactivate_personal(self, request, queryset):
- # """ enables the selected Personal objects """
- # for personal in queryset:
- # personal.reactivate()
- # self.message_user(
- # request, u'El personal seleccionado fue reactivado.')
- # reactivate_personal.short_description = u'Reactivar personal eliminado.'
- def hire(self, request, queryset):
- """
- renders to the page to confirm the hiring
- """
- if queryset.exclude(estado=u'viable'):
- messages.error(request, u'No se pudo realizar el contrado. \
- Recuerde que debe seleccionar sólo personal con estado viable.')
- return redirect('admin:personal_personal_changelist')
- return render_to_response(
- 'admin/personal/personal/confirm_hiring.html',
- {'personal_list': queryset, },
- context_instance=RequestContext(request))
- hire.short_description = u'Contratar personal.'
- def select_modelo_contrato(self, request):
- """
- initializes the form with the data sent by post by the previous view
- and manage the form for selecting a new contract model.
- """
- if request.method == 'POST' or (
- 'select_modelo_contrato' in request.session):
- if 'confirmed' in request.POST or (
- 'select_modelo_contrato' in request.session):
- form = AdminSelectModeloContratoForm().first_init(request)
- else:
- form = AdminSelectModeloContratoForm(request.POST)
- if form.is_valid():
- form.save(request)
- return redirect(
- 'admin:admin_personal_edit_modelo_contrato')
- return render_to_response(
- 'admin/personal/personal/select_modelo_contrato.html',
- {'form': form,
- 'add_shorcurts': {
- 'modelo_contrato': reverse(
- 'admin:proyectos_modelocontrato_add'),
- 'proyecto': reverse('admin:proyectos_proyecto_add'),
- 'cliente': reverse('admin:clientes_cliente_add'),
- 'poliza': reverse('admin:aseguradoras_poliza_add')}},
- context_instance=RequestContext(request))
- return redirect('admin:personal_personal_changelist')
- def edit_modelo_contrato(self, request):
- """
- manages the contract model edition page before creating the contracts
- """
- modified = False
- if request.method == 'GET':
- if 'select_modelo_contrato' not in request.session:
- return redirect('admin:personal_personal_changelist')
- form = AdminEditModeloContratoForm().first_init(request)
- elif 'go_back' in request.POST:
- return redirect('admin:admin_personal_select_modelo_contrato')
- else:
- form = AdminEditModeloContratoForm(request.POST)
- if form.is_valid():
- modified = form.model_has_changed(request)
- if not modified:
- return form.save(request)
- return render_to_response(
- 'admin/personal/personal/edit_modelo_contrato.html',
- {'form': form, 'modified': modified, },
- context_instance=RequestContext(request))
- def contract_done(self, request, project_id):
- """
- shows the page with the download link of the PDF with all the
- contracts, it also shows the buttons to go back to the changelist page
- or to starts the proccess of assuring the personal
- """
- if request.method == 'GET':
- if 'go_back' in request.GET:
- return redirect('admin:personal_personal_changelist')
- if 'assure' in request.GET:
- return redirect('admin:admin_personal_assure_personal',
- project_id)
- return render_to_response(
- 'admin/personal/personal/contract_done.html',
- {'project': get_object_or_404(Proyecto, id=project_id),
- 'CONTRACTS_URL': proyectos_settings.CONTRATOS_PDF_FOLDER},
- context_instance=RequestContext(request))
- def assure_personal(self, request, project_id):
- """ shows the page with the form to assure the selected personal """
- if request.method == 'GET':
- form = AdminAssureForm().first_init(project_id, request.user)
- poliza_list = Poliza.objects.filter(id__in=form.initial['polizas'])
- else:
- form = AdminAssureForm(request.POST, request.FILES)
- poliza_list = Poliza.objects.filter(
- id__in=eval(form.data['polizas']))
- if form.is_valid():
- return form.save(request)
- return render_to_response(
- 'admin/personal/personal/assure_personal.html',
- {'form': form, 'poliza_list': poliza_list},
- context_instance=RequestContext(request))
- def get_urls(self):
- urls = super(self.__class__, self).get_urls()
- my_urls = patterns(
- '',
- url(r'^ajax_get_personal_user_data/$',
- self.admin_site.admin_view(self.ajax_get_personal_user_data),
- name='admin_ajax_get_personal_user_data'),
- url(r'^select_modelo_contrato/$',
- self.admin_site.admin_view(self.select_modelo_contrato),
- name='admin_personal_select_modelo_contrato'),
- url(r'^edit_modelo_contrato/$',
- self.admin_site.admin_view(self.edit_modelo_contrato),
- name='admin_personal_edit_modelo_contrato'),
- url(r'^contract_done/(?P<project_id>\d+)/$',
- self.admin_site.admin_view(self.contract_done),
- name='admin_personal_contrato_done'),
- url(r'^assure_personal/(?P<project_id>\d+)/$',
- self.admin_site.admin_view(self.assure_personal),
- name='admin_personal_assure_personal'),
- )
- return my_urls + urls
- def ajax_get_personal_user_data(self, request):
- """
- Gets and returns the firsname, lastname, email, and the full address
- of the personal user
- """
- if request.method == 'GET':
- try:
- personal = Personal.objects.get(id=request.GET['object_id'])
- except ObjectDoesNotExist:
- data = {'response': 'error'}
- else:
- addr = personal.direcciones.all()[0]
- data = {'first_name': personal.user.first_name,
- 'last_name': personal.user.last_name,
- 'email': personal.user.email,
- 'id_direccion': addr.id,
- 'direccion': addr.texto,
- 'departamento': addr.departamento.id,
- 'provincia': addr.provincia.id,
- 'distrito': addr.distrito.id}
- return json_response(data)
- return None
- admin.site.register(Especialidad, EspecialidadAdmin)
- admin.site.register(Personal, PersonalAdmin)
- admin.site.unregister(IntervalSchedule)
- admin.site.unregister(CrontabSchedule)
- admin.site.unregister(PeriodicTask)
- admin.site.unregister(TaskState)
- admin.site.unregister(WorkerState)