#region Copyright © 2015 CLIPSOFT Co.,Ltd. All Rights Reserved. // // All rights are reserved. Reproduction or transmission in whole or in part, // in any form or by any means, electronic, mechanical or otherwise, is // prohibited without the prior written consent of the copyright owner. // // Filename: ConsentSvc.asmx.cs // #endregion using System; using System.IO; using System.Text; using System.Xml; using System.Collections.Generic; using System.Web.Services; using System.Collections; using IBatisNet.DataMapper; using CLIP.eForm.Server.Data; using CLIP.eForm.Server.VO; using CLIP.eForm.Consent.Entity; using CLIP.eForm.Consent.Dac; using System.DirectoryServices; using System.Web.Script.Services; using System.IO.Compression; namespace CLIP.eForm.Consent.WebService { /// /// 전자 동의서 관련 웹서비스 /// /// ///

[설계자]

///

클립소프트 연구소 홍지철 (jchong@clipsoft.co.kr)

///

[원본 작성자]

///

클립소프트 기술부 이창훈 (chlee@clipsoft.co.kr)

///

[수정 작성자]

///

클립소프트 기술부 이인희

///

----------------------------------------------------------------------------------------

///

[HISTORY]

///

2016-06-15 : 최초작성

///

----------------------------------------------------------------------------------------

///
/// /// ConsentSvc의 요약 설명입니다. /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다. // [System.Web.Script.Services.ScriptService] public class ConsentSvc : System.Web.Services.WebService { private IBatisHelper _ibatisHelper; private static string tempImageDelStatus = string.Empty; public ConsentSvc() { _ibatisHelper = new IBatisHelper("ConsentSvcOracleMap.config"); } protected override void Dispose(bool disposing) { if (IbatisSession != null && IbatisSession.Transaction != null) { IbatisSession.CommitTransaction(); IbatisSession.CloseConnection(); } if (IbatisMapper != null) IbatisMapper.CloseConnection(); base.Dispose(disposing); } /// /// 현재 연결된 IBatis Connection을 반환 /// public ISqlMapper IbatisMapper { get { if (_ibatisHelper == null) { return null; } else { return _ibatisHelper.GetSqlMapper(); } } } /// /// 현재 연결된 ISqlMapSession 을 반환 /// public ISqlMapSession IbatisSession { get { if (_ibatisHelper == null) { return null; } else { return _ibatisHelper.GetMapSession(); } } } [WebMethod] public bool CheckWebService() { return true; } /// /// 경북대학교병원 출력 로그에 기록되지 않아야 할 목록 조회 /// /// /// [WebMethod(Description = "Type 6 인 동의서 조회")] public List getOcrType6Forms(string dutinstcd) { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable param = new Hashtable(); param.Add("instcd", dutinstcd); return (List) dac.getOcrType6Forms(this.IbatisMapper, param); } } [WebMethod] public bool CheckDatabaseConnection() { // TODO: 데이터 베이스 커넥션 테스트 호출 필요 return false; } /// /// 동의서 카테고리 조회 /// [WebMethod(Description = "동의서 카테고리 조회")] public List GetCategoryForDropdown() { List result; try { using (FormCategoryDac dac = new FormCategoryDac()) { Hashtable param = new Hashtable(); result = (List) dac.GetCategoryForDropdown(this.IbatisMapper, param); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetCategoryForDropdown error: {0}", ex.Message)); throw ex; } return result; } /// /// 환자, 상태에 따른 동의서 목록 검색 /// /// 환자등록번호 /// 사용자 아이디, 작성자별 조회시 pid는 입력하지 않고 userId만 보내줘야함 /// 데이터생성일자 조회 시작일 /// 조회 마지막 일자 (현재 일자를 넣음) /// 동의서 상태 /// 근무지기관코드 /// [WebMethod(Description = "환자/상태에 따른 동의서 목록 검색")] public List GetConsentList(string pid, string userId, string startDt, string endDt, string consentState, string instCd) { List result; try { // 임시저장 조회 시 미작성이 없으면 미작성 상태도 추가 if (!string.IsNullOrEmpty(consentState)) { bool _hasTemp = false; bool _hasUnfinished = false; string[] _stateArr = consentState.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in _stateArr) { if (s.Equals("TEMP")) { _hasTemp = true; } else if (s.Equals("UNFINISHED")) { _hasUnfinished = true; } } if (_hasTemp && !_hasUnfinished) { consentState += ",'UNFINISHED'"; } } using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable { { "pid", pid }, { "userId", userId }, { "startDt", startDt }, { "endDt", endDt }, { "consentState", consentState }, { "instCd", instCd } }; result = (List) dac.GetConsentList(this.IbatisMapper, param); } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentList error: {0}", ex.Message)); throw ex; } } /// /// 환자, 상태에 따른 동의서 목록 검색 /// /// 환자 조회에 들어가는 날짜, 검사 탭일때는 fromDt /// 환자등록번호 /// 사용자 아이디, 작성자별 조회시 pid는 입력하지 않고 userId만 보내줘야함 /// 데이터생성일자 조회 시작일 /// 조회 마지막 일자 (현재 일자를 넣음) /// 동의서 상태 /// 근무지기관코드 /// 의사 아이디 /// 진료과 코드 /// 환자 동의서 상태, ordType가 S 이면 patientState가 입원, 외래, 응급으로 구분한다 /// 입원(I), 외래(O), 응급(ER), 수술(OP), 검사(EX), 검색(S) 구분 코드 /// ordType가 입원일때 간호사, 의사 내환자 선택여부 /// 입원 일때 병동코드 /// 로그인 사용자 직종 구분 코드 A : 전문의, B : 주치의(교수), C : 그 외 직종 /// 검색탭 인지 구분 /// 검사탭 일때 시작일 /// 검사탭 일때 판독의 이름 /// 검사탭 일때 판독의, 예정 판독의 구분 Y : 예정 판독의, N : 판독의 /// 검사탭 일때 지원부서 베이스 코드 /// 검사탭 일때 지원부서 하위 코드 /// [WebMethod(Description = "날짜별 확인, 임시 동의서 리스트")] public List GetConsentDateList(string srchDd, string pid, string userId, string startDt, string endDt, string consentState, string instCd, string doctorId, string ordDeptCd, string patientState, string ordType, string myPatient, string wardCd, string drKind, string srchYN, string toDd, string mainDr, string mainDrChecked, string supportBaseCd, string supportDeptCd) { List result = null; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("srchDd -- > " + srchDd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("pid -- > " + pid); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("userId -- > " + userId); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("startDt -- > " + startDt); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("endDt -- > " + endDt); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("consentState -- > " + consentState); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("instCd -- > " + instCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("doctorId -- > " + doctorId); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("ordDeptCd -- > " + ordDeptCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("patientState -- > " + patientState); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("ordType -- > " + ordType); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("myPatient -- > " + myPatient); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("wardCd -- > " + wardCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("drKind -- > " + drKind); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("srchYN -- > " + srchYN); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("toDd -- > " + toDd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("mainDr -- > " + mainDr); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("mainDrChecked -- > " + mainDrChecked); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("supportBaseCd -- > " + supportBaseCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("supportDeptCd -- > " + supportDeptCd); try { // 임시저장 조회 시 미작성이 없으면 미작성 상태도 추가 if (!string.IsNullOrEmpty(consentState)) { bool _hasTemp = false; bool _hasUnfinished = false; string[] _stateArr = consentState.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in _stateArr) { if (s.Equals("TEMP")) { _hasTemp = true; } else if (s.Equals("UNFINISHED")) { _hasUnfinished = true; } } if (_hasTemp && !_hasUnfinished) { consentState += ",'UNFINISHED'"; } } if (ordType == "S") { ordType = patientState; } // 병동 일때 var myPatientFlag = myPatient ?? "N"; wardCd = wardCd ?? ""; userId = userId ?? ""; // 검색탭에서 쓰임 srchYN = srchYN ?? "N"; // 검사 일때 toDd = toDd ?? ""; mainDr = mainDr ?? ""; mainDrChecked = mainDrChecked ?? ""; supportBaseCd = supportBaseCd ?? ""; supportDeptCd = supportDeptCd ?? ""; using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("srchDd", srchDd); param.Add("pid", pid); param.Add("userId", userId); param.Add("startDt", startDt); param.Add("endDt", endDt); param.Add("consentState", consentState); param.Add("instCd", instCd); param.Add("doctorId", doctorId); param.Add("ordDeptCd", ordDeptCd); param.Add("patientState", patientState); param.Add("ordType", ordType); param.Add("myPatient", myPatientFlag); param.Add("wardCd", wardCd); param.Add("srchYN", srchYN); param.Add("drKind", drKind); param.Add("isMainD", mainDrChecked); param.Add("mainDrId", mainDr); param.Add("baseCd", supportBaseCd); param.Add("supportDeptCd", supportDeptCd); param.Add("toDt", toDd); param.Add("fromDt", srchDd); result = (List) dac.GetConsentDateList(this.IbatisMapper, param); } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentDateList error: {0}", ex.Message)); throw ex; } } /// /// 환자 목록에서 환자 선택시 환자 처방연동 서식 리스트 /// /// 환자 등록번호 /// 진료 일자 /// [WebMethod(Description = "환자 처방연동서식")] public List GetPrescriptionConsentList(string pid, string ordDd) { List result; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("pid", pid); param.Add("ordDd", ordDd); result = (List) dac.GetPrescriptionConsentList(this.IbatisMapper, param); } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetPrescriptionConsentList error: {0}", ex.Message)); throw ex; } } /// /// 동의서 찾기 /// /// 카테고리 ID 전체 : 빈값 /// 검색할 키워드 /// 근무지기관코드, 101, 031 /// 오늘 일자, 20190101 /// [WebMethod(Description = "동의서 찾기(조회)")] public List GetConsentBySearch(string categoryId, string keyWord, string instCd, string toDay) { List result; try { using (ConsentDac dac = new ConsentDac()) { keyWord = keyWord ?? ""; if (keyWord != "") { keyWord = string.Format("%{0}%", keyWord); } Hashtable param = new Hashtable(); param.Add("categoryId", categoryId); param.Add("keyWord", keyWord.ToUpper()); param.Add("instCd", instCd); param.Add("toDay", toDay); result = (List) dac.GetConsentBySearch(this.IbatisMapper, param); } //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(result); return result; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentBySearch error: {0}", ex.Message)); throw ex; } } /// /// 동의서 SET 조회 /// /// 사용자 아이디 107810 /// 근무지기관코드 /// 오늘 날짜 [WebMethod(Description = "동의서 SET 조회")] public List GetConsentSetList(string userId, string instCd, string toDay) { List result; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("instCd", instCd); param.Add("userId", userId); param.Add("toDay", toDay); result = (List) dac.GetConsentSetList(this.IbatisMapper, param); } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentSetList error: {0}", ex.Message)); throw ex; } } /// /// 동의서 찾기 /// /// 수가코드 /// //[WebMethod(Description = "동의서 찾기(수가코드)")] //public List GetConsentByCalcscorcd(string calcscorCd) { // List result; // try { // using (ConsentDac dac = new ConsentDac()) { // Hashtable param = new Hashtable(); // param.Add("calcscorcd", calcscorCd); // result = (List) dac.GetConsentByCalcscorcd(this.IbatisMapper, param); // } // return result; // } catch (Exception ex) { // System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentByCalcscorcd error: {0}", ex.Message)); // throw ex; // } //} /// /// 동의서 찾기 /// /// 서식코드 /// 근무지기관코드 /// ConsentBySearchVO 객체 List [WebMethod(Description = "동의서 찾기(서식코드)")] public List GetConsentByFormcd(string formCd, string instCd, string today) { List result; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); string formCdArr = ""; if(formCd.Length == 0) { return null; } string[] cdArr = formCd.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < cdArr.Length; i++) { formCdArr += string.Format("'{0}',", cdArr[i].Trim()); } formCdArr = formCdArr.Remove(formCdArr.Length - 1); param.Add("formcdarr", formCdArr); param.Add("instCd", instCd); param.Add("today", today); result = (List) dac.getConsentByFormcd(this.IbatisMapper, param); } return result; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentByFormcd error: {0}", ex.Message)); throw ex; } } /// /// 동의서 재인증 여부 /// /// 환자 등록번호 /// 진료 일자 /// 수진 일련번호 /// 내원 경로 입원 : I, 외래 : O, 응급 : ER, 수술 : OP, 검사 : EX /// 동의서 작성 일자 /// 사용자 아이디 [WebMethod(Description = "동의서 재인증 여부")] public SingleReturnData ReUseCertifyConsentFlag(string pid, string ordDd, string cretNo, string ordType, string recDd, string userId) { SingleReturnData rts = new SingleReturnData(); try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("vInstcd", "101"); param.Add("vPid", pid); param.Add("vOrddd", ordDd); param.Add("vCretno", cretNo); param.Add("vOrdtype", ordType); param.Add("vRecdd", recDd); param.Add("vUserid", userId); string result = dac.ReUseCertifyConsentFlag(this.IbatisMapper, param); rts.responseData = result; } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm ReUseCertifyConsentFlag error: {0}", ex.Message)); throw ex; } return rts; } /// /// 일괄인증 허용 사용자 여부 /// /// /// /// OK 일때 일괄인증 수행, 그외의 값은 일괄인증 허가되지 않음 [WebMethod(Description = "일괄인증 허용 사용자 여부")] public SingleReturnData getSaveAllFlag(string instcd, string userid) { //string retValue = string.Empty; SingleReturnData retValue = new SingleReturnData(); String result = ""; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("instcd", "101"); param.Add("userid", userid); result = dac.getSaveAllFlag(this.IbatisMapper, param); retValue.responseData = result; } }catch(Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm getSaveAllFlag error: {0}", e.Message)); } return retValue; } /// /// CONSENT_MST_RID를 갖고 저장된 동의서 이미지를 조회 /// /// 동의서 마스터 데이터 Rid [WebMethod(Description = "동의서 저장된 이미지 내역 조회")] public List GetConsentImage(string consentMstRid) { List result; try { using (ConsentDac dac = new ConsentDac()) { string remotePath = ""; Dictionary remoteData = remoteInfo(); Hashtable param = new Hashtable(); int consentMstRidInt = 0; int.TryParse(consentMstRid, out consentMstRidInt); param.Add("consent-mst-rid", consentMstRidInt); result = (List) dac.GetConsentImage(this.IbatisMapper, param); remotePath = result[0].imagePath; // 계정을 choiadmin 으로 가장한다 ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility(); var imResult = util.ImpersonationStart(remotePath, remoteData["NETDRV_USERID_ADMIN"], remoteData["NETDRV_PASSWORD_ADMIN"]); // for debug DirectoryInfo destDi = new DirectoryInfo(Server.MapPath("DataTempImage")); var destDirStr = destDi.ToString(); DirectoryInfo origDi = new DirectoryInfo(remotePath); // 해당 경로에 디렉토리가 없다면 생성하여 준다 if (!destDi.Exists) { destDi.Create(); } foreach (ConsentImageVO img in result) { var origFullPath = String.Format(@"{0}\{1}", origDi, img.imageFilename); var destFullPath = String.Format(@"{0}\{1}{2}", destDirStr, img.imageFilename, ".jpg"); try { // 파일이 존재하면 덮어 쓴다. File.Copy(origFullPath, destFullPath, true); } catch (Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("file copy error", e); } img.imagePath = "DataTempImage"; img.imageFilename = img.imageFilename + ".jpg"; } util.ImpersonationEnd(); } // ?? 왜 로컬에 있는 tempfile 들을 삭제할까? //int iResult = DeleteTempFile(); return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentImage error: {0}", ex.Message)); throw ex; } } [WebMethod(Description = "동의서 저장된 음성 녹음 파일 갯수 확인")] public SingleReturnData GetConsentAudioCount(string consentMstRid) { SingleReturnData rts = new SingleReturnData(); try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("consentMstRid", consentMstRid); int result = 0; result = (int) dac.GetConsentAudioCount(this.IbatisMapper, param); rts.responseData = Convert.ToString(result); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentAudio error: {0}", ex.Message)); throw ex; } return rts; } [WebMethod(Description = "동의서 저장된 음성 녹음 파일 내역 조회")] public List GetConsentAudio(string consentMstRid) { List result; try { using (ConsentDac dac = new ConsentDac()) { string remotePath = ""; Dictionary remoteData = remoteInfo(); Hashtable param = new Hashtable(); int consentMstRidInt = 0; int.TryParse(consentMstRid, out consentMstRidInt); param.Add("consentMstRid", consentMstRid); result = (List) dac.getConsentAudio(this.IbatisMapper, param); if(result.Count > 0) { remotePath = result[0].imagePath; ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility(); var imResult = util.ImpersonationStart(remotePath, remoteData["NETDRV_USERID_ADMIN"], remoteData["NETDRV_PASSWORD_ADMIN"]); DirectoryInfo destDi = new DirectoryInfo(Server.MapPath("DataTempImage")); var destDirStr = destDi.ToString(); DirectoryInfo origDi = new DirectoryInfo(remotePath); // 해당 경로에 디렉토리가 없다면 생성하여 준다 if (!destDi.Exists) { destDi.Create(); } foreach (ConsentImageVO img in result) { var origFullPath = String.Format(@"{0}\{1}", origDi, img.imageFilename); var destFullPath = String.Format(@"{0}\{1}{2}", destDirStr, img.imageFilename, ".mp4"); try { File.Copy(origFullPath, destFullPath, true); } catch (Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("file copy error", e); } img.imagePath = "DataTempImage"; img.imageFilename = img.imageFilename + ".mp4"; } util.ImpersonationEnd(); } } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentAudio error: {0}", ex.Message)); throw ex; } } /// /// 임시저장 동의서 삭제 /// /// /// /// [WebMethod(Description = "임시저장 동의서 삭제")] public SingleReturnData saveDelete(string userId, string consentMstRid, string reasonForUseN) { SingleReturnData rts = new SingleReturnData(); int result = 0; string ocrTag = ""; try { if (this.IbatisSession.IsTransactionStart == false) { this.IbatisSession.BeginTransaction(); } using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable param = new Hashtable(); param.Add("userId", userId); param.Add("consentMstRid", consentMstRid); param.Add("reasonForUseN", reasonForUseN); ocrTag = dac.UpdateConsentMstForDelete(this.IbatisMapper, param); if (!string.IsNullOrEmpty(ocrTag)) { param.Add("ocrTag", ocrTag); result = dac.UpdateMrfhocrprntStatCd(this.IbatisMapper, param); } rts.responseData = Convert.ToString(result); } if (this.IbatisSession != null) this.IbatisSession.CommitTransaction(); } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm saveDelete ERROR : [{0}]", ex.ToString())); throw ex; } return rts; } /// /// 임시저장, 확인저장 /// /// 로그인 사용자ID /// 로그인 사용자 부서 코드 /// 환자 등록번호 /// 서식 ID /// 서식 코드 /// 환자가 내원한, 속해있는 부서 코드 /// 서식 정보 /// 사용자가 작성한 서식 내용 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원 구분 입원 : I, 외래 : O, 수술 : OP, 응급 : ER /// 근무지 기관코드 /// 내원 일자 입원 : inDd, 외래 : ordDd /// 병동 /// 병실 /// ocrTag /// 생성번호 /// 환자를 담당하는 의사(담당교수, 주치의, 담당의사 등) /// 동의서 총 장수 /// 임시저장 : T, 인증저장 : C /// 수술번호 /// 동의서 상태 /// 처방번호 20190822 원형만 유지하되 당장 사용하지 않음 /// 처방 이름 20190822 원형만 유지하되 당장 사용하지 않음 /// 처방 코드? 20190822 원형만 유지하되 당장 사용하지 않음 /// 음성녹음 바이너리 데이터 /// 음성녹음 파일 사이즈 /// 이미지 바이너리 데이터 /// 이미지 파일 사이즈 /// [WebMethod(Description = "동의서 임시저장")] public SingleReturnData SaveTempData(string userId, string userDeptCd, string pid, string formId, string formCd, string patientDeptCd, string formXml, string dataXml, int consentMstRid, int reWriteConsentMstRid, string deviceType, string deviceMacAddr, string ordType, string instCd, string inDd, string dSchDd, string ward, string roomCd, string ocrTag, int cretNo, string mainDrId, string formPageCnt, string actionKind, string opRsrvNo, string consentState, int orderNo, string orderName, string orderCd, string audioFileJson, string audioFileSize, string imageFileJson, string fileSize) { SingleReturnData result = new SingleReturnData(); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(String.Format("userId -- > [{0}]", userId)); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("userDeptCd -- > " + userDeptCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("pid -- > " + pid); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("formId -- > " + formId); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("formCd -- > " + formCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("patientDeptCd -- > " + patientDeptCd); ////CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("formXml -- > " + formXml); ////CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("dataXml -- > " + dataXml); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("consentMstRid -- > " + consentMstRid); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("reWriteConsentMstRid -- > " + reWriteConsentMstRid); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("deviceType -- > " + deviceType); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("deviceMacAddr -- > " + deviceMacAddr); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("ordType -- > " + ordType); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("instCd -- > " + instCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("inDd -- > " + inDd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("ward -- > " + ward); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("roomCd -- > " + roomCd); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("ocrTag -- > " + ocrTag); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("cretNo -- > " + cretNo); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("mainDrId -- > " + mainDrId); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("formPageCnt -- > " + formPageCnt); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("actionKind -- > " + actionKind); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("opRsrvNo -- > " + opRsrvNo); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("consentState -- > " + consentState); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("orderNo -- > " + orderNo); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("orderName -- > " + orderName); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("orderCd -- > " + orderCd); consentMstRid = SaveData(userId, userDeptCd, pid, formId, formCd, patientDeptCd, formXml, dataXml, consentMstRid, reWriteConsentMstRid, deviceType, deviceMacAddr, ordType, instCd, inDd, dSchDd, ward, roomCd, ocrTag, cretNo, mainDrId, formPageCnt, actionKind, opRsrvNo, consentState, orderNo, orderName, orderCd, audioFileJson, audioFileSize, imageFileJson, fileSize); result.responseData = Convert.ToString(consentMstRid); return result; } public int SaveData(string userId, string userDeptCd, string pid, string formId, string formCd, string patientDeptCd, string formXml, string dataXml, int consentMstRid, int reWriteConsentMstRid, string deviceType, string deviceMacAddr, string ordType, string instCd, string inDd, string dSchDd, string ward, string roomCd, string ocrTag, int cretNo, string mainDrId, string formPageCnt, string actionKind, string opRsrvNo, string consentState, int orderNo, string orderName, string orderCd, string audioFileJson, string audioFileSize, string imageFileJson, string fileSize) { bool isNewConsentMasterCase = false; if (consentMstRid < 1) { isNewConsentMasterCase = true; } if (this.IbatisSession.IsTransactionStart == false) { this.IbatisSession.BeginTransaction(); } try { using (SaveConsentDac dac = new SaveConsentDac()) { int updateResult = 0; int deleteResult = 0; Hashtable imrParam = new Hashtable(); imrParam.Add("ocrTag", "'" + ocrTag + "%'"); int imrCount = (int) dac.ImrCount(this.IbatisMapper, imrParam); ImrData imrData = new ImrData(); if (imrCount > 0) { imrData = (ImrData) dac.ImrData(this.IbatisMapper, imrParam); } Hashtable paramHashTable = GetParamHashTable(userId, userDeptCd, pid, formId, formCd, patientDeptCd, formXml, dataXml, consentMstRid, reWriteConsentMstRid, deviceType, deviceMacAddr, ordType, instCd, inDd, ward, roomCd, ocrTag, cretNo, mainDrId, formPageCnt, actionKind, opRsrvNo, consentState, orderNo, orderName, orderCd, null, null); //reasonForUseN paramHashTable.Add("macAddress", deviceMacAddr); consentMstRid = (int) paramHashTable["consentMstRid"]; if (isNewConsentMasterCase == true) { dac.InsertConsentMst(this.IbatisMapper, paramHashTable); dac.InsertConsentData(this.IbatisMapper, paramHashTable); } else { dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); dac.UpdateConsentData(this.IbatisMapper, paramHashTable); } if (!string.IsNullOrEmpty(audioFileJson)) { audioUpLoad(dac, paramHashTable, userId, consentMstRid, formId, audioFileJson, audioFileSize, ocrTag, pid); } if (!string.IsNullOrEmpty(imageFileJson)) { imageUpload(dac, paramHashTable, userId, pid, ordType, inDd, dSchDd, cretNo, ocrTag, consentMstRid, consentState, formCd, formId, dataXml, imageFileJson, instCd, patientDeptCd, fileSize); } if (imrCount > 0) { String[] strAr = imrData.fileName.Split(new char[] { '_' }); imrData.fileName = strAr[0] + "_" + strAr[1]; imrParam.Add("fileName", "'" + imrData.fileName + "%'"); imrParam.Add("inputDate", imrData.inputDate); imrParam.Add("userId", imrData.userId); updateResult = dac.ImrScanFileUpdate(this.IbatisMapper, imrParam); if (updateResult > 0) { deleteResult = dac.ImrScanFileDelete(this.IbatisMapper, imrParam); } if (imrCount != deleteResult) { throw new Exception(); } } Hashtable ocrParam = new Hashtable { { "instcd", instCd }, { "ocrtag", ocrTag }, { "pid", pid }, { "ordtype", ordType }, { "orddd", inDd }, { "cretno", cretNo }, { "orddrid", mainDrId }, { "orddeptcd", patientDeptCd }, { "formcd", formCd }, { "fstprntdeptcd", userDeptCd }, { "fstprntid", userId }, { "updtdeptcd", userDeptCd }, { "updtuserid", userId }, { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")}, { "pagecnt", formPageCnt }, //{ "updtresncnts", reasonForUseN }, { "actkind", actionKind }, { "clienttype", "M" } }; dac.InsertPrintData(this.IbatisMapper, ocrParam); if (this.IbatisSession != null) this.IbatisSession.CommitTransaction(); } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveData ERROR : [{0}]", ex.ToString())); throw ex; } return consentMstRid; } private void audioUpLoad(SaveConsentDac dac, Hashtable paramHashTable, string userId, int consentMstRid, string formId, string audioFileJson, string audioFileSize, string ocrTag, string pid) { Dictionary remoteData = remoteInfo(); try { string[] fileSizeAr = audioFileSize.Split(new char[] { ',' }); int consentImageRid = this.GetSequence("CONSENT_AUDIO"); string sPath = string.Empty; string sFileName = string.Empty; Dictionary jsonRoot = null; jsonRoot = fastJSON.JSON.Parse(audioFileJson) as Dictionary; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("fileSize -- > " + audioFileSize); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("audioFileJson -- > " + audioFileJson); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("jsonRoot -- > " + jsonRoot); if (jsonRoot != null && jsonRoot.Count > 0) { Hashtable audioHashTable = null; int nowCnt = 1; int audioCnt = 1; foreach (KeyValuePair jr in jsonRoot) { audioHashTable = new Hashtable(); audioHashTable.Add("consentMstRid", consentMstRid); if (nowCnt > 1) { consentImageRid = this.GetSequence("CONSENT_AUDIO"); } audioHashTable.Add("consentImageRid", consentImageRid); audioHashTable.Add("userId", userId); audioHashTable.Add("formId", formId); if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) { sPath = ""; sFileName = ""; string[] filePath = jr.Value.ToString().Split('/'); for (int i = 0; i < filePath.Length; i++) { if (i == 0) { sPath = filePath[i]; } else if ((i + 1) == filePath.Length) { sFileName = filePath[i]; } else { sPath += "/" + filePath[i]; } } var date = DateTime.Now.ToString("yyyyMM"); var uniqDatetime = DateTime.Now.ToString("yyyyMMddhhmmss"); string uploadFileName = "audio_" + uniqDatetime + "_" + ocrTag + "_" + audioCnt; string sUploadPath = uploadFileName.Substring(4, 4); string sUploadFileName = uploadFileName.Substring(uploadFileName.LastIndexOf("\\") + 1); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("uploadFileName -- > " + uploadFileName); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("sUploadPath -- > " + sUploadPath); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("sUploadFileName -- > " + sUploadFileName); audioCnt++; //var remotePath = remoteData["IMAGEPATH"] + "\\temp_" + remoteData["PATH_IMGDATA"] + "\\" + date + "\\" + pid; var remotePath = remoteData["IMAGEPATH"] + "\\" + remoteData["PATH_IMGDATA"] + "\\" + date + "\\" + pid; ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility(); var imResult = util.ImpersonationStart(remotePath, remoteData["NETDRV_USERID_ADMIN"], remoteData["NETDRV_PASSWORD_ADMIN"]); DirectoryInfo destDi = new DirectoryInfo(remotePath); string destDirStr = destDi.Name; var destFullname = String.Format(@"{0}\{1}", remotePath, sUploadFileName); var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath, sFileName)); if (!destDi.Exists) { destDi.Create(); } try { File.Copy(localFile, destFullname, true); } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm audioUpLoad fileCopy ERROR : [{0}]", ex.ToString())); throw ex; } util.ImpersonationEnd(); audioHashTable.Add("audioPath", remotePath); audioHashTable.Add("audioFilename", sUploadFileName); audioHashTable.Add("completeYn", paramHashTable["completeYn"]); dac.InsertConsentAudio(this.IbatisMapper, audioHashTable); } } nowCnt++; } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm audioUpLoad ERROR : [{0}]", ex.ToString())); throw ex; } } private Hashtable GetParamHashTable(string userId, string userDeptCd, string pid, string formId, string formCd, string patientDeptCd, string formXml, string dataXml, int consentMstRid, int reWriteConsentMstRid, string deviceType, string deviceMacAddr, string ordType, string instCd, string inDd, string ward, string roomCd, string ocrTag, int cretNo, string mainDrId, string formPageCnt, string actionKind, string opRsrvNo, string consentState, int orderNo, string orderName, string orderCd, string certResult, string certTarget) { Hashtable paramHashTable = new Hashtable(); paramHashTable.Add("userId", userId); if (consentMstRid < 1) { consentMstRid = this.GetSequence("CONSENT_MST"); } paramHashTable.Add("consentMstRid", consentMstRid); paramHashTable.Add("patientCode", pid); paramHashTable.Add("clnDeptCd", patientDeptCd); paramHashTable.Add("vistType", ordType); paramHashTable.Add("hosType", instCd); paramHashTable.Add("clnDate", inDd); paramHashTable.Add("ward", ward); paramHashTable.Add("roomcd", roomCd); paramHashTable.Add("orderNo", orderNo); paramHashTable.Add("orderName", orderName); paramHashTable.Add("orderCd", orderCd); paramHashTable.Add("ocrCode", ocrTag); paramHashTable.Add("cretno", cretNo); paramHashTable.Add("createUserName", userId); paramHashTable.Add("modifyUserName", userId); paramHashTable.Add("formRid", formId); paramHashTable.Add("formCd", formCd); paramHashTable.Add("consentState", consentState); paramHashTable.Add("certTarget", certTarget); // TODO 원무 pass paramHashTable.Add("certResult", certResult); // TODO 원무 pass paramHashTable.Add("mainDrId", mainDrId); paramHashTable.Add("opRsrvNo", opRsrvNo ?? string.Empty); string completeYn = "N"; // 완료 여부 switch (consentState) { case "ELECTR_CMP": case "CERTIFY_CMP": completeYn = "Y"; break; default: break; } paramHashTable.Add("completeYn", completeYn); string completeDateTimeToChars = string.Empty; if (completeYn.Equals("Y")) { completeDateTimeToChars = "TO_CHAR(SYSDATE,'YYYY-MM-DD hh24:mi:ss')"; paramHashTable.Add("completeDateTimeToChars", completeDateTimeToChars); } else { paramHashTable.Add("completeDateTimeToChars", "''"); } string rewriteYn = "N"; // 재 작성 여부 if (reWriteConsentMstRid > 1) { rewriteYn = "Y"; } paramHashTable.Add("rewriteYn", rewriteYn); paramHashTable.Add("rewriteConsentMstRid", reWriteConsentMstRid); int consentDataRid = this.GetSequence("CONSENT_DATA"); paramHashTable.Add("consentDataRid", consentDataRid); paramHashTable.Add("useYn", "Y"); Encoding encoding = Encoding.GetEncoding("UTF-8"); byte[] formBytesConent = null; if (!string.IsNullOrEmpty(formXml)) { formBytesConent = encoding.GetBytes(formXml); } byte[] dataBytesConent = null; if (!string.IsNullOrEmpty(dataXml)) { dataBytesConent = encoding.GetBytes(dataXml); } paramHashTable.Add("formXml", formBytesConent); paramHashTable.Add("dataXml", dataBytesConent); paramHashTable.Add("deviceType", deviceType); paramHashTable.Add("deviceMacAddr", deviceMacAddr); paramHashTable.Add("pageCnt", formPageCnt); //paramHashTable.Add("reasonForUseN", reasonForUseN); return paramHashTable; } /// /// 일괄인증저장 /// /// 사용자 아이디 /// 사용자 이름 /// macAddress /// 일괄인증저장 되어야할 데이터 json string |%%|로 붙어서 나옴 [WebMethod(Description = "일괄 인증저장")] public SingleReturnData SaveAutoCompleteAll(string userId, string userName, string macAddress, string json) { SingleReturnData result = new SingleReturnData(); string success = "false"; int updateResult = 0; try { if (!string.IsNullOrEmpty(json)) { using (SaveConsentDac dac = new SaveConsentDac()) { if (this.IbatisSession.IsTransactionStart == false) { this.IbatisSession.BeginTransaction(); } string[] separatingStrings = { "|%%|" }; string[] jsonAr = json.Split(separatingStrings, System.StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < jsonAr.Length; i++) { string jsonData = jsonAr[i]; Dictionary jsonRoot = fastJSON.JSON.Parse(jsonData) as Dictionary; ; if (jsonRoot != null && jsonRoot.Count > 0) { Hashtable dataTable = new Hashtable(); string idx = jsonRoot["idx"].ToString(); string consentMstRid = jsonRoot["consentMstRid"].ToString(); string pid = jsonRoot["pid"].ToString(); string ocrTag = jsonRoot["ocrTag"].ToString(); string deptCd = jsonRoot["deptCd"].ToString(); dataTable.Add("userId", userId); dataTable.Add("userName", userName); dataTable.Add("idx", idx); dataTable.Add("consentMstRid", consentMstRid); dataTable.Add("consentState", "CERTIFY_CMP"); dataTable.Add("pid", pid); dataTable.Add("ocrTag", ocrTag); dataTable.Add("deptCd", deptCd); dataTable.Add("updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")); dataTable.Add("macAddress", macAddress); updateResult = dac.SaveAutoCompleteAll(this.IbatisMapper, dataTable); if (updateResult < 0) { new Exception(); } } } } success = "true"; if (this.IbatisSession != null) this.IbatisSession.CommitTransaction(); } } catch (Exception ex) { success = "false"; if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveAutoCompleteAll ERROR : [{0}]", ex.ToString())); } //if (!string.IsNullOrEmpty(json)) { //Dictionary jsonRoot = null; //jsonRoot = fastJSON.JSON.Parse(json) as Dictionary; // if (jsonRoot != null && jsonRoot.Count > 0) { // Hashtable imageHashTable = new Hashtable(); // foreach (KeyValuePair jr in jsonRoot) { // int i = 0; // } // } //} result.responseData = success; return result; } [WebMethod(Description = "테스트")] public ImrData imrTest() { int imrCount = 0; ImrData imrData = new ImrData(); try { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable imrParam = new Hashtable(); //var pValue = ocr + "%; imrParam.Add("ocrTag", "'2019121952292%'"); imrParam.Add("inputDate", "20191219 10:11:53"); imrParam.Add("userId", "E00004"); imrData = (ImrData) dac.ImrData(this.IbatisMapper, imrParam); String[] strAr = imrData.fileName.Split(new char[] { '_' }); imrData.fileName = strAr[0] + "_" + strAr[1]; imrParam.Add("fileName", "'" + imrData.fileName + "%'"); int result = dac.ImrScanFileDelete(this.IbatisMapper, imrParam); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("result -- > " + result); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveDataAll ERROR : [{0}]", ex.ToString())); } return imrData; } /// /// 임시저장, 확인저장 /// /// 로그인 사용자ID /// 로그인 사용자 부서 코드 /// 환자 등록번호 /// 서식 ID /// 서식 코드 /// 환자가 내원한, 속해있는 부서 코드 /// 서식 정보 /// 사용자가 작성한 서식 내용 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원 구분 입원 : I, 외래 : O, 수술 : OP, 응급 : ER /// 근무지 기관코드 /// 내원 일자 입원 : inDd, 외래 : ordDd /// 병동 /// 병실 /// ocrTag /// 생성번호 /// 환자를 담당하는 의사(담당교수, 주치의, 담당의사 등) /// 동의서 총 장수 /// 임시저장 : T, 인증저장 : C /// 수술번호 /// 동의서 상태 /// 처방번호 20190822 원형만 유지하되 당장 사용하지 않음 /// 처방 이름 20190822 원형만 유지하되 당장 사용하지 않음 /// 처방 코드? 20190822 원형만 유지하되 당장 사용하지 않음 /// 이미지 파일 정보(전자동의서 서버) /// 이미지 파일 사이즈(전자동의서 서버) /// 오디오 파일 정보(전자동의서 서버) /// 오디오 파일 사이즈 [WebMethod(Description = "동의서 서명 완료")] public SingleReturnData SaveCompleteAll(string userId, string userDeptCd, string pid, string formId, string formCd, string patientDeptCd, string formXml, string dataXml, int consentMstRid, int reWriteConsentMstRid, string deviceType, string deviceMacAddr, string ordType, string instCd, string inDd, string dSchDd, string ward, string roomCd, string ocrTag, int cretNo, string mainDrId, string formPageCnt, string actionKind, string opRsrvNo, string consentState, int orderNo, string orderName, string orderCd, string imageFileJson, string fileSize, string certResult, string certTarget, string audioFileJson, string audioFileSize) { SingleReturnData result = new SingleReturnData(); consentMstRid = SaveDataAll(userId, userDeptCd, pid, formId, formCd, patientDeptCd, formXml, dataXml, consentMstRid, reWriteConsentMstRid, deviceType, deviceMacAddr, ordType, instCd, inDd, dSchDd, ward, roomCd, ocrTag, cretNo, mainDrId, formPageCnt, actionKind, opRsrvNo, consentState, orderNo, orderName, orderCd, imageFileJson, fileSize, certResult, certTarget, audioFileJson, audioFileSize, out int rslt); result.responseData = Convert.ToString(rslt); return result; } public int SaveDataAll(string userId, string userDeptCd, string pid, string formId, string formCd, string patientDeptCd, string formXml, string dataXml, int consentMstRid, int reWriteConsentMstRid, string deviceType, string deviceMacAddr, string ordType, string instCd, string inDd, string dSchDd, string ward, string roomCd, string ocrTag, int cretNo, string mainDrId, string formPageCnt, string actionKind, string opRsrvNo, string consentState, int orderNo, string orderName, string orderCd, string imageFileJson, string fileSize, string certResult, string certTarget, string audioFileJson, string audioFileSize, out int result) { bool isNewConsentMasterCase = false; if (consentMstRid < 1) { isNewConsentMasterCase = true; } if (this.IbatisSession.IsTransactionStart == false) { this.IbatisSession.BeginTransaction(); } try { using (SaveConsentDac dac = new SaveConsentDac()) { int updateResult = 0; int deleteResult = 0; Hashtable imrParam = new Hashtable(); imrParam.Add("ocrTag", "'" + ocrTag + "%'"); int imrCount = (int) dac.ImrCount(this.IbatisMapper, imrParam); ImrData imrData = new ImrData(); if (imrCount > 0) { imrData = (ImrData) dac.ImrData(this.IbatisMapper, imrParam); } Hashtable paramHashTable = GetParamHashTable(userId, userDeptCd, pid, formId, formCd, patientDeptCd, formXml, dataXml, consentMstRid, reWriteConsentMstRid, deviceType, deviceMacAddr, ordType, instCd, inDd, ward, roomCd, ocrTag, cretNo, mainDrId, formPageCnt, actionKind, opRsrvNo, consentState, orderNo, orderName, orderCd, certResult, certTarget); paramHashTable.Add("macAddress", deviceMacAddr); consentMstRid = (int) paramHashTable["consentMstRid"]; result = consentMstRid; if (isNewConsentMasterCase == true) { dac.InsertConsentMst(this.IbatisMapper, paramHashTable); dac.InsertConsentData(this.IbatisMapper, paramHashTable); imageUpload(dac, paramHashTable, userId, pid, ordType, inDd, dSchDd, cretNo, ocrTag, consentMstRid, consentState, formCd, formId, dataXml, imageFileJson, instCd, patientDeptCd, fileSize); } else { if (consentState == "CERTIFY_CMP" && reWriteConsentMstRid > 0) { int newConsentMstRid = this.GetSequence("CONSENT_MST"); paramHashTable["rewriteConsentMstRid"] = newConsentMstRid; dac.ReWriteUpdateConsentMst(this.IbatisMapper, paramHashTable); consentMstRid = newConsentMstRid; paramHashTable["consentMstRid"] = consentMstRid; paramHashTable["rewriteYn"] = "N"; paramHashTable["useYn"] = "Y"; paramHashTable["rewriteConsentMstRid"] = 0; dac.InsertConsentMst(this.IbatisMapper, paramHashTable); dac.InsertConsentData(this.IbatisMapper, paramHashTable); imageUpload(dac, paramHashTable, userId, pid, ordType, inDd, dSchDd, cretNo, ocrTag, consentMstRid, consentState, formCd, formId, dataXml, imageFileJson, instCd, patientDeptCd, fileSize); } else { dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); dac.UpdateConsentData(this.IbatisMapper, paramHashTable); imageUpload(dac, paramHashTable, userId, pid, ordType, inDd, dSchDd, cretNo, ocrTag, consentMstRid, consentState, formCd, formId, dataXml, imageFileJson, instCd, patientDeptCd, fileSize); } } if (!string.IsNullOrEmpty(audioFileJson)) { audioUpLoad(dac, paramHashTable, userId, consentMstRid, formId, audioFileJson, audioFileSize, ocrTag, pid); } if (imrCount > 0) { String[] strAr = imrData.fileName.Split(new char[] { '_' }); imrData.fileName = strAr[0] + "_" + strAr[1]; imrParam.Add("fileName", "'" + imrData.fileName + "%'"); imrParam.Add("inputDate", imrData.inputDate); imrParam.Add("userId", imrData.userId); updateResult = dac.ImrScanFileUpdate(this.IbatisMapper, imrParam); if (updateResult > 0) { deleteResult = dac.ImrScanFileDelete(this.IbatisMapper, imrParam); } if (imrCount != deleteResult) { throw new Exception(); } } Hashtable ocrParam = new Hashtable { { "instcd", instCd }, { "ocrtag", ocrTag }, { "pid", pid }, { "ordtype", ordType }, { "orddd", inDd }, { "cretno", cretNo }, { "orddrid", mainDrId }, { "orddeptcd", patientDeptCd }, { "formcd", formCd }, { "fstprntdeptcd", userDeptCd }, { "fstprntid", userId }, { "updtdeptcd", userDeptCd }, { "updtuserid", userId }, { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")}, { "pagecnt", formPageCnt }, //{ "updtresncnts", reasonForUseN }, { "actkind", actionKind }, { "clienttype", "M" } }; dac.InsertPrintData(this.IbatisMapper, ocrParam, isNewConsentMasterCase); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("formCd -- > " + formCd); if (formCd == "1200005463" || formCd == "1800014564") { SavePatientConsentInfo(formCd, pid, ocrTag, userId, dataXml); } if (this.IbatisSession != null) this.IbatisSession.CommitTransaction(); } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveDataAll ERROR : [{0}]", ex.ToString())); result = -1; throw ex; } return result; } private void imageUpload(SaveConsentDac dac, Hashtable paramHashTable, string userId, string pid, string ordType, string inDd, string dSchDd, int cretNo, string ocrTag, int consentMstRid, string consentState, string formCd, string formId, string dataXml, string imageFileJson, string instCd, string deptCd, string fileSize) { //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("imageUpload"); // 서명 저장일 경우 emrindxm 테이블에 저장 if (!string.IsNullOrEmpty(consentState) && (consentState.Equals("ELECTR_CMP") || consentState.Equals("CERTIFY_CMP"))) { // 진료과 코드 string clnDeptCode = paramHashTable["clnDeptCd"] == null ? string.Empty : paramHashTable["clnDeptCd"].ToString(); Dictionary remoteData = remoteInfo(); string[] fileSizeAr = fileSize.Split(new char[] { ',' }); try { int consentImageRid = this.GetSequence("CONSENT_IMAGE"); int firstImageRid = consentImageRid; string sPath = string.Empty; string sFileName = string.Empty; //string newFileFullName = string.Empty; if (!string.IsNullOrEmpty(imageFileJson)) { Dictionary jsonRoot = null; jsonRoot = fastJSON.JSON.Parse(imageFileJson) as Dictionary; if (jsonRoot != null && jsonRoot.Count > 0) { Hashtable imageHashTable = new Hashtable(); int nowCnt = 1; int pageNum = 1; int fileSizeCnt = 0; var date = DateTime.Now.ToString("yyyyMM"); var uniqDatetime = DateTime.Now.ToString("yyyyMMddhhmmss"); foreach (KeyValuePair jr in jsonRoot) { imageHashTable = new Hashtable(); imageHashTable.Add("consentMstRid", consentMstRid); if (nowCnt > 1) { consentImageRid = this.GetSequence("CONSENT_IMAGE"); } imageHashTable.Add("consentImageRid", consentImageRid); imageHashTable.Add("userId", userId); imageHashTable.Add("formRid", formId); if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) { sPath = ""; sFileName = ""; string[] filePath = jr.Value.ToString().Split('/'); for (int i = 0; i < filePath.Length; i++) { if (i == 0) { sPath = filePath[i]; } else if ((i + 1) == filePath.Length) { sFileName = filePath[i]; } else { sPath += "/" + filePath[i]; } } } string uploadFileName = uniqDatetime + "_" + ocrTag + "_" + pageNum; //int idx = uploadFileName.LastIndexOf("."); string sUploadPath = uploadFileName.Substring(4, 4); string sUploadFileName = uploadFileName.Substring(uploadFileName.LastIndexOf("\\") + 1); authProcess(pid, cretNo, inDd, deptCd, ordType, ocrTag, consentMstRid, userId, pageNum, formCd, sUploadFileName, remoteData["IMAGE_SEQ"], fileSizeAr[fileSizeCnt].Trim()); fileSizeCnt++; pageNum++; // 운영 배포 테스트를 위한 temp 경로 삭제 // 실제 운영 테스트 시 100번 환자로만 진행 필요 var remotePath = remoteData["IMAGEPATH"] + "\\" + remoteData["PATH_IMGDATA"] + "\\" + date + "\\" + pid; //var remotePath = remoteData["IMAGEPATH"] + "\\temp_" + remoteData["PATH_IMGDATA"] + "\\" + date + "\\" + pid; //var destDirectory = remotePath.Substring(2); ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility(); //var imResult = util.ImpersonationStart(remotePath, remoteData["NETDRV_USERID_ADMIN"], remoteData["NETDRV_PASSWORD_ADMIN"]); var imResult = util.ImpersonationStart(remotePath, remoteData["NETDRV_USERID_ADMIN"], remoteData["NETDRV_PASSWORD_ADMIN"]); DirectoryInfo destDi = new DirectoryInfo(remotePath); string destDirStr = destDi.Name; var destFullname = String.Format(@"{0}\{1}", remotePath, sUploadFileName); var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath, sFileName)); if (!destDi.Exists) { destDi.Create(); } try { File.Copy(localFile, destFullname, true); } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload fileCopy ERROR : [{0}]", ex.ToString())); throw ex; } util.ImpersonationEnd(); imageHashTable.Add("imagePath", remotePath); imageHashTable.Add("imageFilename", sUploadFileName); imageHashTable.Add("completeYn", paramHashTable["completeYn"]); dac.InsertConsentImage(this.IbatisMapper, imageHashTable); } nowCnt++; } } paramHashTable.Add("consentImageRid", firstImageRid); // TODO 원무 인증 저장 pass // 원무 저장시 해당 정보 저장 or skip 확인 해 볼 것 // 사인정보 저장 dac.InsertConsentImageSign(this.IbatisMapper, paramHashTable); } catch (Exception ex) { //using (HospitalSvc hospitalWebService = new HospitalSvc()) { // hospitalWebService.delEformData(patientCode, visitType, // clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno), // formCd, ocrcode, userId, createUserName, string.Format("{0}", consentMstRid), hosType, // clnDeptCode, dutinstcd); //} //if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload ERROR : [{0}]", ex.ToString())); throw ex; } } } private void authProcess(string pid, int cretNo, string ordDd, string deptCd, string ordType, string ocrTag, int consentMstRid, string userId, int pageNum, string formCd, string fileName, string imageSvrSeq, string fileSize) { int seq = 0; int seqNo = 0; try { using (ConsentDac consentDac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("pid", pid); param.Add("cretNo", cretNo); param.Add("ordDd", ordDd); param.Add("deptCd", deptCd); param.Add("ordType", ordType); param.Add("userId", userId); //param.Add("pageNo", pageNum); param.Add("formCd", formCd); param.Add("imgServer", imageSvrSeq); param.Add("fileSize", Convert.ToInt32(fileSize)); var date = DateTime.Now.ToString("yyyyMM"); string mstRid = Convert.ToString(consentMstRid); param.Add("ocrTag", ocrTag + "^" + mstRid); param.Add("fileName", date + "\\" + pid + "\\" + fileName); // 외래면 0 아니면 1 if (ordType.Equals("O")) { param.Add("inOut", 0); } else { param.Add("inOut", 1); } if (cretNo == 0 || ordDd.Equals("") || deptCd.Equals("") || ordType.Equals("")) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("cretNo -- > " + cretNo); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("ordDd -- > " + ordDd); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("deptCd -- > " + deptCd); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("ordType -- > " + ordType); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("ocrTag -- > " + ocrTag); throw new Exception(); } seq = Convert.ToInt32(consentDac.getTreatTSeq(this.IbatisMapper, param)); param.Add("seq", seq); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("seq -- > " + seq); if (seq == 0) { seq = Convert.ToInt32(consentDac.getTreatTNewSeq(this.IbatisMapper, param)); seq = seq + 1; param.Remove("seq"); param.Add("seq", seq); consentDac.insertScanGroup(this.IbatisMapper, param); } seqNo = consentDac.getScanFileMaxSeq(this.IbatisMapper, param); seqNo = seqNo + 1; param.Add("seqNo", seqNo); consentDac.insertScanFile(this.IbatisMapper, param); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm authProcess ERROR : [{0}]", ex.ToString())); throw ex; } } private Dictionary remoteInfo() { Dictionary data = new Dictionary(); try { using (CommonCodeDac codeDac = new CommonCodeDac()) { IList imageServerProps; Hashtable opts = new Hashtable(); imageServerProps = codeDac.GetImageServerProps(this.IbatisMapper, opts); foreach (var prop in imageServerProps) { if (prop.imageSeq != "") { data.Add("IMAGE_SEQ", prop.imageSeq); } data.Add(prop.keyName, prop.keyValue); } } List users = new List(); var path = string.Format("WinNT://{0},computer", Environment.MachineName); using (var computerEntry = new DirectoryEntry(path)) { foreach(DirectoryEntry childEntry in computerEntry.Children) { if (childEntry.SchemaClassName == "User") { users.Add(childEntry.Name); } } } //if (users.Contains("imr") == true) { // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("&&&&&&"); // var entry = new DirectoryEntry(path); // DirectoryEntries childEntry2 = entry.Children; // DirectoryEntry user = childEntry2.Find("imr"); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("user.Name -- > " + user.Name); // childEntry2.Remove(user); // user.CommitChanges(); //} if (users.Contains("imr") == false) { DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntry newUser = localMachine.Children.Add(data["NETDRV_USERID_ADMIN"], "user"); newUser.Invoke("SetPassword", new object[] { data["NETDRV_PASSWORD_ADMIN"] }); newUser.Invoke("Put", new object[] { "Description", "Test user" }); newUser.CommitChanges(); newUser.Close(); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm remoteInfo ERROR : [{0}]", ex.ToString())); throw ex; } return data; } [WebMethod(Description = "신규서식이 아닌 서식을 불러온다")] public string GetConsentFormXml(int consentMstRid) { byte[] result = { 0 }; String formXml = ""; //SingleReturnData result = new SingleReturnData(); try { using (ConsentDac consentDac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("consentMstRid", consentMstRid); formXml = consentDac.getConsentFormXml(this.IbatisMapper, param); UTF8Encoding encoder = new UTF8Encoding(); Decoder utf8Decode = encoder.GetDecoder(); byte[] toEcodeByte = Convert.FromBase64String(formXml); int charCount = utf8Decode.GetCharCount(toEcodeByte, 0, toEcodeByte.Length); char[] decodedChar = new char[charCount]; utf8Decode.GetChars(toEcodeByte, 0, toEcodeByte.Length, decodedChar, 0); formXml = Unzip(toEcodeByte); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentFormXml ERROR : [{0}]", ex.ToString())); } return formXml; } public byte[] Zip(string str) { var bytes = Encoding.UTF8.GetBytes(str); using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(mso, CompressionMode.Compress)) { CopyTo(msi, gs); } return mso.ToArray(); } } public string Unzip(byte[] bytes) { using (var msi = new MemoryStream(bytes)) using (var mso = new MemoryStream()) { using (var gs = new GZipStream(msi, CompressionMode.Decompress)) { CopyTo(gs, mso); } return Encoding.UTF8.GetString(mso.ToArray()); } } public void CopyTo(Stream src, Stream dest) { byte[] bytes = new byte[4096]; int cnt; while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) { dest.Write(bytes, 0, cnt); } } /// /// 전자 동의서를 완료저장 한다. /// /// 로그인 사용자ID /// 환자 등록번호 /// 진료과 코드 /// (작성대상)서식 Rid /// 서식코드 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 동의서 EPT Xml /// 동의서 Data(필드들) Xml /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원구분 /// 병원 구분 /// 병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자 /// 병동 코드 /// 병실 코드 /// 처방번호 /// 처방코드 /// 처방명 /// 작성자명 /// 수정자명 /// 이미지 파일 정보(전자동의서 서버) /// 이미지 파일 공인인증 대상정보 /// 이미지 파일 공인인증 처리정보 /// 퇴원일자 /// 상태 /// 주치의 아이디 /// 사용자 부서 코드 /// 동의서 매수 /// 동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제) /// Client구분 (P: PC, M: 모바일) //[WebMethod(Description = "동의서 서명 완료")] //public int SaveCompleteAll(string userId, string patientCode, string clnDeptCode, int formRid, string formCd, // int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml, // string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate, // string ward, string roomcd, int orderNo, string orderName, string orderCd, string ocrCode, int cretno, // string createUserName, string modifyUserName, string imageFileJson, string certTarget, string certResult, // string dschdd, string consentState, string mainDrId, // string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { // string paramLog = ""; // paramLog += "clnDept[" + userId + "]patientCode[" + patientCode + "]clnDeptCode[" + clnDeptCode + "]formRid[" + formRid + "]"; // paramLog += "formCd[" + formCd + "]consentMstRid[" + consentMstRid + "]rewriteConsentMstRid[" + rewriteConsentMstRid + "]"; // paramLog += "deviceType[" + deviceType + "]vistType[" + vistType + "]hosType[" + hosType + "]"; // paramLog += "clnDate[" + clnDate + "]ward[" + ward + "]roomcd[" + roomcd + "]orderNo[" + orderNo + "]"; // paramLog += "orderName[" + orderName + "]orderCd[" + orderCd + "]ocrCode[" + ocrCode + "]cretno[" + cretno + "]"; // paramLog += "createUserName[" + createUserName + "]modifyUserName[" + modifyUserName + "]imageFileJson[" + imageFileJson + "]certTarget[" + certTarget + "]"; // paramLog += "dschdd[" + dschdd + "]consentState[" + consentState + "]mainDrId[" + mainDrId + "]"; // paramLog += "dataXml[" + dataXml + "]formXml[" + formXml + "]certResult[" + certResult + "]"; // //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("CLIP.eForm SaveCompleteAll param : " + paramLog); // //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("json : " + imageFileJson); // int reissueConsentMstRid = 0; // string paperYn = "N"; // string reasonForUseN = string.Empty; // rewriteConsentMstRid = 0; // consentMstRid = SaveDataAll(userId, patientCode, clnDeptCode, formRid, formCd, // consentMstRid, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, formXml, dataXml, // deviceType, deviceIdentNo, vistType, hosType, clnDate, // ward, roomcd, reasonForUseN, orderNo, orderName, orderCd, ocrCode, cretno, // createUserName, modifyUserName, imageFileJson, certTarget, certResult, dschdd, mainDrId, // userDeptCd, pageCnt, actKind, clientType, opRsrvNo); // return consentMstRid; //} /// /// 동의서 삭제/폐기 데이터를 저장 한다. /// /// 로그인 사용자ID /// The consent MST rid int. /// 환자 등록번호 /// 진료과 코드 /// 병동 코드 /// The roomcd. /// (작성대상)서식 Rid /// 서식 코드 /// 재 작성 대상 동의서 마스터 데이터 Rid /// 삭제/폐기 대상 동의서 마스터 데이터 Rid /// 동의서 상태 /// 장비 고유 식별자 /// 진료 형태 /// 기관 코드 /// 진료일 /// 삭제/폐기 사유 /// OCR Tag /// 생성번호 /// 사용자 부서 코드 /// 동의서 매수 /// 동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제) /// Client구분 (P: PC, M: 모바일) /// //[WebMethod(Description = "동의서 삭제/폐기 데이터를 저장")] //public int SaveDelete(string userId, int consentMstRidInt, string patientCode, string clnDeptCode, // string ward, string roomcd, int formRid, string formCd, int rewriteConsentMstRid, int reissueConsentMstRid, // string consentState, string deviceIdentNo, string vistType, string hosType, string clnDate, string reasonForUseN, // string ocrCode, int cretno, // string userDeptCd, string pageCnt, string actKind, string clientType) { // string paperYn = "N"; // consentMstRidInt = SaveData(userId, patientCode, clnDeptCode, formRid, formCd, // consentMstRidInt, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, null, null, // null, deviceIdentNo, vistType, hosType, clnDate, // ward, roomcd, reasonForUseN, 0, null, null, ocrCode, cretno, // null, null, null, null, null, null, // userDeptCd, pageCnt, actKind, clientType, ""); // return consentMstRidInt; //} /// /// 프린트 출력 후 데이터를 저장 한다. /// /// 로그인 사용자ID /// 환자 등록번호 /// 진료과 코드 /// (작성대상)서식 Rid /// 서식코드 /// 동의서 마스터 데이터 Rid /// The reissue consent MST rid. /// 동의서 EPT Xml /// 동의서 Data(필드들) Xml /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원구분 /// 병원 구분 /// 병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자 /// 병동 코드 /// 병실 코드 /// 처방번호 /// 처방명 /// 처방코드 /// OCR코드 /// 생성번호 /// 작성자명 /// 수정자명 /// 주치의 아이디 /// 사용자 부서 코드 /// 출력 매수 /// 동작 방법 /// Client 타입 /// 수술예약번호 /// [WebMethod(Description = "동의서 프린트 출력 후 데이터를 저장")] public int SavePrintOut(string userId, string patientCode, string clnDeptCode, int formRid, string formCd, int consentMstRid, int reissueConsentMstRid, string formXml, string dataXml, string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate, string ward, string roomcd, int orderNo, string orderName, string orderCd, string ocrCode, int cretno, string createUserName, string modifyUserName, string mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { string consentState = "PAPER_OUT"; string paperYn = "Y"; consentMstRid = SavePrintData(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, 0, reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo, vistType, hosType, clnDate, ward, roomcd, null, orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName, null, null, null, mainDrId, userDeptCd, pageCnt, actKind, clientType, opRsrvNo); return consentMstRid; } /// /// 동의서의 기왕력 데이터 저장 /// /// 환자 등록번호 /// 진료일 /// 고/저혈압 /// 당뇨병 /// 심장질환 /// 신장질환 /// 호흡기질환 /// 과거병력 /// 알레르기 /// 복용약물 /// 흡연상태 /// 특이체질 /// 마약사고 /// 기도이상 유무 /// 출혈소인 /// 기타 /// 로그인 사용자ID /// [WebMethod(Description = "동의서의 기왕력 데이터 저장")] public string SaveMedicalHistory(string patientCode, string clnDate, string bp, string dm, string heart, string kidney, string respiration, string hx, string allergy, string drug, string smoking, string idio, string nacrotics, string airway, string hemorrhage, string status_etc, string userId) { try { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable paramHashTable = new Hashtable(); paramHashTable.Add("patientCode", patientCode); paramHashTable.Add("clnDate", clnDate); paramHashTable.Add("bp", bp); paramHashTable.Add("dm", dm); paramHashTable.Add("heart", heart); paramHashTable.Add("kidney", kidney); paramHashTable.Add("respiration", respiration); paramHashTable.Add("hx", hx); paramHashTable.Add("allergy", allergy); paramHashTable.Add("drug", drug); paramHashTable.Add("smoking", smoking); paramHashTable.Add("idio", idio); paramHashTable.Add("nacrotics", nacrotics); paramHashTable.Add("airway", airway); paramHashTable.Add("hemorrhage", hemorrhage); paramHashTable.Add("status_etc", status_etc); paramHashTable.Add("userId", userId); dac.SetMediHistory(this.IbatisMapper, paramHashTable); } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveMedicalHistory ERROR : [{0}]", ex.ToString())); throw ex; } finally { } return patientCode; } /// /// 동의서 서명 완료일 경우 이미지 데이터 저장 /// /// 동의서 상태 /// 이미지파일명(경로포함) /// 동의서 마스터 데이터 Rid /// 등록자ID /// 동의서 FORM ID /// 저장된 consent image rid [WebMethod(Description = "동의서 서명 완료일 경우 이미지 데이터 저장")] public int SaveImageUploadInfo(string consentState, string imageFileName, int consentMstRid, string userId, int formRid) { int consentImageRid = 0; if (!string.IsNullOrEmpty(consentState) && consentState == "ELECTR_CMP") { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable imageHashTable = new Hashtable(); imageHashTable.Add("consentMstRid", consentMstRid); consentImageRid = this.GetSequence("CONSENT_IMAGE"); imageHashTable.Add("consentImageRid", consentImageRid); imageHashTable.Add("userId", userId); imageHashTable.Add("formRid", formRid); imageHashTable.Add("imagePath", imageFileName.Substring(0, imageFileName.LastIndexOf("\\"))); imageHashTable.Add("imageFilename", imageFileName.Substring(imageFileName.LastIndexOf("\\") + 1)); imageHashTable.Add("completeYn", "Y"); //paramHashTable["completeYn"] dac.InsertConsentImage(this.IbatisMapper, imageHashTable); } } return consentImageRid; } /// /// 서명완료된 이미지의 hash 정보 저장 /// /// 동의서 상태 /// 동의서 마스터 데이터 Rid /// 이미지 데이터 Rid /// 등록자ID /// hash 정보 /// 공인인증서명 결과 [WebMethod(Description = "서명완료된 이미지의 hash 정보 저장")] public void SaveImageSignInfo(string consentState, int consentMstRid, int consentImageRid, string userId, string certTarget, string sCertResult) { string paramLog = ""; paramLog += "consentState[" + consentState + "]consentMstRid[" + consentMstRid + "]consentImageRid[" + consentImageRid + "]userId[" + userId + "]"; paramLog += "certTarget[" + certTarget + "]sCertResult[" + sCertResult + "]"; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("CLIP.eForm SaveTempData param : " + paramLog); if (!string.IsNullOrEmpty(consentState) && consentState == "ELECTR_CMP") { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable imageHashTable = new Hashtable(); imageHashTable.Add("consentMstRid", consentMstRid); imageHashTable.Add("consentImageRid", consentImageRid); imageHashTable.Add("certTarget", certTarget); imageHashTable.Add("certResult", sCertResult); imageHashTable.Add("userId", userId); dac.InsertConsentImageSign(this.IbatisMapper, imageHashTable); imageHashTable.Add("consentState", "CERTIFY_CMP"); dac.UpdateConsentMstStatus(this.IbatisMapper, imageHashTable); } } } /// /// Saves the data. /// /// The user identifier. /// The patient code. /// The CLN dept code. /// The form rid. /// The form cd. /// The consent MST rid. /// The rewrite consent MST rid. /// The reissue consent MST rid. /// State of the consent. /// The paper yn. /// The form XML. /// The data XML. /// Type of the device. /// The device ident no. /// Type of the vist. /// Type of the hos. /// The CLN date. /// The ward. /// The roomcd. /// The reason for use n. /// The order no. /// Name of the order. /// The order cd. /// The ocr code. /// The cretno. /// Name of the create user. /// Name of the modify user. /// Name of the image file. /// The cert target. /// The cert result. /// The main dr identifier. /// The user dept cd. /// The page count. /// Kind of the act. /// Type of the client. /// The op RSRV no. /// //private int SaveData(string userId, string patientCode, string clnDeptCode, int formRid, string formCd, // int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml, // string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate, // string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno, // string createUserName, string modifyUserName, string imageFileName, string certTarget, string certResult, // string mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { // bool isNewConsentMasterCase = false; // if (consentMstRid < 1) { // isNewConsentMasterCase = true; // } // if (this.IbatisSession.IsTransactionStart == false) { // this.IbatisSession.BeginTransaction(); // } // try { // using (SaveConsentDac dac = new SaveConsentDac()) { // Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid, // reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo, // vistType, hosType, clnDate, ward, roomcd, reasonForUseN, // orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName, // certTarget, certResult, mainDrId, opRsrvNo); // consentMstRid = (int) paramHashTable["consentMstRid"]; // //새로 작성하는 경우 // if (isNewConsentMasterCase) { // dac.InsertConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // } else { //새로 작성 아닌 경우 // if (reissueConsentMstRid > 0) { // if (string.IsNullOrEmpty(reasonForUseN)) { // //종이->종이 재발행 // int newConsentMstRid = this.GetSequence("CONSENT_MST"); // paramHashTable["consentMstRid"] = newConsentMstRid; // consentMstRid = newConsentMstRid; // dac.InsertConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // } else { // 삭제 // dac.UpdateConsentMstForDelete(this.IbatisMapper, paramHashTable); // } // } else { //임시저장 또는 저장인 경우 // dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // } // } // // OCR 테이블 연계 // Hashtable ocrParam = new Hashtable { // { "instcd", hosType }, // { "ocrtag", ocrCode }, // { "pid", patientCode }, // { "ordtype", vistType }, // { "orddd", clnDate }, // { "cretno", cretno }, // { "orddrid", mainDrId }, // { "orddeptcd", clnDeptCode }, // { "formcd", formCd }, // { "fstprntdeptcd", userDeptCd }, // { "fstprntid", userId }, // { "updtdeptcd", userDeptCd }, // { "updtuserid", userId }, // { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")}, // { "pagecnt", pageCnt }, // { "updtresncnts", reasonForUseN }, // { "actkind", actKind }, // { "clienttype", clientType } // }; // dac.InsertPrintData(this.IbatisMapper, ocrParam); // if (this.IbatisSession != null) this.IbatisSession.CommitTransaction(); // } // } catch (Exception ex) { // if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveData ERROR : [{0}]", ex.ToString())); // throw ex; // } finally { // } // return consentMstRid; //} //private int SaveDataAll(string userId, string patientCode, string clnDeptCode, int formRid, string formCd, // int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml, // string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate, // string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno, // string createUserName, string modifyUserName, string imageFileJson, string certTarget, // string certResult, string dschdd, string mainDrId, // string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { // bool isNewConsentMasterCase = false; // if (consentMstRid < 1) { // isNewConsentMasterCase = true; // } // try { // using (SaveConsentDac dac = new SaveConsentDac()) { // Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid, // reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo, // vistType, hosType, clnDate, ward, roomcd, reasonForUseN, // orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName, // certTarget, certResult, mainDrId, opRsrvNo); // consentMstRid = (int) paramHashTable["consentMstRid"]; // //새로 작성하는 경우 // if (isNewConsentMasterCase) { // dac.InsertConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml, imageFileJson, certTarget, certResult, hosType, createUserName, hosType); // } // //새로 작성 아닌 경우 // else { // if (reissueConsentMstRid > 0) { // if (string.IsNullOrEmpty(reasonForUseN)) { // //종이->종이 재발행 // int newConsentMstRid = this.GetSequence("CONSENT_MST"); // paramHashTable["consentMstRid"] = newConsentMstRid; // consentMstRid = newConsentMstRid; // dac.InsertConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml, imageFileJson, certTarget, certResult, hosType, createUserName, hosType); // } else { // dac.UpdateConsentMstForDelete(this.IbatisMapper, paramHashTable); // } // } // //임시저장 또는 저장인 경우 // else { // dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); // dac.InsertConsentData(this.IbatisMapper, paramHashTable); // imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml, imageFileJson, certTarget, certResult, hosType, createUserName, hosType); // } // } // // OCR 테이블 연계 // Hashtable ocrParam = new Hashtable { // { "instcd", hosType }, // { "ocrtag", ocrCode }, // { "pid", patientCode }, // { "ordtype", vistType }, // { "orddd", clnDate }, // { "cretno", cretno }, // { "orddrid", mainDrId }, // { "orddeptcd", clnDeptCode }, // { "formcd", formCd }, // { "fstprntdeptcd", userDeptCd }, // { "fstprntid", userId }, // { "updtdeptcd", userDeptCd }, // { "updtuserid", userId }, // { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")}, // { "pagecnt", pageCnt }, // { "updtresncnts", reasonForUseN }, // { "actkind", actKind }, // { "clienttype", clientType } // }; // dac.InsertPrintData(this.IbatisMapper, ocrParam); // // 원무 동의서 연동 // SavePatientConsentInfo(formCd // , patientCode // , ocrCode // , hosType // , clnDate // , cretno.ToString() // , vistType // , clnDeptCode // , mainDrId // , userId // , dataXml); // } // } catch (Exception ex) { // if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveDataAll ERROR : [{0}]", ex.ToString())); // throw ex; // } finally { // } // return consentMstRid; //} //private void imageUpload(SaveConsentDac dac // , Hashtable paramHashTable // , string userId // , string patientCode // , string visitType // , string clnDate // , string Dschdd // , int cretno // , string ocrcode // , int consentMstRid // , string consentState // , string formCd // , int formRid // , string dataXml // , string imageFileJson // , string certTarget // , string certResult // , string hosType // , string createUserName // , string dutinstcd // ) { // // 서명 저장일 경우 emrindxm 테이블에 저장 // if (!string.IsNullOrEmpty(consentState) && (consentState.Equals("ELECTR_CMP") || consentState.Equals("CERTIFY_CMP"))) { // string clnDeptCode = paramHashTable["clnDeptCd"] == null ? string.Empty : paramHashTable["clnDeptCd"].ToString(); // try { // int consentImageRid = this.GetSequence("CONSENT_IMAGE"); // int firstImageRid = consentImageRid; // string sPath = string.Empty; // string sFileName = string.Empty; // string newFileFullName = string.Empty; // if (!string.IsNullOrEmpty(imageFileJson)) { // Dictionary jsonRoot = null; // jsonRoot = fastJSON.JSON.Parse(imageFileJson) as Dictionary; // if (jsonRoot != null && jsonRoot.Count > 0) { // Hashtable imageHashTable = new Hashtable(); // int nowCnt = 1; // foreach (KeyValuePair jr in jsonRoot) { // imageHashTable = new Hashtable(); // imageHashTable.Add("consentMstRid", consentMstRid); // if (nowCnt > 1) consentImageRid = this.GetSequence("CONSENT_IMAGE"); // imageHashTable.Add("consentImageRid", consentImageRid); // imageHashTable.Add("userId", userId); // imageHashTable.Add("formRid", formRid); // if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) { // sPath = ""; // sFileName = ""; // string[] filepath = jr.Value.ToString().Split('/'); // for (int i = 0; i < filepath.Length; i++) { // if (i == 0) { // sPath = filepath[i]; // } else if ((i + 1) == filepath.Length) { // sFileName = filepath[i]; // } else { // sPath += "/" + filepath[i]; // } // } // newFileFullName = string.Empty; // using (HospitalSvc hospitalWebService = new HospitalSvc()) { // newFileFullName = hospitalWebService.GetFileName(patientCode, visitType, // clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno), // "500", formCd, nowCnt.ToString(), // ocrcode, userId, clnDeptCode, dutinstcd); // } // string uploadFileName = newFileFullName + ".jpg"; // int idx = uploadFileName.LastIndexOf("."); // string sUploadPath = uploadFileName.Substring(idx - 4, 4); // string sUploadFileName = uploadFileName.Substring(uploadFileName.LastIndexOf("\\") + 1); // var remotePath = imageServerProps.remotePath; // //var destDrive = remotePath.Substring(0, 2); // var destDirectory = remotePath.Substring(2); // var targetDrive = ""; // var virtualDir = ""; // // 경로를 확인하여 가상 디렉토리 경로를 설정한다 // if (imageServerProps != null) { // targetDrive = imageServerProps.remotePath.Substring(0, 1); // switch (targetDrive) { // case "W": // virtualDir = "his032"; // break; // case "Z": // virtualDir = "his031"; // break; // } // } // // 계정을 choiadmin 으로 가장한다 // ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility(); // var imResult = util.ImpersonationStart(string.Empty, "choiadmin", "choiadmin"); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation Start, " + imResult); // // IIS 가상 디렉토리 경로를 가져온다 // DirectoryInfo di = new DirectoryInfo(Server.MapPath(virtualDir)); // var destDirStr = String.Format(@"{0}\{1}\{2}", // di.ToString(), // remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length), // sUploadPath); // // for debug // //var destDirStr = String.Format(@"{0}\{1}\{2}\{3}\", // // di.ToString(), // // remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length), // // "consentTest", // // sUploadPath); // DirectoryInfo destDi = new DirectoryInfo(destDirStr); // //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirStr: " + destDirStr + ", exists: " + destDi.Exists); // var destFullname = String.Format(@"{0}\{1}", destDirStr, sUploadFileName); // var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath, sFileName)); // //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("local: " + localFile + ", remote: " + destFullname); // if (!destDi.Exists) { // destDi.Create(); // } // try { // File.Copy(localFile, destFullname); // } catch (Exception e) { // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(e); // } // util.ImpersonationEnd(); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation end"); // imageHashTable.Add("imagePath", sUploadPath); // imageHashTable.Add("imageFilename", sUploadFileName); // imageHashTable.Add("completeYn", paramHashTable["completeYn"]); // dac.InsertConsentImage(this.IbatisMapper, imageHashTable); // } // nowCnt++; // } // end of foreach // } // } // paramHashTable.Add("consentImageRid", firstImageRid); // // TODO 원무 인증 저장 pass // // 원무 저장시 해당 정보 저장 or skip 확인 해 볼 것 // // 사인정보 저장 // dac.InsertConsentImageSign(this.IbatisMapper, paramHashTable); // } catch (Exception ex) { // using (HospitalSvc hospitalWebService = new HospitalSvc()) { // hospitalWebService.delEformData(patientCode, visitType, // clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno), // formCd, ocrcode, userId, createUserName, string.Format("{0}", consentMstRid), hosType, // clnDeptCode, dutinstcd); // } // if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload ERROR : [{0}]", ex.ToString())); // throw ex; // } // } //} private bool checkOcrType6Form(string dutinstcd, string formCd) { List forms = getOcrType6Forms(dutinstcd); int pos = forms.FindIndex(x => x.StartsWith(formCd)); return (pos > 0) ? true : false; } private int SavePrintData(string userId, string patientCode, string clnDeptCode, int formRid, string formCd, int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml, string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate, string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno, string createUserName, string modifyUserName, string imageFileName, string certTarget, string certResult, string mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { bool isNewConsentMasterCase = false; if (consentMstRid < 1) { isNewConsentMasterCase = true; } // OCR TYPE 6 는 기록하지 않는다 if (checkOcrType6Form(hosType, formCd)) { return -1; } try { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo, vistType, hosType, clnDate, ward, roomcd, reasonForUseN, orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName, certTarget, certResult, mainDrId, opRsrvNo); consentMstRid = (int) paramHashTable["consentMstRid"]; //새로 출력하는 경우 if (isNewConsentMasterCase) { dac.InsertConsentMst(this.IbatisMapper, paramHashTable); } //새로 작성 아닌 경우 else { if (reissueConsentMstRid > 0) dac.UpdateConsentMstForReissue(this.IbatisMapper, paramHashTable); else dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); } // OCR 테이블 연계 Hashtable ocrParam = new Hashtable { { "instcd", hosType }, { "ocrtag", ocrCode }, { "pid", patientCode }, { "ordtype", vistType }, { "orddd", clnDate }, { "cretno", cretno }, { "orddrid", mainDrId }, { "orddeptcd", clnDeptCode }, { "formcd", formCd }, { "fstprntdeptcd", userDeptCd }, { "fstprntid", userId }, { "updtdeptcd", userDeptCd }, { "updtuserid", userId }, { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")}, { "pagecnt", pageCnt }, { "updtresncnts", reasonForUseN }, { "actkind", actKind }, { "clienttype", clientType } }; dac.InsertPrintData(this.IbatisMapper, ocrParam); } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveData ERROR : [{0}]", ex.ToString())); throw ex; } finally { } return consentMstRid; } public static int ExecuteCommand(string command, int timeout) { var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/C " + command) { RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false, //WorkingDirectory = "C:\\", //WorkingDirectory = ".\\", }; var process = System.Diagnostics.Process.Start(processInfo); process.WaitForExit(20000); //string txt = process.StandardOutput.ReadToEnd(); //Console.WriteLine(txt); var exitCode = process.ExitCode; process.Close(); return exitCode; } private static Dictionary DataXmlToDictionary(string dataXml) { Dictionary outputDataDic; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(dataXml); outputDataDic = new Dictionary(); XmlNode rootNode = xmlDocument.SelectSingleNode("form-data"); foreach (XmlNode childNode in rootNode.ChildNodes) { string fieldName = string.Empty; string fieldValue = string.Empty; XmlElement outFieldElement = childNode as XmlElement; if (outFieldElement != null) { fieldName = outFieldElement.Name; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 0 : {0}/{1}", outFieldElement.ChildNodes.Count, fieldName)); if (outFieldElement.ChildNodes.Count == 1 && outFieldElement.ChildNodes[0] is XmlCDataSection) { fieldValue = ((XmlCDataSection) outFieldElement.ChildNodes[0]).InnerText; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 1 : {0}/{1}", fieldName, fieldValue)); if (outputDataDic.ContainsKey(fieldName)) { outputDataDic[fieldName] = fieldValue; } else { outputDataDic.Add(fieldName, fieldValue); } } else if (outFieldElement.ChildNodes.Count > 1) { foreach (XmlNode childNode2 in childNode.ChildNodes) { string fieldName2 = string.Empty; string fieldValue2 = string.Empty; XmlElement outFieldElement2 = childNode2 as XmlElement; fieldName2 = outFieldElement2.Name; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary : {0}", fieldName2)); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary : {0}", outFieldElement2.ChildNodes.Count)); if (outFieldElement2.ChildNodes.Count > 0 && outFieldElement2.ChildNodes[0] is XmlCDataSection) { fieldValue2 = ((XmlCDataSection) outFieldElement2.ChildNodes[0]).InnerText; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 2 : {0}/{1}", fieldName2, fieldValue2)); } if (outputDataDic.ContainsKey(fieldName2)) { outputDataDic[fieldName2] = fieldValue2; } else { outputDataDic.Add(fieldName2, fieldValue2); } } } } } return outputDataDic; } /// /// EFORM_CODE에 정의하는 시퀀스(채번)을 구한다. /// /// /// private int GetSequence(string sSubCd) { int nSeq = -1; try { using (CommonCodeDac dac = new CommonCodeDac()) { Code param = new Code(); param.sub_cd = sSubCd; nSeq = dac.GetSequence(this.IbatisMapper, param); if (nSeq == 0) { dac.InsertSequence(this.IbatisMapper, param); nSeq = 1; } else { param.ud1_num = ++nSeq; dac.UpdateSequence(this.IbatisMapper, param); } } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); throw ex; } return nSeq; } #region GetParamHashTable private Hashtable GetParamHashTable(string userId, // 사용자 Id string patientCode, // 환자 등록번호 string clnDeptCode, // 진료과 코드 int formRid, // (작성대상)서식 Rid string formCd, // 서식코드 === CONSENT_DATA_CHOICE에서 입력여부 판단할 파라미터 int consentMstRid, // 동의서 마스터 데이터 Rid int rewriteConsentMstRid, // 재 작성 대상 동의서 마스터 데이터 Rid int reissueConsentMstRid, // 재 발행 대상 동의서 마스터 데이터 Rid string consentState, // 동의서 상태 (TEMP, PAPER_OUT, ELECTR_CMP, CERTIFY_CMP) string paperYn, // 인쇄 발행 여부 string formXml, // 동의서 EPT Xml string dataXml, // 동의서 Data(필드들) Xml string deviceType, // 장비 유형 (WIN, AND, IOS, PRT 중1) string deviceIdentNo, // 장비 고유식별 번호 string vistType, // 내원 구분 string hosType, // 병원 구분 string clnDate, // 내원구분에 따른 입원일자/진료일자 string ward, // 병동 코드 string roomcd, // 병실 코드 string reasonForUseN, // 출력된 동의서 폐기 사유 int orderNo, // 처방번호 string orderName, // 처방명 string orderCd, // 처방코드 string ocrCode, // OCR 코드 int cretno, // 생성번호 string createUserName, // 작성자명 string modifyUserName, // 수정자명 string certTarget, // 서명데이터 원본 string certResult, // 서명데이터 결과값 string mainDrId, // 주치의 아이디 string opRsrvNo // 수술 예약 번호 ) { Hashtable paramHashTable = new Hashtable(); paramHashTable.Add("userId", userId); if (consentMstRid < 1) { // insert case consentMstRid = this.GetSequence("CONSENT_MST"); } paramHashTable.Add("consentMstRid", consentMstRid); paramHashTable.Add("patientCode", patientCode); paramHashTable.Add("clnDeptCd", clnDeptCode); paramHashTable.Add("vistType", vistType); paramHashTable.Add("hosType", hosType); paramHashTable.Add("clnDate", clnDate); paramHashTable.Add("ward", ward); paramHashTable.Add("roomcd", roomcd); paramHashTable.Add("orderNo", orderNo); paramHashTable.Add("orderName", orderName); paramHashTable.Add("orderCd", orderCd); paramHashTable.Add("ocrCode", ocrCode); paramHashTable.Add("cretno", cretno); paramHashTable.Add("createUserName", createUserName); paramHashTable.Add("modifyUserName", modifyUserName); paramHashTable.Add("formRid", formRid); paramHashTable.Add("formCd", formCd); paramHashTable.Add("consentState", consentState); paramHashTable.Add("certTarget", certTarget); // TODO 원무 pass paramHashTable.Add("certResult", certResult); // TODO 원무 pass paramHashTable.Add("mainDrId", mainDrId); paramHashTable.Add("opRsrvNo", opRsrvNo ?? string.Empty); Encoding encoding = Encoding.GetEncoding("UTF-8"); //if (certResult != null) //{ // paramHashTable.Add("certResult", encoding.GetBytes(certResult)); //} string completeYn = "N"; // 완료 여부 switch (consentState) { case "ELECTR_CMP": case "CERTIFY_CMP": completeYn = "Y"; break; default: break; } paramHashTable.Add("completeYn", completeYn); string completeDateTimeToChars = string.Empty; if (completeYn.Equals("Y")) { completeDateTimeToChars = "TO_CHAR(SYSDATE,'YYYY-MM-DD hh24:mi:ss')"; paramHashTable.Add("completeDateTimeToChars", completeDateTimeToChars); } else { paramHashTable.Add("completeDateTimeToChars", "''"); } paramHashTable.Add("paperYn", paperYn); string rewriteYn = "N"; // 재 작성 여부 if (rewriteConsentMstRid > 1) { rewriteYn = "Y"; } paramHashTable.Add("rewriteYn", rewriteYn); paramHashTable.Add("rewriteConsentMstRid", rewriteConsentMstRid); string reissueYn = "N"; // 재 발행(종이) 여부 if (reissueConsentMstRid > 1) { reissueYn = "Y"; } paramHashTable.Add("reissueYn", reissueYn); paramHashTable.Add("reissueConsentMstRid", reissueConsentMstRid); int consentDataRid = this.GetSequence("CONSENT_DATA"); paramHashTable.Add("consentDataRid", consentDataRid); paramHashTable.Add("useYn", "Y"); encoding = Encoding.GetEncoding("UTF-8"); byte[] formBytesConent = null; if (!string.IsNullOrEmpty(formXml)) { formBytesConent = encoding.GetBytes(formXml); } byte[] dataBytesConent = null; if (!string.IsNullOrEmpty(dataXml)) { dataBytesConent = encoding.GetBytes(dataXml); } paramHashTable.Add("formXml", formBytesConent); paramHashTable.Add("dataXml", dataBytesConent); paramHashTable.Add("deviceType", deviceType); paramHashTable.Add("deviceIdentNo", deviceIdentNo); paramHashTable.Add("reasonForUseN", reasonForUseN); return paramHashTable; } #endregion //임시파일 삭제 (1일전 파일은 삭제) //public int DeleteTempFile(string targetDate) public int DeleteTempFile() { //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DeleteTempFile DateTime.Now.AddDays(-1) : {0}", DateTime.Now.AddDays(-1).ToString())); // 2016-11-06 오후 8:19:56 if (tempImageDelStatus.Equals(DateTime.Now.AddDays(-1).ToString().Substring(0, 10).Replace("-", ""))) { return 1; } try { string sSeverImgPath = Server.MapPath("./DataTempImage/"); DirectoryInfo di = new System.IO.DirectoryInfo(sSeverImgPath); if (Directory.Exists(sSeverImgPath)) { string[] filePaths = Directory.GetFiles(sSeverImgPath); foreach (string fileName in filePaths) { FileInfo fileInfo = new FileInfo(fileName); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DeleteTempFile fileInfo.CreationTime : {0}", fileInfo.CreationTime.ToString())); if (fileInfo.CreationTime < DateTime.Now.AddDays(-1)) { fileInfo.Delete(); } } } tempImageDelStatus = DateTime.Now.AddDays(-1).ToString().Substring(0, 10).Replace("-", ""); return 1; } catch { return -1; } } /// /// 동의서 로드 전 consent_mst_rid에 해당하는 동의서가 상위 상태값이 있는지 체크 /// /// /// /// [WebMethod(Description = "동의서 상위 상태값이 있는지 체크")] public int CheckConsentState(int consentmstrid, string consent_state) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("rid: {0}, state: {1}", consentmstrid, consent_state)); try { int result = -1; int StateNo = 0; String CurState; using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("consentmstrid", consentmstrid); CurState = dac.GetConsentStateCheck(this.IbatisMapper, param); } if (CurState == null) { return result; } else if (CurState.Equals("UNFINISHED")) { StateNo = 1; } else if (CurState.Equals("TEMP")) { StateNo = 2; } else if (CurState.Equals("VERBAL")) { StateNo = 3; } else if (CurState.Equals("PAPER_OUT")) { StateNo = 4; } else if (CurState.Equals("ELECTR_CMP")) { StateNo = 5; } else if (CurState.Equals("CERTIFY_CMP")) { StateNo = 6; } if (consent_state == null/* || string.IsNullOrEmpty(consent_state)*/) { return result; } else if (consent_state.Equals("UNFINISHED")) { result = 1; } else if (consent_state.Equals("TEMP")) { result = 2; } else if (consent_state.Equals("VERBAL")) { result = 3; } else if (consent_state.Equals("PAPER_OUT")) { result = 4; } else if (consent_state.Equals("ELECTR_CMP")) { result = 5; } else if (consent_state.Equals("CERTIFY_CMP")) { return result; } if (result < StateNo)//로드하려는 동의서의 상태보다 현재 저장된 상태가 더 높은 상태일 경우 { return 1; } else//로드하려는 동의서보다 현재 저장된 상태가 낮은상태일 경우 또는 같을경우 { return 0; } } catch { return -1; } } /// /// 개인정보 동의서 일때만 해당 메서드를 사용함 (formCd가 1200005463, 1800014564 인것만) /// private void SavePatientConsentInfo(string formCd, string pid, string ocrTag, string userId, string dataXml) { try { // 동의서 내부 데이터 추출 UTF8Encoding encoder = new UTF8Encoding(); Decoder utf8Decode = encoder.GetDecoder(); byte[] toEcodeByte = Convert.FromBase64String(dataXml); int charCount = utf8Decode.GetCharCount(toEcodeByte, 0, toEcodeByte.Length); char[] decodedChar = new char[charCount]; utf8Decode.GetChars(toEcodeByte, 0, toEcodeByte.Length, decodedChar, 0); dataXml = Unzip(toEcodeByte); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("dataXml -- > " + dataXml); Dictionary pamDic = DataXmlToDictionary(dataXml); string savPrivacy1 = pamDic.ContainsKey("sav_privacy1") ? pamDic["sav_privacy1"].ToString() : ""; // 개인정보 서식의 메인 동의, 미동의 데이터 string savPrivacy2 = pamDic.ContainsKey("sav_privacy2") ? pamDic["sav_privacy2"].ToString() : ""; // 개인정보 서식의 첫 번째 동의, 미동의 데이터 (사후서비스제공) string savPrivacy3 = pamDic.ContainsKey("sav_privacy3") ? pamDic["sav_privacy3"].ToString() : ""; // 개인정보 서식의 두 번째 동의, 미동의 데이터 (모바일안내) string savPrivacy4 = pamDic.ContainsKey("sav_privacy4") ? pamDic["sav_privacy4"].ToString() : ""; // 개인정보 서식의 세 번째 동의, 미동의 데이터 (행사안내) string savPrivacy5 = pamDic.ContainsKey("sav_privacy5") ? pamDic["sav_privacy5"].ToString() : ""; // 개인정보 서식의 네 번째 동의, 미동의 데이터 (협력병원) string patientNm = pamDic.ContainsKey("savSG_PatientNm") ? pamDic["savSG_PatientNm"].ToString() : ""; // 환자 이름 string patientSign = pamDic.ContainsKey("savSG_PatientSign") ? pamDic["savSG_PatientSign"].ToString() : ""; // 환자 서명 string agentNm = pamDic.ContainsKey("savSG_AgentNm") ? pamDic["savSG_AgentNm"].ToString() : ""; // 동의권자 이름 string agnentSign = pamDic.ContainsKey("savSG_AgentSign") ? pamDic["savSG_AgentSign"].ToString() : ""; // 동의권자 서명 string agentRelation = pamDic.ContainsKey("savSG_AgentRelation") ? pamDic["savSG_AgentRelation"].ToString() : "1"; // 환자와의 관계 드롭박스 string agentETC = pamDic.ContainsKey("savSG_AgentETC") ? pamDic["savSG_AgentETC"].ToString() : ""; // 환자와의 관계 글상자(기타 입력란) string agentReason = pamDic.ContainsKey("savSG_AgentReason") ? pamDic["savSG_AgentReason"].ToString() : ""; // 동의권자서명이유 상위컨트롤(라디오박스) string agentPhone = pamDic.ContainsKey("savSG_AgentPhone") ? pamDic["savSG_AgentPhone"].ToString() : ""; // 법정대리인 연락처 글상자 string agentReasonText = pamDic.ContainsKey("savSG_AgentReasonText") ? pamDic["savSG_AgentReasonText"].ToString() : ""; // 기타 글 상자 // 관계가 없다면 본인 서명 아니라면 값을 agentRelation = agentRelation == "" ? "1" : agentRelation; // 동의권자 서명 사유 var value5 = string.Empty; var value6 = string.Empty; var value7 = string.Empty; var value8 = string.Empty; var value9 = string.Empty; switch (agentReason) { case "value1": value5 = "Y"; break; case "value2": value6 = "Y"; break; case "value3": value7 = "Y"; break; case "value4": value8 = "Y"; break; case "value5": value9 = "Y"; break; } using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable param = new Hashtable(); param.Add("pid", pid); param.Add("userId", userId); param.Add("instcd", "101"); int pamSeqResult = dac.getPamSeqNo(this.IbatisMapper, param); // 기존의 개인정보보호 동의서가 있다면 업데이트 if(pamSeqResult > 0) { dac.updatePreSignData(this.IbatisMapper, param); } // 개인정보보호동의서 신규 param.Add("patientNm", patientNm); param.Add("agentRelation", agentRelation); param.Add("patientSign", string.IsNullOrEmpty(patientSign) ? "N" : "Y"); param.Add("savPrivacy1", savPrivacy1); param.Add("savPrivacy2", savPrivacy2); param.Add("savPrivacy3", savPrivacy3); param.Add("savPrivacy4", savPrivacy4); param.Add("savPrivacy5", savPrivacy5); param.Add("value5", value5); param.Add("value6", value6); param.Add("value7", value7); param.Add("value8", value8); param.Add("value9", value9); param.Add("telno", agentPhone); param.Add("etc", agentReasonText); param.Add("seqno", pamSeqResult); param.Add("seqno2", Convert.ToString(Convert.ToInt32(pamSeqResult) + 1)); var result = dac.insPmcmpicm(this.IbatisMapper, param); pamSeqResult = pamSeqResult + 1; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("pamSeqResult -- > " + pamSeqResult); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SavePatientConsentInfo ERROR : [{0}]", ex.ToString())); throw ex; } } /// /// 기준자료로 부터 OCT 태그에 찍힐 String 값 /// 경북대병원 dependency /// /// The form cd. /// The dutinstcd. /// [WebMethod(Description = "기준자료로 부터 OCT 태그에 찍힐 String 값")] public String getOcrString(string formCd, string dutinstcd) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("formcd", formCd); param.Add("instcd", dutinstcd); return dac.getOcrString(this.IbatisMapper, param); } } /// /// 원무 서식의 인증저장 사용여부 /// Y 일 경우 인증서 묻기를 하지 않는다 /// 경북대병원 dependency /// /// 서식 코드 /// 근무지기관코드 /// [WebMethod(Description = "원무서식 인증저장 사용여부, Y 일 경우 인증저장시 인증서 묻기 pass")] public String getCertUseYn(String formCd, String dutinstcd) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("formcd", formCd); param.Add("instcd", dutinstcd); String value = dac.getCertuseYn(this.IbatisMapper, param); return (value == null) ? "N" : value; //return dac.getCertuseYn(this.IbatisMapper, param); } } /// /// 원무 서식의 인증저장 사용여부 (모바일에서 사용) /// 원무 서식이 여러개 선택되었을때 /// Y 일 경우 인증서 묻기를 하지 않는다 /// 경북대병원 dependency /// /// 서식 코드 서식코드는 '11111111', '2222222', '333333' 형태로 들어옴 /// 근무지기관코드 /// [WebMethod(Description = "원무서식 인증저장 사용여부, Y 일 경우 인증저장시 인증서 묻기 pass (모바일에서 다중 선택 기능 포함)")] public String getCertUseYnData(String formCd, String dutinstcd) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("formcd", formCd); param.Add("instcd", dutinstcd); String result = dac.getCertUseYnData(this.IbatisMapper, param); if (result == null) { result = ""; } return result; } } /// /// 경북대학교병원 PC 클라이언트 dual view 모드 활성화 여부 조회 /// /// 근무지기관코드 /// 해당 PC 의 ip address /// [WebMethod(Description = "경북대학교병원 PC 클라이언트 dual view 모드 활성화 여부 조회")] public String getDualViewMode(String dutinstcd, String ipaddr) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("instcd", dutinstcd); param.Add("ipaddr", ipaddr); String value = dac.getDualViewMode(this.IbatisMapper, param); return (value == null) ? "N" : value; } //return "N"; } /// /// 확인저장 된 서식을 일괄저장 /// /// /// /// /// [WebMethod(Description = "경북대학교병원 일괄 인증 저장")] public String updateCertifyComplete(String consent_rids, String ocrtags, String instcd) { String result = "N"; try { Hashtable param1 = new Hashtable(); Hashtable param2 = new Hashtable(); param1.Add("consent_rids", consent_rids); param1.Add("instcd", instcd); param2.Add("ocrtags", ocrtags); param2.Add("instcd", instcd); using (ConsentDac dac = new ConsentDac()) { // 동의서 테이블 master dac.updateToCertifyConsentMst(this.IbatisMapper, param1); // 경북대학교병원 출력 로그 테이블 dac.updateToCertifyOcrprnt(this.IbatisMapper, param2); } result = "Y"; } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); result = "N"; CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error( String.Format("CLIP.eForm updateCertifyComplete ERROR : [{0}]", ex.ToString())); } return result; } /// /// 전자동의서 프린트 출력 오류 시 프린트 로그 삭제 메서드 /// /// /// /// [WebMethod(Description = "프린터 출력 오류 시 출력 히스토리 삭제")] public void updatePrintHistory(String pid, String ocrtag, String instcd) { try { Hashtable param1 = new Hashtable(); param1.Add("pid", pid); param1.Add("instcd", instcd); param1.Add("ocrtag", ocrtag); using (ConsentDac dac = new ConsentDac()) { dac.updateOcrPrintHistory(this.IbatisMapper, param1); dac.updateConsentMaster(this.IbatisMapper, param1); } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error( String.Format("CLIP.eForm updatePrintHistory ERROR : [{0}]", ex.ToString())); } } /// /// 동의서 선택시 해당일에 대해 중복으로 정상되었는지 확인 /// /// /// /// '000000', '000001', '000002' 콤마로 붙여야함 [WebMethod(Description = "동의서 선택시 해당일에 대해 중복으로 정상되었는지 확인")] public String duplicateCertConsent(String pid, String instcd, String formcd) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("pid", pid); param.Add("instcd", instcd); param.Add("formcd", formcd); String result = dac.getDupCertConsent(this.IbatisMapper, param); if (result == null) { result = "N"; } return result; } } [WebMethod(Description = "동의서 선택시 해당일에 대해 중복으로 정상되었는지 확인")] public String getUserTableGrants() { string result = string.Empty; using(CommonCodeDac dac = new CommonCodeDac()) { Hashtable param = new Hashtable(); dac.GetImageServerProps(this.IbatisMapper, param); } return result; } } }