PageRenderTime 315ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/personal/admin.py

https://bitbucket.org/giussepi/resinmetal
Python | 296 lines | 216 code | 18 blank | 62 comment | 27 complexity | 03187a38ba4dc81ec4fa2162dde085c7 MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """ personal admin """
  3. from django.contrib import admin, messages
  4. from django.conf.urls.defaults import patterns, url
  5. from django.core.exceptions import ObjectDoesNotExist
  6. from django.core.urlresolvers import reverse
  7. from django.shortcuts import render_to_response, get_object_or_404, redirect
  8. from django.template import RequestContext
  9. from django.template.response import TemplateResponse
  10. #from django.utils.safestring import SafeString
  11. from common.utils import json_response
  12. from proyectos.forms import AdminSelectModeloContratoForm, \
  13. AdminEditModeloContratoForm, AdminAssureForm
  14. from aseguradoras.models import Poliza
  15. from proyectos.models import Proyecto
  16. from proyectos import settings as proyectos_settings
  17. from personal.models import Especialidad, Personal, PersonalEspecialidad
  18. from personal.forms import AdminEspecialidadForm, AdminPersonalForm, \
  19. MultiSelectEspecialidades
  20. from djcelery.models import PeriodicTask, IntervalSchedule, CrontabSchedule, \
  21. TaskState, WorkerState
  22. import djcelery
  23. class PersonalEspecialidadInline(admin.TabularInline):
  24. """ TabularInline of the PersonalEspecialidad model """
  25. model = PersonalEspecialidad
  26. extra = 1
  27. class EspecialidadAdmin(admin.ModelAdmin):
  28. """ Model Admin que gestiona las especialidades """
  29. form = AdminEspecialidadForm
  30. search_fields = ('nombre', )
  31. class PersonalAdmin(admin.ModelAdmin):
  32. """
  33. Model Admin que gestiona al personal
  34. """
  35. exclude = ('web', 'telefonos', 'observaciones', 'direcciones', 'user', )
  36. form = AdminPersonalForm
  37. # fields = ('id', 'nombres', 'apellidos', 'correo', 'ruc', 'dni',
  38. # 'id_direccion',
  39. # 'direccion', 'departamento', 'provincia', 'distrito',
  40. # 'sexo', 'grado_instruccion', 'estado_civil', 'ocupacion',
  41. # 'foto', 'fecha_nacimiento', 'sistema_de_pensiones', 'nro_cuspp',
  42. # 'nro_seguro_social', 'grupo_sanguineo',
  43. # 'antecedentes_policiales', 'tipo', 'valoracion', )
  44. fieldsets = (
  45. (u'Datos Básicos', {
  46. 'fields': ('id', ('nombres', 'apellidos', 'dni', ),
  47. 'id_direccion', 'direccion',
  48. ('departamento', 'provincia', 'distrito'),
  49. ('grupo_sanguineo', 'grado_instruccion',
  50. 'estado_civil'),
  51. ('sexo', 'tipo'), 'valoracion', ),
  52. 'description': u'Datos necesarios para realizar un contrato.',
  53. }),
  54. (u'Datos Extra', {
  55. 'classes': ('collapse', ),
  56. 'fields': (('fecha_nacimiento', 'ocupacion'),
  57. ('correo', 'ruc'),
  58. ('foto', 'antecedentes_policiales'),
  59. 'sistema_de_pensiones',
  60. ('nro_cuspp', 'nro_seguro_social'),
  61. ),
  62. 'description': u'Datos no extríctamente necesarios para realizar \
  63. un contrato.',
  64. })
  65. )
  66. list_display = ('__unicode__', 'disponibilidad', )
  67. list_filter = ('estado', 'tipo', 'valoracion', )
  68. search_fields = ('^user__last_name', )
  69. actions = ('delete_personal', 'hire', )
  70. inlines = (PersonalEspecialidadInline, )
  71. def queryset(self, request):
  72. """
  73. """
  74. # from django.http import QueryDict
  75. # exp_flag = False
  76. # if 'experience' in request.GET:
  77. # request.GET = request.GET.copy()
  78. # exp = request.GET.pop('experience')
  79. # exp_flag = True
  80. query_set = super(self.__class__, self).queryset(request)
  81. # if exp_flag:
  82. # experience_form = ExperienciaForm(QueryDict(
  83. # 'experience=%s' % exp[0]))
  84. # if experience_form.is_valid():
  85. # experience_form.save(query_set)
  86. return query_set
  87. def changelist_view(self, request, extra_context=None):
  88. """
  89. adds and additional filter using the form MultiSelectEspecialidades
  90. """
  91. extra_context = extra_context or {}
  92. extra_context['form_multiselect'] = MultiSelectEspecialidades(
  93. initial={
  94. 'especialidad': request.session.get('especialidades') or [],
  95. 'experiencia_minima': request.session.get(
  96. 'min_experience') or 0})
  97. res = super(self.__class__, self).changelist_view(
  98. request, extra_context)
  99. # for some reason it doesn't work using GET
  100. if isinstance(res, TemplateResponse):
  101. if request.method == 'POST':
  102. res.context_data['form_multiselect'] = \
  103. MultiSelectEspecialidades(request.POST)
  104. if res.context_data['form_multiselect'].is_valid():
  105. res.context_data['form_multiselect'].save(request)
  106. else:
  107. request.session['especialidades'] = []
  108. res.context_data['form_multiselect'].apply_filters(res, request)
  109. return res
  110. def get_actions(self, request):
  111. """ disables actions for this ModelAdmin """
  112. actions = super(self.__class__, self).get_actions(request)
  113. del actions['delete_selected']
  114. return actions
  115. def delete_personal(self, request, queryset):
  116. """ disables the selected Personal objects """
  117. for personal in queryset:
  118. personal.delete()
  119. self.message_user(request, u'El personal seleccionado fue eliminado.')
  120. delete_personal.short_description = u'Borrar al personal seleccionado.'
  121. # this action was deactivated cause enabling a person that is already
  122. # hired will cause problems when finishing the contract. Ex:
  123. # if a already hired person is reactivated and then hired, when the
  124. # first contract is closed this person will be reactivated one more time
  125. # despite of he should be with hired state.
  126. # def reactivate_personal(self, request, queryset):
  127. # """ enables the selected Personal objects """
  128. # for personal in queryset:
  129. # personal.reactivate()
  130. # self.message_user(
  131. # request, u'El personal seleccionado fue reactivado.')
  132. # reactivate_personal.short_description = u'Reactivar personal eliminado.'
  133. def hire(self, request, queryset):
  134. """
  135. renders to the page to confirm the hiring
  136. """
  137. if queryset.exclude(estado=u'viable'):
  138. messages.error(request, u'No se pudo realizar el contrado. \
  139. Recuerde que debe seleccionar sólo personal con estado viable.')
  140. return redirect('admin:personal_personal_changelist')
  141. return render_to_response(
  142. 'admin/personal/personal/confirm_hiring.html',
  143. {'personal_list': queryset, },
  144. context_instance=RequestContext(request))
  145. hire.short_description = u'Contratar personal.'
  146. def select_modelo_contrato(self, request):
  147. """
  148. initializes the form with the data sent by post by the previous view
  149. and manage the form for selecting a new contract model.
  150. """
  151. if request.method == 'POST' or (
  152. 'select_modelo_contrato' in request.session):
  153. if 'confirmed' in request.POST or (
  154. 'select_modelo_contrato' in request.session):
  155. form = AdminSelectModeloContratoForm().first_init(request)
  156. else:
  157. form = AdminSelectModeloContratoForm(request.POST)
  158. if form.is_valid():
  159. form.save(request)
  160. return redirect(
  161. 'admin:admin_personal_edit_modelo_contrato')
  162. return render_to_response(
  163. 'admin/personal/personal/select_modelo_contrato.html',
  164. {'form': form,
  165. 'add_shorcurts': {
  166. 'modelo_contrato': reverse(
  167. 'admin:proyectos_modelocontrato_add'),
  168. 'proyecto': reverse('admin:proyectos_proyecto_add'),
  169. 'cliente': reverse('admin:clientes_cliente_add'),
  170. 'poliza': reverse('admin:aseguradoras_poliza_add')}},
  171. context_instance=RequestContext(request))
  172. return redirect('admin:personal_personal_changelist')
  173. def edit_modelo_contrato(self, request):
  174. """
  175. manages the contract model edition page before creating the contracts
  176. """
  177. modified = False
  178. if request.method == 'GET':
  179. if 'select_modelo_contrato' not in request.session:
  180. return redirect('admin:personal_personal_changelist')
  181. form = AdminEditModeloContratoForm().first_init(request)
  182. elif 'go_back' in request.POST:
  183. return redirect('admin:admin_personal_select_modelo_contrato')
  184. else:
  185. form = AdminEditModeloContratoForm(request.POST)
  186. if form.is_valid():
  187. modified = form.model_has_changed(request)
  188. if not modified:
  189. return form.save(request)
  190. return render_to_response(
  191. 'admin/personal/personal/edit_modelo_contrato.html',
  192. {'form': form, 'modified': modified, },
  193. context_instance=RequestContext(request))
  194. def contract_done(self, request, project_id):
  195. """
  196. shows the page with the download link of the PDF with all the
  197. contracts, it also shows the buttons to go back to the changelist page
  198. or to starts the proccess of assuring the personal
  199. """
  200. if request.method == 'GET':
  201. if 'go_back' in request.GET:
  202. return redirect('admin:personal_personal_changelist')
  203. if 'assure' in request.GET:
  204. return redirect('admin:admin_personal_assure_personal',
  205. project_id)
  206. return render_to_response(
  207. 'admin/personal/personal/contract_done.html',
  208. {'project': get_object_or_404(Proyecto, id=project_id),
  209. 'CONTRACTS_URL': proyectos_settings.CONTRATOS_PDF_FOLDER},
  210. context_instance=RequestContext(request))
  211. def assure_personal(self, request, project_id):
  212. """ shows the page with the form to assure the selected personal """
  213. if request.method == 'GET':
  214. form = AdminAssureForm().first_init(project_id, request.user)
  215. poliza_list = Poliza.objects.filter(id__in=form.initial['polizas'])
  216. else:
  217. form = AdminAssureForm(request.POST, request.FILES)
  218. poliza_list = Poliza.objects.filter(
  219. id__in=eval(form.data['polizas']))
  220. if form.is_valid():
  221. return form.save(request)
  222. return render_to_response(
  223. 'admin/personal/personal/assure_personal.html',
  224. {'form': form, 'poliza_list': poliza_list},
  225. context_instance=RequestContext(request))
  226. def get_urls(self):
  227. urls = super(self.__class__, self).get_urls()
  228. my_urls = patterns(
  229. '',
  230. url(r'^ajax_get_personal_user_data/$',
  231. self.admin_site.admin_view(self.ajax_get_personal_user_data),
  232. name='admin_ajax_get_personal_user_data'),
  233. url(r'^select_modelo_contrato/$',
  234. self.admin_site.admin_view(self.select_modelo_contrato),
  235. name='admin_personal_select_modelo_contrato'),
  236. url(r'^edit_modelo_contrato/$',
  237. self.admin_site.admin_view(self.edit_modelo_contrato),
  238. name='admin_personal_edit_modelo_contrato'),
  239. url(r'^contract_done/(?P<project_id>\d+)/$',
  240. self.admin_site.admin_view(self.contract_done),
  241. name='admin_personal_contrato_done'),
  242. url(r'^assure_personal/(?P<project_id>\d+)/$',
  243. self.admin_site.admin_view(self.assure_personal),
  244. name='admin_personal_assure_personal'),
  245. )
  246. return my_urls + urls
  247. def ajax_get_personal_user_data(self, request):
  248. """
  249. Gets and returns the firsname, lastname, email, and the full address
  250. of the personal user
  251. """
  252. if request.method == 'GET':
  253. try:
  254. personal = Personal.objects.get(id=request.GET['object_id'])
  255. except ObjectDoesNotExist:
  256. data = {'response': 'error'}
  257. else:
  258. addr = personal.direcciones.all()[0]
  259. data = {'first_name': personal.user.first_name,
  260. 'last_name': personal.user.last_name,
  261. 'email': personal.user.email,
  262. 'id_direccion': addr.id,
  263. 'direccion': addr.texto,
  264. 'departamento': addr.departamento.id,
  265. 'provincia': addr.provincia.id,
  266. 'distrito': addr.distrito.id}
  267. return json_response(data)
  268. return None
  269. admin.site.register(Especialidad, EspecialidadAdmin)
  270. admin.site.register(Personal, PersonalAdmin)
  271. admin.site.unregister(IntervalSchedule)
  272. admin.site.unregister(CrontabSchedule)
  273. admin.site.unregister(PeriodicTask)
  274. admin.site.unregister(TaskState)
  275. admin.site.unregister(WorkerState)