-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpatient.js
More file actions
733 lines (652 loc) · 18.3 KB
/
patient.js
File metadata and controls
733 lines (652 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
import { fakerEN_GB as faker } from '@faker-js/faker'
import _ from 'lodash'
import programmesData from '../datasets/programmes.js'
import schools from '../datasets/schools.js'
import { AuditEventType, NoticeType } from '../enums.js'
import {
AuditEvent,
Child,
Move,
Parent,
PatientProgramme,
PatientSession,
Programme,
Reply,
Vaccination
} from '../models.js'
import { getDateValueDifference, removeDays, today } from '../utils/date.js'
import { tokenize } from '../utils/object.js'
import { getPreferredNames } from '../utils/reply.js'
import {
formatLink,
formatLinkWithSecondaryText,
formatList,
formatNhsNumber,
formatOther,
formatParent,
formatWithSecondaryText,
sentenceCaseProgrammeName,
stringToBoolean
} from '../utils/string.js'
/**
* @class Patient record
* @augments Child
* @param {object} options - Options
* @param {object} [context] - Global context
* @property {string} uuid - UUID
* @property {string} nhsn - NHS number
* @property {boolean} invalid - Flagged as invalid
* @property {boolean} sensitive - Flagged as sensitive
* @property {Date} [updatedAt] - Updated date
* @property {object} [address] - Address
* @property {Parent} [parent1] - Parent 1
* @property {Parent} [parent2] - Parent 2
* @property {Patient} [pendingChanges] - Pending changes to record values
* @property {import('../enums.js').ArchiveRecordReason} [archiveReason] - Archival reason
* @property {string} [archiveReasonOther] - Other archival reason
* @property {Array<string} [clinicProgramme_ids] - Clinic programme invitations
* @property {Array<import('./audit-event.js').AuditEvent>} events - Events
* @property {Array<string>} [reply_uuids] - Reply IDs
* @property {Array<string>} [patientSession_uuids] - Patient session IDs
* @property {Array<string>} [vaccination_uuids] - Vaccination UUIDs
*/
export class Patient extends Child {
constructor(options, context) {
super(options, context)
const invalid = stringToBoolean(options?.invalid)
const sensitive = stringToBoolean(options?.sensitive)
this.uuid = options?.uuid || faker.string.uuid()
this.nhsn = options?.nhsn || this.nhsNumber
this.invalid = invalid
this.sensitive = sensitive
this.updatedAt = options?.updatedAt && new Date(options.updatedAt)
this.address = !sensitive && options?.address ? options.address : undefined
this.parent1 =
!sensitive && options?.parent1 ? new Parent(options.parent1) : undefined
this.parent2 =
!sensitive && options?.parent2 ? new Parent(options.parent2) : undefined
this.archiveReason = options?.archiveReason
this.archiveReasonOther = options?.archiveReasonOther
this.pendingChanges = options?.pendingChanges || {}
this.clinicProgramme_ids = options?.clinicProgramme_ids || []
this.events = options?.events || []
this.reply_uuids = options?.reply_uuids || []
this.patientSession_uuids = options?.patientSession_uuids || []
this.vaccination_uuids = options?.vaccination_uuids || []
}
/**
* Get NHS number
*
* @returns {string} NHS Number
*/
get nhsNumber() {
const nhsn = '999#######'.replace(/#+/g, (m) =>
faker.string.numeric(m.length)
)
const temporaryNhsn = faker.string.alpha(10)
// 5% of records don’t have an NHS number
const hasNhsNumber = faker.helpers.maybe(() => true, { probability: 0.95 })
return hasNhsNumber ? nhsn : temporaryNhsn
}
/**
* Has missing NHS number
*
* @returns {boolean} Has missing NHS number
*/
get hasMissingNhsNumber() {
return !this.nhsn.match(/^\d{10}$/)
}
/**
* Has no parental contact details
*
* @returns {boolean} Has no parental details
*/
get hasNoContactDetails() {
return (
!this.parent1?.email &&
!this.parent1?.tel &&
!this.parent2?.email &&
!this.parent2?.tel
)
}
/**
* Needs reasonable adjustments(s)
*
* @returns {boolean} Needs reasonable adjustments(s)
*/
get hasAdjustment() {
return this.adjustments.length > 0
}
/**
* Has impairment(s)
*
* @returns {boolean} Has impairment(s)
*/
get hasImpairment() {
return this.impairments.length > 0
}
/**
* Get full name, formatted as LASTNAME, Firstname
*
* @returns {string} Full name
*/
get fullName() {
return [this.lastName.toUpperCase(), this.firstName].join(', ')
}
/**
* Get preferred names (from replies)
*
* @returns {string|boolean} Full name
*/
get preferredNames() {
return getPreferredNames(this.replies)
}
/**
* Get parents (from record and replies)
*
* @returns {Array<Parent>} Parents
*/
get parents() {
const parents = new Map()
if (this.parent1) {
parents.set(this.parent1.uuid, new Parent(this.parent1))
}
if (this.parent2) {
parents.set(this.parent2.uuid, new Parent(this.parent2))
}
// Add any new parents found in consent replies
Object.values(this.replies).forEach(({ parent }) => {
if (parent && !parents.has(parent.uuid)) {
parents.set(parent.uuid, new Parent(parent))
}
})
return [...parents.values()]
}
get recordEvents() {
const recordEvents = []
recordEvents.push(
new AuditEvent({
type: AuditEventType.Record,
name: 'Child record imported',
createdAt: '2025-08-01T12:00:00'
})
)
if (this.sensitive) {
recordEvents.push(
new AuditEvent({
type: AuditEventType.Record,
name: 'Record flagged as sensitive',
createdAt: '2025-08-01T12:00:00'
})
)
}
let move
if (this.context.moves) {
move = Move.findAll(this.context).find(
(move) => move.patient_uuid === this.uuid
)
}
if (move) {
recordEvents.push(
new AuditEvent({
type: AuditEventType.Record,
// Fake it to make it look like school move has already occurred
name: `Moved from ${move.formatted.to_urn} to ${move.formatted.from_urn}`,
createdAt: move.createdAt
})
)
}
return recordEvents
}
/**
* Get audit events
*
* @returns {Array<AuditEvent>} Audit events
*/
get auditEvents() {
const events = [...this.events, ...this.recordEvents]
return events
.map((auditEvent) => new AuditEvent(auditEvent, this.context))
.filter(({ type }) => type === AuditEventType.Record)
}
/**
* Get audit events grouped by date
*
* @returns {object} Audit events grouped by date
*/
get auditEventLog() {
const auditEvents = this.auditEvents.sort((a, b) =>
getDateValueDifference(b.createdAt, a.createdAt)
)
return Object.groupBy(auditEvents, (auditEvent) => {
return auditEvent.formatted.createdAt
})
}
/**
* Get reminders sent
*
* @returns {Array} Reminders sent
*/
get reminders() {
return this.events
.map((event) => new AuditEvent(event))
.filter((event) => event.type === AuditEventType.Reminder)
}
/**
* Get date last reminders sent
*
* @returns {string|undefined} Date last reminders sent
*/
get lastReminderDate() {
const lastReminder = this.reminders.at(-1)
if (lastReminder) {
return lastReminder.formatted.createdAt
}
}
/**
* Get all notices
*
* @returns {Array<AuditEvent>} Notice events
*/
get notices() {
return this.events
.map((event) => new AuditEvent(event))
.filter((event) => event.type === AuditEventType.Notice)
}
/**
* Get most recent notice
*
* @returns {AuditEvent} Notice event
*/
get notice() {
return this.notices && this.notices[0]
}
/**
* Get patient programmes
*
* @returns {Record<string, PatientProgramme>}
*/
get programmes() {
/** @type {Record<string, PatientProgramme>} */
const programmes = {}
for (const programme of Object.values(programmesData).filter(
(programme) => !programme.hidden
)) {
const patientProgramme = new PatientProgramme(
{
patient_uuid: this.uuid,
programme_id: programme.id
},
this.context
)
// Patient invited to clinic if invitation needed and invitation sent
patientProgramme.invitedToClinic =
patientProgramme.inviteToSession &&
this.clinicProgramme_ids.includes(programme.id)
programmes[programme.id] = patientProgramme
}
return programmes
}
/**
* Get replies
*
* @returns {Array<Reply>} Replies
*/
get replies() {
return this.reply_uuids
.map((uuid) => Reply.findOne(uuid, this.context))
.filter((reply) => reply?.patient_uuid === this.uuid)
}
/**
* Get patient sessions
*
* @returns {Array<PatientSession>} Patient sessions
*/
get patientSessions() {
if (this.context?.patientSessions && this.patientSession_uuids) {
return this.patientSession_uuids
.map((uuid) => PatientSession.findOne(uuid, this.context))
.sort((a, b) => getDateValueDifference(b.createdAt, a.createdAt))
}
return []
}
/**
* Get vaccinations
*
* @returns {Array<Vaccination>} Vaccinations
*/
get vaccinations() {
if (this.context?.vaccinations && this.vaccination_uuids) {
return this.vaccination_uuids.map(
(uuid) =>
new Vaccination(this.context?.vaccinations[uuid], this.context)
)
}
return []
}
/**
* Record is archived
*
* @returns {boolean} Record is archived
*/
get archived() {
return this.archiveReason !== undefined
}
/**
* Has pending changes
*
* @returns {boolean} Has pending changes
*/
get hasPendingChanges() {
return Object.keys(this.pendingChanges).length > 0
}
/**
* Get formatted links
*
* @returns {object} Formatted links
*/
get link() {
return {
fullName: formatLink(this.uri, this.fullName),
fullNameAndNhsn: formatLinkWithSecondaryText(
this.uri,
this.fullName,
this.formatted.nhsn || 'Missing NHS number'
)
}
}
/**
* Get formatted summary
*
* @returns {object} Formatted summaries
*/
get summary() {
return {
dob: `${this.formatted.dob}</br>
<span class="nhsuk-u-secondary-text-colour nhsuk-u-font-size-16">
${this.formatted.yearGroup}
</span>`
}
}
/**
* Get tokenised values (to use in search queries)
*
* @returns {string} Tokens
*/
get tokenized() {
const parentTokens = []
for (const parent of this.parents) {
parentTokens.push(tokenize(parent, ['fullName', 'tel', 'email']))
}
const childTokens = tokenize(this, [
'nhsn',
'fullName',
'postalCode',
'school.name'
])
return [childTokens, parentTokens].join(' ')
}
/**
* Get formatted values
*
* @returns {object} Formatted values
*/
get formatted() {
const formattedNhsn = formatNhsNumber(this.nhsn, this.invalid)
const formattedParents = this.parents.map((parent) => formatParent(parent))
return {
...super.formatted,
fullNameAndNhsn: formatWithSecondaryText(this.fullName, formattedNhsn),
nhsn: formattedNhsn,
newUrn:
this.pendingChanges?.school_id &&
schools[this.pendingChanges.school_id].name,
parent1: this.parent1 && formatParent(this.parent1),
parent2: this.parent2 && formatParent(this.parent2),
parents: formatList(formattedParents),
archiveReason: formatOther(this.archiveReasonOther, this.archiveReason),
lastReminderDate: this.lastReminderDate
? `Last reminder sent on ${this.lastReminderDate}`
: 'No reminders sent',
clinicProgramme_ids: this.clinicProgramme_ids
.map((id) => Programme.findOne(id, this.context).nameTag)
.join(' ')
}
}
/**
* Get namespace
*
* @returns {string} Namespace
*/
get ns() {
return 'patient'
}
/**
* Get URI
*
* @returns {string} URI
*/
get uri() {
return `/patients/${this.uuid}`
}
/**
* Find all
*
* @param {object} context - Context
* @returns {Array<Patient>|undefined} Patient records
* @static
*/
static findAll(context) {
return Object.values(context.patients).map(
(patient) => new Patient(patient, context)
)
}
/**
* Find one
*
* @param {string} uuid - Patient UUID
* @param {object} context - Context
* @returns {Patient|undefined} Patient record
* @static
*/
static findOne(uuid, context) {
if (context?.patients?.[uuid]) {
return new Patient(context.patients[uuid], context)
}
}
/**
* Create
*
* @param {Patient} patient - Patient record
* @param {object} context - Context
* @returns {Patient} Created patient record
* @static
*/
static create(patient, context) {
const createdPatient = new Patient(patient)
// Update context
context.patients = context.patients || {}
context.patients[createdPatient.uuid] = createdPatient
return createdPatient
}
/**
* Update
*
* @param {string} uuid - Patient record UUID
* @param {object} updates - Updates
* @param {object} context - Context
* @returns {Patient} Updated patient record
* @static
*/
static update(uuid, updates, context) {
const updatedPatient = _.merge(Patient.findOne(uuid, context), updates)
updatedPatient.updatedAt = today()
// Add update to activity log (but only when updating wizard context)
// TODO: Make this work with nested values like date of birth
if (Object.keys(context.patients).length === 1) {
for (const [key, value] of Object.entries(updates)) {
updatedPatient.addEvent({
name: `Updated \`${key}\` to **${value}**`,
type: AuditEventType.Record,
createdAt: updatedPatient.updatedAt
})
}
}
// Remove patient context
delete updatedPatient.context
// Delete original patient (with previous UUID)
delete context.patients[uuid]
// Update context
context.patients[updatedPatient.uuid] = updatedPatient
return updatedPatient
}
/**
* Add event to activity log
*
* @param {object} event - Event
*/
addEvent(event) {
this.events.push(new AuditEvent(event))
}
/**
* Archive
*
* @param {string} uuid - Patient record UUID
* @param {object} archive - Archive details
* @param {object} context - Context
* @returns {Patient} Archived patient record
* @static
*/
static archive(uuid, archive, context) {
const archivedPatient = Patient.update(uuid, archive, context)
archivedPatient.addEvent({
name: `Record archived: ${archive.archiveReason}`,
note: archive.archiveReasonOther,
type: AuditEventType.Record,
createdBy_uid: archive.createdBy_uid
})
return archivedPatient
}
/**
* Add patient to session
*
* @param {import('./patient-session.js').PatientSession} patientSession - Patient session
*/
addToSession(patientSession) {
this.patientSession_uuids.push(patientSession.uuid)
}
/**
* Invite parent to give consent
*
* @param {import('./session.js').Session} session - Session
*/
inviteToSession(session) {
this.addEvent({
name: `Added to the ${sentenceCaseProgrammeName(session.name)}`,
createdAt: session.openAt,
createdBy_uid: session.createdBy_uid,
programme_ids: session.programme_ids
})
}
/**
* Record reply
*
* @param {object} reply - Reply
*/
addReply(reply) {
if (!reply) {
return
}
const { decision, fullName, invalid, relationship, uuid } = reply
const isNew = !this.replies[uuid]
const parent = new Parent({ fullName, relationship })
const formattedParent = formatParent(parent, false)
let name = `${decision} by ${formattedParent}`
if (invalid) {
name = `${decision} by ${formattedParent} marked as invalid`
} else if (isNew) {
name = `${decision} in response from ${formattedParent}`
} else {
name = `${decision} in updated response from ${formattedParent}`
}
this.reply_uuids.push(reply.uuid)
this.addEvent({
name,
createdAt: isNew ? reply.createdAt : today(),
createdBy_uid: reply.createdBy_uid,
programme_ids: [reply.programme_id]
})
}
/**
* Record vaccination
*
* @param {import('./vaccination.js').Vaccination} vaccination - Vaccination
*/
recordVaccination(vaccination) {
this.vaccination_uuids.push(vaccination.uuid)
let name
if (vaccination.given) {
name = vaccination.updatedAt
? `Vaccination record for ${vaccination.formatted.vaccine_snomed} updated`
: `Vaccinated with ${vaccination.formatted.vaccine_snomed}`
} else {
name = `Unable to vaccinate: ${vaccination.outcome}`
}
this.addEvent({
name,
note: vaccination.note,
createdAt: vaccination.updatedAt || vaccination.createdAt,
createdBy_uid: vaccination.createdBy_uid,
programme_ids: [vaccination.programme_id]
})
}
/**
* Save note
*
* @param {import('./audit-event.js').AuditEvent} event - Event
*/
saveNote(event) {
this.addEvent({
type: AuditEventType.Record,
name: event.name,
note: event.note,
createdBy_uid: event.createdBy_uid
})
}
/**
* Add notice
*
* @param {import('./notice.js').Notice} notice - Notice
*/
addNotice(notice) {
let name
switch (true) {
case notice.type === NoticeType.Deceased:
// Update patient record with date of death
this.dod = removeDays(today(), 5)
name = `Record updated with child’s date of death`
break
case notice.type === NoticeType.NoNotify && this.parent1?.notify:
// Notify request to not share vaccination with GP
this.parent1.notify = false
name = `Child gave consent for HPV and flu vaccinations under Gillick competence and does not want their parents to be notified.\n\nThese records are not automatically synced with GP records.\n\nYour team must let the child’s GP know they were vaccinated.`
break
case notice.type === NoticeType.Invalid:
// Flag record as invalid
this.invalid = true
name = `Record flagged as invalid`
break
case notice.type === NoticeType.Sensitive:
// Flag record as sensitive
this.sensitive = true
name = `Record flagged as sensitive`
break
default:
}
this.addEvent({
type: AuditEventType.Notice,
name,
createdAt: notice.createdAt
})
}
}