Project

General

Profile

« Previous | Next » 

Revision 5b90c12e

Added by Serghei Mihai over 11 years ago

Group absences refactored

View differences:

calebasse/personnes/forms.py
232 232
    def __init__(self, *args, **kwargs):
233 233
        self.service = kwargs.pop('service', None)
234 234
        super(GroupHolidayForm, self).__init__(*args, **kwargs)
235
        self.fields['service'].choices = ((service.id, service.name) for service in Service.objects.all())
236 235
        if self.instance and self.instance.id:
237
            self.initial['for_all_services'] = self.instance.service is None
236
            self.initial['for_all_services'] = self.instance.services.count() == Service.objects.count()
238 237
        self.fields['holiday_type'].queryset = \
239 238
                HolidayType.objects.filter(for_group=True)
240 239

  
241 240

  
242 241
    def save(self, commit=True):
243 242
        instance = super(GroupHolidayForm, self).save(commit=False)
244
        if self.cleaned_data.get('for_all_services', False):
245
            instance.service = None
246
        else:
247
            instance.service = self.service
248 243
        if commit:
249 244
            instance.save()
250 245
        return instance
......
253 248
        model = Holiday
254 249
        widgets = {
255 250
            'comment': forms.Textarea(attrs = {'rows': 3, 'cols': 18}),
256
            'service': forms.CheckboxSelectMultiple(attrs = {'class': ''})
251
            'services': forms.CheckboxSelectMultiple()
257 252
        }
258 253

  
259 254
GroupHolidayFormSet = modelformset_factory(Holiday,
calebasse/personnes/models.py
338 338
    def for_worker(self, worker):
339 339
        filter_query = models.Q(worker=worker) \
340 340
              | models.Q(worker__isnull=True,
341
                           service=None) \
341
                           services = None) \
342 342
              | models.Q(worker__isnull=True,
343
                           service__in=worker.services.all())
343
                           services__in = worker.services.all())
344 344
        return self.filter(filter_query)
345 345

  
346 346
    def for_worker_id(self, worker_id):
......
351 351
            return None
352 352
        filter_query = models.Q(worker=worker) \
353 353
              | models.Q(worker__isnull=True,
354
                           service=None) \
354
                           services = None) \
355 355
              | models.Q(worker__isnull=True,
356
                           service__in=worker.services.all())
356
                           services__in = worker.services.all())
357 357
        return self.filter(filter_query)
358 358

  
359 359
    def for_type(self, holiday_type):
360
        return self.filter(holiday_type=holiday_type)
360
        return self.filter(holiday_type = holiday_type)
361 361

  
362 362
    def for_service(self, service):
363
        return self.filter(worker__isnull=True) \
364
                   .filter(models.Q(service=service)
365
                          |models.Q(service__isnull=True))
363
        return self.filter(worker__isnull = True) \
364
                   .filter(models.Q(services = service)
365
                          |models.Q(services__isnull = True))
366 366

  
367 367
    def for_service_workers(self, service):
368
        return self.filter(models.Q(worker__services=service)
369
                |models.Q(service=service)
370
                |models.Q(worker__isnull=True, service__isnull=True))
368
        return self.filter(models.Q(worker__services = [service])
369
                |models.Q(services__in = [service])
370
                |models.Q(worker__isnull=True, services__isnull = True))
371 371

  
372 372
    def future(self):
373 373
        return self.filter(end_date__gte=date.today())
......
405 405
            verbose_name=u'Type de congé')
406 406
    worker = models.ForeignKey(Worker, blank=True, null=True,
407 407
            verbose_name=u"Personnel")
408
    service = models.ForeignKey(Service, blank=True, null=True,
409
            verbose_name=u"Service")
410
    services = models.ManyToManyField(Service, null = True, blank = True, related_name = 'new_services')
408
    services = models.ManyToManyField(Service, null = True,
409
                                      blank = True, verbose_name = u'Services')
411 410
    start_date = models.DateField(verbose_name=u"Date de début",
412 411
        help_text=u'format: jj/mm/aaaa')
413 412
    end_date = models.DateField(verbose_name=u"Date de fin",
......
426 425
    def is_current(self):
427 426
        return self.start_date <= date.today() <= self.end_date
428 427

  
428
    def for_all_services(self):
429
        return self.services.count() == Service.objects.count()
430

  
429 431
    def __unicode__(self):
430 432
        ret = ''
431 433
        if self.start_date == self.end_date:
calebasse/personnes/templates/personnes/group_holiday_update_form.html
1
<form>
2
  {% csrf_token %}
3
  {% if form %}
4
  <table>
5
    <tr><td colspan=2>{{ form.non_field_errors }}</td></tr>
6
    <tr>
7
      <th>Date début</th><th>Date fin</th>
8
    </tr>
9
    <tr>
10
      <td id="start" data-before-selector="#end" class="datepicker" data-number-of-months="2">
11
        {{ form.start_date }} {{ form.start_date.errors }}
12
      </td>
13
      <td id="end" data-after-selector="#start" class="datepicker" data-number-of-months="2">
14
        {{ form.end_date }} {{ form.end_date.errors }}
15
      </td>
16
    </tr>
17
    <tr>
18
      <th>Heure début</th><th>Heure fin</th>
19
    </tr>
20
    <tr>
21
      <td>{{ form.start_time }} {{ form.start_time.errors }}</td>
22
      <td>{{ form.end_time }} {{ form.end_time.errors }}</td>
23
    </tr>
24
    <tr>
25
      <th colspan=2>Service</th>
26
    </tr>
27
    <tr id="services">
28
      <td colspan=2>{{ form.services }}</td>
29
    </tr>
30
    <tr>
31
      <th>Type</<th><th>Commentaire</th>
32
    </tr>
33
    <tr>
34
      <td>{{ form.holiday_type }} {{ form.holiday_type.errors }}</td>
35
      <td>{{ form.comment }} {{ form.comment.errors }}</td>
36
    </tr>
37
  </table>
38
  {% else %}
39
  Etez-vous sur de vouloir supprimer cette absence?
40
  {% endif %}
41
</form>
calebasse/personnes/templates/personnes/group_holidays_list.html
1
{% extends "personnes/simple-form.html" %}
2

  
3
{% block extrascripts %}
4
{{ block.super }}
5
    <script>
6
        $(function() {
7

  
8
            $('button[data-action=delete]').click(function() {
9
                delete_group_holiday($(this).data('id'));
10
            });
11

  
12
            $('button[data-action=edit]').click(function() {
13
                edit_group_holiday($(this).data('id'));
14
            });
15

  
16
            $('button[data-action=new]').click(function() {
17
                add_group_holiday();
18
            });
19

  
20
        });
21
    </script>
22
{% endblock %}
23

  
24

  
25
{% block appbar %}
26
<h2>&nbsp;</h2>
27
  <a href="..">Retour à la gestion des absences</a>
28
{% endblock %}
29

  
30

  
31
{% block content %}
32
    <div class="group_holidays frame">
33
      <h3>Absences de groupe</h3>
34
      <button class="save icon-plus" data-action='new'></button>
35
      <ul id="holidays" class="group">
36
        <li>
37
          <ul class="caption">
38
            <li class="start_date">Date de début</li>
39
            <li class="end_date">Date de fin</li>
40
            <li class="start_time">Heure de début</li>
41
            <li class="end_time">Heure de fin</li>
42
            <li class="type">Type</li>
43
            <li class="all">Tous les services</li>
44
            <li class="comment">Commentaire</li>
45
            <li class="actions">Actions</li>
46
          </ul>
47
        </li>
48
        {% for object in object_list %}
49
        <li id="{{ object.id }}">
50
          <ul style="background: {% cycle '#fff' '#eee' %}">
51
            <li class="start_date">{{ object.start_date }}</li>
52
            <li class="end_date">{{ object.end_date }}</li>
53
            <li class="start_time">{% if object.start_time %}{{ object.start_time }}{% else %}---{% endif %}</li>
54
            <li class="end_time">{% if object.end_time %}{{ object.end_time }}{% else %} --- {% endif %}</li>
55
            <li class="type">{{ object.holiday_type }}</li>
56
            <li class="all">{% if object.for_all_services %}<span class="icon-ok"></span>{% endif %}</li>
57
            <li class="comment">{{ object.comment }}</li>
58
            <li class="actions">
59
              <button class="icon-edit" data-action='edit' data-id='{{ object.id }}'></button>
60
              <button class="icon-remove" data-action='delete' data-id='{{ object.id }}'></button>
61
            </li>
62
          </ul>
63
        </li>
64
        {% endfor %}
65
      </ul>
66
    </div>
67
<p><a href="..">{% block back-link %}Retour à la gestion des absences{% endblock %}</a></p>
68
{% endblock %}
69
{% block dialogs %}
70
<div id="holiday-dlg"></div>
71
{% endblock %}
calebasse/personnes/templates/personnes/holiday_group_form.html
1
<form>
2
  {% csrf_token %}
3
  {% if form %}
4
  <table>
5
    <tr><td colspan=2>{{ form.non_field_errors }}</td></tr>
6
    <tr>
7
      <th>Date début</th><th>Date fin</th>
8
    </tr>
9
    <tr>
10
      <td id="start" data-before-selector="#end" class="datepicker" data-number-of-months="2">
11
        {{ form.start_date }} {{ form.start_date.errors }}
12
      </td>
13
      <td id="end" data-after-selector="#start" class="datepicker" data-number-of-months="2">
14
        {{ form.end_date }} {{ form.end_date.errors }}
15
      </td>
16
    </tr>
17
    <tr>
18
      <th>Heure début</th><th>Heure fin</th>
19
    </tr>
20
    <tr>
21
      <td>{{ form.start_time }} {{ form.start_time.errors }}</td>
22
      <td>{{ form.end_time }} {{ form.end_time.errors }}</td>
23
    </tr>
24
    <tr>
25
      <th colspan=2>Service</th>
26
    </tr>
27
    <tr id="services">
28
      <td colspan=2>{{ form.services }}</td>
29
    </tr>
30
    <tr>
31
      <th>Type</<th><th>Commentaire</th>
32
    </tr>
33
    <tr>
34
      <td>{{ form.holiday_type }} {{ form.holiday_type.errors }}</td>
35
      <td>{{ form.comment }} {{ form.comment.errors }}</td>
36
    </tr>
37
  </table>
38
  {% else %}
39
  Etez-vous sur de vouloir supprimer cette absence?
40
  {% endif %}
41
</form>
calebasse/personnes/urls.py
30 30
    # url(r'^groupe/$', 'group_holiday_update',
31 31
    #     name='group-holiday-update'),
32 32
    url(r'^groupe/$', 'group_holidays', name = 'group-holidays'),
33
    url(r'^groupe/ajouter/?$', 'create_group_holiday', name = 'create-group-holiday'),
33 34
    url(r'^groupe/(?P<pk>\d+)/editer/?$', 'edit_group_holiday', name = 'edit-group-holiday'),
34 35
    url(r'^groupe/(?P<pk>\d+)/supprimer/?$', 'delete_group_holiday', name = 'delete-group-holiday'),
35 36
    )
calebasse/personnes/views.py
229 229
        success_url='../../')
230 230

  
231 231

  
232
class HolidayView(cbv.TemplateView):
232
class HolidayView(cbv.TemplateView, cbv.ServiceViewMixin):
233 233
    months = 3
234 234
    template_name='personnes/holidays.html'
235 235

  
......
267 267
        def holiday_url(holiday):
268 268
            if holiday.worker:
269 269
                return reverse('worker_update', kwargs=dict(
270
                    service=self.service.slug, pk=holiday.worker.pk))
270
                    service = ctx['service'], pk=holiday.worker.pk))
271 271
            else:
272
                slug = holiday.service.slug if holiday.service else self.service.slug
272
                slug = ctx['service']
273 273
                return reverse('group-holidays', kwargs=dict(
274 274
                    service=slug))
275 275

  
......
325 325

  
326 326
group_holiday_update = GroupHolidayUpdateView.as_view()
327 327

  
328
# ===================================================================
328
class HolidayManagement(object):
329
    """
330
    A class providing some methods for handling the absences management
331
    """
332

  
333
    def render_to_json(self, id, context, err = 0, **kwargs):
334
        data = {'err': err, 'id': id, 'content': context}
335
        response = json.dumps(data)
336
        kwargs['content_type'] = 'application/json'
337
        return HttpResponse(response, **kwargs)
338

  
339
    def update_post_data(self, request):
340
        worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
341
        post = request.POST.copy()
342
        post.update({'worker': worker.id})
343
        return worker, post
344

  
345
    def form_valid(self, form):
346
        form.save()
347
        if self.request.is_ajax:
348
            instance = form.instance
349
            status = ''
350
            if instance.is_current() and instance.services.count():
351
                status = u'congés annuels, en cours'
352
            elif instance.is_current():
353
                status = u'en cours'
354
            elif instance.services.count():
355
                status = u'congés annuels'
356

  
357
            context = (('period', '%s' % instance),
358
                       ('status', status),
359
                       ('type', '%s' % instance.holiday_type),
360
                       ('comment', instance.comment)
361
                       )
362
            return self.render_to_json(instance.id, context)
363
        return super(HolidayManagement, self).form_valid(form)
364

  
365
    def group_form_valid(self, form):
366
        """
367
        Method handling the saving of group absences form
368
        """
369
        form.save()
370
        form.save_m2m()
371
        if self.request.is_ajax:
372
            instance = form.instance
373
            context = (('start_date', '%s' % instance.start_date),
374
                       ('end_date', '%s' % instance.end_date),
375
                       ('start_time',
376
                        instance.start_time and '%s' % instance.start_time or '---'),
377
                       ('end_time',
378
                        instance.end_time and '%s' % instance.end_time  or '---'),
379
                       ('type', '%s' % instance.holiday_type),
380
                       ('all',
381
                        instance.for_all_services() and '<span class="icon-ok"></span>' or ''),
382
                       ('comment',
383
                        instance.comment)
384
                       )
385
            return self.render_to_json(instance.id, context)
386
        return super(EditGroupHolidayView, self).form_valid(form)
329 387

  
330 388
class GroupHolidaysList(cbv.ListView):
331 389
    model = models.Holiday
332 390
    template_name = 'personnes/group_holidays_list.html'
333 391
    queryset = model.objects.future()
334 392

  
393
    def get_queryset(self, *args, **kwargs):
394
        qs = super(GroupHolidaysList, self).get_queryset(*args, **kwargs)
395
        qs = qs.for_service(self.service)
396
        return qs
397

  
335 398
group_holidays = GroupHolidaysList.as_view()
336 399

  
337
class CreateGroupHolidayView(cbv.CreateView):
400
class CreateGroupHolidayView(HolidayManagement, cbv.CreateView):
338 401
    form_class = forms.GroupHolidayForm
339 402
    model = models.Holiday
403
    template_name_suffix = '_group_form'
404

  
405
    def get_form_kwargs(self):
406
        return {'initial': {'services': Service.objects.all()}}
340 407

  
341 408
    def post(self, request, *args, **kwargs):
342
        # créer l'objet
343
        pass
409
        form = self.form_class(request.POST)
410
        if form.is_valid():
411
            return self.group_form_valid(form)
412

  
413
        return self.form_invalid(form)
414

  
344 415

  
345 416
create_group_holiday = CreateGroupHolidayView.as_view()
346 417

  
347
class EditGroupHolidayView(cbv.FormView):
418
class EditGroupHolidayView(HolidayManagement, cbv.FormView):
348 419
    template_name = 'personnes/group_holiday_update_form.html'
349 420
    form_class = forms.GroupHolidayForm
350 421
    model = models.Holiday
......
352 423
    def get_form_kwargs(self):
353 424
        kwargs = super(EditGroupHolidayView, self).get_form_kwargs()
354 425
        kwargs['instance'] = self.model.objects.get(pk = self.kwargs['pk'])
355
        print kwargs['instance'].service
356 426
        return kwargs
357 427

  
358 428
    def post(self, request, *args, **kwargs):
359
        return super(EditGroupHolidayView, self).post(request, *args, **kwargs)
429
        obj = self.model.objects.get(pk = self.kwargs['pk'])
430
        form = self.form_class(request.POST, instance = obj)
431
        if form.is_valid():
432
            return self.group_form_valid(form)
433

  
434
        return self.form_invalid(form)
360 435

  
361 436
edit_group_holiday = EditGroupHolidayView.as_view()
362 437

  
......
377 452

  
378 453
delete_group_holiday = DeleteGroupHolidayView.as_view()
379 454

  
380
class HolidayManagement(object):
381

  
382
    def render_to_json(self, id, context, err = 0, **kwargs):
383
        data = {'err': err, 'id': id, 'content': context}
384
        response = json.dumps(data)
385
        kwargs['content_type'] = 'application/json'
386
        return HttpResponse(response, **kwargs)
387

  
388
    def update_post_data(self, request):
389
        worker = models.Worker.objects.get(pk = self.kwargs['worker_pk'])
390
        post = request.POST.copy()
391
        post.update({'worker': worker.id})
392
        return worker, post
393

  
394
    def form_valid(self, form):
395
        form.save()
396
        if self.request.is_ajax:
397
            instance = form.instance
398
            status = ''
399
            if instance.is_current() and instance.service:
400
                status = u'congés annuels, en cours'
401
            elif instance.is_current():
402
                status = u'en cours'
403
            elif instance.service:
404
                status = u'congés annuels'
405

  
406
            context = (('period', '%s' % instance),
407
                       ('status', status),
408
                       ('type', '%s' % instance.holiday_type),
409
                       ('comment', instance.comment)
410
                       )
411
            return self.render_to_json(instance.id, context)
412
        return super(HolidayManagement, self).form_valid(form)
413

  
414 455
class HolidayCreateView(HolidayManagement, cbv.CreateView):
415 456
    model = models.Holiday
416 457
    form_class = forms.HolidayForm
calebasse/static/css/style.css
1483 1483
    padding: 0 .5em;
1484 1484
}
1485 1485

  
1486
#holidays.group li.date, #holidays.group li.hour {
1486
#holidays.group li.start_date, #holidays.group li.end_date,
1487
#holidays.group li.start_time, #holidays.group li.end_time {
1487 1488
    width: 9%;
1488 1489
}
1489 1490

  
calebasse/static/js/calebasse.absences.js
29 29
                           })
30 30
};
31 31

  
32
function add_holiday(worker) {
32
function add_holiday(worker, url) {
33
    var url = url || '/cmpp/personnes/gestion/';
33 34
    params = {'title': 'Ajouter une absence', 'button_close': 'Fermer',
34 35
              'button_confirm': 'Ajouter', 'width': '550px'};
35 36

  
......
59 60
        }
60 61

  
61 62
    };
62
    action('/cmpp/personnes/gestion/', worker, null, 'ajouter', null, null, null, params, on_success);
63
    action(url, worker, null, 'ajouter', null, null, null, params, on_success);
63 64
};
64 65

  
65 66
function delete_holiday(worker, holiday, url) {
......
108 109
    action(url, worker, holiday, 'editer', selector, initial_color,  '#af7', params, on_success);
109 110
};
110 111

  
112
function add_group_holiday() {
113
    var url = '/cmpp/personnes/conges/groupe/';
114
    add_holiday(null, url);
115
}
116

  
111 117
function edit_group_holiday(holiday) {
112 118
    var url = '/cmpp/personnes/conges/groupe/';
119
    console.log(holiday);
113 120
    edit_holiday(null, holiday, url);
114 121
};
115 122

  

Also available in: Unified diff