treatment

This commit is contained in:
Flatlogic Bot 2025-06-14 12:23:59 +00:00
parent 6e7086cea3
commit 643a791cc9
76 changed files with 7963 additions and 16 deletions

5
.gitignore vendored
View File

@ -1,3 +1,8 @@
node_modules/ node_modules/
*/node_modules/ */node_modules/
*/build/ */build/
**/node_modules/
**/build/
.DS_Store
.env

File diff suppressed because one or more lines are too long

View File

@ -149,6 +149,14 @@ module.exports = class ClinicsDBApi {
transaction, transaction,
}); });
output.diagnoses_clinics = await clinics.getDiagnoses_clinics({
transaction,
});
output.prescriptions_clinics = await clinics.getPrescriptions_clinics({
transaction,
});
return output; return output;
} }

View File

@ -0,0 +1,357 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DiagnosesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const diagnoses = await db.diagnoses.create(
{
id: data.id || undefined,
code: data.code || null,
notes: data.notes || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await diagnoses.setClinics(data.clinics || null, {
transaction,
});
await diagnoses.setTreatment_id(data.treatment_id || null, {
transaction,
});
return diagnoses;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const diagnosesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code || null,
notes: item.notes || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const diagnoses = await db.diagnoses.bulkCreate(diagnosesData, {
transaction,
});
// For each item created, replace relation files
return diagnoses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const diagnoses = await db.diagnoses.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await diagnoses.update(updatePayload, { transaction });
if (data.clinics !== undefined) {
await diagnoses.setClinics(
data.clinics,
{ transaction },
);
}
if (data.treatment_id !== undefined) {
await diagnoses.setTreatment_id(
data.treatment_id,
{ transaction },
);
}
return diagnoses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const diagnoses = await db.diagnoses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of diagnoses) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of diagnoses) {
await record.destroy({ transaction });
}
});
return diagnoses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const diagnoses = await db.diagnoses.findByPk(id, options);
await diagnoses.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await diagnoses.destroy({
transaction,
});
return diagnoses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const diagnoses = await db.diagnoses.findOne({ where }, { transaction });
if (!diagnoses) {
return diagnoses;
}
const output = diagnoses.get({ plain: true });
output.clinics = await diagnoses.getClinics({
transaction,
});
output.treatment_id = await diagnoses.getTreatment_id({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userClinics = (user && user.clinics?.id) || null;
if (userClinics) {
if (options?.currentUser?.clinicsId) {
where.clinicsId = options.currentUser.clinicsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clinics,
as: 'clinics',
},
{
model: db.treatments,
as: 'treatment_id',
where: filter.treatment_id
? {
[Op.or]: [
{
id: {
[Op.in]: filter.treatment_id
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
description: {
[Op.or]: filter.treatment_id
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike('diagnoses', 'code', filter.code),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike('diagnoses', 'notes', filter.notes),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.clinics) {
const listItems = filter.clinics.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
clinicsId: { [Op.or]: listItems },
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.clinicsId;
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.diagnoses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(
query,
limit,
offset,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('diagnoses', 'code', query),
],
};
}
const records = await db.diagnoses.findAll({
attributes: ['id', 'code'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.code,
}));
}
};

View File

@ -168,6 +168,10 @@ module.exports = class PatientsDBApi {
transaction, transaction,
}); });
output.treatments_patient_id = await patients.getTreatments_patient_id({
transaction,
});
output.clinic = await patients.getClinic({ output.clinic = await patients.getClinic({
transaction, transaction,
}); });

View File

@ -0,0 +1,387 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PrescriptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const prescriptions = await db.prescriptions.create(
{
id: data.id || undefined,
medication: data.medication || null,
dosage: data.dosage || null,
instructions: data.instructions || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await prescriptions.setClinics(data.clinics || null, {
transaction,
});
await prescriptions.setTreatment_id(data.treatment_id || null, {
transaction,
});
return prescriptions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const prescriptionsData = data.map((item, index) => ({
id: item.id || undefined,
medication: item.medication || null,
dosage: item.dosage || null,
instructions: item.instructions || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const prescriptions = await db.prescriptions.bulkCreate(prescriptionsData, {
transaction,
});
// For each item created, replace relation files
return prescriptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const prescriptions = await db.prescriptions.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.medication !== undefined)
updatePayload.medication = data.medication;
if (data.dosage !== undefined) updatePayload.dosage = data.dosage;
if (data.instructions !== undefined)
updatePayload.instructions = data.instructions;
updatePayload.updatedById = currentUser.id;
await prescriptions.update(updatePayload, { transaction });
if (data.clinics !== undefined) {
await prescriptions.setClinics(
data.clinics,
{ transaction },
);
}
if (data.treatment_id !== undefined) {
await prescriptions.setTreatment_id(
data.treatment_id,
{ transaction },
);
}
return prescriptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const prescriptions = await db.prescriptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of prescriptions) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of prescriptions) {
await record.destroy({ transaction });
}
});
return prescriptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const prescriptions = await db.prescriptions.findByPk(id, options);
await prescriptions.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await prescriptions.destroy({
transaction,
});
return prescriptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const prescriptions = await db.prescriptions.findOne(
{ where },
{ transaction },
);
if (!prescriptions) {
return prescriptions;
}
const output = prescriptions.get({ plain: true });
output.clinics = await prescriptions.getClinics({
transaction,
});
output.treatment_id = await prescriptions.getTreatment_id({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userClinics = (user && user.clinics?.id) || null;
if (userClinics) {
if (options?.currentUser?.clinicsId) {
where.clinicsId = options.currentUser.clinicsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clinics,
as: 'clinics',
},
{
model: db.treatments,
as: 'treatment_id',
where: filter.treatment_id
? {
[Op.or]: [
{
id: {
[Op.in]: filter.treatment_id
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
description: {
[Op.or]: filter.treatment_id
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.medication) {
where = {
...where,
[Op.and]: Utils.ilike(
'prescriptions',
'medication',
filter.medication,
),
};
}
if (filter.dosage) {
where = {
...where,
[Op.and]: Utils.ilike('prescriptions', 'dosage', filter.dosage),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'prescriptions',
'instructions',
filter.instructions,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.clinics) {
const listItems = filter.clinics.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
clinicsId: { [Op.or]: listItems },
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.clinicsId;
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.prescriptions.findAndCountAll(
queryOptions,
);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(
query,
limit,
offset,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('prescriptions', 'medication', query),
],
};
}
const records = await db.prescriptions.findAll({
attributes: ['id', 'medication'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['medication', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.medication,
}));
}
};

View File

@ -32,6 +32,14 @@ module.exports = class TreatmentsDBApi {
transaction, transaction,
}); });
await treatments.setPatient_id(data.patient_id || null, {
transaction,
});
await treatments.setDoctor_id(data.doctor_id || null, {
transaction,
});
return treatments; return treatments;
} }
@ -95,6 +103,22 @@ module.exports = class TreatmentsDBApi {
); );
} }
if (data.patient_id !== undefined) {
await treatments.setPatient_id(
data.patient_id,
{ transaction },
);
}
if (data.doctor_id !== undefined) {
await treatments.setDoctor_id(
data.doctor_id,
{ transaction },
);
}
return treatments; return treatments;
} }
@ -156,6 +180,10 @@ module.exports = class TreatmentsDBApi {
const output = treatments.get({ plain: true }); const output = treatments.get({ plain: true });
output.diagnoses_treatment_id = await treatments.getDiagnoses_treatment_id({
transaction,
});
output.appointment = await treatments.getAppointment({ output.appointment = await treatments.getAppointment({
transaction, transaction,
}); });
@ -164,6 +192,14 @@ module.exports = class TreatmentsDBApi {
transaction, transaction,
}); });
output.patient_id = await treatments.getPatient_id({
transaction,
});
output.doctor_id = await treatments.getDoctor_id({
transaction,
});
return output; return output;
} }
@ -219,6 +255,58 @@ module.exports = class TreatmentsDBApi {
model: db.clinics, model: db.clinics,
as: 'clinics', as: 'clinics',
}, },
{
model: db.patients,
as: 'patient_id',
where: filter.patient_id
? {
[Op.or]: [
{
id: {
[Op.in]: filter.patient_id
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
first_name: {
[Op.or]: filter.patient_id
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.users,
as: 'doctor_id',
where: filter.doctor_id
? {
[Op.or]: [
{
id: {
[Op.in]: filter.doctor_id
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.doctor_id
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
]; ];
if (filter) { if (filter) {

View File

@ -283,6 +283,10 @@ module.exports = class UsersDBApi {
transaction, transaction,
}); });
output.treatments_doctor_id = await users.getTreatments_doctor_id({
transaction,
});
output.avatar = await users.getAvatar({ output.avatar = await users.getAvatar({
transaction, transaction,
}); });

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'treatments',
'patient_idId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'patients',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('treatments', 'patient_idId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'treatments',
'doctor_idId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('treatments', 'doctor_idId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,90 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable(
'diagnoses',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
updatedById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{ transaction },
);
await queryInterface.addColumn(
'diagnoses',
'clinicsId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'clinics',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('diagnoses', 'clinicsId', {
transaction,
});
await queryInterface.dropTable('diagnoses', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,54 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'diagnoses',
'treatment_idId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'treatments',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('diagnoses', 'treatment_idId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,90 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.createTable(
'prescriptions',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
updatedById: {
type: Sequelize.DataTypes.UUID,
references: {
key: 'id',
model: 'users',
},
},
createdAt: { type: Sequelize.DataTypes.DATE },
updatedAt: { type: Sequelize.DataTypes.DATE },
deletedAt: { type: Sequelize.DataTypes.DATE },
importHash: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{ transaction },
);
await queryInterface.addColumn(
'prescriptions',
'clinicsId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'clinics',
key: 'id',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('prescriptions', 'clinicsId', {
transaction,
});
await queryInterface.dropTable('prescriptions', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,47 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'diagnoses',
'code',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('diagnoses', 'code', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,47 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'diagnoses',
'notes',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('diagnoses', 'notes', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'prescriptions',
'medication',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('prescriptions', 'medication', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,49 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'prescriptions',
'instructions',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('prescriptions', 'instructions', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -82,6 +82,22 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.clinics.hasMany(db.diagnoses, {
as: 'diagnoses_clinics',
foreignKey: {
name: 'clinicsId',
},
constraints: false,
});
db.clinics.hasMany(db.prescriptions, {
as: 'prescriptions_clinics',
foreignKey: {
name: 'clinicsId',
},
constraints: false,
});
//end loop //end loop
db.clinics.belongsTo(db.users, { db.clinics.belongsTo(db.users, {

View File

@ -0,0 +1,69 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const diagnoses = sequelize.define(
'diagnoses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
diagnoses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.diagnoses.belongsTo(db.clinics, {
as: 'clinics',
foreignKey: {
name: 'clinicsId',
},
constraints: false,
});
db.diagnoses.belongsTo(db.treatments, {
as: 'treatment_id',
foreignKey: {
name: 'treatment_idId',
},
constraints: false,
});
db.diagnoses.belongsTo(db.users, {
as: 'createdBy',
});
db.diagnoses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return diagnoses;
};

View File

@ -54,6 +54,14 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.patients.hasMany(db.treatments, {
as: 'treatments_patient_id',
foreignKey: {
name: 'patient_idId',
},
constraints: false,
});
//end loop //end loop
db.patients.belongsTo(db.clinics, { db.patients.belongsTo(db.clinics, {

View File

@ -0,0 +1,73 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const prescriptions = sequelize.define(
'prescriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
medication: {
type: DataTypes.TEXT,
},
dosage: {
type: DataTypes.TEXT,
},
instructions: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
prescriptions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.prescriptions.belongsTo(db.clinics, {
as: 'clinics',
foreignKey: {
name: 'clinicsId',
},
constraints: false,
});
db.prescriptions.belongsTo(db.treatments, {
as: 'treatment_id',
foreignKey: {
name: 'treatment_idId',
},
constraints: false,
});
db.prescriptions.belongsTo(db.users, {
as: 'createdBy',
});
db.prescriptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return prescriptions;
};

View File

@ -38,6 +38,14 @@ module.exports = function (sequelize, DataTypes) {
treatments.associate = (db) => { treatments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.treatments.hasMany(db.diagnoses, {
as: 'diagnoses_treatment_id',
foreignKey: {
name: 'treatment_idId',
},
constraints: false,
});
//end loop //end loop
db.treatments.belongsTo(db.appointments, { db.treatments.belongsTo(db.appointments, {
@ -56,6 +64,22 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.treatments.belongsTo(db.patients, {
as: 'patient_id',
foreignKey: {
name: 'patient_idId',
},
constraints: false,
});
db.treatments.belongsTo(db.users, {
as: 'doctor_id',
foreignKey: {
name: 'doctor_idId',
},
constraints: false,
});
db.treatments.belongsTo(db.users, { db.treatments.belongsTo(db.users, {
as: 'createdBy', as: 'createdBy',
}); });

View File

@ -110,6 +110,14 @@ module.exports = function (sequelize, DataTypes) {
constraints: false, constraints: false,
}); });
db.users.hasMany(db.treatments, {
as: 'treatments_doctor_id',
foreignKey: {
name: 'doctor_idId',
},
constraints: false,
});
//end loop //end loop
db.users.belongsTo(db.roles, { db.users.belongsTo(db.roles, {

View File

@ -114,6 +114,8 @@ module.exports = {
'roles', 'roles',
'permissions', 'permissions',
'clinics', 'clinics',
'diagnoses',
'prescriptions',
, ,
]; ];
await queryInterface.bulkInsert( await queryInterface.bulkInsert(
@ -664,6 +666,56 @@ primary key ("roles_permissionsId", "permissionId")
permissionId: getId('DELETE_TREATMENTS'), permissionId: getId('DELETE_TREATMENTS'),
}, },
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('CREATE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('READ_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('UPDATE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('DELETE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('CREATE_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('READ_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('UPDATE_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('Administrator'),
permissionId: getId('DELETE_PRESCRIPTIONS'),
},
{ {
createdAt, createdAt,
updatedAt, updatedAt,
@ -864,6 +916,56 @@ primary key ("roles_permissionsId", "permissionId")
permissionId: getId('DELETE_CLINICS'), permissionId: getId('DELETE_CLINICS'),
}, },
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('CREATE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('READ_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('UPDATE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('DELETE_DIAGNOSES'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('CREATE_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('READ_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('UPDATE_PRESCRIPTIONS'),
},
{
createdAt,
updatedAt,
roles_permissionsId: getId('SuperAdmin'),
permissionId: getId('DELETE_PRESCRIPTIONS'),
},
{ {
createdAt, createdAt,
updatedAt, updatedAt,

View File

@ -11,6 +11,10 @@ const Treatments = db.treatments;
const Clinics = db.clinics; const Clinics = db.clinics;
const Diagnoses = db.diagnoses;
const Prescriptions = db.prescriptions;
const AppointmentsData = [ const AppointmentsData = [
{ {
// type code here for "relation_one" field // type code here for "relation_one" field
@ -21,7 +25,7 @@ const AppointmentsData = [
end_time: new Date('2023-11-01T09:30:00Z'), end_time: new Date('2023-11-01T09:30:00Z'),
status: 'scheduled', status: 'completed',
// type code here for "relation_one" field // type code here for "relation_one" field
}, },
@ -35,7 +39,7 @@ const AppointmentsData = [
end_time: new Date('2023-11-01T10:30:00Z'), end_time: new Date('2023-11-01T10:30:00Z'),
status: 'scheduled', status: 'completed',
// type code here for "relation_one" field // type code here for "relation_one" field
}, },
@ -63,7 +67,7 @@ const AppointmentsData = [
end_time: new Date('2023-11-01T13:30:00Z'), end_time: new Date('2023-11-01T13:30:00Z'),
status: 'completed', status: 'cancelled',
// type code here for "relation_one" field // type code here for "relation_one" field
}, },
@ -133,7 +137,7 @@ const PaymentsData = [
amount: 150, amount: 150,
method: 'creditcard', method: 'insurance',
payment_date: new Date('2023-11-01T09:30:00Z'), payment_date: new Date('2023-11-01T09:30:00Z'),
@ -145,7 +149,7 @@ const PaymentsData = [
amount: 100, amount: 100,
method: 'cash', method: 'insurance',
payment_date: new Date('2023-11-01T10:30:00Z'), payment_date: new Date('2023-11-01T10:30:00Z'),
@ -157,7 +161,7 @@ const PaymentsData = [
amount: 200, amount: 200,
method: 'insurance', method: 'creditcard',
payment_date: new Date('2023-11-01T11:30:00Z'), payment_date: new Date('2023-11-01T11:30:00Z'),
@ -169,7 +173,7 @@ const PaymentsData = [
amount: 75, amount: 75,
method: 'insurance', method: 'creditcard',
payment_date: new Date('2023-11-01T13:30:00Z'), payment_date: new Date('2023-11-01T13:30:00Z'),
@ -186,6 +190,10 @@ const TreatmentsData = [
cost: 150, cost: 150,
// type code here for "relation_one" field // type code here for "relation_one" field
// type code here for "relation_one" field
// type code here for "relation_one" field
}, },
{ {
@ -196,6 +204,10 @@ const TreatmentsData = [
cost: 100, cost: 100,
// type code here for "relation_one" field // type code here for "relation_one" field
// type code here for "relation_one" field
// type code here for "relation_one" field
}, },
{ {
@ -206,6 +218,10 @@ const TreatmentsData = [
cost: 200, cost: 200,
// type code here for "relation_one" field // type code here for "relation_one" field
// type code here for "relation_one" field
// type code here for "relation_one" field
}, },
{ {
@ -216,6 +232,10 @@ const TreatmentsData = [
cost: 75, cost: 75,
// type code here for "relation_one" field // type code here for "relation_one" field
// type code here for "relation_one" field
// type code here for "relation_one" field
}, },
]; ];
@ -237,6 +257,98 @@ const ClinicsData = [
}, },
]; ];
const DiagnosesData = [
{
// type code here for "relation_one" field
// type code here for "relation_one" field
code: 'Rudolf Virchow',
notes: 'William Bayliss',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
code: 'Claude Bernard',
notes: 'Albert Einstein',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
code: 'Gregor Mendel',
notes: 'Marie Curie',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
code: 'Lynn Margulis',
notes: 'Sheldon Glashow',
},
];
const PrescriptionsData = [
{
// type code here for "relation_one" field
// type code here for "relation_one" field
medication: 'Marie Curie',
dosage: 'Murray Gell-Mann',
instructions: 'Marcello Malpighi',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
medication: 'William Herschel',
dosage: 'Hans Bethe',
instructions: 'Paul Dirac',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
medication: 'Werner Heisenberg',
dosage: 'Emil Kraepelin',
instructions: 'Marie Curie',
},
{
// type code here for "relation_one" field
// type code here for "relation_one" field
medication: 'William Bayliss',
dosage: 'Ernst Mayr',
instructions: 'Anton van Leeuwenhoek',
},
];
// Similar logic for "relation_many" // Similar logic for "relation_many"
async function associateUserWithClinic() { async function associateUserWithClinic() {
@ -699,6 +811,282 @@ async function associateTreatmentWithClinic() {
} }
} }
async function associateTreatmentWithPatient_id() {
const relatedPatient_id0 = await Patients.findOne({
offset: Math.floor(Math.random() * (await Patients.count())),
});
const Treatment0 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Treatment0?.setPatient_id) {
await Treatment0.setPatient_id(relatedPatient_id0);
}
const relatedPatient_id1 = await Patients.findOne({
offset: Math.floor(Math.random() * (await Patients.count())),
});
const Treatment1 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Treatment1?.setPatient_id) {
await Treatment1.setPatient_id(relatedPatient_id1);
}
const relatedPatient_id2 = await Patients.findOne({
offset: Math.floor(Math.random() * (await Patients.count())),
});
const Treatment2 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Treatment2?.setPatient_id) {
await Treatment2.setPatient_id(relatedPatient_id2);
}
const relatedPatient_id3 = await Patients.findOne({
offset: Math.floor(Math.random() * (await Patients.count())),
});
const Treatment3 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Treatment3?.setPatient_id) {
await Treatment3.setPatient_id(relatedPatient_id3);
}
}
async function associateTreatmentWithDoctor_id() {
const relatedDoctor_id0 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Treatment0 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Treatment0?.setDoctor_id) {
await Treatment0.setDoctor_id(relatedDoctor_id0);
}
const relatedDoctor_id1 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Treatment1 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Treatment1?.setDoctor_id) {
await Treatment1.setDoctor_id(relatedDoctor_id1);
}
const relatedDoctor_id2 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Treatment2 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Treatment2?.setDoctor_id) {
await Treatment2.setDoctor_id(relatedDoctor_id2);
}
const relatedDoctor_id3 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const Treatment3 = await Treatments.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Treatment3?.setDoctor_id) {
await Treatment3.setDoctor_id(relatedDoctor_id3);
}
}
async function associateDiagnosisWithClinic() {
const relatedClinic0 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Diagnosis0 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Diagnosis0?.setClinic) {
await Diagnosis0.setClinic(relatedClinic0);
}
const relatedClinic1 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Diagnosis1 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Diagnosis1?.setClinic) {
await Diagnosis1.setClinic(relatedClinic1);
}
const relatedClinic2 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Diagnosis2 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Diagnosis2?.setClinic) {
await Diagnosis2.setClinic(relatedClinic2);
}
const relatedClinic3 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Diagnosis3 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Diagnosis3?.setClinic) {
await Diagnosis3.setClinic(relatedClinic3);
}
}
async function associateDiagnosisWithTreatment_id() {
const relatedTreatment_id0 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Diagnosis0 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Diagnosis0?.setTreatment_id) {
await Diagnosis0.setTreatment_id(relatedTreatment_id0);
}
const relatedTreatment_id1 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Diagnosis1 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Diagnosis1?.setTreatment_id) {
await Diagnosis1.setTreatment_id(relatedTreatment_id1);
}
const relatedTreatment_id2 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Diagnosis2 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Diagnosis2?.setTreatment_id) {
await Diagnosis2.setTreatment_id(relatedTreatment_id2);
}
const relatedTreatment_id3 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Diagnosis3 = await Diagnoses.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Diagnosis3?.setTreatment_id) {
await Diagnosis3.setTreatment_id(relatedTreatment_id3);
}
}
async function associatePrescriptionWithClinic() {
const relatedClinic0 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Prescription0 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Prescription0?.setClinic) {
await Prescription0.setClinic(relatedClinic0);
}
const relatedClinic1 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Prescription1 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Prescription1?.setClinic) {
await Prescription1.setClinic(relatedClinic1);
}
const relatedClinic2 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Prescription2 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Prescription2?.setClinic) {
await Prescription2.setClinic(relatedClinic2);
}
const relatedClinic3 = await Clinics.findOne({
offset: Math.floor(Math.random() * (await Clinics.count())),
});
const Prescription3 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Prescription3?.setClinic) {
await Prescription3.setClinic(relatedClinic3);
}
}
async function associatePrescriptionWithTreatment_id() {
const relatedTreatment_id0 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Prescription0 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Prescription0?.setTreatment_id) {
await Prescription0.setTreatment_id(relatedTreatment_id0);
}
const relatedTreatment_id1 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Prescription1 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Prescription1?.setTreatment_id) {
await Prescription1.setTreatment_id(relatedTreatment_id1);
}
const relatedTreatment_id2 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Prescription2 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Prescription2?.setTreatment_id) {
await Prescription2.setTreatment_id(relatedTreatment_id2);
}
const relatedTreatment_id3 = await Treatments.findOne({
offset: Math.floor(Math.random() * (await Treatments.count())),
});
const Prescription3 = await Prescriptions.findOne({
order: [['id', 'ASC']],
offset: 3,
});
if (Prescription3?.setTreatment_id) {
await Prescription3.setTreatment_id(relatedTreatment_id3);
}
}
module.exports = { module.exports = {
up: async (queryInterface, Sequelize) => { up: async (queryInterface, Sequelize) => {
await Appointments.bulkCreate(AppointmentsData); await Appointments.bulkCreate(AppointmentsData);
@ -711,6 +1099,10 @@ module.exports = {
await Clinics.bulkCreate(ClinicsData); await Clinics.bulkCreate(ClinicsData);
await Diagnoses.bulkCreate(DiagnosesData);
await Prescriptions.bulkCreate(PrescriptionsData);
await Promise.all([ await Promise.all([
// Similar logic for "relation_many" // Similar logic for "relation_many"
@ -733,6 +1125,18 @@ module.exports = {
await associateTreatmentWithAppointment(), await associateTreatmentWithAppointment(),
await associateTreatmentWithClinic(), await associateTreatmentWithClinic(),
await associateTreatmentWithPatient_id(),
await associateTreatmentWithDoctor_id(),
await associateDiagnosisWithClinic(),
await associateDiagnosisWithTreatment_id(),
await associatePrescriptionWithClinic(),
await associatePrescriptionWithTreatment_id(),
]); ]);
}, },
@ -746,5 +1150,9 @@ module.exports = {
await queryInterface.bulkDelete('treatments', null, {}); await queryInterface.bulkDelete('treatments', null, {});
await queryInterface.bulkDelete('clinics', null, {}); await queryInterface.bulkDelete('clinics', null, {});
await queryInterface.bulkDelete('diagnoses', null, {});
await queryInterface.bulkDelete('prescriptions', null, {});
}, },
}; };

View File

@ -0,0 +1,87 @@
const { v4: uuid } = require('uuid');
const db = require('../models');
const Sequelize = require('sequelize');
const config = require('../../config');
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{
id: getId(`CREATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `CREATE_${name.toUpperCase()}`,
},
{
id: getId(`READ_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `READ_${name.toUpperCase()}`,
},
{
id: getId(`UPDATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `UPDATE_${name.toUpperCase()}`,
},
{
id: getId(`DELETE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `DELETE_${name.toUpperCase()}`,
},
];
}
const entities = ['diagnoses'];
const createdPermissions = entities.flatMap(createPermissions);
// Add permissions to database
await queryInterface.bulkInsert('permissions', createdPermissions);
// Get permissions ids
const permissionsIds = createdPermissions.map((p) => p.id);
// Get admin role
const adminRole = await db.roles.findOne({
where: { name: config.roles.super_admin },
});
if (adminRole) {
// Add permissions to admin role if it exists
await adminRole.addPermissions(permissionsIds);
}
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete(
'permissions',
entities.flatMap(createPermissions),
);
},
};

View File

@ -0,0 +1,87 @@
const { v4: uuid } = require('uuid');
const db = require('../models');
const Sequelize = require('sequelize');
const config = require('../../config');
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{
id: getId(`CREATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `CREATE_${name.toUpperCase()}`,
},
{
id: getId(`READ_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `READ_${name.toUpperCase()}`,
},
{
id: getId(`UPDATE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `UPDATE_${name.toUpperCase()}`,
},
{
id: getId(`DELETE_${name.toUpperCase()}`),
createdAt,
updatedAt,
name: `DELETE_${name.toUpperCase()}`,
},
];
}
const entities = ['prescriptions'];
const createdPermissions = entities.flatMap(createPermissions);
// Add permissions to database
await queryInterface.bulkInsert('permissions', createdPermissions);
// Get permissions ids
const permissionsIds = createdPermissions.map((p) => p.id);
// Get admin role
const adminRole = await db.roles.findOne({
where: { name: config.roles.super_admin },
});
if (adminRole) {
// Add permissions to admin role if it exists
await adminRole.addPermissions(permissionsIds);
}
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete(
'permissions',
entities.flatMap(createPermissions),
);
},
};

View File

@ -37,6 +37,10 @@ const permissionsRoutes = require('./routes/permissions');
const clinicsRoutes = require('./routes/clinics'); const clinicsRoutes = require('./routes/clinics');
const diagnosesRoutes = require('./routes/diagnoses');
const prescriptionsRoutes = require('./routes/prescriptions');
const getBaseUrl = (url) => { const getBaseUrl = (url) => {
if (!url) return ''; if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url; return url.endsWith('/api') ? url.slice(0, -4) : url;
@ -150,6 +154,18 @@ app.use(
clinicsRoutes, clinicsRoutes,
); );
app.use(
'/api/diagnoses',
passport.authenticate('jwt', { session: false }),
diagnosesRoutes,
);
app.use(
'/api/prescriptions',
passport.authenticate('jwt', { session: false }),
prescriptionsRoutes,
);
app.use( app.use(
'/api/openai', '/api/openai',
passport.authenticate('jwt', { session: false }), passport.authenticate('jwt', { session: false }),

View File

@ -0,0 +1,455 @@
const express = require('express');
const DiagnosesService = require('../services/diagnoses');
const DiagnosesDBApi = require('../db/api/diagnoses');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('diagnoses'));
/**
* @swagger
* components:
* schemas:
* Diagnoses:
* type: object
* properties:
* code:
* type: string
* default: code
* notes:
* type: string
* default: notes
*/
/**
* @swagger
* tags:
* name: Diagnoses
* description: The Diagnoses managing API
*/
/**
* @swagger
* /api/diagnoses:
* post:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Diagnoses"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await DiagnosesService.create(
req.body.data,
req.currentUser,
true,
link.host,
);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Diagnoses"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post(
'/bulk-import',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await DiagnosesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/diagnoses/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Diagnoses"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put(
'/:id',
wrapAsync(async (req, res) => {
await DiagnosesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/diagnoses/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete(
'/:id',
wrapAsync(async (req, res) => {
await DiagnosesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/diagnoses/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post(
'/deleteByIds',
wrapAsync(async (req, res) => {
await DiagnosesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/diagnoses:
* get:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Get all diagnoses
* description: Get all diagnoses
* responses:
* 200:
* description: Diagnoses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const filetype = req.query.filetype;
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await DiagnosesDBApi.findAll(req.query, globalAccess, {
currentUser,
});
if (filetype && filetype === 'csv') {
const fields = ['id', 'code', 'notes'];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv);
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}),
);
/**
* @swagger
* /api/diagnoses/count:
* get:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Count all diagnoses
* description: Count all diagnoses
* responses:
* 200:
* description: Diagnoses count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/count',
wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await DiagnosesDBApi.findAll(req.query, globalAccess, {
countOnly: true,
currentUser,
});
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/diagnoses/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Find all diagnoses that match search criteria
* description: Find all diagnoses that match search criteria
* responses:
* 200:
* description: Diagnoses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Diagnoses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id;
const payload = await DiagnosesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess,
organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/diagnoses/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Diagnoses]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Diagnoses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get(
'/:id',
wrapAsync(async (req, res) => {
const payload = await DiagnosesDBApi.findBy({ id: req.params.id });
res.status(200).send(payload);
}),
);
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,462 @@
const express = require('express');
const PrescriptionsService = require('../services/prescriptions');
const PrescriptionsDBApi = require('../db/api/prescriptions');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('prescriptions'));
/**
* @swagger
* components:
* schemas:
* Prescriptions:
* type: object
* properties:
* medication:
* type: string
* default: medication
* dosage:
* type: string
* default: dosage
* instructions:
* type: string
* default: instructions
*/
/**
* @swagger
* tags:
* name: Prescriptions
* description: The Prescriptions managing API
*/
/**
* @swagger
* /api/prescriptions:
* post:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Prescriptions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PrescriptionsService.create(
req.body.data,
req.currentUser,
true,
link.host,
);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Prescriptions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post(
'/bulk-import',
wrapAsync(async (req, res) => {
const referer =
req.headers.referer ||
`${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await PrescriptionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/prescriptions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Prescriptions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put(
'/:id',
wrapAsync(async (req, res) => {
await PrescriptionsService.update(
req.body.data,
req.body.id,
req.currentUser,
);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/prescriptions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete(
'/:id',
wrapAsync(async (req, res) => {
await PrescriptionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/prescriptions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post(
'/deleteByIds',
wrapAsync(async (req, res) => {
await PrescriptionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/prescriptions:
* get:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Get all prescriptions
* description: Get all prescriptions
* responses:
* 200:
* description: Prescriptions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const filetype = req.query.filetype;
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await PrescriptionsDBApi.findAll(req.query, globalAccess, {
currentUser,
});
if (filetype && filetype === 'csv') {
const fields = ['id', 'medication', 'dosage', 'instructions'];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv);
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}),
);
/**
* @swagger
* /api/prescriptions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Count all prescriptions
* description: Count all prescriptions
* responses:
* 200:
* description: Prescriptions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/count',
wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await PrescriptionsDBApi.findAll(req.query, globalAccess, {
countOnly: true,
currentUser,
});
res.status(200).send(payload);
}),
);
/**
* @swagger
* /api/prescriptions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Find all prescriptions that match search criteria
* description: Find all prescriptions that match search criteria
* responses:
* 200:
* description: Prescriptions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Prescriptions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id;
const payload = await PrescriptionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess,
organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/prescriptions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Prescriptions]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Prescriptions"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get(
'/:id',
wrapAsync(async (req, res) => {
const payload = await PrescriptionsDBApi.findBy({ id: req.params.id });
res.status(200).send(payload);
}),
);
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const DiagnosesDBApi = require('../db/api/diagnoses');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class DiagnosesService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await DiagnosesDBApi.create(data, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
});
await DiagnosesDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let diagnoses = await DiagnosesDBApi.findBy({ id }, { transaction });
if (!diagnoses) {
throw new ValidationError('diagnosesNotFound');
}
const updatedDiagnoses = await DiagnosesDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedDiagnoses;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await DiagnosesDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await DiagnosesDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,117 @@
const db = require('../db/models');
const PrescriptionsDBApi = require('../db/api/prescriptions');
const processFile = require('../middlewares/upload');
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class PrescriptionsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await PrescriptionsDBApi.create(data, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, 'utf-8')); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
});
await PrescriptionsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let prescriptions = await PrescriptionsDBApi.findBy(
{ id },
{ transaction },
);
if (!prescriptions) {
throw new ValidationError('prescriptionsNotFound');
}
const updatedPrescriptions = await PrescriptionsDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedPrescriptions;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await PrescriptionsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await PrescriptionsDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -48,6 +48,10 @@ module.exports = class SearchService {
treatments: ['description'], treatments: ['description'],
clinics: ['name'], clinics: ['name'],
diagnoses: ['code', 'notes'],
prescriptions: ['medication', 'dosage', 'instructions'],
}; };
const columnsInt = { const columnsInt = {
payments: ['amount'], payments: ['amount'],

View File

@ -0,0 +1 @@
{}

View File

@ -0,0 +1,125 @@
import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
diagnoses: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const CardDiagnoses = ({
diagnoses,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const asideScrollbarsStyle = useAppSelector(
(state) => state.style.asideScrollbarsStyle,
);
const bgColor = useAppSelector((state) => state.style.cardsColor);
const darkMode = useAppSelector((state) => state.style.darkMode);
const corners = useAppSelector((state) => state.style.corners);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_DIAGNOSES');
return (
<div className={'p-4'}>
{loading && <LoadingSpinner />}
<ul
role='list'
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
>
{!loading &&
diagnoses.map((item, index) => (
<li
key={item.id}
className={`overflow-hidden ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} border ${focusRing} border-gray-200 dark:border-dark-700 ${
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
}`}
>
<div
className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}
>
<Link
href={`/diagnoses/diagnoses-view/?id=${item.id}`}
className='text-lg font-bold leading-6 line-clamp-1'
>
{item.code}
</Link>
<div className='ml-auto '>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/diagnoses/diagnoses-edit/?id=${item.id}`}
pathView={`/diagnoses/diagnoses-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</div>
<dl className='divide-y divide-stone-300 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Treatment_id
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.treatmentsOneListFormatter(
item.treatment_id,
)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>Code</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>{item.code}</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>Notes</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>{item.notes}</div>
</dd>
</div>
</dl>
</li>
))}
{!loading && diagnoses.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</ul>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</div>
);
};
export default CardDiagnoses;

View File

@ -0,0 +1,103 @@
import React from 'react';
import CardBox from '../CardBox';
import ImageField from '../ImageField';
import dataFormatter from '../../helpers/dataFormatter';
import { saveFile } from '../../helpers/fileSaver';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
diagnoses: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const ListDiagnoses = ({
diagnoses,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_DIAGNOSES');
const corners = useAppSelector((state) => state.style.corners);
const bgColor = useAppSelector((state) => state.style.cardsColor);
return (
<>
<div className='relative overflow-x-auto p-4 space-y-4'>
{loading && <LoadingSpinner />}
{!loading &&
diagnoses.map((item) => (
<div key={item.id}>
<CardBox hasTable isList className={'rounded shadow-none'}>
<div
className={`flex ${bgColor} ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 border border-stone-300 items-center overflow-hidden`}
>
<Link
href={`/diagnoses/diagnoses-view/?id=${item.id}`}
className={
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-stone-300 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
}
>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Treatment_id</p>
<p className={'line-clamp-2'}>
{dataFormatter.treatmentsOneListFormatter(
item.treatment_id,
)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Code</p>
<p className={'line-clamp-2'}>{item.code}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Notes</p>
<p className={'line-clamp-2'}>{item.notes}</p>
</div>
</Link>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/diagnoses/diagnoses-edit/?id=${item.id}`}
pathView={`/diagnoses/diagnoses-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</CardBox>
</div>
))}
{!loading && diagnoses.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</div>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</>
);
};
export default ListDiagnoses;

View File

@ -0,0 +1,487 @@
import React, { useEffect, useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton';
import CardBoxModal from '../CardBoxModal';
import CardBox from '../CardBox';
import {
fetch,
update,
deleteItem,
setRefetch,
deleteItemsByIds,
} from '../../stores/diagnoses/diagnosesSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { Field, Form, Formik } from 'formik';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { loadColumns } from './configureDiagnosesCols';
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter';
import { dataGridStyles } from '../../styles';
const perPage = 10;
const TableSampleDiagnoses = ({
filterItems,
setFilterItems,
filters,
showGrid,
}) => {
const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });
const dispatch = useAppDispatch();
const router = useRouter();
const pagesList = [];
const [id, setId] = useState(null);
const [currentPage, setCurrentPage] = useState(0);
const [filterRequest, setFilterRequest] = React.useState('');
const [columns, setColumns] = useState<GridColDef[]>([]);
const [selectedRows, setSelectedRows] = useState([]);
const [sortModel, setSortModel] = useState([
{
field: '',
sort: 'desc',
},
]);
const {
diagnoses,
loading,
count,
notify: diagnosesNotify,
refetch,
} = useAppSelector((state) => state.diagnoses);
const { currentUser } = useAppSelector((state) => state.auth);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
const corners = useAppSelector((state) => state.style.corners);
const numPages =
Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
for (let i = 0; i < numPages; i++) {
pagesList.push(i);
}
const loadData = async (page = currentPage, request = filterRequest) => {
if (page !== currentPage) setCurrentPage(page);
if (request !== filterRequest) setFilterRequest(request);
const { sort, field } = sortModel[0];
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
dispatch(fetch({ limit: perPage, page, query }));
};
useEffect(() => {
if (diagnosesNotify.showNotification) {
notify(
diagnosesNotify.typeNotification,
diagnosesNotify.textNotification,
);
}
}, [diagnosesNotify.showNotification]);
useEffect(() => {
if (!currentUser) return;
loadData();
}, [sortModel, currentUser]);
useEffect(() => {
if (refetch) {
loadData(0);
dispatch(setRefetch(false));
}
}, [refetch, dispatch]);
const [isModalInfoActive, setIsModalInfoActive] = useState(false);
const [isModalTrashActive, setIsModalTrashActive] = useState(false);
const handleModalAction = () => {
setIsModalInfoActive(false);
setIsModalTrashActive(false);
};
const handleDeleteModalAction = (id: string) => {
setId(id);
setIsModalTrashActive(true);
};
const handleDeleteAction = async () => {
if (id) {
await dispatch(deleteItem(id));
await loadData(0);
setIsModalTrashActive(false);
}
};
const generateFilterRequests = useMemo(() => {
let request = '&';
filterItems.forEach((item) => {
const isRangeFilter = filters.find(
(filter) =>
filter.title === item.fields.selectedField &&
(filter.number || filter.date),
);
if (isRangeFilter) {
const from = item.fields.filterValueFrom;
const to = item.fields.filterValueTo;
if (from) {
request += `${item.fields.selectedField}Range=${from}&`;
}
if (to) {
request += `${item.fields.selectedField}Range=${to}&`;
}
} else {
const value = item.fields.filterValue;
if (value) {
request += `${item.fields.selectedField}=${value}&`;
}
}
});
return request;
}, [filterItems, filters]);
const deleteFilter = (value) => {
const newItems = filterItems.filter((item) => item.id !== value);
if (newItems.length) {
setFilterItems(newItems);
} else {
loadData(0, '');
setFilterItems(newItems);
}
};
const handleSubmit = () => {
loadData(0, generateFilterRequests);
};
const handleChange = (id) => (e) => {
const value = e.target.value;
const name = e.target.name;
setFilterItems(
filterItems.map((item) => {
if (item.id !== id) return item;
if (name === 'selectedField') return { id, fields: { [name]: value } };
return { id, fields: { ...item.fields, [name]: value } };
}),
);
};
const handleReset = () => {
setFilterItems([]);
loadData(0, '');
};
const onPageChange = (page: number) => {
loadData(page);
setCurrentPage(page);
};
useEffect(() => {
if (!currentUser) return;
loadColumns(handleDeleteModalAction, `diagnoses`, currentUser).then(
(newCols) => setColumns(newCols),
);
}, [currentUser]);
const handleTableSubmit = async (id: string, data) => {
if (!_.isEmpty(data)) {
await dispatch(update({ id, data }))
.unwrap()
.then((res) => res)
.catch((err) => {
throw new Error(err);
});
}
};
const onDeleteRows = async (selectedRows) => {
await dispatch(deleteItemsByIds(selectedRows));
await loadData(0);
};
const controlClasses =
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
` ${bgColor} ${focusRing} ${corners} ` +
'dark:bg-slate-800 border';
const dataGrid = (
<div className='relative overflow-x-auto'>
<DataGrid
autoHeight
rowHeight={64}
sx={dataGridStyles}
className={'datagrid--table'}
getRowClassName={() => `datagrid--row`}
rows={diagnoses ?? []}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 10,
},
},
}}
disableRowSelectionOnClick
onProcessRowUpdateError={(params) => {
console.log('Error', params);
}}
processRowUpdate={async (newRow, oldRow) => {
const data = dataFormatter.dataGridEditFormatter(newRow);
try {
await handleTableSubmit(newRow.id, data);
return newRow;
} catch {
return oldRow;
}
}}
sortingMode={'server'}
checkboxSelection
onRowSelectionModelChange={(ids) => {
setSelectedRows(ids);
}}
onSortModelChange={(params) => {
params.length
? setSortModel(params)
: setSortModel([{ field: '', sort: 'desc' }]);
}}
rowCount={count}
pageSizeOptions={[10]}
paginationMode={'server'}
loading={loading}
onPaginationModelChange={(params) => {
onPageChange(params.page);
}}
/>
</div>
);
return (
<>
{filterItems && Array.isArray(filterItems) && filterItems.length ? (
<CardBox>
<Formik
initialValues={{
checkboxes: ['lorem'],
switches: ['lorem'],
radio: 'lorem',
}}
onSubmit={() => null}
>
<Form>
<>
{filterItems &&
filterItems.map((filterItem) => {
return (
<div key={filterItem.id} className='flex mb-4'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Filter
</div>
<Field
className={controlClasses}
name='selectedField'
id='selectedField'
component='select'
value={filterItem?.fields?.selectedField || ''}
onChange={handleChange(filterItem.id)}
>
{filters.map((selectOption) => (
<option
key={selectOption.title}
value={`${selectOption.title}`}
>
{selectOption.label}
</option>
))}
</Field>
</div>
{filters.find(
(filter) =>
filter.title === filterItem?.fields?.selectedField,
)?.type === 'enum' ? (
<div className='flex flex-col w-full mr-3'>
<div className='text-gray-500 font-bold'>Value</div>
<Field
className={controlClasses}
name='filterValue'
id='filterValue'
component='select'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
>
<option value=''>Select Value</option>
{filters
.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)
?.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</Field>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.number ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.date ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
type='datetime-local'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
type='datetime-local'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : (
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Contains
</div>
<Field
className={controlClasses}
name='filterValue'
placeholder='Contained'
id='filterValue'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
)}
<div className='flex flex-col'>
<div className=' text-gray-500 font-bold'>
Action
</div>
<BaseButton
className='my-2'
type='reset'
color='danger'
label='Delete'
onClick={() => {
deleteFilter(filterItem.id);
}}
/>
</div>
</div>
);
})}
<div className='flex'>
<BaseButton
className='my-2 mr-3'
type='submit'
color='info'
label='Apply'
onClick={handleSubmit}
/>
<BaseButton
className='my-2'
type='reset'
color='info'
outline
label='Cancel'
onClick={handleReset}
/>
</div>
</>
</Form>
</Formik>
</CardBox>
) : null}
<CardBoxModal
title='Please confirm'
buttonColor='info'
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
isActive={isModalTrashActive}
onConfirm={handleDeleteAction}
onCancel={handleModalAction}
>
<p>Are you sure you want to delete this item?</p>
</CardBoxModal>
{dataGrid}
{selectedRows.length > 0 &&
createPortal(
<BaseButton
className='me-4'
color='danger'
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
onClick={() => onDeleteRows(selectedRows)}
/>,
document.getElementById('delete-rows-button'),
)}
<ToastContainer />
</>
);
};
export default TableSampleDiagnoses;

View File

@ -0,0 +1,106 @@
import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
GridActionsCellItem,
GridRowParams,
GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import DataGridMultiSelect from '../DataGridMultiSelect';
import ListActionsPopover from '../ListActionsPopover';
import { hasPermission } from '../../helpers/userPermissions';
type Params = (id: string) => void;
export const loadColumns = async (
onDelete: Params,
entityName: string,
user,
) => {
async function callOptionsApi(entityName: string) {
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
try {
const data = await axios(`/${entityName}/autocomplete?limit=100`);
return data.data;
} catch (error) {
console.log(error);
return [];
}
}
const hasUpdatePermission = hasPermission(user, 'UPDATE_DIAGNOSES');
return [
{
field: 'treatment_id',
headerName: 'Treatment_id',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('treatments'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'code',
headerName: 'Code',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'notes',
headerName: 'Notes',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'actions',
type: 'actions',
minWidth: 30,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
getActions: (params: GridRowParams) => {
return [
<div key={params?.row?.id}>
<ListActionsPopover
onDelete={onDelete}
itemId={params?.row?.id}
pathEdit={`/diagnoses/diagnoses-edit/?id=${params?.row?.id}`}
pathView={`/diagnoses/diagnoses-view/?id=${params?.row?.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>,
];
},
},
];
};

View File

@ -0,0 +1,147 @@
import React from 'react';
import ImageField from '../ImageField';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import dataFormatter from '../../helpers/dataFormatter';
import { Pagination } from '../Pagination';
import { saveFile } from '../../helpers/fileSaver';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
prescriptions: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const CardPrescriptions = ({
prescriptions,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const asideScrollbarsStyle = useAppSelector(
(state) => state.style.asideScrollbarsStyle,
);
const bgColor = useAppSelector((state) => state.style.cardsColor);
const darkMode = useAppSelector((state) => state.style.darkMode);
const corners = useAppSelector((state) => state.style.corners);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(
currentUser,
'UPDATE_PRESCRIPTIONS',
);
return (
<div className={'p-4'}>
{loading && <LoadingSpinner />}
<ul
role='list'
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
>
{!loading &&
prescriptions.map((item, index) => (
<li
key={item.id}
className={`overflow-hidden ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} border ${focusRing} border-gray-200 dark:border-dark-700 ${
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
}`}
>
<div
className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}
>
<Link
href={`/prescriptions/prescriptions-view/?id=${item.id}`}
className='text-lg font-bold leading-6 line-clamp-1'
>
{item.medication}
</Link>
<div className='ml-auto '>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/prescriptions/prescriptions-edit/?id=${item.id}`}
pathView={`/prescriptions/prescriptions-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</div>
<dl className='divide-y divide-stone-300 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Treatment_id
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.treatmentsOneListFormatter(
item.treatment_id,
)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Medication
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.medication}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Dosage
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.dosage}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Instructions
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{item.instructions}
</div>
</dd>
</div>
</dl>
</li>
))}
{!loading && prescriptions.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</ul>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</div>
);
};
export default CardPrescriptions;

View File

@ -0,0 +1,111 @@
import React from 'react';
import CardBox from '../CardBox';
import ImageField from '../ImageField';
import dataFormatter from '../../helpers/dataFormatter';
import { saveFile } from '../../helpers/fileSaver';
import ListActionsPopover from '../ListActionsPopover';
import { useAppSelector } from '../../stores/hooks';
import { Pagination } from '../Pagination';
import LoadingSpinner from '../LoadingSpinner';
import Link from 'next/link';
import { hasPermission } from '../../helpers/userPermissions';
type Props = {
prescriptions: any[];
loading: boolean;
onDelete: (id: string) => void;
currentPage: number;
numPages: number;
onPageChange: (page: number) => void;
};
const ListPrescriptions = ({
prescriptions,
loading,
onDelete,
currentPage,
numPages,
onPageChange,
}: Props) => {
const currentUser = useAppSelector((state) => state.auth.currentUser);
const hasUpdatePermission = hasPermission(
currentUser,
'UPDATE_PRESCRIPTIONS',
);
const corners = useAppSelector((state) => state.style.corners);
const bgColor = useAppSelector((state) => state.style.cardsColor);
return (
<>
<div className='relative overflow-x-auto p-4 space-y-4'>
{loading && <LoadingSpinner />}
{!loading &&
prescriptions.map((item) => (
<div key={item.id}>
<CardBox hasTable isList className={'rounded shadow-none'}>
<div
className={`flex ${bgColor} ${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 border border-stone-300 items-center overflow-hidden`}
>
<Link
href={`/prescriptions/prescriptions-view/?id=${item.id}`}
className={
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-stone-300 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
}
>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Treatment_id</p>
<p className={'line-clamp-2'}>
{dataFormatter.treatmentsOneListFormatter(
item.treatment_id,
)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Medication</p>
<p className={'line-clamp-2'}>{item.medication}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Dosage</p>
<p className={'line-clamp-2'}>{item.dosage}</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Instructions</p>
<p className={'line-clamp-2'}>{item.instructions}</p>
</div>
</Link>
<ListActionsPopover
onDelete={onDelete}
itemId={item.id}
pathEdit={`/prescriptions/prescriptions-edit/?id=${item.id}`}
pathView={`/prescriptions/prescriptions-view/?id=${item.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>
</CardBox>
</div>
))}
{!loading && prescriptions.length === 0 && (
<div className='col-span-full flex items-center justify-center h-40'>
<p className=''>No data to display</p>
</div>
)}
</div>
<div className={'flex items-center justify-center my-6'}>
<Pagination
currentPage={currentPage}
numPages={numPages}
setCurrentPage={onPageChange}
/>
</div>
</>
);
};
export default ListPrescriptions;

View File

@ -0,0 +1,487 @@
import React, { useEffect, useState, useMemo } from 'react';
import { createPortal } from 'react-dom';
import { ToastContainer, toast } from 'react-toastify';
import BaseButton from '../BaseButton';
import CardBoxModal from '../CardBoxModal';
import CardBox from '../CardBox';
import {
fetch,
update,
deleteItem,
setRefetch,
deleteItemsByIds,
} from '../../stores/prescriptions/prescriptionsSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { Field, Form, Formik } from 'formik';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { loadColumns } from './configurePrescriptionsCols';
import _ from 'lodash';
import dataFormatter from '../../helpers/dataFormatter';
import { dataGridStyles } from '../../styles';
const perPage = 10;
const TableSamplePrescriptions = ({
filterItems,
setFilterItems,
filters,
showGrid,
}) => {
const notify = (type, msg) => toast(msg, { type, position: 'bottom-center' });
const dispatch = useAppDispatch();
const router = useRouter();
const pagesList = [];
const [id, setId] = useState(null);
const [currentPage, setCurrentPage] = useState(0);
const [filterRequest, setFilterRequest] = React.useState('');
const [columns, setColumns] = useState<GridColDef[]>([]);
const [selectedRows, setSelectedRows] = useState([]);
const [sortModel, setSortModel] = useState([
{
field: '',
sort: 'desc',
},
]);
const {
prescriptions,
loading,
count,
notify: prescriptionsNotify,
refetch,
} = useAppSelector((state) => state.prescriptions);
const { currentUser } = useAppSelector((state) => state.auth);
const focusRing = useAppSelector((state) => state.style.focusRingColor);
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
const corners = useAppSelector((state) => state.style.corners);
const numPages =
Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
for (let i = 0; i < numPages; i++) {
pagesList.push(i);
}
const loadData = async (page = currentPage, request = filterRequest) => {
if (page !== currentPage) setCurrentPage(page);
if (request !== filterRequest) setFilterRequest(request);
const { sort, field } = sortModel[0];
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
dispatch(fetch({ limit: perPage, page, query }));
};
useEffect(() => {
if (prescriptionsNotify.showNotification) {
notify(
prescriptionsNotify.typeNotification,
prescriptionsNotify.textNotification,
);
}
}, [prescriptionsNotify.showNotification]);
useEffect(() => {
if (!currentUser) return;
loadData();
}, [sortModel, currentUser]);
useEffect(() => {
if (refetch) {
loadData(0);
dispatch(setRefetch(false));
}
}, [refetch, dispatch]);
const [isModalInfoActive, setIsModalInfoActive] = useState(false);
const [isModalTrashActive, setIsModalTrashActive] = useState(false);
const handleModalAction = () => {
setIsModalInfoActive(false);
setIsModalTrashActive(false);
};
const handleDeleteModalAction = (id: string) => {
setId(id);
setIsModalTrashActive(true);
};
const handleDeleteAction = async () => {
if (id) {
await dispatch(deleteItem(id));
await loadData(0);
setIsModalTrashActive(false);
}
};
const generateFilterRequests = useMemo(() => {
let request = '&';
filterItems.forEach((item) => {
const isRangeFilter = filters.find(
(filter) =>
filter.title === item.fields.selectedField &&
(filter.number || filter.date),
);
if (isRangeFilter) {
const from = item.fields.filterValueFrom;
const to = item.fields.filterValueTo;
if (from) {
request += `${item.fields.selectedField}Range=${from}&`;
}
if (to) {
request += `${item.fields.selectedField}Range=${to}&`;
}
} else {
const value = item.fields.filterValue;
if (value) {
request += `${item.fields.selectedField}=${value}&`;
}
}
});
return request;
}, [filterItems, filters]);
const deleteFilter = (value) => {
const newItems = filterItems.filter((item) => item.id !== value);
if (newItems.length) {
setFilterItems(newItems);
} else {
loadData(0, '');
setFilterItems(newItems);
}
};
const handleSubmit = () => {
loadData(0, generateFilterRequests);
};
const handleChange = (id) => (e) => {
const value = e.target.value;
const name = e.target.name;
setFilterItems(
filterItems.map((item) => {
if (item.id !== id) return item;
if (name === 'selectedField') return { id, fields: { [name]: value } };
return { id, fields: { ...item.fields, [name]: value } };
}),
);
};
const handleReset = () => {
setFilterItems([]);
loadData(0, '');
};
const onPageChange = (page: number) => {
loadData(page);
setCurrentPage(page);
};
useEffect(() => {
if (!currentUser) return;
loadColumns(handleDeleteModalAction, `prescriptions`, currentUser).then(
(newCols) => setColumns(newCols),
);
}, [currentUser]);
const handleTableSubmit = async (id: string, data) => {
if (!_.isEmpty(data)) {
await dispatch(update({ id, data }))
.unwrap()
.then((res) => res)
.catch((err) => {
throw new Error(err);
});
}
};
const onDeleteRows = async (selectedRows) => {
await dispatch(deleteItemsByIds(selectedRows));
await loadData(0);
};
const controlClasses =
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
` ${bgColor} ${focusRing} ${corners} ` +
'dark:bg-slate-800 border';
const dataGrid = (
<div className='relative overflow-x-auto'>
<DataGrid
autoHeight
rowHeight={64}
sx={dataGridStyles}
className={'datagrid--table'}
getRowClassName={() => `datagrid--row`}
rows={prescriptions ?? []}
columns={columns}
initialState={{
pagination: {
paginationModel: {
pageSize: 10,
},
},
}}
disableRowSelectionOnClick
onProcessRowUpdateError={(params) => {
console.log('Error', params);
}}
processRowUpdate={async (newRow, oldRow) => {
const data = dataFormatter.dataGridEditFormatter(newRow);
try {
await handleTableSubmit(newRow.id, data);
return newRow;
} catch {
return oldRow;
}
}}
sortingMode={'server'}
checkboxSelection
onRowSelectionModelChange={(ids) => {
setSelectedRows(ids);
}}
onSortModelChange={(params) => {
params.length
? setSortModel(params)
: setSortModel([{ field: '', sort: 'desc' }]);
}}
rowCount={count}
pageSizeOptions={[10]}
paginationMode={'server'}
loading={loading}
onPaginationModelChange={(params) => {
onPageChange(params.page);
}}
/>
</div>
);
return (
<>
{filterItems && Array.isArray(filterItems) && filterItems.length ? (
<CardBox>
<Formik
initialValues={{
checkboxes: ['lorem'],
switches: ['lorem'],
radio: 'lorem',
}}
onSubmit={() => null}
>
<Form>
<>
{filterItems &&
filterItems.map((filterItem) => {
return (
<div key={filterItem.id} className='flex mb-4'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Filter
</div>
<Field
className={controlClasses}
name='selectedField'
id='selectedField'
component='select'
value={filterItem?.fields?.selectedField || ''}
onChange={handleChange(filterItem.id)}
>
{filters.map((selectOption) => (
<option
key={selectOption.title}
value={`${selectOption.title}`}
>
{selectOption.label}
</option>
))}
</Field>
</div>
{filters.find(
(filter) =>
filter.title === filterItem?.fields?.selectedField,
)?.type === 'enum' ? (
<div className='flex flex-col w-full mr-3'>
<div className='text-gray-500 font-bold'>Value</div>
<Field
className={controlClasses}
name='filterValue'
id='filterValue'
component='select'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
>
<option value=''>Select Value</option>
{filters
.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)
?.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</Field>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.number ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : filters.find(
(filter) =>
filter.title ===
filterItem?.fields?.selectedField,
)?.date ? (
<div className='flex flex-row w-full mr-3'>
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
From
</div>
<Field
className={controlClasses}
name='filterValueFrom'
placeholder='From'
id='filterValueFrom'
type='datetime-local'
value={
filterItem?.fields?.filterValueFrom || ''
}
onChange={handleChange(filterItem.id)}
/>
</div>
<div className='flex flex-col w-full'>
<div className=' text-gray-500 font-bold'>
To
</div>
<Field
className={controlClasses}
name='filterValueTo'
placeholder='to'
id='filterValueTo'
type='datetime-local'
value={filterItem?.fields?.filterValueTo || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
</div>
) : (
<div className='flex flex-col w-full mr-3'>
<div className=' text-gray-500 font-bold'>
Contains
</div>
<Field
className={controlClasses}
name='filterValue'
placeholder='Contained'
id='filterValue'
value={filterItem?.fields?.filterValue || ''}
onChange={handleChange(filterItem.id)}
/>
</div>
)}
<div className='flex flex-col'>
<div className=' text-gray-500 font-bold'>
Action
</div>
<BaseButton
className='my-2'
type='reset'
color='danger'
label='Delete'
onClick={() => {
deleteFilter(filterItem.id);
}}
/>
</div>
</div>
);
})}
<div className='flex'>
<BaseButton
className='my-2 mr-3'
type='submit'
color='info'
label='Apply'
onClick={handleSubmit}
/>
<BaseButton
className='my-2'
type='reset'
color='info'
outline
label='Cancel'
onClick={handleReset}
/>
</div>
</>
</Form>
</Formik>
</CardBox>
) : null}
<CardBoxModal
title='Please confirm'
buttonColor='info'
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
isActive={isModalTrashActive}
onConfirm={handleDeleteAction}
onCancel={handleModalAction}
>
<p>Are you sure you want to delete this item?</p>
</CardBoxModal>
{dataGrid}
{selectedRows.length > 0 &&
createPortal(
<BaseButton
className='me-4'
color='danger'
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
onClick={() => onDeleteRows(selectedRows)}
/>,
document.getElementById('delete-rows-button'),
)}
<ToastContainer />
</>
);
};
export default TableSamplePrescriptions;

View File

@ -0,0 +1,118 @@
import React from 'react';
import BaseIcon from '../BaseIcon';
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
import axios from 'axios';
import {
GridActionsCellItem,
GridRowParams,
GridValueGetterParams,
} from '@mui/x-data-grid';
import ImageField from '../ImageField';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import DataGridMultiSelect from '../DataGridMultiSelect';
import ListActionsPopover from '../ListActionsPopover';
import { hasPermission } from '../../helpers/userPermissions';
type Params = (id: string) => void;
export const loadColumns = async (
onDelete: Params,
entityName: string,
user,
) => {
async function callOptionsApi(entityName: string) {
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
try {
const data = await axios(`/${entityName}/autocomplete?limit=100`);
return data.data;
} catch (error) {
console.log(error);
return [];
}
}
const hasUpdatePermission = hasPermission(user, 'UPDATE_PRESCRIPTIONS');
return [
{
field: 'treatment_id',
headerName: 'Treatment_id',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('treatments'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'medication',
headerName: 'Medication',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'dosage',
headerName: 'Dosage',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'instructions',
headerName: 'Instructions',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
},
{
field: 'actions',
type: 'actions',
minWidth: 30,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
getActions: (params: GridRowParams) => {
return [
<div key={params?.row?.id}>
<ListActionsPopover
onDelete={onDelete}
itemId={params?.row?.id}
pathEdit={`/prescriptions/prescriptions-edit/?id=${params?.row?.id}`}
pathView={`/prescriptions/prescriptions-view/?id=${params?.row?.id}`}
hasUpdatePermission={hasUpdatePermission}
/>
</div>,
];
},
},
];
};

View File

@ -106,6 +106,28 @@ const CardTreatments = ({
<div className='font-medium line-clamp-4'>{item.cost}</div> <div className='font-medium line-clamp-4'>{item.cost}</div>
</dd> </dd>
</div> </div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Patient_id
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.patientsOneListFormatter(item.patient_id)}
</div>
</dd>
</div>
<div className='flex justify-between gap-x-4 py-3'>
<dt className=' text-gray-500 dark:text-dark-600'>
Doctor_id
</dt>
<dd className='flex items-start gap-x-2'>
<div className='font-medium line-clamp-4'>
{dataFormatter.usersOneListFormatter(item.doctor_id)}
</div>
</dd>
</div>
</dl> </dl>
</li> </li>
))} ))}

View File

@ -71,6 +71,22 @@ const ListTreatments = ({
<p className={'text-xs text-gray-500 '}>Cost</p> <p className={'text-xs text-gray-500 '}>Cost</p>
<p className={'line-clamp-2'}>{item.cost}</p> <p className={'line-clamp-2'}>{item.cost}</p>
</div> </div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Patient_id</p>
<p className={'line-clamp-2'}>
{dataFormatter.patientsOneListFormatter(
item.patient_id,
)}
</p>
</div>
<div className={'flex-1 px-3'}>
<p className={'text-xs text-gray-500 '}>Doctor_id</p>
<p className={'line-clamp-2'}>
{dataFormatter.usersOneListFormatter(item.doctor_id)}
</p>
</div>
</Link> </Link>
<ListActionsPopover <ListActionsPopover
onDelete={onDelete} onDelete={onDelete}

View File

@ -84,6 +84,46 @@ export const loadColumns = async (
type: 'number', type: 'number',
}, },
{
field: 'patient_id',
headerName: 'Patient_id',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('patients'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{
field: 'doctor_id',
headerName: 'Doctor_id',
flex: 1,
minWidth: 120,
filterable: false,
headerClassName: 'datagrid--header',
cellClassName: 'datagrid--cell',
editable: hasUpdatePermission,
sortable: false,
type: 'singleSelect',
getOptionValue: (value: any) => value?.id,
getOptionLabel: (value: any) => value?.label,
valueOptions: await callOptionsApi('users'),
valueGetter: (params: GridValueGetterParams) =>
params?.value?.id ?? params?.value,
},
{ {
field: 'actions', field: 'actions',
type: 'actions', type: 'actions',

View File

@ -19,7 +19,7 @@ export default function WebSiteFooter({ projectName }: WebSiteFooterProps) {
const style = FooterStyle.WITH_PROJECT_NAME; const style = FooterStyle.WITH_PROJECT_NAME;
const design = FooterDesigns.DESIGN_DIVERSITY; const design = FooterDesigns.DEFAULT_DESIGN;
return ( return (
<div <div

View File

@ -17,9 +17,9 @@ export default function WebSiteHeader({ projectName }: WebSiteHeaderProps) {
const websiteHeder = useAppSelector((state) => state.style.websiteHeder); const websiteHeder = useAppSelector((state) => state.style.websiteHeder);
const borders = useAppSelector((state) => state.style.borders); const borders = useAppSelector((state) => state.style.borders);
const style = HeaderStyle.PAGES_RIGHT; const style = HeaderStyle.PAGES_LEFT;
const design = HeaderDesigns.DEFAULT_DESIGN; const design = HeaderDesigns.DESIGN_DIVERSITY;
return ( return (
<header id='websiteHeader' className='overflow-hidden'> <header id='websiteHeader' className='overflow-hidden'>
<div <div

View File

@ -96,6 +96,25 @@ export default {
return { label: val.first_name, id: val.id }; return { label: val.first_name, id: val.id };
}, },
treatmentsManyListFormatter(val) {
if (!val || !val.length) return [];
return val.map((item) => item.description);
},
treatmentsOneListFormatter(val) {
if (!val) return '';
return val.description;
},
treatmentsManyListFormatterEdit(val) {
if (!val || !val.length) return [];
return val.map((item) => {
return { id: item.id, label: item.description };
});
},
treatmentsOneListFormatterEdit(val) {
if (!val) return '';
return { label: val.description, id: val.id };
},
rolesManyListFormatter(val) { rolesManyListFormatter(val) {
if (!val || !val.length) return []; if (!val || !val.length) return [];
return val.map((item) => item.name); return val.map((item) => item.name);

View File

@ -84,6 +84,22 @@ const menuAside: MenuAsideItem[] = [
icon: icon.mdiTable ?? icon.mdiTable, icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_CLINICS', permissions: 'READ_CLINICS',
}, },
{
href: '/diagnoses/diagnoses-list',
label: 'Diagnoses',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_DIAGNOSES',
},
{
href: '/prescriptions/prescriptions-list',
label: 'Prescriptions',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_PRESCRIPTIONS',
},
{ {
href: '/profile', href: '/profile',
label: 'Profile', label: 'Profile',

View File

@ -347,6 +347,92 @@ const ClinicsView = () => {
</CardBox> </CardBox>
</> </>
<>
<p className={'block font-bold mb-2'}>Diagnoses clinics</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Code</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{clinics.diagnoses_clinics &&
Array.isArray(clinics.diagnoses_clinics) &&
clinics.diagnoses_clinics.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/diagnoses/diagnoses-view/?id=${item.id}`,
)
}
>
<td data-label='code'>{item.code}</td>
<td data-label='notes'>{item.notes}</td>
</tr>
))}
</tbody>
</table>
</div>
{!clinics?.diagnoses_clinics?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<>
<p className={'block font-bold mb-2'}>Prescriptions clinics</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Medication</th>
<th>Dosage</th>
<th>Instructions</th>
</tr>
</thead>
<tbody>
{clinics.prescriptions_clinics &&
Array.isArray(clinics.prescriptions_clinics) &&
clinics.prescriptions_clinics.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/prescriptions/prescriptions-view/?id=${item.id}`,
)
}
>
<td data-label='medication'>{item.medication}</td>
<td data-label='dosage'>{item.dosage}</td>
<td data-label='instructions'>{item.instructions}</td>
</tr>
))}
</tbody>
</table>
</div>
{!clinics?.prescriptions_clinics?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -36,6 +36,8 @@ const Dashboard = () => {
const [roles, setRoles] = React.useState(loadingMessage); const [roles, setRoles] = React.useState(loadingMessage);
const [permissions, setPermissions] = React.useState(loadingMessage); const [permissions, setPermissions] = React.useState(loadingMessage);
const [clinics, setClinics] = React.useState(loadingMessage); const [clinics, setClinics] = React.useState(loadingMessage);
const [diagnoses, setDiagnoses] = React.useState(loadingMessage);
const [prescriptions, setPrescriptions] = React.useState(loadingMessage);
const [widgetsRole, setWidgetsRole] = React.useState({ const [widgetsRole, setWidgetsRole] = React.useState({
role: { value: '', label: '' }, role: { value: '', label: '' },
@ -57,6 +59,8 @@ const Dashboard = () => {
'roles', 'roles',
'permissions', 'permissions',
'clinics', 'clinics',
'diagnoses',
'prescriptions',
]; ];
const fns = [ const fns = [
setUsers, setUsers,
@ -67,6 +71,8 @@ const Dashboard = () => {
setRoles, setRoles,
setPermissions, setPermissions,
setClinics, setClinics,
setDiagnoses,
setPrescriptions,
]; ];
const requests = entities.map((entity, index) => { const requests = entities.map((entity, index) => {
@ -454,6 +460,70 @@ const Dashboard = () => {
</div> </div>
</Link> </Link>
)} )}
{hasPermission(currentUser, 'READ_DIAGNOSES') && (
<Link href={'/diagnoses/diagnoses-list'}>
<div
className={`${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
>
<div className='flex justify-between align-center'>
<div>
<div className='text-lg leading-tight text-gray-500 dark:text-gray-400'>
Diagnoses
</div>
<div className='text-3xl leading-tight font-semibold'>
{diagnoses}
</div>
</div>
<div>
<BaseIcon
className={`${iconsColor}`}
w='w-16'
h='h-16'
size={48}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
path={icon.mdiTable || icon.mdiTable}
/>
</div>
</div>
</div>
</Link>
)}
{hasPermission(currentUser, 'READ_PRESCRIPTIONS') && (
<Link href={'/prescriptions/prescriptions-list'}>
<div
className={`${
corners !== 'rounded-full' ? corners : 'rounded-3xl'
} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
>
<div className='flex justify-between align-center'>
<div>
<div className='text-lg leading-tight text-gray-500 dark:text-gray-400'>
Prescriptions
</div>
<div className='text-3xl leading-tight font-semibold'>
{prescriptions}
</div>
</div>
<div>
<BaseIcon
className={`${iconsColor}`}
w='w-16'
h='h-16'
size={48}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
path={icon.mdiTable || icon.mdiTable}
/>
</div>
</div>
</div>
</Link>
)}
</div> </div>
</SectionMain> </SectionMain>
</> </>

View File

@ -0,0 +1,162 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/diagnoses/diagnosesSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import { hasPermission } from '../../helpers/userPermissions';
const EditDiagnoses = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
clinics: null,
treatment_id: null,
code: '',
notes: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { diagnoses } = useAppSelector((state) => state.diagnoses);
const { currentUser } = useAppSelector((state) => state.auth);
const { diagnosesId } = router.query;
useEffect(() => {
dispatch(fetch({ id: diagnosesId }));
}, [diagnosesId]);
useEffect(() => {
if (typeof diagnoses === 'object') {
setInitialValues(diagnoses);
}
}, [diagnoses]);
useEffect(() => {
if (typeof diagnoses === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = diagnoses[el]),
);
setInitialValues(newInitialVal);
}
}, [diagnoses]);
const handleSubmit = async (data) => {
await dispatch(update({ id: diagnosesId, data }));
await router.push('/diagnoses/diagnoses-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit diagnoses')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit diagnoses'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={initialValues.clinics}
itemRef={'clinics'}
showField={'name'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={initialValues.treatment_id}
itemRef={'treatments'}
showField={'description'}
></Field>
</FormField>
<FormField label='Code'>
<Field name='code' placeholder='Code' />
</FormField>
<FormField label='Notes'>
<Field name='notes' placeholder='Notes' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/diagnoses/diagnoses-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditDiagnoses.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default EditDiagnoses;

View File

@ -0,0 +1,160 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/diagnoses/diagnosesSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import { hasPermission } from '../../helpers/userPermissions';
const EditDiagnosesPage = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
clinics: null,
treatment_id: null,
code: '',
notes: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { diagnoses } = useAppSelector((state) => state.diagnoses);
const { currentUser } = useAppSelector((state) => state.auth);
const { id } = router.query;
useEffect(() => {
dispatch(fetch({ id: id }));
}, [id]);
useEffect(() => {
if (typeof diagnoses === 'object') {
setInitialValues(diagnoses);
}
}, [diagnoses]);
useEffect(() => {
if (typeof diagnoses === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = diagnoses[el]),
);
setInitialValues(newInitialVal);
}
}, [diagnoses]);
const handleSubmit = async (data) => {
await dispatch(update({ id: id, data }));
await router.push('/diagnoses/diagnoses-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit diagnoses')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit diagnoses'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={initialValues.clinics}
itemRef={'clinics'}
showField={'name'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={initialValues.treatment_id}
itemRef={'treatments'}
showField={'description'}
></Field>
</FormField>
<FormField label='Code'>
<Field name='code' placeholder='Code' />
</FormField>
<FormField label='Notes'>
<Field name='notes' placeholder='Notes' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/diagnoses/diagnoses-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditDiagnosesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default EditDiagnosesPage;

View File

@ -0,0 +1,167 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TableDiagnoses from '../../components/Diagnoses/TableDiagnoses';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/diagnoses/diagnosesSlice';
import { hasPermission } from '../../helpers/userPermissions';
const DiagnosesTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Code', title: 'code' },
{ label: 'Notes', title: 'notes' },
{ label: 'Treatment_id', title: 'treatment_id' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_DIAGNOSES');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getDiagnosesCSV = async () => {
const response = await axios({
url: '/diagnoses?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'diagnosesCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Diagnoses')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Diagnoses'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/diagnoses/diagnoses-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getDiagnosesCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableDiagnoses
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={false}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
DiagnosesTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default DiagnosesTablesPage;

View File

@ -0,0 +1,128 @@
import {
mdiAccount,
mdiChartTimelineVariant,
mdiMail,
mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SwitchField } from '../../components/SwitchField';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { RichTextField } from '../../components/RichTextField';
import { create } from '../../stores/diagnoses/diagnosesSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import moment from 'moment';
const initialValues = {
clinics: '',
treatment_id: '',
code: '',
notes: '',
};
const DiagnosesNew = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const handleSubmit = async (data) => {
await dispatch(create(data));
await router.push('/diagnoses/diagnoses-list');
};
return (
<>
<Head>
<title>{getPageTitle('New Item')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='New Item'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={[]}
itemRef={'clinics'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={[]}
itemRef={'treatments'}
></Field>
</FormField>
<FormField label='Code'>
<Field name='code' placeholder='Code' />
</FormField>
<FormField label='Notes'>
<Field name='notes' placeholder='Notes' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() => router.push('/diagnoses/diagnoses-list')}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
DiagnosesNew.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'CREATE_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default DiagnosesNew;

View File

@ -0,0 +1,166 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TableDiagnoses from '../../components/Diagnoses/TableDiagnoses';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import { setRefetch, uploadCsv } from '../../stores/diagnoses/diagnosesSlice';
import { hasPermission } from '../../helpers/userPermissions';
const DiagnosesTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Code', title: 'code' },
{ label: 'Notes', title: 'notes' },
{ label: 'Treatment_id', title: 'treatment_id' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_DIAGNOSES');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getDiagnosesCSV = async () => {
const response = await axios({
url: '/diagnoses?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'diagnosesCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Diagnoses')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Diagnoses'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/diagnoses/diagnoses-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getDiagnosesCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TableDiagnoses
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={true}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
DiagnosesTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default DiagnosesTablesPage;

View File

@ -0,0 +1,104 @@
import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/diagnoses/diagnosesSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';
import { hasPermission } from '../../helpers/userPermissions';
const DiagnosesView = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { diagnoses } = useAppSelector((state) => state.diagnoses);
const { currentUser } = useAppSelector((state) => state.auth);
const { id } = router.query;
function removeLastCharacter(str) {
console.log(str, `str`);
return str.slice(0, -1);
}
useEffect(() => {
dispatch(fetch({ id }));
}, [dispatch, id]);
return (
<>
<Head>
<title>{getPageTitle('View diagnoses')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={removeLastCharacter('View diagnoses')}
main
>
<BaseButton
color='info'
label='Edit'
href={`/diagnoses/diagnoses-edit/?id=${id}`}
/>
</SectionTitleLineWithButton>
<CardBox>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>clinics</p>
<p>{diagnoses?.clinics?.name ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Treatment_id</p>
<p>{diagnoses?.treatment_id?.description ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Code</p>
<p>{diagnoses?.code}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Notes</p>
<p>{diagnoses?.notes}</p>
</div>
<BaseDivider />
<BaseButton
color='info'
label='Back'
onClick={() => router.push('/diagnoses/diagnoses-list')}
/>
</CardBox>
</SectionMain>
</>
);
};
DiagnosesView.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_DIAGNOSES'}>
{page}
</LayoutAuthenticated>
);
};
export default DiagnosesView;

View File

@ -139,6 +139,43 @@ const PatientsView = () => {
</CardBox> </CardBox>
</> </>
<>
<p className={'block font-bold mb-2'}>Treatments Patient_id</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Cost</th>
</tr>
</thead>
<tbody>
{patients.treatments_patient_id &&
Array.isArray(patients.treatments_patient_id) &&
patients.treatments_patient_id.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/treatments/treatments-view/?id=${item.id}`,
)
}
>
<td data-label='cost'>{item.cost}</td>
</tr>
))}
</tbody>
</table>
</div>
{!patients?.treatments_patient_id?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -0,0 +1,170 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/prescriptions/prescriptionsSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import { hasPermission } from '../../helpers/userPermissions';
const EditPrescriptions = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
clinics: null,
treatment_id: null,
medication: '',
dosage: '',
instructions: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { prescriptions } = useAppSelector((state) => state.prescriptions);
const { currentUser } = useAppSelector((state) => state.auth);
const { prescriptionsId } = router.query;
useEffect(() => {
dispatch(fetch({ id: prescriptionsId }));
}, [prescriptionsId]);
useEffect(() => {
if (typeof prescriptions === 'object') {
setInitialValues(prescriptions);
}
}, [prescriptions]);
useEffect(() => {
if (typeof prescriptions === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = prescriptions[el]),
);
setInitialValues(newInitialVal);
}
}, [prescriptions]);
const handleSubmit = async (data) => {
await dispatch(update({ id: prescriptionsId, data }));
await router.push('/prescriptions/prescriptions-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit prescriptions')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit prescriptions'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={initialValues.clinics}
itemRef={'clinics'}
showField={'name'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={initialValues.treatment_id}
itemRef={'treatments'}
showField={'description'}
></Field>
</FormField>
<FormField label='Medication'>
<Field name='medication' placeholder='Medication' />
</FormField>
<FormField label='Dosage'>
<Field name='dosage' placeholder='Dosage' />
</FormField>
<FormField label='Instructions'>
<Field name='instructions' placeholder='Instructions' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() =>
router.push('/prescriptions/prescriptions-list')
}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditPrescriptions.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default EditPrescriptions;

View File

@ -0,0 +1,168 @@
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { SwitchField } from '../../components/SwitchField';
import { RichTextField } from '../../components/RichTextField';
import { update, fetch } from '../../stores/prescriptions/prescriptionsSlice';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import { hasPermission } from '../../helpers/userPermissions';
const EditPrescriptionsPage = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const initVals = {
clinics: null,
treatment_id: null,
medication: '',
dosage: '',
instructions: '',
};
const [initialValues, setInitialValues] = useState(initVals);
const { prescriptions } = useAppSelector((state) => state.prescriptions);
const { currentUser } = useAppSelector((state) => state.auth);
const { id } = router.query;
useEffect(() => {
dispatch(fetch({ id: id }));
}, [id]);
useEffect(() => {
if (typeof prescriptions === 'object') {
setInitialValues(prescriptions);
}
}, [prescriptions]);
useEffect(() => {
if (typeof prescriptions === 'object') {
const newInitialVal = { ...initVals };
Object.keys(initVals).forEach(
(el) => (newInitialVal[el] = prescriptions[el]),
);
setInitialValues(newInitialVal);
}
}, [prescriptions]);
const handleSubmit = async (data) => {
await dispatch(update({ id: id, data }));
await router.push('/prescriptions/prescriptions-list');
};
return (
<>
<Head>
<title>{getPageTitle('Edit prescriptions')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={'Edit prescriptions'}
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
enableReinitialize
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={initialValues.clinics}
itemRef={'clinics'}
showField={'name'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={initialValues.treatment_id}
itemRef={'treatments'}
showField={'description'}
></Field>
</FormField>
<FormField label='Medication'>
<Field name='medication' placeholder='Medication' />
</FormField>
<FormField label='Dosage'>
<Field name='dosage' placeholder='Dosage' />
</FormField>
<FormField label='Instructions'>
<Field name='instructions' placeholder='Instructions' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() =>
router.push('/prescriptions/prescriptions-list')
}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
EditPrescriptionsPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'UPDATE_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default EditPrescriptionsPage;

View File

@ -0,0 +1,171 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TablePrescriptions from '../../components/Prescriptions/TablePrescriptions';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import {
setRefetch,
uploadCsv,
} from '../../stores/prescriptions/prescriptionsSlice';
import { hasPermission } from '../../helpers/userPermissions';
const PrescriptionsTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Medication', title: 'medication' },
{ label: 'Dosage', title: 'dosage' },
{ label: 'Instructions', title: 'instructions' },
{ label: 'Treatment_id', title: 'treatment_id' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_PRESCRIPTIONS');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getPrescriptionsCSV = async () => {
const response = await axios({
url: '/prescriptions?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'prescriptionsCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Prescriptions')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Prescriptions'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/prescriptions/prescriptions-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getPrescriptionsCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TablePrescriptions
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={false}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
PrescriptionsTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default PrescriptionsTablesPage;

View File

@ -0,0 +1,136 @@
import {
mdiAccount,
mdiChartTimelineVariant,
mdiMail,
mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import { Field, Form, Formik } from 'formik';
import FormField from '../../components/FormField';
import BaseDivider from '../../components/BaseDivider';
import BaseButtons from '../../components/BaseButtons';
import BaseButton from '../../components/BaseButton';
import FormCheckRadio from '../../components/FormCheckRadio';
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup';
import FormFilePicker from '../../components/FormFilePicker';
import FormImagePicker from '../../components/FormImagePicker';
import { SwitchField } from '../../components/SwitchField';
import { SelectField } from '../../components/SelectField';
import { SelectFieldMany } from '../../components/SelectFieldMany';
import { RichTextField } from '../../components/RichTextField';
import { create } from '../../stores/prescriptions/prescriptionsSlice';
import { useAppDispatch } from '../../stores/hooks';
import { useRouter } from 'next/router';
import moment from 'moment';
const initialValues = {
clinics: '',
treatment_id: '',
medication: '',
dosage: '',
instructions: '',
};
const PrescriptionsNew = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const handleSubmit = async (data) => {
await dispatch(create(data));
await router.push('/prescriptions/prescriptions-list');
};
return (
<>
<Head>
<title>{getPageTitle('New Item')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='New Item'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox>
<Formik
initialValues={initialValues}
onSubmit={(values) => handleSubmit(values)}
>
<Form>
<FormField label='clinics' labelFor='clinics'>
<Field
name='clinics'
id='clinics'
component={SelectField}
options={[]}
itemRef={'clinics'}
></Field>
</FormField>
<FormField label='Treatment_id' labelFor='treatment_id'>
<Field
name='treatment_id'
id='treatment_id'
component={SelectField}
options={[]}
itemRef={'treatments'}
></Field>
</FormField>
<FormField label='Medication'>
<Field name='medication' placeholder='Medication' />
</FormField>
<FormField label='Dosage'>
<Field name='dosage' placeholder='Dosage' />
</FormField>
<FormField label='Instructions'>
<Field name='instructions' placeholder='Instructions' />
</FormField>
<BaseDivider />
<BaseButtons>
<BaseButton type='submit' color='info' label='Submit' />
<BaseButton type='reset' color='info' outline label='Reset' />
<BaseButton
type='reset'
color='danger'
outline
label='Cancel'
onClick={() =>
router.push('/prescriptions/prescriptions-list')
}
/>
</BaseButtons>
</Form>
</Formik>
</CardBox>
</SectionMain>
</>
);
};
PrescriptionsNew.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'CREATE_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default PrescriptionsNew;

View File

@ -0,0 +1,170 @@
import { mdiChartTimelineVariant } from '@mdi/js';
import Head from 'next/head';
import { uniqueId } from 'lodash';
import React, { ReactElement, useState } from 'react';
import CardBox from '../../components/CardBox';
import LayoutAuthenticated from '../../layouts/Authenticated';
import SectionMain from '../../components/SectionMain';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import { getPageTitle } from '../../config';
import TablePrescriptions from '../../components/Prescriptions/TablePrescriptions';
import BaseButton from '../../components/BaseButton';
import axios from 'axios';
import Link from 'next/link';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import CardBoxModal from '../../components/CardBoxModal';
import DragDropFilePicker from '../../components/DragDropFilePicker';
import {
setRefetch,
uploadCsv,
} from '../../stores/prescriptions/prescriptionsSlice';
import { hasPermission } from '../../helpers/userPermissions';
const PrescriptionsTablesPage = () => {
const [filterItems, setFilterItems] = useState([]);
const [csvFile, setCsvFile] = useState<File | null>(null);
const [isModalActive, setIsModalActive] = useState(false);
const [showTableView, setShowTableView] = useState(false);
const { currentUser } = useAppSelector((state) => state.auth);
const dispatch = useAppDispatch();
const [filters] = useState([
{ label: 'Medication', title: 'medication' },
{ label: 'Dosage', title: 'dosage' },
{ label: 'Instructions', title: 'instructions' },
{ label: 'Treatment_id', title: 'treatment_id' },
]);
const hasCreatePermission =
currentUser && hasPermission(currentUser, 'CREATE_PRESCRIPTIONS');
const addFilter = () => {
const newItem = {
id: uniqueId(),
fields: {
filterValue: '',
filterValueFrom: '',
filterValueTo: '',
selectedField: '',
},
};
newItem.fields.selectedField = filters[0].title;
setFilterItems([...filterItems, newItem]);
};
const getPrescriptionsCSV = async () => {
const response = await axios({
url: '/prescriptions?filetype=csv',
method: 'GET',
responseType: 'blob',
});
const type = response.headers['content-type'];
const blob = new Blob([response.data], { type: type });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'prescriptionsCSV.csv';
link.click();
};
const onModalConfirm = async () => {
if (!csvFile) return;
await dispatch(uploadCsv(csvFile));
dispatch(setRefetch(true));
setCsvFile(null);
setIsModalActive(false);
};
const onModalCancel = () => {
setCsvFile(null);
setIsModalActive(false);
};
return (
<>
<Head>
<title>{getPageTitle('Prescriptions')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title='Prescriptions'
main
>
{''}
</SectionTitleLineWithButton>
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
{hasCreatePermission && (
<BaseButton
className={'mr-3'}
href={'/prescriptions/prescriptions-new'}
color='info'
label='New Item'
/>
)}
<BaseButton
className={'mr-3'}
color='info'
label='Filter'
onClick={addFilter}
/>
<BaseButton
className={'mr-3'}
color='info'
label='Download CSV'
onClick={getPrescriptionsCSV}
/>
{hasCreatePermission && (
<BaseButton
color='info'
label='Upload CSV'
onClick={() => setIsModalActive(true)}
/>
)}
<div className='md:inline-flex items-center ms-auto'>
<div id='delete-rows-button'></div>
</div>
</CardBox>
<CardBox className='mb-6' hasTable>
<TablePrescriptions
filterItems={filterItems}
setFilterItems={setFilterItems}
filters={filters}
showGrid={true}
/>
</CardBox>
</SectionMain>
<CardBoxModal
title='Upload CSV'
buttonColor='info'
buttonLabel={'Confirm'}
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
isActive={isModalActive}
onConfirm={onModalConfirm}
onCancel={onModalCancel}
>
<DragDropFilePicker
file={csvFile}
setFile={setCsvFile}
formats={'.csv'}
/>
</CardBoxModal>
</>
);
};
PrescriptionsTablesPage.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default PrescriptionsTablesPage;

View File

@ -0,0 +1,109 @@
import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import dayjs from 'dayjs';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { useRouter } from 'next/router';
import { fetch } from '../../stores/prescriptions/prescriptionsSlice';
import { saveFile } from '../../helpers/fileSaver';
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from '../../components/ImageField';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseDivider from '../../components/BaseDivider';
import { mdiChartTimelineVariant } from '@mdi/js';
import { SwitchField } from '../../components/SwitchField';
import FormField from '../../components/FormField';
import { hasPermission } from '../../helpers/userPermissions';
const PrescriptionsView = () => {
const router = useRouter();
const dispatch = useAppDispatch();
const { prescriptions } = useAppSelector((state) => state.prescriptions);
const { currentUser } = useAppSelector((state) => state.auth);
const { id } = router.query;
function removeLastCharacter(str) {
console.log(str, `str`);
return str.slice(0, -1);
}
useEffect(() => {
dispatch(fetch({ id }));
}, [dispatch, id]);
return (
<>
<Head>
<title>{getPageTitle('View prescriptions')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton
icon={mdiChartTimelineVariant}
title={removeLastCharacter('View prescriptions')}
main
>
<BaseButton
color='info'
label='Edit'
href={`/prescriptions/prescriptions-edit/?id=${id}`}
/>
</SectionTitleLineWithButton>
<CardBox>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>clinics</p>
<p>{prescriptions?.clinics?.name ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Treatment_id</p>
<p>{prescriptions?.treatment_id?.description ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Medication</p>
<p>{prescriptions?.medication}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Dosage</p>
<p>{prescriptions?.dosage}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Instructions</p>
<p>{prescriptions?.instructions}</p>
</div>
<BaseDivider />
<BaseButton
color='info'
label='Back'
onClick={() => router.push('/prescriptions/prescriptions-list')}
/>
</CardBox>
</SectionMain>
</>
);
};
PrescriptionsView.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutAuthenticated permission={'READ_PRESCRIPTIONS'}>
{page}
</LayoutAuthenticated>
);
};
export default PrescriptionsView;

View File

@ -45,6 +45,10 @@ const EditTreatments = () => {
cost: '', cost: '',
clinics: null, clinics: null,
patient_id: null,
doctor_id: null,
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -135,6 +139,28 @@ const EditTreatments = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Patient_id' labelFor='patient_id'>
<Field
name='patient_id'
id='patient_id'
component={SelectField}
options={initialValues.patient_id}
itemRef={'patients'}
showField={'first_name'}
></Field>
</FormField>
<FormField label='Doctor_id' labelFor='doctor_id'>
<Field
name='doctor_id'
id='doctor_id'
component={SelectField}
options={initialValues.doctor_id}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -45,6 +45,10 @@ const EditTreatmentsPage = () => {
cost: '', cost: '',
clinics: null, clinics: null,
patient_id: null,
doctor_id: null,
}; };
const [initialValues, setInitialValues] = useState(initVals); const [initialValues, setInitialValues] = useState(initVals);
@ -133,6 +137,28 @@ const EditTreatmentsPage = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Patient_id' labelFor='patient_id'>
<Field
name='patient_id'
id='patient_id'
component={SelectField}
options={initialValues.patient_id}
itemRef={'patients'}
showField={'first_name'}
></Field>
</FormField>
<FormField label='Doctor_id' labelFor='doctor_id'>
<Field
name='doctor_id'
id='doctor_id'
component={SelectField}
options={initialValues.doctor_id}
itemRef={'users'}
showField={'firstName'}
></Field>
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -34,6 +34,10 @@ const TreatmentsTablesPage = () => {
{ label: 'Cost', title: 'cost', number: 'true' }, { label: 'Cost', title: 'cost', number: 'true' },
{ label: 'Appointment', title: 'appointment' }, { label: 'Appointment', title: 'appointment' },
{ label: 'Patient_id', title: 'patient_id' },
{ label: 'Doctor_id', title: 'doctor_id' },
]); ]);
const hasCreatePermission = const hasCreatePermission =

View File

@ -40,6 +40,10 @@ const initialValues = {
cost: '', cost: '',
clinics: '', clinics: '',
patient_id: '',
doctor_id: '',
}; };
const TreatmentsNew = () => { const TreatmentsNew = () => {
@ -101,6 +105,26 @@ const TreatmentsNew = () => {
></Field> ></Field>
</FormField> </FormField>
<FormField label='Patient_id' labelFor='patient_id'>
<Field
name='patient_id'
id='patient_id'
component={SelectField}
options={[]}
itemRef={'patients'}
></Field>
</FormField>
<FormField label='Doctor_id' labelFor='doctor_id'>
<Field
name='doctor_id'
id='doctor_id'
component={SelectField}
options={[]}
itemRef={'users'}
></Field>
</FormField>
<BaseDivider /> <BaseDivider />
<BaseButtons> <BaseButtons>
<BaseButton type='submit' color='info' label='Submit' /> <BaseButton type='submit' color='info' label='Submit' />

View File

@ -34,6 +34,10 @@ const TreatmentsTablesPage = () => {
{ label: 'Cost', title: 'cost', number: 'true' }, { label: 'Cost', title: 'cost', number: 'true' },
{ label: 'Appointment', title: 'appointment' }, { label: 'Appointment', title: 'appointment' },
{ label: 'Patient_id', title: 'patient_id' },
{ label: 'Doctor_id', title: 'doctor_id' },
]); ]);
const hasCreatePermission = const hasCreatePermission =

View File

@ -84,6 +84,104 @@ const TreatmentsView = () => {
<p>{treatments?.clinics?.name ?? 'No data'}</p> <p>{treatments?.clinics?.name ?? 'No data'}</p>
</div> </div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Patient_id</p>
<p>{treatments?.patient_id?.first_name ?? 'No data'}</p>
</div>
<div className={'mb-4'}>
<p className={'block font-bold mb-2'}>Doctor_id</p>
<p>{treatments?.doctor_id?.firstName ?? 'No data'}</p>
</div>
<>
<p className={'block font-bold mb-2'}>Diagnoses Treatment_id</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Code</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
{treatments.diagnoses_treatment_id &&
Array.isArray(treatments.diagnoses_treatment_id) &&
treatments.diagnoses_treatment_id.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/diagnoses/diagnoses-view/?id=${item.id}`,
)
}
>
<td data-label='code'>{item.code}</td>
<td data-label='notes'>{item.notes}</td>
</tr>
))}
</tbody>
</table>
</div>
{!treatments?.diagnoses_treatment_id?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<>
<p className={'block font-bold mb-2'}>Prescriptions Treatment_id</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Medication</th>
<th>Dosage</th>
<th>Instructions</th>
</tr>
</thead>
<tbody>
{treatments.prescriptions_treatment_id &&
Array.isArray(treatments.prescriptions_treatment_id) &&
treatments.prescriptions_treatment_id.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/prescriptions/prescriptions-view/?id=${item.id}`,
)
}
>
<td data-label='medication'>{item.medication}</td>
<td data-label='dosage'>{item.dosage}</td>
<td data-label='instructions'>{item.instructions}</td>
</tr>
))}
</tbody>
</table>
</div>
{!treatments?.prescriptions_treatment_id?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -197,6 +197,43 @@ const UsersView = () => {
</CardBox> </CardBox>
</> </>
<>
<p className={'block font-bold mb-2'}>Treatments Doctor_id</p>
<CardBox
className='mb-6 border border-gray-300 rounded overflow-hidden'
hasTable
>
<div className='overflow-x-auto'>
<table>
<thead>
<tr>
<th>Cost</th>
</tr>
</thead>
<tbody>
{users.treatments_doctor_id &&
Array.isArray(users.treatments_doctor_id) &&
users.treatments_doctor_id.map((item: any) => (
<tr
key={item.id}
onClick={() =>
router.push(
`/treatments/treatments-view/?id=${item.id}`,
)
}
>
<td data-label='cost'>{item.cost}</td>
</tr>
))}
</tbody>
</table>
</div>
{!users?.treatments_doctor_id?.length && (
<div className={'text-center py-4'}>No data</div>
)}
</CardBox>
</>
<BaseDivider /> <BaseDivider />
<BaseButton <BaseButton

View File

@ -122,7 +122,7 @@ export default function WebSite() {
<FeaturesSection <FeaturesSection
projectName={'ClinicX'} projectName={'ClinicX'}
image={['Clinic management dashboard view']} image={['Clinic management dashboard view']}
withBg={1} withBg={0}
features={features_points} features={features_points}
mainText={`Discover ${projectName} Features`} mainText={`Discover ${projectName} Features`}
subTitle={`Explore the powerful features of ${projectName} designed to enhance clinic efficiency and patient care.`} subTitle={`Explore the powerful features of ${projectName} designed to enhance clinic efficiency and patient care.`}

View File

@ -105,7 +105,7 @@ export default function WebSite() {
<FeaturesSection <FeaturesSection
projectName={'ClinicX'} projectName={'ClinicX'}
image={['Icons representing clinic services']} image={['Icons representing clinic services']}
withBg={1} withBg={0}
features={features_points} features={features_points}
mainText={`Explore ${projectName} Service Features`} mainText={`Explore ${projectName} Service Features`}
subTitle={`Uncover the powerful features of ${projectName} designed to optimize your clinic's operations and enhance patient care.`} subTitle={`Uncover the powerful features of ${projectName} designed to optimize your clinic's operations and enhance patient care.`}

View File

@ -0,0 +1,236 @@
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import {
fulfilledNotify,
rejectNotify,
resetNotify,
} from '../../helpers/notifyStateHandler';
interface MainState {
diagnoses: any;
loading: boolean;
count: number;
refetch: boolean;
rolesWidgets: any[];
notify: {
showNotification: boolean;
textNotification: string;
typeNotification: string;
};
}
const initialState: MainState = {
diagnoses: [],
loading: false,
count: 0,
refetch: false,
rolesWidgets: [],
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
};
export const fetch = createAsyncThunk('diagnoses/fetch', async (data: any) => {
const { id, query } = data;
const result = await axios.get(`diagnoses${query || (id ? `/${id}` : '')}`);
return id
? result.data
: { rows: result.data.rows, count: result.data.count };
});
export const deleteItemsByIds = createAsyncThunk(
'diagnoses/deleteByIds',
async (data: any, { rejectWithValue }) => {
try {
await axios.post('diagnoses/deleteByIds', { data });
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const deleteItem = createAsyncThunk(
'diagnoses/deleteDiagnoses',
async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`diagnoses/${id}`);
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const create = createAsyncThunk(
'diagnoses/createDiagnoses',
async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post('diagnoses', { data });
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const uploadCsv = createAsyncThunk(
'diagnoses/uploadCsv',
async (file: File, { rejectWithValue }) => {
try {
const data = new FormData();
data.append('file', file);
data.append('filename', file.name);
const result = await axios.post('diagnoses/bulk-import', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const update = createAsyncThunk(
'diagnoses/updateDiagnoses',
async (payload: any, { rejectWithValue }) => {
try {
const result = await axios.put(`diagnoses/${payload.id}`, {
id: payload.id,
data: payload.data,
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const diagnosesSlice = createSlice({
name: 'diagnoses',
initialState,
reducers: {
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(fetch.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(fetch.fulfilled, (state, action) => {
if (action.payload.rows && action.payload.count >= 0) {
state.diagnoses = action.payload.rows;
state.count = action.payload.count;
} else {
state.diagnoses = action.payload;
}
state.loading = false;
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Diagnoses has been deleted');
});
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(deleteItem.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItem.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Diagnoses'.slice(0, -1)} has been deleted`);
});
builder.addCase(deleteItem.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(create.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Diagnoses'.slice(0, -1)} has been created`);
});
builder.addCase(update.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(update.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, `${'Diagnoses'.slice(0, -1)} has been updated`);
});
builder.addCase(update.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(uploadCsv.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(uploadCsv.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Diagnoses has been uploaded');
});
builder.addCase(uploadCsv.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
},
});
// Action creators are generated for each case reducer function
export const { setRefetch } = diagnosesSlice.actions;
export default diagnosesSlice.reducer;

View File

@ -0,0 +1,250 @@
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';
import {
fulfilledNotify,
rejectNotify,
resetNotify,
} from '../../helpers/notifyStateHandler';
interface MainState {
prescriptions: any;
loading: boolean;
count: number;
refetch: boolean;
rolesWidgets: any[];
notify: {
showNotification: boolean;
textNotification: string;
typeNotification: string;
};
}
const initialState: MainState = {
prescriptions: [],
loading: false,
count: 0,
refetch: false,
rolesWidgets: [],
notify: {
showNotification: false,
textNotification: '',
typeNotification: 'warn',
},
};
export const fetch = createAsyncThunk(
'prescriptions/fetch',
async (data: any) => {
const { id, query } = data;
const result = await axios.get(
`prescriptions${query || (id ? `/${id}` : '')}`,
);
return id
? result.data
: { rows: result.data.rows, count: result.data.count };
},
);
export const deleteItemsByIds = createAsyncThunk(
'prescriptions/deleteByIds',
async (data: any, { rejectWithValue }) => {
try {
await axios.post('prescriptions/deleteByIds', { data });
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const deleteItem = createAsyncThunk(
'prescriptions/deletePrescriptions',
async (id: string, { rejectWithValue }) => {
try {
await axios.delete(`prescriptions/${id}`);
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const create = createAsyncThunk(
'prescriptions/createPrescriptions',
async (data: any, { rejectWithValue }) => {
try {
const result = await axios.post('prescriptions', { data });
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const uploadCsv = createAsyncThunk(
'prescriptions/uploadCsv',
async (file: File, { rejectWithValue }) => {
try {
const data = new FormData();
data.append('file', file);
data.append('filename', file.name);
const result = await axios.post('prescriptions/bulk-import', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const update = createAsyncThunk(
'prescriptions/updatePrescriptions',
async (payload: any, { rejectWithValue }) => {
try {
const result = await axios.put(`prescriptions/${payload.id}`, {
id: payload.id,
data: payload.data,
});
return result.data;
} catch (error) {
if (!error.response) {
throw error;
}
return rejectWithValue(error.response.data);
}
},
);
export const prescriptionsSlice = createSlice({
name: 'prescriptions',
initialState,
reducers: {
setRefetch: (state, action: PayloadAction<boolean>) => {
state.refetch = action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetch.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(fetch.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(fetch.fulfilled, (state, action) => {
if (action.payload.rows && action.payload.count >= 0) {
state.prescriptions = action.payload.rows;
state.count = action.payload.count;
} else {
state.prescriptions = action.payload;
}
state.loading = false;
});
builder.addCase(deleteItemsByIds.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Prescriptions has been deleted');
});
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(deleteItem.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(deleteItem.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(
state,
`${'Prescriptions'.slice(0, -1)} has been deleted`,
);
});
builder.addCase(deleteItem.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(create.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(create.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(
state,
`${'Prescriptions'.slice(0, -1)} has been created`,
);
});
builder.addCase(update.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(update.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(
state,
`${'Prescriptions'.slice(0, -1)} has been updated`,
);
});
builder.addCase(update.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
builder.addCase(uploadCsv.pending, (state) => {
state.loading = true;
resetNotify(state);
});
builder.addCase(uploadCsv.fulfilled, (state) => {
state.loading = false;
fulfilledNotify(state, 'Prescriptions has been uploaded');
});
builder.addCase(uploadCsv.rejected, (state, action) => {
state.loading = false;
rejectNotify(state, action);
});
},
});
// Action creators are generated for each case reducer function
export const { setRefetch } = prescriptionsSlice.actions;
export default prescriptionsSlice.reducer;

View File

@ -12,6 +12,8 @@ import treatmentsSlice from './treatments/treatmentsSlice';
import rolesSlice from './roles/rolesSlice'; import rolesSlice from './roles/rolesSlice';
import permissionsSlice from './permissions/permissionsSlice'; import permissionsSlice from './permissions/permissionsSlice';
import clinicsSlice from './clinics/clinicsSlice'; import clinicsSlice from './clinics/clinicsSlice';
import diagnosesSlice from './diagnoses/diagnosesSlice';
import prescriptionsSlice from './prescriptions/prescriptionsSlice';
export const store = configureStore({ export const store = configureStore({
reducer: { reducer: {
@ -28,6 +30,8 @@ export const store = configureStore({
roles: rolesSlice, roles: rolesSlice,
permissions: permissionsSlice, permissions: permissionsSlice,
clinics: clinicsSlice, clinics: clinicsSlice,
diagnoses: diagnosesSlice,
prescriptions: prescriptionsSlice,
}, },
}); });