Attention une mise à jour du serveur va être effectuée le lundi 17 mai entre 13h et 13h30. Cette mise à jour va générer une interruption du service de quelques minutes.

patient.py 6.34 KB
Newer Older
Marc Duez's avatar
Marc Duez committed
1
# coding: utf8
2
import gluon.contrib.simplejson, datetime
3
import vidjil_utils
4
import time
5
import datetime
6

7 8 9 10 11
if request.env.http_origin:
    response.headers['Access-Control-Allow-Origin'] = request.env.http_origin  
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Max-Age'] = 86400

12
ACCESS_DENIED = "access denied"
13

14
## return form to create new patient
15 16 17 18 19 20 21 22 23 24
def form():
    # edit patient
    if("id" in request.vars and auth.can_modify_patient(request.vars["id"])):
        groups = [get_set_group(defs.SET_TYPE_PATIENT, request.vars["id"])]
        message = 'edit patient'
        max_group = None

    #new patient
    elif (auth.can_create_patient()):
        creation_group_tuple = get_default_creation_group(auth)
25 26
        groups = creation_group_tuple[0]
        max_group = creation_group_tuple[1]
27
        message = 'add patient'
28
    else :
29 30
        res = {"message": ACCESS_DENIED}
        log.error(res)
31
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
32 33 34 35
    return dict(message=T(message),
                groups=groups,
                master_group=max_group,
                patient=db.patient[request.vars["id"]])
36 37


Marc Duez's avatar
Marc Duez committed
38

39 40 41 42
## create a patient if the html form is complete
## need ["first_name", "last_name", "birth_date", "info"]
## redirect to patient list if success
## return a flash error message if fail
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
def submit():
    error = ""
    if request.vars["first_name"] == "" :
        error += "first name needed, "
    if request.vars["last_name"] == "" :
        error += "last name needed, "
    if request.vars["birth"] != "" :
        try:
            datetime.datetime.strptime(""+request.vars['birth'], '%Y-%m-%d')
        except ValueError:
            error += "date (wrong format)"

    if error != "":
        res = {"success" : "false",
               "message" : error}
58
        log.error(res)
59 60
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

61 62 63 64 65 66
    p = dict(first_name=request.vars["first_name"],
             last_name=request.vars["last_name"],
             birth=request.vars["birth"],
             info=request.vars["info"],
             id_label=request.vars["id_label"]
            )
67

68 69
    register = False
    reset = False
70

71 72 73 74 75 76
    # edit patient
    log.debug("id present: " + "id" in request.vars)
    log.debug("id: " + request.vars["id"] + request.vars['id'] == "" + request.vars['id'] is None)
    if (request.vars['id'] != "" and auth.can_modify_patient(request.vars["id"])):
        patient = db.patient[request.vars["id"]]
        db.patient[request.vars["id"]] = p
77

78 79 80 81
        if (patient.info != request.vars["info"]):
            group_id = get_set_group(defs.SET_TYPE_PATIENT, request.vars["id"])
            register = True
            reset = True
82

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        res = {"redirect": "back",
               "message": "%s %s (%s): patient edited" % (request.vars["first_name"], request.vars["last_name"], request.vars["id"])}
        id = request.vars["id"]

    # add patient
    elif (auth.can_create_patient()):

        id_sample_set = db.sample_set.insert(sample_type=defs.SET_TYPE_PATIENT)

        p['creator'] = auth.user_id
        p['sample_set_id'] = id_sample_set
        id = db.patient.insert(**p)

        user_group = int(request.vars["patient_group"])
        admin_group = db(db.auth_group.role=='admin').select().first().id

        group_id = user_group
        register = True

        #patient creator automaticaly has all rights
        auth.add_permission(user_group, PermissionEnum.access.value, db.patient, id)

        patient_name = request.vars["first_name"] + ' ' + request.vars["last_name"]

        res = {"redirect": "sample_set/index",
               "args" : { "id" : id_sample_set },
               "message": "(%s) patient %s added" % (id_sample_set, patient_name) }

        if (id % 100) == 0:
            mail.send(to=defs.ADMIN_EMAILS,
            subject="[Vidjil] %d" % id,
            message="The %dth patient has just been created." % id)
115

116
    else :
117 118
        res = {"message": ACCESS_DENIED}
        log.error(res)
119

120 121 122 123
    if register:
        register_tags(db, defs.SET_TYPE_PATIENT, request.vars["id"], request.vars["info"], group_id, reset=reset)
    log.info(res, extra={'user_id': auth.user.id, 'record_id': id, 'table_name': 'patient'})
    return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
124

125
def download():
Marc Duez's avatar
Marc Duez committed
126
    return response.download(request, db)
127

128 129

#
130
def confirm():
131
    if (auth.can_modify_patient(request.vars["id"]) ):
132
        log.debug('request patient deletion')
133 134
        return dict(message=T('confirm patient deletion'))
    else :
135 136
        res = {"message": ACCESS_DENIED}
        log.error(res)
137
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
138

139 140

#
141
def delete():
142
    if (auth.can_modify_patient(request.vars["id"]) ):
143 144 145 146 147 148
        patient = db.patient[request.vars["id"]]
        if patient is None:
            res = {"message": 'An error occured. This patient may have already been deleted'}
            log.error(res)
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

149
        sample_set_id = patient.sample_set_id
150

151
        #delete data file 
152 153 154
        query = db( (db.sample_set_membership.sample_set_id == sample_set_id)
                    & (db.sequence_file.id == db.sample_set_membership.sequence_file_id)
                ).select(db.sequence_file.id) 
155
        for row in query :
156
            db(db.results_file.sequence_file_id == row.id).delete()
157
        
158
        #delete sequence file
159 160 161 162 163
        query = db((db.sequence_file.id == db.sample_set_membership.sequence_file_id)
            & (db.sample_set_membership.sample_set_id == sample_set_id)
            ).select(db.sequence_file.id)
        for row in query :
            db(db.sequence_file.id == row.id).delete()
164 165 166

        #delete patient
        db(db.patient.id == request.vars["id"]).delete()
167 168 169
        
        #delete patient sample_set
        db(db.sample_set.id == sample_set_id).delete()
170 171 172

        res = {"redirect": "patient/index",
               "success": "true",
Marc Duez's avatar
Marc Duez committed
173
               "message": "patient ("+str(request.vars["id"])+") deleted"}
174
        log.info(res, extra={'user_id': auth.user.id, 'record_id': request.vars["id"], 'table_name': 'patient'})
175 176
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
    else :
177
        res = {"message": ACCESS_DENIED}
178
        log.error(res)
179
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
180

181
    
182

183