Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(dashboard): migration pour cleaner les dossiers médicaux dupliqués #1707

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion api/src/controllers/migration.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const { looseUuidRegex, dateRegex } = require("../utils");
const { capture } = require("../sentry");
const validateUser = require("../middleware/validateUser");
const { serializeOrganisation } = require("../utils/data-serializer");
const { Organisation, Person, Action, Comment, Report, Team, Service, sequelize, Group } = require("../db/sequelize");
const { Organisation, Person, Action, Comment, Report, Team, Service, sequelize, Group, MedicalFile } = require("../db/sequelize");

router.put(
"/:migrationName",
Expand Down Expand Up @@ -88,6 +88,29 @@ router.put(
}
}

if (req.params.migrationName === "clean-duplicated-medical-files") {
try {
z.array(z.string().regex(looseUuidRegex)).parse(req.body.medicalFileIdsToDelete);
z.array(
z.object({
_id: z.string().regex(looseUuidRegex),
encrypted: z.string(),
encryptedEntityKey: z.string(),
})
).parse(req.body.medicalFilesToUpdate);
} catch (e) {
const error = new Error(`Invalid request in clean-duplicated-medical-files migration: ${e}`);
error.status = 400;
throw error;
}
for (const _id of req.body.medicalFileIdsToDelete) {
await MedicalFile.destroy({ where: { _id, organisation: req.user.organisation }, transaction: tx });
}
for (const { _id, encrypted, encryptedEntityKey } of req.body.medicalFilesToUpdate) {
await MedicalFile.update({ encrypted, encryptedEntityKey }, { where: { _id }, transaction: tx, paranoid: false });
}
}

organisation.set({
migrations: [...(organisation.migrations || []), req.params.migrationName],
migrating: false,
Expand Down
72 changes: 72 additions & 0 deletions dashboard/src/components/DataMigrator.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { looseUuidRegex } from '../utils';
import { prepareCommentForEncryption } from '../recoil/comments';
import { prepareGroupForEncryption } from '../recoil/groups';
import { capture } from '../services/sentry';
import { defaultMedicalFileCustomFields, prepareMedicalFileForEncryption } from '../recoil/medicalFiles';

const LOADING_TEXT = 'Mise à jour des données de votre organisation…';

Expand Down Expand Up @@ -111,6 +112,77 @@ export default function useDataMigrator() {
migrationLastUpdateAt = response.organisation.migrationLastUpdateAt;
}
}

if (['admin', 'normal'].includes(user.role) && !organisation.migrations?.includes('clean-duplicated-medical-files')) {
setLoadingText(LOADING_TEXT);
const customFieldsMedicalFile = Array.isArray(organisation.customFieldsMedicalFile)
? organisation.customFieldsMedicalFile
: defaultMedicalFileCustomFields;
const medicalFiles = await API.get({
path: '/medical-file',
query: { organisation: organisationId, after: 0, withDeleted: false },
}).then((res) => res.decryptedData || []);

const medicalFilePerPersonId = {};
const medicalFilesPerPersonId = {};
const medicalFilesToUpdate = {};
const medicalFileIdsToDelete = [];
for (const newMedicalFile of medicalFiles) {
const personId = newMedicalFile.person;
if (medicalFilePerPersonId[personId]) {
if (!medicalFilesPerPersonId[personId]) medicalFilesPerPersonId[personId] = [medicalFilePerPersonId[personId]];
medicalFilesPerPersonId[personId].push(newMedicalFile);
const existingMedicalFile = medicalFilePerPersonId[personId];
const nextDocuments = {};
const nextComments = {};
for (const document of newMedicalFile.documents || []) {
nextDocuments[document._id] = document;
}
for (const document of existingMedicalFile.documents || []) {
nextDocuments[document._id] = document;
}
for (const comment of newMedicalFile.comments || []) {
nextComments[comment._id] = comment;
}
for (const comment of existingMedicalFile.comments || []) {
nextComments[comment._id] = comment;
}
medicalFilePerPersonId[personId] = {
...newMedicalFile,
...existingMedicalFile,
documents: Object.values(nextDocuments),
comments: Object.values(nextComments),
};
medicalFileIdsToDelete.push(newMedicalFile._id);
medicalFilesToUpdate[personId] = medicalFilePerPersonId[personId];
} else {
medicalFilePerPersonId[personId] = newMedicalFile;
}
}

const encryptedMedicalFilesToUpdate = await Promise.all(
Object.values(medicalFilesToUpdate)
.map((medicalFile) => prepareMedicalFileForEncryption(customFieldsMedicalFile)(medicalFile))
.map(encryptItem)
);

console.log('medicalFilesPerPersonId', medicalFilesPerPersonId);
console.log('medicalFilesToUpdate', medicalFilesToUpdate);
console.log(
'encryptedMedicalFilesToUpdate',
encryptedMedicalFilesToUpdate.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt))
);

// const response = await API.put({
// path: `/migration/clean-duplicated-medical-files`,
// body: { medicalFileIdsToDelete, medicalFilesToUpdate: encryptedMedicalFilesToUpdate },
// query: { migrationLastUpdateAt },
// });
// if (response.ok) {
// setOrganisation(response.organisation);
// migrationLastUpdateAt = response.organisation.migrationLastUpdateAt;
// }
}
},
};
}
2 changes: 1 addition & 1 deletion dashboard/src/recoil/medicalFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export const prepareMedicalFileForEncryption =
};
};

const defaultMedicalFileCustomFields: CustomField[] = [
export const defaultMedicalFileCustomFields: CustomField[] = [
{
name: 'numeroSecuriteSociale',
label: 'Numéro de sécurité sociale',
Expand Down
7 changes: 7 additions & 0 deletions dashboard/src/recoil/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,19 @@ export const itemsGroupedByPersonSelector = selector({
for (const medicalFile of medicalFiles) {
if (!personsObject[medicalFile.person]) continue;
if (personsObject[medicalFile.person].medicalFile) {
if ('0a0f7577-890e-4731-a71c-a78cbcf1d595' === medicalFile.person) {
console.log('medicalFile', medicalFile);
console.log('personsObject[medicalFile.person].medicalFile', personsObject[medicalFile.person].medicalFile);
}
personsObject[medicalFile.person].medicalFile = {
...medicalFile,
...personsObject[medicalFile.person].medicalFile,
documents: [...(medicalFile?.documents || []), ...(personsObject[medicalFile.person].medicalFile?.documents || [])],
comments: [...(medicalFile?.comments || []), ...(personsObject[medicalFile.person].medicalFile?.comments || [])],
};
if ('0a0f7577-890e-4731-a71c-a78cbcf1d595' === medicalFile.person) {
console.log('new personsObject[medicalFile.person].medicalFile', personsObject[medicalFile.person].medicalFile);
}
} else {
personsObject[medicalFile.person].medicalFile = medicalFile;
}
Expand Down
Loading