def sendMobileMessage(userId, diagnoseId, diagnose=None, message=None): telPhoneNo = None if diagnoseId: diagnose = Diagnose.getDiagnoseById(diagnoseId) else: diagnose = Diagnose.getDiagnoseById(diagnose.id) if diagnose and hasattr(diagnose, 'patient') and diagnose.patient: telPhoneNo = diagnose.patient.identityPhone if telPhoneNo is None and hasattr(diagnose.patient, 'user') and diagnose.patient.user: telPhoneNo = diagnose.patient.user.phone if telPhoneNo is None: user = User.getById(userId) telPhoneNo = user.phone if telPhoneNo: smsRc = sms_utils.RandCode() param1 = diagnose.diagnoseSeriesNumber param3 = constant.MobileMessageConstant.UrlPrefix + diagnose.alipayHashCode param4 = constant.MobileMessageConstant.KefuPhone from DoctorSpring.util.helper import getPayCountByDiagnoseId param2 = getPayCountByDiagnoseId(diagnose.id) template_param = { 'param1': param1, 'param2': param2, 'param3': param3, 'param4': param4 } smsRc.send_emp_sms(telPhoneNo, smsRc.TEMPLATE_PAY, json.dumps(template_param))
def updateReport(): userId=session['userId'] user=User.getById(userId) if user is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) # if UserRole.checkRole(db_session,userId,constant.RoleId.Doctor): # return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) form = ReportForm(request.form) if form.reportId: #session['remember_me'] = form.remember_me.data # login and validate the user... if form.status and form.status==constant.ReportStatus.Commited: fileUrl=pdf_utils.generatorPdf(form.diagnoseId)#需要先生存文檔上傳到服務器,獲取url report=Report.update(form.reportId,constant.ReportType.Doctor,form.status,fileUrl,form.techDesc,form.imageDesc,form.diagnoseDesc) Diagnose.changeDiagnoseStatus(form.diagnoseId,constant.DiagnoseStatus.Diagnosed) #需要給用戶發信和記錄操作日誌 diagnose=Diagnose.getDiagnoseById(form.diagnoseId) sendMessageAndRecordLog(diagnose,userId) else: fileUrl=None#這是草稿,不需要生存文檔 diagnose=Diagnose.getDiagnoseById(form.diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) report=Report.update(form.reportId,constant.ReportType.Doctor,form.status,fileUrl,form.techDesc,form.imageDesc,form.diagnoseDesc) recordDiagnoseLog(diagnose,userId) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def updateReport(): userId = session['userId'] user = User.getById(userId) if user is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) # if UserRole.checkRole(db_session,userId,constant.RoleId.Doctor): # return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) form = ReportForm(request.form) patient_id = Diagnose.get_patientID_by_diagnoseID(form.diagnoseId) identity_Phone = Patient.get_identityPhone_by_patientID(patient_id) #identityPhone = Patient.get_identityPhone_by_patientID(patient_id)[0].decode(encoding='UTF-8') identityPhone = identity_Phone[0] #print(identityPhone) if form.reportId: #session['remember_me'] = form.remember_me.data # login and validate the user... if form.status and form.status == constant.ReportStatus.Commited: #first update based on form , then generate html Report.update(reportId=form.reportId, techDesc=form.techDesc, imageDesc=form.imageDesc, diagnoseDesc=form.diagnoseDesc) # fileUrl=pdf_utils.generatorPdf(form.diagnoseId, identityPhone)#需要先生存文檔上傳到服務器,獲取url fileUrl = pdf_utils.generatorHtml(form.diagnoseId, identityPhone) if fileUrl: report = Report.update(form.reportId, constant.ReportType.Doctor, form.status, fileUrl, form.techDesc, form.imageDesc, form.diagnoseDesc) Diagnose.changeDiagnoseStatus( form.diagnoseId, constant.DiagnoseStatus.Diagnosed) #需要給用戶發信和記錄操作日誌 diagnose = Diagnose.getDiagnoseById(form.diagnoseId) sendMessageAndRecordLog(diagnose, userId) else: return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False) else: fileUrl = None #這是草稿,不需要生存文檔 diagnose = Diagnose.getDiagnoseById(form.diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) report = Report.update(form.reportId, constant.ReportType.Doctor, form.status, fileUrl, form.techDesc, form.imageDesc, form.diagnoseDesc) recordDiagnoseLog(diagnose, userId) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False)
def addOrUpdateReport(): userId=session['userId'] user=User.getById(userId) if user is None : return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) #权限查看 if UserRole.checkRole(db_session,userId,constant.RoleId.Admin) == False: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) form = ReportForm(request.form) formResult=form.validate() if formResult.status==rs.SUCCESS.status: diagnose=Diagnose.getDiagnoseById(form.diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) #session['remember_me'] = form.remember_me.data # login and validate the user... report = None if form.reportId: report=Report.getReportById(form.reportId) if report.type==constant.ReportType.Doctor: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) Report.update(form.reportId,None,form.status,None,form.techDesc,form.imageDesc,form.diagnoseDesc) else: report=Report(form.techDesc,form.imageDesc,form.diagnoseDesc,form.fileUrl,ReportType.Admin,form.status) Report.save(report) diagnose.reportId=report.id Diagnose.save(diagnose) #flash('成功添加诊断评论') if form.status and form.status == constant.ReportStatus.Commited: diagnose=Diagnose.getDiagnoseById(form.diagnoseId) if diagnose: Diagnose.changeDiagnoseStatus(diagnose.id,constant.DiagnoseStatus.NeedDiagnose) if form.reportId is None and report: form.reportId = report.id Report.update(form.reportId,constant.ReportType.Doctor,status=constant.ReportStatus.Draft) if diagnose and hasattr(diagnose,'doctor'): doctor=diagnose.doctor if doctor and doctor.userId: content=dataChangeService.getDoctorNeedDiagnoseMessageContent(diagnose,doctor) #诊断通知 message=Message(constant.DefaultSystemAdminUserId,doctor.userId,'诊断通知',content,constant.MessageType.Diagnose) Message.save(message) #诊断日志 diagoseLog=DiagnoseLog(userId,form.diagnoseId,constant.DiagnoseLogAction.FetchDiagnoseEndAction) DiagnoseLog.save(db_session,diagoseLog) return json.dumps(formResult.__dict__,ensure_ascii=False) return json.dumps(formResult.__dict__,ensure_ascii=False)
def updateReport(): userId=session['userId'] user=User.getById(userId) if user is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) # if UserRole.checkRole(db_session,userId,constant.RoleId.Doctor): # return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) form = ReportForm(request.form) patient_id = Diagnose.get_patientID_by_diagnoseID(form.diagnoseId) identity_Phone = Patient.get_identityPhone_by_patientID(patient_id) #identityPhone = Patient.get_identityPhone_by_patientID(patient_id)[0].decode(encoding='UTF-8') identityPhone = identity_Phone[0] #print(identityPhone) if form.reportId: #session['remember_me'] = form.remember_me.data # login and validate the user... if form.status and form.status==constant.ReportStatus.Commited: #first update based on form , then generate html Report.update(reportId=form.reportId,techDesc=form.techDesc,imageDesc=form.imageDesc,diagnoseDesc=form.diagnoseDesc) # fileUrl=pdf_utils.generatorPdf(form.diagnoseId, identityPhone)#需要先生存文檔上傳到服務器,獲取url fileUrl=pdf_utils.generatorHtml(form.diagnoseId, identityPhone) if fileUrl: report=Report.update(form.reportId,constant.ReportType.Doctor,form.status,fileUrl,form.techDesc,form.imageDesc,form.diagnoseDesc) Diagnose.changeDiagnoseStatus(form.diagnoseId,constant.DiagnoseStatus.Diagnosed) #需要給用戶發信和記錄操作日誌 diagnose=Diagnose.getDiagnoseById(form.diagnoseId) sendMessageAndRecordLog(diagnose,userId) else: return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False) else: fileUrl=None#這是草稿,不需要生存文檔 diagnose=Diagnose.getDiagnoseById(form.diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) report=Report.update(form.reportId,constant.ReportType.Doctor,form.status,fileUrl,form.techDesc,form.imageDesc,form.diagnoseDesc) recordDiagnoseLog(diagnose,userId) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def rollbackDiagnose(diagnoseId): userId=session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False) userId=string.atoi(userId) status=request.form.get('status') comments=request.form.get('comments') if status: status=string.atoi(status) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) if hasattr(diagnose,'adminId') and diagnose.adminId and diagnose.adminId==userId: if status is None: status=constant.DiagnoseStatus.Draft diagnose.status=status Diagnose.save(diagnose) diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseNeedUpateAction) diagoseLog.description=comments DiagnoseLog.save(db_session,diagoseLog) if hasattr(diagnose,'patient') and diagnose.patient.userID: content=dataChangeService.getPatienDiagnoseMessageContent(diagnose) #诊断通知 message=Message(constant.DefaultSystemAdminUserId,diagnose.patient.userID,'诊断通知',content,constant.MessageType.Diagnose) Message.save(message) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
def addDiagnoseComment(): form = CommentsForm(request.form) resultForm = form.validate() if resultForm.status == rs.SUCCESS.status: #session['remember_me'] = form.remember_me.data # login and validate the user... diagnoseComment = Comment(form.userId, form.receiverId, form.diagnoseId, form.content) db_session.add(diagnoseComment) db_session.commit() db_session.flush() score = constant.DiagnoseScore[form.score] diagnose = Diagnose.getDiagnoseById(form.diagnoseId) diagnose.score = form.score Diagnose.save(diagnose) #为医生添加一些冗余字段 if hasattr(diagnose, 'doctor'): doctor = diagnose.doctor if score != 0: if doctor.goodFeedbackCount: doctor.goodFeedbackCount += 1 else: doctor.goodFeedbackCount = 1 if doctor.feedbackCount: doctor.feedbackCount += 1 else: doctor.feedbackCount = 1 Doctor.save(doctor) #flash('成功添加诊断评论') return jsonify(rs.SUCCESS.__dict__) return jsonify(rs.FAILURE.__dict__)
def evaluateDiagnose(diagnoseId): userId = session['uesrId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__, ensure_ascii=False) userId = string.atoi(userId) score = request.args.get('score') description = request.args.get('description') if score: score = string.atoi(score) else: return json.dumps(rs.PARAM_ERROR.__dict__, ensure_ascii=False) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) if hasattr( diagnose, 'patient' ) and diagnose.patient and diagnose.patient.userID and diagnose.patient.userID == userId: diagnose.status = constant.DiagnoseStatus.Diagnosed diagnose.score = score Diagnose.save(diagnose) diagoseLog = DiagnoseLog(userId, diagnoseId, constant.DiagnoseLogAction.DiagnoseFinished) diagoseLog.description = description DiagnoseLog.save(db_session, diagoseLog) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False)
def getDiagnoseActions(): try: diagnoseId = request.args.get('diagnoseId') userId = session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__, ensure_ascii=False) userId = string.atoi(userId) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) if hasattr( diagnose, 'patient' ) and diagnose.patient and diagnose.patient.userID and diagnose.uploadUserId: if userId != diagnose.patient.userID and userId != diagnose.uploadUserId: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False) diagDict = dataChangeService.getDiagnoseDetailInfoByPatient( db_session, diagnose) resultStatus = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, diagDict) resultDict = resultStatus.__dict__ return json.dumps(resultDict, ensure_ascii=False) except Exception, e: print e.message print e resultDict = rs.SUCCESS.__dict__ json.dumps(resultDict, ensure_ascii=False)
def addDiagnoseComment(): form = CommentsForm(request.form) resultForm=form.validate() if resultForm.status==rs.SUCCESS.status: #session['remember_me'] = form.remember_me.data # login and validate the user... diagnoseComment=Comment(form.userId,form.receiverId,form.diagnoseId,form.content) db_session.add(diagnoseComment) db_session.commit() db_session.flush() score=constant.DiagnoseScore[form.score] diagnose=Diagnose.getDiagnoseById(form.diagnoseId) diagnose.score=form.score Diagnose.save(diagnose) #为医生添加一些冗余字段 if hasattr(diagnose,'doctor'): doctor=diagnose.doctor if score!=0: if doctor.goodFeedbackCount: doctor.goodFeedbackCount+=1 else: doctor.goodFeedbackCount=1 if doctor.feedbackCount: doctor.feedbackCount+=1 else: doctor.feedbackCount=1 Doctor.save(doctor) #flash('成功添加诊断评论') return jsonify(rs.SUCCESS.__dict__) return jsonify(rs.FAILURE.__dict__)
def evaluateDiagnose(diagnoseId): userId=session['uesrId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False) userId=string.atoi(userId) score=request.args.get('score') description=request.args.get('description') if score: score=string.atoi(score) else: return json.dumps(rs.PARAM_ERROR.__dict__,ensure_ascii=False) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) if hasattr(diagnose,'patient') and diagnose.patient and diagnose.patient.userID and diagnose.patient.userID==userId: diagnose.status=constant.DiagnoseStatus.Diagnosed diagnose.score=score Diagnose.save(diagnose) diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseFinished) diagoseLog.description=description DiagnoseLog.save(db_session,diagoseLog) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
def getMobileVerifyCode(): try: from DoctorSpring.util import verify_code,sms_utils verifyCode= verify_code.generatorVerifyCode() LOG.info("产生验证码") session['verifyCode']=verifyCode telPhoneNo=None userId=session.get('userId') diagnoseId=request.args.get('diagnoseId') diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr(diagnose,'patient') and diagnose.patient: telPhoneNo=diagnose.patient.identityPhone if telPhoneNo is None and hasattr(diagnose.patient,'user') and diagnose.patient.user: telPhoneNo=diagnose.patient.user.phone if telPhoneNo is None: user=User.getById(userId) telPhoneNo=user.phone if telPhoneNo: smsRc=sms_utils.RandCode() template_param = {'param1':verifyCode} smsRc.send_emp_sms(telPhoneNo,smsRc.TEMPLATE_ID_1,json.dumps(template_param)) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) else: LOG.error("诊断[%s]发送验证码错误"%diagnoseId) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False) except Exception,e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def getDiagnoseActions(): try: diagnoseId=request.args.get('diagnoseId') userId=session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False) userId=string.atoi(userId) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None : return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) if hasattr(diagnose,'patient') and diagnose.patient and diagnose.patient.userID: if userId!=diagnose.patient.userID: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False) diagDict=dataChangeService.getDiagnoseDetailInfoByPatient(db_session,diagnose) resultStatus=rs.ResultStatus(rs.SUCCESS.status,rs.SUCCESS.msg,diagDict) resultDict=resultStatus.__dict__ return json.dumps(resultDict,ensure_ascii=False) except Exception, e: print e.message print e resultDict=rs.SUCCESS.__dict__ json.dumps(resultDict,ensure_ascii=False)
def validate(self): try: if self.diagnoseId is None: return FAILURE diagnose=Diagnose.getDiagnoseById(self.diagnoseId) if diagnose is None: return FAILURE if diagnose.doctorId and hasattr(diagnose,'doctor') and diagnose.doctor and diagnose.doctor.userId: self.receiverId=diagnose.doctor.userId else: return FAILURE if diagnose.patientId and hasattr(diagnose,'patient') and diagnose.patient and diagnose.patient.userID: self.userId=diagnose.patient.userID else: return FAILURE # if self.title is None: # return FAILURE if self.content is None or len(self.content)<10: failure=ResultStatus(FAILURE.status,"输入的内容长度必须大于等于10") return failure if self.score is None or self.score == u'': return FAILURE else: self.score=string.atoi(self.score) except Exception,e: return FAILURE
def generatorPdf(diagnoseId): diagnose=Diagnose.getDiagnoseById(diagnoseId) if session.has_key('userId'): userId=session['userId'] if userId is None: return redirect('/loginPage') resHtml = None if UserRole.checkRole(db_session,userId,constant.RoleId.Patient) and Patient.is_patient_under_user(int(userId),diagnose.patientId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole(db_session,userId,constant.RoleId.Admin) and (int(userId) == diagnose.adminId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole(db_session,userId,constant.RoleId.Doctor) and (int(userId) == diagnose.doctorId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole(db_session,userId,constant.RoleId.HospitalUser) and (int(userId) == diagnose.uploadUserId): resHtml = renderHtmlFromDiagnose(diagnose) if resHtml: return resHtml else: return redirect('/error')
def getMobileVerifyCode(): try: from DoctorSpring.util import verify_code, sms_utils verifyCode = verify_code.generatorVerifyCode() LOG.info("产生验证码") session['verifyCode'] = verifyCode telPhoneNo = None userId = session.get('userId') diagnoseId = request.args.get('diagnoseId') diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr(diagnose, 'patient') and diagnose.patient: telPhoneNo = diagnose.patient.identityPhone if telPhoneNo is None and hasattr( diagnose.patient, 'user') and diagnose.patient.user: telPhoneNo = diagnose.patient.user.phone if telPhoneNo is None: user = User.getById(userId) telPhoneNo = user.phone if telPhoneNo: smsRc = sms_utils.RandCode() template_param = {'param1': verifyCode} smsRc.send_emp_sms(telPhoneNo, smsRc.TEMPLATE_ID_1, json.dumps(template_param)) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) else: LOG.error("诊断[%s]发送验证码错误" % diagnoseId) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False) except Exception, e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False)
def diagnosefileUpload(filetype): userId = session.get('userId') diagnoseId = request.args.get('diagnoseId') diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose and userId: userId = string.atoi(userId) if diagnose.uploadUserId == userId: File.deleteFileByPathologyId(diagnose.pathologyId, filetype)
def applyDiagnose(): if session.has_key('userId'): userId = session['userId'] if userId is None: return redirect('/loginPage') data = {} hospitals = Hospital.getAllHospitals(db_session) hospitalsDict = object2dict.objects2dicts(hospitals) data['hospitals'] = hospitalsDict positions = Position.getPositions() positionsDict = object2dict.objects2dicts(positions) data['positions'] = positionsDict locations = Location.getAllLocations(db_session) locationsDict = object2dict.objects2dicts(locations) data['locations'] = locationsDict #hospital user if 'type' in request.args.keys(): data['type'] = int(request.args.get('type')) if 'edit' in request.args.keys() and 'diagnoseid' in request.args.keys(): new_diagnose = Diagnose.getDiagnoseById(request.args['diagnoseid']) data['edit'] = 1 else: new_diagnose = Diagnose.getNewDiagnoseByStatus(ModelStatus.Draft, session['userId']) if new_diagnose is not None: data['doctor'] = new_diagnose.doctor data['patient'] = new_diagnose.patient data['pathology'] = new_diagnose.pathology new_file = File.getFiles(new_diagnose.pathologyId, constant.FileType.Dicom) data['dicomfile'] = new_file new_files = File.getFiles(new_diagnose.pathologyId, constant.FileType.FileAboutDiagnose) data['fileAboutDiagnose'] = new_files pathologyPositions = [] if hasattr(new_diagnose, 'pathology') and hasattr( new_diagnose.pathology, 'pathologyPostions'): pathologyPositions = object2dict.objects2dicts( new_diagnose.pathology.pathologyPostions) data['pathologyPositions'] = pathologyPositions patients = Patient.get_patient_by_user(session['userId']) if patients is None or len(patients) < 1: patientdict = [] else: patientdict = object2dict.objects2dicts(patients) data['patientdict'] = patientdict return render_template("applyDiagnose.html", result=data)
def dicomfileUpload(): userId=session.get('userId') if userId is None: return redirect(LOGIN_URL) userId=string.atoi(userId) type=request.form.get('type') diagnoseId=request.form.get("diagnoseId") if diagnoseId is None: return jsonify({'code': 1, 'message' : "error", 'data': ''}) diagnoseId=string.atoi(diagnoseId) if type: type=string.atoi(type) else: type=constant.FileType.Dicom try: diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose and diagnose.pathologyId: file_infos = [] files = request.files for key, file in files.iteritems(): if file and allowed_file(file.filename): filename = file.filename # file_url = oss_util.uploadFile(diagnoseId, filename) from DoctorSpring.util.oss_util import uploadFileFromFileStorage fileurl = uploadFileFromFileStorage(diagnoseId, filename, file,'',{}) new_file = File(FileType.Dicom, filename, '11', fileurl,diagnose.pathologyId) File.save(new_file) if type==FileType.Dicom: filesAboutDiagnose=File.getFiles(diagnose.pathologyId,FileType.FileAboutDiagnose) if filesAboutDiagnose and len(filesAboutDiagnose)>0: diagnoseChange=Diagnose() diagnoseChange.id=diagnoseId diagnoseChange.ossUploaded=constant.DiagnoseUploaed.Uploaded diagnose.uploadUserId=userId Diagnose.update(diagnoseChange) if type==FileType.FileAboutDiagnose: filesAboutDiagnose=File.getFiles(diagnose.pathologyId,FileType.Dicom) if filesAboutDiagnose and len(filesAboutDiagnose)>0: diagnoseChange=Diagnose() diagnoseChange.id=diagnoseId diagnoseChange.ossUploaded=constant.DiagnoseUploaed.Uploaded diagnose.uploadUserId=userId Diagnose.update(diagnoseChange) file_infos.append(dict(id=new_file.id, name=filename, size=11, url=fileurl)) else: return jsonify({'code': 1, 'message' : "error", 'data': ''}) return jsonify(files=file_infos) except Exception,e: print e.message return jsonify({'code': 1, 'message' : "error", 'data': ''})
def rollbackDiagnose(diagnoseId): userId=session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False) userId=string.atoi(userId) status=request.form.get('status') comments=request.form.get('comments') if status: status=string.atoi(status) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) if (hasattr(diagnose,'adminId') and diagnose.adminId and diagnose.adminId==userId) or (hasattr(diagnose,'doctorId') and diagnose.doctorId and diagnose.doctor.userId == userId): if status is None: status=constant.DiagnoseStatus.Draft diagnose.status=status Diagnose.save(diagnose) diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseNeedUpateAction) diagoseLog.description=comments DiagnoseLog.save(db_session,diagoseLog) if hasattr(diagnose,'patient') and diagnose.patient.userID: content=dataChangeService.getPatienDiagnoseMessageContent(diagnose) #诊断通知 message=Message(constant.DefaultSystemAdminUserId,diagnose.patient.userID,'诊断通知',content,constant.MessageType.Diagnose) Message.save(message) if(hasattr(diagnose,'doctorId') and diagnose.doctorId and diagnose.doctor.userId == userId): reportDiagnoseRelations = ReportDiagnoseRelation.getReportsByDiagnoseId(diagnose.id) for reportDiagnoseRelation in reportDiagnoseRelations: if reportDiagnoseRelation.report.status != constant.ReportStatus.Del: if reportDiagnoseRelation.report.type == constant.ReportType.Doctor: print 'doctor report' #delete doctor report if exist # reportDiagnoseRelation.report.status = constant.ModelStatus.Del Report.update(reportDiagnoseRelation.report.id,status=constant.ReportStatus.Del) ReportDiagnoseRelation.update(reportDiagnoseRelation.id,status=constant.ModelStatus.Del) elif reportDiagnoseRelation.report.type == constant.ReportType.Admin: print 'admin report' #set diagnose report to admin report diagnose.reportId = reportDiagnoseRelation.report.id Diagnose.update(diagnose) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
def diagnoseFinish(diagnoseId): diagnosePayStats = DiagnosePayStats() diagnose = Diagnose.getDiagnoseById(diagnoseId) diagnosePayStats.diagnoseId = diagnoseId diagnosePayStats.diagnoseSeriesNumber = diagnose.diagnoseSeriesNumber diagnosePayStats.userId = session["user_id"] diagnosePayStats.finishDate = datetime.now() diagnosePayStats.money = diagnose.money diagnosePayStats.status = constant.DiagnosePayStatsConstant.Ongoing DiagnosePayStats.save(diagnosePayStats) resultJson = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg) return json.dumps(resultJson.__dict__, ensure_ascii=False)
def diagnoseFinish(diagnoseId): diagnosePayStats = DiagnosePayStats() diagnose = Diagnose.getDiagnoseById(diagnoseId) diagnosePayStats.diagnoseId = diagnoseId diagnosePayStats.diagnoseSeriesNumber = diagnose.diagnoseSeriesNumber diagnosePayStats.userId = session["user_id"] diagnosePayStats.finishDate = datetime.now() diagnosePayStats.money = diagnose.money diagnosePayStats.status = constant.DiagnosePayStatsConstant.Ongoing DiagnosePayStats.save(diagnosePayStats) resultJson=rs.ResultStatus(rs.SUCCESS.status,rs.SUCCESS.msg) return json.dumps(resultJson.__dict__,ensure_ascii=False)
def applyDiagnose(): if session.has_key('userId'): userId=session['userId'] if userId is None: return redirect('/loginPage') data = {} hospitals = Hospital.getAllHospitals(db_session) hospitalsDict = object2dict.objects2dicts(hospitals) data['hospitals'] = hospitalsDict positions = Position.getPositions() positionsDict = object2dict.objects2dicts(positions) data['positions'] = positionsDict locations = Location.getAllLocations(db_session) locationsDict = object2dict.objects2dicts(locations) data['locations'] = locationsDict if 'edit' in request.args.keys() and 'diagnoseid' in request.args.keys(): new_diagnose = Diagnose.getDiagnoseById(request.args['diagnoseid']) data['edit'] = 1 else: new_diagnose = Diagnose.getNewDiagnoseByStatus(ModelStatus.Draft, session['userId']) if new_diagnose is not None: data['doctor'] = new_diagnose.doctor data['patient'] = new_diagnose.patient data['pathology'] = new_diagnose.pathology new_file = File.getFiles(new_diagnose.pathologyId, constant.FileType.Dicom) data['dicomfile'] = new_file new_files = File.getFiles(new_diagnose.pathologyId, constant.FileType.FileAboutDiagnose) data['fileAboutDiagnose'] = new_files pathologyPositions = [] if hasattr(new_diagnose, 'pathology') and hasattr(new_diagnose.pathology, 'pathologyPostions'): pathologyPositions = object2dict.objects2dicts(new_diagnose.pathology.pathologyPostions) data['pathologyPositions'] = pathologyPositions patients = Patient.get_patient_by_user(session['userId']) if patients is None or len(patients) < 1: patientdict = [] else: patientdict = object2dict.objects2dicts(patients) data['patientdict'] = patientdict return render_template("applyDiagnose.html", result=data)
def applyRefund(diagnoseId): userId = session['user_id'] diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.DiagnoseRefund) DiagnoseLog.save(session,diagoseLog) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose.status == constant.DiagnoseStatus.Diagnosed: diagnosePayStats = DiagnosePayStats.getPayStatsByDiagnoseId(diagnoseId) for payStats in diagnosePayStats: payStats.status = constant.DiagnosePayStatsConstant.Refund DiagnosePayStats.updatePayStats(diagnosePayStats) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False)
def getDiagnoseLogBydiagnoseId(diagnoseId): if session.has_key('userId'): userId=session['userId'] if userId is None: return redirect(LOGIN_URL) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr(diagnose,'patient') and diagnose.patient.userID==string.atoi(userId): diagnoseLogs=AlipayLog.getAlipayLogsByDiagnoseId(diagnoseId) if diagnoseLogs and len(diagnoseLogs)>0: resultLogs=object2dict.objects2dicts(diagnoseLogs) result=rs.ResultStatus(rs.SUCCESS.status,rs.SUCCESS.msg,resultLogs) return json.dumps(result.__dict__,ensure_ascii=False) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def getDiagnoseDetailInfo(): diagnoseId=request.args.get('diagnoseId') if diagnoseId: diagnoseId=string.atoi(diagnoseId) else: return json.dumps(rs.PARAM_ERROR,ensure_ascii=False) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose: diagnoseResult=dataChangeService.getDiagnoseDetailInfo(diagnose) resultStatus=rs.ResultStatus(rs.SUCCESS.status,rs.SUCCESS.msg,diagnoseResult) resultDict=resultStatus.__dict__ return json.dumps(resultDict,ensure_ascii=False) return json.dumps(rs.NO_DATA,ensure_ascii=False)
def applyRefund(diagnoseId): userId = session['user_id'] diagoseLog = DiagnoseLog(userId, diagnoseId, constant.DiagnoseLogAction.DiagnoseRefund) DiagnoseLog.save(session, diagoseLog) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose.status == constant.DiagnoseStatus.Diagnosed: diagnosePayStats = DiagnosePayStats.getPayStatsByDiagnoseId(diagnoseId) for payStats in diagnosePayStats: payStats.status = constant.DiagnosePayStatsConstant.Refund DiagnosePayStats.updatePayStats(diagnosePayStats) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False)
def changeDiagnoseToNeedPay(diagnoseId): try: loginUserId = session.get('userId') if loginUserId is None: return fileIds = request.form.getlist('fileIds') loginUserId = string.atoi(loginUserId) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None or (not hasattr( diagnose, "patient")) or diagnose.patient is None: return userID = diagnose.patient.userID if userID == loginUserId or diagnose.uploadUserId == loginUserId: # diagnose=Diagnose() # diagnose.id=diagnoseId #update by lichuan # diagnose.status= constant.DiagnoseStatus.NeedPay # Diagnose.update(diagnose) from DoctorSpring.views.front import sendAllMessage, checkFilesExisting from DoctorSpring.models.diagnoseDocument import File if (checkFilesExisting(diagnose)): # newDiagnose= Diagnose() # newDiagnose.id=diagnoseId if diagnose.status == constant.DiagnoseStatus.NeedUpdate: new_diagnoselog = DiagnoseLog( diagnose.uploadUserId, diagnose.id, DiagnoseLogAction.DiagnoseNeedUpateRecommitAction) DiagnoseLog.save(db_session, new_diagnoselog) diagnose.status = constant.DiagnoseStatus.Triaging Diagnose.update(diagnose) pathologyId = diagnose.pathologyId File.cleanAllDirtyFile(fileIds, pathologyId) else: diagnose.status = constant.DiagnoseStatus.NeedPay Diagnose.update(diagnose) #清除以前的无用文件 pathologyId = diagnose.pathologyId File.cleanAllDirtyFile(fileIds, pathologyId) sendAllMessage(userID, diagnose) else: return json.dumps(rs.FAILURE.__dict__, "需要上传DICOM文件和诊断文件") #end update except Exception, e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False)
def generateAlipayUrl(diagnoseId): if session.has_key('userId'): userId=session['userId'] if userId is None: return redirect(LOGIN_URL) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr(diagnose,'patient') and string.atoi(userId)!=diagnose.patient.userID: result=rs.ResultStatus(rs.FAILURE.status,"诊断不存在或不是用户申请的") return json.dumps(result.__dict__,ensure_ascii=False) if diagnose and diagnose.status==constant.DiagnoseStatus.NeedPay and diagnose.ossUploaded==constant.DiagnoseUploaed.Uploaded: alipayLog=AlipayLog(userId,diagnoseId,constant.AlipayLogAction.StartApplyAlipay) AlipayLog.save(alipayLog) description=None needPay=None if hasattr(diagnose,'pathology') and hasattr(diagnose.pathology,'pathologyPostions'): if len(diagnose.pathology.pathologyPostions)>0: if diagnose.pathology.diagnoseMethod==constant.DiagnoseMethod.Mri: needPay=diagnose.getPayCount(constant.DiagnoseMethod.Mri,len(diagnose.pathology.pathologyPostions),diagnose.getUserDiscount(diagnose.patientId)) elif diagnose.pathology.diagnoseMethod==constant.DiagnoseMethod.Ct: needPay=diagnose.getPayCount(constant.DiagnoseMethod.Ct,len(diagnose.pathology.pathologyPostions),diagnose.getUserDiscount(diagnose.patientId)) else: result=rs.ResultStatus(rs.FAILURE.status,"诊断不存在或这状态不对") return json.dumps(result.__dict__,ensure_ascii=False) else: result=rs.ResultStatus(rs.FAILURE.status,"诊断不存在或这状态不对") return json.dumps(result.__dict__,ensure_ascii=False) if hasattr(diagnose,'doctor') and hasattr(diagnose.doctor,'username'): description=' 医生(%s)的诊断费用:%f 元'%(diagnose.doctor.username,needPay) if hasattr(diagnose.doctor.hospital,'name'): description=diagnose.doctor.hospital.name+description payUrl=alipay.create_direct_pay_by_user(diagnose.diagnoseSeriesNumber,diagnose.diagnoseSeriesNumber,'咨询费',needPay) if payUrl: alipayLog=AlipayLog(userId,diagnoseId,constant.AlipayLogAction.GetAlipayUrl) alipayLog.description=description alipayLog.payUrl=payUrl AlipayLog.save(alipayLog) result=rs.ResultStatus(rs.SUCCESS.status,rs.SUCCESS.msg,payUrl) return json.dumps(result.__dict__,ensure_ascii=False) else: alipayLog=AlipayLog(userId,diagnoseId,constant.AlipayLogAction.GetAlipayUrlFailure) AlipayLog.save(alipayLog) result=rs.ResultStatus(rs.FAILURE.status,constant.AlipayLogAction.GetAlipayUrlFailure) return json.dumps(result.__dict__,ensure_ascii=False) result=rs.ResultStatus(rs.FAILURE.status,"诊断不存在或这状态不对") return json.dumps(result.__dict__,ensure_ascii=False)
def getDiagnoseDetailInfo(): diagnoseId = request.args.get('diagnoseId') if diagnoseId: diagnoseId = string.atoi(diagnoseId) else: return json.dumps(rs.PARAM_ERROR, ensure_ascii=False) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose: diagnoseResult = dataChangeService.getDiagnoseDetailInfo(diagnose) resultStatus = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, diagnoseResult) resultDict = resultStatus.__dict__ return json.dumps(resultDict, ensure_ascii=False) return json.dumps(rs.NO_DATA, ensure_ascii=False)
def changeDiagnoseToNeedPay(diagnoseId): try: loginUserId=session.get('userId') if loginUserId is None: return fileIds = request.form.getlist('fileIds') loginUserId=string.atoi(loginUserId) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None or (not hasattr(diagnose,"patient")) or diagnose.patient is None: return userID=diagnose.patient.userID if userID==loginUserId or diagnose.uploadUserId==loginUserId: # diagnose=Diagnose() # diagnose.id=diagnoseId #update by lichuan # diagnose.status= constant.DiagnoseStatus.NeedPay # Diagnose.update(diagnose) from DoctorSpring.views.front import sendAllMessage,checkFilesExisting from DoctorSpring.models.diagnoseDocument import File if(checkFilesExisting(diagnose)): # newDiagnose= Diagnose() # newDiagnose.id=diagnoseId if diagnose.status == constant.DiagnoseStatus.NeedUpdate: new_diagnoselog = DiagnoseLog(diagnose.uploadUserId, diagnose.id, DiagnoseLogAction.DiagnoseNeedUpateRecommitAction) DiagnoseLog.save(db_session, new_diagnoselog) diagnose.status = constant.DiagnoseStatus.Triaging Diagnose.update(diagnose) pathologyId = diagnose.pathologyId File.cleanAllDirtyFile(fileIds, pathologyId) else: diagnose.status = constant.DiagnoseStatus.NeedPay Diagnose.update(diagnose) #清除以前的无用文件 pathologyId = diagnose.pathologyId File.cleanAllDirtyFile(fileIds, pathologyId) sendAllMessage(userID,diagnose) else: return json.dumps(rs.FAILURE.__dict__,"需要上传DICOM文件和诊断文件") #end update except Exception,e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def cancleDiagnose(diagnoseId): userId=session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__,ensure_ascii=False) userId=string.atoi(userId) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__,ensure_ascii=False) if (hasattr(diagnose,'patient') and diagnose.patient and diagnose.patient.userID and diagnose.patient.userID==userId) or (hasattr(diagnose,'uploadUser') and diagnose.uploadUserId and diagnose.uploadUserId==userId): diagnose.status=constant.DiagnoseStatus.Del Diagnose.save(diagnose) diagoseLog=DiagnoseLog(userId,diagnoseId,constant.DiagnoseLogAction.CancleDiagnose) DiagnoseLog.save(db_session,diagoseLog) return json.dumps(rs.SUCCESS.__dict__,ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__,ensure_ascii=False)
def getDiagnoseLogBydiagnoseId(diagnoseId): if session.has_key('userId'): userId = session['userId'] if userId is None: return redirect(LOGIN_URL) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr( diagnose, 'patient') and diagnose.patient.userID == string.atoi(userId): diagnoseLogs = AlipayLog.getAlipayLogsByDiagnoseId(diagnoseId) if diagnoseLogs and len(diagnoseLogs) > 0: resultLogs = object2dict.objects2dicts(diagnoseLogs) result = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, resultLogs) return json.dumps(result.__dict__, ensure_ascii=False) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False)
def setDiagnoseCommentsDetailInfo(diagnoseCommentsDict): if diagnoseCommentsDict is None or len(diagnoseCommentsDict) < 1: return for diagnoseComment in diagnoseCommentsDict: if diagnoseComment.has_key('observer'): observer = diagnoseComment.get('observer') user = User.getById(observer) if user: diagnoseComment['avatar'] = user.imagePath diagnoseComment['senderName'] = user.name if diagnoseComment.has_key('receiver'): receiver = diagnoseComment.get('receiver') user = User.getById(receiver) if user: #diagnoseComment['receiverName']=user.name doctor = Doctor.getByUserId(receiver) if doctor and hasattr(doctor, "hospital") and doctor.hospital: diagnoseComment['doctorUserId'] = receiver diagnoseComment['hospitalId'] = doctor.hospitalId diagnoseComment['hospitalName'] = doctor.hospital.name diagnoseComment['receiverName'] = doctor.username if diagnoseComment.has_key('diagnoseId'): diagnose = Diagnose.getDiagnoseById( diagnoseComment.get('diagnoseId')) if diagnose: if diagnose.score: diagnoseComment['scoreName'] = constant.DiagnoseScore[ diagnose.score] # if diagnose.hospitalId and hasattr(diagnose,'hospital') and diagnose.hospital and diagnose.hospita.name: # diagnoseComment['hospitalId']= diagnose.hospitalId # diagnoseComment['hospitalName']=diagnose.hospital.name if hasattr(diagnose, "pathology") and diagnose.pathology: pathology = diagnose.pathology if hasattr(pathology, "pathologyPostions" ) and pathology.pathologyPostions: pathologyPositons = pathology.pathologyPostions if pathologyPositons and len(pathologyPositons) > 0: positions = u'' for pathologyPositon in pathologyPositons: position = pathologyPositon.position positions += (u' ' + position.name) diagnoseComment['positionName'] = positions
def doctor_rec(): doctor = None if 'doctorId' in request.args.keys(): doctorId = request.args['doctorId'] doctor = Doctor.get_doctor(doctorId,"") elif 'diagnoseId' in request.args.keys(): diagnoseId = int(request.args['diagnoseId']) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is not None: doctor = diagnose.doctor else: doctor = Doctor.get_doctor(0, True) if doctor is None: return jsonify(rs.SUCCESS.__dict__, ensure_ascii=False) doctors_dict = dataChangeService.get_doctor(doctor) resultStatus = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, doctors_dict) return jsonify(resultStatus.__dict__, ensure_ascii=False)
def setDiagnoseCommentsDetailInfo(diagnoseCommentsDict): if diagnoseCommentsDict is None or len(diagnoseCommentsDict)<1: return for diagnoseComment in diagnoseCommentsDict: if diagnoseComment.has_key('observer'): observer=diagnoseComment.get('observer') user=User.getById(observer) if user: diagnoseComment['avatar']=user.imagePath diagnoseComment['senderName']=user.name if diagnoseComment.has_key('receiver'): receiver=diagnoseComment.get('receiver') user=User.getById(receiver) if user: #diagnoseComment['receiverName']=user.name doctor=Doctor.getByUserId(receiver) if doctor and hasattr(doctor,"hospital") and doctor.hospital : diagnoseComment['doctorUserId']=receiver diagnoseComment['hospitalId']= doctor.hospitalId diagnoseComment['hospitalName']=doctor.hospital.name diagnoseComment['receiverName']=doctor.username if diagnoseComment.has_key('diagnoseId'): diagnose=Diagnose.getDiagnoseById(diagnoseComment.get('diagnoseId')) if diagnose: if diagnose.score: diagnoseComment['scoreName']=constant.DiagnoseScore[diagnose.score] # if diagnose.hospitalId and hasattr(diagnose,'hospital') and diagnose.hospital and diagnose.hospita.name: # diagnoseComment['hospitalId']= diagnose.hospitalId # diagnoseComment['hospitalName']=diagnose.hospital.name if hasattr(diagnose,"pathology") and diagnose.pathology: pathology=diagnose.pathology if hasattr(pathology,"pathologyPostions") and pathology.pathologyPostions: pathologyPositons=pathology.pathologyPostions if pathologyPositons and len(pathologyPositons)>0: positions=u'' for pathologyPositon in pathologyPositons: position=pathologyPositon.position positions+=(u' '+position.name) diagnoseComment['positionName']=positions
def doctor_rec(): doctor = None if 'doctorId' in request.args.keys(): doctorId = request.args['doctorId'] doctor = Doctor.get_doctor(doctorId, "") elif 'diagnoseId' in request.args.keys(): diagnoseId = int(request.args['diagnoseId']) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is not None: doctor = diagnose.doctor else: doctor = Doctor.get_doctor(0, True) if doctor is None: return jsonify(rs.SUCCESS.__dict__, ensure_ascii=False) doctors_dict = dataChangeService.get_doctor(doctor) resultStatus = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, doctors_dict) return jsonify(resultStatus.__dict__, ensure_ascii=False)
def generatorPdf(diagnoseId): diagnose=Diagnose.getDiagnoseById(diagnoseId) if hasattr(diagnose,'report'): report=diagnose.report if diagnose and report and report.status==ReportStatus.Commited and report.type==ReportType.Doctor: data={} data['techDesc']=report.techDesc data['imageDesc']=report.imageDesc data['diagnoseDesc']=report.diagnoseDesc data['seriesNumber']=report.seriesNumber data['fileUrl']=report.fileUrl createDate=report.createDate if createDate: createDate=createDate.strftime('%Y-%m-%d') data['createDate']=createDate postions=dataChangeService.getDiagnosePositonFromDiagnose(diagnose) if postions: data['postions']=postions if hasattr(diagnose,'patient') and diagnose.patient: data['gender']=diagnose.patient.gender birthDate=diagnose.patient.birthDate if birthDate: birthDate=birthDate.strftime('%Y-%m-%d') data['birthDate']=birthDate data['name']=diagnose.patient.realname if hasattr(diagnose,'doctor'): data['doctorName']=diagnose.doctor.username html = render_template('diagnoseResultPdf.html',data=data) # fileName=constant.DirConstant.DIAGNOSE_PDF_DIR+'test.pdf' # result = open(fileName, 'wb') # Changed from file to filename # # pdf = pdf_utils.save_pdf(html,result,diagnoseId,fileName) # result.close() # return render_template("testpdf.html",getAvatar=getAvatar) return html return None
def addConsult(): user_id = None if session.has_key('userId'): userId = session['userId'] if userId is None: redirect(LOGIN_URL) form = ConsultForm(request.form) formResult = form.validate() if formResult.status == rs.SUCCESS.status: #session['remember_me'] = form.remember_me.data # login and validate the user... if form.doctorId is None or form.doctorId == u'': dignose = Diagnose.getDiagnoseById(form.diagnose_id) if dignose and dignose.doctorId: form.doctorId = dignose.doctorId else: return redirect(ERROR_URL) if hasattr(dignose, 'patient') and dignose.patient: userId = dignose.patient.userID if form.source_id is None or form.source_id == u'': form.source_id = -1 if form.userId is not None and form.userId != u'': userId = form.userId consult = Consult(userId, form.doctorId, form.title, form.content, form.parent_id, form.source_id, form.type, form.diagnose_id) Consult.save(consult) if form.source_id: sourceConsult = Consult.getById(form.source_id) if sourceConsult: sourceConsult.count += 1 if (form.type == 0): sourceConsult.status = 3 else: sourceConsult.status = 4 Consult.update(consult) #LOG.info('%d 成功添加诊断评论')%userId return json.dumps(formResult.__dict__, ensure_ascii=False) return json.dumps(formResult.__dict__, ensure_ascii=False)
def generatorPdf(diagnoseId, identityPhone): diagnose = Diagnose.getDiagnoseById(diagnoseId) report = None if hasattr(diagnose, 'report'): report = diagnose.report if diagnose and report and report.type == constant.ReportType.Doctor: data = {} data['techDesc'] = report.techDesc data['imageDesc'] = report.imageDesc data['diagnoseDesc'] = report.diagnoseDesc data['seriesNumber'] = report.seriesNumber data['fileUrl'] = report.fileUrl createDate = report.createDate if createDate: createDate = createDate.strftime('%Y-%m-%d') data['createDate'] = createDate import DoctorSpring.views.data_change_service as dataChangeService postions = dataChangeService.getDiagnosePositonFromDiagnose( diagnose) if postions: data['postions'] = postions if hasattr(diagnose, 'patient') and diagnose.patient: data['gender'] = diagnose.patient.gender birthDate = diagnose.patient.birthDate if birthDate: birthDate = birthDate.strftime('%Y-%m-%d') data['birthDate'] = birthDate data['name'] = diagnose.patient.realname if hasattr(diagnose, 'doctor'): data['doctorName'] = diagnose.doctor.username html = render_template('diagnoseResultPdf.html', data=data) fileName = constant.DirConstant.DIAGNOSE_PDF_DIR + 'test.pdf' result = open(fileName, 'wb') # Changed from file to filename url = save_pdf(html, result, diagnoseId, fileName, identityPhone) result.close() # return render_template("testpdf.html",getAvatar=getAvatar) return url return None
def changeDiagnoseStatus(diagnoseId): try: status=request.args.get('status') loginUserId=session.get('userId') if loginUserId is None: return if status is None: return json.dumps(rs.PARAM_ERROR.__dict__,ensure_ascii=False) status=string.atoi(status) loginUserId=string.atoi(loginUserId) diagnose=Diagnose.getDiagnoseById(diagnoseId) if diagnose is None or (not hasattr(diagnose,"patient")) or diagnose.patient is None: return userID=diagnose.patient.userID if userID==loginUserId or diagnose.uploadUserId==loginUserId: diagnose=Diagnose() diagnose.id=diagnoseId diagnose.status= status Diagnose.update(diagnose) except Exception,e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__,ensure_ascii=False)
def addConsult(): user_id=None if session.has_key('userId'): userId=session['userId'] if userId is None: redirect(LOGIN_URL) form = ConsultForm(request.form) formResult=form.validate() if formResult.status==rs.SUCCESS.status : #session['remember_me'] = form.remember_me.data # login and validate the user... if form.doctorId is None or form.doctorId==u'': dignose=Diagnose.getDiagnoseById(form.diagnose_id) if dignose and dignose.doctorId: form.doctorId=dignose.doctorId else: return redirect(ERROR_URL) if hasattr(dignose,'patient') and dignose.patient: userId=dignose.patient.userID if form.source_id is None or form.source_id == u'': form.source_id=-1 if form.userId is not None and form.userId != u'': userId = form.userId consult=Consult(userId,form.doctorId,form.title,form.content,form.parent_id,form.source_id,form.type,form.diagnose_id) Consult.save(consult) if form.source_id: sourceConsult=Consult.getById(form.source_id) if sourceConsult: sourceConsult.count+=1 if (form.type == 0): sourceConsult.status = 3 else: sourceConsult.status = 4 Consult.update(consult) #LOG.info('%d 成功添加诊断评论')%userId return json.dumps(formResult.__dict__,ensure_ascii=False) return json.dumps(formResult.__dict__,ensure_ascii=False)
def cancleDiagnose(diagnoseId): userId = session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__, ensure_ascii=False) userId = string.atoi(userId) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) if (hasattr(diagnose, 'patient') and diagnose.patient and diagnose.patient.userID and diagnose.patient.userID == userId) or (hasattr(diagnose, 'uploadUser') and diagnose.uploadUserId and diagnose.uploadUserId == userId): diagnose.status = constant.DiagnoseStatus.Del Diagnose.save(diagnose) diagoseLog = DiagnoseLog(userId, diagnoseId, constant.DiagnoseLogAction.CancleDiagnose) DiagnoseLog.save(db_session, diagoseLog) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False)
def disableFile(): try: disgnoseId = request.form.get('diagnoseId') type = request.form.get('type') if disgnoseId is None: disgnoseId = string.atoi(disgnoseId) if type is None: type = constant.FileType.Dicom else: type = string.atoi(type) diagnose = Diagnose.getDiagnoseById(disgnoseId) if diagnose and diagnose.pathologyId: pathologyId = diagnose.pathologyId result = File.deleteFileByPathologyId(pathologyId, type) if result > 0: diagnose.ossUploaded = constant.DiagnoseUploaed.NoUploaded Diagnose.save(diagnose) return jsonify(rs.SUCCESS.__dict__, ensure_ascii=False) return jsonify(rs.FAILURE.__dict__, ensure_ascii=False) except Exception, e: LOG.error(e.message) return redirect(ERROR_URL)
def changeDiagnoseStatus(diagnoseId): try: status = request.args.get('status') loginUserId = session.get('userId') if loginUserId is None: return if status is None: return json.dumps(rs.PARAM_ERROR.__dict__, ensure_ascii=False) status = string.atoi(status) loginUserId = string.atoi(loginUserId) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None or (not hasattr( diagnose, "patient")) or diagnose.patient is None: return userID = diagnose.patient.userID if userID == loginUserId or diagnose.uploadUserId == loginUserId: diagnose = Diagnose() diagnose.id = diagnoseId diagnose.status = status Diagnose.update(diagnose) except Exception, e: LOG.error(e.message) return json.dumps(rs.FAILURE.__dict__, ensure_ascii=False)
def generatorPdf(diagnoseId): diagnose = Diagnose.getDiagnoseById(diagnoseId) if session.has_key('userId'): userId = session['userId'] if userId is None: return redirect('/loginPage') resHtml = None if UserRole.checkRole( db_session, userId, constant.RoleId.Patient) and Patient.is_patient_under_user( int(userId), diagnose.patientId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole(db_session, userId, constant.RoleId.Admin) and (int(userId) == diagnose.adminId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole(db_session, userId, constant.RoleId.Doctor) and (int(userId) == diagnose.doctorId): resHtml = renderHtmlFromDiagnose(diagnose) if UserRole.checkRole( db_session, userId, constant.RoleId.HospitalUser) and (int(userId) == diagnose.uploadUserId): resHtml = renderHtmlFromDiagnose(diagnose) if resHtml: return resHtml else: return redirect('/error')
def generatorHtml(diagnoseId, identityPhone): diagnose = Diagnose.getDiagnoseById(diagnoseId) report = None if hasattr(diagnose, 'report'): report = diagnose.report if diagnose and report and report.type == constant.ReportType.Doctor: data = {} data['techDesc'] = report.techDesc data['imageDesc'] = report.imageDesc data['diagnoseDesc'] = report.diagnoseDesc data['seriesNumber'] = report.seriesNumber data['fileUrl'] = report.fileUrl if hasattr(diagnose, 'diagnoseSeriesNumber'): data['diagnoseSN'] = diagnose.diagnoseSeriesNumber createDate = report.createDate if createDate: createDate = createDate.strftime('%Y-%m-%d') data['createDate'] = createDate import DoctorSpring.views.data_change_service as dataChangeService postions = dataChangeService.getDiagnosePositonFromDiagnose( diagnose) if postions: data['postions'] = postions if hasattr(diagnose, 'patient') and diagnose.patient: data['gender'] = diagnose.patient.gender birthDate = diagnose.patient.birthDate if birthDate: birthDate = birthDate.strftime('%Y-%m-%d') data['birthDate'] = getAge(birthDate) data['name'] = diagnose.patient.realname if hasattr(diagnose, 'doctor'): data['doctorName'] = diagnose.doctor.username if hasattr(diagnose, 'adminId'): adminUser = User.getById(diagnose.adminId) if adminUser.name: data['adminName'] = adminUser.name html = render_template('diagnoseResultPdf.html', data=data) fileName = constant.DirConstant.DIAGNOSE_PDF_DIR + 'diagnose' + str( diagnoseId) + 'Html.html' result = open(fileName, 'w+b') # Changed from file to filename result.write(html) result.close() fileLink = 'file://' + fileName pdfLink = constant.DirConstant.DIAGNOSE_PDF_DIR + 'diagnose' + str( diagnoseId) + 'Pdf.pdf' print fileLink print pdfLink returnCode = generate_pdf_from_html(fileLink, pdfLink) # return render_template("testpdf.html",getAvatar=getAvatar) if (returnCode == 0): #add encrypt for pdf output = PdfFileWriter() with open(pdfLink, "r+") as f1: input1 = PdfFileReader(f1) for i in range(input1.getNumPages()): output.addPage(input1.getPage(i)) #print(identityPhone) password = str(int(identityPhone)) owner_pwd = ''.join( random.choice(string.letters + string.digits) for _ in range(64)) #print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + owner_pwd) output.encrypt(password, owner_pwd) f1.seek(0) output.write(f1) f1.truncate() fileUrl = upload_pdf(pdfLink, diagnoseId) return fileUrl else: return None return None
def fileUpload(): userId = session.get('userId') if userId is None: return redirect(LOGIN_URL) userId = string.atoi(userId) type = request.form.get('type') diagnoseId = request.form.get("diagnoseId") if diagnoseId is None: return jsonify({'code': 1, 'message': "error", 'data': ''}) diagnoseId = string.atoi(diagnoseId) if type: type = string.atoi(type) else: type = constant.FileType.Dicom try: diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose and diagnose.pathologyId: file_infos = [] files = request.files for key, file in files.iteritems(): if file and allowed_file(file.filename): filename = file.filename extension = getFileExtension(filename) # file_url = oss_util.uploadFile(diagnoseId, filename) from DoctorSpring.util.oss_util import uploadFileFromFileStorage, size, getFileName fileurl = uploadFileFromFileStorage( diagnoseId, filename, file, '', {}, extension) newFileName = getFileName(diagnoseId, filename, extension) size = size(newFileName) new_file = File(type, filename, size, fileurl, diagnose.pathologyId) File.save(new_file) if type == FileType.Dicom: filesAboutDiagnose = File.getFiles( diagnose.pathologyId, FileType.FileAboutDiagnose) if filesAboutDiagnose and len(filesAboutDiagnose) > 0: diagnoseChange = Diagnose() diagnoseChange.id = diagnoseId diagnoseChange.ossUploaded = constant.DiagnoseUploaed.Uploaded #diagnoseChange.status=constant.DiagnoseStatus.NeedPay diagnose.uploadUserId = userId Diagnose.update(diagnoseChange) #sendAllMessage(userId,diagnose)需要提交了才能发信息h new_diagnoselog = DiagnoseLog( diagnose.uploadUserId, diagnose.id, DiagnoseLogAction.NewDiagnoseAction) DiagnoseLog.save(db_session, new_diagnoselog) if type == FileType.FileAboutDiagnose: filesAboutDiagnose = File.getFiles( diagnose.pathologyId, FileType.Dicom) if filesAboutDiagnose and len(filesAboutDiagnose) > 0: diagnoseChange = Diagnose() diagnoseChange.id = diagnoseId diagnoseChange.ossUploaded = constant.DiagnoseUploaed.Uploaded #diagnoseChange.status=constant.DiagnoseStatus.NeedPay diagnose.uploadUserId = userId Diagnose.update(diagnoseChange) #sendAllMessage(userId,diagnose) new_diagnoselog = DiagnoseLog( diagnose.uploadUserId, diagnose.id, DiagnoseLogAction.NewDiagnoseAction) DiagnoseLog.save(db_session, new_diagnoselog) file_infos.append( dict(id=new_file.id, name=filename, size=size, url=fileurl)) else: return jsonify({'code': 1, 'message': "error", 'data': ''}) return jsonify(files=file_infos) except Exception, e: LOG.error(e.message) return jsonify({'code': 1, 'message': "上传出错", 'data': ''})
def rollbackDiagnose(diagnoseId): userId = session['userId'] if userId is None: return json.dumps(rs.NO_LOGIN.__dict__, ensure_ascii=False) userId = string.atoi(userId) status = request.form.get('status') comments = request.form.get('comments') if status: status = string.atoi(status) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) if (hasattr(diagnose, 'adminId') and diagnose.adminId and diagnose.adminId == userId) or (hasattr(diagnose, 'doctorId') and diagnose.doctorId and diagnose.doctor.userId == userId): if status is None: status = constant.DiagnoseStatus.Draft diagnose.status = status Diagnose.save(diagnose) diagoseLog = DiagnoseLog( userId, diagnoseId, constant.DiagnoseLogAction.DiagnoseNeedUpateAction) diagoseLog.description = comments DiagnoseLog.save(db_session, diagoseLog) if hasattr(diagnose, 'patient') and diagnose.patient.userID: content = dataChangeService.getPatienDiagnoseMessageContent( diagnose) #诊断通知 message = Message(constant.DefaultSystemAdminUserId, diagnose.patient.userID, '诊断通知', content, constant.MessageType.Diagnose) Message.save(message) if (hasattr(diagnose, 'doctorId') and diagnose.doctorId and diagnose.doctor.userId == userId): reportDiagnoseRelations = ReportDiagnoseRelation.getReportsByDiagnoseId( diagnose.id) for reportDiagnoseRelation in reportDiagnoseRelations: if reportDiagnoseRelation.report.status != constant.ReportStatus.Del: if reportDiagnoseRelation.report.type == constant.ReportType.Doctor: print 'doctor report' #delete doctor report if exist # reportDiagnoseRelation.report.status = constant.ModelStatus.Del Report.update(reportDiagnoseRelation.report.id, status=constant.ReportStatus.Del) ReportDiagnoseRelation.update( reportDiagnoseRelation.id, status=constant.ModelStatus.Del) elif reportDiagnoseRelation.report.type == constant.ReportType.Admin: print 'admin report' #set diagnose report to admin report diagnose.reportId = reportDiagnoseRelation.report.id Diagnose.update(diagnose) return json.dumps(rs.SUCCESS.__dict__, ensure_ascii=False) else: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False)
def addOrUpdateReport(): userId = session['userId'] user = User.getById(userId) if user is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) #权限查看 if UserRole.checkRole(db_session, userId, constant.RoleId.Admin) == False: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False) form = ReportForm(request.form) formResult = form.validate() if formResult.status == rs.SUCCESS.status: diagnose = Diagnose.getDiagnoseById(form.diagnoseId) if diagnose is None: return json.dumps(rs.NO_DATA.__dict__, ensure_ascii=False) #session['remember_me'] = form.remember_me.data # login and validate the user... report = None if form.reportId: report = Report.getReportById(form.reportId) if report.type == constant.ReportType.Doctor: return json.dumps(rs.PERMISSION_DENY.__dict__, ensure_ascii=False) Report.update(form.reportId, None, form.status, None, form.techDesc, form.imageDesc, form.diagnoseDesc) else: report = Report(form.techDesc, form.imageDesc, form.diagnoseDesc, form.fileUrl, ReportType.Admin, form.status) Report.save(report) diagnose.reportId = report.id Diagnose.save(diagnose) #add report and diagnose to relation table reportDiagnoseRelation = ReportDiagnoseRelation( report.id, diagnose.id) ReportDiagnoseRelation.save(reportDiagnoseRelation) #flash('成功添加诊断评论') if form.status and form.status == constant.ReportStatus.Commited: diagnose = Diagnose.getDiagnoseById(form.diagnoseId) if diagnose: Diagnose.changeDiagnoseStatus( diagnose.id, constant.DiagnoseStatus.NeedDiagnose) if form.reportId is None and report: form.reportId = report.id #copy a report and add to relation table newReport = Report(form.techDesc, form.imageDesc, form.diagnoseDesc, form.fileUrl, ReportType.Doctor, constant.ReportStatus.Draft) Report.save(newReport) reportDiagnoseRelation = ReportDiagnoseRelation( newReport.id, diagnose.id) ReportDiagnoseRelation.save(reportDiagnoseRelation) diagnose.reportId = newReport.id Diagnose.save(diagnose) #end copy if diagnose and hasattr(diagnose, 'doctor'): doctor = diagnose.doctor if doctor and doctor.userId: content = dataChangeService.getDoctorNeedDiagnoseMessageContent( diagnose, doctor) #诊断通知 message = Message(constant.DefaultSystemAdminUserId, doctor.userId, '诊断通知', content, constant.MessageType.Diagnose) Message.save(message) #诊断日志 diagoseLog = DiagnoseLog( userId, form.diagnoseId, constant.DiagnoseLogAction.FetchDiagnoseEndAction) DiagnoseLog.save(db_session, diagoseLog) return json.dumps(formResult.__dict__, ensure_ascii=False) return json.dumps(formResult.__dict__, ensure_ascii=False)
def applyDiagnoseForm(formid): if (int(formid) == 1) : form = DiagnoseForm3(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if(form.diagnoseId): new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus(DiagnoseStatus.Draft, session['userId']) if(new_diagnose is None): new_diagnose = Diagnose() new_diagnose.status = DiagnoseStatus.Draft new_diagnose.doctorId = form.doctorId new_diagnose.uploadUserId = session['userId'] Diagnose.save(new_diagnose) form_result.data = {'formId': 2, 'diagnoseId': new_diagnose.id} return jsonify(form_result.__dict__) elif (int(formid) == 2) : form = DiagnoseForm1(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus(DiagnoseStatus.Draft, int(session['userId'])) if(new_diagnose is not None): # 去拿没有draft的用户 if(form.exist): new_patient = Patient.get_patient_by_id(form.patientid) else: new_patient = Patient.get_patient_draft(new_diagnose.patientId) if new_patient is None: new_patient = Patient() new_patient.type = PatientStatus.diagnose new_patient.userID = session['userId'] new_patient.realname = form.patientname new_patient.gender = form.patientsex new_patient.birthDate = datetime.strptime(form.birthdate, "%Y-%m-%d") new_patient.identityCode = form.identitynumber new_patient.locationId = form.locationId new_patient.identityPhone = form.phonenumber new_patient.status = ModelStatus.Draft # new_patient.locationId = form.location Patient.save(new_patient) new_diagnose.patientId = new_patient.id Diagnose.save(new_diagnose) # Hospital User 注册用户 if(form.isHospitalUser): new_user = User(form.phonenumber, random.sample('zyxwvutsrqponmlkjihgfedcba1234567890',6), False) new_user.type = UserStatus.patent new_user.status = ModelStatus.Draft User.save(new_user) new_patient.userID = new_user.id Patient.save(new_patient) new_userrole = UserRole(new_user.id, RoleId.Patient) UserRole.save(new_userrole) form_result.data = {'formId': 3, } else: form_result = ResultStatus(FAILURE.status, "找不到第一步草稿") return jsonify(form_result.__dict__) elif (int(formid) == 3): form = DiagnoseForm2(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus(DiagnoseStatus.Draft, int(session['userId'])) if new_diagnose is not None: if form.exist: new_pathology = Pathology.getById(form.pathologyId) elif new_diagnose.pathologyId: new_pathology = Pathology.getById(new_diagnose.pathologyId) else: new_pathology = Pathology.getByPatientStatus(session['userId'], ModelStatus.Draft) if new_pathology is None: new_pathology = Pathology(new_diagnose.patientId) new_pathology.diagnoseMethod = form.dicomtype new_pathology.status = ModelStatus.Draft new_pathology.save(new_pathology) PathologyPostion.deleteByPathologyId(new_pathology.id) for position in form.patientlocation: new_position_id = PathologyPostion(new_pathology.id, position) PathologyPostion.save(new_position_id) File.cleanDirtyFile(form.fileurl, new_pathology.id, FileType.Dicom) for fileurl in form.fileurl: new_file = File.getFilebyId(int(fileurl)) new_file.pathologyId = new_pathology.id File.save(new_file) new_diagnose.pathologyId = new_pathology.id Diagnose.save(new_diagnose) form_result.data = {'formId': 4} else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿") return jsonify(form_result.__dict__) elif (int(formid) == 4): form = DiagnoseForm4(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus(DiagnoseStatus.Draft, int(session['userId'])) if(new_diagnose is not None): new_pathology = Pathology.getById(new_diagnose.pathologyId) if(new_pathology is not None): new_pathology.caseHistory = form.illnessHistory new_pathology.hospitalId = form.hospitalId new_pathology.status = ModelStatus.Normal Pathology.save(new_pathology) File.cleanDirtyFile(form.fileurl, new_pathology.id, FileType.FileAboutDiagnose) for fileurl in form.fileurl: new_file = File.getFilebyId(int(fileurl)) new_file.pathologyId = new_pathology.id File.save(new_file) new_patient = Patient.get_patient_by_id(new_diagnose.patientId) new_patient.status = PatientStatus.diagnose new_diagnose.status = DiagnoseStatus.NeedPay Diagnose.save(new_diagnose) new_diagnoselog = DiagnoseLog(new_diagnose.uploadUserId, new_diagnose.id, DiagnoseLogAction.NewDiagnoseAction) DiagnoseLog.save(db_session, new_diagnoselog) else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿1") else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿2") form_result.data = {'isFinal': True} return jsonify(form_result.__dict__) else: return jsonify(ResultStatus(FAILURE.status, "错误的表单号").__dict__)
def generateAliPay(userId, diagnoseId, diagnose=None): if diagnoseId: diagnose = Diagnose.getDiagnoseById(diagnoseId) else: diagnose = Diagnose.getDiagnoseById(diagnose.id) if diagnoseId is None and diagnose: diagnoseId = diagnose.id if userId is None: LOG.warn("诊断生成阿里支付地址出错,用户未登录") if isinstance(userId, basestring): userId = string.atoi(userId) if diagnose is None: LOG.error("诊断[diagnoseId=%d]生成阿里支付地址出错,诊断在系统中不存在" % diagnoseId) if diagnose and diagnose.uploadUserId != userId: if hasattr(diagnose, 'patient') and userId != diagnose.patient.userID: LOG.error("诊断[diagnoseId=%d][userId=%d]生成阿里支付地址出错,用户没有权限" % (diagnoseId, userId)) if diagnose and diagnose.status == constant.DiagnoseStatus.NeedPay and diagnose.ossUploaded == constant.DiagnoseUploaed.Uploaded: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.StartApplyAlipay) AlipayLog.save(alipayLog) description = None needPay = None if hasattr(diagnose, 'pathology') and hasattr(diagnose.pathology, 'pathologyPostions'): if len(diagnose.pathology.pathologyPostions) > 0: if diagnose.pathology.diagnoseMethod == constant.DiagnoseMethod.Mri: needPay = diagnose.getPayCount( constant.DiagnoseMethod.Mri, len(diagnose.pathology.pathologyPostions), diagnose.getUserDiscount(diagnose.patientId)) elif diagnose.pathology.diagnoseMethod == constant.DiagnoseMethod.Ct: needPay = diagnose.getPayCount( constant.DiagnoseMethod.Ct, len(diagnose.pathology.pathologyPostions), diagnose.getUserDiscount(diagnose.patientId)) else: result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或这状态不对") return json.dumps(result.__dict__, ensure_ascii=False) else: result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或这状态不对") return json.dumps(result.__dict__, ensure_ascii=False) if hasattr(diagnose, 'doctor') and hasattr(diagnose.doctor, 'username'): description = ' 医生(%s)的诊断费用:%f 元' % (diagnose.doctor.username, needPay) if hasattr(diagnose.doctor.hospital, 'name'): description = diagnose.doctor.hospital.name + description payUrl = alipay.create_direct_pay_by_user( diagnose.diagnoseSeriesNumber, diagnose.diagnoseSeriesNumber, '咨询费', needPay) if payUrl: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.GetAlipayUrl) alipayLog.description = description alipayLog.payUrl = payUrl AlipayLog.save(alipayLog) updateDiagnose(diagnose.id, payUrl) LOG.info("诊断[diagnoseId=%d][userId=%d]生成阿里支付地址成功" % (diagnoseId, userId)) return payUrl else: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.GetAlipayUrlFailure) AlipayLog.save(alipayLog) LOG.error("诊断[diagnoseId=%d][userId=%d]生成阿里支付地址出错,去阿里获取的payurl为空" % (diagnoseId, userId)) LOG.error("诊断[diagnoseId=%d][userId=%d]生成阿里支付地址出错,其他未知原因" % (diagnoseId, userId))
def generateAlipayUrl(diagnoseId): if session.has_key('userId'): userId = session['userId'] if userId is None: return redirect(LOGIN_URL) diagnose = Diagnose.getDiagnoseById(diagnoseId) if diagnose and hasattr( diagnose, 'patient') and string.atoi(userId) != diagnose.patient.userID: result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或不是用户申请的") return json.dumps(result.__dict__, ensure_ascii=False) if diagnose and diagnose.status == constant.DiagnoseStatus.NeedPay and diagnose.ossUploaded == constant.DiagnoseUploaed.Uploaded: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.StartApplyAlipay) AlipayLog.save(alipayLog) description = None needPay = None if hasattr(diagnose, 'pathology') and hasattr(diagnose.pathology, 'pathologyPostions'): if len(diagnose.pathology.pathologyPostions) > 0: if diagnose.pathology.diagnoseMethod == constant.DiagnoseMethod.Mri: needPay = diagnose.getPayCount( constant.DiagnoseMethod.Mri, len(diagnose.pathology.pathologyPostions), diagnose.getUserDiscount(diagnose.patientId)) elif diagnose.pathology.diagnoseMethod == constant.DiagnoseMethod.Ct: needPay = diagnose.getPayCount( constant.DiagnoseMethod.Ct, len(diagnose.pathology.pathologyPostions), diagnose.getUserDiscount(diagnose.patientId)) else: result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或这状态不对") return json.dumps(result.__dict__, ensure_ascii=False) else: result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或这状态不对") return json.dumps(result.__dict__, ensure_ascii=False) if hasattr(diagnose, 'doctor') and hasattr(diagnose.doctor, 'username'): description = ' 医生(%s)的诊断费用:%f 元' % (diagnose.doctor.username, needPay) if hasattr(diagnose.doctor.hospital, 'name'): description = diagnose.doctor.hospital.name + description payUrl = alipay.create_direct_pay_by_user( diagnose.diagnoseSeriesNumber, diagnose.diagnoseSeriesNumber, '咨询费', needPay) if payUrl: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.GetAlipayUrl) alipayLog.description = description alipayLog.payUrl = payUrl AlipayLog.save(alipayLog) result = rs.ResultStatus(rs.SUCCESS.status, rs.SUCCESS.msg, payUrl) return json.dumps(result.__dict__, ensure_ascii=False) else: alipayLog = AlipayLog(userId, diagnoseId, constant.AlipayLogAction.GetAlipayUrlFailure) AlipayLog.save(alipayLog) result = rs.ResultStatus( rs.FAILURE.status, constant.AlipayLogAction.GetAlipayUrlFailure) return json.dumps(result.__dict__, ensure_ascii=False) result = rs.ResultStatus(rs.FAILURE.status, "诊断不存在或这状态不对") return json.dumps(result.__dict__, ensure_ascii=False)
def generatorHtml(diagnoseId, identityPhone): diagnose=Diagnose.getDiagnoseById(diagnoseId) report=None if hasattr(diagnose,'report'): report=diagnose.report if diagnose and report and report.type==constant.ReportType.Doctor: data={} data['techDesc']=report.techDesc data['imageDesc']=report.imageDesc data['diagnoseDesc']=report.diagnoseDesc data['seriesNumber']=report.seriesNumber data['fileUrl']=report.fileUrl if hasattr(diagnose,'diagnoseSeriesNumber'): data['diagnoseSN'] = diagnose.diagnoseSeriesNumber createDate=report.createDate if createDate: createDate=createDate.strftime('%Y-%m-%d') data['createDate']=createDate import DoctorSpring.views.data_change_service as dataChangeService postions=dataChangeService.getDiagnosePositonFromDiagnose(diagnose) if postions: data['postions']=postions if hasattr(diagnose,'patient') and diagnose.patient: data['gender']=diagnose.patient.gender birthDate=diagnose.patient.birthDate if birthDate: birthDate=birthDate.strftime('%Y-%m-%d') data['birthDate']=getAge(birthDate) data['name']=diagnose.patient.realname if hasattr(diagnose,'doctor'): data['doctorName']=diagnose.doctor.username if hasattr(diagnose,'adminId'): adminUser = User.getById(diagnose.adminId) if adminUser.name: data['adminName']= adminUser.name html = render_template('diagnoseResultPdf.html',data=data) fileName=constant.DirConstant.DIAGNOSE_PDF_DIR+'diagnose'+str(diagnoseId)+'Html.html' result = open(fileName, 'w+b') # Changed from file to filename result.write(html) result.close() fileLink = 'file://'+fileName pdfLink = constant.DirConstant.DIAGNOSE_PDF_DIR+'diagnose'+str(diagnoseId)+'Pdf.pdf' print fileLink print pdfLink returnCode = generate_pdf_from_html(fileLink,pdfLink) # return render_template("testpdf.html",getAvatar=getAvatar) if(returnCode == 0): #add encrypt for pdf output = PdfFileWriter() with open(pdfLink, "r+") as f1: input1 = PdfFileReader(f1) for i in range(input1.getNumPages()): output.addPage(input1.getPage(i)) #print(identityPhone) password = str(int(identityPhone)) owner_pwd = ''.join(random.choice(string.letters + string.digits) for _ in range(64)) #print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + owner_pwd) output.encrypt(password, owner_pwd) f1.seek(0) output.write(f1) f1.truncate() fileUrl=upload_pdf(pdfLink,diagnoseId) return fileUrl else: return None return None
def applyDiagnoseForm(formid): if (int(formid) == 1): form = DiagnoseForm3(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if (form.diagnoseId): new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus( DiagnoseStatus.Draft, session['userId']) if (new_diagnose is None): new_diagnose = Diagnose() new_diagnose.status = DiagnoseStatus.Draft new_diagnose.doctorId = form.doctorId new_diagnose.uploadUserId = session['userId'] Diagnose.save(new_diagnose) form_result.data = {'formId': 2, 'diagnoseId': new_diagnose.id} return jsonify(form_result.__dict__) elif (int(formid) == 2): form = DiagnoseForm1(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus( DiagnoseStatus.Draft, int(session['userId'])) if (new_diagnose is not None): needcreateNewUserByHospitalUser = True # 去拿没有draft的用户 if (form.exist): #select exist patient , from list, when modify exist diagnose new_patient = Patient.get_patient_by_id(form.patientid) else: #update draft patient when modify exist diagnose new_patient = Patient.getPatientDraftByPatienId( new_diagnose.patientId) if new_patient: new_patient.realname = form.patientname new_patient.gender = form.patientsex new_patient.birthDate = datetime.strptime( form.birthdate, "%Y-%m-%d") new_patient.identityCode = form.identitynumber new_patient.locationId = form.locationId new_patient.identityPhone = form.phonenumber Patient.save(new_patient) needcreateNewUserByHospitalUser = False #create a new patient if new_patient is None: new_patient = Patient() new_patient.type = PatientStatus.diagnose new_patient.userID = session['userId'] new_patient.realname = form.patientname new_patient.gender = form.patientsex new_patient.birthDate = datetime.strptime( form.birthdate, "%Y-%m-%d") new_patient.identityCode = form.identitynumber new_patient.locationId = form.locationId new_patient.identityPhone = form.phonenumber new_patient.status = ModelStatus.Draft # new_patient.locationId = form.location Patient.save(new_patient) new_diagnose.patientId = new_patient.id Diagnose.save(new_diagnose) # Hospital User 注册用户 if form.isHospitalUser and ( not form.exist) and needcreateNewUserByHospitalUser: userQuery = User.getByPhone(form.phonenumber) if userQuery.count() <= 0: passwd = random.sample( 'zyxwvutsrqponmlkjihgfedcba1234567890', 6) passwd = ''.join(passwd) new_user = User(form.patientname, form.phonenumber, passwd, True) new_user.type = UserStatus.patent new_user.status = ModelStatus.Normal User.save(new_user) new_patient.userID = new_user.id Patient.save(new_patient) new_userrole = UserRole(new_user.id, RoleId.Patient) UserRole.save(new_userrole) sendRegisterMobileMessage(session.get('userId'), new_diagnose, new_user.phone, passwd) else: new_patient.userID = userQuery.first().id Patient.save(new_patient) form_result.data = { 'formId': 3, } else: form_result = ResultStatus(FAILURE.status, "找不到第一步草稿") return jsonify(form_result.__dict__) elif (int(formid) == 3): form = DiagnoseForm2(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus( DiagnoseStatus.Draft, int(session['userId'])) if new_diagnose is not None: #直接选择的病例,不是新建或者更改 isExistingPathology = False if form.exist: new_pathology = Pathology.getById(form.pathologyId) isExistingPathology = True elif new_diagnose.pathologyId: new_pathology = Pathology.getById(new_diagnose.pathologyId) else: new_pathology = Pathology.getByPatientStatus( session['userId'], ModelStatus.Draft) if new_pathology is None: new_pathology = Pathology(new_diagnose.patientId) if not isExistingPathology: new_pathology.diagnoseMethod = form.dicomtype new_pathology.status = ModelStatus.Draft new_pathology.save(new_pathology) PathologyPostion.deleteByPathologyId(new_pathology.id) for position in form.patientlocation: new_position_id = PathologyPostion( new_pathology.id, position) PathologyPostion.save(new_position_id) File.cleanDirtyFile(form.fileurl, new_pathology.id, FileType.Dicom) if form.fileurl and len(form.fileurl) > 0: for fileurl in form.fileurl: new_file = File.getFilebyId(int(fileurl)) new_file.pathologyId = new_pathology.id File.save(new_file) new_diagnose.pathologyId = new_pathology.id Diagnose.save(new_diagnose) form_result.data = {'formId': 4} else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿") return jsonify(form_result.__dict__) elif (int(formid) == 4): form = DiagnoseForm4(request.form) form_result = form.validate() if form_result.status == rs.SUCCESS.status: if form.diagnoseId is not None: new_diagnose = Diagnose.getDiagnoseById(form.diagnoseId) else: new_diagnose = Diagnose.getNewDiagnoseByStatus( DiagnoseStatus.Draft, int(session['userId'])) if (new_diagnose is not None): new_pathology = Pathology.getById(new_diagnose.pathologyId) if (new_pathology is not None): new_pathology.caseHistory = form.illnessHistory new_pathology.hospitalId = form.hospitalId new_pathology.status = ModelStatus.Normal Pathology.save(new_pathology) File.cleanDirtyFile(form.fileurl, new_pathology.id, FileType.FileAboutDiagnose) if form.fileurl and len(form.fileurl) > 0: for fileurl in form.fileurl: new_file = File.getFilebyId(int(fileurl)) new_file.pathologyId = new_pathology.id File.save(new_file) new_patient = Patient.get_patient_by_id( new_diagnose.patientId) new_patient.status = PatientStatus.diagnose #add for need update scenario if new_diagnose.status == constant.DiagnoseStatus.NeedUpdate: new_diagnoselog = DiagnoseLog( new_diagnose.uploadUserId, new_diagnose.id, DiagnoseLogAction.DiagnoseNeedUpateRecommitAction) DiagnoseLog.save(db_session, new_diagnoselog) new_diagnose.status = DiagnoseStatus.Triaging Diagnose.save(new_diagnose) #hospitalUser type=1 else: if form.type == '1' and not checkFilesExisting( new_diagnose): new_diagnoselog = DiagnoseLog( new_diagnose.uploadUserId, new_diagnose.id, DiagnoseLogAction.NewDiagnoseAction) DiagnoseLog.save(db_session, new_diagnoselog) #update by lichuan , save diagnose and change to needPay new_diagnose.status = DiagnoseStatus.HospitalUserDiagnoseNeedCommit Diagnose.save(new_diagnose) #end update else: #产生alipay,发送短消息 userId = session.get('userId') new_diagnose.ossUploaded = constant.DiagnoseUploaed.Uploaded new_diagnose.status = DiagnoseStatus.NeedPay Diagnose.save(new_diagnose) sendAllMessage(userId, new_diagnose) else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿1") else: form_result = ResultStatus(FAILURE.status, "找不到上步的草稿2") form_result.data = {'isFinal': True} return jsonify(form_result.__dict__) else: return jsonify(ResultStatus(FAILURE.status, "错误的表单号").__dict__)