#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 CLIP.eForm.Consent.Web; using System.Security.AccessControl; 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"); imageServerProps = new ImageServerProps(_ibatisHelper.GetSqlMapper()); } 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(string instCd) { List result; try { using (FormCategoryDac dac = new FormCategoryDac()) { string categoryId = ""; if (instCd.Equals("031")) { categoryId = "EMA_031"; } else { categoryId = "EMA_032"; } Hashtable param = new Hashtable(); param.Add("category_id", categoryId); result = (List) dac.GetCategoryForDropdown(this.IbatisMapper, param); CategoryForDropdownVO allSubCategory = new CategoryForDropdownVO(); allSubCategory.CategoryId = categoryId; allSubCategory.CategoryName = "전체"; allSubCategory.CategoryType = "F"; result.Insert(0, allSubCategory); } return result; } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetCategoryForDropdown error: {0}", ex.Message)); throw ex; } } ///// ///// 동의서 하위 카테고리 조회 ///// ///// 카테고리 ID ///// //[WebMethod(Description = "동의서 하위 카테고리 조회")] //public List GetCategoryForDropdown(string categoryId) { // List result; // try { // using (FormCategoryDac dac = new FormCategoryDac()) { // Hashtable param = new Hashtable(); // param.Add("category_id", categoryId); // result = (List) dac.GetCategoryForDropdown(this.IbatisMapper, param); // if (categoryId.Equals("1")) { // CategoryForDropdownVO categoryForDropdownVO = new CategoryForDropdownVO(); // categoryForDropdownVO.CategoryType = "F"; // categoryForDropdownVO.CategoryId = "1CB1B494-1EF0-48BD-84D6-4965A54E6AEA"; // categoryForDropdownVO.CategoryName = "전체"; // result.Insert(0, categoryForDropdownVO); // } else { // CategoryForDropdownVO allSubCategory = new CategoryForDropdownVO(); // allSubCategory.CategoryId = categoryId; // allSubCategory.CategoryName = "전체"; // allSubCategory.CategoryType = "F"; // result.Insert(0, allSubCategory); // } // } // return result; // } catch (Exception ex) { // CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetCategoryForDropdown error: {0}", ex.Message)); // throw ex; // } //} [WebMethod(Description = "사용자 이름에 따른 환자별 동의서 목록 조회")] public List GetConsentListByUserName(string username, string startDt, string endDt, string consetState, string dutinstcd) { List result = null; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable { { "instcd", dutinstcd }, { "startDt", startDt }, { "endDt", endDt }, { "usename", username }, { "status", consetState} }; return (List) dac.GetUnfinishedListPerUserName(this.IbatisMapper, param); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetUnfinishedListPerDoctor error: {0}", ex.Message)); throw ex; } return result; } /// /// 환자, 상태에 따른 동의서 목록 검색 /// /// 환자등록번호 /// 데이터생성일자 조회 시작일 /// The end dt. /// State of the conset. /// 근무지기관코드 /// The user identifier. /// [WebMethod(Description = "환자/상태에 따른 동의서 목록 검색")] public List GetConsentList(string pid, string startDt, string endDt, string consentState, string instCd , string userId) { 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 }, { "startDt", startDt }, { "endDt", endDt }, { "consentState", consentState }, { "instCd", instCd }, { "userId", userId ?? string.Empty} }; //result = (List) dac.GetConsentList(this.IbatisMapper, param); 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; } } /// /// 동의서 찾기 /// /// 카테고리 ID /// 검색할 키워드 /// 근무지기관코드 /// [WebMethod(Description = "동의서 찾기(조회)")] public List GetConsentBySearch(string categoryId, string keyWord, string instCd) { List result; if (categoryId.Equals("EMA_031") || categoryId.Equals("EMA_032")) { categoryId = ""; } try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("categoryId", categoryId); param.Add("instCd", instCd); param.Add("keyWord", string.Format("%{0}%", keyWord)); result = (List) dac.GetConsentBySearch(this.IbatisMapper, param); } return result; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentBySearch error: {0}", ex.Message)); throw ex; } } /// /// 동의서 찾기 /// /// 서식코드 /// 근무지기관코드 /// ConsentBySearchVO 객체 List [WebMethod(Description = "동의서 찾기(서식코드)")] public ConsentVO GetConsentByFormcd(string formCd, string instCd) { ConsentVO result = new ConsentVO(); try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); //string formCdArr = ""; //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("formCd", formCd); param.Add("instCd", instCd); result = 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; } } private class ImageServerProps { public string ipAddr; public string remotePath; public string user; public string pwd; public ImageServerProps(ISqlMapper IbatisMapper) { using (CommonCodeDac ccdac = new CommonCodeDac()) { IList props; Hashtable opts = new Hashtable(); props = ccdac.GetImageServerProps(IbatisMapper, opts); foreach (var prop in props) { if (prop.active == "A") { ipAddr = prop.ipaddr; remotePath = prop.localpath; user = prop.username; pwd = prop.userpasswd; break; } } } } } ImageServerProps imageServerProps = null; /// /// CONSENT_MST_RID를 갖고 저장된 동의서 이미지를 조회 /// /// 동의서 마스터 데이터 Rid [WebMethod(Description = "동의서 저장된 이미지 내역 조회")] public List GetConsentImage(string consentMstRid) { List result; try { using (ConsentDac dac = new ConsentDac()) { 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); // 사용자 ID 와 패스워드가 없다면 강제로 하드코딩 해서 기입한다 if (imageServerProps.user == null || imageServerProps.user == "") { imageServerProps.user = "choiadmin"; } if (imageServerProps.pwd == null || imageServerProps.pwd == "") { imageServerProps.pwd = "choiadmin"; } var targetDrive = ""; var destDirectory = imageServerProps.remotePath.Substring(2); var virtualDir = ""; var remotePath = ""; // 경로를 확인하여 가상 디렉토리 경로를 설정한다 if (imageServerProps != null) { targetDrive = imageServerProps.remotePath.Substring(0, 1); switch (targetDrive) { case "W": virtualDir = "his032"; break; case "Z": virtualDir = "his031"; break; } remotePath = imageServerProps.remotePath; } // 계정을 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); // for debug DirectoryInfo destDi = new DirectoryInfo(Server.MapPath("DataTempImage")); var destDirStr = destDi.ToString(); DirectoryInfo origDi = new DirectoryInfo(Server.MapPath(virtualDir)); // 해당 경로에 디렉토리가 없다면 생성하여 준다 if (!destDi.Exists) { destDi.Create(); } foreach (ConsentImageVO img in result) { string newFileName = String.Format(@"{0}{1}", img.ImagePath.Replace("\\", ""), img.ImageFilename); var origDiStr = String.Format(@"{0}\{1}\{2}", origDi.ToString(), remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length), img.ImagePath); // for debug //var origDiStr = String.Format(@"{0}\{1}\{2}\{3}", // origDi.ToString(), // remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length), // "consentTest", // img.ImagePath); var origFullPath = String.Format(@"{0}\{1}", origDiStr, img.ImageFilename); var destFullPath = String.Format(@"{0}\{1}", destDirStr, newFileName); try { File.Copy(origFullPath, destFullPath, true); } catch (Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("file copy error", e); } img.ImagePath = destDirStr; img.ImageFilename = newFileName; } util.ImpersonationEnd(); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation end"); } // ?? 왜 로컬에 있는 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; } } public byte[] xmlData(string xml) { UTF8Encoding encoder = new UTF8Encoding(); Decoder utf8Decode = encoder.GetDecoder(); byte[] toEcodeByte = Convert.FromBase64String(xml); //byte[] toEcodeByte = Encoding.UTF8.GetBytes(xml); int charCount = utf8Decode.GetCharCount(toEcodeByte, 0, toEcodeByte.Length); char[] decodedChar = new char[charCount]; utf8Decode.GetChars(toEcodeByte, 0, toEcodeByte.Length, decodedChar, 0); return toEcodeByte; } /// /// 전자동의서를 임시저장 한다. 안드로이드 저장부분 http connection 변경으로 인한 임시저장 함수 신설 /// /// 로그인 사용자ID /// 환자 등록번호 /// 진료과 코드 /// (작성대상)서식 Rid /// 서식코드 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 동의서 EPT Xml /// 동의서 Data(필드들) Xml /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원구분 /// 병원 구분 /// 병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자 /// 병동 코드 /// 병실 코드 /// 처방번호 /// 처방명 /// 처방코드 /// OCR 코드 /// 생성번호 /// 작성자명 /// 수정자명 /// 주치의 아이디 /// 사용자 부서 코드 /// 동의서 매수 /// 동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제) /// Client구분 (P: PC, M: 모바일) /// 수술예약번호 /// /// CONSENT_MST_RID /// [WebMethod(Description = "동의서 임시저장 NEW")] public SingleReturnData SaveTempDataNew(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 mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo, string consentState) { SingleReturnData result = new SingleReturnData(); byte[] formXmlbyte64 = Convert.FromBase64String(formXml); byte[] dataXmlbyte64 = Convert.FromBase64String(dataXml); formXml = Encoding.UTF8.GetString(formXmlbyte64); dataXml = Encoding.UTF8.GetString(dataXmlbyte64); int reissueConsentMstRid = 0; consentState = string.IsNullOrEmpty(consentState) ? "TEMP" : consentState; consentMstRid = SaveData(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, 0, reissueConsentMstRid, consentState, "N", formXml, dataXml, deviceType, deviceIdentNo, vistType, hosType, clnDate, ward, roomCd, string.Empty, orderNo, orderName, orderCd, ocrCode, cretNo, createUserName, modifyUserName, null, null, null, mainDrId, userDeptCd, pageCnt, actKind, clientType, opRsrvNo); result.responseData = Convert.ToString(consentMstRid); return result; } /// /// 전자동의서를 임시저장 한다. /// /// 로그인 사용자ID /// 환자 등록번호 /// 진료과 코드 /// (작성대상)서식 Rid /// 서식코드 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 동의서 EPT Xml /// 동의서 Data(필드들) Xml /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원구분 /// 병원 구분 /// 병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자 /// 병동 코드 /// 병실 코드 /// 처방번호 /// 처방명 /// 처방코드 /// OCR 코드 /// 생성번호 /// 작성자명 /// 수정자명 /// 주치의 아이디 /// 사용자 부서 코드 /// 동의서 매수 /// 동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제) /// Client구분 (P: PC, M: 모바일) /// 수술예약번호 /// /// CONSENT_MST_RID /// [WebMethod(Description = "동의서 임시저장")] public SingleReturnData SaveTempData(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 mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo, string consentState) { SingleReturnData result = new SingleReturnData(); //string orgFormXml = Unzip(formXml); //string orgDataXml = Unzip(dataXml); //dataXml = Unzip(xmlData(dataXml)); //formXml = Unzip(xmlData(formXml)); //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 + "]"; //paramLog += "deviceIdentNo[" + deviceIdentNo + "]mainDrId[" + mainDrId + "]"; //paramLog += "dataXml[" + dataXml + "]formXml[" + formXml + "]"; //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("dataXml -- > " + dataXml); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("formXml -- > " + formXml); int reissueConsentMstRid = 0; consentState = string.IsNullOrEmpty(consentState) ? "TEMP" : consentState; consentMstRid = SaveData(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, 0, reissueConsentMstRid, consentState, "N", formXml, dataXml, deviceType, deviceIdentNo, vistType, hosType, clnDate, ward, roomCd, string.Empty, orderNo, orderName, orderCd, ocrCode, cretNo, createUserName, modifyUserName, null, null, null, mainDrId, userDeptCd, pageCnt, actKind, clientType, opRsrvNo); result.responseData = Convert.ToString(consentMstRid); return result; } /// /// 전자 동의서를 완료저장 한다. /// /// 로그인 사용자ID /// 환자 등록번호 /// 진료과 코드 /// (작성대상)서식 Rid /// 서식코드 /// 동의서 마스터 데이터 Rid /// 재 작성 대상 동의서 마스터 데이터 Rid /// 동의서 EPT Xml /// 동의서 Data(필드들) Xml /// 장비 유형 (WIN, AND, IOS, PRT 중1) /// 장비 고유 식별자 /// 내원구분 /// 병원 구분 /// 병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자 /// 병동 코드 /// 병실 코드 /// 처방번호 /// 처방명 /// 처방코드 /// The ocr code. /// The cretno. /// 작성자명 /// 수정자명 /// 주치의 아이디 /// 사용자 부서 코드 /// 출력 매수 /// 동작 코드 /// Client 구분 /// 수술 예약 번호 /// l [WebMethod(Description = "동의서 서명 완료")] public int SaveComplete(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 mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) { int reissueConsentMstRid = 0; string consentState = "ELECTR_CMP"; string paperYn = "N"; string reasonForUseN = string.Empty; rewriteConsentMstRid = 0; consentMstRid = SaveData(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, null, null, null, mainDrId, userDeptCd, pageCnt, actKind, clientType, opRsrvNo); return consentMstRid; } /// /// 전자 동의서를 완료저장 한다. 안드로이드 저장부분 http connection 변경으로 인한 인증, 확인 함수 신설 /// /// 로그인 사용자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 = "동의서 서명 완료 NEW")] public SingleReturnData SaveCompleteAllNew(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 fileSize) { SingleReturnData result = new SingleReturnData(); int reissueConsentMstRid = 0; string paperYn = "N"; string reasonForUseN = string.Empty; byte[] formXmlbyte64 = Convert.FromBase64String(formXml); byte[] dataXmlbyte64 = Convert.FromBase64String(dataXml); formXml = Encoding.UTF8.GetString(formXmlbyte64); dataXml = Encoding.UTF8.GetString(dataXmlbyte64); 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, fileSize); result.responseData = Convert.ToString(consentMstRid); return result; } /// /// 전자 동의서를 완료저장 한다. /// /// 로그인 사용자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 SingleReturnData 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 fileSize) { SingleReturnData result = new SingleReturnData(); //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 + "]" + "fileSize[" + fileSize + "]"; //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, fileSize); result.responseData = Convert.ToString(consentMstRid); return result; } /// /// 동의서 삭제/폐기 데이터를 저장 한다. /// /// 로그인 사용자ID /// The consent MST rid int. /// 환자 등록번호 /// 진료과 코드 /// 병동 코드 /// The roomcd. /// (작성대상)서식 Rid /// 서식 코드 /// 재 작성 대상 동의서 마스터 데이터 Rid /// 삭제/폐기 대상 동의서 마스터 데이터 Rid /// 동의서 상태 /// 장비 고유 식별자 /// 진료 형태 /// 기관 코드 /// 진료일 /// 삭제/폐기 사유 /// OCR Tag /// 생성번호 /// 사용자 부서 코드 /// 동의서 매수 /// 동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제) /// Client구분 (P: PC, M: 모바일) /// [WebMethod(Description = "동의서 삭제/폐기 데이터를 저장")] public SingleReturnData SaveDelete(string userId, int consentMstRid, string patientCode, string clnDeptCode, string formCd, string vistType, string hosType, string clnDate, string reasonForUseN, string ocrCode, int cretno, string userDeptCd, string pageCnt, string actKind, string clientType) { SingleReturnData result = new SingleReturnData(); if (this.IbatisSession.IsTransactionStart == false) { this.IbatisSession.BeginTransaction(); } try { using (SaveConsentDac dac = new SaveConsentDac()) { Hashtable param = new Hashtable(); param.Add("userId", userId); param.Add("reasonForUseN", reasonForUseN); param.Add("consentMstRid", consentMstRid); param.Add("ocrTag", ocrCode); int resultInt = dac.UpdateConsentMstForDelete(this.IbatisMapper, param); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("Update resultInt -- > " + resultInt); if (resultInt > 0) { resultInt = dac.DeleteChartpageT(this.IbatisMapper, param); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("Delete resultInt -- > " + resultInt); Hashtable ocrParam = new Hashtable { { "instcd", hosType }, { "ocrtag", ocrCode }, { "pid", patientCode }, { "ordtype", vistType }, { "orddd", clnDate }, { "cretno", cretno }, { "orddrid", null }, { "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 }, { "endYn", "N" } }; dac.InsertPrintData(this.IbatisMapper, ocrParam); } else { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); consentMstRid = -1; } } } 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())); consentMstRid = -1; } result.responseData = Convert.ToString(consentMstRid); return result; } public List GetConsentData(string patientCode, int consentMstRid, string startDt, string endDt, string dutinstcd , string userId) { List result; try { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable { { "patientCode", patientCode }, { "consentMstRid", consentMstRid }, { "startDt", startDt }, { "endDt", endDt }, { "consentState", "'UNFINISHED', 'TEMP'" }, { "instcd", dutinstcd }, { "userId", userId ?? string.Empty} }; result = (List) dac.GetConsentList(this.IbatisMapper, param); } return result; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentList error: {0}", ex.Message)); throw ex; } } /// /// 프린트 출력 후 데이터를 저장 한다. /// /// 로그인 사용자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; } 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"]; String endYn = "N"; if (consentState.Equals("TEMP")) { endYn = "N"; } //새로 작성하는 경우 if (isNewConsentMasterCase) { //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(""); 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 }, { "endYn", endYn } }; dac.InsertPrintData(this.IbatisMapper, ocrParam); // 사용 안함 /* if (!string.IsNullOrEmpty(dataXml)) { Dictionary outputDataDic = DataXmlToDictionary(dataXml); Hashtable paramHashTableForMediHistory = new Hashtable(); paramHashTableForMediHistory.Add("patientCode", patientCode); paramHashTableForMediHistory.Add("clnDate", clnDate.Replace("-", "")); paramHashTableForMediHistory.Add("bp", outputDataDic.ContainsKey("IO_bp") ? outputDataDic["IO_bp"] : ""); paramHashTableForMediHistory.Add("dm", outputDataDic.ContainsKey("IO_dm") ? outputDataDic["IO_dm"] : ""); paramHashTableForMediHistory.Add("heart", outputDataDic.ContainsKey("IO_heart") ? outputDataDic["IO_heart"] : ""); paramHashTableForMediHistory.Add("kidney", outputDataDic.ContainsKey("IO_kidney") ? outputDataDic["IO_kidney"] : ""); paramHashTableForMediHistory.Add("respiration", outputDataDic.ContainsKey("IO_respiration") ? outputDataDic["IO_respiration"] : ""); paramHashTableForMediHistory.Add("hx", outputDataDic.ContainsKey("IO_hx") ? outputDataDic["IO_hx"] : ""); paramHashTableForMediHistory.Add("allergy", outputDataDic.ContainsKey("IO_allergy") ? outputDataDic["IO_allergy"] : ""); paramHashTableForMediHistory.Add("drug", outputDataDic.ContainsKey("IO_drug") ? outputDataDic["IO_drug"] : ""); paramHashTableForMediHistory.Add("smoking", outputDataDic.ContainsKey("IO_smoking") ? outputDataDic["IO_smoking"] : ""); paramHashTableForMediHistory.Add("idio", outputDataDic.ContainsKey("IO_idio") ? outputDataDic["IO_idio"] : ""); paramHashTableForMediHistory.Add("nacrotics", outputDataDic.ContainsKey("IO_nacrotics") ? outputDataDic["IO_nacrotics"] : ""); paramHashTableForMediHistory.Add("airway", outputDataDic.ContainsKey("IO_airway") ? outputDataDic["IO_airway"] : ""); paramHashTableForMediHistory.Add("hemorrhage", outputDataDic.ContainsKey("IO_hemorrhage") ? outputDataDic["IO_hemorrhage"] : ""); paramHashTableForMediHistory.Add("status_etc", outputDataDic.ContainsKey("IO_status_etc") ? outputDataDic["IO_status_etc"] : ""); paramHashTableForMediHistory.Add("userId", userId); dac.SetMediHistory(this.IbatisMapper, paramHashTableForMediHistory); } */ } } 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())); return -1; 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, string fileSize) { string endYn = ""; bool isNewConsentMasterCase = false; if (consentMstRid < 1) { isNewConsentMasterCase = true; } // CERTIFY_CMP 인증저장, ELECTR_CMP 확인저장 if (consentState.Equals("CERTIFY_CMP")) { endYn = "Y"; } else if (consentState.Equals("ELECTR_CMP")) { endYn = "C"; } 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); // TODO 이미지 저장 루틴 확인 및 적용 필요 //imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml // , imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize); } //새로 작성 아닌 경우 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); // TODO 이미지 저장 루틴 확인 및 적용 필요 //imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml, // imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize); } else { dac.UpdateConsentMstForDelete(this.IbatisMapper, paramHashTable); } } //임시저장 또는 저장인 경우 else { Hashtable param = new Hashtable(); param.Add("consentMstRid", consentMstRid); int imageCount = dac.GetConsentImageCount(this.IbatisMapper, param); if (imageCount == 0) { // TODO 이미지 저장 루틴 확인 및 적용 필요 //imageUpload(dac, paramHashTable, userId // , patientCode, vistType, clnDate, dschdd, cretno, ocrCode // , consentMstRid, consentState, formCd, formRid, dataXml // , imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize); } dac.UpdateConsentMst(this.IbatisMapper, paramHashTable); dac.InsertConsentData(this.IbatisMapper, paramHashTable); if (imageCount > 0) { // TODO 이미지 저장 루틴 확인 및 적용 필요 //confirmSaveImageCover(consentMstRid, userId, ocrCode, imageFileJson, consentState); } } } // 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 }, { "endYn", endYn } }; dac.InsertPrintData(this.IbatisMapper, ocrParam); if (consentState.Equals("CERTIFY_CMP")) { // 원무 동의서 연동 지금은 사용하지 않음 // TODO 원무 동의서 연동 여부 //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())); return -1; 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, string fileSize) { // 서명 저장일 경우 emrindxm 테이블에 저장 if (!string.IsNullOrEmpty(consentState) && (consentState.Equals("ELECTR_CMP") || consentState.Equals("CERTIFY_CMP"))) { string clnDeptCode = paramHashTable["clnDeptCd"] == null ? string.Empty : paramHashTable["clnDeptCd"].ToString(); 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 fileSizeCnt = 0; 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); newFileFullName = hospitalWebService.GetFileName(patientCode, visitType, clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno), fileSizeAr[fileSizeCnt], formCd, nowCnt.ToString(), ocrcode, userId, clnDeptCode, dutinstcd); fileSizeCnt++; } 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); //remotePath = "Z:\\ACTIVE_ENC\\M\\TEST"; //destDirectory = "\\ACTIVE_ENC\\M\\TEST"; //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); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("remotePath -- > " + remotePath); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirectory -- > " + destDirectory); 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; } } //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("targetDrive -- > " + targetDrive); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("virtualDir -- > " + virtualDir); // 계정을 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); //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirStr -- > " + destDirStr); // 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("localFile -- > " + localFile); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destFullname -- > " + destFullname); CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("new DateTime() -- > " + DateTime.Now.ToString("yyyyMMddHHmmss")); if (!destDi.Exists) { destDi.Create(); } try { File.Copy(localFile, destFullname); } catch (Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(e); File.Move(destFullname, destFullname.Insert(destFullname.LastIndexOf(".jpg"), "_" + imageHashTable["consentMstRid"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"))); File.Copy(localFile, destFullname); } 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; } } } /// /// 확인저장 재 확인시 이미지 이름을 가져온다 /// 재 업로드하는 이미지를 가져온 이름으로 변경 후 기존의 이미지를 덮어쓴다 /// /// 환자번호 /// ocrTag /// 페이지 번호 //[WebMethod(Description = "!@#")] private string confirmSaveImageCover(int consentMstRidInt, string userId, string ocrCode, string imageFileJson, string consentState) { List result; string fileName = ""; try { using (ConsentDac dac = new ConsentDac()) { Dictionary jsonRoot = fastJSON.JSON.Parse(imageFileJson) as Dictionary; Dictionary pathDic = new Dictionary(); List sPath = new List(); List sFileName = new List(); foreach (KeyValuePair jr in jsonRoot) { if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) { //sPath = ""; //sFileName = ""; string[] filepath = jr.Value.ToString().Split('/'); sPath.Add(filepath[0] + "/" + filepath[1]); sFileName.Add(filepath[2]); } } Hashtable param = new Hashtable(); param.Add("consentMstRid", consentMstRidInt); param.Add("userId", consentMstRidInt); param.Add("ocrCode", ocrCode); param.Add("consentState", consentState); result = (List) dac.GetConsentImageFileName(this.IbatisMapper, param); int cnt = 0; foreach (ConsentImageVO img in result) { fileName = img.ImageFilename; var sUploadPath = img.ImagePath; var remotePath = imageServerProps.remotePath; 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); DirectoryInfo destDi = new DirectoryInfo(destDirStr); var destFullname = String.Format(@"{0}\{1}", destDirStr, fileName); var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath[cnt], sFileName[cnt])); if (!destDi.Exists) { destDi.Create(); } try { File.Copy(localFile, destFullname, true); } catch (Exception e) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(e); File.Move(destFullname, destFullname.Insert(destFullname.LastIndexOf(".jpg"), "_" + consentMstRidInt + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"))); File.Copy(localFile, destFullname); } util.ImpersonationEnd(); cnt++; } dac.UpdateConsentImage(this.IbatisMapper, param); } } catch (Exception ex) { CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload ERROR : [{0}]", ex.ToString())); throw ex; } return fileName; } 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 SingleReturnData CheckConsentState(int consentmstrid, string consent_state) { //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("rid: {0}, state: {1}", consentmstrid, consent_state)); SingleReturnData singleReturnData = new SingleReturnData(); 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) { singleReturnData.responseData = "0"; return singleReturnData; } 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)*/) { singleReturnData.responseData = Convert.ToString(result); return singleReturnData; } 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")) { singleReturnData.responseData = Convert.ToString(result); return singleReturnData; } if (result < StateNo)//로드하려는 동의서의 상태보다 현재 저장된 상태가 더 높은 상태일 경우 { singleReturnData.responseData = "1"; return singleReturnData; } else//로드하려는 동의서보다 현재 저장된 상태가 낮은상태일 경우 또는 같을경우 { singleReturnData.responseData = "0"; return singleReturnData; } } catch { singleReturnData.responseData = "-1"; return singleReturnData; } } [WebMethod(Description = "AGMT 입력을 위한 consent_mst 조회")] public string getAgmtConsentData(string instcd, string ocrtag) { string retStr = string.Empty; using(ConsentDac dac = new ConsentDac()) { // 1. 먼저 OCRTAG 로 consent_mst 쪽에서 데이터를 가져온다 Hashtable param1 = new Hashtable(); param1.Add("instcd", instcd); param1.Add("ocrtag", ocrtag); AgmtVo vo = dac.getConsentMst(this.IbatisMapper, param1); if(vo == null) { return "error, EMA.CONSENT_MST 에 데이터가 없습니다. 입력 파라미터를 다시 확인하세요."; } // BLOB 데이터를 불러 온다. Hashtable parma2 = new Hashtable(); parma2.Add("consentMstRid", vo.consentMstRid); string rawXml = dac.getConsentData(IbatisMapper, parma2); if(string.IsNullOrEmpty(rawXml)) { return "error, BLOB 데이터 호출 오류"; } try { SavePatientConsentInfo(vo.formCd, vo.pid, vo.ocrtag, vo.instcd, vo.clnDate, String.Format("{0}", vo.cretno), vo.ordtype, vo.deptcd, vo.orddrid, vo.createUserId, rawXml); retStr = String.Format("PID: {0}, ordtype: {1}, ocrtag: {2} 의 입원약정서가 pam.pmihagmt 테이블에 Insert 되었습니다.", vo.pid, vo.ordtype, vo.ocrtag); } catch(Exception e) { retStr = e.ToString(); } } return retStr; } private void SavePatientConsentInfo(string p_formcd , string p_pid , string p_ocrtag , string p_instcd , string p_orddd , string p_cretno , string p_ordtype , string p_orddeptcd , string p_orddrid , string p_userid , string p_dataxml) { try { // 원무 동의서 연동 정보 입력 // 1300013649 : 입원약정서(기간)(E) // 1300013647 : 선택진료신청서(E) // 1300013648 : 입원약정서(일반)(E) // 1100012120 : C3-개인정보 수집·이용 제공 동의서 // 1400015188 : C3-개인정보 수집 이용 제공 동의서(중국어) // 1400015531 : C3-개인정보 수집·이용 및 제공 동의서(영어) // 현재 입원 약정서 외에는 사용하지 않음 if (!p_formcd.Equals("1300013648") /*&& !p_formcd.Equals("1300013647") && !p_formcd.Equals("1100012120") && !p_formcd.Equals("1400015188") && !p_formcd.Equals("1400015531")*/ && !p_formcd.Equals("1300013649")) { return; } // 동의서 내부 데이터 추출 Dictionary pamDic = DataXmlToDictionary(p_dataxml); var today = DateTime.Today.ToString("yyyyMMdd"); string fromdt = null, todt = null; if (string.IsNullOrEmpty(pamDic["savCMDCBD_ContStartDate"])) { fromdt = today; } else { fromdt = pamDic["savCMDCBD_ContStartDate"]; } if (string.IsNullOrEmpty(pamDic["savCMDCBD_ContEndDate"])) { todt = today; } else { todt = pamDic["savCMDCBD_ContEndDate"]; } // 선택진료신청서 - 선택 진료 여부 > savCMDCBD_SpDrYN // 입원약정서 - 약정시작일 > savCMDCBD_ContStartDate // 입원약정서 - 약정종료일 > savCMDCBD_ContEndDate // 개인정보이용동의서 - 확인항목 > chkitem00 // 개인정보이용동의서 - 확인여부 > chkvalue Hashtable param = new Hashtable { { "pid", p_pid } , { "ocrtag", p_ocrtag } , { "instcd", p_instcd } , { "orddd", p_orddd } , { "cretno", p_cretno } , { "ordtype", p_ordtype } , { "msflag", "" } , { "orddeptkind", "" } , { "orddeptcd", p_orddeptcd } , { "orddrid", p_orddrid } , { "specordyn", ( pamDic.ContainsKey("savCMDCBD_SpDrYN") ? pamDic["savCMDCBD_SpDrYN"] : "" ) } , { "specdrid", "" } , { "userid", p_userid } , { "contfromdd", fromdt } , { "conttodd", todt } , { "formcd", p_formcd } , { "chkitem", "" } , { "chkvalue", ""} }; using (SaveConsentDac dac = new SaveConsentDac()) { // 선택 진료 신청 동의서 /* if (p_formcd.Equals("1300013647")) { for (int i = 0; i < 9; i++) { param["msflag"] = i == 0 ? "M" : "S"; param["orddeptkind"] = string.Format("0{0}", i); param["specdrid"] = i == 0 ? p_orddrid : "-"; dac.InsertPmcmspif(this.IbatisMapper, param); } } */ // 입원 약정서 if (p_formcd.Equals("1300013648") || p_formcd.Equals("1300013649")) { param["agmttype"] = p_formcd.Equals("1300013648") ? "1" : p_formcd.Equals("1300013649") ? "2" : ""; dac.InsertPmihagmt(this.IbatisMapper, param); } // 개인 정보 이용 동의서 // 개인정보이용동의서 연동 안함 /* List chkItemList = new List(); List chkValueList = new List(); foreach(string key in pamDic.Keys) { if (key.ToLower().Contains("chkitem")) { chkItemList.Add(key); chkValueList.Add(pamDic[key]); } } for (int i = 0; i < chkItemList.Count; i++) { param["chkitem"] = chkItemList[i]; param["chkvalue"] = chkValueList[i]; dac.InsertPmcminfo(this.IbatisMapper, param); } */ } } catch (Exception ex) { if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction(); 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 SingleReturnData duplicateCertConsent(String pid, String instCd, String formCd) { SingleReturnData result = new SingleReturnData(); using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("pid", pid); param.Add("instCd", instCd); param.Add("formCd", formCd); String res = dac.getDupCertConsent(this.IbatisMapper, param); result.responseData = res; return result; } } /// /// 진정동의서 출력 여부 확인 /// /// 사용자 근무지 기관코드 /// 조회할 서식 코드 /// 출력 하여야 할 서식이라면 0 초과의 값을 리턴 /// 0보다 크면 진정동의서 작성 0이면 기존 link서식 작성 [WebMethod(Description = "진정동의서 출력 여부 확인")] public int checkJinJeongDocument(String instcd, String formcd) { using (ConsentDac dac = new ConsentDac()) { int result = 0; Hashtable param = new Hashtable(); param.Add("instcd", instcd); param.Add("formcd", formcd); result = dac.checkJinJeongDocument(this.IbatisMapper, param); return result; } } /// /// 기관코드별 마취 동의서 서식 코드를 조회한다 /// /// /// 마취동의서 서식 코드 [WebMethod(Description = "마취동의서 서식 코드 조회")] public String getLinkedAnstDocument(String instcd) { using (ConsentDac dac = new ConsentDac()) { String formCd = null; Hashtable param = new Hashtable { { "instcd", instcd } }; formCd = dac.getLinkedAsntDocument(this.IbatisMapper, param); return formCd; } } [WebMethod(Description = "수술 관련 동의서 조회")] public string checkOperationDocument(String instcd, String formCd) { using (ConsentDac dac = new ConsentDac()) { Hashtable param = new Hashtable(); param.Add("instcd", instcd); param.Add("formCd", formCd); return dac.checkOperationDocuemnt(this.IbatisMapper, param); } } 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); } } [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; } } }