/* * SPDX-License-Identifier: Apache-2.0 */ 'use strict'; const { Contract } = require('fabric-contract-api'); const crypto = require('crypto'); let initPatients = require('./initpatientLedger.json'); let initDoctors = require('./initdoctorLedger.json'); let initAdmins = require('./initadminLedger.json'); let initHosp = require('./inithospLedger.json'); class PatientContract extends Contract { async initLedger(ctx) { console.info('============= START : Initialize Patient Ledger ==========='); const patient = initPatients; for (let i = 0; i < patient.length; i++) { patient[i].docType = 'patient'; await ctx.stub.putState('MRN' + i, Buffer.from(JSON.stringify(patient[i]))); console.info('Added <--> ', patient[i]); } console.info('============= END : Initialize Patient Ledger ==========='); const doctor = initDoctors; console.info('============= START : Initialize Doctor Ledger ==========='); for (let i = 0; i < doctor.length; i++) { patient[i].docType = 'doctor'; await ctx.stub.putState('DOC' + i, Buffer.from(JSON.stringify(doctor[i]))); console.info('Added <--> ', doctor[i]); } console.info('============= END : Initialize Doctor Ledger ==========='); const admin = initAdmins; console.info('============= END : Initialize Admin Ledger ==========='); for (let i = 0; i < admin.length; i++) { admin[i].docType = 'admin'; await ctx.stub.putState('ADMIN' + i, Buffer.from(JSON.stringify(admin[i]))); console.info('Added <--> ', admin[i]); } console.info('============= END : Initialize Admin Ledger ==========='); const hospital = initHosp; console.info('============= END : Initialize Hospital Ledger ==========='); for (let i = 0; i < hospital.length; i++) { hospital[i].docType = 'hospital'; await ctx.stub.putState('HOSP' + i, Buffer.from(JSON.stringify(hospital[i]))); console.info('Added <--> ', hospital[i]); } console.info('============= END : Initialize Hospital Ledger ==========='); } async getAllPatientResults(iterator, isHistory) { let allResults = []; while (true) { let res = await iterator.next(); if (res.value && res.value.value.toString()) { let jsonRes = {}; console.log(res.value.value.toString('utf8')); if (isHistory && isHistory === true) { jsonRes.Timestamp = res.value.timestamp; } jsonRes.Key = res.value.key; try { jsonRes.Record = JSON.parse(res.value.value.toString('utf8')); } catch (err) { console.log(err); jsonRes.Record = res.value.value.toString('utf8'); } allResults.push(jsonRes); } if (res.done) { console.log('end of data'); await iterator.close(); console.info(allResults); return allResults; } } } //PatientContract async patientExists(ctx, patientId) { const buffer = await ctx.stub.getState(patientId); return (!!buffer && buffer.length > 0); } async Patient_updatePatient(ctx, patientId, newAge,newWeight,newmarriageStatus,updatedBy,newPregnant) { const exists = await this.patientExists(ctx, patientId); if (!exists) { throw new Error(`The patient ${patientId} does not exist`); } const patient = await this.Patient_readPatient(ctx, patientId) let isDataChanged = false; if (newAge !== null && newAge !== '' && patient.Age !== newAge) { patient.Age = newAge; isDataChanged = true; } if (newWeight !== null && newWeight !== '' && patient.Weight !== newWeight) { patient.Weight = newWeight; isDataChanged = true; } if (newmarriageStatus!== null && newmarriageStatus !== '' && patient.Marriage_Status !== newmarriageStatus) { patient.Marriage_Status = newmarriageStatus; isDataChanged = true; } if (updatedBy !== null && updatedBy !== '') { patient.changedBy = updatedBy; } if (newPregnant !== null && newPregnant !== '' && patient.Pregnant !== newPregnant) { patient.Pregnant = newPregnant; isDataChanged = true; } if (isDataChanged === false) return; const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } async Patient_readPatient(ctx, patientId) { const exists = await this.patientExists(ctx, patientId); if (!exists) { throw new Error(`The patient ${patientId} does not exist`); } const buffer = await ctx.stub.getState(patientId); const asset = JSON.parse(buffer.toString()); return asset; } async Patient_grantAccessToDoctor(ctx, patientId,doctorId) { // Get the patient asset from world state const patient = await this.Patient_readPatient(ctx, patientId); // unique doctorIDs in Granted if (!patient.permissionGranted.includes(doctorId)) { patient.permissionGranted.push(doctorId); patient.changedBy = patientId; } const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } async Patient_revokeAccessFromDoctor(ctx, patientId,doctorId) { const patient = await this.Patient_readPatient(ctx, patientId); // Remove the doctor if existing if (patient.permissionGranted.includes(doctorId)) { patient.permissionGranted = patient.permissionGranted.filter(doctor => doctor !== doctorId); patient.changedBy = patientId; } const buffer = Buffer.from(JSON.stringify(patient)); // Update the ledger with updated permissionGranted await ctx.stub.putState(patientId, buffer); } //DoctorContract async doctorExists(ctx, doctorId) { const buffer = await ctx.stub.getState(doctorId); return (!!buffer && buffer.length > 0); } async Doctor_readDoctor(ctx, doctorId) { const exists = await this.doctorExists(ctx, doctorId); if (!exists) { throw new Error(`The patient ${doctorId} does not exist`); } const buffer = await ctx.stub.getState(doctorId); const result = JSON.parse(buffer.toString()); return result; } async Doctor_ReadPatients(ctx, patientId,doctorId) { let patient = await this.Patient_readPatient(ctx, patientId); const permissionArray = patient.permissionGranted; if(!permissionArray.includes(doctorId)) { throw new Error(`The doctor ${doctorId} does not have permission to patient ${patientId}`); } patient = ({ patientId: patientId, Age: patient.Age, Weight: patient.Weight, Height: patient.Height, Blood_Group: patient.Blood_Group, BMI: patient.BMI, Marriage_Status: patient.Marriage_Status }); return patient; } async Doctor_updateDoctor(ctx, doctorId, firstName, lastName, password, age, phoneNumber,address, bloodGroup, fields) { const exists = await this.doctorExists(ctx, doctorId); if (!exists) { throw new Error(`The patient ${doctorId} does not exist`); } const doctor = { firstName, lastName, password:crypto.createHash('sha256').update(password).digest('hex'), age, phoneNumber, address, bloodGroup, fields }; const buffer = Buffer.from(JSON.stringify(doctor)); await ctx.stub.putState(doctorId, buffer); } async Doctor_updatePatientDetails(ctx, patientId, newAge, newWeight, newmarriageStatus, updatedBy, newPregnant, newpulseRate, newabortionsNo, newhairLoss) { const exists = await this.patientExists(ctx, patientId); if (!exists) { throw new Error(`The patient ${patientId} does not exist`); } const patient = await this.Patient_readPatient(ctx, patientId); let isDataChanged = false; if (newAge !== null && newAge !== '' && patient.Age !== newAge) { patient.Age = newAge; isDataChanged = true; } if (newWeight !== null && newWeight !== '' && patient.Weight !== newWeight) { patient.Weight = newWeight; isDataChanged = true; } if (newmarriageStatus!== null && newmarriageStatus !== '' && patient.Marriage_Status !== newmarriageStatus) { patient.Marriage_Status = newmarriageStatus; isDataChanged = true; } if (updatedBy !== null && updatedBy !== '') { patient.changedBy = updatedBy; } if (newPregnant !== null && newPregnant !== '' && patient.Pregnant !== newPregnant) { patient.Pregnant = newPregnant; isDataChanged = true; } if (newpulseRate !== null && newpulseRate !== '' && patient.Pulse_rate !== newpulseRate) { patient.Pulse_rate = newpulseRate; isDataChanged = true; } if (newabortionsNo!== null && newabortionsNo !== '' && patient.Abortions_no !== newabortionsNo) { patient.Abortions_no = newabortionsNo; isDataChanged = true; } if (newhairLoss !== null && newhairLoss !== '' && patient.Hair_loss !== newhairLoss) { patient.Hair_loss = newhairLoss; isDataChanged = true; } if (isDataChanged === false) return; const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } //ADMIN contract async AdminExists(ctx, adminId) { const buffer = await ctx.stub.getState(adminId); return (!!buffer && buffer.length > 0); } async readAdminDetails(ctx, adminId) { const exists = await this.AdminExists(ctx, adminId); if (!exists) { throw new Error(`The Admin ${adminId} does not exist`); } const buffer = await ctx.stub.getState(adminId); const asset = JSON.parse(buffer.toString()); return asset; } async Admin_createPatient(ctx, patientId, Age,Weight, Height, BMI, Blood_Group, Pulse_rate ) { const exists = await this.patientExists(ctx, patientId); if (exists) { throw new Error(`The patient ${patientId} already exists`); } const patient = { Age, Weight, Height, BMI, Blood_Group, Pulse_rate, docType: 'patient', }; const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } async Admin_createDoctor(ctx, doctorId,emailId, firstName, lastName,password, age, phoneNumber,Fields) { const exists = await this.doctorExists(ctx, doctorId); if (exists) { throw new Error(`The Doctor ${doctorId} already exists`); } const patient = { emailId, firstName, lastName, password:crypto.createHash('sha256').update(password).digest('hex'), age, phoneNumber, Fields, docType: 'doctor', }; const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(doctorId, buffer); } async Admin_readPatient(ctx, patientId) { const exists = await this.patientExists(ctx, patientId); if (!exists) { throw new Error(`The patient ${patientId} does not exist`); } const buffer = await ctx.stub.getState(patientId); const asset = JSON.parse(buffer.toString()); return asset; } async Admin_readDoctor(ctx, doctorId) { const exists = await this.doctorExists(ctx, doctorId); if (!exists) { throw new Error(`The doctor ${doctorId} does not exist`); } const buffer = await ctx.stub.getState(doctorId); const asset = JSON.parse(buffer.toString()); return asset; } async Admin_deletePatient(ctx, patientId) { const exists = await this.patientExists(ctx, patientId); if (!exists) { throw new Error(`The patient ${patientId} does not exist`); } await ctx.stub.deleteState(patientId); } async Admin_deleteDoctor(ctx, doctorId) { const exists = await this.doctorExists(ctx, doctorId); if (!exists) { throw new Error(`The doctor ${doctorId} does not exist`); } await ctx.stub.deleteState(doctorId); } async queryAllIds(ctx) { let resultsIterator = await ctx.stub.getStateByRange('', ''); let asset = await this.getAllPatientResults(resultsIterator, false); return this.fetchLimitedFields(asset); } async queryAllPatients(ctx) { let resultsIterator = await ctx.stub.getStateByRange('', ''); let result = await this.getAllPatientResults(resultsIterator, false); return this.fetchLimitedFields1(result); } fetchLimitedFields = result => { for (let i = 0; i < result.length; i++) { const obj = result[i]; result[i] = { EntityId: obj.Key, firstName: obj.Record.firstName, lastName: obj.Record.lastName, phoneNumber: obj.Record.phoneNumber, emergPhoneNumber: obj.Record.emergPhoneNumber }; } return result; } fetchLimitedFields1 = result => { for (let i = 0; i < result.length; i++) { const obj = result[i]; result[i] = { EntityId: obj.Key }; } return result; } async getQueryResultForQueryString(ctx, queryString) { let resultsIterator = await ctx.stub.getQueryResult(queryString); console.info('getQueryResultForQueryString <--> ', resultsIterator); let results = await this.getAllPatientResults(resultsIterator, false); return JSON.stringify(results); } async getPatientHistory(ctx, patientId) { let resultsIterator = await ctx.stub.getHistoryForKey(patientId); let asset = await this.getAllPatientResults(resultsIterator, true); return this.fetchLimitedFields(asset, true); } //Insurance Contract async Ins_ReadPatients(ctx, patientId){ let patient = await this.Patient_readPatient(ctx, patientId); patient = ({ patientId: patientId, Age: patient.Age, Weight: patient.Weight, Marriage_Status: patient.Marriage_Status, Height: patient.Height, BMI: patient.BMI, Blood_Group: patient.Blood_Group, Pulse_rate: patient.Pulse_rate }); return patient; } //added hospital functions Admin_createHospital async hospitalExists(ctx, hospitalId) { const buffer = await ctx.stub.getState(hospitalId); return (!!buffer && buffer.length > 0); } async hospital_readhospital(ctx, hospitalId) { const exists = await this.hospitalExists(ctx, hospitalId); if (!exists) { throw new Error(`The hospital ${hospitalId} does not exist`); } const buffer = await ctx.stub.getState(hospitalId); const result = JSON.parse(buffer.toString()); return result; } async hospital_ReadPatients(ctx, patientId,hospitalId) { let patient = await this.Patient_readPatient(ctx, patientId); const permissionArray = patient.permissionGranted; if(!permissionArray.includes(hospitalId)) { throw new Error(`The hospital ${hospitalId} does not have permission to patient ${patientId}`); } patient = ({ patientId: patientId, Age: patient.Age, Weight: patient.Weight, Marriage_Status: patient.Marriage_Status, Height: patient.Height, BMI: patient.BMI, Blood_Group: patient.Blood_Group, Pulse_rate: patient.Pulse_rate }); return patient; } async Patient_grantAccessTohospital(ctx, patientId,hospitalId) { // Get the patient asset from world state const patient = await this.Patient_readPatient(ctx, patientId); // unique doctorIDs in Granted if (!patient.permissionGranted.includes(hospitalId)) { patient.permissionGranted.push(hospitalId); patient.changedBy = patientId; } const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } async Patient_revokeAccessFromhospital(ctx, patientId,hospitalId) { const patient = await this.Patient_readPatient(ctx, patientId); // Remove the doctor if existing if (patient.permissionGranted.includes(hospitalId)) { patient.permissionGranted = patient.permissionGranted.filter(hospital => hospital !== hospitalId); patient.changedBy = patientId; } const buffer = Buffer.from(JSON.stringify(patient)); // Update the ledger with updated permissionGranted await ctx.stub.putState(patientId, buffer); } async Admin_createHospital(ctx, hospitalId,Name, phoneNumber, address, emailId, employeescount, password) { const exists = await this.hospitalExists(ctx, hospitalId); if (exists) { throw new Error(`The hospital ${hospitalId} already exists`); } const patient = { Name, phoneNumber, address, emailId, employeescount, password:crypto.createHash('sha256').update(password).digest('hex'), docType: 'hospital' }; const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(hospitalId, buffer); } // Doctor request access from patient async Doctor_requestAccessfromPatient(ctx, patientId,doctorId) { return this.Patient_grantAccessToDoctor(ctx, patientId,doctorId); } /** * @description Get the client used to connect to the network. */ async getClientId(ctx) { const clientIdentity = ctx.clientIdentity.getID(); // Ouput of the above - 'x509::/OU=client/CN=hosp1admin::/C=US/ST=North Carolina/L=Durham/O=hosp1.lithium.com/CN=ca.hosp1.lithium.com' let identity = clientIdentity.split('::'); identity = identity[1].split('/')[2].split('='); return identity[1].toString('utf8'); } //Pharmacy contract /* async Pharma_Adddetails(ctx, patientId,date,vacId,vacname,dose,pharmaId) { // Get the patient asset from world state const patient = await this.Patient_readPatient(ctx, patientId); // unique doctorIDs in Granted if (!patient.vaccineDetails.includes(vacId)) { patient.vaccineDetails.push({"vaccine Id":vacId, "vaccine date": date,"vaccine name":vacname, "Dose details": dose}); // nietos.push({"01": nieto.label, "02": nieto.value}); patient.changedBy = pharmaId; } const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); } */ async Pharma_ReadPatients(ctx, patientId){ let patient = await this.Patient_readPatient(ctx, patientId); patient = ({ patientId: patientId, Age: patient.Age, Weight: patient.Weight, Marriage_Status: patient.Marriage_Status, Height: patient.Height, BMI: patient.BMI, Blood_Group: patient.Blood_Group, Pulse_rate: patient.Pulse_rate }); return patient; } //Primary Health Centre /*async PHC_addVaccinationdetails(ctx, patientId,date,vacId,vacname,dose,PHCId) { // Get the patient asset from world state const patient = await this.Patient_readPatient(ctx, patientId); // unique doctorIDs in Granted if (!patient.vaccineDetails.includes(vacId)) { patient.vaccineDetails.push({"vaccine Id":vacId, "vaccine date": date,"vaccine name":vacname, "Dose details": dose}); // nietos.push({"01": nieto.label, "02": nieto.value}); patient.changedBy = PHCId; } const buffer = Buffer.from(JSON.stringify(patient)); await ctx.stub.putState(patientId, buffer); }*/ async PHC_ReadPatients(ctx, patientId){ let patient = await this.Patient_readPatient(ctx, patientId); patient = ({ patientId: patientId, Age: patient.Age, Weight: patient.Weight, Marriage_Status: patient.Marriage_Status, Height: patient.Height, BMI: patient.BMI, Blood_Group: patient.Blood_Group, Pulse_rate: patient.Pulse_rate }); return patient; } async processData(ctx, key, value) { // Add logic to process data received from external sources // Update the state or perform any other required actions await ctx.stub.putState(key, Buffer.from(value)); return 'Data processed successfully'; } async getResults(ctx) { // Add logic to retrieve and return results const results = await ctx.stub.getState('resultKey'); return results.toString(); } } module.exports = PatientContract;