def records(reuest): """ Add a list of all non-singleton subrecords to context """ show = [s for s in subrecords() if not s._is_singleton] show = [s for s in show if s.get_display_name() != 'Inpatient Admissions'] return {'records': show}
def remove_unchanged_subrecords(self, episode, new_data, user): # to_dict outputs dates as date() instances, but our incoming data # will be settings.DATE_FORMAT date strings. So we dump() then load() old_data = json.dumps(episode.to_dict(user), cls=OpalSerializer) old_data = json.loads(old_data) changed = defaultdict(list) for subrecord_class in subrecords.subrecords(): subrecord_name = subrecord_class.get_api_name() old_subrecords = old_data.get(subrecord_name) new_subrecords = new_data.get(subrecord_name) if not new_subrecords: continue if not old_subrecords and new_subrecords: changed[subrecord_name] = new_subrecords continue id_to_old_subrecord = {i["id"]: i for i in old_subrecords} for new_subrecord in new_subrecords: if not new_subrecord.get("id"): changed[subrecord_name].append(new_subrecord) else: # schema doesn't translate these ids, so pop them out old_subrecord = id_to_old_subrecord[new_subrecord["id"]] old_subrecord.pop("episode_id", None) old_subrecord.pop("patient_id", None) if not new_subrecord == old_subrecord: changed[subrecord_name].append(new_subrecord) return changed
def get_context_data(self, *args, **kwargs): context = super(MicroHaemTemplateView, self).get_context_data(*args, **kwargs) context['models'] = {m.__name__: m for m in subrecords()} context['inline_forms'] = { "General Consultation": "inline_forms/clinical_advice.html", } return context
def _get_all_fields(): response = { subclass.get_api_name(): serialize_model(subclass) for subclass in subrecords() } response['tagging'] = serialize_model(models.Tagging) return response
def test_subrecords_are_populated(self): context = context_processors.models(None) subrecord_context = context["models"] for subrecord in subrecords(): name = subrecord.__name__ found_class = getattr(subrecord_context, name) self.assertEqual(found_class, subrecord)
def generate_csv_files(root_dir, episodes, user): """ Generate the files and return a tuple of absolute_file_name, file_name """ file_names = [] file_name = "data_dictionary.html" full_file_name = os.path.join(root_dir, file_name) write_data_dictionary(full_file_name) file_names.append((full_file_name, file_name,)) file_name = "episodes.csv" full_file_name = os.path.join(root_dir, file_name) renderer = EpisodeCsvRenderer(Episode, episodes, user) renderer.write_to_file(full_file_name) file_names.append((full_file_name, file_name,)) for subrecord in subrecords(): if getattr(subrecord, '_exclude_from_extract', False): continue file_name = '{0}.csv'.format(subrecord.get_api_name()) full_file_name = os.path.join(root_dir, file_name) if subrecord in episode_subrecords(): renderer = EpisodeSubrecordCsvRenderer( subrecord, episodes, user ) else: renderer = PatientSubrecordCsvRenderer( subrecord, episodes, user ) if renderer.count(): renderer.write_to_file(full_file_name) file_names.append((full_file_name, file_name,)) return file_names
def test_all_modal_templates(self): """ This renders all of our modal templates and blows up if they fail to render """ for i in subrecords(): if i.get_form_template(): url = reverse("{}_modal".format(i.get_api_name())) self.assertStatusCode(url, 200)
def register_subrecords(): for subrecord in subrecords(): sub_name = subrecord.get_api_name() class SubViewSet(SubrecordViewSet): base_name = sub_name model = subrecord router.register(sub_name, SubViewSet)
def get_data_dictionary(): schema = {} for subrecord in subrecords(): if getattr(subrecord, '_exclude_from_extract', False): continue field_names = subrecord._get_fieldnames_to_extract() record_schema = [field_to_dict(subrecord, i) for i in field_names] schema[subrecord.get_display_name()] = record_schema field_names = Episode._get_fieldnames_to_extract() schema["Episode"] = [field_to_dict(Episode, i) for i in field_names] return OrderedDict(sorted(schema.items(), key=lambda t: t[0]))
def get_context_data(self, **kwargs): context = super(EpisodeTemplateView, self).get_context_data(**kwargs) teams = models.Team.for_user(self.request.user) context['teams'] = teams context['columns'] = self.get_column_context(**kwargs) if 'tag' in kwargs: try: context['team'] = models.Team.objects.get(name=kwargs['tag']) except models.Team.DoesNotExist: context['team'] = None context['models'] = {m.__name__: m for m in subrecords()} return context
def get_context_data(self, **kwargs): context = super(EpisodeTemplateView, self).get_context_data(**kwargs) teams = models.Team.for_user(self.request.user) context['teams'] = teams context['columns'] = self.get_column_context(**kwargs) if 'tag' in kwargs: try: context['team'] = models.Team.objects.get(name=kwargs['tag']) except models.Team.DoesNotExist: context['team'] = None context['models'] = { m.__name__: m for m in subrecords() } return context
def scaffold_subrecords( app, migrations=True, dry_run=False, dir=SCAFFOLDING_BASE ): """ In which we scaffold an django app (opal plugin or application). 1. Make migrations 2. Migrate 3. Create Form Templates of all subrecords in the models 4. Create Record Templates of all subrecords in the models """ if app not in apps.all_models: err = "Unable to find app {} in settings.INSTALLED_APPS" raise ValueError( err.format(app) ) if migrations: if dry_run: management.call_command( 'makemigrations', app, "--traceback", "--dry-run" ) else: management.call_command( 'makemigrations', app, "--traceback" ) management.call_command('migrate', app, "--traceback") models = apps.all_models[app] all_subrecords = set(i for i in subrecords.subrecords()) for model in models.values(): if model in all_subrecords: if not model.get_display_template(): if dry_run: write('No Display template for {0}'.format(model)) else: create_display_template_for( model, SCAFFOLDING_BASE ) if not model.get_form_template(): if dry_run: write('No Form template for {0}'.format(model)) else: create_form_template_for( model, SCAFFOLDING_BASE )
def get_context_data(self, *args, **kwargs): ctx = super(OverviewSubrecordListView, self).get_context_data(*args, **kwargs) episode_qs = self.get_episode_qs() ctx["subrecords"] = [] for subrecord in subrecords.subrecords(): qs = overview_utils.get_subrecord_use( subrecord, episode_qs, ) ctx["subrecords"].append( (overview_utils.get_summary_row(subrecord, qs, episode_qs))) ctx["subrecords"] = sorted(ctx["subrecords"], key=lambda x: x[0]) ctx["subrecords"] = sorted(ctx["subrecords"], key=lambda x: -x[1]) ctx["subrecords"] = sorted(ctx["subrecords"], key=lambda x: -x[2]) return ctx
def get_data_dictionary(): schema = {} for subrecord in subrecords(): field_names = subrecord._get_fieldnames_to_extract() record_schema = [field_to_dict(subrecord, i) for i in field_names] schema[subrecord.get_display_name()] = record_schema field_names = Episode._get_fieldnames_to_extract() field_names.remove("start") field_names.remove("end") schema["Episode"] = [field_to_dict(Episode, i) for i in field_names] schema["Episode"].append(dict( display_name="Start", type_display_name="Date & Time" )) schema["Episode"].append(dict( display_name="End", type_display_name="Date & Time" )) return OrderedDict(sorted(schema.items(), key=lambda t: t[0]))
def scaffold_subrecords(app, migrations=True, dry_run=False, dir=SCAFFOLDING_BASE): """ In which we scaffold an django app (opal plugin or application). 1. Make migrations 2. Migrate 3. Create Form Templates of all subrecords in the models 4. Create Record Templates of all subrecords in the models """ if app not in apps.all_models: err = "Unable to find app {} in settings.INSTALLED_APPS" raise ValueError(err.format(app)) if migrations: if dry_run: management.call_command('makemigrations', app, "--traceback", "--dry-run") else: management.call_command('makemigrations', app, "--traceback") management.call_command('migrate', app, "--traceback") models = apps.all_models[app] all_subrecords = set(i for i in subrecords.subrecords()) for model in models.values(): if model in all_subrecords: if not model.get_display_template(): if dry_run: write('No Display template for {0}'.format(model)) else: create_display_template_for(model, SCAFFOLDING_BASE) if not model.get_form_template(): if dry_run: write('No Form template for {0}'.format(model)) else: create_form_template_for(model, SCAFFOLDING_BASE)
def remove_unchanged_subrecords(self, episode, new_data, user): # to_dict outputs dates as date() instances, but our incoming data # will be settings.DATE_FORMAT date strings. So we dump() then load() old_data = json.dumps( episode.to_dict(user), cls=OpalSerializer ) old_data = json.loads(old_data) changed = defaultdict(list) for subrecord_class in subrecords.subrecords(): subrecord_name = subrecord_class.get_api_name() old_subrecords = old_data.get(subrecord_name) new_subrecords = new_data.get(subrecord_name) if not new_subrecords: continue if not old_subrecords and new_subrecords: changed[subrecord_name] = new_subrecords continue id_to_old_subrecord = {i["id"]: i for i in old_subrecords} for new_subrecord in new_subrecords: if not new_subrecord.get("id"): changed[subrecord_name].append(new_subrecord) else: # schema doesn't translate these ids, so pop them out old_subrecord = id_to_old_subrecord[new_subrecord["id"]] old_subrecord.pop("episode_id", None) old_subrecord.pop("patient_id", None) if not new_subrecord == old_subrecord: changed[subrecord_name].append(new_subrecord) return changed
return json_response(patientlist.to_dict(request.user)) router.register('patient', PatientViewSet) router.register('episode', EpisodeViewSet) router.register('record', RecordViewSet) router.register('userprofile', UserProfileViewSet) router.register('user', UserViewSet) router.register('tagging', TaggingViewSet) router.register('patientlist', PatientListViewSet) router.register('patientrecordaccess', PatientRecordAccessViewSet) router.register('referencedata', ReferenceDataViewSet) router.register('metadata', MetadataViewSet) for subrecord in subrecords(): sub_name = subrecord.get_api_name() class SubViewSet(SubrecordViewSet): base_name = sub_name model = subrecord router.register(sub_name, SubViewSet) def register_plugin_apis(): for plugin in plugins.OpalPlugin.list(): for api in plugin.get_apis(): router.register(*api)
def extract_schema(): custom_rules = [i().to_dict() for i in SearchRule.list()] schema = serialize_schema(itertools.chain([models.Tagging], subrecords())) return custom_rules + schema
def test_subrecords(self): all_subrecords = [i for i in subrecords.subrecords()] self.assertIn(tmodels.FamousLastWords, all_subrecords) self.assertIn(tmodels.HatWearer, all_subrecords)
def extract_schema(): return serialize_schema(itertools.chain([models.Tagging], subrecords()))
# New Public facing API urls url(r'api/v0.1/', include(api.router.urls)), url(r'^templates/record/(?P<model>[0-9a-z_\-]+).html$', views.RecordTemplateView.as_view(), name="record_view"), url(r'^templates/forms/(?P<model>[0-9a-z_\-]+).html/?$', views.FormTemplateView.as_view(), name="form_view"), url(r'^design-patterns/$', TemplateView.as_view(template_name='design_patterns.html'), name='design_patterns'), ] # Generated subrecord template views for subrecord_model in subrecords.subrecords(): sub_url = subrecord_model.get_api_name() url_name = "{}_modal".format(sub_url) urlpatterns += [ url(r'^templates/modals/%s.html/?$' % sub_url, views.ModalTemplateView.as_view(), {'model': subrecord_model}, name=url_name), url(r'^templates/modals/%s.html/(?P<list>[0-9a-z_\-]+/?)$' % sub_url, views.ModalTemplateView.as_view(), {'model': subrecord_model}, name=url_name) ] urlpatterns += staticfiles_urlpatterns() for plugin in plugins.OpalPlugin.list(): urlpatterns += plugin.get_urls()
url(r"^templates/modals/undischarge.html/?$", views.UndischargeTemplateView.as_view()), url(r"^templates/modals/add_episode.html/?$", views.AddEpisodeTemplateView.as_view()), url(r"^templates/modals/add_episode_without_teams.html/?$", views.AddEpisodeWithoutTeamsTemplateView.as_view()), url(r"^templates/modals/hospital_number.html/?$", views.HospitalNumberTemplateView.as_view()), url(r"^templates/modals/reopen_episode.html/?$", views.ReopenEpisodeTemplateView.as_view()), url(r"^templates/modals/discharge_episode.html/?$", views.DischargeEpisodeTemplateView.as_view()), url(r"^templates/modals/copy_to_category.html/?$", views.CopyToCategoryTemplateView.as_view()), url(r"^templates/modals/delete_item_confirmation.html/?$", views.DeleteItemConfirmationView.as_view()), # New Public facing API urls url(r"api/v0.1/episode/admit", csrf_exempt(api.APIAdmitEpisodeView.as_view())), url(r"api/v0.1/episode/refer", csrf_exempt(api.APIReferPatientView.as_view())), url(r"api/v0.1/", include(api.router.urls)), ) # Generated subrecord template views for subrecord_model in subrecords(): sub_url = camelcase_to_underscore(subrecord_model.__name__) urlpatterns += patterns( "", url(r"^templates/modals/%s.html/?$" % sub_url, views.ModalTemplateView.as_view(), {"model": subrecord_model}), url( r"^templates/modals/%s.html/(?P<tag>[a-z_\-]+)/?$" % sub_url, views.ModalTemplateView.as_view(), {"model": subrecord_model}, ), url( r"^templates/modals/%s.html/(?P<tag>[a-z_\-]+)/(?P<subtag>[a-z_\-]+)/?$" % sub_url, views.ModalTemplateView.as_view(), {"model": subrecord_model}, ), )
def get_context_data(self, **kwargs): context = super(EpisodeDetailTemplateView, self).get_context_data(**kwargs) context['models'] = { m.__name__: m for m in subrecords() } return context
def extract_schema(): custom_queries = [i().to_dict() for i in SearchRule.list()] schema = serialize_schema(itertools.chain([models.Tagging], subrecords())) return custom_queries + schema
def extract_schema(): return serialize_schema([models.Tagging] + [c for c in subrecords()])
router.register('patient', PatientViewSet) router.register('episode', EpisodeViewSet) router.register('record', RecordViewSet) router.register('extract-schema', ExtractSchemaViewSet) router.register('userprofile', UserProfileViewSet) router.register('tagging', TaggingViewSet) router.register('patientlist', PatientListViewSet) router.register('patientrecordaccess', PatientRecordAccessViewSet) router.register('options', OptionsViewSet) router.register('referencedata', ReferenceDataViewSet) router.register('metadata', MetadataViewSet) for subrecord in subrecords(): sub_name = camelcase_to_underscore(subrecord.__name__) class SubViewSet(SubrecordViewSet): base_name = sub_name model = subrecord router.register(sub_name, SubViewSet) for plugin in plugins.plugins(): for api in plugin.apis: router.register(*api) class APIAdmitEpisodeView(View): """ Admit an episode from upstream!
def get_context_data(self, **kwargs): context = super(EpisodeDetailTemplateView, self).get_context_data(**kwargs) context['models'] = {m.__name__: m for m in subrecords()} return context