db.js 8.85 KB
   const pg = require('pg');
   var isNumber = require("isnumber");
   const fs = require('fs');
   const async = require('async');
   const toCSV = require('array-to-csv')
   const csvToObject = require('csv-to-object')
   var Iconv = require('iconv').Iconv;
   var iconv = new Iconv('EUC-KR', 'UTF-8//TRANSLIT//IGNORE');

   

  const config = {
    host: 'localhost',
    user: 'postgres',     
    password: 'root',
    database: 'khuh_local',
    port: 5432,
    ssl: false
    }; 
   
   const client = new pg.Client(config);
   
   client.connect(err => {
       if (err) throw err;
       else { 
            getPatient("당뇨");
        }
   });
   
   var allPat = [];
   var presTable = [];
   var normalSet={};

    function getPatient(desease) {
       console.log(`1. 모든 환자 리스팅중.`);
       const query = 'select "ID" from "ocsDWIDATA" \
       where "MCD"  in \
      (select "Mcd" from "ocsDWVDIS" \
       where "KorName" like(\'%'+desease+'%\')) \
       union \
      select "ID" from "ocsDWWDATA"  \
       where "MCD"  in \
      (select "Mcd" from "ocsDWVDIS" \
       where "KorName" like(\'%'+desease+'%\')) \
       ORDER BY "ID"';
   
       client.query(query)
           .then(res => {
               allPat = res.rows;
               console.log(allPat.length+"명");
               getAverageSet();
               //process.exit();
           })
           .catch(err => {
               console.log(err);
               process.exit();
           });
    }

    function getAverageSet(){
        console.log("2. 정상범주 가져오는중.");

        var columns = ["code", "name", "val"];
        require("csv-to-array")({
        file: "normal_value_delete_version_utf8.csv",
        columns: columns
        }, function (err, array) {
            array.forEach((value)=>{
                normalSet[value.name]=value.val;
                
            });
            console.log(normalSet);
            buildData();
        });

        /*
        fs.readFile('normal_value_delete_version.csv', 'utf8',function(err,data){
            
            
            let result = csvToObject({
                dilemeter: '\n',
                string: data
            });
            console.log(data);
            normalSet=result;
            buildData();
        });
        */
        
    }

    function buildData(){
        console.log("3. 환자 처방목록 가져오는중.");
        let i=0;
        let sum =0;
        allPat.forEach((patient)=>{
                const query=
                `SELECT "YMD", "DAY2", "SEQ", "ORDCD", "KorName","EngName", "CODE", "CDNM", "KUM", "RR", "DAN", "ARE", "BunCode" \
                    FROM \
                    (SELECT * \
                        FROM \
                            ((SELECT "YMD","SEQ","ORDCD" FROM "ocsDWWORD" WHERE "ocsDWWORD"."ID"='` + patient.ID +`') \
                            UNION \
                            (SELECT "YMD","SEQ","ORDCD" FROM "ocsDWIORD" WHERE "ocsDWIORD"."ID"='` + patient.ID +`')) \
                            AS a \
                    LEFT OUTER JOIN "ocsDWVSUGA" ON "a"."ORDCD"= "ocsDWVSUGA"."SuCode" \
                    ORDER BY "a"."YMD",CAST("a"."SEQ" AS INTEGER)) AS b \
                FULL OUTER JOIN \
                    (SELECT * FROM "ocsKHULAB1" WHERE "ocsKHULAB1"."ID"='` + patient.ID +`') AS c \
                ON "c"."DAY"="b"."YMD" AND "c"."CODE" = "b"."SuCode" \
                WHERE "BunCode" IN ('50','51','54','56','59','61')
                ORDER BY "YMD",CAST("SEQ" AS INTEGER)`;
                
                return client.query(query)
                .then(res => {

                    let resultList = res.rows;
                    let prev=null;
                    let isVisited={};
                     
                    for(let i=0;i<resultList.length;i++){
                        let current = resultList[i];
                        let inspList=[];
                        let presList=[];
                        if(current.DAY2!=null && !isVisited[current.DAY2]){   //검사면,
                            let found=false;
                            let foundDay='';
                            
                            for(let j=i;j<resultList.length;j++){
                                //순회해서 같은 검사결과 날짜를 찾아 검사리스트에 넣는다.
                                if(resultList[j].DAY2!=null && current.DAY2==resultList[j].DAY2){
                                    if(isNumber(resultList[j].RR)){
                                        inspList.push({"code":resultList[j].CODE, "name":resultList[j].CDNM, "value":resultList[j].RR, "scale":resultList[j].DAN});
                                    }
                                }
                                //순회해서 가장 가까운 다음 날짜를 찾는다면 처방리스트에 넣는다.
                                if(resultList[j].DAY2==null){
                                    if(found && foundDay==resultList[j].YMD){
                                        if(resultList[j].KorName){
                                            presList.push({"code":resultList[j].ORDCD,"name":resultList[j].KorName});
                                        }
                                    }else{
                                        if(resultList[j].YMD>current.YMD){
                                            found=true;
                                            foundDay=resultList[j].YMD;
                                            if(resultList[j].KorName){ 
                                                presList.push({"code":resultList[j].ORDCD,"name":resultList[j].KorName}); 
                                            }
                                        }
                                    }
                                }
                                //해당 날짜는 방문 했다고 표시.
                                isVisited[current.DAY2]=true;
                            }
                        }
                        
                        if(inspList.length!=0 && presList.length!=0){
                            let tmpNormal = clone(normalSet);
                            inspList.forEach((insp)=>{
                                //정상범주 row에 존재한다면 넣는다
                                if(tmpNormal[insp.name+'-'+insp.scale]){
                                    tmpNormal[insp.name+'-'+insp.scale]=insp.value;
                                }else if(tmpNormal[insp.name]){
                                    tmpNormal[insp.name]=insp.value; 
                                }
                            });
                            for(let k=0;k<presList.length;k++){
                                for(let l=k+1;l<presList.length;l++){
                                    if(presList[k].name==presList[l].name){
                                        presList.splice(l,1);
                                        l--;
                                    }else{
                                    }
                                }
                            }
                            presList.sort((a,b)=>a.name<b.name);

                            tmpNormal["prescription"]='\"'+presList.map(e=>e.name).join('|').replace(/\"/gi,"").replace(/,/gi,"&").replace(/\n/gi," ")+'\"';
                            
                            //console.log(tmpNormal);
                            //console.log(Object.values(tmpNormal)[125]);
                            presTable.push(Object.values(tmpNormal));
                            //presTable.push({"inspection":inspList, "prescription":presList});
                        }
                        inspList=[];
                        presList=[];
                    }

                    console.log(i + "번 환자("+ patient.ID +") :" +resultList.length + "개의 처방");
                    i++;
                    if(i==allPat.length){
                        let tmpCSV = Object.keys(normalSet).join(',')+',prescription\n';
                        let tmpTable = Object.values(presTable);
                        for(let j=0;j<tmpTable.length;j++){
                            tmpCSV+=tmpTable[j].join(',');
                            if(j!=tmpTable.length-1){
                                tmpCSV+='\n';
                            }
                        }
                        //console.log(tmpCSV);

                        fs.writeFileSync("result.csv", '\ufeff'+ tmpCSV, {encoding: 'utf8'});
                        
                        console.log("끝");
                        process.exit();
                    }
                })
        })
        
    }

    function clone(obj) {
        if (obj === null || typeof(obj) !== 'object')
        return obj;
        var copy = obj.constructor();
        for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) {
            copy[attr] = obj[attr];
          }
        }
        return copy;
      }