patient.py 21.6 KB
Newer Older
Marc Duez's avatar
Marc Duez committed
1
# coding: utf8
2
import gluon.contrib.simplejson, datetime
3
import vidjil_utils
4
5
6
7
8
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

9
10
ACCESS_DENIED = "access denied"

11
12
## return patient file list
##
Marc Duez's avatar
Marc Duez committed
13
def info():
14
15
16
17
18
19
    

    patient = db.patient[request.vars["id"]]

    if request.vars["config_id"] and request.vars["config_id"] != "-1" :
        config_id = long(request.vars["config_id"])
20
        patient_name = vidjil_utils.anon(patient.id, auth.user_id)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
        config_name = db.config[request.vars["config_id"]].name

        fused = db(
            (db.fused_file.patient_id == patient)
            & (db.fused_file.config_id == config_id)
        )

        analysis = db(
            (db.analysis_file.patient_id == patient)
            & (db.analysis_file.config_id == config_id)
        )
        
        
        config = True
        fused_count = fused.count()
        fused_file = fused.select()
        fused_filename = patient_name +"_"+ config_name + ".data"
        analysis_count = analysis.count()
        analysis_file = analysis.select()
        analysis_filename = patient_name +"_"+ config_name + ".analysis"
        
    else:
        config_id = -1
        config = False
        fused_count = 0
        fused_file = ""
        fused_filename = ""
        analysis_count = 0
        analysis_file = ""
        analysis_filename = ""

    if config :
53
54
55
	query =[]
	
        query2 = db(
56
57
58
59
60
61
62
                (db.sequence_file.patient_id==db.patient.id)
                & (db.patient.id==request.vars["id"])
            ).select(
                left=db.results_file.on(
                    (db.results_file.sequence_file_id==db.sequence_file.id)
                    & (db.results_file.config_id==str(config_id) )
                ), 
63
                orderby = db.sequence_file.id|~db.results_file.run_date
64
            )
65
66
67
68
69
	previous=-1
	for row in query2 :
	    if row.sequence_file.id != previous : 
		query.append(row)
		previous=row.sequence_file.id
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

    else:

        query = db(
                (db.sequence_file.patient_id==db.patient.id)
                & (db.patient.id==request.vars["id"])
            ).select(
                left=db.results_file.on(
                    (db.results_file.sequence_file_id==db.sequence_file.id)
                    & (db.results_file.config_id==str(config_id) )
                )
            )


    
85
    log.debug('patient (%s)' % request.vars["id"])
86
    if (auth.has_permission('read', 'patient', request.vars["id"]) ):
87
88
        return dict(query=query,
                    patient=patient,
89
                    birth=vidjil_utils.anon_birth(request.vars["id"], auth.user.id),
90
91
92
93
94
95
96
97
98
99
                    config_id=config_id,
                    fused_count=fused_count,
                    fused_file=fused_file,
                    fused_filename=fused_filename,
                    analysis_count=analysis_count,
                    analysis_file = analysis_file,
                    analysis_filename = analysis_filename,
                    config=config)
    
    
100
    else :
101
        res = {"message": ACCESS_DENIED}
102
        log.error(res)
103
104
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

Marc Duez's avatar
Marc Duez committed
105

106
107
108
109
110
111
112
def custom():
    if request.vars["config_id"] and request.vars["config_id"] != "-1" :
        config_id = long(request.vars["config_id"])
        config_name = db.config[request.vars["config_id"]].name
        config = True
        
    else:
113
        request.vars["config_id"] = -1
114
        config_id = -1
115
        config_name = None
116
        config = False
117
118
119
120
121
122
        
    if "custom_list" not in request.vars :
        request.vars["custom_list"] = []
    if type(request.vars["custom_list"]) is str :
        request.vars["custom_list"] = [request.vars["custom_list"]]
        
123

124
125
    q = ((auth.accessible_query('read', db.patient)) 
                & (auth.accessible_query('read', db.config)) 
126
127
                & (db.sequence_file.patient_id==db.patient.id)
                & (db.results_file.sequence_file_id==db.sequence_file.id)
128
                & (db.results_file.data_file != '')
129
                & (db.config.id==db.results_file.config_id)
130
131
            )

132
    query = db(q).select(
133
                db.patient.id, db.results_file.id, db.results_file.config_id, db.sequence_file.sampling_date, 
134
                db.sequence_file.pcr, db.config.name, db.results_file.run_date, db.results_file.data_file, db.sequence_file.filename,
135
136
                db.sequence_file.patient_id, db.sequence_file.data_file, db.sequence_file.id, db.sequence_file.info,
                db.sequence_file.size_file,
137
138
139
                orderby = ~db.sequence_file.patient_id|db.sequence_file.id|db.results_file.run_date,
                groupby = db.sequence_file.id|db.results_file.config_id,
            )
140

141
142
143
144
145
146
147
148
149
    ##filter
    if "filter" not in request.vars :
        request.vars["filter"] = ""
        
    for row in query :
        row.checked = False
        if (str(row.results_file.id) in request.vars["custom_list"]) :
            row.checked = True
        row.string = (vidjil_utils.anon(row.sequence_file.patient_id, auth.user_id) + row.sequence_file.filename +
Marc Duez's avatar
Marc Duez committed
150
                      str(row.sequence_file.sampling_date) + str(row.sequence_file.pcr) + str(row.config.name) + str(row.results_file.run_date)).lower()
151
152
153
    query = query.find(lambda row : ( vidjil_utils.filter(row.string,request.vars["filter"]) or row.checked) )
    
    if config :
Marc Duez's avatar
Marc Duez committed
154
        query = query.find(lambda row : ( row.results_file.config_id==config_id or (str(row.results_file.id) in request.vars["custom_list"])) )
155
    
156
157
    res = {"message": "custom list (%s)" % config_name}
    log.debug(res)
158

159
160
161
162
    return dict(query=query,
                config_id=config_id,
                config=config)
    
163

164
STATS_READLINES = 1000 # approx. size in which the stats are searched
165
166

def stats():
167
168
169
    import time
    start = time.time()

170
171
172
    d = custom()

    stats_regex = [
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        # found 771265 40-windows in 2620561 segments (85.4%) inside 3068713 sequences
        'in (?P<seg>\d+) segments \((?P<seg_ratio>.*?)\) inside (?P<reads>\d+) sequences',

        # locus
        'log.* TRG.*?->\s*?(?P<TRG_reads>\d+)\s+(?P<TRG_av_len>[0-9.]+)\s+(?P<TRG_clones>\d+)\s+(?P<TRG_av_reads>[0-9.]+)\s*.n',
        'log.* IGH.*?->\s*?(?P<IGH_reads>\d+)\s+(?P<IGH_av_len>[0-9.]+)\s+(?P<IGH_clones>\d+)\s+(?P<IGH_av_reads>[0-9.]+)\s*.n',

        # segmentation causes
        'log.* SEG_[+].*?-> (?P<SEG_plus>.*?).n',
        'log.* SEG_[-].*?-> (?P<SEG_minus>.*?).n',

        # main clone
        '"name".*"(?P<main_clone>.*)"',
        '"reads" :  [[] (?P<main_clone_reads>\d+) ',

188
189
190
191
192
193
194
195
196
197
198
199
200
        '"producer" :  [[] "(?P<version>.*)"',
    ]

    keys = []
    regex = []
    for sr in stats_regex:
        r = re.compile(sr)
        regex += [r]
        keys += r.groupindex.keys()

    d['stats'] = keys

    for row in d['query']:
201
202
        results_f = row.results_file.data_file
        row_result = vidjil_utils.search_first_regex_in_file(regex, defs.DIR_RESULTS + results_f, STATS_READLINES)
203
204
205
206

        for key in keys:
            row[key] = ''

207
    log.debug("patient/stats (%.3fs)" % (time.time()-start))
208
209
    return d

210
## return patient list
Marc Duez's avatar
Marc Duez committed
211
def index():
Marc Duez's avatar
Marc Duez committed
212
213
214
    import time
    
    start = time.time()
215
    if not auth.user : 
216
217
218
219
        res = {"redirect" : URL('default', 'user', args='login', scheme=True, host=True,
                            vars=dict(_next=URL('patient', 'index', scheme=True, host=True)))
            }
        
220
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
Marc Duez's avatar
Marc Duez committed
221
    
222
223
    isAdmin = auth.has_membership("admin")
    
224
    ##retrieve patient list 
225
    query = db(
Marc Duez's avatar
Marc Duez committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
        auth.accessible_query('read', db.patient)
    ).select(
        db.patient.ALL,
        orderby = ~db.patient.id
    )
    result = {}
    
    for i, row in enumerate(query) :
        try:
            ln = unicode(row.last_name, 'utf-8')
        except UnicodeDecodeError:
            ln = row.last_name
        result[row.id] = {
            "id" :int(row.id),
            "last_name" : row.last_name,
            "first_name" : row.first_name,
            "has_permission" : False,
            "name" : ln[:3],
            "birth" : row.birth,
            "info" : row.info,
            "creator" : row.creator,
            "confs" : "",
            "conf_list" : [],
            "conf_id_list" : [-1],
            "most_used_conf" : "",
            "groups" : "",
            "group_list" : [],
            "file_count" : 0,
            "size" : 0
        }
        
    keys = result.keys() 
    
    (auth.has_permission('admin', 'patient', row['id']) )
    query = db(
        (db.auth_permission.name == "admin") & 
        (db.auth_permission.table_name == "patient") &
        (db.patient.id == db.auth_permission.record_id ) &
        (auth.user_group() == db.auth_permission.group_id )
265
    ).select(
Marc Duez's avatar
Marc Duez committed
266
        db.patient.ALL, db.auth_permission.ALL
267
    )
268

Marc Duez's avatar
Marc Duez committed
269
270
271
272
    for i, row in enumerate(query) :
        if row.patient.id in keys :
            result[row.patient.id]['has_permission'] = True
            
Vidjil Team's avatar
Vidjil Team committed
273
    query1 = db(
Marc Duez's avatar
Marc Duez committed
274
275
        db.patient.creator == db.auth_user.id
    ).select(
Vidjil Team's avatar
Vidjil Team committed
276
        db.patient.id, db.auth_user.last_name
Marc Duez's avatar
Marc Duez committed
277
    )
Vidjil Team's avatar
Vidjil Team committed
278
    for i, row in enumerate(query1) :
Marc Duez's avatar
Marc Duez committed
279
280
        if row.patient.id in keys :
            result[row.patient.id]['creator'] = row.auth_user.last_name
Vidjil Team's avatar
Vidjil Team committed
281
282
       
    query2 = db(
Marc Duez's avatar
Marc Duez committed
283
284
        db.patient.id == db.sequence_file.patient_id
    ).select(
Vidjil Team's avatar
Vidjil Team committed
285
        db.patient.id, db.sequence_file.size_file
Marc Duez's avatar
Marc Duez committed
286
    )
Vidjil Team's avatar
Vidjil Team committed
287
    for i, row in enumerate(query2) :
Marc Duez's avatar
Marc Duez committed
288
289
290
291
        if row.patient.id in keys :
            result[row.patient.id]['file_count'] += 1
            result[row.patient.id]['size'] += row.sequence_file.size_file
    
Vidjil Team's avatar
Vidjil Team committed
292
    query3 = db(
Marc Duez's avatar
Marc Duez committed
293
294
295
        (db.patient.id == db.fused_file.patient_id) &
        (db.fused_file.config_id == db.config.id)
    ).select(
Vidjil Team's avatar
Vidjil Team committed
296
        db.patient.id, db.config.name, db.config.id
Marc Duez's avatar
Marc Duez committed
297
    )
Vidjil Team's avatar
Vidjil Team committed
298
    for i, row in enumerate(query3) :
Marc Duez's avatar
Marc Duez committed
299
300
301
        if row.patient.id in keys :
            result[row.patient.id]['conf_list'].append(row.config.name)
            result[row.patient.id]['conf_id_list'].append(row.config.id)
Vidjil Team's avatar
Vidjil Team committed
302
303
    
    query4 = db(
Marc Duez's avatar
Marc Duez committed
304
305
306
307
308
        ((db.patient.id == db.auth_permission.record_id) | (db.auth_permission.record_id == 0)) &
        (db.auth_permission.table_name == 'patient') &
        (db.auth_permission.name == 'read') &
        (db.auth_group.id == db.auth_permission.group_id)
    ).select(
Vidjil Team's avatar
Vidjil Team committed
309
        db.patient.id, db.auth_group.role
Marc Duez's avatar
Marc Duez committed
310
    )
Vidjil Team's avatar
Vidjil Team committed
311
    for i, row in enumerate(query4) :
Marc Duez's avatar
Marc Duez committed
312
        if row.patient.id in keys :
313
            result[row.patient.id]['group_list'].append(row.auth_group.role.replace('user_','u'))
314
            
Vidjil Team's avatar
Vidjil Team committed
315
    query5 = db(
Marc Duez's avatar
Marc Duez committed
316
317
318
319
320
        (db.auth_permission.name == "anon") & 
        (db.auth_permission.table_name == "patient") &
        (db.patient.id == db.auth_permission.record_id ) &
        (auth.user_group() == db.auth_permission.group_id )
    ).select(
Vidjil Team's avatar
Vidjil Team committed
321
        db.patient.id, db.patient.last_name, db.patient.first_name
Marc Duez's avatar
Marc Duez committed
322
    )
Vidjil Team's avatar
Vidjil Team committed
323
    for i, row in enumerate(query5) :
Marc Duez's avatar
Marc Duez committed
324
        if row.id in keys :
Marc Duez's avatar
Marc Duez committed
325
            result[row.id]['name'] = row.last_name + " " + row.first_name
326

327
        
Marc Duez's avatar
Marc Duez committed
328
329
    for key, row in result.iteritems():
        row['most_used_conf'] = max(set(row['conf_id_list']), key=row['conf_id_list'].count)
Vidjil Team's avatar
Vidjil Team committed
330
        row['confs'] = ", ".join(list(set(row['conf_list']))) 
331
        row['groups'] = ", ".join(filter(lambda g: g != 'admin', set(row['group_list'])))
Marc Duez's avatar
Marc Duez committed
332
333
334
        
    result = result.values()

335
    ##sort result
336
337
338
    reverse = False
    if request.vars["reverse"] == "true" :
        reverse = True
339
    if request.vars["sort"] == "configs" :
Marc Duez's avatar
Marc Duez committed
340
        result = sorted(result, key = lambda row : row['confs'], reverse=reverse)
341
    elif request.vars["sort"] == "groups" :
Marc Duez's avatar
Marc Duez committed
342
        result = sorted(result, key = lambda row : row['groups'], reverse=reverse)
343
    elif request.vars["sort"] == "files" :
Marc Duez's avatar
Marc Duez committed
344
        result = sorted(result, key = lambda row : row['file_count'], reverse=reverse)
345
    elif "sort" in request.vars:
Marc Duez's avatar
Marc Duez committed
346
        result = sorted(result, key = lambda row : row[request.vars["sort"]], reverse=reverse)
347
348
349
    else:
        result = sorted(result, key = lambda row : row['id'], reverse=not reverse)

350
    ##filter
351
    if "filter" not in request.vars :
352
        request.vars["filter"] = ""
353

Marc Duez's avatar
Marc Duez committed
354
355
356
    for row in result :
        row['string'] = (row['last_name']+row['first_name']+row['confs']+row['groups']+str(row['birth'])).lower()+str(row['info'])
    result = filter(lambda row : vidjil_utils.filter(row['string'],request.vars["filter"]), result )
357
    log.debug("patient list (%.3fs)" % (time.time()-start))
358
    return dict(query = result,
359
                isAdmin = isAdmin,
360
                reverse = reverse)
Marc Duez's avatar
Marc Duez committed
361

362

363

364
## return form to create new patient
Marc Duez's avatar
Marc Duez committed
365
def add(): 
366
367
368
    if (auth.has_permission('create', 'patient') ):
        return dict(message=T('add patient'))
    else :
369
370
        res = {"message": ACCESS_DENIED}
        log.error(res)
371
372
373
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


Marc Duez's avatar
Marc Duez committed
374

375
376
377
378
## 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
Marc Duez's avatar
Marc Duez committed
379
def add_form(): 
380
    if (auth.has_permission('create', 'patient') ):
Marc Duez's avatar
Marc Duez committed
381
382
383
384
385
386
        
        error = ""
        if request.vars["first_name"] == "" :
            error += "first name needed, "
        if request.vars["last_name"] == "" :
            error += "last name needed, "
Marc Duez's avatar
Marc Duez committed
387
388
389
390
        try:
            datetime.datetime.strptime(""+request.vars['birth'], '%Y-%m-%d')
        except ValueError:
            error += "date missing or wrong format"
391

Marc Duez's avatar
Marc Duez committed
392
393
394
395
        if error=="" :
            id = db.patient.insert(first_name=request.vars["first_name"],
                                   last_name=request.vars["last_name"],
                                   birth=request.vars["birth"],
396
                                   info=request.vars["info"],
397
398
                                   id_label=request.vars["id_label"],
                                   creator=auth.user_id)
399
400


401
402
            user_group = auth.user_group(auth.user.id)
            admin_group = db(db.auth_group.role=='admin').select().first().id
403
            
404
            #patient creator automaticaly has all rights 
405
            auth.add_permission(user_group, 'admin', db.patient, id)
406
            auth.add_permission(user_group, 'read', db.patient, id)
407
            auth.add_permission(user_group, 'anon', db.patient, id)
408
            
409
410
            patient_name = request.vars["first_name"] + ' ' + request.vars["last_name"]

411
412
            res = {"redirect": "patient/info",
                   "args" : { "id" : id },
413
                   "message": patient_name + ": patient added"}
414
            log.info(res)
Marc Duez's avatar
Marc Duez committed
415
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
416

Marc Duez's avatar
Marc Duez committed
417
        else :
418
419
            res = {"success" : "false",
                   "message" : error}
420
            log.error(res)
Marc Duez's avatar
Marc Duez committed
421
422
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
        
423
    else :
424
425
        res = {"message": ACCESS_DENIED}
        log.error(res)
426
427
428
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


429

430
## return edit form 
431
def edit(): 
432
433
434
    if (auth.has_permission('admin', 'patient', request.vars["id"]) ):
        return dict(message=T('edit patient'))
    else :
435
436
        res = {"message": ACCESS_DENIED}
        log.error(res)
437
438
439
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


440

441
442
443
444
## check edit form
## need ["first_name", "last_name", "birth_date", "info"]
## redirect to patient list if success
## return a flash error message if fail
445
def edit_form(): 
446
    if (auth.has_permission('admin', 'patient', request.vars["id"]) ):
447
448
449
450
451
        error = ""
        if request.vars["first_name"] == "" :
            error += "first name needed, "
        if request.vars["last_name"] == "" :
            error += "last name needed, "
Marc Duez's avatar
Marc Duez committed
452
453
454
455
        try:
            datetime.datetime.strptime(""+request.vars['birth'], '%Y-%m-%d')
        except ValueError:
            error += "date missing or wrong format"
456
457
        if request.vars["id"] == "" :
            error += "patient id needed, "
458

459
460
461
462
        if error=="" :
            db.patient[request.vars["id"]] = dict(first_name=request.vars["first_name"],
                                                   last_name=request.vars["last_name"],
                                                   birth=request.vars["birth"],
463
464
                                                   info=request.vars["info"],
                                                   id_label=request.vars["id_label"]
465
                                                   )
466

467
            res = {"redirect": "back",
468
                   "message": "%s %s (%s): patient edited" % (request.vars["first_name"], request.vars["last_name"], request.vars["id"])}
469
            log.info(res)
470
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
471

472
        else :
473
            res = {"success" : "false", "message" : error}
474
            log.error(res)
475
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
476
    else :
477
478
        res = {"message": ACCESS_DENIED}
        log.error(res)
479
480
481
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


482
def download():
Marc Duez's avatar
Marc Duez committed
483
    return response.download(request, db)
484

485
486

#
487
def confirm():
488
    if (auth.has_permission('admin', 'patient', request.vars["id"]) ):
489
        log.debug('request patient deletion')
490
491
        return dict(message=T('confirm patient deletion'))
    else :
492
493
        res = {"message": ACCESS_DENIED}
        log.error(res)
494
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
495

496
497

#
498
def delete():
499
500
501
502
503
    if (auth.has_permission('admin', 'patient', request.vars["id"]) ):
        import shutil, os.path
        #delete data file 
        query = db( (db.sequence_file.patient_id==request.vars["id"])).select() 
        for row in query :
504
            db(db.results_file.sequence_file_id == row.id).delete()
505
506
507
508
509
510
511
512
513

        #delete sequence file
        db(db.sequence_file.patient_id == request.vars["id"]).delete()

        #delete patient
        db(db.patient.id == request.vars["id"]).delete()

        res = {"redirect": "patient/index",
               "success": "true",
Marc Duez's avatar
Marc Duez committed
514
               "message": "patient ("+str(request.vars["id"])+") deleted"}
515
        log.info(res)
516
517
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
    else :
518
        res = {"message": ACCESS_DENIED}
519
        log.error(res)
520
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
521

522
    
523
#
524
def permission(): 
525
    if (auth.has_permission('admin', 'patient', request.vars["id"]) ):
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
        
        query = db( db.auth_group.role != 'admin' ).select()
        
        for row in query :
            row.owner = row.role
            if row.owner[:5] == "user_" :
                id = int(row.owner[5:])
                row.owner = db.auth_user[id].first_name + " " + db.auth_user[id].last_name 

            row.admin = False
            if db(   (db.auth_permission.name == "admin")
                  & (db.auth_permission.record_id == request.vars["id"])
                  & (db.auth_permission.group_id == row.id)
                  & (db.auth_permission.table_name == db.patient)
              ).count() > 0 :
                row.admin = True
                
            row.anon = False
            if db(   (db.auth_permission.name == "anon")
                  & (db.auth_permission.record_id == request.vars["id"])
                  & (db.auth_permission.group_id == row.id)
                  & (db.auth_permission.table_name == db.patient)
              ).count() > 0 :
                row.anon = True
                
            row.read = False
            if db(   (db.auth_permission.name == "read")
                  & (db.auth_permission.record_id == request.vars["id"])
                  & (db.auth_permission.group_id == row.id)
                  & (db.auth_permission.table_name == db.patient)
              ).count() > 0 :
                row.read = True
        
        return dict(query=query)
560
    else :
561
562
        res = {"message": ACCESS_DENIED}
        log.error(res)
563
564
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

565

566
#
567
def change_permission():
Marc Duez's avatar
Marc Duez committed
568
    if (auth.has_permission('admin', 'patient', request.vars["patient_id"]) ):
569
570
571
572
573
        error = ""
        if request.vars["group_id"] == "" :
            error += "missing group_id, "
        if request.vars["patient_id"] == "" :
            error += "missing patient_id, "
574
575
        if request.vars["permission"] == "" :
            error += "missing permission, "
576
577

        if error=="":
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
            if db(   (db.auth_permission.name == request.vars["permission"])
                      & (db.auth_permission.record_id == request.vars["patient_id"])
                      & (db.auth_permission.group_id == request.vars["group_id"])
                      & (db.auth_permission.table_name == db.patient)
                  ).count() > 0 :
                auth.del_permission(request.vars["group_id"], request.vars["permission"], db.patient, request.vars["patient_id"])
                res = {"message" : "access '%s' deleted to '%s'" % (request.vars["permission"], db.auth_group[request.vars["group_id"]].role)}
            else :
                auth.add_permission(request.vars["group_id"], request.vars["permission"], db.patient, request.vars["patient_id"])
                res = {"message" : "access '%s' granted to '%s'" % (request.vars["permission"], db.auth_group[request.vars["group_id"]].role)}
            
            log.info(res)
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
        else :
            res = {"message": "incomplete request : "+error }
            log.error(res)
            return gluon.contrib.simplejson.dumps(res, separators=(',',':'))
595
    else :
596
597
        res = {"message": ACCESS_DENIED}
        log.error(res)
598
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))