1
|
# -*- coding: utf-8 -*-
|
2
|
#!/usr/bin/env python
|
3
|
|
4
|
import os
|
5
|
import sys
|
6
|
import csv
|
7
|
import pdb
|
8
|
|
9
|
from datetime import datetime, time
|
10
|
from dateutil.relativedelta import relativedelta
|
11
|
|
12
|
import calebasse.settings
|
13
|
import django.core.management
|
14
|
|
15
|
django.core.management.setup_environ(calebasse.settings)
|
16
|
|
17
|
from django.contrib.auth.models import User
|
18
|
from django.db import transaction
|
19
|
|
20
|
from calebasse.agenda.models import Event, EventType
|
21
|
from calebasse.dossiers.models import PatientRecord, Status, FileState, PatientAddress, PatientContact, \
|
22
|
CmppHealthCareDiagnostic, CmppHealthCareTreatment
|
23
|
|
24
|
from calebasse.ressources.models import Service
|
25
|
from calebasse.personnes.models import Worker, Holiday, ExternalWorker, ExternalTherapist
|
26
|
from calebasse.ressources.models import (WorkerType, ParentalAuthorityType, ParentalCustodyType,
|
27
|
FamilySituationType, TransportType, TransportCompany, Provenance, AnalyseMotive, FamilyMotive,
|
28
|
CodeCFTMEA, SocialisationDuration, School, SchoolLevel, OutMotive, OutTo, AdviceGiver,
|
29
|
MaritalStatusType, Job, PatientRelatedLink, HealthCenter)
|
30
|
from calebasse.actes.models import Act
|
31
|
|
32
|
# Configuration
|
33
|
db_path = "./scripts/20130104-213225"
|
34
|
|
35
|
#dbs = ["F_ST_ETIENNE_SESSAD_TED", "F_ST_ETIENNE_CMPP", "F_ST_ETIENNE_CAMSP", "F_ST_ETIENNE_SESSAD"]
|
36
|
dbs = ["F_ST_ETIENNE_CMPP"]
|
37
|
|
38
|
|
39
|
map_cs = {}
|
40
|
map_cs['CAMSP'] = {
|
41
|
'1': 'ACT_DOUBLE',
|
42
|
'2': 'ABS_NON_EXC',
|
43
|
'3': 'ABS_EXC',
|
44
|
'4': 'ABS_INTER',
|
45
|
'5': 'ACT_LOST',
|
46
|
'6': 'ANNUL_NOUS',
|
47
|
'7': 'ANNUL_FAMILLE',
|
48
|
'8': 'ENF_HOSP',
|
49
|
'9': 'ACT_LOST',
|
50
|
'10': 'ACT_LOST',
|
51
|
'11': 'ACT_LOST',
|
52
|
'12': 'REPORTE'
|
53
|
}
|
54
|
|
55
|
map_cs['CMPP'] = {
|
56
|
'1': 'ACT_DOUBLE',
|
57
|
'2': 'ABS_NON_EXC',
|
58
|
'3': 'ABS_EXC',
|
59
|
'4': 'ABS_INTER',
|
60
|
'5': 'ACT_LOST',
|
61
|
'6': 'ANNUL_NOUS',
|
62
|
'7': 'ANNUL_FAMILLE',
|
63
|
'8': 'ABS_ESS_PPS',
|
64
|
'9': 'ACT_LOST',
|
65
|
'10': 'ACT_LOST',
|
66
|
'11': 'ACT_LOST',
|
67
|
'12': 'REPORTE'
|
68
|
}
|
69
|
|
70
|
map_cs['SESSAD DYS'] = {
|
71
|
'1': 'ACT_DOUBLE',
|
72
|
'2': 'ABS_NON_EXC',
|
73
|
'3': 'ABS_EXC',
|
74
|
'4': 'ABS_INTER',
|
75
|
'5': 'ACT_LOST',
|
76
|
'6': 'ANNUL_NOUS',
|
77
|
'7': 'ANNUL_FAMILLE',
|
78
|
'8': 'ABS_ESS_PPS',
|
79
|
'9': 'ACT_LOST',
|
80
|
'10': 'ACT_LOST',
|
81
|
'11': 'REPORTE'
|
82
|
}
|
83
|
|
84
|
|
85
|
map_cs['SESSAD TED'] = {
|
86
|
'1': 'ACT_DOUBLE',
|
87
|
'2': 'ABS_NON_EXC',
|
88
|
'3': 'ABS_EXC',
|
89
|
'4': 'ACT_LOST',
|
90
|
'5': 'ABS_INTER',
|
91
|
'6': 'ANNUL_NOUS',
|
92
|
'7': 'ANNUL_FAMILLE',
|
93
|
'8': 'REPORTE'
|
94
|
}
|
95
|
|
96
|
def _exist(str):
|
97
|
if str and str != "" and str != '0':
|
98
|
return True
|
99
|
return False
|
100
|
|
101
|
def treat_name(name):
|
102
|
res = ''
|
103
|
for p in name.split():
|
104
|
res += p[0].upper()+p[1:].lower()
|
105
|
res += ' '
|
106
|
return res[:-1]
|
107
|
|
108
|
def _to_date(str_date):
|
109
|
if not str_date:
|
110
|
return None
|
111
|
return datetime.strptime(str_date[:-13], "%Y-%m-%d")
|
112
|
|
113
|
def _to_int(str_int):
|
114
|
if not str_int:
|
115
|
return None
|
116
|
return int(str_int)
|
117
|
|
118
|
def _get_dict(cols, line):
|
119
|
""""""
|
120
|
res = {}
|
121
|
for i, data in enumerate(line):
|
122
|
res[cols[i]] = data.decode('utf-8')
|
123
|
return res
|
124
|
|
125
|
tables_data = {}
|
126
|
|
127
|
map_rm_cmpp = [1, 3, 2, 8, 6, 4]
|
128
|
|
129
|
def get_rm(service, val):
|
130
|
old_id_rm = _to_int(val)
|
131
|
if old_id_rm < 1 or 'SESSAD' in service.name:
|
132
|
return None
|
133
|
if service.name == 'CMPP':
|
134
|
old_id_rm = map_rm_cmpp[old_id_rm - 1]
|
135
|
try:
|
136
|
return MaritalStatusType.objects.get(id=old_id_rm)
|
137
|
except:
|
138
|
return None
|
139
|
|
140
|
map_job_camsp = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 25, 21, 23, 20, 17, 15, 18, 16, 26, 27, 28]
|
141
|
|
142
|
# CMPP à 25 = Rien
|
143
|
def get_job(service, val):
|
144
|
old_id_job = _to_int(val)
|
145
|
if old_id_job < 1:
|
146
|
return None
|
147
|
if service.name == 'CAMSP' and old_id_job == 26:
|
148
|
return None
|
149
|
if service.name == 'CAMSP':
|
150
|
try:
|
151
|
old_id_job = map_job_camsp[old_id_job - 1]
|
152
|
except:
|
153
|
print 'Old id job out of range: %d' % old_id_job
|
154
|
try:
|
155
|
return Job.objects.get(id=old_id_job)
|
156
|
except:
|
157
|
return None
|
158
|
|
159
|
def extract_phone(val):
|
160
|
if not val or val == '' or val == '0':
|
161
|
return None
|
162
|
s = ''.join([c for c in val if c.isdigit()])
|
163
|
return s[:11]
|
164
|
|
165
|
def get_nir(nir, key, writer, line, service):
|
166
|
if not nir:
|
167
|
return None
|
168
|
if len(nir) != 13:
|
169
|
return -1
|
170
|
if key:
|
171
|
minus = 0
|
172
|
# Corsica dept 2A et 2B
|
173
|
if nir[6] in ('A', 'a'):
|
174
|
nir = [c for c in nir]
|
175
|
nir[6] = '0'
|
176
|
nir = ''.join(nir)
|
177
|
minus = 1000000
|
178
|
elif nir[6] in ('B', 'b'):
|
179
|
nir = [c for c in nir]
|
180
|
nir[6] = '0'
|
181
|
nir = ''.join(nir)
|
182
|
minus = 2000000
|
183
|
try:
|
184
|
nir = int(nir) - minus
|
185
|
good_key = 97 - (nir % 97)
|
186
|
key = int(key)
|
187
|
if key != good_key:
|
188
|
msg = 'Clé incorrect %s pour %s' % (str(key), str(nir))
|
189
|
writer.writerow(line + [service.name, msg])
|
190
|
except:
|
191
|
pass
|
192
|
return nir
|
193
|
|
194
|
|
195
|
@transaction.commit_manually
|
196
|
def import_dossiers_phase_1():
|
197
|
""" """
|
198
|
print "====== Début à %s ======" % str(datetime.today())
|
199
|
|
200
|
# f1 = open('./scripts/dossiers_ecoles_manuel.csv', 'wb')
|
201
|
# writer1 = csv.writer(f1, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
202
|
|
203
|
# f2 = open('./scripts/dossiers_manuel.csv', 'wb')
|
204
|
# writer2 = csv.writer(f2, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
205
|
|
206
|
# f3 = open('./scripts/contacts_manuel.csv', 'wb')
|
207
|
# writer3 = csv.writer(f3, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
208
|
|
209
|
f4 = open('./scripts/pc_manuel_phase2.csv', 'wb')
|
210
|
writer4 = csv.writer(f4, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
|
211
|
|
212
|
status_accueil = Status.objects.filter(type="ACCUEIL")[0]
|
213
|
status_diagnostic = Status.objects.filter(type="DIAGNOSTIC")[0]
|
214
|
status_traitement = Status.objects.filter(type="TRAITEMENT")[0]
|
215
|
status_clos = Status.objects.filter(type="CLOS")[0]
|
216
|
status_bilan = Status.objects.filter(type="BILAN")[0]
|
217
|
status_suivi = Status.objects.filter(type="SUIVI")[0]
|
218
|
status_surveillance = Status.objects.filter(type="SURVEILLANCE")[0]
|
219
|
creator = User.objects.get(id=1)
|
220
|
|
221
|
for db in dbs:
|
222
|
if "F_ST_ETIENNE_CMPP" == db:
|
223
|
service = Service.objects.get(name="CMPP")
|
224
|
elif "F_ST_ETIENNE_CAMSP" == db:
|
225
|
service = Service.objects.get(name="CAMSP")
|
226
|
elif "F_ST_ETIENNE_SESSAD_TED" == db:
|
227
|
service = Service.objects.get(name="SESSAD TED")
|
228
|
elif "F_ST_ETIENNE_SESSAD" == db:
|
229
|
service = Service.objects.get(name="SESSAD DYS")
|
230
|
|
231
|
print "====== %s ======" % service.name
|
232
|
print datetime.today()
|
233
|
|
234
|
pcs_d = {}
|
235
|
|
236
|
print "--> Chargement des actes..."
|
237
|
csvfile = open(os.path.join(db_path, db, 'actes.csv'), 'rb')
|
238
|
csvlines = csv.reader(csvfile, delimiter=';', quotechar='|')
|
239
|
pc_cols = csvlines.next()
|
240
|
tables_data['actes'] = {}
|
241
|
tables_data['actes']['nf'] = []
|
242
|
for line in csvlines:
|
243
|
data = _get_dict(pc_cols, line)
|
244
|
if _exist(line[6]):
|
245
|
if line[6] in tables_data['actes'].keys():
|
246
|
tables_data['actes'][line[6]].append(data)
|
247
|
else:
|
248
|
tables_data['actes'][line[6]] = [data]
|
249
|
else:
|
250
|
tables_data['actes']['nf'].append(data)
|
251
|
csvfile.close()
|
252
|
print "<-- Terminé : dictionnaire avec clé facture prêt"
|
253
|
|
254
|
print "--> Chargement des factures..."
|
255
|
csvfile = open(os.path.join(db_path, db, 'factures.csv'), 'rb')
|
256
|
csvlines = csv.reader(csvfile, delimiter=';', quotechar='|')
|
257
|
pc_cols = csvlines.next()
|
258
|
tables_data['factures'] = {}
|
259
|
for line in csvlines:
|
260
|
data = _get_dict(pc_cols, line)
|
261
|
if line[7] in tables_data['factures'].keys():
|
262
|
tables_data['factures'][line[7]].append(data)
|
263
|
else:
|
264
|
tables_data['factures'][line[7]] = [data]
|
265
|
csvfile.close()
|
266
|
print "<-- Terminé : dictionnaire avec clé période de pc prêt"
|
267
|
|
268
|
print "--> Chargement des prise en charge..."
|
269
|
csvfile = open(os.path.join(db_path, db, 'pc.csv'), 'rb')
|
270
|
csvlines = csv.reader(csvfile, delimiter=';', quotechar='|')
|
271
|
pc_cols = csvlines.next()
|
272
|
tables_data['pcs'] = {}
|
273
|
i = 0
|
274
|
for line in csvlines:
|
275
|
data = _get_dict(pc_cols, line)
|
276
|
pcs_d[line[0]] = data
|
277
|
if line[1] in tables_data['pcs'].keys():
|
278
|
tables_data['pcs'][line[1]].append(data)
|
279
|
else:
|
280
|
tables_data['pcs'][line[1]] = [data]
|
281
|
i += 1
|
282
|
csvfile.close()
|
283
|
print "<-- Terminé : dictionnaire avec clé patient prêt"
|
284
|
|
285
|
print "--> Chargement des periodes prise en charge..."
|
286
|
csvfile = open(os.path.join(db_path, db, 'periodes_pc.csv'), 'rb')
|
287
|
csvlines = csv.reader(csvfile, delimiter=';', quotechar='|')
|
288
|
pc_cols = csvlines.next()
|
289
|
tables_data['periodes_pcs'] = {}
|
290
|
j = 0
|
291
|
for line in csvlines:
|
292
|
data = _get_dict(pc_cols, line)
|
293
|
if line[1] in tables_data['periodes_pcs'].keys():
|
294
|
tables_data['periodes_pcs'][line[1]].append(data)
|
295
|
else:
|
296
|
tables_data['periodes_pcs'][line[1]] = [data]
|
297
|
j += 1
|
298
|
csvfile.close()
|
299
|
print "<-- Terminé : dictionnaire avec clé prise en charge prêt"
|
300
|
|
301
|
print "Nombre de patients : %d" % len(tables_data['pcs'].keys())
|
302
|
print "Nombre de pc : %d" % i
|
303
|
k = 0
|
304
|
l = 0
|
305
|
for dossier_id, pcs in tables_data['pcs'].items():
|
306
|
if len(pcs) > 1:
|
307
|
k += 1
|
308
|
else:
|
309
|
if pcs[0]['genre_pc'] != '1':
|
310
|
l += 1
|
311
|
print "Nombre de patient qui ont plus d'une pc : %d" % k
|
312
|
print "Nombre de patient qui n'ont qu'une pc mais pas diag : %d" % l
|
313
|
print "Nombre de periodes : %d" % j
|
314
|
k = 0
|
315
|
l = 0
|
316
|
m = 0
|
317
|
for pc, periodes in tables_data['periodes_pcs'].items():
|
318
|
if len(periodes) > 1:
|
319
|
k += 1
|
320
|
if pcs_d[pc]['genre_pc'] != '1':
|
321
|
l += 1
|
322
|
print "Nombre de pc qui on plus d'une periode : %d" % k
|
323
|
print "Nombre de pc qui on plus d'une periode qui sont en trait : %d" % l
|
324
|
|
325
|
i = 0
|
326
|
j = 0
|
327
|
k = 0
|
328
|
nb_actes_diag = [0 for i in range(20)]
|
329
|
nb_actes_trait = [0 for i in range(100)]
|
330
|
periode_ss_fact = []
|
331
|
facture_ss_actes = []
|
332
|
histo = {}
|
333
|
facturations = {}
|
334
|
for dossier_id, pcs in tables_data['pcs'].items():
|
335
|
histo[dossier_id] = []
|
336
|
for pc in pcs:
|
337
|
t = pc['genre_pc']
|
338
|
for periode in tables_data['periodes_pcs'][pc['id']]:
|
339
|
if not _exist(periode['date_debut']):# or _to_date(periode['date_debut']) < datetime(year=2002, month=1, day=1):
|
340
|
continue
|
341
|
my_pc = {}
|
342
|
my_pc['type'] = t
|
343
|
my_pc['periode'] = periode
|
344
|
# Il n'y qu'au cmpp où il y a des factures
|
345
|
# pour le sessad dy, on ajoute juste les periodes pour indiquer les notifications
|
346
|
# Dans les autres services, rien ?
|
347
|
factures = tables_data['factures'].get(periode['ppc_id'], None)
|
348
|
my_pc['factures'] = []
|
349
|
my_pc['actes'] = []
|
350
|
if factures:
|
351
|
for facture in factures:
|
352
|
if facture['pc_id'] != pc['id']:
|
353
|
print "%s != %s" % (facture['pc_id'], pc['id'])
|
354
|
num = facture['numero']
|
355
|
actes = tables_data['actes'].get(num, None)
|
356
|
if actes:
|
357
|
my_pc['factures'].append((facture, actes))
|
358
|
my_pc['actes'] += actes
|
359
|
fact_num = facture['numero'][0:3]
|
360
|
if not fact_num in facturations:
|
361
|
facturations[fact_num] = {}
|
362
|
facturations[fact_num]['factures'] = []
|
363
|
facturations[fact_num]['actes'] = []
|
364
|
facturations[fact_num]['factures'].append(facture)
|
365
|
facturations[fact_num]['actes'] += actes
|
366
|
else:
|
367
|
facture_ss_actes.append(facture)
|
368
|
else:
|
369
|
periode_ss_fact.append(periode)
|
370
|
if t == '1':
|
371
|
k += 1
|
372
|
if t == '1':
|
373
|
nb_actes_diag[len(my_pc['actes'])] += 1
|
374
|
else:
|
375
|
nb_actes_trait[len(my_pc['actes'])] += 1
|
376
|
histo[dossier_id].append(my_pc)
|
377
|
i += len(my_pc['factures'])
|
378
|
j += len(my_pc['actes'])
|
379
|
print "Factures : %d" % i
|
380
|
print "Actes : %d" % j
|
381
|
# Ca arrive surtout avant car ajout periode auto sans qu'il y ait de facturation derriere
|
382
|
print "Periodes sans factures, donc sans actes : %d" % len(periode_ss_fact)
|
383
|
print "Periodes sans factures diag : %d" % k
|
384
|
print "Periodes sans factures trait : %d" % (len(periode_ss_fact) - k)
|
385
|
# Ca arrive aussi
|
386
|
print "Factures sans actes, aïe : %d" % len(facture_ss_actes)
|
387
|
|
388
|
print "Nombre d'actes par pc diag"
|
389
|
i = 0
|
390
|
for val in nb_actes_diag:
|
391
|
print "%d : %d" % (i, val)
|
392
|
i += 1
|
393
|
print "Nombre d'actes par pc trait"
|
394
|
i = 0
|
395
|
for val in nb_actes_trait:
|
396
|
print "%d : %d" % (i, val)
|
397
|
i += 1
|
398
|
|
399
|
for num, values in facturations.items():
|
400
|
print "Facturation : %s" % num
|
401
|
print "Nb factures : %d" % len(values['factures'])
|
402
|
print "Nb actes : %d" % len(values['actes'])
|
403
|
|
404
|
#Facturation : 132
|
405
|
#Nb factures : 280
|
406
|
#Nb actes : 517
|
407
|
|
408
|
#Facturation : 133
|
409
|
#Nb factures : 182
|
410
|
#Nb actes : 292
|
411
|
|
412
|
author = User.objects.get(pk=1)
|
413
|
|
414
|
# Commencer par péter toutes les healthcare existantes
|
415
|
CmppHealthCareDiagnostic.objects.all().delete()
|
416
|
CmppHealthCareTreatment.objects.all().delete()
|
417
|
# Creation des Healthcare
|
418
|
HcDiags = []
|
419
|
HcTraits = []
|
420
|
for patient_id, pcs in histo.items():
|
421
|
patient = None
|
422
|
try:
|
423
|
patient = PatientRecord.objects.get(old_id=patient_id, service=service)
|
424
|
except:
|
425
|
print 'Patient %s non trouve' % patient_id
|
426
|
continue
|
427
|
for pc in pcs:
|
428
|
start_date = _to_date(pc['periode']['date_debut'])
|
429
|
request_date = _to_date(pc['periode']['date_demande'])
|
430
|
agree_date = _to_date(pc['periode']['date_accord'])
|
431
|
insist_date = _to_date(pc['periode']['date_relance'])
|
432
|
act_number = _to_int(pc['periode']['nbr_seances']) or 0
|
433
|
if pc['type'] == '1':
|
434
|
hc = CmppHealthCareDiagnostic(start_date=start_date,
|
435
|
request_date=request_date,
|
436
|
agree_date=agree_date,
|
437
|
insist_date=insist_date,
|
438
|
patient=patient,
|
439
|
act_number=act_number,
|
440
|
author=author)
|
441
|
HcDiags.append(hc)
|
442
|
else:
|
443
|
hc = CmppHealthCareTreatment(start_date=start_date,
|
444
|
request_date=request_date,
|
445
|
agree_date=agree_date,
|
446
|
insist_date=insist_date,
|
447
|
patient=patient,
|
448
|
act_number=act_number,
|
449
|
author=author)
|
450
|
HcTraits.append(hc)
|
451
|
hc.save()
|
452
|
pc['hc'] = hc
|
453
|
#CmppHealthCareDiagnostic.objects.bulk_create(HcDiags)
|
454
|
#CmppHealthCareTreatment.objects.bulk_create(HcTraits)
|
455
|
# Association des actes au healthcare
|
456
|
i = 0
|
457
|
for patient_id, pcs in histo.items():
|
458
|
patient = None
|
459
|
try:
|
460
|
patient = PatientRecord.objects.get(old_id=patient_id, service=service)
|
461
|
except:
|
462
|
print 'Patient %s non trouve' % patient_id
|
463
|
continue
|
464
|
for pc in pcs:
|
465
|
hc = pc['hc']
|
466
|
for act in pc['actes']:
|
467
|
a = None
|
468
|
try:
|
469
|
a = Act.objects.get(old_id=act['id'])
|
470
|
except:
|
471
|
print "Acte non trouve %s" % act['id']
|
472
|
i += 1
|
473
|
continue
|
474
|
if not a.is_billed:
|
475
|
print "Acte deja pris en charge mais non facture %s" %a
|
476
|
a.is_billed = True
|
477
|
a.healthcare = hc
|
478
|
a.save()
|
479
|
print "Acte non trouve %d" % i
|
480
|
# Historique des dossiers, Automatic switch state ? Automated hc creation ?
|
481
|
print "--> Lecture table des dossiers..."
|
482
|
csvfile = open(os.path.join(db_path, db, 'dossiers.csv'), 'rb')
|
483
|
csvlines = csv.reader(csvfile, delimiter=';', quotechar='|')
|
484
|
d_cols = csvlines.next()
|
485
|
tables_data['dossiers'] = []
|
486
|
for line in csvlines:
|
487
|
data = _get_dict(d_cols, line)
|
488
|
tables_data['dossiers'].append(data)
|
489
|
csvfile.close()
|
490
|
print "<-- Terminé : dictionnaire avec clé patient prêt"
|
491
|
|
492
|
date_accueil = None
|
493
|
date_diagnostic = None
|
494
|
date_inscription = None
|
495
|
date_clos = None
|
496
|
date_retour = None
|
497
|
|
498
|
pdb.set_trace()
|
499
|
FileState.objects.filter(patient__service=service).delete()
|
500
|
for dossier in tables_data['dossiers']:
|
501
|
fss = []
|
502
|
patient = None
|
503
|
try:
|
504
|
patient = PatientRecord.objects.get(old_id=dossier['id'], service=service)
|
505
|
except:
|
506
|
print 'Patient %s non trouve' % dossier['id']
|
507
|
continue
|
508
|
date_accueil = _to_date(dossier['con_date'])
|
509
|
date_inscription = _to_date(dossier['ins_date'])
|
510
|
date_clos = _to_date(dossier['sor_date'])
|
511
|
date_retour = _to_date(dossier['ret_date'])
|
512
|
|
513
|
# La vrai date d'inscription c'est le premier acte facturé
|
514
|
# donc date_inscription devrait être égale
|
515
|
# verification
|
516
|
try:
|
517
|
real_date_inscription = patient.act_set.filter(is_billed=True).order_by('date')[0].date
|
518
|
except:
|
519
|
print "Patient %s jamais facture" % dossier['id']
|
520
|
else:
|
521
|
if date_inscription and real_date_inscription != date_inscription:
|
522
|
print "La date d'inscription est differente du premier acte facture pour %s" % dossier['id']
|
523
|
elif not date_inscription:
|
524
|
print "Pas de date d'inscription, on prend le premier acte pour %s" % dossier['id']
|
525
|
date_inscription = real_date_inscription
|
526
|
|
527
|
# date d'accueil devrait précéder la date d'inscription
|
528
|
# sinon, on l'ignore
|
529
|
if (date_accueil and not date_inscription) or (date_accueil and date_inscription and date_accueil < date_inscription):
|
530
|
fss.append((status_accueil, date_accueil, None))
|
531
|
|
532
|
# revoir, si on a un acte non facturé avant le diag, on va avoir l'impression que le dossier a été en traitement, ne faut pas prendre que les actes billed ?
|
533
|
# On tente avec que du is_billed.
|
534
|
# Lors dossiers qui n'aurant jamsi eu d'acte de facturé, on prend les dates et on fait un historique par défaut comme avant!
|
535
|
|
536
|
if date_clos and date_inscription and date_clos < date_inscription:
|
537
|
print "Cloture avant inscription pour %s, on ne cloture pas" % dossier['id']
|
538
|
date_clos = None
|
539
|
|
540
|
# Historique par les actes
|
541
|
history = []
|
542
|
d = True
|
543
|
for act in patient.act_set.filter(is_billed=True).order_by('date'):
|
544
|
tag = act.get_hc_tag()
|
545
|
if tag and'D' in tag:
|
546
|
if not history or not d:
|
547
|
history.append(('D', act.date))
|
548
|
d = True
|
549
|
else:
|
550
|
if not tag:
|
551
|
print 'Act facture %d sans pc associee, traitement.' % act.id
|
552
|
if d:
|
553
|
history.append(('T', act.date))
|
554
|
d = False
|
555
|
|
556
|
clos = False
|
557
|
inscrit = False
|
558
|
tt = None
|
559
|
for i in range(len(history)):
|
560
|
t, date = history[i]
|
561
|
if not inscrit:
|
562
|
inscrit = True
|
563
|
if date_inscription:
|
564
|
if t == 'D':
|
565
|
fss.append((status_diagnostic, date, None))
|
566
|
else:
|
567
|
fss.append((status_traitement, date, None))
|
568
|
else:
|
569
|
if not date_clos:
|
570
|
if t == 'D':
|
571
|
fss.append((status_diagnostic, date, None))
|
572
|
else:
|
573
|
fss.append((status_traitement, date, None))
|
574
|
elif not clos:
|
575
|
if t == 'D':
|
576
|
fss.append((status_diagnostic, date, None))
|
577
|
else:
|
578
|
fss.append((status_traitement, date, None))
|
579
|
next_date = None
|
580
|
if i < len(history) - 1:
|
581
|
_, next_date = history[i+1]
|
582
|
if not next_date or clos < next_date:
|
583
|
fss.append((status_clos, date_clos, None))
|
584
|
clos = True
|
585
|
else:
|
586
|
if date_retour and date_retour > date_clos:
|
587
|
if date >= date_retour:
|
588
|
if t == 'D':
|
589
|
fss.append((status_diagnostic, date, None))
|
590
|
else:
|
591
|
fss.append((status_traitement, date, None))
|
592
|
|
593
|
if not fss:
|
594
|
print "Pas d'etat pour le dossier patient %s!" % dossier['id']
|
595
|
else:
|
596
|
fs = FileState(status=fss[0][0], author=creator, previous_state=None)
|
597
|
date_selected = fss[0][1]
|
598
|
fs.patient = patient
|
599
|
fs.date_selected = date_selected
|
600
|
fs.comment = fss[0][2]
|
601
|
fs.save()
|
602
|
patient.last_state = fs
|
603
|
patient.save()
|
604
|
if len(fss) > 1:
|
605
|
for status, date_selected, comment in fss[1:]:
|
606
|
try:
|
607
|
patient.set_state(status=status, author=creator, date_selected=date_selected, comment=comment)
|
608
|
except Exception, e:
|
609
|
print "Pour patient %s, exception %s" % (patient, str(e))
|
610
|
|
611
|
# Si reouverture apres date de cloture, passer à cette date en d ou en t
|
612
|
# Combinaisons possibles
|
613
|
# Mais au final la reouverture n'a d'intérêt que si on a
|
614
|
# une date de cloture antérieure
|
615
|
# if date_retour and date_clos and date_retour < date_clos:
|
616
|
# # accueil, d/t, cloture (date inconnue), d/t, cloture
|
617
|
# elif date_retour and date_clos and date_retour > date_clos:
|
618
|
# # accueil, d/t, cloture, d/t
|
619
|
# elif date_retour and date_clos and date_retour == date_clos:
|
620
|
# print "Date de retour et date de clotûre égale pour %s" % dossier['id']
|
621
|
# elif date_retour:
|
622
|
# # accueil, d/t, cloture (date inconnue), d/t
|
623
|
# elif date_clos:
|
624
|
# # accueil, d/t, cloture
|
625
|
# else:
|
626
|
# # accueil, d/t
|
627
|
|
628
|
print "<-- Terminé"
|
629
|
transaction.commit()
|
630
|
print "====== Fin à %s ======" % str(datetime.today())
|
631
|
|
632
|
|
633
|
if __name__ == "__main__":
|
634
|
import_dossiers_phase_1()
|