Project

General

Profile

Download (4.33 KB) Statistics
| Branch: | Tag: | Revision:

calebasse / calebasse / statistics / statistics.py @ b16a4439

1
# -*- coding: utf-8 -*-
2
import os
3
import tempfile
4
import csv
5

    
6
from collections import OrderedDict
7
from datetime import datetime
8

    
9
from django.db import models
10

    
11
from calebasse.dossiers.models import PatientRecord
12
from calebasse.personnes.models import Worker
13
from calebasse.actes.models import Act
14

    
15

    
16
STATISTICS = {
17
    'patients_per_worker_for_period_per_service' :
18
        {
19
        'display_name': 'Liste des enfants suivis par intervenant sur une '
20
            'période pour un service',
21
        'category': 'Suivi'
22
    },
23
}
24

    
25

    
26
def patients_per_worker_for_period_per_service(statistic):
27
    if not (statistic.in_start_date and statistic.in_end_date
28
            and statistic.in_service):
29
        return None
30
    data_tables = []
31
    data = []
32
    data.append(['Intervenants', 'Nombre', 'Patients'])
33
    values = []
34
    # Get all acts in the period with a patient in the service
35
    # Make a dic with intervene for keys
36
    acts = None
37
    if statistic.in_patients:
38
        acts = Act.objects.filter(date__gte=statistic.in_start_date,
39
            date__lte=statistic.in_end_date,
40
            patient__service=statistic.in_service,
41
            patient__in=statistic.in_patients)
42
    else:
43
        acts = Act.objects.filter(date__gte=statistic.in_start_date,
44
            date__lte=statistic.in_end_date,
45
            patient__service=statistic.in_service)
46
    analyse = dict()
47
    for act in acts:
48
        for intervene in act.doctors.all():
49
            if statistic.in_participants:
50
                if intervene in statistic.in_participants:
51
                    analyse.setdefault(intervene, []).append(str(act.patient))
52
            else:
53
                analyse.setdefault(intervene, []).append(str(act.patient))
54
    o_analyse = OrderedDict(sorted(analyse.items(), key=lambda t: t[0]))
55
    for intervene, patients in o_analyse.iteritems():
56
        lst = list(set(patients))
57
        values.append([str(intervene), len(lst), lst])
58
    data.append(values)
59
    data_tables.append(data)
60
    return data_tables
61

    
62
class Statistic(models.Model):
63
    patients = models.ManyToManyField('dossiers.PatientRecord',
64
            null=True, blank=True, default=None)
65
    participants = models.ManyToManyField('personnes.People',
66
            null=True, blank=True, default=None)
67

    
68
    def __init__(self, name=None, inputs=dict()):
69
        self.name = name
70
        params = STATISTICS.get(name, {})
71
        self.display_name = params['display_name']
72
        self.category = params['category']
73
        self.inputs = inputs
74
        self.in_participants = list()
75
        participants = inputs.get('participants')
76
        if participants:
77
            p_str_ids = [p for p in participants.split('|') if p]
78
            for str_id in p_str_ids:
79
                try:
80
                    self.in_participants.append(Worker.objects.get(pk=int(str_id)))
81
                except:
82
                    pass
83
        self.in_patients = list()
84
        patients = inputs.get('patients')
85
        if patients:
86
            p_str_ids = [p for p in patients.split('|') if p]
87
            for str_id in p_str_ids:
88
                try:
89
                    self.in_patients.append(PatientRecord.objects.get(pk=int(str_id)))
90
                except:
91
                    pass
92
        self.in_service = inputs.get('service')
93
        self.in_start_date = None
94
        try:
95
            self.in_start_date = datetime.strptime(inputs.get('start_date'),
96
                "%d/%m/%Y")
97
        except:
98
            pass
99
        self.in_end_date = None
100
        try:
101
            self.in_end_date = datetime.strptime(inputs.get('end_date'),
102
                "%d/%m/%Y")
103
        except:
104
            pass
105

    
106
    def get_data(self):
107
        func = globals()[self.name]
108
        self.data = func(self)
109
        return self.data
110

    
111
    def render_to_csv(self):
112
        with tempfile.NamedTemporaryFile(delete=False) as temp_out_csv:
113
            try:
114
                writer = csv.writer(temp_out_csv, delimiter=';', quotechar='|',
115
                    quoting=csv.QUOTE_MINIMAL)
116
                for data in self.data:
117
                    writer.writerow(data[0])
118
                    for d in data[1]:
119
                        writer.writerow(d)
120
                return temp_out_csv.name
121
            except:
122
                try:
123
                    os.unlink(temp_out_pdf.name)
124
                except:
125
                    pass
126

    
127
    def get_file(self):
128
        self.get_data()
129
        return self.render_to_csv()
(5-5/8)