50. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 10/4/2017 8:04:34 AM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.

50.1 Files compared

# Location File Last Modified
1 rdk.zip\rdk\product\production\rdk\src\resources\cds-patient-list patient-list.js Fri Aug 25 15:36:55 2017 UTC
2 rdk.zip\rdk\product\production\rdk\src\resources\cds-patient-list patient-list.js Tue Oct 3 18:14:06 2017 UTC

50.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 7 1504
Changed 6 12
Inserted 0 0
Removed 0 0

50.3 Comparison options

Whitespace
Character case Differences in character case are significant
Line endings Differences in line endings (CR and LF characters) are ignored
CR/LF characters Not shown in the comparison detail

50.4 Active regular expressions

No regular expressions were active.

50.5 Comparison detail

  1   'use stric t';
  2  
  3   //FUTURE-T ODO: Exami ne the nee d to handl e multiple  patient i dentifier  types.  It  is curren tly assume d that all
  4   //patient  ids are of  type 'pid ' and not  'icn.'  Th is may req uire addin g a new fi eld to eac h id store d in the / /patient l ists
  5  
  6   // set up  the packag es we need
  7   var rdk =  require('. ./../core/ rdk');
  8   var _ = re quire('lod ash');
  9   var utils  = require( './utils.j s');
  10   var Object Id = requi re('mongod b').Object ID;
  11   var testId  = require ('../../ut ils/mongo- utils').va lidateMong oDBId;
  12   var http =  rdk.utils .http;
  13   var nullch ecker = rd k.utils.nu llchecker;
  14  
  15   var dbName  = 'patien tlist';
  16   var patCol lection =  'patientli st';
  17  
  18  
  19   // /////// //////
  20   // Patient  List
  21   // /////// //////
  22  
  23   /**
  24    * Retriev e patient  list(s) us ed in proc essing
  25    *
  26    * @api {g et} /resou rce/cds/pa tient/list [?id=id|na me=name] R equest Pat ientlist
  27    *
  28    * @apiNam e getPatie ntlist
  29    * @apiGro up Patient  List
  30    *
  31    * @apiPar am {String } [id] Pat ientlist i d (24 digi t HEX numb er), id ha s
  32    *            precede nce over n ame
  33    * @apiPar am {String } [name] P atientlist  name (if  id not use d)
  34    *
  35    * @apiSuc cess (200)  {json[]}  data Array  of one or  more Pati entlists
  36    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 00 OK
  37    * {
  38    *     "da ta": [{
  39    *              "name ":
  40    *                       "pat li st one",
  41    *              "defi nition": {
  42    *                  " _id":
  43    *                           "54 f0d4a540d3 7300003a57 11",
  44    *                  " name": "de f one",
  45    *                  " descriptio n": "user  defined de scription  of thisdef inition te mplate",
  46    *                  " expression ": "{and:  [ {or:['A. A', 'B.B'] , {'A.A'}  ]}",
  47    *                  " date":
  48    *                           "20 15-02-27T2 0:33:41.30 8Z",
  49    *                  " scope": "p rivate",
  50    *                  " owner":
  51    *                           " REDACTED "
  52    *              },
  53    *              "pidh istory": [ {
  54    *                       "timest amp": "201 5-03-10T00 :53:55.934 Z",
  55    *                       "pid":  "12345V123 ",
  56    *                       "add":  true
  57    *                  } ],
  58    *              "pati ents": [
  59    *                  " 12345V123" ],
  60    *              "scop e": "priva te",
  61    *                "owner": " R E D A CTED ",
  62    *              "_id" : "54fe407 fc9f41fad0 fff5dc4"
  63    *          }]
  64    * }
  65    *
  66    * @apiErr or (Error  400) messa ge Specifi ed _id not  formatted  correctly
  67    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  68    * { "stat us": 400,
  69    *   "mess age": Argu ment passe d in must  be a singl e String o f 12 bytes  or a stri ng of 24 h ex charact ers }
  70    * @apiErr or (Error  404) . The  id or nam e specifie d does not  exist
  71    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  72    * { "stat us": 404,
  73    *  "messa ge": "Pati entlist no t found" }
  74    *
  75    */
  76   function g etPatientL ist(req, r es) {
  77       req.lo gger.debug ('patient- list.getPa tientList( )');
  78  
  79       if (_. isUndefine d(req.app. subsystems .cds)) {
  80           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  81       }
  82  
  83       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  84           if  (error) {
  85                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  86           }
  87           va r status =  rdk.https tatus.ok;
  88           va r message  = '';
  89           va r match =  utils.comp uteMatch(r eq);
  90  
  91           if  (match.sc ope && (ma tch.scope  !== 'priva te' && mat ch.scope ! == 'site'  && match.s cope !== ' enterprise ')) {
  92                status =  rdk.https tatus.bad_ request; / / 400
  93                message  = 'Scope m ust be spe cified usi ng private  (default) , site or  enterprise ';
  94                return r es.status( status).rd kSend(mess age);
  95           }
  96  
  97           if  (match._i d) {
  98                message  = testId(m atch._id);
  99                if (mess age) {
  100                    retu rn res.sta tus(rdk.ht tpstatus.b ad_request ).rdkSend( message);
  101                }
  102                match._i d = new Ob jectId(mat ch._id);
  103           }
  104           if  (match.na me || matc h._id) {
  105                // db.co llection(p atCollecti on).find(m atch).toAr ray(functi on(err, re sult) {
  106                dbConnec tion.colle ction(patC ollection) .findOne(m atch, func tion(err,  result) {
  107                    mess age = (err  === null)  ? result  : err;
  108                    if ( err === nu ll && _.is Empty(resu lt)) {
  109                         status = r dk.httpsta tus.not_fo und;
  110                         message =  'Patientli st not fou nd';
  111                    }
  112                    retu rn res.sta tus(status ).rdkSend( message);
  113                });
  114           }  else { //  return mul tiple
  115                dbConnec tion.colle ction(patC ollection) .find(matc h).toArray (function( err, resul t) {
  116                    mess age = (err  === null)  ? result  : err;
  117                    if ( err === nu ll && _.is Empty(resu lt)) {
  118                         status = r dk.httpsta tus.not_fo und;
  119                         message =  'Patientli st(s) not  found';
  120                    }
  121                    retu rn res.sta tus(status ).rdkSend( message);
  122                });
  123           }
  124       });
  125   }
  126  
  127  
  128   /**
  129    * Create  Patientlis t used in  processing
  130    *
  131    * @api {p ost} /reso urce/cds/p atient/lis t Create P atientlist
  132    *
  133    * @apiNam e postPati entlist
  134    * @apiGro up Patient  List
  135    *
  136    * @apiHea der {appli cation/jso n} Content -Type
  137    * @apiHea der {json}  content P atientlist  object
  138    * @apiDes cription T he post pa sses the P atientlist  in the co ntent as a
  139    *                  s tringified  json obje ct The hea der will i nclude the  content
  140    *                  l ength, i.e . Content- Length = l ength
  141    *
  142    * @apiSuc cess (201)  {json} da ta Patient list JSON  document
  143    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 01 Created
  144    * {
  145    *     "da ta": [{
  146    *              "name ":
  147    *                       "pat li st one",
  148    *              "defi nition": {
  149    *                  " _id":
  150    *                           "54 f0d4a540d3 7300003a57 11",
  151    *                  " name": "de f one",
  152    *                  " descriptio n": "user  defined de scription  of thisdef inition te mplate",
  153    *                  " expression ": "{and:  [ {or:['A. A', 'B.B'] , {'A.A'}  ]}",
  154    *                  " date":
  155    *                           "20 15-02-27T2 0:33:41.30 8Z",
  156    *                  " scope": "p rivate",
  157    *                  " owner":
  158    *                           " REDACTED "
  159    *              },
  160    *              "pidh istory": [ {
  161    *                       "timest amp": "201 5-03-10T00 :53:55.934 Z",
  162    *                       "pid":  "12345V123 ",
  163    *                       "add":  true
  164    *                  } ],
  165    *              "pati ents": [
  166    *                  " 12345V123" ],
  167    *              "scop e": "priva te",
  168    *                "owner": " R E D A CTED ",
  169    *              "_id" : "54fe407 fc9f41fad0 fff5dc4"
  170    *          }]
  171    * }
  172    * @apiErr or (Error  400) messa ge Patient list docum ent (reque st body) m ust be
  173    *            defined
  174    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  175    * { statu s: 400
  176    *                    message: P atientlist  document  (request b ody) must  be defined  }
  177    * @apiErr or (Error  400) messa ge Scope m ust be spe cified usi ng private
  178    *            (defaul t), site o r enterpri se
  179    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  180    * { statu s: 400 mes sage: Scop e must be  specified  using priv ate (defau lt), site  or enterpr ise }
  181    * @apiErr or (Error  400) messa ge The id  or name sp ecified do es not exi st
  182    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  183    * { statu s: 400 mes sage: Name  or Id and  a Pid req uired }
  184    * @apiErr or (Error  400) messa ge Patient list docum ent can no t have _id  defined
  185    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  186    * { statu s: 400 mes sage: Pati entlist do cument can  not have  _id define d }
  187    * @apiErr or (Error  400) messa ge Patient list.defin ition must  be define d
  188    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  189    * { statu s: 400 mes sage: Pati entlist.de finition m ust be def ined }
  190    * @apiErr or (Error  404) messa ge Source  Patientlis t not foun d
  191    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  192    * { statu s: 404  me ssage: Sou rce Patien tlist not  found }
  193    * @apiErr or (Error  500) {json } error A  system or  database e rror messa ge was
  194    *            returne d
  195    * @apiErr orExample  Error-Resp onse: HTTP /1.1 500 I nternal Se rver Error
  196    * { statu s: 500 mes sage: syst em or data base error  message }
  197    *
  198    *
  199    */
  200   function p ostPatient list(req,  res) {
  201       req.lo gger.debug ('patient- list.postP atientlist ()');
  202  
  203       if (_. isUndefine d(req.app. subsystems .cds)) {
  204           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  205       }
  206  
  207       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  208           if  (error) {
  209                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  210           }
  211           va r status =  rdk.https tatus.crea ted;
  212           va r message  = '';
  213           va r doc = re q.body;
  214  
  215           if  (!doc) {
  216                status =  rdk.https tatus.bad_ request;
  217                message  = 'Patient list docum ent (reque st body) m ust be def ined';
  218                return r es.status( status).rd kSend(mess age);
  219           }
  220           if  (doc.scop e && (doc. scope !==  'private'  && doc.sco pe !== 'si te' && doc .scope !==  'enterpri se')) {
  221                status =  rdk.https tatus.bad_ request; / / 400
  222                message  = 'Scope m ust be spe cified usi ng private  (default) , site or  enterprise ';
  223                return r es.status( status).rd kSend(mess age);
  224           }
  225           de lete doc._ id;
  226  
  227           if  (!doc.nam e) {
  228                status =  rdk.https tatus.bad_ request;
  229                message  = 'Patient list name  must be de fined';
  230                return r es.status( status).rd kSend(mess age);
  231           }
  232           if  (!doc.def inition) {
  233                status =  rdk.https tatus.bad_ request;
  234                message  = 'Patient list.defin ition must  be define d';
  235                return r es.status( status).rd kSend(mess age);
  236           }
  237           do c.date = n ew Date();
  238           if  (!doc.sco pe) {
  239                // defau lt to priv ate scope
  240                doc.scop e = 'priva te';
  241           }
  242           sw itch (doc. scope) {
  243                case 'pr ivate':
  244                    doc. owner = re q.session. user.usern ame;
  245                    brea k;
  246                case 'si te':
  247                    doc. owner = re q.session. user.site;
  248                    brea k;
  249                default:
  250                    dele te doc.own er;
  251           }
  252           do c.pidhisto ry = [];
  253           if  (doc.pati ents === u ndefined)  {
  254                doc.pati ents = [];
  255           }
  256           va r match =  {
  257                name: do c.name,
  258                scope: d oc.scope,
  259                owner: d oc.owner
  260           };
  261           //  Verify th e definiti on does no t already  exist
  262           db Connection .collectio n(patColle ction).fin dOne(match , function (err, resu lt) {
  263                if (!_.i sEmpty(res ult)) {
  264                    mess age = 'Pat ientlist \ '' + doc.n ame + '\'  exists, ca n not be c reated';
  265                    retu rn res.sta tus(rdk.ht tpstatus.c onflict).r dkSend(mes sage);
  266                }
  267                if (err)  {
  268                    retu rn res.sta tus(rdk.ht tpstatus.i nternal_se rver_error ).rdkSend( err);
  269                }
  270                dbConnec tion.colle ction(patC ollection) .insert(do c, functio n(err, res ult) {
  271                    var  message =  (err === n ull) ? res ult.ops :  err;
  272                    if ( err) {
  273                         status = r dk.httpsta tus.intern al_server_ error;
  274                    }
  275                    retu rn res.sta tus(status ).rdkSend( message);
  276                });
  277           }) ;
  278       });
  279   }
  280  
  281  
  282   /**
  283    * Delete  Patientlis t used in  processing
  284    *
  285    * @api {d elete} /re source/cds /patient/l ist?id=id  Delete Pat ientlist ( or name=na me)
  286    * @apiNam e deletePa tientlist
  287    * @apiGro up Patient  List
  288    *
  289    * @apiPar am {String } [id] 24  digit HEX  number doc  id
  290    * @apiPar am {String } [name] P atientlist  name (if  id not use d)
  291    *
  292    * @apiSuc cess (200)  {Number}  data Delet e count
  293    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 00 OK
  294    * { "data ": "1" }
  295    *
  296    * @apiErr or (Error  400) messa ge The id  or name sp ecified do es not exi st
  297    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  298    * { statu s: 400  me ssage: Nam e or Id an d a Pid re quired }
  299    * @apiErr or (Error  404) messa ge Patient list not f ound
  300    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  301    * { statu s: 404 mes sage: Pati entlist no t found }
  302    *
  303    */
  304   function d eletePatie ntlist(req , res) {
  305       req.lo gger.debug ('patient- list.delet ePatientli st()');
  306  
  307       if (_. isUndefine d(req.app. subsystems .cds)) {
  308           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  309       }
  310  
  311       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  312           if  (error) {
  313                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  314           }
  315           va r status =  rdk.https tatus.ok;
  316           va r message  = '';
  317  
  318           va r match =  utils.comp uteMatch(r eq);
  319           if  (match._i d) {
  320                message  = testId(m atch._id);
  321                if (mess age) {
  322                    retu rn res.sta tus(rdk.ht tpstatus.b ad_request ).rdkSend( message);
  323                }
  324                match._i d = new Ob jectId(mat ch._id);
  325           }
  326           if  (!match.n ame && !ma tch._id) {
  327                return r es.status( rdk.httpst atus.bad_r equest).rd kSend('Nam e or Id re quired');
  328           }
  329           db Connection .collectio n(patColle ction).rem ove(match,  function( err, resul t) {
  330                var mess age = (err  === null)  ? result  : err;
  331                if (_.is Empty(err)  && result  === 0) {
  332                    stat us = rdk.h ttpstatus. not_found;
  333                    mess age = 'Pat ient list  not found' ;
  334                }
  335                if (!_.i sEmpty(err )) {
  336                    stat us = rdk.h ttpstatus. bad_reques t;
  337                }
  338                return r es.status( status).rd kSend(mess age);
  339           }) ;
  340       });
  341   }
  342  
  343  
  344   /**
  345    * Add a p atient to  Patientlis t
  346    *
  347    * @api {p ost} /reso urce/cds/p atient/lis t/patients ?id&pid Ad d Patient
  348    *
  349    * @apiNam e addPatie nt
  350    * @apiGro up Patient  List
  351    *
  352    * @apiPar am {String } [id] - 2 4 digit HE X number d oc id
  353    * @apiPar am {String } [name] P atientlist  name (if  id not use d)
  354    * @apiPar am {String } pid Pati ent ID to  be added
  355    *
  356    * @apiSuc cess(200)  {json} dat a update c ount
  357    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 00 OK
  358    *  { "dat a": 1 }
  359    *
  360    * @apiErr or (Error  400) messa ge The id  or name sp ecified do es not exi st
  361    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  362    * { statu s: 400
  363    *                    message: N ame or Id  and a Pid  required }
  364    * @apiErr or (Error  404) messa ge Source  Patientlis t not foun d
  365    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  366    * { statu s: 404
  367    *                    message: S ource Pati entlist no t found }
  368    *
  369    */
  370   function a ddPatient( req, res)  {
  371       req.lo gger.debug ('patient- list.addPa tient()');
  372  
  373       if (_. isUndefine d(req.app. subsystems .cds)) {
  374           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  375       }
  376  
  377       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  378           if  (error) {
  379                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  380           }
  381           va r status =  rdk.https tatus.ok;
  382           va r message  = '';
  383           va r pid = re q.query.pi d;
  384  
  385           //  Find the  patientlis t
  386           va r match =  utils.comp uteMatch(r eq);
  387           if  ((!match. name && !m atch._id)  || !pid) {
  388                status =  rdk.https tatus.bad_ request;
  389                message  = 'Name or  Id and a  Pid requir ed';
  390                return r es.status( status).rd kSend(mess age);
  391           }
  392           if  (match._i d) {
  393                message  = testId(m atch._id);
  394                if (mess age) {
  395                    retu rn res.sta tus(rdk.ht tpstatus.b ad_request ).rdkSend( message);
  396                }
  397                match._i d = new Ob jectId(mat ch._id);
  398           }
  399  
  400           db Connection .collectio n(patColle ction).fin dOne(match , function (err, resu lt) {
  401                if (err  || _.isEmp ty(result) ) {
  402                    if ( err) {
  403                         status = r dk.httpsta tus.intern al_server_ error;
  404                    } el se {
  405                         status = r dk.httpsta tus.not_fo und;
  406                         message =  'Source Pa tientlist  not found' ;
  407                    }
  408                    retu rn res.sta tus(status ).rdkSend( message);
  409                }
  410  
  411                // Add p atient, up date chang e history
  412                if (resu lt.patient s.indexOf( pid) === - 1) {
  413                    resu lt.patient s.push(pid );
  414                }
  415                var obj  = {
  416                    time stamp: new  Date(),
  417                    pid:  pid,
  418                    add:  true
  419                };
  420                result.p idhistory. push(obj);
  421                // updat e the pati ent list
  422                dbConnec tion.colle ction(patC ollection) .update({
  423                    _id:  result._i d
  424                }, resul t, functio n(err, res ult) {
  425                    mess age = (err  === null)  ? result  : err;
  426                    if ( err) {
  427                         status = r dk.httpsta tus.intern al_server_ error;
  428                    }
  429                    retu rn res.sta tus(status ).rdkSend( message);
  430                });
  431           }) ;
  432       });
  433   }
  434  
  435  
  436   /**
  437    * Remove  a patient  from Patie ntlist
  438    *
  439    * @api {d elete} /re source/cds /patient/l ist/patien ts?id=123& pid=abc Re move Patie nt
  440    *
  441    * @apiNam e removePa tient
  442    * @apiGro up Patient  List
  443    *
  444    * @apiPar am {String } [id] - 2 4 digit HE X number d oc id
  445    * @apiPar am {String } [name] P atientlist  name (if  id not use d)
  446    * @apiPar am {String } pid Pati ent ID to  be removed
  447    *
  448    * @apiSuc cess (200)  {json} da ta update  count
  449    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 00 OK
  450    * { "data ": 1 }
  451    *
  452    * @apiErr or (Error  400) messa ge The id  or name sp ecified do es not exi st
  453    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  454    * { statu s: 400
  455    *                    message: N ame or Id  and a Pid  required }
  456    * @apiErr or (Error  404) messa ge Source  Patientlis t not foun d
  457    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  458    * { statu s: 404
  459    *                    message: S ource Pati entlist no t found }
  460    * @apiErr or (Error  500) {json } error A  system or  database e rror messa ge was
  461    *            returne d
  462    * @apiErr orExample  Error-Resp onse: HTTP /1.1 500 I nternal Se rver Error
  463    * { statu s:
  464    *                    500 messag e: system  or databas e error me ssage }
  465    *
  466    */
  467   function r emovePatie nt(req, re s) {
  468       req.lo gger.debug ('patient- list.remov ePatient() ');
  469  
  470       if (_. isUndefine d(req.app. subsystems .cds)) {
  471           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  472       }
  473  
  474       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  475           if  (error) {
  476                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  477           }
  478           va r status =  rdk.https tatus.ok;
  479           va r message  = '';
  480           va r pid = re q.query.pi d;
  481  
  482           //  Find the  patientlis t
  483           va r match =  utils.comp uteMatch(r eq);
  484           if  ((!match. name && !m atch._id)  || !pid) {
  485                status =  rdk.https tatus.bad_ request;
  486                message  = 'Name or  Id and a  Pid requir ed';
  487                return r es.status( status).rd kSend(mess age);
  488           }
  489  
  490           if  (match._i d) {
  491                message  = testId(m atch._id);
  492                if (mess age) {
  493                    retu rn res.sta tus(rdk.ht tpstatus.b ad_request ).rdkSend( message);
  494                }
  495                match._i d = new Ob jectId(mat ch._id);
  496           }
  497  
  498           db Connection .collectio n(patColle ction).fin dOne(match , function (err, resu lt) {
  499                if (err  || _.isEmp ty(result) ) {
  500                    if ( err) {
  501                         status = r dk.httpsta tus.intern al_server_ error;
  502                    } el se {
  503                         status = r dk.httpsta tus.not_fo und;
  504                         message =  'Source Pa tientlist  not found' ;
  505                    }
  506                    retu rn res.sta tus(status ).rdkSend( message);
  507                }
  508  
  509                // Remov e patient  id
  510                var i =  result.pat ients.inde xOf(pid);
  511                if (i >=  0) {
  512                    resu lt.patient s.splice(i , 1);
  513                }
  514                var obj  = {
  515                    time stamp: new  Date(),
  516                    pid:  pid,
  517                    add:  false
  518                };
  519                result.p idhistory. push(obj);
  520                dbConnec tion.colle ction(patC ollection) .update({
  521                    _id:  result._i d
  522                }, resul t, functio n(err, res ult) {
  523                    mess age = (err  === null)  ? result  : err;
  524                    if ( err) {
  525                         status = r dk.httpsta tus.intern al_server_ error;
  526                    }
  527                    retu rn res.sta tus(status ).rdkSend( message);
  528                });
  529           }) ;
  530       });
  531   }
  532  
  533  
  534   /**
  535    * Checks  if a patie nt is a me mber of an y patient  list
  536    *
  537    * @api {g et} /resou rce/cds/pa tient/list /status?ty pe=pid&val ue=9E7A;10 0001 Get M embership  Status
  538    *
  539    * @apiNam e checkPat ientMember shipStatus
  540    * @apiGro up Patient  List
  541    *
  542    * @apiPar am {String } type the  type of t he Patient  ID
  543    * @apiPar am {String } value th e actual P atient ID  value to b e found
  544    *
  545    * @apiSuc cess (200)  {json} da ta boolean  value
  546    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 00 OK
  547    *  { "mes sage": "tr ue", "stat us": 200 }
  548    *
  549    * @apiErr or (Error  400) messa ge The id  or name sp ecified do es not exi st
  550    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  551    * { "mess age": "Pat ient ident ifier type  and value  are requi red", "sta tus": 400  }
  552    * @apiErr or (Error  500) {json } error A  system or  database e rror messa ge was
  553    *            returne d
  554    * @apiErr orExample  Error-Resp onse: HTTP /1.1 500 I nternal Se rver Error
  555    * { statu s: 500 mes sage: syst em or data base error  message }
  556    *
  557    */
  558   function c heckPatien tMembershi pStatus(re q, res) {
  559       req.lo gger.debug ('patient- list.check PatientMem bershipSta tus()');
  560  
  561       if (_. isUndefine d(req.app. subsystems .cds)) {
  562           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  563       }
  564  
  565       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  566           if  (error) {
  567                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  568           }
  569           va r type = r eq.query.t ype;
  570           va r pid = re q.query.va lue;
  571  
  572           if  (!type ||  !pid) {
  573                return r es.status( rdk.httpst atus.bad_r equest).rd kSend('Pat ient ident ifier type  and value  are requi red');
  574           }
  575  
  576           va r jdsResou rce = '/vp r/jpid';
  577           re q.logger.i nfo('jpid  search usi ng pid [%s ]', pid);
  578  
  579           va r jdsPath  = jdsResou rce + '/'  + pid;
  580           va r options  = _.extend ({}, req.a pp.config. jdsServer,  {
  581                url: jds Path,
  582                logger:  req.logger ,
  583                json: tr ue
  584           }) ;
  585  
  586           ht tp.get(opt ions, func tion(error , response , result)  {
  587                if (erro r) {
  588                    req. logger.err or({
  589                         error: err or
  590                    }, ' patient-li st.checkPa tientMembe rshipStatu s error');
  591                    retu rn res.sta tus(rdk.ht tpstatus.o k).rdkSend ('false');
  592                }
  593  
  594                var pati entIdentif iers = res ult.patien tIdentifie rs;
  595                if (null checker.is Nullish(pa tientIdent ifiers)) {
  596                    req. logger.deb ug('No pat ient ident ifiers for  pid [%s]' , pid);
  597                    retu rn res.sta tus(rdk.ht tpstatus.o k).rdkSend ('false');
  598                }
  599  
  600                //FUTURE  - This ma y need fut ure optimi zation.  T he two pos sible appr aches:
  601                //1) add  a multi-k ey index t o the pati ents field  in mongo  (http://do cs.mongodb .org/manua l/core/ind ex-multike y/)
  602                //2) kee p a master  list of p atients wi th a count er to be i ncremented  or decrem ented each  time a pa tient is
  603                //added  to or remo ved from a  list.
  604                var matc hStatement  = {
  605                    pati ents: {
  606                         $in: patie ntIdentifi ers
  607                    }
  608                };
  609                dbConnec tion.colle ction(patC ollection) .findOne(m atchStatem ent, funct ion(err, r esult) {
  610                    if ( err) {
  611                         return res .status(rd k.httpstat us.interna l_server_e rror).rdkS end(err);
  612                    }
  613                    var  isMember =  !_.isEmpt y(_.get(re sult, 'pat ients'));
  614                    retu rn res.sta tus(rdk.ht tpstatus.o k).rdkSend (isMember  ? 'true' :  'false');
  615                });
  616           }) ;
  617       });
  618   }
  619   module.exp orts.check PatientMem bershipSta tus = chec kPatientMe mbershipSt atus;
  620  
  621   /**
  622    * Copy a  Patientlis t
  623    *
  624    * @api {p ost} /reso urce/cds/p atient/lis t/copy?id= 123&newnam e=somename  Copy Pati ent-List
  625    *
  626    * @apiNam e copyPati entlist
  627    * @apiGro up Patient  List
  628    *
  629    * @apiPar am {String } [id] 24  digit HEX  number doc  id
  630    * @apiPar am {String } [name] P atientlist  name (if  id not use d)
  631    * @apiPar am {String } newname  new Patien tlist name
  632    *
  633    * @apiSuc cess (201)  {json} da ta update  count
  634    * @apiSuc cessExampl e Success- Response:  HTTP/1.1 2 01 Created
  635    * {
  636    *     "da ta": [{
  637    *              "name ":
  638    *                       "pat li st one",
  639    *              "defi nition": {
  640    *                  " _id":
  641    *                           "54 f0d4a540d3 7300003a57 11",
  642    *                  " name": "de f one",
  643    *                  " descriptio n": "user  defined de scription  of thisdef inition te mplate",
  644    *                  " expression ": "{and:  [ {or:['A. A', 'B.B'] , {'A.A'}  ]}",
  645    *                  " date":
  646    *                           "20 15-02-27T2 0:33:41.30 8Z",
  647    *                  " scope": "p rivate",
  648    *                  " owner":
  649    *                           " REDACTED "
  650    *              },
  651    *              "pidh istory": [ {
  652    *                       "timest amp": "201 5-03-10T00 :53:55.934 Z",
  653    *                       "pid":  "12345V123 ",
  654    *                       "add":  true
  655    *                  } ],
  656    *              "pati ents": [
  657    *                  " 12345V123" ],
  658    *              "scop e": "priva te",
  659    *                "owner": " R E D A CTED ",
  660    *              "_id" : "54fe407 fc9f41fad0 fff5dc4"
  661    *          }]
  662    * }
  663    *
  664    * @apiErr or (Error  400) messa ge Error o n request
  665    * @apiErr orExample  Error-Resp onse: HTTP /1.1 400 B ad Request
  666    * { statu s: 400
  667    *    mess age: Name  or Id and  a Newname  required }
  668    * @apiErr or (Error  404) messa ge The id  or name sp ecified do es not exi st
  669    * @apiErr orExample  Error-Resp onse: HTTP /1.1 404 N ot Found
  670    * { statu s: 404
  671    *   messa ge: Source  Patientli st not fou nd }
  672    * @apiErr or (Error  409) messa ge The new  name spec ified alre ady exists
  673    * @apiErr orExample  Error-Resp onse: HTTP /1.1 409 C onflict
  674    * { statu s: 409
  675    *  messag e: Patient list docum ent with n ame 'newna me' alread y exists }
  676    * @apiErr or (Error  500) messa ge Severe  internal e rror
  677    * @apiErr orExample  Error-Resp onse: HTTP /1.1 500 I nternal Se rver Error
  678    * { statu s: 500 mes sage: Inte rnal Serve r Error }
  679    *
  680    */
  681   function c opyPatient list(req,  res) {
  682       req.lo gger.debug ('patient- list.copyP atientlist ()');
  683  
  684       if (_. isUndefine d(req.app. subsystems .cds)) {
  685           re turn res.s tatus(rdk. httpstatus .service_u navailable ).rdkSend( 'CDS patie nt list re source is  unavailabl e.');
  686       }
  687  
  688       req.ap p.subsyste ms.cds.get CDSDB(req. logger, db Name, null , function (error, db Connection ) {
  689           if  (error) {
  690                return r es.status( rdk.httpst atus.servi ce_unavail able).rdkS end('CDS p ersistence  store is  unavailabl e.');
  691           }
  692           va r status =  rdk.https tatus.crea ted;
  693           va r message  = '';
  694           va r newname  = req.quer y.newname;
  695  
  696           va r match =  utils.comp uteMatch(r eq);
  697           if  ((!match. name && !m atch._id)  || !newnam e) {
  698                message  = 'Name or  Id and a  Newname re quired';
  699                return r es.status( rdk.httpst atus.bad_r equest).rd kSend(mess age);
  700           }
  701  
  702           if  (match._i d) {
  703                message  = testId(m atch._id);
  704                if (mess age) {
  705                    retu rn res.sta tus(rdk.ht tpstatus.b ad_request ).rdkSend( message);
  706                }
  707                match._i d = new Ob jectId(mat ch._id);
  708           }
  709  
  710           //  retrieve  source Pat ientlist d ocument
  711           db Connection .collectio n(patColle ction).fin dOne(match , function (err, patl st) {
  712                if (err  || _.isEmp ty(patlst) ) {
  713                    if ( err) {
  714                         status = r dk.httpsta tus.intern al_server_ error;
  715                    } el se {
  716                         status = r dk.httpsta tus.not_fo und;
  717                         message =  'Source Pa tientlist  not found' ;
  718                    }
  719                    retu rn res.sta tus(status ).rdkSend( message);
  720                }
  721  
  722                // see i f destinat ion Patien t list doc ument exis ts
  723                delete m atch._id;
  724                match.na me = newna me;
  725                dbConnec tion.colle ction(patC ollection) .findOne(m atch, func tion(err,  test) {
  726                    if ( err || !_. isEmpty(te st)) {
  727                         if (err) {
  728                             status  = rdk.htt pstatus.ba d_request;
  729                             messag e = err;
  730                         } else {
  731                             status  = rdk.htt pstatus.co nflict;
  732                             messag e = 'Patie ntlist doc ument with  name \''  + newname  + '\' alre ady exists ';
  733                         }
  734                         return res .status(st atus).rdkS end(messag e);
  735                    }
  736  
  737                    // c reate a ne w Patientl ist based  on result
  738                    patl st.name =  newname;
  739                    dele te patlst. _id;
  740                    dbCo nnection.c ollection( patCollect ion).inser t(patlst,  function(e rr, result ) {
  741                         message =  (err === n ull) ? res ult.ops :  err;
  742                         if (err) {
  743                             status  = rdk.htt pstatus.in ternal_ser ver_error;
  744                         }
  745                         return res .status(st atus).rdkS end(messag e);
  746                    });
  747                });
  748           }) ;
  749       });
  750   }
  751  
  752  
  753   module.exp orts.getPa tientList  = getPatie ntList;
  754   module.exp orts.postP atientlist  = postPat ientlist;
  755   module.exp orts.delet ePatientli st = delet ePatientli st;
  756   module.exp orts.addPa tient = ad dPatient;
  757   module.exp orts.remov ePatient =  removePat ient;
  758   module.exp orts.copyP atientlist  = copyPat ientlist;