author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
288,323 | 02.04.2020 23:00:25 | 18,000 | f354c940ceac9e41b6b92d21fc37c91c7eb09121 | feat(labs): adds test for lab related routes | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/HospitalRun.test.tsx",
"new_path": "src/__tests__/HospitalRun.test.tsx",
"diff": "@@ -14,6 +14,8 @@ import Appointments from 'scheduling/appointments/Appointments'\nimport NewAppointment from 'scheduling/appointments/new/NewAppointment'\nimport EditAppointment from 'scheduling/appointments/edit/EditAppointment'\nimport { addBreadcrumbs } from 'breadcrumbs/breadcrumbs-slice'\n+import ViewLabs from 'labs/ViewLabs'\n+import LabRepository from 'clients/db/LabRepository'\nimport NewPatient from '../patients/new/NewPatient'\nimport EditPatient from '../patients/edit/EditPatient'\nimport ViewPatient from '../patients/view/ViewPatient'\n@@ -407,6 +409,49 @@ describe('HospitalRun', () => {\nexpect(wrapper.find(Dashboard)).toHaveLength(1)\n})\n})\n+\n+ describe('/labs', () => {\n+ it('should render the Labs component when /labs is accessed', () => {\n+ jest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.ViewLabs] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs']}>\n+ <HospitalRun />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewLabs)).toHaveLength(1)\n+ })\n+\n+ it('should render the dasboard if the user does not have permissions to view labs', () => {\n+ jest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs']}>\n+ <HospitalRun />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewLabs)).toHaveLength(0)\n+ expect(wrapper.find(Dashboard)).toHaveLength(1)\n+ })\n+ })\n})\ndescribe('layout', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Navbar.test.tsx",
"new_path": "src/__tests__/components/Navbar.test.tsx",
"diff": "@@ -96,20 +96,14 @@ describe('Navbar', () => {\nit('should navigate to to /labs when the labs list option is selected', () => {\nact(() => {\n- labsLinkList\n- .first()\n- .props()\n- .children[0].props.onClick()\n+ labsLinkList.first().props().children[0].props.onClick()\n})\nexpect(history.location.pathname).toEqual('/labs')\n})\nit('should navigate to /labs/new when the new labs list option is selected', () => {\nact(() => {\n- labsLinkList\n- .first()\n- .props()\n- .children[1].props.onClick()\n+ labsLinkList.first().props().children[1].props.onClick()\n})\nexpect(history.location.pathname).toEqual('/labs/new')\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Sidebar.test.tsx",
"new_path": "src/__tests__/components/Sidebar.test.tsx",
"diff": "@@ -35,12 +35,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('dashboard.label')\n+ expect(listItems.at(1).text().trim()).toEqual('dashboard.label')\n})\nit('should be active when the current path is /', () => {\n@@ -71,12 +66,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('patients.label')\n+ expect(listItems.at(2).text().trim()).toEqual('patients.label')\n})\nit('should render the new_patient link', () => {\n@@ -84,12 +74,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(3)\n- .text()\n- .trim(),\n- ).toEqual('patients.newPatient')\n+ expect(listItems.at(3).text().trim()).toEqual('patients.newPatient')\n})\nit('should render the patients_list link', () => {\n@@ -97,12 +82,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('patients.patientsList')\n+ expect(listItems.at(4).text().trim()).toEqual('patients.patientsList')\n})\nit('main patients link should be active when the current path is /patients', () => {\n@@ -175,12 +155,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(3)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.label')\n+ expect(listItems.at(3).text().trim()).toEqual('scheduling.label')\n})\nit('should render the new appointment link', () => {\n@@ -188,12 +163,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.appointments.new')\n+ expect(listItems.at(4).text().trim()).toEqual('scheduling.appointments.new')\n})\nit('should render the appointments schedule link', () => {\n@@ -201,12 +171,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(5)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.appointments.schedule')\n+ expect(listItems.at(5).text().trim()).toEqual('scheduling.appointments.schedule')\n})\nit('main scheduling link should be active when the current path is /appointments', () => {\n@@ -279,12 +244,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('labs.label')\n+ expect(listItems.at(4).text().trim()).toEqual('labs.label')\n})\nit('should render the new labs request link', () => {\n@@ -292,12 +252,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(5)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.new')\n+ expect(listItems.at(5).text().trim()).toEqual('labs.requests.new')\n})\nit('should render the labs list link', () => {\n@@ -305,12 +260,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(6)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.label')\n+ expect(listItems.at(6).text().trim()).toEqual('labs.requests.label')\n})\nit('main labs link should be active when the current path is /labs', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/Labs.test.tsx",
"new_path": "src/__tests__/labs/Labs.test.tsx",
"diff": "+import '../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { MemoryRouter } from 'react-router'\n+import { Provider } from 'react-redux'\n+import thunk from 'redux-thunk'\n+import configureMockStore from 'redux-mock-store'\n+\n+import { act } from 'react-dom/test-utils'\n+import Labs from 'labs/Labs'\n+import NewLabRequest from 'labs/requests/NewLabRequest'\n+import Permissions from 'model/Permissions'\n+import ViewLab from 'labs/ViewLab'\n+import LabRepository from 'clients/db/LabRepository'\n+import Lab from 'model/Lab'\n+import Patient from 'model/Patient'\n+import PatientRepository from 'clients/db/PatientRepository'\n+\n+const mockStore = configureMockStore([thunk])\n+\ndescribe('Labs', () => {\n- it('should render the routes', () => {})\n+ jest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\n+ jest\n+ .spyOn(LabRepository, 'find')\n+ .mockResolvedValue({ id: '1234', requestedOn: new Date().toISOString() } as Lab)\n+ jest\n+ .spyOn(PatientRepository, 'find')\n+ .mockResolvedValue({ id: '12345', fullName: 'test test' } as Patient)\n+\n+ describe('routing', () => {\n+ describe('/labs/new', () => {\n+ it('should render the new lab request screen when /labs/new is accessed', () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.RequestLab] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs/new']}>\n+ <Labs />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(NewLabRequest)).toHaveLength(1)\n+ })\n+\n+ it('should not navigate to /labs/new if the user does not have RequestLab permissions', () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs/new']}>\n+ <Labs />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(NewLabRequest)).toHaveLength(0)\n+ })\n+ })\n+\n+ describe('/labs/:id', () => {\n+ it('should render the view lab screen when /labs/:id is accessed', async () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.ViewLab] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ let wrapper: any\n+\n+ await act(async () => {\n+ wrapper = await mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs/1234']}>\n+ <Labs />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewLab)).toHaveLength(1)\n+ })\n+ })\n+\n+ it('should not navigate to /labs/:id if the user does not have ViewLab permissions', async () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = await mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/labs/1234']}>\n+ <Labs />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewLab)).toHaveLength(0)\n+ })\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLab.test.tsx",
"new_path": "src/__tests__/labs/ViewLab.test.tsx",
"diff": "@@ -84,57 +84,27 @@ describe('View Labs', () => {\nconst expectedLab = { ...mockLab } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst forPatientDiv = wrapper.find('.for-patient')\n- expect(\n- forPatientDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.for')\n+ expect(forPatientDiv.find('h4').text().trim()).toEqual('labs.lab.for')\n- expect(\n- forPatientDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(mockPatient.fullName)\n+ expect(forPatientDiv.find('h5').text().trim()).toEqual(mockPatient.fullName)\n})\nit('should display the lab type for type', async () => {\nconst expectedLab = { ...mockLab, type: 'expected type' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labTypeDiv = wrapper.find('.lab-type')\n- expect(\n- labTypeDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.type')\n+ expect(labTypeDiv.find('h4').text().trim()).toEqual('labs.lab.type')\n- expect(\n- labTypeDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.type)\n+ expect(labTypeDiv.find('h5').text().trim()).toEqual(expectedLab.type)\n})\nit('should display the requested on date', async () => {\nconst expectedLab = { ...mockLab, requestedOn: '2020-03-30T04:43:20.102Z' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst requestedOnDiv = wrapper.find('.requested-on')\n- expect(\n- requestedOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.requestedOn')\n+ expect(requestedOnDiv.find('h4').text().trim()).toEqual('labs.lab.requestedOn')\n- expect(\n- requestedOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual('2020-03-29 11:43 PM')\n+ expect(requestedOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:43 PM')\n})\nit('should not display the completed date if the lab is not completed', async () => {\n@@ -178,20 +148,13 @@ describe('View Labs', () => {\nexpect(notesTextField.prop('value')).toEqual(expectedLab.notes)\n})\n- it('should display an update button if the lab is in a requested state', async () => {})\n-\ndescribe('requested lab request', () => {\nit('should display a warning badge if the status is requested', async () => {\nconst expectedLab = { ...mockLab, status: 'requested' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('warning')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -207,26 +170,11 @@ describe('View Labs', () => {\n])\nconst buttons = wrapper.find(Button)\n- expect(\n- buttons\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual('actions.update')\n+ expect(buttons.at(0).text().trim()).toEqual('actions.update')\n- expect(\n- buttons\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.complete')\n+ expect(buttons.at(1).text().trim()).toEqual('labs.requests.complete')\n- expect(\n- buttons\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.cancel')\n+ expect(buttons.at(2).text().trim()).toEqual('labs.requests.cancel')\n})\n})\n@@ -237,12 +185,7 @@ describe('View Labs', () => {\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('danger')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -257,19 +200,9 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst canceledOnDiv = wrapper.find('.canceled-on')\n- expect(\n- canceledOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.canceledOn')\n+ expect(canceledOnDiv.find('h4').text().trim()).toEqual('labs.lab.canceledOn')\n- expect(\n- canceledOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual('2020-03-29 11:45 PM')\n+ expect(canceledOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:45 PM')\n})\nit('should not display update, complete, and cancel button if the lab is canceled', async () => {\n@@ -301,12 +234,7 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('primary')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -321,19 +249,9 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst completedOnDiv = wrapper.find('.completed-on')\n- expect(\n- completedOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.completedOn')\n-\n- expect(\n- completedOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual('2020-03-29 11:44 PM')\n+ expect(completedOnDiv.find('h4').text().trim()).toEqual('labs.lab.completedOn')\n+\n+ expect(completedOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:44 PM')\n})\nit('should not display update, complete, and cancel buttons if the lab is completed', async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -131,47 +131,17 @@ describe('View Labs', () => {\nexpect(table).toBeDefined()\nexpect(tableHeader).toBeDefined()\nexpect(tableBody).toBeDefined()\n- expect(\n- tableColumnHeaders\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.type')\n-\n- expect(\n- tableColumnHeaders\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.requestedOn')\n-\n- expect(\n- tableColumnHeaders\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n-\n- expect(\n- tableDataColumns\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.type)\n-\n- expect(\n- tableDataColumns\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('2020-03-29 11:43 PM')\n-\n- expect(\n- tableDataColumns\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.status)\n+ expect(tableColumnHeaders.at(0).text().trim()).toEqual('labs.lab.type')\n+\n+ expect(tableColumnHeaders.at(1).text().trim()).toEqual('labs.lab.requestedOn')\n+\n+ expect(tableColumnHeaders.at(2).text().trim()).toEqual('labs.lab.status')\n+\n+ expect(tableDataColumns.at(0).text().trim()).toEqual(expectedLab.type)\n+\n+ expect(tableDataColumns.at(1).text().trim()).toEqual('2020-03-29 11:43 PM')\n+\n+ expect(tableDataColumns.at(2).text().trim()).toEqual(expectedLab.status)\n})\nit('should navigate to the lab when the row is clicked', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"new_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"diff": "@@ -21,7 +21,6 @@ const mockStore = configureMockStore([thunk])\ndescribe('New Lab Request', () => {\ndescribe('title and breadcrumbs', () => {\n- let wrapper: ReactWrapper\nlet titleSpy: any\nconst history = createMemoryHistory()\n@@ -30,7 +29,7 @@ describe('New Lab Request', () => {\ntitleSpy = jest.spyOn(titleUtil, 'default')\nhistory.push('/labs/new')\n- wrapper = mount(\n+ mount(\n<Provider store={store}>\n<Router history={history}>\n<NewLabRequest />\n@@ -42,8 +41,6 @@ describe('New Lab Request', () => {\nit('should have New Lab Request as the title', () => {\nexpect(titleSpy).toHaveBeenCalledWith('labs.requests.new')\n})\n-\n- it('should render the breadcrumbs', () => {})\n})\ndescribe('form layout', () => {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(labs): adds test for lab related routes |
288,323 | 02.04.2020 23:51:56 | 18,000 | 94fa61aa2cff1f504cd415abde1e1c4483f2e3a4 | feat(labs): fix time related tests | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLab.test.tsx",
"new_path": "src/__tests__/labs/ViewLab.test.tsx",
"diff": "@@ -15,6 +15,7 @@ import * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport createMockStore from 'redux-mock-store'\nimport { Badge, Button, Alert } from '@hospitalrun/components'\nimport TextFieldWithLabelFormGroup from 'components/input/TextFieldWithLabelFormGroup'\n+import format from 'date-fns/format'\nimport * as titleUtil from '../../page-header/useTitle'\nimport ViewLab from '../../labs/ViewLab'\n@@ -104,7 +105,9 @@ describe('View Labs', () => {\nconst requestedOnDiv = wrapper.find('.requested-on')\nexpect(requestedOnDiv.find('h4').text().trim()).toEqual('labs.lab.requestedOn')\n- expect(requestedOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:43 PM')\n+ expect(requestedOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display the completed date if the lab is not completed', async () => {\n@@ -202,7 +205,9 @@ describe('View Labs', () => {\nexpect(canceledOnDiv.find('h4').text().trim()).toEqual('labs.lab.canceledOn')\n- expect(canceledOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:45 PM')\n+ expect(canceledOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display update, complete, and cancel button if the lab is canceled', async () => {\n@@ -251,7 +256,9 @@ describe('View Labs', () => {\nexpect(completedOnDiv.find('h4').text().trim()).toEqual('labs.lab.completedOn')\n- expect(completedOnDiv.find('h5').text().trim()).toEqual('2020-03-29 11:44 PM')\n+ expect(completedOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.completedOn as string), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display update, complete, and cancel buttons if the lab is completed', async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -11,6 +11,7 @@ import Permissions from 'model/Permissions'\nimport { act } from '@testing-library/react'\nimport LabRepository from 'clients/db/LabRepository'\nimport Lab from 'model/Lab'\n+import format from 'date-fns/format'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport * as titleUtil from '../../page-header/useTitle'\n@@ -139,7 +140,9 @@ describe('View Labs', () => {\nexpect(tableDataColumns.at(0).text().trim()).toEqual(expectedLab.type)\n- expect(tableDataColumns.at(1).text().trim()).toEqual('2020-03-29 11:43 PM')\n+ expect(tableDataColumns.at(1).text().trim()).toEqual(\n+ format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n+ )\nexpect(tableDataColumns.at(2).text().trim()).toEqual(expectedLab.status)\n})\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(labs): fix time related tests |
288,323 | 03.04.2020 08:13:46 | 18,000 | be799ac21453346ebed5c1b6dabb363cc22e13e5 | feat(labs): use different act import | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/Labs.test.tsx",
"new_path": "src/__tests__/labs/Labs.test.tsx",
"diff": "@@ -5,8 +5,7 @@ import { MemoryRouter } from 'react-router'\nimport { Provider } from 'react-redux'\nimport thunk from 'redux-thunk'\nimport configureMockStore from 'redux-mock-store'\n-\n-import { act } from 'react-dom/test-utils'\n+import { act } from '@testing-library/react'\nimport Labs from 'labs/Labs'\nimport NewLabRequest from 'labs/requests/NewLabRequest'\nimport Permissions from 'model/Permissions'\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(labs): use different act import |
288,381 | 04.04.2020 18:34:12 | -21,600 | ec5d655650875024b0bba12d49bc0dfad4c670ab | feat(patient): add appointment button | [
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -32,6 +32,9 @@ export default {\nnew: 'New Related Person',\nrelationshipType: 'Relationship Type',\n},\n+ appointments: {\n+ new: 'Add Appointment',\n+ },\nallergies: {\nlabel: 'Allergies',\nnew: 'Add Allergy',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/appointments/AppointmentsList.tsx",
"new_path": "src/patients/appointments/AppointmentsList.tsx",
"diff": "@@ -54,6 +54,20 @@ const AppointmentsList = (props: Props) => {\nreturn (\n<Container>\n+ <div className=\"row\">\n+ <div className=\"col-md-12 d-flex justify-content-end\">\n+ <Button\n+ outlined\n+ color=\"success\"\n+ icon=\"add\"\n+ iconLocation=\"left\"\n+ onClick={() => history.push('/appointments/new')}\n+ >\n+ {t('patient.appointments.new')}\n+ </Button>\n+ </div>\n+ </div>\n+ <br />\n<form className=\"form-inline\" onSubmit={onSearchFormSubmit}>\n<div className=\"input-group\" style={{ width: '100%' }}>\n<TextInput\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patient): add appointment button |
288,323 | 05.04.2020 20:01:03 | 18,000 | 7f856c84ca94808b4a85d6ae6abf6ecde1351d77 | feat: work in progress paging and sorting | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/Sort.ts",
"diff": "+export default interface Sort {\n+ field: string\n+ direction: 'asc' | 'desc'\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/LabRepository.ts",
"new_path": "src/clients/db/LabRepository.ts",
"diff": "@@ -2,6 +2,10 @@ import Lab from 'model/Lab'\nimport Repository from './Repository'\nimport { labs } from '../../config/pouchdb'\n+labs.createIndex({\n+ index: { fields: ['requestedOn'] },\n+})\n+\nexport class LabRepository extends Repository<Lab> {\nconstructor() {\nsuper(labs)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/db/Page.ts",
"diff": "+export default class Page<T> {\n+ /** the content for this page */\n+ content: T[]\n+\n+ /** the total number of elements that match the search */\n+ totalElements: number\n+\n+ /** the size of the current page */\n+ size: number\n+\n+ /** the current page number */\n+ number: number\n+\n+ getNextPage?: () => Promise<Page<T>>\n+\n+ getPreviousPage?: () => Promise<Page<T>>\n+\n+ constructor(content: T[], totalElements: number, size: number, number: number) {\n+ this.content = content\n+ this.totalElements = totalElements\n+ this.size = size\n+ this.number = number\n+ }\n+\n+ getContent(): T[] {\n+ return this.content\n+ }\n+\n+ getTotalElements(): number {\n+ return this.totalElements\n+ }\n+\n+ getSize(): number {\n+ return this.size\n+ }\n+\n+ getNumber(): number {\n+ return this.number\n+ }\n+\n+ hasNext(): boolean {\n+ return this.getNextPage !== undefined\n+ }\n+\n+ hasPrevious(): boolean {\n+ return this.getPreviousPage !== undefined\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/db/PageRequest.ts",
"diff": "+export default interface PageRequest {\n+ /** the page number requested */\n+ number: number\n+ /** the size of the pages */\n+ size: number\n+\n+ startKey?: string\n+\n+ previousStartKeys?: string[]\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport { v4 as uuidv4 } from 'uuid'\nimport AbstractDBModel from '../../model/AbstractDBModel'\n-\n-function mapRow(row: any): any {\n- const { value, doc } = row\n- const { id, _rev, _id, rev, ...restOfDoc } = doc\n- return {\n- id: _id,\n- rev: value.rev,\n- ...restOfDoc,\n- }\n-}\n+import PageRequest from './PageRequest'\n+import Page from './Page'\n+import SortRequest, { Unsorted } from './SortRequest'\nfunction mapDocument(document: any): any {\nconst { _id, _rev, ...values } = document\n@@ -33,17 +26,106 @@ export default class Repository<T extends AbstractDBModel> {\nreturn mapDocument(document)\n}\n- async search(criteria: any): Promise<T[]> {\n- const response = await this.db.find(criteria)\n- return response.docs.map(mapDocument)\n+ async findAll(sort = Unsorted): Promise<T[]> {\n+ const selector = {\n+ _id: { $gt: null },\n}\n- async findAll(): Promise<T[]> {\n- const allDocs = await this.db.allDocs({\n- include_docs: true,\n+ return this.search({ selector }, sort)\n+ }\n+\n+ async pagedFindAll(pageRequest: PageRequest, sortRequest = Unsorted): Promise<Page<T>> {\n+ return this.pagedSearch(\n+ { selector: { _id: { $gt: pageRequest?.startKey } } },\n+ pageRequest,\n+ sortRequest,\n+ )\n+ }\n+\n+ async search(criteria: any, sort: SortRequest = Unsorted): Promise<T[]> {\n+ // hack to get around the requirement that any sorted field must be in the selector list\n+ sort.sorts.forEach((s) => {\n+ criteria.selector[s.field] = { $gt: null }\n})\n+ const allCriteria = {\n+ ...criteria,\n+ sort: sort.sorts.map((s) => ({ [s.field]: s.direction })),\n+ }\n+ const response = await this.db.find(allCriteria)\n+ return response.docs.map(mapDocument)\n+ }\n+\n+ async pagedSearch(\n+ criteria: any,\n+ pageRequest: PageRequest,\n+ sortRequest = Unsorted,\n+ ): Promise<Page<T>> {\n+ // eslint-disable-next-line\n+ criteria.selector._id = { $gt: pageRequest?.startKey }\n+ criteria.selector.requestedOn = { $gt: null }\n+ const allCriteria = {\n+ ...criteria,\n+ limit: pageRequest?.size,\n+ // if the page request has a start key included, then do not use skip due to its performance drawbacks\n+ // documented here: https://pouchdb.com/2014/04/14/pagination-strategies-with-pouchdb.html\n+ // if the start key was provided, make the skip 1. This will get the next document after the one with the given id defined\n+ // by the start key\n+ skip: pageRequest && !pageRequest.startKey ? pageRequest.size * pageRequest.number : 1,\n+ sort: sortRequest.sorts.length > 0 ? sortRequest.sorts.map((s) => s.field) : undefined,\n+ }\n+\n+ const info = await this.db.allDocs({ limit: 0 })\n+ const result = await this.db.find(allCriteria)\n+\n+ const rows = result.docs.map(mapDocument)\n+ const page = new Page<T>(rows, info.total_rows, rows.length, pageRequest.number)\n+\n+ const lastPageNumber =\n+ Math.floor(info.total_rows / pageRequest.size) + (info.total_rows % pageRequest.size)\n+\n+ // if it's not the last page, calculate the next page\n+ if (lastPageNumber !== pageRequest.number + 1) {\n+ // add the current start key to the previous start keys list\n+ // this is to keep track of the previous start key in order to do \"linked list paging\"\n+ // for performance reasons\n+ // the current page's start key will become the previous start key\n+ const previousStartKeys = pageRequest.previousStartKeys || []\n+ if (pageRequest.startKey) {\n+ previousStartKeys.push(pageRequest.startKey)\n+ }\n+\n+ page.getNextPage = async () =>\n+ this.pagedSearch(\n+ criteria,\n+ {\n+ size: pageRequest.size,\n+ // the start key is the last row returned on the current page\n+ startKey: rows[rows.length - 1].id,\n+ previousStartKeys,\n+ number: pageRequest.number + 1,\n+ },\n+ sortRequest,\n+ ) as Promise<Page<T>>\n+ }\n+\n+ // if it's not the first page, calculate the previous page\n+ if (pageRequest.number !== 0) {\n+ // pop a start key off the list to get the previous start key\n+ const previousStartKey = pageRequest.previousStartKeys?.pop()\n+ page.getPreviousPage = async () =>\n+ this.pagedSearch(\n+ criteria,\n+ {\n+ size: pageRequest.size,\n+ number: pageRequest.number - 1,\n+ startKey: previousStartKey,\n+ previousStartKeys: pageRequest.previousStartKeys,\n+ },\n+ sortRequest,\n+ ) as Promise<Page<T>>\n+ }\n- return allDocs.rows.map(mapRow)\n+ return page\n}\nasync save(entity: T): Promise<T> {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/db/SortRequest.ts",
"diff": "+import Sort from 'clients/Sort'\n+\n+export default interface SortRequest {\n+ sorts: Sort[]\n+}\n+\n+export const Unsorted: SortRequest = { sorts: [] }\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat: work in progress paging and sorting |
288,323 | 05.04.2020 20:41:11 | 18,000 | a1569b181845a8d0543d4147d65ce00cbb799fc7 | feat: remove paging stuff | [
{
"change_type": "DELETE",
"old_path": "src/clients/db/Page.ts",
"new_path": null,
"diff": "-export default class Page<T> {\n- /** the content for this page */\n- content: T[]\n-\n- /** the total number of elements that match the search */\n- totalElements: number\n-\n- /** the size of the current page */\n- size: number\n-\n- /** the current page number */\n- number: number\n-\n- getNextPage?: () => Promise<Page<T>>\n-\n- getPreviousPage?: () => Promise<Page<T>>\n-\n- constructor(content: T[], totalElements: number, size: number, number: number) {\n- this.content = content\n- this.totalElements = totalElements\n- this.size = size\n- this.number = number\n- }\n-\n- getContent(): T[] {\n- return this.content\n- }\n-\n- getTotalElements(): number {\n- return this.totalElements\n- }\n-\n- getSize(): number {\n- return this.size\n- }\n-\n- getNumber(): number {\n- return this.number\n- }\n-\n- hasNext(): boolean {\n- return this.getNextPage !== undefined\n- }\n-\n- hasPrevious(): boolean {\n- return this.getPreviousPage !== undefined\n- }\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": null,
"diff": "-export default interface PageRequest {\n- /** the page number requested */\n- number: number\n- /** the size of the pages */\n- size: number\n-\n- startKey?: string\n-\n- previousStartKeys?: string[]\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport { v4 as uuidv4 } from 'uuid'\nimport AbstractDBModel from '../../model/AbstractDBModel'\n-import PageRequest from './PageRequest'\n-import Page from './Page'\nimport SortRequest, { Unsorted } from './SortRequest'\nfunction mapDocument(document: any): any {\n@@ -34,14 +32,6 @@ export default class Repository<T extends AbstractDBModel> {\nreturn this.search({ selector }, sort)\n}\n- async pagedFindAll(pageRequest: PageRequest, sortRequest = Unsorted): Promise<Page<T>> {\n- return this.pagedSearch(\n- { selector: { _id: { $gt: pageRequest?.startKey } } },\n- pageRequest,\n- sortRequest,\n- )\n- }\n-\nasync search(criteria: any, sort: SortRequest = Unsorted): Promise<T[]> {\n// hack to get around the requirement that any sorted field must be in the selector list\nsort.sorts.forEach((s) => {\n@@ -55,79 +45,6 @@ export default class Repository<T extends AbstractDBModel> {\nreturn response.docs.map(mapDocument)\n}\n- async pagedSearch(\n- criteria: any,\n- pageRequest: PageRequest,\n- sortRequest = Unsorted,\n- ): Promise<Page<T>> {\n- // eslint-disable-next-line\n- criteria.selector._id = { $gt: pageRequest?.startKey }\n- criteria.selector.requestedOn = { $gt: null }\n- const allCriteria = {\n- ...criteria,\n- limit: pageRequest?.size,\n- // if the page request has a start key included, then do not use skip due to its performance drawbacks\n- // documented here: https://pouchdb.com/2014/04/14/pagination-strategies-with-pouchdb.html\n- // if the start key was provided, make the skip 1. This will get the next document after the one with the given id defined\n- // by the start key\n- skip: pageRequest && !pageRequest.startKey ? pageRequest.size * pageRequest.number : 1,\n- sort: sortRequest.sorts.length > 0 ? sortRequest.sorts.map((s) => s.field) : undefined,\n- }\n-\n- const info = await this.db.allDocs({ limit: 0 })\n- const result = await this.db.find(allCriteria)\n-\n- const rows = result.docs.map(mapDocument)\n- const page = new Page<T>(rows, info.total_rows, rows.length, pageRequest.number)\n-\n- const lastPageNumber =\n- Math.floor(info.total_rows / pageRequest.size) + (info.total_rows % pageRequest.size)\n-\n- // if it's not the last page, calculate the next page\n- if (lastPageNumber !== pageRequest.number + 1) {\n- // add the current start key to the previous start keys list\n- // this is to keep track of the previous start key in order to do \"linked list paging\"\n- // for performance reasons\n- // the current page's start key will become the previous start key\n- const previousStartKeys = pageRequest.previousStartKeys || []\n- if (pageRequest.startKey) {\n- previousStartKeys.push(pageRequest.startKey)\n- }\n-\n- page.getNextPage = async () =>\n- this.pagedSearch(\n- criteria,\n- {\n- size: pageRequest.size,\n- // the start key is the last row returned on the current page\n- startKey: rows[rows.length - 1].id,\n- previousStartKeys,\n- number: pageRequest.number + 1,\n- },\n- sortRequest,\n- ) as Promise<Page<T>>\n- }\n-\n- // if it's not the first page, calculate the previous page\n- if (pageRequest.number !== 0) {\n- // pop a start key off the list to get the previous start key\n- const previousStartKey = pageRequest.previousStartKeys?.pop()\n- page.getPreviousPage = async () =>\n- this.pagedSearch(\n- criteria,\n- {\n- size: pageRequest.size,\n- number: pageRequest.number - 1,\n- startKey: previousStartKey,\n- previousStartKeys: pageRequest.previousStartKeys,\n- },\n- sortRequest,\n- ) as Promise<Page<T>>\n- }\n-\n- return page\n- }\n-\nasync save(entity: T): Promise<T> {\nconst currentTime = new Date().toISOString()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat: remove paging stuff |
288,381 | 06.04.2020 15:19:02 | -21,600 | 1704ccb0ecdf0678038aa7e6c06c222f60ed501f | feat(patient): change newAppointment button label and add tests | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/patients/appointments/NewAppointment.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { createMemoryHistory } from 'history'\n+import configureMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import Patient from 'model/Patient'\n+import Permissions from 'model/Permissions'\n+import { Router } from 'react-router'\n+import { Provider } from 'react-redux'\n+import AppointmentsList from 'patients/appointments/AppointmentsList'\n+import * as components from '@hospitalrun/components'\n+import { act } from 'react-dom/test-utils'\n+import PatientRepository from 'clients/db/PatientRepository'\n+\n+const expectedPatient = {\n+ id: '123',\n+} as Patient\n+\n+const mockStore = configureMockStore([thunk])\n+const history = createMemoryHistory()\n+\n+let store: any\n+\n+const setup = (patient = expectedPatient) => {\n+ store = mockStore({ patient })\n+ const wrapper = mount(\n+ <Router history={history}>\n+ <Provider store={store}>\n+ <AppointmentsList patientId={patient.id} />\n+ </Provider>\n+ </Router>,\n+ )\n+\n+ return wrapper\n+}\n+\n+describe('AppointmentsList', () => {\n+ describe('add new appointment button', () => {\n+ beforeEach(() => {\n+ jest.resetAllMocks()\n+ jest.spyOn(PatientRepository, 'saveOrUpdate')\n+ })\n+\n+ it('should render a new appointment button', () => {\n+ const wrapper = setup()\n+\n+ const addNewAppointmentButton = wrapper.find(components.Button)\n+ expect(addNewAppointmentButton).toHaveLength(1)\n+ expect(addNewAppointmentButton.text().trim()).toEqual('scheduling.appointments.new')\n+ })\n+\n+ it('should navigate to new appointment page', () => {\n+ const wrapper = setup()\n+\n+ act(() => {\n+ wrapper.find(components.Button).prop('onClick')()\n+ })\n+ wrapper.update()\n+\n+ expect(history.location.pathname).toEqual('/appointments/new')\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/appointments/AppointmentsList.tsx",
"new_path": "src/patients/appointments/AppointmentsList.tsx",
"diff": "@@ -57,13 +57,13 @@ const AppointmentsList = (props: Props) => {\n<div className=\"row\">\n<div className=\"col-md-12 d-flex justify-content-end\">\n<Button\n+ key=\"newAppointmentButton\"\noutlined\ncolor=\"success\"\n- icon=\"add\"\n- iconLocation=\"left\"\n+ icon=\"appointment-add\"\nonClick={() => history.push('/appointments/new')}\n>\n- {t('patient.appointments.new')}\n+ {t('scheduling.appointments.new')}\n</Button>\n</div>\n</div>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patient): change newAppointment button label and add tests |
288,323 | 06.04.2020 17:02:24 | 18,000 | 89430f79c25e793171d5eff73ced0338b6fbf1c4 | feat(patients): refactor patient list to use table | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/Patients.test.tsx",
"new_path": "src/__tests__/patients/list/Patients.test.tsx",
"diff": "import '../../../__mocks__/matchMediaMock'\nimport React from 'react'\nimport { mount } from 'enzyme'\n-import { TextInput, Button, Spinner, ListItem } from '@hospitalrun/components'\n+import { TextInput, Button, Spinner } from '@hospitalrun/components'\nimport { MemoryRouter } from 'react-router-dom'\nimport { Provider } from 'react-redux'\nimport thunk from 'redux-thunk'\n@@ -9,6 +9,7 @@ import configureStore from 'redux-mock-store'\nimport { mocked } from 'ts-jest/utils'\nimport { act } from 'react-dom/test-utils'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\n+import format from 'date-fns/format'\nimport Patients from '../../../patients/list/Patients'\nimport PatientRepository from '../../../clients/db/PatientRepository'\nimport * as patientSlice from '../../../patients/patients-slice'\n@@ -17,7 +18,17 @@ const middlewares = [thunk]\nconst mockStore = configureStore(middlewares)\ndescribe('Patients', () => {\n- const patients = [{ id: '123', fullName: 'test test', code: 'P12345' }]\n+ const patients = [\n+ {\n+ id: '123',\n+ fullName: 'test test',\n+ givenName: 'test',\n+ familyName: 'test',\n+ code: 'P12345',\n+ sex: 'male',\n+ dateOfBirth: new Date().toISOString(),\n+ },\n+ ]\nconst mockedPatientRepository = mocked(PatientRepository, true)\nconst setup = (isLoading?: boolean) => {\n@@ -62,12 +73,29 @@ describe('Patients', () => {\nexpect(wrapper.find(Spinner)).toHaveLength(1)\n})\n- it('should render a list of patients', () => {\n+ it('should render a table of patients', () => {\nconst wrapper = setup()\n- const patientListItems = wrapper.find(ListItem)\n- expect(patientListItems).toHaveLength(1)\n- expect(patientListItems.at(0).text()).toEqual(`${patients[0].fullName} (${patients[0].code})`)\n+ const table = wrapper.find('table')\n+ const tableHeaders = table.find('th')\n+ const tableColumns = table.find('td')\n+\n+ expect(table).toHaveLength(1)\n+ expect(tableHeaders).toHaveLength(5)\n+ expect(tableColumns).toHaveLength(5)\n+ expect(tableHeaders.at(0).text()).toEqual('patient.code')\n+ expect(tableHeaders.at(1).text()).toEqual('patient.givenName')\n+ expect(tableHeaders.at(2).text()).toEqual('patient.familyName')\n+ expect(tableHeaders.at(3).text()).toEqual('patient.sex')\n+ expect(tableHeaders.at(4).text()).toEqual('patient.dateOfBirth')\n+\n+ expect(tableColumns.at(0).text()).toEqual(patients[0].code)\n+ expect(tableColumns.at(1).text()).toEqual(patients[0].givenName)\n+ expect(tableColumns.at(2).text()).toEqual(patients[0].familyName)\n+ expect(tableColumns.at(3).text()).toEqual(patients[0].sex)\n+ expect(tableColumns.at(4).text()).toEqual(\n+ format(new Date(patients[0].dateOfBirth), 'yyyy-MM-dd'),\n+ )\n})\nit('should add a \"New Patient\" button to the button tool bar', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "export default {\npatient: {\n+ code: 'Code',\nfirstName: 'First Name',\nlastName: 'Last Name',\nsuffix: 'Suffix',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/Patients.tsx",
"new_path": "src/patients/list/Patients.tsx",
"diff": "@@ -2,17 +2,9 @@ import React, { useEffect, useState } from 'react'\nimport { useSelector, useDispatch } from 'react-redux'\nimport { useHistory } from 'react-router'\nimport { useTranslation } from 'react-i18next'\n-import {\n- Spinner,\n- Button,\n- List,\n- ListItem,\n- Container,\n- Row,\n- TextInput,\n- Column,\n-} from '@hospitalrun/components'\n+import { Spinner, Button, Container, Row, TextInput, Column } from '@hospitalrun/components'\nimport { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\n+import format from 'date-fns/format'\nimport { RootState } from '../../store'\nimport { fetchPatients, searchPatients } from '../patients-slice'\nimport useTitle from '../../page-header/useTitle'\n@@ -56,13 +48,28 @@ const Patients = () => {\n}\nconst list = (\n- <ul>\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light \">\n+ <tr>\n+ <th>{t('patient.code')}</th>\n+ <th>{t('patient.givenName')}</th>\n+ <th>{t('patient.familyName')}</th>\n+ <th>{t('patient.sex')}</th>\n+ <th>{t('patient.dateOfBirth')}</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n{patients.map((p) => (\n- <ListItem action key={p.id} onClick={() => history.push(`/patients/${p.id}`)}>\n- {p.fullName} ({p.code})\n- </ListItem>\n+ <tr key={p.id} onClick={() => history.push(`/patients/${p.id}`)}>\n+ <td>{p.code}</td>\n+ <td>{p.givenName}</td>\n+ <td>{p.familyName}</td>\n+ <td>{p.sex}</td>\n+ <td>{p.dateOfBirth ? format(new Date(p.dateOfBirth), 'yyyy-MM-dd') : ''}</td>\n+ </tr>\n))}\n- </ul>\n+ </tbody>\n+ </table>\n)\nconst onSearchBoxChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n@@ -95,11 +102,7 @@ const Patients = () => {\n</Row>\n</form>\n- <Row>\n- <List layout=\"flush\" style={{ width: '100%', marginTop: '10px', marginLeft: '-25px' }}>\n- {list}\n- </List>\n- </Row>\n+ <Row>{list}</Row>\n</Container>\n)\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): refactor patient list to use table (#1965) |
288,323 | 06.04.2020 18:56:34 | 18,000 | 6e08babcad9f25e830e53c9f301c60706562ab61 | feat(patients): adds ability to remove related person | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/related-persons/RelatedPersons.test.tsx",
"new_path": "src/__tests__/patients/related-persons/RelatedPersons.test.tsx",
"diff": "@@ -16,6 +16,8 @@ import { Provider } from 'react-redux'\nimport Permissions from 'model/Permissions'\nimport { mocked } from 'ts-jest/utils'\n+import RelatedPerson from 'model/RelatedPerson'\n+import { Button } from '@hospitalrun/components'\nimport * as patientSlice from '../../../patients/patient-slice'\nconst mockStore = configureMockStore([thunk])\n@@ -173,23 +175,29 @@ describe('Related Persons Tab', () => {\n})\n})\n- describe('List', () => {\n+ describe('Table', () => {\nconst patient = {\nid: '123',\nrev: '123',\n- relatedPersons: [{ patientId: '123', type: 'type' }],\n+ relatedPersons: [{ patientId: '123001', type: 'type' }],\n+ } as Patient\n+ const expectedRelatedPerson = {\n+ givenName: 'test',\n+ familyName: 'test',\n+ fullName: 'test test',\n+ id: '123001',\n} as Patient\nconst user = {\npermissions: [Permissions.WritePatients, Permissions.ReadPatients],\n}\n+ let patientSaveOrUpdateSpy: any\n+\nbeforeEach(async () => {\n+ patientSaveOrUpdateSpy = jest.spyOn(PatientRepository, 'saveOrUpdate')\njest.spyOn(PatientRepository, 'find')\n- mocked(PatientRepository.find).mockResolvedValue({\n- fullName: 'test test',\n- id: '123001',\n- } as Patient)\n+ mocked(PatientRepository.find).mockResolvedValue(expectedRelatedPerson)\nawait act(async () => {\nwrapper = await mount(\n@@ -204,20 +212,53 @@ describe('Related Persons Tab', () => {\n})\nit('should render a list of related persons with their full name being displayed', () => {\n- const list = wrapper.find(components.List)\n- const listItems = wrapper.find(components.ListItem)\n- expect(list).toHaveLength(1)\n- expect(listItems).toHaveLength(1)\n- expect(listItems.at(0).text()).toEqual('test test')\n+ const table = wrapper.find('table')\n+ const tableHeader = wrapper.find('thead')\n+ const tableHeaders = wrapper.find('th')\n+ const tableBody = wrapper.find('tbody')\n+ const tableData = wrapper.find('td')\n+ const deleteButton = tableData.at(3).find(Button)\n+ expect(table).toHaveLength(1)\n+ expect(tableHeader).toHaveLength(1)\n+ expect(tableBody).toHaveLength(1)\n+ expect(tableHeaders.at(0).text()).toEqual('patient.givenName')\n+ expect(tableHeaders.at(1).text()).toEqual('patient.familyName')\n+ expect(tableHeaders.at(2).text()).toEqual('patient.relatedPersons.relationshipType')\n+ expect(tableHeaders.at(3).text()).toEqual('actions.label')\n+ expect(tableData.at(0).text()).toEqual(expectedRelatedPerson.givenName)\n+ expect(tableData.at(1).text()).toEqual(expectedRelatedPerson.familyName)\n+ expect(tableData.at(2).text()).toEqual((patient.relatedPersons as RelatedPerson[])[0].type)\n+ expect(deleteButton).toHaveLength(1)\n+ expect(deleteButton.text().trim()).toEqual('actions.delete')\n+ expect(deleteButton.prop('color')).toEqual('danger')\n+ })\n+\n+ it('should remove the related person when the delete button is clicked', async () => {\n+ const eventPropagationSpy = jest.fn()\n+\n+ const table = wrapper.find('table')\n+ const tableBody = table.find('tbody')\n+ const tableData = tableBody.find('td')\n+ const deleteButton = tableData.at(3).find(Button)\n+\n+ await act(async () => {\n+ const onClick = deleteButton.prop('onClick')\n+ onClick({ stopPropagation: eventPropagationSpy })\n})\n+\n+ expect(eventPropagationSpy).toHaveBeenCalledTimes(1)\n+ expect(patientSaveOrUpdateSpy).toHaveBeenLastCalledWith({ ...patient, relatedPersons: [] })\n+ })\n+\nit('should navigate to related person patient profile on related person click', () => {\n- const list = wrapper.find(components.List)\n- const listItems = wrapper.find(components.ListItem)\n+ const table = wrapper.find('table')\n+ const tableBody = table.find('tbody')\n+ const row = tableBody.find('tr')\nact(() => {\n- ;(listItems.at(0).prop('onClick') as any)()\n+ const onClick = row.prop('onClick')\n+ onClick()\n})\n- expect(list).toHaveLength(1)\n- expect(listItems).toHaveLength(1)\n+\nexpect(history.location.pathname).toEqual('/patients/123001')\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/actions/index.ts",
"new_path": "src/locales/enUs/translations/actions/index.ts",
"diff": "export default {\nactions: {\n+ label: 'Actions',\nedit: 'Edit',\nsave: 'Save',\nupdate: 'Update',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/related-persons/RelatedPersonTab.tsx",
"new_path": "src/patients/related-persons/RelatedPersonTab.tsx",
"diff": "import React, { useState, useEffect } from 'react'\n-import { Button, Panel, List, ListItem, Alert, Spinner, Toast } from '@hospitalrun/components'\n+import { Button, Alert, Spinner, Toast } from '@hospitalrun/components'\nimport AddRelatedPersonModal from 'patients/related-persons/AddRelatedPersonModal'\nimport RelatedPerson from 'model/RelatedPerson'\nimport { useTranslation } from 'react-i18next'\n@@ -44,7 +44,7 @@ const RelatedPersonTab = (props: Props) => {\nawait Promise.all(\npatient.relatedPersons.map(async (person) => {\nconst fetchedRelatedPerson = await PatientRepository.find(person.patientId)\n- fetchedRelatedPersons.push(fetchedRelatedPerson)\n+ fetchedRelatedPersons.push({ ...fetchedRelatedPerson, type: person.type })\n}),\n)\n}\n@@ -88,6 +88,20 @@ const RelatedPersonTab = (props: Props) => {\ncloseNewRelatedPersonModal()\n}\n+ const onRelatedPersonDelete = (\n+ event: React.MouseEvent<HTMLButtonElement>,\n+ relatedPerson: Patient,\n+ ) => {\n+ event.stopPropagation()\n+ const patientToUpdate = { ...patient }\n+ const newRelatedPersons = patientToUpdate.relatedPersons?.filter(\n+ (r) => r.patientId !== relatedPerson.id,\n+ )\n+ patientToUpdate.relatedPersons = newRelatedPersons\n+\n+ dispatch(updatePatient(patientToUpdate))\n+ }\n+\nreturn (\n<div>\n<div className=\"row\">\n@@ -108,16 +122,36 @@ const RelatedPersonTab = (props: Props) => {\n<br />\n<div className=\"row\">\n<div className=\"col-md-12\">\n- <Panel title={t('patient.relatedPersons.label')} color=\"primary\" collapsible>\n{relatedPersons ? (\nrelatedPersons.length > 0 ? (\n- <List>\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light\">\n+ <tr>\n+ <th>{t('patient.givenName')}</th>\n+ <th>{t('patient.familyName')}</th>\n+ <th>{t('patient.relatedPersons.relationshipType')}</th>\n+ <th>{t('actions.label')}</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n{relatedPersons.map((r) => (\n- <ListItem action key={r.id} onClick={() => onRelatedPersonClick(r.id)}>\n- {r.fullName}\n- </ListItem>\n+ <tr key={r.id} onClick={() => onRelatedPersonClick(r.id)}>\n+ <td>{r.givenName}</td>\n+ <td>{r.familyName}</td>\n+ <td>{r.type}</td>\n+ <td>\n+ <Button\n+ icon=\"remove\"\n+ color=\"danger\"\n+ onClick={(e) => onRelatedPersonDelete(e, r)}\n+ >\n+ {t('actions.delete')}\n+ </Button>\n+ </td>\n+ </tr>\n))}\n- </List>\n+ </tbody>\n+ </table>\n) : (\n<Alert\ncolor=\"warning\"\n@@ -128,7 +162,6 @@ const RelatedPersonTab = (props: Props) => {\n) : (\n<Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\n)}\n- </Panel>\n</div>\n</div>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): adds ability to remove related person (#1968) |
288,315 | 06.04.2020 21:29:36 | 14,400 | 3ba741c0988165f8121c0025074e9eaaafadc577 | feat(patients): added live search to the patients search | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/hooks/debounce.spec.ts",
"diff": "+import { renderHook, act } from '@testing-library/react-hooks'\n+import useDebounce from 'hooks/debounce'\n+\n+describe('useDebounce', () => {\n+ beforeAll(() => jest.useFakeTimers())\n+\n+ afterAll(() => jest.useRealTimers())\n+\n+ it('should set the next value after the input value has not changed for the specified amount of time', () => {\n+ const initialValue = 'initialValue'\n+ const expectedValue = 'someValue'\n+ const debounceDelay = 500\n+\n+ let currentValue = initialValue\n+\n+ const { rerender, result } = renderHook(() => useDebounce(currentValue, debounceDelay))\n+\n+ currentValue = expectedValue\n+\n+ act(() => {\n+ rerender()\n+ jest.advanceTimersByTime(debounceDelay)\n+ })\n+\n+ expect(result.current).toBe(expectedValue)\n+ })\n+\n+ it('should not set a new value before the specified delay has elapsed', () => {\n+ const initialValue = 'initialValue'\n+ const nextValue = 'someValue'\n+ const debounceDelay = 500\n+\n+ let currentValue = initialValue\n+\n+ const { rerender, result } = renderHook(() => useDebounce(currentValue, debounceDelay))\n+\n+ currentValue = nextValue\n+\n+ act(() => {\n+ rerender()\n+ jest.advanceTimersByTime(debounceDelay - 1)\n+ })\n+\n+ expect(result.current).toBe(initialValue)\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/Patients.test.tsx",
"new_path": "src/__tests__/patients/list/Patients.test.tsx",
"diff": "import '../../../__mocks__/matchMediaMock'\nimport React from 'react'\nimport { mount } from 'enzyme'\n-import { TextInput, Button, Spinner } from '@hospitalrun/components'\n+import { TextInput, Spinner } from '@hospitalrun/components'\nimport { MemoryRouter } from 'react-router-dom'\nimport { Provider } from 'react-redux'\nimport thunk from 'redux-thunk'\n@@ -58,15 +58,6 @@ describe('Patients', () => {\njest.restoreAllMocks()\n})\n- it('should render a search input with button', () => {\n- const wrapper = setup()\n- const searchInput = wrapper.find(TextInput)\n- const searchButton = wrapper.find(Button)\n- expect(searchInput).toHaveLength(1)\n- expect(searchInput.prop('placeholder')).toEqual('actions.search')\n- expect(searchButton.text().trim()).toEqual('actions.search')\n- })\n-\nit('should render a loading bar if it is loading', () => {\nconst wrapper = setup(true)\n@@ -111,10 +102,15 @@ describe('Patients', () => {\n})\ndescribe('search functionality', () => {\n- it('should call the searchPatients() action with the correct data', () => {\n+ beforeEach(() => jest.useFakeTimers())\n+\n+ afterEach(() => jest.useRealTimers())\n+\n+ it('should search for patients after the search text has not changed for 500 milliseconds', () => {\nconst searchPatientsSpy = jest.spyOn(patientSlice, 'searchPatients')\n- const expectedSearchText = 'search text'\nconst wrapper = setup()\n+ searchPatientsSpy.mockClear()\n+ const expectedSearchText = 'search text'\nact(() => {\n;(wrapper.find(TextInput).prop('onChange') as any)({\n@@ -127,14 +123,8 @@ describe('Patients', () => {\n} as React.ChangeEvent<HTMLInputElement>)\n})\n- wrapper.update()\n-\nact(() => {\n- ;(wrapper.find(Button).prop('onClick') as any)({\n- preventDefault(): void {\n- // noop\n- },\n- } as React.MouseEvent<HTMLButtonElement>)\n+ jest.advanceTimersByTime(500)\n})\nwrapper.update()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/hooks/debounce.ts",
"diff": "+import { useState, useEffect } from 'react'\n+\n+export default function <T>(value: T, delayInMilliseconds: number): T {\n+ const [debouncedValue, setDebouncedValue] = useState(value)\n+\n+ useEffect(() => {\n+ const debounceHandler = setTimeout(() => setDebouncedValue(value), delayInMilliseconds)\n+\n+ return () => clearTimeout(debounceHandler)\n+ }, [value, delayInMilliseconds])\n+\n+ return debouncedValue\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/Patients.tsx",
"new_path": "src/patients/list/Patients.tsx",
"diff": "@@ -9,6 +9,7 @@ import { RootState } from '../../store'\nimport { fetchPatients, searchPatients } from '../patients-slice'\nimport useTitle from '../../page-header/useTitle'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\n+import useDebounce from '../../hooks/debounce'\nconst breadcrumbs = [{ i18nKey: 'patients.label', location: '/patients' }]\n@@ -35,6 +36,12 @@ const Patients = () => {\nconst [searchText, setSearchText] = useState<string>('')\n+ const debouncedSearchText = useDebounce(searchText, 500)\n+\n+ useEffect(() => {\n+ dispatch(searchPatients(debouncedSearchText))\n+ }, [dispatch, debouncedSearchText])\n+\nuseEffect(() => {\ndispatch(fetchPatients())\n@@ -43,21 +50,9 @@ const Patients = () => {\n}\n}, [dispatch, setButtonToolBar])\n- if (isLoading) {\n- return <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\n- }\n+ const loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\n- const list = (\n- <table className=\"table table-hover\">\n- <thead className=\"thead-light \">\n- <tr>\n- <th>{t('patient.code')}</th>\n- <th>{t('patient.givenName')}</th>\n- <th>{t('patient.familyName')}</th>\n- <th>{t('patient.sex')}</th>\n- <th>{t('patient.dateOfBirth')}</th>\n- </tr>\n- </thead>\n+ const listBody = (\n<tbody>\n{patients.map((p) => (\n<tr key={p.id} onClick={() => history.push(`/patients/${p.id}`)}>\n@@ -69,6 +64,20 @@ const Patients = () => {\n</tr>\n))}\n</tbody>\n+ )\n+\n+ const list = (\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light \">\n+ <tr>\n+ <th>{t('patient.code')}</th>\n+ <th>{t('patient.givenName')}</th>\n+ <th>{t('patient.familyName')}</th>\n+ <th>{t('patient.sex')}</th>\n+ <th>{t('patient.dateOfBirth')}</th>\n+ </tr>\n+ </thead>\n+ {isLoading ? loadingIndicator : listBody}\n</table>\n)\n@@ -76,16 +85,10 @@ const Patients = () => {\nsetSearchText(event.target.value)\n}\n- const onSearchFormSubmit = (event: React.FormEvent | React.MouseEvent) => {\n- event.preventDefault()\n- dispatch(searchPatients(searchText))\n- }\n-\nreturn (\n<Container>\n- <form className=\"form\" onSubmit={onSearchFormSubmit}>\n<Row>\n- <Column md={10}>\n+ <Column md={12}>\n<TextInput\nsize=\"lg\"\ntype=\"text\"\n@@ -94,13 +97,7 @@ const Patients = () => {\nplaceholder={t('actions.search')}\n/>\n</Column>\n- <Column md={2}>\n- <Button size=\"large\" onClick={onSearchFormSubmit}>\n- {t('actions.search')}\n- </Button>\n- </Column>\n</Row>\n- </form>\n<Row>{list}</Row>\n</Container>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): added live search to the patients search (#1970) |
288,381 | 07.04.2020 16:22:19 | -21,600 | af66ec68c5c34d87755205c3dfab3debce7bd393 | fix(patient): appointments list tests | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/appointments/NewAppointment.test.tsx",
"new_path": "src/__tests__/patients/appointments/NewAppointment.test.tsx",
"diff": "@@ -5,7 +5,6 @@ import { createMemoryHistory } from 'history'\nimport configureMockStore from 'redux-mock-store'\nimport thunk from 'redux-thunk'\nimport Patient from 'model/Patient'\n-import Permissions from 'model/Permissions'\nimport { Router } from 'react-router'\nimport { Provider } from 'react-redux'\nimport AppointmentsList from 'patients/appointments/AppointmentsList'\n@@ -16,14 +15,25 @@ import PatientRepository from 'clients/db/PatientRepository'\nconst expectedPatient = {\nid: '123',\n} as Patient\n+const expectedAppointments = [\n+ {\n+ id: '123',\n+ rev: '1',\n+ patientId: '1234',\n+ startDateTime: new Date().toISOString(),\n+ endDateTime: new Date().toISOString(),\n+ location: 'location',\n+ reason: 'reason',\n+ },\n+]\nconst mockStore = configureMockStore([thunk])\nconst history = createMemoryHistory()\nlet store: any\n-const setup = (patient = expectedPatient) => {\n- store = mockStore({ patient })\n+const setup = (patient = expectedPatient, appointments = expectedAppointments) => {\n+ store = mockStore({ patient, appointments: { appointments } })\nconst wrapper = mount(\n<Router history={history}>\n<Provider store={store}>\n@@ -45,7 +55,7 @@ describe('AppointmentsList', () => {\nit('should render a new appointment button', () => {\nconst wrapper = setup()\n- const addNewAppointmentButton = wrapper.find(components.Button)\n+ const addNewAppointmentButton = wrapper.find(components.Button).at(0)\nexpect(addNewAppointmentButton).toHaveLength(1)\nexpect(addNewAppointmentButton.text().trim()).toEqual('scheduling.appointments.new')\n})\n@@ -54,7 +64,10 @@ describe('AppointmentsList', () => {\nconst wrapper = setup()\nact(() => {\n- wrapper.find(components.Button).prop('onClick')()\n+ wrapper\n+ .find(components.Button)\n+ .at(0)\n+ .prop('onClick')()\n})\nwrapper.update()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(patient): appointments list tests |
288,323 | 08.04.2020 22:58:13 | 18,000 | 3ce732a99a9952e082febd811a1205260682f1e2 | feat: fix tests for sorting | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/scheduling/appointments/Appointments.test.tsx",
"new_path": "src/__tests__/scheduling/appointments/Appointments.test.tsx",
"diff": "@@ -12,6 +12,8 @@ import PatientRepository from 'clients/db/PatientRepository'\nimport { mocked } from 'ts-jest/utils'\nimport Patient from 'model/Patient'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\n+import AppointmentRepository from 'clients/db/AppointmentRepository'\n+import Appointment from 'model/Appointment'\nimport * as titleUtil from '../../../page-header/useTitle'\ndescribe('Appointments', () => {\n@@ -25,9 +27,10 @@ describe('Appointments', () => {\nlocation: 'location',\nreason: 'reason',\n},\n- ]\n+ ] as Appointment[]\nconst setup = async () => {\n+ jest.spyOn(AppointmentRepository, 'findAll').mockResolvedValue(expectedAppointments)\njest.spyOn(PatientRepository, 'find')\nconst mockedPatientRepository = mocked(PatientRepository, true)\nmockedPatientRepository.find.mockResolvedValue({\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/LabRepository.ts",
"new_path": "src/clients/db/LabRepository.ts",
"diff": "@@ -2,13 +2,12 @@ import Lab from 'model/Lab'\nimport Repository from './Repository'\nimport { labs } from '../../config/pouchdb'\n-labs.createIndex({\n- index: { fields: ['requestedOn'] },\n-})\n-\nexport class LabRepository extends Repository<Lab> {\nconstructor() {\nsuper(labs)\n+ labs.createIndex({\n+ index: { fields: ['requestedOn'] },\n+ })\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -25,23 +25,24 @@ export default class Repository<T extends AbstractDBModel> {\n}\nasync findAll(sort = Unsorted): Promise<T[]> {\n- const selector = {\n+ const selector: any = {\n_id: { $gt: null },\n}\n- return this.search({ selector }, sort)\n- }\n-\n- async search(criteria: any, sort: SortRequest = Unsorted): Promise<T[]> {\n- // hack to get around the requirement that any sorted field must be in the selector list\nsort.sorts.forEach((s) => {\n- criteria.selector[s.field] = { $gt: null }\n+ selector[s.field] = { $gt: null }\n+ })\n+\n+ const result = await this.db.find({\n+ selector,\n+ sort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\n})\n- const allCriteria = {\n- ...criteria,\n- sort: sort.sorts.map((s) => ({ [s.field]: s.direction })),\n+\n+ return result.docs.map(mapDocument)\n}\n- const response = await this.db.find(allCriteria)\n+\n+ async search(criteria: any): Promise<T[]> {\n+ const response = await this.db.find(criteria)\nreturn response.docs.map(mapDocument)\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat: fix tests for sorting |
288,381 | 10.04.2020 13:58:12 | -21,600 | 648681b25adec1897eb5612c322ddcba95afa73f | refactor(patient): rename test and remove mock | [
{
"change_type": "RENAME",
"old_path": "src/__tests__/patients/appointments/NewAppointment.test.tsx",
"new_path": "src/__tests__/patients/appointments/AppointmentsList.test.tsx",
"diff": "@@ -47,11 +47,6 @@ const setup = (patient = expectedPatient, appointments = expectedAppointments) =\ndescribe('AppointmentsList', () => {\ndescribe('add new appointment button', () => {\n- beforeEach(() => {\n- jest.resetAllMocks()\n- jest.spyOn(PatientRepository, 'saveOrUpdate')\n- })\n-\nit('should render a new appointment button', () => {\nconst wrapper = setup()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(patient): rename test and remove mock |
288,323 | 10.04.2020 15:59:20 | 18,000 | 9fa3c416934547650f04ac83f8c8bad58adf423b | style: fix inconsistent lint issues | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -53,6 +53,7 @@ module.exports = {\n'no-nested-ternary': 'off',\n'import/no-unresolved': 'off',\n'import/extensions': ['error', 'never'],\n+ 'newline-per-chained-call': 'off',\ncurly: ['error', 'all'],\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Navbar.test.tsx",
"new_path": "src/__tests__/components/Navbar.test.tsx",
"diff": "@@ -25,34 +25,42 @@ describe('Navbar', () => {\ndescribe('header', () => {\nconst header = wrapper.find('.nav-header')\n+ const { children } = header.first().props() as any\n+\nit('should render a HospitalRun Navbar with the navbar header', () => {\n- expect(header.first().props().children.props.children).toEqual('HospitalRun')\n+ expect(children.props.children).toEqual('HospitalRun')\n})\nit('should navigate to / when the header is clicked', () => {\nact(() => {\n- header.first().props().onClick()\n+ const onClick = header.first().prop('onClick') as any\n+ onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/')\n})\n})\ndescribe('patients', () => {\nconst patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n+ const { children } = patientsLinkList.first().props() as any\n+\nit('should render a patients link list', () => {\nexpect(patientsLinkList.first().props().title).toEqual('patients.label')\n- expect(patientsLinkList.first().props().children[0].props.children).toEqual('actions.list')\n- expect(patientsLinkList.first().props().children[1].props.children).toEqual('actions.new')\n+ expect(children[0].props.children).toEqual('actions.list')\n+ expect(children[1].props.children).toEqual('actions.new')\n})\nit('should navigate to /patients when the list option is selected', () => {\nact(() => {\n- patientsLinkList.first().props().children[0].props.onClick()\n+ children[0].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/patients')\n})\nit('should navigate to /patients/new when the list option is selected', () => {\nact(() => {\n- patientsLinkList.first().props().children[1].props.onClick()\n+ children[1].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/patients/new')\n})\n})\n@@ -62,66 +70,74 @@ describe('Navbar', () => {\nit('should render a scheduling dropdown', () => {\nexpect(scheduleLinkList.first().props().title).toEqual('scheduling.label')\n- expect(scheduleLinkList.first().props().children[0].props.children).toEqual(\n- 'scheduling.appointments.label',\n- )\n- expect(scheduleLinkList.first().props().children[1].props.children).toEqual(\n- 'scheduling.appointments.new',\n- )\n+\n+ const children = scheduleLinkList.first().props().children as any[]\n+ const firstChild = children[0] as any\n+ const secondChild = children[1] as any\n+\n+ if (scheduleLinkList.first().props().children) {\n+ expect(firstChild.props.children).toEqual('scheduling.appointments.label')\n+ expect(secondChild.props.children).toEqual('scheduling.appointments.new')\n+ }\n})\nit('should navigate to to /appointments when the appointment list option is selected', () => {\n+ const children = scheduleLinkList.first().props().children as any[]\n+\nact(() => {\n- scheduleLinkList.first().props().children[0].props.onClick()\n+ children[0].props.onClick()\n})\nexpect(history.location.pathname).toEqual('/appointments')\n})\nit('should navigate to /appointments/new when the new appointment list option is selected', () => {\n+ const children = scheduleLinkList.first().props().children as any[]\n+\nact(() => {\n- scheduleLinkList.first().props().children[1].props.onClick()\n+ children[1].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/appointments/new')\n})\n})\ndescribe('labs', () => {\nconst labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n+ const { children } = labsLinkList.first().props() as any\nit('should render a labs dropdown', () => {\nexpect(labsLinkList.first().props().title).toEqual('labs.label')\n- expect(labsLinkList.first().props().children[0].props.children).toEqual('labs.label')\n- expect(labsLinkList.first().props().children[1].props.children).toEqual('labs.requests.new')\n+ expect(children[0].props.children).toEqual('labs.label')\n+ expect(children[1].props.children).toEqual('labs.requests.new')\n})\nit('should navigate to to /labs when the labs list option is selected', () => {\nact(() => {\n- labsLinkList.first().props().children[0].props.onClick()\n+ children[0].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/labs')\n})\nit('should navigate to /labs/new when the new labs list option is selected', () => {\nact(() => {\n- labsLinkList.first().props().children[1].props.onClick()\n+ children[1].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/labs/new')\n})\n})\ndescribe('search', () => {\nconst navSearch = hospitalRunNavbar.find('.nav-search')\n+ const { children } = navSearch.first().props() as any\nit('should render Search as the search box placeholder', () => {\n- expect(navSearch.at(2).props().children.props.children[0].props.placeholder).toEqual(\n- 'actions.search',\n- )\n+ expect(children.props.children[0].props.placeholder).toEqual('actions.search')\n})\nit('should render Search as the search button label', () => {\n- expect(navSearch.at(2).props().children.props.children[1].props.children).toEqual(\n- 'actions.search',\n- )\n+ expect(children.props.children[1].props.children).toEqual('actions.search')\n})\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Sidebar.test.tsx",
"new_path": "src/__tests__/components/Sidebar.test.tsx",
"diff": "@@ -35,7 +35,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(1).text().trim()).toEqual('dashboard.label')\n+ expect(\n+ listItems\n+ .at(1)\n+ .text()\n+ .trim(),\n+ ).toEqual('dashboard.label')\n})\nit('should be active when the current path is /', () => {\n@@ -66,7 +71,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(2).text().trim()).toEqual('patients.label')\n+ expect(\n+ listItems\n+ .at(2)\n+ .text()\n+ .trim(),\n+ ).toEqual('patients.label')\n})\nit('should render the new_patient link', () => {\n@@ -74,7 +84,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(3).text().trim()).toEqual('patients.newPatient')\n+ expect(\n+ listItems\n+ .at(3)\n+ .text()\n+ .trim(),\n+ ).toEqual('patients.newPatient')\n})\nit('should render the patients_list link', () => {\n@@ -82,7 +97,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(4).text().trim()).toEqual('patients.patientsList')\n+ expect(\n+ listItems\n+ .at(4)\n+ .text()\n+ .trim(),\n+ ).toEqual('patients.patientsList')\n})\nit('main patients link should be active when the current path is /patients', () => {\n@@ -155,7 +175,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(3).text().trim()).toEqual('scheduling.label')\n+ expect(\n+ listItems\n+ .at(3)\n+ .text()\n+ .trim(),\n+ ).toEqual('scheduling.label')\n})\nit('should render the new appointment link', () => {\n@@ -163,7 +188,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(4).text().trim()).toEqual('scheduling.appointments.new')\n+ expect(\n+ listItems\n+ .at(4)\n+ .text()\n+ .trim(),\n+ ).toEqual('scheduling.appointments.new')\n})\nit('should render the appointments schedule link', () => {\n@@ -171,7 +201,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(5).text().trim()).toEqual('scheduling.appointments.schedule')\n+ expect(\n+ listItems\n+ .at(5)\n+ .text()\n+ .trim(),\n+ ).toEqual('scheduling.appointments.schedule')\n})\nit('main scheduling link should be active when the current path is /appointments', () => {\n@@ -244,7 +279,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(4).text().trim()).toEqual('labs.label')\n+ expect(\n+ listItems\n+ .at(4)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.label')\n})\nit('should render the new labs request link', () => {\n@@ -252,7 +292,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(5).text().trim()).toEqual('labs.requests.new')\n+ expect(\n+ listItems\n+ .at(5)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.requests.new')\n})\nit('should render the labs list link', () => {\n@@ -260,7 +305,12 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(listItems.at(6).text().trim()).toEqual('labs.requests.label')\n+ expect(\n+ listItems\n+ .at(6)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.requests.label')\n})\nit('main labs link should be active when the current path is /labs', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLab.test.tsx",
"new_path": "src/__tests__/labs/ViewLab.test.tsx",
"diff": "@@ -85,29 +85,57 @@ describe('View Labs', () => {\nconst expectedLab = { ...mockLab } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst forPatientDiv = wrapper.find('.for-patient')\n- expect(forPatientDiv.find('h4').text().trim()).toEqual('labs.lab.for')\n+ expect(\n+ forPatientDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.for')\n- expect(forPatientDiv.find('h5').text().trim()).toEqual(mockPatient.fullName)\n+ expect(\n+ forPatientDiv\n+ .find('h5')\n+ .text()\n+ .trim(),\n+ ).toEqual(mockPatient.fullName)\n})\nit('should display the lab type for type', async () => {\nconst expectedLab = { ...mockLab, type: 'expected type' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labTypeDiv = wrapper.find('.lab-type')\n- expect(labTypeDiv.find('h4').text().trim()).toEqual('labs.lab.type')\n+ expect(\n+ labTypeDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.type')\n- expect(labTypeDiv.find('h5').text().trim()).toEqual(expectedLab.type)\n+ expect(\n+ labTypeDiv\n+ .find('h5')\n+ .text()\n+ .trim(),\n+ ).toEqual(expectedLab.type)\n})\nit('should display the requested on date', async () => {\nconst expectedLab = { ...mockLab, requestedOn: '2020-03-30T04:43:20.102Z' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst requestedOnDiv = wrapper.find('.requested-on')\n- expect(requestedOnDiv.find('h4').text().trim()).toEqual('labs.lab.requestedOn')\n+ expect(\n+ requestedOnDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.requestedOn')\n- expect(requestedOnDiv.find('h5').text().trim()).toEqual(\n- format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n- )\n+ expect(\n+ requestedOnDiv\n+ .find('h5')\n+ .text()\n+ .trim(),\n+ ).toEqual(format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'))\n})\nit('should not display the completed date if the lab is not completed', async () => {\n@@ -157,7 +185,12 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\n+ expect(\n+ labStatusDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('warning')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -173,11 +206,26 @@ describe('View Labs', () => {\n])\nconst buttons = wrapper.find(Button)\n- expect(buttons.at(0).text().trim()).toEqual('actions.update')\n+ expect(\n+ buttons\n+ .at(0)\n+ .text()\n+ .trim(),\n+ ).toEqual('actions.update')\n- expect(buttons.at(1).text().trim()).toEqual('labs.requests.complete')\n+ expect(\n+ buttons\n+ .at(1)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.requests.complete')\n- expect(buttons.at(2).text().trim()).toEqual('labs.requests.cancel')\n+ expect(\n+ buttons\n+ .at(2)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.requests.cancel')\n})\n})\n@@ -188,7 +236,12 @@ describe('View Labs', () => {\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\n+ expect(\n+ labStatusDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('danger')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -203,11 +256,19 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst canceledOnDiv = wrapper.find('.canceled-on')\n- expect(canceledOnDiv.find('h4').text().trim()).toEqual('labs.lab.canceledOn')\n+ expect(\n+ canceledOnDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.canceledOn')\n- expect(canceledOnDiv.find('h5').text().trim()).toEqual(\n- format(new Date(expectedLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'),\n- )\n+ expect(\n+ canceledOnDiv\n+ .find('h5')\n+ .text()\n+ .trim(),\n+ ).toEqual(format(new Date(expectedLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'))\n})\nit('should not display update, complete, and cancel button if the lab is canceled', async () => {\n@@ -239,7 +300,12 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\n+ expect(\n+ labStatusDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('primary')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -254,11 +320,19 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst completedOnDiv = wrapper.find('.completed-on')\n- expect(completedOnDiv.find('h4').text().trim()).toEqual('labs.lab.completedOn')\n-\n- expect(completedOnDiv.find('h5').text().trim()).toEqual(\n- format(new Date(expectedLab.completedOn as string), 'yyyy-MM-dd hh:mm a'),\n- )\n+ expect(\n+ completedOnDiv\n+ .find('h4')\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.completedOn')\n+\n+ expect(\n+ completedOnDiv\n+ .find('h5')\n+ .text()\n+ .trim(),\n+ ).toEqual(format(new Date(expectedLab.completedOn as string), 'yyyy-MM-dd hh:mm a'))\n})\nit('should not display update, complete, and cancel buttons if the lab is completed', async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -132,19 +132,47 @@ describe('View Labs', () => {\nexpect(table).toBeDefined()\nexpect(tableHeader).toBeDefined()\nexpect(tableBody).toBeDefined()\n- expect(tableColumnHeaders.at(0).text().trim()).toEqual('labs.lab.type')\n-\n- expect(tableColumnHeaders.at(1).text().trim()).toEqual('labs.lab.requestedOn')\n-\n- expect(tableColumnHeaders.at(2).text().trim()).toEqual('labs.lab.status')\n-\n- expect(tableDataColumns.at(0).text().trim()).toEqual(expectedLab.type)\n-\n- expect(tableDataColumns.at(1).text().trim()).toEqual(\n- format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n- )\n-\n- expect(tableDataColumns.at(2).text().trim()).toEqual(expectedLab.status)\n+ expect(\n+ tableColumnHeaders\n+ .at(0)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.type')\n+\n+ expect(\n+ tableColumnHeaders\n+ .at(1)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.requestedOn')\n+\n+ expect(\n+ tableColumnHeaders\n+ .at(2)\n+ .text()\n+ .trim(),\n+ ).toEqual('labs.lab.status')\n+\n+ expect(\n+ tableDataColumns\n+ .at(0)\n+ .text()\n+ .trim(),\n+ ).toEqual(expectedLab.type)\n+\n+ expect(\n+ tableDataColumns\n+ .at(1)\n+ .text()\n+ .trim(),\n+ ).toEqual(format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'))\n+\n+ expect(\n+ tableDataColumns\n+ .at(2)\n+ .text()\n+ .trim(),\n+ ).toEqual(expectedLab.status)\n})\nit('should navigate to the lab when the row is clicked', () => {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | style: fix inconsistent lint issues |
288,323 | 10.04.2020 16:12:54 | 18,000 | c49aa778b65f2ba49be5c1246aa402e3d6640b5e | style: change eslint config | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -7,13 +7,11 @@ module.exports = {\n},\nextends: [\n'airbnb',\n- \"eslint:recommended\",\n- \"plugin:@typescript-eslint/eslint-recommended\",\n- \"plugin:@typescript-eslint/recommended\",\n+ 'eslint:recommended',\n+ 'plugin:@typescript-eslint/eslint-recommended',\n+ 'plugin:@typescript-eslint/recommended',\n'prettier',\n- 'prettier/@typescript-eslint',\n- 'plugin:prettier/recommended',\n- 'eslint-config-prettier',\n+ 'prettier/@typescript-eslint'\n],\nglobals: {\nAtomics: 'readonly',\n@@ -37,7 +35,7 @@ module.exports = {\n'@typescript-eslint/member-delimiter-style': 'off',\n'@typescript-eslint/explicit-function-return-type': 'off',\n'@typescript-eslint/no-explicit-any': 'off',\n- '@typescript-eslint/no-unused-vars': ['error', { \"ignoreRestSiblings\": true }],\n+ '@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true }],\n'@typescript-eslint/unified-signatures': 'error',\n'@typescript-eslint/no-inferrable-types': ['error', { ignoreParameters: true }],\n'react/jsx-filename-extension': ['error', { extensions: ['.tsx'] }],\n@@ -53,7 +51,6 @@ module.exports = {\n'no-nested-ternary': 'off',\n'import/no-unresolved': 'off',\n'import/extensions': ['error', 'never'],\n- 'newline-per-chained-call': 'off',\ncurly: ['error', 'all'],\n},\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | style: change eslint config |
288,323 | 10.04.2020 17:03:18 | 18,000 | 71a6c7cacc3641a33bb0912eba01cddeb662c990 | style: revert eslint changes | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -11,7 +11,9 @@ module.exports = {\n'plugin:@typescript-eslint/eslint-recommended',\n'plugin:@typescript-eslint/recommended',\n'prettier',\n- 'prettier/@typescript-eslint'\n+ 'prettier/@typescript-eslint',\n+ 'plugin:prettier/recommended',\n+ 'eslint-config-prettier',\n],\nglobals: {\nAtomics: 'readonly',\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"enzyme-adapter-react-16\": \"~1.15.2\",\n\"eslint\": \"~6.8.0\",\n\"eslint-config-airbnb\": \"~18.1.0\",\n- \"eslint-config-prettier\": \"~6.10.0\",\n+ \"eslint-config-prettier\": \"~6.10.1\",\n\"eslint-plugin-import\": \"~2.20.0\",\n\"eslint-plugin-jest\": \"~23.8.0\",\n\"eslint-plugin-jsx-a11y\": \"~6.2.3\",\n- \"eslint-plugin-prettier\": \"~3.1.1\",\n+ \"eslint-plugin-prettier\": \"~3.1.2\",\n\"eslint-plugin-react\": \"~7.19.0\",\n\"eslint-plugin-react-hooks\": \"~2.5.0\",\n\"history\": \"~4.10.1\",\n\"jest\": \"~24.9.0\",\n\"lint-staged\": \"~10.1.0\",\n\"memdown\": \"~5.1.0\",\n- \"prettier\": \"~2.0.0\",\n+ \"prettier\": \"~2.0.4\",\n\"redux-mock-store\": \"~1.5.4\",\n\"source-map-explorer\": \"^2.2.2\",\n\"standard-version\": \"~7.1.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Sidebar.test.tsx",
"new_path": "src/__tests__/components/Sidebar.test.tsx",
"diff": "@@ -35,12 +35,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('dashboard.label')\n+ expect(listItems.at(1).text().trim()).toEqual('dashboard.label')\n})\nit('should be active when the current path is /', () => {\n@@ -71,12 +66,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('patients.label')\n+ expect(listItems.at(2).text().trim()).toEqual('patients.label')\n})\nit('should render the new_patient link', () => {\n@@ -84,12 +74,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(3)\n- .text()\n- .trim(),\n- ).toEqual('patients.newPatient')\n+ expect(listItems.at(3).text().trim()).toEqual('patients.newPatient')\n})\nit('should render the patients_list link', () => {\n@@ -97,12 +82,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('patients.patientsList')\n+ expect(listItems.at(4).text().trim()).toEqual('patients.patientsList')\n})\nit('main patients link should be active when the current path is /patients', () => {\n@@ -175,12 +155,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(3)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.label')\n+ expect(listItems.at(3).text().trim()).toEqual('scheduling.label')\n})\nit('should render the new appointment link', () => {\n@@ -188,12 +163,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.appointments.new')\n+ expect(listItems.at(4).text().trim()).toEqual('scheduling.appointments.new')\n})\nit('should render the appointments schedule link', () => {\n@@ -201,12 +171,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(5)\n- .text()\n- .trim(),\n- ).toEqual('scheduling.appointments.schedule')\n+ expect(listItems.at(5).text().trim()).toEqual('scheduling.appointments.schedule')\n})\nit('main scheduling link should be active when the current path is /appointments', () => {\n@@ -279,12 +244,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(4)\n- .text()\n- .trim(),\n- ).toEqual('labs.label')\n+ expect(listItems.at(4).text().trim()).toEqual('labs.label')\n})\nit('should render the new labs request link', () => {\n@@ -292,12 +252,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(5)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.new')\n+ expect(listItems.at(5).text().trim()).toEqual('labs.requests.new')\n})\nit('should render the labs list link', () => {\n@@ -305,12 +260,7 @@ describe('Sidebar', () => {\nconst listItems = wrapper.find(ListItem)\n- expect(\n- listItems\n- .at(6)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.label')\n+ expect(listItems.at(6).text().trim()).toEqual('labs.requests.label')\n})\nit('main labs link should be active when the current path is /labs', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLab.test.tsx",
"new_path": "src/__tests__/labs/ViewLab.test.tsx",
"diff": "@@ -85,57 +85,29 @@ describe('View Labs', () => {\nconst expectedLab = { ...mockLab } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst forPatientDiv = wrapper.find('.for-patient')\n- expect(\n- forPatientDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.for')\n+ expect(forPatientDiv.find('h4').text().trim()).toEqual('labs.lab.for')\n- expect(\n- forPatientDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(mockPatient.fullName)\n+ expect(forPatientDiv.find('h5').text().trim()).toEqual(mockPatient.fullName)\n})\nit('should display the lab type for type', async () => {\nconst expectedLab = { ...mockLab, type: 'expected type' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labTypeDiv = wrapper.find('.lab-type')\n- expect(\n- labTypeDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.type')\n+ expect(labTypeDiv.find('h4').text().trim()).toEqual('labs.lab.type')\n- expect(\n- labTypeDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.type)\n+ expect(labTypeDiv.find('h5').text().trim()).toEqual(expectedLab.type)\n})\nit('should display the requested on date', async () => {\nconst expectedLab = { ...mockLab, requestedOn: '2020-03-30T04:43:20.102Z' } as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst requestedOnDiv = wrapper.find('.requested-on')\n- expect(\n- requestedOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.requestedOn')\n+ expect(requestedOnDiv.find('h4').text().trim()).toEqual('labs.lab.requestedOn')\n- expect(\n- requestedOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'))\n+ expect(requestedOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display the completed date if the lab is not completed', async () => {\n@@ -185,12 +157,7 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('warning')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -206,26 +173,11 @@ describe('View Labs', () => {\n])\nconst buttons = wrapper.find(Button)\n- expect(\n- buttons\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual('actions.update')\n+ expect(buttons.at(0).text().trim()).toEqual('actions.update')\n- expect(\n- buttons\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.complete')\n+ expect(buttons.at(1).text().trim()).toEqual('labs.requests.complete')\n- expect(\n- buttons\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('labs.requests.cancel')\n+ expect(buttons.at(2).text().trim()).toEqual('labs.requests.cancel')\n})\n})\n@@ -236,12 +188,7 @@ describe('View Labs', () => {\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('danger')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -256,19 +203,11 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst canceledOnDiv = wrapper.find('.canceled-on')\n- expect(\n- canceledOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.canceledOn')\n+ expect(canceledOnDiv.find('h4').text().trim()).toEqual('labs.lab.canceledOn')\n- expect(\n- canceledOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(format(new Date(expectedLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'))\n+ expect(canceledOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.canceledOn as string), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display update, complete, and cancel button if the lab is canceled', async () => {\n@@ -300,12 +239,7 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst labStatusDiv = wrapper.find('.lab-status')\nconst badge = labStatusDiv.find(Badge)\n- expect(\n- labStatusDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n+ expect(labStatusDiv.find('h4').text().trim()).toEqual('labs.lab.status')\nexpect(badge.prop('color')).toEqual('primary')\nexpect(badge.text().trim()).toEqual(expectedLab.status)\n@@ -320,19 +254,11 @@ describe('View Labs', () => {\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\nconst completedOnDiv = wrapper.find('.completed-on')\n- expect(\n- completedOnDiv\n- .find('h4')\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.completedOn')\n-\n- expect(\n- completedOnDiv\n- .find('h5')\n- .text()\n- .trim(),\n- ).toEqual(format(new Date(expectedLab.completedOn as string), 'yyyy-MM-dd hh:mm a'))\n+ expect(completedOnDiv.find('h4').text().trim()).toEqual('labs.lab.completedOn')\n+\n+ expect(completedOnDiv.find('h5').text().trim()).toEqual(\n+ format(new Date(expectedLab.completedOn as string), 'yyyy-MM-dd hh:mm a'),\n+ )\n})\nit('should not display update, complete, and cancel buttons if the lab is completed', async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -132,47 +132,19 @@ describe('View Labs', () => {\nexpect(table).toBeDefined()\nexpect(tableHeader).toBeDefined()\nexpect(tableBody).toBeDefined()\n- expect(\n- tableColumnHeaders\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.type')\n-\n- expect(\n- tableColumnHeaders\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.requestedOn')\n-\n- expect(\n- tableColumnHeaders\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual('labs.lab.status')\n-\n- expect(\n- tableDataColumns\n- .at(0)\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.type)\n-\n- expect(\n- tableDataColumns\n- .at(1)\n- .text()\n- .trim(),\n- ).toEqual(format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'))\n-\n- expect(\n- tableDataColumns\n- .at(2)\n- .text()\n- .trim(),\n- ).toEqual(expectedLab.status)\n+ expect(tableColumnHeaders.at(0).text().trim()).toEqual('labs.lab.type')\n+\n+ expect(tableColumnHeaders.at(1).text().trim()).toEqual('labs.lab.requestedOn')\n+\n+ expect(tableColumnHeaders.at(2).text().trim()).toEqual('labs.lab.status')\n+\n+ expect(tableDataColumns.at(0).text().trim()).toEqual(expectedLab.type)\n+\n+ expect(tableDataColumns.at(1).text().trim()).toEqual(\n+ format(new Date(expectedLab.requestedOn), 'yyyy-MM-dd hh:mm a'),\n+ )\n+\n+ expect(tableDataColumns.at(2).text().trim()).toEqual(expectedLab.status)\n})\nit('should navigate to the lab when the row is clicked', () => {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | style: revert eslint changes |
288,333 | 10.04.2020 17:44:10 | 25,200 | b816ebf84661fe7290338451fe2737dfc1c0efa2 | fix(patients): current patient can no longer be related person | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"new_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"diff": "@@ -3,20 +3,51 @@ import React from 'react'\nimport { ReactWrapper, mount } from 'enzyme'\nimport { Modal, Alert, Typeahead } from '@hospitalrun/components'\nimport { act } from '@testing-library/react'\n-import AddRelatedPersonModal from '../../../patients/related-persons/AddRelatedPersonModal'\n+import { Provider } from 'react-redux'\n+import thunk from 'redux-thunk'\n+import configureMockStore, { MockStore } from 'redux-mock-store'\n+import Patient from 'model/Patient'\nimport TextInputWithLabelFormGroup from '../../../components/input/TextInputWithLabelFormGroup'\n+import AddRelatedPersonModal from '../../../patients/related-persons/AddRelatedPersonModal'\n+\n+const mockStore = configureMockStore([thunk])\ndescribe('Add Related Person Modal', () => {\n+ const patient = {\n+ id: '123',\n+ prefix: 'prefix',\n+ givenName: 'givenName',\n+ familyName: 'familyName',\n+ suffix: 'suffix',\n+ sex: 'male',\n+ type: 'charity',\n+ occupation: 'occupation',\n+ preferredLanguage: 'preferredLanguage',\n+ phoneNumber: 'phoneNumber',\n+ email: '[email protected]',\n+ address: 'address',\n+ code: 'P00001',\n+ dateOfBirth: new Date().toISOString(),\n+ } as Patient\n+\n+ let store: MockStore\n+\ndescribe('layout', () => {\nlet wrapper: ReactWrapper\n+\n+ store = mockStore({\n+ patient: { patient },\n+ })\nbeforeEach(() => {\nwrapper = mount(\n+ <Provider store={store}>\n<AddRelatedPersonModal\nshow\nonSave={jest.fn()}\nonCloseButtonClick={jest.fn()}\ntoggle={jest.fn()}\n- />,\n+ />\n+ </Provider>,\n)\n})\n@@ -65,12 +96,14 @@ describe('Add Related Person Modal', () => {\nbeforeEach(() => {\nonSaveSpy = jest.fn()\nwrapper = mount(\n+ <Provider store={store}>\n<AddRelatedPersonModal\nshow\nonSave={onSaveSpy}\nonCloseButtonClick={jest.fn()}\ntoggle={jest.fn()}\n- />,\n+ />\n+ </Provider>,\n)\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"new_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"diff": "@@ -5,6 +5,8 @@ import TextInputWithLabelFormGroup from 'components/input/TextInputWithLabelForm\nimport RelatedPerson from 'model/RelatedPerson'\nimport PatientRepository from 'clients/db/PatientRepository'\nimport Patient from 'model/Patient'\n+import { useSelector } from 'react-redux'\n+import { RootState } from '../../store'\ninterface Props {\nshow: boolean\n@@ -21,6 +23,9 @@ const AddRelatedPersonModal = (props: Props) => {\npatientId: '',\ntype: '',\n})\n+ const { patient } = useSelector((state: RootState) => state.patient)\n+\n+ const patientId = () => patient.id\nconst onFieldChange = (key: string, value: string) => {\nsetRelatedPerson({\n@@ -33,8 +38,8 @@ const AddRelatedPersonModal = (props: Props) => {\nonFieldChange(fieldName, event.target.value)\n}\n- const onPatientSelect = (patient: Patient[]) => {\n- setRelatedPerson({ ...relatedPerson, patientId: patient[0].id })\n+ const onPatientSelect = (p: Patient[]) => {\n+ setRelatedPerson({ ...relatedPerson, patientId: p[0].id })\n}\nconst body = (\n@@ -50,9 +55,13 @@ const AddRelatedPersonModal = (props: Props) => {\nplaceholder={t('patient.relatedPerson')}\nonChange={onPatientSelect}\nonSearch={async (query: string) => PatientRepository.search(query)}\n- renderMenuItemChildren={(patient: Patient) => (\n- <div>{`${patient.fullName} (${patient.code})`}</div>\n- )}\n+ renderMenuItemChildren={(p: Patient) => {\n+ if (patientId() === p.id) {\n+ return <div />\n+ }\n+\n+ return <div>{`${p.fullName} (${p.code})`}</div>\n+ }}\n/>\n</div>\n</div>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(patients): current patient can no longer be related person (#1959) |
288,312 | 12.04.2020 16:49:56 | 10,800 | 992e58df8ebdaac2e2df2b0e50423608513a5176 | fix(patient): Input validation and error feedback | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"new_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"diff": "@@ -9,6 +9,7 @@ import { act } from 'react-dom/test-utils'\nimport configureMockStore, { MockStore } from 'redux-mock-store'\nimport thunk from 'redux-thunk'\nimport { Button } from '@hospitalrun/components'\n+import { addDays, endOfToday } from 'date-fns'\nimport EditPatient from '../../../patients/edit/EditPatient'\nimport GeneralInformation from '../../../patients/GeneralInformation'\nimport Patient from '../../../model/Patient'\n@@ -119,6 +120,71 @@ describe('Edit Patient', () => {\nexpect(store.getActions()).toContainEqual(patientSlice.updatePatientSuccess(patient))\n})\n+ it('should pass no given name error when form doesnt contain a given name on save button click', async () => {\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await setup()\n+ })\n+\n+ const givenName = wrapper.findWhere((w: any) => w.prop('name') === 'givenName')\n+ expect(givenName.prop('value')).toBe('')\n+\n+ const generalInformationForm = wrapper.find(GeneralInformation)\n+ expect(generalInformationForm.prop('errorMessage')).toBe('')\n+\n+ const saveButton = wrapper.find(Button).at(0)\n+ const onClick = saveButton.prop('onClick') as any\n+ expect(saveButton.text().trim()).toEqual('actions.save')\n+\n+ act(() => {\n+ onClick()\n+ })\n+\n+ wrapper.update()\n+ expect(wrapper.find(GeneralInformation).prop('errorMessage')).toMatch(\n+ 'patient.errors.updatePatientError',\n+ )\n+ expect(wrapper.find(GeneralInformation).prop('feedbackFields').givenName).toMatch(\n+ 'patient.errors.patientGivenNameFeedback',\n+ )\n+ expect(wrapper.update.isInvalid === true)\n+ })\n+\n+ it('should pass invalid date of birth error when input date is grater than today on save button click', async () => {\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await setup()\n+ })\n+\n+ const generalInformationForm = wrapper.find(GeneralInformation)\n+\n+ act(() => {\n+ generalInformationForm.prop('onFieldChange')(\n+ 'dateOfBirth',\n+ addDays(endOfToday(), 10).toISOString(),\n+ )\n+ })\n+\n+ wrapper.update()\n+\n+ const saveButton = wrapper.find(Button).at(0)\n+ const onClick = saveButton.prop('onClick') as any\n+ expect(saveButton.text().trim()).toEqual('actions.save')\n+\n+ await act(async () => {\n+ await onClick()\n+ })\n+\n+ wrapper.update()\n+ expect(wrapper.find(GeneralInformation).prop('errorMessage')).toMatch(\n+ 'patient.errors.updatePatientError',\n+ )\n+ expect(wrapper.find(GeneralInformation).prop('feedbackFields').dateOfBirth).toMatch(\n+ 'patient.errors.patientDateOfBirthFeedback',\n+ )\n+ expect(wrapper.update.isInvalid === true)\n+ })\n+\nit('should navigate to /patients/:id when cancel is clicked', async () => {\nlet wrapper: any\nawait act(async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/new/NewPatient.test.tsx",
"new_path": "src/__tests__/patients/new/NewPatient.test.tsx",
"diff": "@@ -10,6 +10,7 @@ import configureMockStore, { MockStore } from 'redux-mock-store'\nimport thunk from 'redux-thunk'\nimport * as components from '@hospitalrun/components'\n+import { addDays, endOfToday } from 'date-fns'\nimport NewPatient from '../../../patients/new/NewPatient'\nimport GeneralInformation from '../../../patients/GeneralInformation'\nimport Patient from '../../../model/Patient'\n@@ -95,7 +96,45 @@ describe('New Patient', () => {\nwrapper.update()\nexpect(wrapper.find(GeneralInformation).prop('errorMessage')).toMatch(\n- 'patient.errors.patientGivenNameRequiredOnCreate',\n+ 'patient.errors.createPatientError',\n+ )\n+ expect(wrapper.find(GeneralInformation).prop('feedbackFields').givenName).toMatch(\n+ 'patient.errors.patientGivenNameFeedback',\n+ )\n+ expect(wrapper.update.isInvalid === true)\n+ })\n+\n+ it('should pass invalid date of birth error when input date is grater than today on save button click', async () => {\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await setup()\n+ })\n+\n+ const generalInformationForm = wrapper.find(GeneralInformation)\n+\n+ act(() => {\n+ generalInformationForm.prop('onFieldChange')(\n+ 'dateOfBirth',\n+ addDays(endOfToday(), 10).toISOString(),\n+ )\n+ })\n+\n+ wrapper.update()\n+\n+ const saveButton = wrapper.find(components.Button).at(0)\n+ const onClick = saveButton.prop('onClick') as any\n+ expect(saveButton.text().trim()).toEqual('actions.save')\n+\n+ await act(async () => {\n+ await onClick()\n+ })\n+\n+ wrapper.update()\n+ expect(wrapper.find(GeneralInformation).prop('errorMessage')).toMatch(\n+ 'patient.errors.createPatientError',\n+ )\n+ expect(wrapper.find(GeneralInformation).prop('feedbackFields').dateOfBirth).toMatch(\n+ 'patient.errors.patientDateOfBirthFeedback',\n)\nexpect(wrapper.update.isInvalid === true)\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"new_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"diff": "@@ -8,10 +8,12 @@ interface Props {\nisEditable?: boolean\nonChange?: (date: Date) => void\nisRequired?: boolean\n+ feedback?: string\n+ isInvalid?: boolean\n}\nconst DatePickerWithLabelFormGroup = (props: Props) => {\n- const { onChange, label, name, isEditable, value, isRequired } = props\n+ const { onChange, label, name, isEditable, value, isRequired, feedback, isInvalid } = props\nconst id = `${name}DatePicker`\nreturn (\n<div className=\"form-group\">\n@@ -24,6 +26,8 @@ const DatePickerWithLabelFormGroup = (props: Props) => {\ntimeIntervals={30}\nwithPortal={false}\ndisabled={!isEditable}\n+ feedback={feedback}\n+ isInvalid={isInvalid}\nonChange={(inputDate) => {\nif (onChange) {\nonChange(inputDate)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "export default {\npatient: {\n- code: 'Code',\nfirstName: 'First Name',\nlastName: 'Last Name',\nsuffix: 'Suffix',\n@@ -85,9 +84,10 @@ export default {\nprivate: 'Private',\n},\nerrors: {\n- patientGivenNameRequiredOnCreate: 'Could not create new patient.',\n- patientGivenNameRequiredOnUpdate: 'Could not update patient.',\n+ createPatientError: 'Could not create new patient.',\n+ updatePatientError: 'Could not update patient.',\npatientGivenNameFeedback: 'Given Name is required.',\n+ patientDateOfBirthFeedback: 'Date of Birth can not be greater than today',\n},\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/GeneralInformation.tsx",
"new_path": "src/patients/GeneralInformation.tsx",
"diff": "@@ -9,25 +9,28 @@ import TextInputWithLabelFormGroup from '../components/input/TextInputWithLabelF\nimport SelectWithLabelFormGroup from '../components/input/SelectWithLableFormGroup'\nimport DatePickerWithLabelFormGroup from '../components/input/DatePickerWithLabelFormGroup'\n+interface Feedback {\n+ givenName: string\n+ dateOfBirth: string\n+}\n+\n+interface InvalidFields {\n+ givenName: boolean\n+ dateOfBirth: boolean\n+}\n+\ninterface Props {\npatient: Patient\nisEditable?: boolean\nerrorMessage?: string\nonFieldChange?: (key: string, value: string | boolean) => void\n- isInvalid?: boolean\n- patientGivenNameFeedback?: string\n+ invalidFields?: InvalidFields\n+ feedbackFields?: Feedback\n}\nconst GeneralInformation = (props: Props) => {\nconst { t } = useTranslation()\n- const {\n- patient,\n- isEditable,\n- onFieldChange,\n- errorMessage,\n- isInvalid,\n- patientGivenNameFeedback,\n- } = props\n+ const { patient, isEditable, onFieldChange, errorMessage, invalidFields, feedbackFields } = props\nconst onSelectChange = (event: React.ChangeEvent<HTMLSelectElement>, fieldName: string) =>\nonFieldChange && onFieldChange(fieldName, event.target.value)\n@@ -81,8 +84,8 @@ const GeneralInformation = (props: Props) => {\nonInputElementChange(event, 'givenName')\n}}\nisRequired\n- isInvalid={isInvalid}\n- feedback={patientGivenNameFeedback}\n+ isInvalid={invalidFields?.givenName}\n+ feedback={feedbackFields?.givenName}\n/>\n</div>\n<div className=\"col-md-4\">\n@@ -163,6 +166,8 @@ const GeneralInformation = (props: Props) => {\n? new Date(patient.dateOfBirth)\n: undefined\n}\n+ isInvalid={invalidFields?.dateOfBirth}\n+ feedback={feedbackFields?.dateOfBirth}\nonChange={(date: Date) => {\nonDateOfBirthChange(date)\n}}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/edit/EditPatient.tsx",
"new_path": "src/patients/edit/EditPatient.tsx",
"diff": "@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { Spinner, Button, Toast } from '@hospitalrun/components'\n+import { parseISO } from 'date-fns'\nimport GeneralInformation from '../GeneralInformation'\nimport useTitle from '../../page-header/useTitle'\nimport Patient from '../../model/Patient'\n@@ -27,8 +28,14 @@ const EditPatient = () => {\nconst [patient, setPatient] = useState({} as Patient)\nconst [errorMessage, setErrorMessage] = useState('')\n- const [isInvalid, setIsInvalid] = useState(false)\n- const [patientGivenNameFeedback, setPatientGivenNameFeedback] = useState('')\n+ const [invalidFields, setInvalidFields] = useState({\n+ givenName: false,\n+ dateOfBirth: false,\n+ })\n+ const [feedbackFields, setFeedbackFields] = useState({\n+ givenName: '',\n+ dateOfBirth: '',\n+ })\nconst { patient: reduxPatient, isLoading } = useSelector((state: RootState) => state.patient)\nuseTitle(\n@@ -68,12 +75,40 @@ const EditPatient = () => {\n)\n}\n- const onSave = () => {\n+ const validateInput = () => {\n+ let inputIsValid = true\n+\nif (!patient.givenName) {\n- setErrorMessage(t('patient.errors.patientGivenNameRequiredOnUpdate'))\n- setIsInvalid(true)\n- setPatientGivenNameFeedback(t('patient.errors.patientGivenNameFeedback'))\n- } else {\n+ inputIsValid = false\n+ setErrorMessage(t('patient.errors.updatePatientError'))\n+ setInvalidFields((prevState) => ({\n+ ...prevState,\n+ givenName: true,\n+ }))\n+ setFeedbackFields((prevState) => ({\n+ ...prevState,\n+ givenName: t('patient.errors.patientGivenNameFeedback'),\n+ }))\n+ }\n+ if (patient.dateOfBirth) {\n+ if (parseISO(patient.dateOfBirth) > new Date(Date.now())) {\n+ inputIsValid = false\n+ setErrorMessage(t('patient.errors.updatePatientError'))\n+ setInvalidFields((prevState) => ({\n+ ...prevState,\n+ dateOfBirth: true,\n+ }))\n+ setFeedbackFields((prevState) => ({\n+ ...prevState,\n+ dateOfBirth: t('patient.errors.patientDateOfBirthFeedback'),\n+ }))\n+ }\n+ }\n+ return inputIsValid\n+ }\n+\n+ const onSave = () => {\n+ if (validateInput()) {\ndispatch(\nupdatePatient(\n{\n@@ -104,8 +139,8 @@ const EditPatient = () => {\npatient={patient}\nonFieldChange={onFieldChange}\nerrorMessage={errorMessage}\n- isInvalid={isInvalid}\n- patientGivenNameFeedback={patientGivenNameFeedback}\n+ invalidFields={invalidFields}\n+ feedbackFields={feedbackFields}\n/>\n<div className=\"row float-right\">\n<div className=\"btn-group btn-group-lg\">\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/new/NewPatient.tsx",
"new_path": "src/patients/new/NewPatient.tsx",
"diff": "@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'\nimport { useDispatch } from 'react-redux'\nimport { Button, Toast } from '@hospitalrun/components'\n+import { parseISO } from 'date-fns'\nimport GeneralInformation from '../GeneralInformation'\nimport useTitle from '../../page-header/useTitle'\nimport Patient from '../../model/Patient'\n@@ -23,8 +24,14 @@ const NewPatient = () => {\nconst [patient, setPatient] = useState({} as Patient)\nconst [errorMessage, setErrorMessage] = useState('')\n- const [isInvalid, setIsInvalid] = useState(false)\n- const [patientGivenNameFeedback, setPatientGivenNameFeedback] = useState('')\n+ const [invalidFields, setInvalidFields] = useState({\n+ givenName: false,\n+ dateOfBirth: false,\n+ })\n+ const [feedbackFields, setFeedbackFields] = useState({\n+ givenName: '',\n+ dateOfBirth: '',\n+ })\nuseTitle(t('patients.newPatient'))\nuseAddBreadcrumbs(breadcrumbs, true)\n@@ -42,12 +49,40 @@ const NewPatient = () => {\n)\n}\n- const onSave = () => {\n+ const validateInput = () => {\n+ let inputIsValid = true\n+\nif (!patient.givenName) {\n- setErrorMessage(t('patient.errors.patientGivenNameRequiredOnCreate'))\n- setIsInvalid(true)\n- setPatientGivenNameFeedback(t('patient.errors.patientGivenNameFeedback'))\n- } else {\n+ inputIsValid = false\n+ setErrorMessage(t('patient.errors.createPatientError'))\n+ setInvalidFields((prevState) => ({\n+ ...prevState,\n+ givenName: true,\n+ }))\n+ setFeedbackFields((prevState) => ({\n+ ...prevState,\n+ givenName: t('patient.errors.patientGivenNameFeedback'),\n+ }))\n+ }\n+ if (patient.dateOfBirth) {\n+ if (parseISO(patient.dateOfBirth) > new Date(Date.now())) {\n+ inputIsValid = false\n+ setErrorMessage(t('patient.errors.createPatientError'))\n+ setInvalidFields((prevState) => ({\n+ ...prevState,\n+ dateOfBirth: true,\n+ }))\n+ setFeedbackFields((prevState) => ({\n+ ...prevState,\n+ dateOfBirth: t('patient.errors.patientDateOfBirthFeedback'),\n+ }))\n+ }\n+ }\n+ return inputIsValid\n+ }\n+\n+ const onSave = () => {\n+ if (validateInput()) {\ndispatch(\ncreatePatient(\n{\n@@ -65,6 +100,7 @@ const NewPatient = () => {\n...patient,\n[key]: value,\n})\n+ setErrorMessage('')\n}\nreturn (\n@@ -74,8 +110,8 @@ const NewPatient = () => {\npatient={patient}\nonFieldChange={onFieldChange}\nerrorMessage={errorMessage}\n- isInvalid={isInvalid}\n- patientGivenNameFeedback={patientGivenNameFeedback}\n+ invalidFields={invalidFields}\n+ feedbackFields={feedbackFields}\n/>\n<div className=\"row float-right\">\n<div className=\"btn-group btn-group-lg mt-3\">\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(patient): Input validation and error feedback (#1977) |
288,323 | 12.04.2020 16:50:49 | 18,000 | 1a4ece9d4a1a4b05a7166f34a741c57595a550c0 | refactor labs to use redux | [
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLab.tsx",
"new_path": "src/labs/ViewLab.tsx",
"diff": "import React, { useEffect, useState } from 'react'\nimport { useParams, useHistory } from 'react-router'\nimport format from 'date-fns/format'\n-import LabRepository from 'clients/db/LabRepository'\nimport Lab from 'model/Lab'\nimport Patient from 'model/Patient'\n-import PatientRepository from 'clients/db/PatientRepository'\nimport useTitle from 'page-header/useTitle'\nimport { useTranslation } from 'react-i18next'\nimport { Row, Column, Badge, Button, Alert } from '@hospitalrun/components'\nimport TextFieldWithLabelFormGroup from 'components/input/TextFieldWithLabelFormGroup'\nimport useAddBreadcrumbs from 'breadcrumbs/useAddBreadcrumbs'\n-import { useSelector } from 'react-redux'\n+import { useSelector, useDispatch } from 'react-redux'\nimport Permissions from 'model/Permissions'\nimport { RootState } from '../store'\n+import { cancelLab, completeLab, updateLab, fetchLab } from './lab-slice'\nconst getTitle = (patient: Patient | undefined, lab: Lab | undefined) =>\npatient && lab ? `${lab.type} for ${patient.fullName}` : ''\n@@ -21,94 +20,82 @@ const ViewLab = () => {\nconst { id } = useParams()\nconst { t } = useTranslation()\nconst history = useHistory()\n+ const dispatch = useDispatch()\nconst { permissions } = useSelector((state: RootState) => state.user)\n- const [patient, setPatient] = useState<Patient | undefined>()\n- const [lab, setLab] = useState<Lab | undefined>()\n+ const { lab, patient, status, error } = useSelector((state: RootState) => state.lab)\n+\n+ const [labToView, setLabToView] = useState<Lab>()\nconst [isEditable, setIsEditable] = useState<boolean>(true)\n- const [isResultInvalid, setIsResultInvalid] = useState<boolean>(false)\n- const [resultFeedback, setResultFeedback] = useState()\n- const [errorMessage, setErrorMessage] = useState()\n- useTitle(getTitle(patient, lab))\n+ useTitle(getTitle(patient, labToView))\nconst breadcrumbs = [\n{\ni18nKey: 'labs.requests.view',\n- location: `/labs/${lab?.id}`,\n+ location: `/labs/${labToView?.id}`,\n},\n]\nuseAddBreadcrumbs(breadcrumbs)\nuseEffect(() => {\n- const fetchLab = async () => {\nif (id) {\n- const fetchedLab = await LabRepository.find(id)\n- setLab(fetchedLab)\n- setIsEditable(fetchedLab.status === 'requested')\n- }\n+ dispatch(fetchLab(id))\n}\n- fetchLab()\n- }, [id])\n+ }, [id, dispatch])\nuseEffect(() => {\n- const fetchPatient = async () => {\nif (lab) {\n- const fetchedPatient = await PatientRepository.find(lab.patientId)\n- setPatient(fetchedPatient)\n+ setLabToView({ ...lab })\n+ setIsEditable(lab.status === 'requested')\n}\n- }\n-\n- fetchPatient()\n+ console.log('lab change')\n+ console.log(lab)\n}, [lab])\nconst onResultChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {\nconst result = event.currentTarget.value\n- const newLab = lab as Lab\n- setLab({ ...newLab, result })\n+ const newLab = labToView as Lab\n+ setLabToView({ ...newLab, result })\n}\nconst onNotesChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {\nconst notes = event.currentTarget.value\n- const newLab = lab as Lab\n- setLab({ ...newLab, notes })\n+ const newLab = labToView as Lab\n+ setLabToView({ ...newLab, notes })\n}\nconst onUpdate = async () => {\n- await LabRepository.saveOrUpdate(lab as Lab)\n+ const onSuccess = () => {\nhistory.push('/labs')\n}\n+ if (labToView) {\n+ dispatch(updateLab(labToView, onSuccess))\n+ }\n+ }\nconst onComplete = async () => {\n- const newLab = lab as Lab\n-\n- if (!newLab.result) {\n- setIsResultInvalid(true)\n- setResultFeedback(t('labs.requests.error.resultRequiredToComplete'))\n- setErrorMessage(t('labs.requests.error.unableToComplete'))\n- return\n+ const onSuccess = () => {\n+ history.push('/labs')\n}\n- await LabRepository.saveOrUpdate({\n- ...newLab,\n- completedOn: new Date(Date.now().valueOf()).toISOString(),\n- status: 'completed',\n- })\n- history.push('/labs')\n+ if (labToView) {\n+ dispatch(completeLab(labToView, onSuccess))\n+ }\n}\nconst onCancel = async () => {\n- const newLab = lab as Lab\n- await LabRepository.saveOrUpdate({\n- ...newLab,\n- canceledOn: new Date(Date.now().valueOf()).toISOString(),\n- status: 'canceled',\n- })\n+ const onSuccess = () => {\nhistory.push('/labs')\n}\n+ if (labToView) {\n+ dispatch(cancelLab(labToView, onSuccess))\n+ }\n+ }\n+\nconst getButtons = () => {\nconst buttons: React.ReactNode[] = []\n- if (lab?.status === 'completed' || lab?.status === 'canceled') {\n+ if (labToView?.status === 'completed' || labToView?.status === 'canceled') {\nreturn buttons\n}\n@@ -137,34 +124,34 @@ const ViewLab = () => {\nreturn buttons\n}\n- if (lab && patient) {\n+ if (labToView && patient) {\nconst getBadgeColor = () => {\n- if (lab.status === 'completed') {\n+ if (labToView.status === 'completed') {\nreturn 'primary'\n}\n- if (lab.status === 'canceled') {\n+ if (labToView.status === 'canceled') {\nreturn 'danger'\n}\nreturn 'warning'\n}\nconst getCanceledOnOrCompletedOnDate = () => {\n- if (lab.status === 'completed' && lab.completedOn) {\n+ if (labToView.status === 'completed' && labToView.completedOn) {\nreturn (\n<Column>\n<div className=\"form-group completed-on\">\n<h4>{t('labs.lab.completedOn')}</h4>\n- <h5>{format(new Date(lab.completedOn), 'yyyy-MM-dd hh:mm a')}</h5>\n+ <h5>{format(new Date(labToView.completedOn), 'yyyy-MM-dd hh:mm a')}</h5>\n</div>\n</Column>\n)\n}\n- if (lab.status === 'canceled' && lab.canceledOn) {\n+ if (labToView.status === 'canceled' && labToView.canceledOn) {\nreturn (\n<Column>\n<div className=\"form-group canceled-on\">\n<h4>{t('labs.lab.canceledOn')}</h4>\n- <h5>{format(new Date(lab.canceledOn), 'yyyy-MM-dd hh:mm a')}</h5>\n+ <h5>{format(new Date(labToView.canceledOn), 'yyyy-MM-dd hh:mm a')}</h5>\n</div>\n</Column>\n)\n@@ -174,15 +161,15 @@ const ViewLab = () => {\nreturn (\n<>\n- {isResultInvalid && (\n- <Alert color=\"danger\" title={t('states.error')} message={errorMessage} />\n+ {status === 'error' && (\n+ <Alert color=\"danger\" title={t('states.error')} message={t(error.message || '')} />\n)}\n<Row>\n<Column>\n<div className=\"form-group lab-status\">\n<h4>{t('labs.lab.status')}</h4>\n<Badge color={getBadgeColor()}>\n- <h5>{lab.status}</h5>\n+ <h5>{labToView.status}</h5>\n</Badge>\n</div>\n</Column>\n@@ -195,13 +182,13 @@ const ViewLab = () => {\n<Column>\n<div className=\"form-group lab-type\">\n<h4>{t('labs.lab.type')}</h4>\n- <h5>{lab.type}</h5>\n+ <h5>{labToView.type}</h5>\n</div>\n</Column>\n<Column>\n<div className=\"form-group requested-on\">\n<h4>{t('labs.lab.requestedOn')}</h4>\n- <h5>{format(new Date(lab.requestedOn), 'yyyy-MM-dd hh:mm a')}</h5>\n+ <h5>{format(new Date(labToView.requestedOn), 'yyyy-MM-dd hh:mm a')}</h5>\n</div>\n</Column>\n{getCanceledOnOrCompletedOnDate()}\n@@ -211,16 +198,16 @@ const ViewLab = () => {\n<TextFieldWithLabelFormGroup\nname=\"result\"\nlabel={t('labs.lab.result')}\n- value={lab.result}\n+ value={labToView.result}\nisEditable={isEditable}\n- isInvalid={isResultInvalid}\n- feedback={resultFeedback}\n+ isInvalid={!!error.result}\n+ feedback={t(error.result || '')}\nonChange={onResultChange}\n/>\n<TextFieldWithLabelFormGroup\nname=\"notes\"\nlabel={t('labs.lab.notes')}\n- value={lab.notes}\n+ value={labToView.notes}\nisEditable={isEditable}\nonChange={onNotesChange}\n/>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/labs/lab-slice.ts",
"diff": "+import Lab from 'model/Lab'\n+import Patient from 'model/Patient'\n+import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import { AppThunk } from 'store'\n+import LabRepository from 'clients/db/LabRepository'\n+import PatientRepository from 'clients/db/PatientRepository'\n+\n+interface Error {\n+ result?: string\n+ patient?: string\n+ type?: string\n+ message?: string\n+}\n+\n+interface LabState {\n+ error: Error\n+ lab?: Lab\n+ patient?: Patient\n+ status: 'loading' | 'error' | 'success'\n+}\n+\n+const initialState: LabState = {\n+ error: {},\n+ lab: undefined,\n+ patient: undefined,\n+ status: 'loading',\n+}\n+\n+function start(state: LabState) {\n+ state.status = 'loading'\n+}\n+\n+function finish(state: LabState, { payload }: PayloadAction<Lab>) {\n+ state.status = 'success'\n+ state.lab = payload\n+ state.error = {}\n+}\n+\n+function error(state: LabState, { payload }: PayloadAction<Error>) {\n+ state.status = 'error'\n+ state.error = payload\n+}\n+\n+const labSlice = createSlice({\n+ name: 'lab',\n+ initialState,\n+ reducers: {\n+ fetchLabStart: start,\n+ fetchLabSuccess: (\n+ state: LabState,\n+ { payload }: PayloadAction<{ lab: Lab; patient: Patient }>,\n+ ) => {\n+ state.status = 'success'\n+ state.lab = payload.lab\n+ state.patient = payload.patient\n+ },\n+ updateLabStart: start,\n+ updateLabSuccess: finish,\n+ requestLabStart: start,\n+ requestLabSuccess: finish,\n+ requestLabError: error,\n+ cancelLabStart: start,\n+ cancelLabSuccess: finish,\n+ completeLabStart: start,\n+ completeLabSuccess: finish,\n+ completeLabError: error,\n+ },\n+})\n+\n+export const {\n+ fetchLabStart,\n+ fetchLabSuccess,\n+ updateLabStart,\n+ updateLabSuccess,\n+ requestLabStart,\n+ requestLabSuccess,\n+ requestLabError,\n+ cancelLabStart,\n+ cancelLabSuccess,\n+ completeLabStart,\n+ completeLabSuccess,\n+ completeLabError,\n+} = labSlice.actions\n+\n+export const fetchLab = (labId: string): AppThunk => async (dispatch) => {\n+ dispatch(fetchLabStart())\n+ const fetchedLab = await LabRepository.find(labId)\n+ const fetchedPatient = await PatientRepository.find(fetchedLab.patientId)\n+ dispatch(fetchLabSuccess({ lab: fetchedLab, patient: fetchedPatient }))\n+}\n+\n+const validateLabRequest = (newLab: Lab): Error => {\n+ const labRequestError: Error = {}\n+ if (!newLab.patientId) {\n+ labRequestError.patient = 'labs.requests.error.patientRequired'\n+ }\n+\n+ if (!newLab.type) {\n+ labRequestError.type = 'labs.requests.error.typeRequired'\n+ }\n+\n+ return labRequestError\n+}\n+\n+export const requestLab = (newLab: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\n+ dispatch,\n+) => {\n+ dispatch(requestLabStart())\n+\n+ const labRequestError = validateLabRequest(newLab)\n+ if (Object.keys(labRequestError).length > 0) {\n+ labRequestError.message = 'labs.requests.error.unableToRequest'\n+ dispatch(requestLabError(labRequestError))\n+ } else {\n+ newLab.requestedOn = new Date(Date.now().valueOf()).toISOString()\n+ const requestedLab = await LabRepository.saveOrUpdate(newLab)\n+ dispatch(requestLabSuccess(requestedLab))\n+\n+ if (onSuccess) {\n+ onSuccess(newLab)\n+ }\n+ }\n+}\n+\n+export const cancelLab = (labToCancel: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\n+ dispatch,\n+) => {\n+ dispatch(cancelLabStart())\n+\n+ labToCancel.canceledOn = new Date(Date.now().valueOf()).toISOString()\n+ labToCancel.status = 'canceled'\n+ const canceledLab = await LabRepository.saveOrUpdate(labToCancel)\n+ dispatch(cancelLabSuccess(canceledLab))\n+\n+ if (onSuccess) {\n+ onSuccess(canceledLab)\n+ }\n+}\n+\n+const validateCompleteLab = (labToComplete: Lab): Error => {\n+ const completeError: Error = {}\n+\n+ if (!labToComplete.result) {\n+ completeError.result = 'labs.requests.error.resultRequiredToComplete'\n+ }\n+\n+ return completeError\n+}\n+\n+export const completeLab = (labToComplete: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\n+ dispatch,\n+) => {\n+ dispatch(cancelLabStart())\n+\n+ const completeLabErrors = validateCompleteLab(labToComplete)\n+ if (Object.keys(completeLabErrors).length > 0) {\n+ completeLabErrors.message = 'labs.requests.error.unableToComplete'\n+ dispatch(completeLabError(completeLabErrors))\n+ } else {\n+ labToComplete.completedOn = new Date(Date.now().valueOf()).toISOString()\n+ labToComplete.status = 'completed'\n+ const completedLab = await LabRepository.saveOrUpdate(labToComplete)\n+ dispatch(cancelLabSuccess(completedLab))\n+\n+ if (onSuccess) {\n+ onSuccess(completedLab)\n+ }\n+ }\n+}\n+\n+export const updateLab = (labToUpdate: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\n+ dispatch,\n+) => {\n+ dispatch(updateLabStart())\n+ const updatedLab = await LabRepository.saveOrUpdate(labToUpdate)\n+ dispatch(updateLabSuccess(updatedLab))\n+\n+ if (onSuccess) {\n+ onSuccess(updatedLab)\n+ }\n+}\n+\n+export default labSlice.reducer\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/requests/NewLabRequest.tsx",
"new_path": "src/labs/requests/NewLabRequest.tsx",
"diff": "@@ -6,19 +6,19 @@ import PatientRepository from 'clients/db/PatientRepository'\nimport Patient from 'model/Patient'\nimport TextInputWithLabelFormGroup from 'components/input/TextInputWithLabelFormGroup'\nimport { useHistory } from 'react-router'\n-import LabRepository from 'clients/db/LabRepository'\nimport Lab from 'model/Lab'\nimport TextFieldWithLabelFormGroup from 'components/input/TextFieldWithLabelFormGroup'\nimport useAddBreadcrumbs from 'breadcrumbs/useAddBreadcrumbs'\n+import { useDispatch, useSelector } from 'react-redux'\n+import { requestLab } from 'labs/lab-slice'\n+import { RootState } from 'store'\nconst NewLabRequest = () => {\nconst { t } = useTranslation()\n+ const dispatch = useDispatch()\nconst history = useHistory()\nuseTitle(t('labs.requests.new'))\n-\n- const [isPatientInvalid, setIsPatientInvalid] = useState(false)\n- const [isTypeInvalid, setIsTypeInvalid] = useState(false)\n- const [typeFeedback, setTypeFeedback] = useState()\n+ const { status, error } = useSelector((state: RootState) => state.lab)\nconst [newLabRequest, setNewLabRequest] = useState({\npatientId: '',\n@@ -60,34 +60,21 @@ const NewLabRequest = () => {\nconst onSave = async () => {\nconst newLab = newLabRequest as Lab\n-\n- if (!newLab.patientId) {\n- setIsPatientInvalid(true)\n- return\n+ const onSuccess = (createdLab: Lab) => {\n+ history.push(`/labs/${createdLab.id}`)\n}\n- if (!newLab.type) {\n- setIsTypeInvalid(true)\n- setTypeFeedback(t('labs.requests.error.typeRequired'))\n- return\n+ dispatch(requestLab(newLab, onSuccess))\n}\n- newLab.requestedOn = new Date(Date.now().valueOf()).toISOString()\n- const createdLab = await LabRepository.save(newLab)\n- history.push(`/labs/${createdLab.id}`)\n- }\nconst onCancel = () => {\nhistory.push('/labs')\n}\nreturn (\n<>\n- {(isTypeInvalid || isPatientInvalid) && (\n- <Alert\n- color=\"danger\"\n- title={t('states.error')}\n- message={t('labs.requests.error.unableToRequest')}\n- />\n+ {status === 'error' && (\n+ <Alert color=\"danger\" title={t('states.error')} message={t(error.message || '')} />\n)}\n<form>\n<div className=\"form-group patient-typeahead\">\n@@ -99,7 +86,7 @@ const NewLabRequest = () => {\nonSearch={async (query: string) => PatientRepository.search(query)}\nsearchAccessor=\"fullName\"\nrenderMenuItemChildren={(p: Patient) => <div>{`${p.fullName} (${p.code})`}</div>}\n- isInvalid={isPatientInvalid}\n+ isInvalid={!!error.patient}\n/>\n</div>\n<TextInputWithLabelFormGroup\n@@ -107,8 +94,8 @@ const NewLabRequest = () => {\nlabel={t('labs.lab.type')}\nisRequired\nisEditable\n- isInvalid={isTypeInvalid}\n- feedback={typeFeedback}\n+ isInvalid={!!error.type}\n+ feedback={t(error.type || '')}\nvalue={newLabRequest.type}\nonChange={onLabTypeChange}\n/>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/store/index.ts",
"new_path": "src/store/index.ts",
"diff": "@@ -6,6 +6,7 @@ import appointment from '../scheduling/appointments/appointment-slice'\nimport appointments from '../scheduling/appointments/appointments-slice'\nimport title from '../page-header/title-slice'\nimport user from '../user/user-slice'\n+import lab from '../labs/lab-slice'\nimport breadcrumbs from '../breadcrumbs/breadcrumbs-slice'\nimport components from '../components/component-slice'\n@@ -18,6 +19,7 @@ const reducer = combineReducers({\nappointments,\nbreadcrumbs,\ncomponents,\n+ lab,\n})\nconst store = configureStore({\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor labs to use redux |
288,323 | 12.04.2020 19:15:42 | 18,000 | ce714fa86d9e3b7af67b45bcb80df46fbd8e57c5 | docs: updates documentation for better onboarding | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -24,78 +24,56 @@ React frontend for [HospitalRun](http://hospitalrun.io/): free software for deve\n</div>\n-# Contributing\n+## Contributing\nContributions are always welcome. Before contributing please read our [contributor guide](https://github.com/HospitalRun/hospitalrun-frontend/blob/master/.github/CONTRIBUTING.md).\n-1. Fork this repository to your own GitHub account and then clone it to your local device\n-2. Navigate to the cloned folder: `cd hospitalrun-frontend`\n-3. Install the dependencies: `yarn`\n-4. Run `yarn run start` to build and watch for code changes\n-\n-## Connecting to HospitalRun Server\n-\n-**Note: The following instructions are for connecting to HospitalRun Server during development and are not intended to be for production use. For production deployments, see the deployment instructions.**\n-\n-1. Configure [HospitalRun Server](https://github.com/HospitalRun/hospitalrun-server)\n-2. Start the HospitalRun Development Server\n-3. Copy the `.env.example` file to `.env`\n-4. Change the `REACT_APP_HOSPITALRUN_API` variable to point to the HospitalRun Development Server.\n-\n-## Working on an Issue\n-\n-In order to optimize the workflow and to prevent multiple contributors working on the same issue without interactions, a contributor must ask to be assigned to an issue by one of the core team members: it's enough to ask it inside the specific issue.\n-\n-## How to commit\n-\n-This repo uses Conventional Commits. Commitizen is mandatory for making proper commits. Once you have staged your changes, can run `npm run commit` or `yarn commit` from the root directory in order to commit following our standards.\n-\n<hr />\n-# Behind HospitalRun\n+## Behind HospitalRun\n-## Hosted by\n+### Hosted by\n[<img src=\"https://github.com/openjs-foundation/cross-project-council/blob/master/logos/openjsf-color.png?raw=true\" width=\"120px;\"/>](https://openjsf.org/projects/#atlarge)\n-## Sponsors\n+### Sponsors\n[](https://opencollective.com/hospitalrun/contribute/sponsors-336/checkout)\n-### Big Thanks\n+#### Big Thanks\nCross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][homepage]\n[homepage]: https://saucelabs.com\n-## Backers\n+### Backers\n[](https://opencollective.com/hospitalrun/contribute/backers-335/checkout)\n-## Lead Maintainer\n+### Lead Maintainer\n[<img src=\"https://avatars2.githubusercontent.com/u/1620916?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Maksim Sinik</b></sub>](https://github.com/fox1t)<br />\n-## Core Team\n+### Core Team\n<!-- prettier-ignore -->\n| [<img src=\"https://avatars3.githubusercontent.com/u/25089405?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Stefano Casasola</b></sub>](https://github.com/irvelervel) |[<img src=\"https://avatars2.githubusercontent.com/u/8914893?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Michael Daly</b></sub>](https://github.com/MichaelDalyDev)|[<img src=\"https://avatars1.githubusercontent.com/u/25009192?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Riccardo Gulin</b></sub>](https://github.com/bazuzu666) | [<img src=\"https://avatars3.githubusercontent.com/u/603924?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Grace Lau</b></sub>](https://github.com/lauggh) | [<img src=\"https://avatars3.githubusercontent.com/u/18731800?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Jack Meyer</b></sub>](https://github.com/jackcmeyer) | [<img src=\"https://avatars0.githubusercontent.com/u/6388707?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Matteo Vivona</b></sub>](https://github.com/tehKapa) |\n|---|---|---|---|---|---|\n-## Medical Supervisor\n+### Medical Supervisor\n[<img src=\"https://avatars2.githubusercontent.com/u/24660474?s=460&v=4\" width=\"100px;\"/><br /><sub><b>M.D. Daniele Piccolo</b></sub>](https://it.linkedin.com/in/danielepiccolo)<br />\n-## Contributors\n+### Contributors\n[](https://github.com/HospitalRun/hospitalrun-frontend/graphs/contributors)\n-## Founders\n+### Founders\n<!-- prettier-ignore -->\n| [<img src=\"https://avatars0.githubusercontent.com/u/609052?s=460&v=4\" width=\"100px;\"/><br /><sub><b>John Kleinschmidtr</b></sub>](https://github.com/jkleinsc) | [<img src=\"https://avatars0.githubusercontent.com/u/929261?s=400&v=4\" width=\"100px;\"/><br /><sub><b>Joel Worrall</b></sub>](https://github.com/tangollama) | [<img src=\"https://avatars0.githubusercontent.com/u/1319791?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Joel Glovier</b></sub>](https://github.com/jglovier) |\n|---|---|---|\n-# License\n+## License\nReleased under the [MIT license](LICENSE).\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | docs: updates documentation for better onboarding |
288,381 | 14.04.2020 14:59:59 | -21,600 | 21fe92b6c93dfbb7ae31174f4dd723b0256df98d | style(patient): change new appointment button position | [
{
"change_type": "MODIFY",
"old_path": "src/patients/appointments/AppointmentsList.tsx",
"new_path": "src/patients/appointments/AppointmentsList.tsx",
"diff": "@@ -53,7 +53,7 @@ const AppointmentsList = (props: Props) => {\n}\nreturn (\n- <Container>\n+ <>\n<div className=\"row\">\n<div className=\"col-md-12 d-flex justify-content-end\">\n<Button\n@@ -68,7 +68,7 @@ const AppointmentsList = (props: Props) => {\n</div>\n</div>\n<br />\n-\n+ <Container>\n<form className=\"form\" onSubmit={onSearchFormSubmit}>\n<Row>\n<Column md={10}>\n@@ -94,6 +94,7 @@ const AppointmentsList = (props: Props) => {\n</List>\n</Row>\n</Container>\n+ </>\n)\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | style(patient): change new appointment button position |
288,334 | 14.04.2020 11:30:51 | -7,200 | 9485a0baecc3fa1b0ea3ea628556973aeffaa49f | Updates readme and contributing | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -24,56 +24,121 @@ React frontend for [HospitalRun](http://hospitalrun.io/): free software for deve\n</div>\n-## Contributing\n+# Contributing\nContributions are always welcome. Before contributing please read our [contributor guide](https://github.com/HospitalRun/hospitalrun-frontend/blob/master/.github/CONTRIBUTING.md).\n+1. Fork this repository to your own GitHub account and then clone it to your local device\n+2. Navigate to the cloned folder: `cd hospitalrun-frontend`\n+3. Install the dependencies: `yarn`\n+4. Run `yarn run start` to build and watch for code changes\n+\n+## Connecting to HospitalRun Server\n+\n+**Note: The following instructions are for connecting to HospitalRun Server during development and are not intended to be for production use. For production deployments, see the deployment instructions.**\n+\n+1. Configure [HospitalRun Server](https://github.com/HospitalRun/hospitalrun-server)\n+2. Start the HospitalRun Development Server\n+3. Copy the `.env.example` file to `.env`\n+4. Change the `REACT_APP_HOSPITALRUN_API` variable to point to the HospitalRun Development Server.\n+\n+### Potential Setup Issues\n+\n+Some developers have reported the following errors and the corresponding fixes\n+\n+### Problem with Project Dependency Tree\n+\n+```\n+There might be a problem with the project dependency tree.\n+It is likely not a bug in Create React App, but something you need to fix locally.\n+The react-scripts package provided by Create React App requires a dependency:\n+ \"babel-loader\": \"8.1.0\"\n+Don't try to install it manually: your package manager does it automatically.\n+However, a different version of babel-loader was detected higher up in the tree:\n+ /path/to/hospitalrun/node_modules/babel-loader (version: 8.0.6)\n+Manually installing incompatible versions is known to cause hard-to-debug issues.\n+If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.\n+That will permanently disable this message but you might encounter other issues.\n+To fix the dependency tree, try following the steps below in the exact order:\n+ 1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.\n+ 2. Delete node_modules in your project folder.\n+ 3. Remove \"babel-loader\" from dependencies and/or devDependencies in the package.json file in your project folder.\n+ 4. Run npm install or yarn, depending on the package manager you use.\n+```\n+\n+To fix this issue, add `SKIP_PREFLIGHT_CHECK=true` to the `.env` file.\n+\n+## Running Tests and Linter\n+\n+`yarn test:ci` will run the entire test suite\n+\n+`yarn test` will run the test suite in watch mode\n+\n+`yarn lint` will run the linter\n+\n+`yarn lint:fix` will run the linter and fix fixable errors\n+\n+## Useful Developer Tools\n+\n+- [VSCode](https://code.visualstudio.com/)\n+- [VSCode React Extension Pack](https://marketplace.visualstudio.com/items?itemName=jawandarajbir.react-vscode-extension-pack)\n+- [React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en)\n+- [Redux Developer Tools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en)\n+\n+## Working on an Issue\n+\n+In order to optimize the workflow and to prevent multiple contributors working on the same issue without interactions, a contributor must ask to be assigned to an issue by one of the core team members: it's enough to ask it inside the specific issue.\n+\n+## How to commit\n+\n+This repo uses Conventional Commits. Commitizen is mandatory for making proper commits. Once you have staged your changes, can run `npm run commit` or `yarn commit` from the root directory in order to commit following our standards.\n+\n<hr />\n-## Behind HospitalRun\n+# Behind HospitalRun\n-### Hosted by\n+## Hosted by\n[<img src=\"https://github.com/openjs-foundation/cross-project-council/blob/master/logos/openjsf-color.png?raw=true\" width=\"120px;\"/>](https://openjsf.org/projects/#atlarge)\n-### Sponsors\n+## Sponsors\n[](https://opencollective.com/hospitalrun/contribute/sponsors-336/checkout)\n-#### Big Thanks\n+### Big Thanks\nCross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][homepage]\n[homepage]: https://saucelabs.com\n-### Backers\n+## Backers\n[](https://opencollective.com/hospitalrun/contribute/backers-335/checkout)\n-### Lead Maintainer\n+## Lead Maintainer\n[<img src=\"https://avatars2.githubusercontent.com/u/1620916?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Maksim Sinik</b></sub>](https://github.com/fox1t)<br />\n-### Core Team\n+## Core Team\n<!-- prettier-ignore -->\n| [<img src=\"https://avatars3.githubusercontent.com/u/25089405?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Stefano Casasola</b></sub>](https://github.com/irvelervel) |[<img src=\"https://avatars2.githubusercontent.com/u/8914893?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Michael Daly</b></sub>](https://github.com/MichaelDalyDev)|[<img src=\"https://avatars1.githubusercontent.com/u/25009192?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Riccardo Gulin</b></sub>](https://github.com/bazuzu666) | [<img src=\"https://avatars3.githubusercontent.com/u/603924?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Grace Lau</b></sub>](https://github.com/lauggh) | [<img src=\"https://avatars3.githubusercontent.com/u/18731800?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Jack Meyer</b></sub>](https://github.com/jackcmeyer) | [<img src=\"https://avatars0.githubusercontent.com/u/6388707?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Matteo Vivona</b></sub>](https://github.com/tehKapa) |\n|---|---|---|---|---|---|\n-### Medical Supervisor\n+## Medical Supervisor\n[<img src=\"https://avatars2.githubusercontent.com/u/24660474?s=460&v=4\" width=\"100px;\"/><br /><sub><b>M.D. Daniele Piccolo</b></sub>](https://it.linkedin.com/in/danielepiccolo)<br />\n-### Contributors\n+## Contributors\n[](https://github.com/HospitalRun/hospitalrun-frontend/graphs/contributors)\n-### Founders\n+## Founders\n<!-- prettier-ignore -->\n| [<img src=\"https://avatars0.githubusercontent.com/u/609052?s=460&v=4\" width=\"100px;\"/><br /><sub><b>John Kleinschmidtr</b></sub>](https://github.com/jkleinsc) | [<img src=\"https://avatars0.githubusercontent.com/u/929261?s=400&v=4\" width=\"100px;\"/><br /><sub><b>Joel Worrall</b></sub>](https://github.com/tangollama) | [<img src=\"https://avatars0.githubusercontent.com/u/1319791?s=460&v=4\" width=\"100px;\"/><br /><sub><b>Joel Glovier</b></sub>](https://github.com/jglovier) |\n|---|---|---|\n-## License\n+# License\nReleased under the [MIT license](LICENSE).\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | Updates readme and contributing |
288,334 | 16.04.2020 19:55:40 | -7,200 | 06d3c8692733cc0b301bdf4187adfc1f08930e94 | chore(lint): lint file | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/appointments/AppointmentsList.test.tsx",
"new_path": "src/__tests__/patients/appointments/AppointmentsList.test.tsx",
"diff": "@@ -10,7 +10,7 @@ import { Provider } from 'react-redux'\nimport AppointmentsList from 'patients/appointments/AppointmentsList'\nimport * as components from '@hospitalrun/components'\nimport { act } from 'react-dom/test-utils'\n-import PatientRepository from 'clients/db/PatientRepository'\n+// import PatientRepository from 'clients/db/PatientRepository' # Lint warning: 'PatientRepository' is defined but never used\nconst expectedPatient = {\nid: '123',\n@@ -59,10 +59,7 @@ describe('AppointmentsList', () => {\nconst wrapper = setup()\nact(() => {\n- wrapper\n- .find(components.Button)\n- .at(0)\n- .prop('onClick')()\n+ wrapper.find(components.Button).at(0).prop('onClick')()\n})\nwrapper.update()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | chore(lint): lint file |
288,311 | 30.03.2020 22:16:29 | 14,400 | 57f9d7ac34d5c366a6faeac324809599bf30a953 | feat(newrelatedpersonmodal): update Error Feedback
re | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"new_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"diff": "@@ -143,10 +143,11 @@ describe('Add Related Person Modal', () => {\nwrapper.update()\nconst errorAlert = wrapper.find(Alert)\n+\nexpect(onSaveSpy).not.toHaveBeenCalled()\nexpect(errorAlert).toHaveLength(1)\nexpect(errorAlert.prop('message')).toEqual(\n- 'patient.relatedPersons.error.relatedPersonRequired patient.relatedPersons.error.relationshipTypeRequired',\n+ 'patient.relatedPersons.error.relatedPersonErrorBanner',\n)\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -25,6 +25,7 @@ export default {\nrelatedPerson: 'Related Person',\nrelatedPersons: {\nerror: {\n+ relatedPersonErrorBanner: 'Unable to add new related person.',\nrelatedPersonRequired: 'Related Person is required.',\nrelationshipTypeRequired: 'Relationship Type is required.',\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"new_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"diff": "@@ -19,6 +19,8 @@ const AddRelatedPersonModal = (props: Props) => {\nconst { show, toggle, onCloseButtonClick, onSave } = props\nconst { t } = useTranslation()\nconst [errorMessage, setErrorMessage] = useState('')\n+ const [isRelatedPersonInvalid, setIsRelatedPersonInvalid] = useState(false)\n+ const [isRelationshipInvalid, setIsRelationshipInvalid] = useState(false)\nconst [relatedPerson, setRelatedPerson] = useState({\npatientId: '',\ntype: '',\n@@ -54,6 +56,7 @@ const AddRelatedPersonModal = (props: Props) => {\nsearchAccessor=\"fullName\"\nplaceholder={t('patient.relatedPerson')}\nonChange={onPatientSelect}\n+ isInvalid={isRelatedPersonInvalid}\nonSearch={async (query: string) => PatientRepository.search(query)}\nrenderMenuItemChildren={(p: Patient) => {\nif (patientId() === p.id) {\n@@ -63,6 +66,11 @@ const AddRelatedPersonModal = (props: Props) => {\nreturn <div>{`${p.fullName} (${p.code})`}</div>\n}}\n/>\n+ {isRelatedPersonInvalid && (\n+ <div className=\"text-left ml-3 mt-1 text-small text-danger invalid-feedback d-block\">\n+ {t('patient.relatedPersons.error.relatedPersonRequired')}\n+ </div>\n+ )}\n</div>\n</div>\n</div>\n@@ -73,6 +81,8 @@ const AddRelatedPersonModal = (props: Props) => {\nlabel={t('patient.relatedPersons.relationshipType')}\nvalue={relatedPerson.type}\nisEditable\n+ isInvalid={isRelationshipInvalid}\n+ feedback={t('patient.relatedPersons.error.relationshipTypeRequired')}\nisRequired\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'type')\n@@ -100,19 +110,21 @@ const AddRelatedPersonModal = (props: Props) => {\nicon: 'add',\niconLocation: 'left',\nonClick: () => {\n- let newErrorMessage = ''\n+ let isValid = true\nif (!relatedPerson.patientId) {\n- newErrorMessage += `${t('patient.relatedPersons.error.relatedPersonRequired')} `\n+ isValid = false\n+ setIsRelatedPersonInvalid(true)\n}\nif (!relatedPerson.type) {\n- newErrorMessage += `${t('patient.relatedPersons.error.relationshipTypeRequired')}`\n+ isValid = false\n+ setIsRelationshipInvalid(true)\n}\n- if (!newErrorMessage) {\n+ if (isValid) {\nonSave(relatedPerson as RelatedPerson)\n} else {\n- setErrorMessage(newErrorMessage.trim())\n+ setErrorMessage(t('patient.relatedPersons.error.relatedPersonErrorBanner'))\n}\n},\n}}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(newrelatedpersonmodal): update Error Feedback
re #1925 |
288,323 | 17.04.2020 00:02:46 | 18,000 | 53f93f6d6193dc71bfc4d639b54d1556d645222a | feat(patients): add tests | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"new_path": "src/__tests__/patients/related-persons/AddRelatedPersonModal.test.tsx",
"diff": "@@ -65,7 +65,7 @@ describe('Add Related Person Modal', () => {\n})\nit('should render a relationship type text input', () => {\n- const relationshipTypeTextInput = wrapper.findWhere((w) => w.prop('name') === 'type')\n+ const relationshipTypeTextInput = wrapper.findWhere((w: any) => w.prop('name') === 'type')\nexpect(relationshipTypeTextInput).toHaveLength(1)\nexpect(relationshipTypeTextInput.type()).toBe(TextInputWithLabelFormGroup)\n@@ -115,16 +115,16 @@ describe('Add Related Person Modal', () => {\nwrapper.update()\nact(() => {\n- const relationshipTypeTextInput = wrapper.findWhere((w) => w.prop('name') === 'type')\n+ const relationshipTypeTextInput = wrapper.findWhere((w: any) => w.prop('name') === 'type')\nrelationshipTypeTextInput.prop('onChange')({ target: { value: 'relationship' } })\n})\nwrapper.update()\nact(() => {\n- ;(wrapper.find(Modal).prop('successButton') as any).onClick(\n- {} as React.MouseEvent<HTMLButtonElement, MouseEvent>,\n- )\n+ const { onClick } = wrapper.find(Modal).prop('successButton') as any\n+ onClick({} as React.MouseEvent<HTMLButtonElement, MouseEvent>)\n})\n+\nexpect(onSaveSpy).toHaveBeenCalledTimes(1)\nexpect(onSaveSpy).toHaveBeenCalledWith({\npatientId: '123',\n@@ -132,7 +132,13 @@ describe('Add Related Person Modal', () => {\n})\n})\n- it('should display an error message if given name or relationship type is not entered.', () => {\n+ it('should display an error message if given name is not entered', () => {\n+ act(() => {\n+ const patientTypeahead = wrapper.find(Typeahead)\n+ patientTypeahead.prop('onChange')([{ id: '123' }])\n+ })\n+ wrapper.update()\n+\nact(() => {\nwrapper\n.find(Modal)\n@@ -143,11 +149,37 @@ describe('Add Related Person Modal', () => {\nwrapper.update()\nconst errorAlert = wrapper.find(Alert)\n+ const relationshipTypeTextInput = wrapper.findWhere((w: any) => w.prop('name') === 'type')\n+ expect(errorAlert).toHaveLength(1)\n+ expect(errorAlert.prop('message')).toEqual(\n+ 'patient.relatedPersons.error.unableToAddRelatedPerson',\n+ )\n+ expect(relationshipTypeTextInput.prop('isInvalid')).toBeTruthy()\n+ expect(relationshipTypeTextInput.prop('feedback')).toEqual(\n+ 'patient.relatedPersons.error.relationshipTypeRequired',\n+ )\n+ })\n+\n+ it('should display an error message if relationship type is not entered', () => {\n+ act(() => {\n+ wrapper\n+ .find(Modal)\n+ .prop('successButton')\n+ .onClick({} as React.MouseEvent<HTMLButtonElement, MouseEvent>)\n+ })\n+\n+ wrapper.update()\n- expect(onSaveSpy).not.toHaveBeenCalled()\n+ const errorAlert = wrapper.find(Alert)\n+ const typeahead = wrapper.find(Typeahead)\n+ const typeaheadError = wrapper.find('.related-person-feedback')\nexpect(errorAlert).toHaveLength(1)\nexpect(errorAlert.prop('message')).toEqual(\n- 'patient.relatedPersons.error.relatedPersonErrorBanner',\n+ 'patient.relatedPersons.error.unableToAddRelatedPerson',\n+ )\n+ expect(typeahead.prop('isInvalid')).toBeTruthy()\n+ expect(typeaheadError.text().trim()).toEqual(\n+ 'patient.relatedPersons.error.relatedPersonRequired',\n)\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -25,7 +25,7 @@ export default {\nrelatedPerson: 'Related Person',\nrelatedPersons: {\nerror: {\n- relatedPersonErrorBanner: 'Unable to add new related person.',\n+ unableToAddRelatedPerson: 'Unable to add new related person.',\nrelatedPersonRequired: 'Related Person is required.',\nrelationshipTypeRequired: 'Relationship Type is required.',\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"new_path": "src/patients/related-persons/AddRelatedPersonModal.tsx",
"diff": "@@ -67,7 +67,7 @@ const AddRelatedPersonModal = (props: Props) => {\n}}\n/>\n{isRelatedPersonInvalid && (\n- <div className=\"text-left ml-3 mt-1 text-small text-danger invalid-feedback d-block\">\n+ <div className=\"text-left ml-3 mt-1 text-small text-danger invalid-feedback d-block related-person-feedback\">\n{t('patient.relatedPersons.error.relatedPersonRequired')}\n</div>\n)}\n@@ -124,7 +124,7 @@ const AddRelatedPersonModal = (props: Props) => {\nif (isValid) {\nonSave(relatedPerson as RelatedPerson)\n} else {\n- setErrorMessage(t('patient.relatedPersons.error.relatedPersonErrorBanner'))\n+ setErrorMessage(t('patient.relatedPersons.error.unableToAddRelatedPerson'))\n}\n},\n}}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): add tests |
288,323 | 19.04.2020 01:18:47 | 18,000 | 7ba2e8ea6ffb20b71b9781e27c07e9f6a4d26ac7 | feat(labs): reduxify request, cancel, fetch, and update labs | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/Labs.test.tsx",
"new_path": "src/__tests__/labs/Labs.test.tsx",
"diff": "@@ -34,6 +34,11 @@ describe('Labs', () => {\nuser: { permissions: [Permissions.RequestLab] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ lab: {\n+ lab: { id: 'labId', patientId: 'patientId' } as Lab,\n+ patient: { id: 'patientId', fullName: 'some name' },\n+ error: {},\n+ },\n})\nconst wrapper = mount(\n@@ -74,6 +79,15 @@ describe('Labs', () => {\nuser: { permissions: [Permissions.ViewLab] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ lab: {\n+ lab: {\n+ id: 'labId',\n+ patientId: 'patientId',\n+ requestedOn: new Date().toISOString(),\n+ } as Lab,\n+ patient: { id: 'patientId', fullName: 'some name' },\n+ error: {},\n+ },\n})\nlet wrapper: any\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLab.test.tsx",
"new_path": "src/__tests__/labs/ViewLab.test.tsx",
"diff": "@@ -37,7 +37,7 @@ describe('View Labs', () => {\nlet titleSpy: any\nlet labRepositorySaveSpy: any\nconst expectedDate = new Date()\n- const setup = async (lab: Lab, permissions: Permissions[]) => {\n+ const setup = async (lab: Lab, permissions: Permissions[], error = {}) => {\njest.resetAllMocks()\nDate.now = jest.fn(() => expectedDate.valueOf())\nsetButtonToolBarSpy = jest.fn()\n@@ -54,6 +54,12 @@ describe('View Labs', () => {\nuser: {\npermissions,\n},\n+ lab: {\n+ lab,\n+ patient: mockPatient,\n+ error,\n+ status: Object.keys(error).length > 0 ? 'error' : 'success',\n+ },\n})\nlet wrapper: any\n@@ -133,11 +139,11 @@ describe('View Labs', () => {\n} as Lab\nconst wrapper = await setup(expectedLab, [Permissions.ViewLab])\n- const notesTextField = wrapper.find(TextFieldWithLabelFormGroup).at(0)\n+ const resultTextField = wrapper.find(TextFieldWithLabelFormGroup).at(0)\n- expect(notesTextField).toBeDefined()\n- expect(notesTextField.prop('label')).toEqual('labs.lab.result')\n- expect(notesTextField.prop('value')).toEqual(expectedLab.result)\n+ expect(resultTextField).toBeDefined()\n+ expect(resultTextField.prop('label')).toEqual('labs.lab.result')\n+ expect(resultTextField.prop('value')).toEqual(expectedLab.result)\n})\nit('should display the notes in the notes text field', async () => {\n@@ -151,6 +157,20 @@ describe('View Labs', () => {\nexpect(notesTextField.prop('value')).toEqual(expectedLab.notes)\n})\n+ it('should display errors', async () => {\n+ const expectedLab = { ...mockLab, status: 'requested' } as Lab\n+ const expectedError = { message: 'some message', result: 'some result feedback' }\n+ const wrapper = await setup(expectedLab, [Permissions.ViewLab], expectedError)\n+\n+ const alert = wrapper.find(Alert)\n+ const resultTextField = wrapper.find(TextFieldWithLabelFormGroup).at(0)\n+ expect(alert.prop('message')).toEqual(expectedError.message)\n+ expect(alert.prop('title')).toEqual('states.error')\n+ expect(alert.prop('color')).toEqual('danger')\n+ expect(resultTextField.prop('isInvalid')).toBeTruthy()\n+ expect(resultTextField.prop('feedback')).toEqual(expectedError.result)\n+ })\n+\ndescribe('requested lab request', () => {\nit('should display a warning badge if the status is requested', async () => {\nconst expectedLab = { ...mockLab, status: 'requested' } as Lab\n@@ -343,31 +363,6 @@ describe('View Labs', () => {\n)\nexpect(history.location.pathname).toEqual('/labs')\n})\n-\n- it('should validate that the result has been filled in', async () => {\n- const wrapper = await setup(mockLab, [\n- Permissions.ViewLab,\n- Permissions.CompleteLab,\n- Permissions.CancelLab,\n- ])\n-\n- const completeButton = wrapper.find(Button).at(1)\n- await act(async () => {\n- const onClick = completeButton.prop('onClick')\n- await onClick()\n- })\n- wrapper.update()\n-\n- const alert = wrapper.find(Alert)\n- const resultField = wrapper.find(TextFieldWithLabelFormGroup).at(0)\n- expect(alert).toHaveLength(1)\n- expect(alert.prop('title')).toEqual('states.error')\n- expect(alert.prop('message')).toEqual('labs.requests.error.unableToComplete')\n- expect(resultField.prop('isInvalid')).toBeTruthy()\n- expect(resultField.prop('feedback')).toEqual('labs.requests.error.resultRequiredToComplete')\n-\n- expect(labRepositorySaveSpy).not.toHaveBeenCalled()\n- })\n})\ndescribe('on cancel', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -38,7 +38,7 @@ describe('View Labs', () => {\n})\n})\n- it('should have New Lab Request as the title', () => {\n+ it('should have the title', () => {\nexpect(titleSpy).toHaveBeenCalledWith('labs.label')\n})\n})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/labs/lab-slice.test.ts",
"diff": "+import thunk from 'redux-thunk'\n+import createMockStore from 'redux-mock-store'\n+import PatientRepository from '../../clients/db/PatientRepository'\n+import LabRepository from '../../clients/db/LabRepository'\n+import Lab from '../../model/Lab'\n+import Patient from '../../model/Patient'\n+import * as labSlice from '../../labs/lab-slice'\n+import { RootState } from '../../store'\n+import { requestLab } from '../../labs/lab-slice'\n+\n+const mockStore = createMockStore<RootState, any>([thunk])\n+\n+describe('lab slice', () => {\n+ describe('reducers', () => {\n+ describe('fetchLabStart', () => {\n+ it('should set status to loading', async () => {\n+ const labStore = labSlice.default(undefined, labSlice.fetchLabStart())\n+\n+ expect(labStore.status).toEqual('loading')\n+ })\n+ })\n+\n+ describe('fetchLabSuccess', () => {\n+ it('should set the lab, patient, and status to success', () => {\n+ const expectedLab = { id: 'labId' } as Lab\n+ const expectedPatient = { id: 'patientId' } as Patient\n+\n+ const labStore = labSlice.default(\n+ undefined,\n+ labSlice.fetchLabSuccess({ lab: expectedLab, patient: expectedPatient }),\n+ )\n+\n+ expect(labStore.status).toEqual('success')\n+ expect(labStore.lab).toEqual(expectedLab)\n+ expect(labStore.patient).toEqual(expectedPatient)\n+ })\n+ })\n+\n+ describe('updateLabStart', () => {\n+ it('should set status to loading', async () => {\n+ const labStore = labSlice.default(undefined, labSlice.updateLabStart())\n+\n+ expect(labStore.status).toEqual('loading')\n+ })\n+ })\n+\n+ describe('updateLabSuccess', () => {\n+ it('should set the lab and status to success', () => {\n+ const expectedLab = { id: 'labId' } as Lab\n+\n+ const labStore = labSlice.default(undefined, labSlice.updateLabSuccess(expectedLab))\n+\n+ expect(labStore.status).toEqual('success')\n+ expect(labStore.lab).toEqual(expectedLab)\n+ })\n+ })\n+\n+ describe('requestLabStart', () => {\n+ it('should set status to loading', async () => {\n+ const labStore = labSlice.default(undefined, labSlice.requestLabStart())\n+\n+ expect(labStore.status).toEqual('loading')\n+ })\n+ })\n+\n+ describe('requestLabSuccess', () => {\n+ it('should set the lab and status to success', () => {\n+ const expectedLab = { id: 'labId' } as Lab\n+\n+ const labStore = labSlice.default(undefined, labSlice.requestLabSuccess(expectedLab))\n+\n+ expect(labStore.status).toEqual('success')\n+ expect(labStore.lab).toEqual(expectedLab)\n+ })\n+ })\n+\n+ describe('requestLabError', () => {\n+ const expectedError = { message: 'some message', result: 'some result error' }\n+\n+ const labStore = labSlice.default(undefined, labSlice.requestLabError(expectedError))\n+\n+ expect(labStore.status).toEqual('error')\n+ expect(labStore.error).toEqual(expectedError)\n+ })\n+\n+ describe('completeLabStart', () => {\n+ it('should set status to loading', async () => {\n+ const labStore = labSlice.default(undefined, labSlice.completeLabStart())\n+\n+ expect(labStore.status).toEqual('loading')\n+ })\n+ })\n+\n+ describe('completeLabSuccess', () => {\n+ it('should set the lab and status to success', () => {\n+ const expectedLab = { id: 'labId' } as Lab\n+\n+ const labStore = labSlice.default(undefined, labSlice.completeLabSuccess(expectedLab))\n+\n+ expect(labStore.status).toEqual('success')\n+ expect(labStore.lab).toEqual(expectedLab)\n+ })\n+ })\n+\n+ describe('completeLabError', () => {\n+ const expectedError = { message: 'some message', result: 'some result error' }\n+\n+ const labStore = labSlice.default(undefined, labSlice.completeLabError(expectedError))\n+\n+ expect(labStore.status).toEqual('error')\n+ expect(labStore.error).toEqual(expectedError)\n+ })\n+\n+ describe('cancelLabStart', () => {\n+ it('should set status to loading', async () => {\n+ const labStore = labSlice.default(undefined, labSlice.cancelLabStart())\n+\n+ expect(labStore.status).toEqual('loading')\n+ })\n+ })\n+\n+ describe('cancelLabSuccess', () => {\n+ it('should set the lab and status to success', () => {\n+ const expectedLab = { id: 'labId' } as Lab\n+\n+ const labStore = labSlice.default(undefined, labSlice.cancelLabSuccess(expectedLab))\n+\n+ expect(labStore.status).toEqual('success')\n+ expect(labStore.lab).toEqual(expectedLab)\n+ })\n+ })\n+ })\n+\n+ describe('fetch lab', () => {\n+ let patientRepositorySpy: any\n+ let labRepositoryFindSpy: any\n+\n+ const mockLab = {\n+ id: 'labId',\n+ patientId: 'patientId',\n+ } as Lab\n+\n+ const mockPatient = {\n+ id: 'patientId',\n+ } as Patient\n+\n+ beforeEach(() => {\n+ patientRepositorySpy = jest.spyOn(PatientRepository, 'find').mockResolvedValue(mockPatient)\n+ labRepositoryFindSpy = jest.spyOn(LabRepository, 'find').mockResolvedValue(mockLab)\n+ })\n+\n+ it('should fetch the lab and patient', async () => {\n+ const store = mockStore()\n+\n+ await store.dispatch(labSlice.fetchLab(mockLab.id))\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.fetchLabStart())\n+ expect(labRepositoryFindSpy).toHaveBeenCalledWith(mockLab.id)\n+ expect(patientRepositorySpy).toHaveBeenCalledWith(mockLab.patientId)\n+ expect(actions[1]).toEqual(labSlice.fetchLabSuccess({ lab: mockLab, patient: mockPatient }))\n+ })\n+ })\n+\n+ describe('cancel lab', () => {\n+ const mockLab = {\n+ id: 'labId',\n+ patientId: 'patientId',\n+ } as Lab\n+ let labRepositorySaveOrUpdateSpy: any\n+\n+ beforeEach(() => {\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\n+ labRepositorySaveOrUpdateSpy = jest\n+ .spyOn(LabRepository, 'saveOrUpdate')\n+ .mockResolvedValue(mockLab)\n+ })\n+\n+ it('should cancel a lab', async () => {\n+ const expectedCanceledLab = {\n+ ...mockLab,\n+ canceledOn: new Date(Date.now()).toISOString(),\n+ status: 'canceled',\n+ } as Lab\n+\n+ const store = mockStore()\n+\n+ await store.dispatch(labSlice.cancelLab(mockLab))\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.cancelLabStart())\n+ expect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedCanceledLab)\n+ expect(actions[1]).toEqual(labSlice.cancelLabSuccess(expectedCanceledLab))\n+ })\n+\n+ it('should call on success callback if provided', async () => {\n+ const expectedCanceledLab = {\n+ ...mockLab,\n+ canceledOn: new Date(Date.now()).toISOString(),\n+ status: 'canceled',\n+ } as Lab\n+\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+ await store.dispatch(labSlice.cancelLab(mockLab, onSuccessSpy))\n+\n+ expect(onSuccessSpy).toHaveBeenCalledWith(expectedCanceledLab)\n+ })\n+ })\n+\n+ describe('complete lab', () => {\n+ const mockLab = {\n+ id: 'labId',\n+ patientId: 'patientId',\n+ result: 'lab result',\n+ } as Lab\n+ let labRepositorySaveOrUpdateSpy: any\n+\n+ beforeEach(() => {\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\n+ labRepositorySaveOrUpdateSpy = jest\n+ .spyOn(LabRepository, 'saveOrUpdate')\n+ .mockResolvedValue(mockLab)\n+ })\n+\n+ it('should complete a lab', async () => {\n+ const expectedCompletedLab = {\n+ ...mockLab,\n+ completedOn: new Date(Date.now()).toISOString(),\n+ status: 'completed',\n+ result: 'lab result',\n+ } as Lab\n+\n+ const store = mockStore()\n+\n+ await store.dispatch(labSlice.completeLab(mockLab))\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.completeLabStart())\n+ expect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedCompletedLab)\n+ expect(actions[1]).toEqual(labSlice.completeLabSuccess(expectedCompletedLab))\n+ })\n+\n+ it('should call on success callback if provided', async () => {\n+ const expectedCompletedLab = {\n+ ...mockLab,\n+ completedOn: new Date(Date.now()).toISOString(),\n+ status: 'completed',\n+ } as Lab\n+\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+ await store.dispatch(labSlice.completeLab(mockLab, onSuccessSpy))\n+\n+ expect(onSuccessSpy).toHaveBeenCalledWith(expectedCompletedLab)\n+ })\n+\n+ it('should validate that the lab can be completed', async () => {\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+ await store.dispatch(labSlice.completeLab({ id: 'labId' } as Lab, onSuccessSpy))\n+ const actions = store.getActions()\n+\n+ expect(actions[1]).toEqual(\n+ labSlice.completeLabError({\n+ result: 'labs.requests.error.resultRequiredToComplete',\n+ message: 'labs.requests.error.unableToComplete',\n+ }),\n+ )\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ })\n+ })\n+\n+ describe('request lab', () => {\n+ const mockLab = {\n+ id: 'labId',\n+ type: 'labType',\n+ patientId: 'patientId',\n+ } as Lab\n+ let labRepositorySaveSpy: any\n+\n+ beforeEach(() => {\n+ jest.restoreAllMocks()\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\n+ labRepositorySaveSpy = jest.spyOn(LabRepository, 'save').mockResolvedValue(mockLab)\n+ })\n+\n+ it('should request a new lab', async () => {\n+ const store = mockStore()\n+ const expectedRequestedLab = {\n+ ...mockLab,\n+ requestedOn: new Date(Date.now()).toISOString(),\n+ status: 'requested',\n+ } as Lab\n+\n+ await store.dispatch(requestLab(mockLab))\n+\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.requestLabStart())\n+ expect(labRepositorySaveSpy).toHaveBeenCalledWith(expectedRequestedLab)\n+ expect(actions[1]).toEqual(labSlice.requestLabSuccess(expectedRequestedLab))\n+ })\n+\n+ it('should execute the onSuccess callback if provided', async () => {\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(requestLab(mockLab, onSuccessSpy))\n+\n+ expect(onSuccessSpy).toHaveBeenCalledWith(mockLab)\n+ })\n+\n+ it('should validate that the lab can be requested', async () => {\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+ await store.dispatch(requestLab({} as Lab, onSuccessSpy))\n+\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.requestLabStart())\n+ expect(actions[1]).toEqual(\n+ labSlice.requestLabError({\n+ patient: 'labs.requests.error.patientRequired',\n+ type: 'labs.requests.error.typeRequired',\n+ message: 'labs.requests.error.unableToRequest',\n+ }),\n+ )\n+ expect(labRepositorySaveSpy).not.toHaveBeenCalled()\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ })\n+ })\n+\n+ describe('update lab', () => {\n+ const mockLab = {\n+ id: 'labId',\n+ patientId: 'patientId',\n+ result: 'lab result',\n+ } as Lab\n+ let labRepositorySaveOrUpdateSpy: any\n+\n+ const expectedUpdatedLab = {\n+ ...mockLab,\n+ type: 'some other type',\n+ }\n+\n+ beforeEach(() => {\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\n+ labRepositorySaveOrUpdateSpy = jest\n+ .spyOn(LabRepository, 'saveOrUpdate')\n+ .mockResolvedValue(expectedUpdatedLab)\n+ })\n+\n+ it('should update the lab', async () => {\n+ const store = mockStore()\n+\n+ await store.dispatch(labSlice.updateLab(expectedUpdatedLab))\n+ const actions = store.getActions()\n+\n+ expect(actions[0]).toEqual(labSlice.updateLabStart())\n+ expect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedUpdatedLab)\n+ expect(actions[1]).toEqual(labSlice.updateLabSuccess(expectedUpdatedLab))\n+ })\n+\n+ it('should call the onSuccess callback if successful', async () => {\n+ const store = mockStore()\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(labSlice.updateLab(expectedUpdatedLab, onSuccessSpy))\n+\n+ expect(onSuccessSpy).toHaveBeenCalledWith(expectedUpdatedLab)\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"new_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"diff": "@@ -25,7 +25,7 @@ describe('New Lab Request', () => {\nconst history = createMemoryHistory()\nbeforeEach(() => {\n- const store = mockStore({ title: '' })\n+ const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\ntitleSpy = jest.spyOn(titleUtil, 'default')\nhistory.push('/labs/new')\n@@ -48,7 +48,7 @@ describe('New Lab Request', () => {\nconst history = createMemoryHistory()\nbeforeEach(() => {\n- const store = mockStore({ title: '' })\n+ const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\nhistory.push('/labs/new')\nwrapper = mount(\n@@ -106,13 +106,50 @@ describe('New Lab Request', () => {\n})\n})\n+ describe('errors', () => {\n+ let wrapper: ReactWrapper\n+ const history = createMemoryHistory()\n+ const error = {\n+ message: 'some message',\n+ patient: 'some patient message',\n+ type: 'some type error',\n+ }\n+\n+ beforeEach(() => {\n+ history.push('/labs/new')\n+ const store = mockStore({ title: '', lab: { status: 'error', error } })\n+ wrapper = mount(\n+ <Provider store={store}>\n+ <Router history={history}>\n+ <NewLabRequest />\n+ </Router>\n+ </Provider>,\n+ )\n+ })\n+\n+ it('should display errors', () => {\n+ const alert = wrapper.find(Alert)\n+ const typeInput = wrapper.find(TextInputWithLabelFormGroup)\n+ const patientTypeahead = wrapper.find(Typeahead)\n+\n+ expect(alert.prop('message')).toEqual(error.message)\n+ expect(alert.prop('title')).toEqual('states.error')\n+ expect(alert.prop('color')).toEqual('danger')\n+\n+ expect(patientTypeahead.prop('isInvalid')).toBeTruthy()\n+\n+ expect(typeInput.prop('feedback')).toEqual(error.type)\n+ expect(typeInput.prop('isInvalid')).toBeTruthy()\n+ })\n+ })\n+\ndescribe('on cancel', () => {\nlet wrapper: ReactWrapper\nconst history = createMemoryHistory()\nbeforeEach(() => {\nhistory.push('/labs/new')\n- const store = mockStore({ title: '' })\n+ const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\nwrapper = mount(\n<Provider store={store}>\n<Router history={history}>\n@@ -158,7 +195,7 @@ describe('New Lab Request', () => {\n.mockResolvedValue([{ id: expectedLab.patientId, fullName: 'some full name' }] as Patient[])\nhistory.push('/labs/new')\n- const store = mockStore({ title: '' })\n+ const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\nwrapper = mount(\n<Provider store={store}>\n<Router history={history}>\n@@ -206,66 +243,5 @@ describe('New Lab Request', () => {\n)\nexpect(history.location.pathname).toEqual(`/labs/${expectedLab.id}`)\n})\n-\n- it('should require a patient', async () => {\n- const typeInput = wrapper.find(TextInputWithLabelFormGroup)\n- act(() => {\n- const onChange = typeInput.prop('onChange') as any\n- onChange({ currentTarget: { value: expectedLab.type } })\n- })\n-\n- const notesTextField = wrapper.find(TextFieldWithLabelFormGroup)\n- act(() => {\n- const onChange = notesTextField.prop('onChange') as any\n- onChange({ currentTarget: { value: expectedLab.notes } })\n- })\n- wrapper.update()\n-\n- const saveButton = wrapper.find(Button).at(0)\n- await act(async () => {\n- const onClick = saveButton.prop('onClick') as any\n- await onClick()\n- })\n- wrapper.update()\n-\n- const alert = wrapper.find(Alert)\n- const typeahead = wrapper.find(Typeahead)\n- expect(alert).toBeDefined()\n- expect(alert.prop('title')).toEqual('states.error')\n- expect(alert.prop('message')).toEqual('labs.requests.error.unableToRequest')\n- expect(typeahead.prop('isInvalid')).toBeTruthy()\n- expect(labRepositorySaveSpy).not.toHaveBeenCalled()\n- })\n-\n- it('should require a type', async () => {\n- const patientTypeahead = wrapper.find(Typeahead)\n- await act(async () => {\n- const onChange = patientTypeahead.prop('onChange')\n- await onChange([{ id: expectedLab.patientId }] as Patient[])\n- })\n-\n- const notesTextField = wrapper.find(TextFieldWithLabelFormGroup)\n- act(() => {\n- const onChange = notesTextField.prop('onChange') as any\n- onChange({ currentTarget: { value: expectedLab.notes } })\n- })\n- wrapper.update()\n-\n- const saveButton = wrapper.find(Button).at(0)\n- await act(async () => {\n- const onClick = saveButton.prop('onClick') as any\n- await onClick()\n- })\n- wrapper.update()\n-\n- const alert = wrapper.find(Alert)\n- const typeInput = wrapper.find(TextInputWithLabelFormGroup)\n- expect(alert).toBeDefined()\n- expect(alert.prop('title')).toEqual('states.error')\n- expect(alert.prop('message')).toEqual('labs.requests.error.unableToRequest')\n- expect(typeInput.prop('isInvalid')).toBeTruthy()\n- expect(typeInput.prop('feedback')).toEqual('labs.requests.error.typeRequired')\n- expect(labRepositorySaveSpy).not.toHaveBeenCalled()\n- })\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLab.tsx",
"new_path": "src/labs/ViewLab.tsx",
"diff": "@@ -48,8 +48,6 @@ const ViewLab = () => {\nsetLabToView({ ...lab })\nsetIsEditable(lab.status === 'requested')\n}\n- console.log('lab change')\n- console.log(lab)\n}, [lab])\nconst onResultChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/lab-slice.ts",
"new_path": "src/labs/lab-slice.ts",
"diff": "@@ -112,12 +112,13 @@ export const requestLab = (newLab: Lab, onSuccess?: (lab: Lab) => void): AppThun\nlabRequestError.message = 'labs.requests.error.unableToRequest'\ndispatch(requestLabError(labRequestError))\n} else {\n+ newLab.status = 'requested'\nnewLab.requestedOn = new Date(Date.now().valueOf()).toISOString()\n- const requestedLab = await LabRepository.saveOrUpdate(newLab)\n+ const requestedLab = await LabRepository.save(newLab)\ndispatch(requestLabSuccess(requestedLab))\nif (onSuccess) {\n- onSuccess(newLab)\n+ onSuccess(requestedLab)\n}\n}\n}\n@@ -150,7 +151,7 @@ const validateCompleteLab = (labToComplete: Lab): Error => {\nexport const completeLab = (labToComplete: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\ndispatch,\n) => {\n- dispatch(cancelLabStart())\n+ dispatch(completeLabStart())\nconst completeLabErrors = validateCompleteLab(labToComplete)\nif (Object.keys(completeLabErrors).length > 0) {\n@@ -160,7 +161,7 @@ export const completeLab = (labToComplete: Lab, onSuccess?: (lab: Lab) => void):\nlabToComplete.completedOn = new Date(Date.now().valueOf()).toISOString()\nlabToComplete.status = 'completed'\nconst completedLab = await LabRepository.saveOrUpdate(labToComplete)\n- dispatch(cancelLabSuccess(completedLab))\n+ dispatch(completeLabSuccess(completedLab))\nif (onSuccess) {\nonSuccess(completedLab)\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(labs): reduxify request, cancel, fetch, and update labs |
288,323 | 20.04.2020 23:19:06 | 18,000 | a58c90b41dd663b248af4bbb71c13aa3f3026db0 | test(labs): remove * as import | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/lab-slice.test.ts",
"new_path": "src/__tests__/labs/lab-slice.test.ts",
"diff": "@@ -4,9 +4,26 @@ import PatientRepository from '../../clients/db/PatientRepository'\nimport LabRepository from '../../clients/db/LabRepository'\nimport Lab from '../../model/Lab'\nimport Patient from '../../model/Patient'\n-import * as labSlice from '../../labs/lab-slice'\n+import labSlice, {\n+ requestLab,\n+ fetchLabStart,\n+ fetchLabSuccess,\n+ updateLabStart,\n+ updateLabSuccess,\n+ requestLabStart,\n+ requestLabSuccess,\n+ completeLabStart,\n+ completeLabSuccess,\n+ cancelLabStart,\n+ cancelLabSuccess,\n+ fetchLab,\n+ cancelLab,\n+ completeLab,\n+ completeLabError,\n+ requestLabError,\n+ updateLab,\n+} from '../../labs/lab-slice'\nimport { RootState } from '../../store'\n-import { requestLab } from '../../labs/lab-slice'\nconst mockStore = createMockStore<RootState, any>([thunk])\n@@ -14,7 +31,7 @@ describe('lab slice', () => {\ndescribe('reducers', () => {\ndescribe('fetchLabStart', () => {\nit('should set status to loading', async () => {\n- const labStore = labSlice.default(undefined, labSlice.fetchLabStart())\n+ const labStore = labSlice(undefined, fetchLabStart())\nexpect(labStore.status).toEqual('loading')\n})\n@@ -25,9 +42,9 @@ describe('lab slice', () => {\nconst expectedLab = { id: 'labId' } as Lab\nconst expectedPatient = { id: 'patientId' } as Patient\n- const labStore = labSlice.default(\n+ const labStore = labSlice(\nundefined,\n- labSlice.fetchLabSuccess({ lab: expectedLab, patient: expectedPatient }),\n+ fetchLabSuccess({ lab: expectedLab, patient: expectedPatient }),\n)\nexpect(labStore.status).toEqual('success')\n@@ -38,7 +55,7 @@ describe('lab slice', () => {\ndescribe('updateLabStart', () => {\nit('should set status to loading', async () => {\n- const labStore = labSlice.default(undefined, labSlice.updateLabStart())\n+ const labStore = labSlice(undefined, updateLabStart())\nexpect(labStore.status).toEqual('loading')\n})\n@@ -48,7 +65,7 @@ describe('lab slice', () => {\nit('should set the lab and status to success', () => {\nconst expectedLab = { id: 'labId' } as Lab\n- const labStore = labSlice.default(undefined, labSlice.updateLabSuccess(expectedLab))\n+ const labStore = labSlice(undefined, updateLabSuccess(expectedLab))\nexpect(labStore.status).toEqual('success')\nexpect(labStore.lab).toEqual(expectedLab)\n@@ -57,7 +74,7 @@ describe('lab slice', () => {\ndescribe('requestLabStart', () => {\nit('should set status to loading', async () => {\n- const labStore = labSlice.default(undefined, labSlice.requestLabStart())\n+ const labStore = labSlice(undefined, requestLabStart())\nexpect(labStore.status).toEqual('loading')\n})\n@@ -67,7 +84,7 @@ describe('lab slice', () => {\nit('should set the lab and status to success', () => {\nconst expectedLab = { id: 'labId' } as Lab\n- const labStore = labSlice.default(undefined, labSlice.requestLabSuccess(expectedLab))\n+ const labStore = labSlice(undefined, requestLabSuccess(expectedLab))\nexpect(labStore.status).toEqual('success')\nexpect(labStore.lab).toEqual(expectedLab)\n@@ -77,7 +94,7 @@ describe('lab slice', () => {\ndescribe('requestLabError', () => {\nconst expectedError = { message: 'some message', result: 'some result error' }\n- const labStore = labSlice.default(undefined, labSlice.requestLabError(expectedError))\n+ const labStore = labSlice(undefined, requestLabError(expectedError))\nexpect(labStore.status).toEqual('error')\nexpect(labStore.error).toEqual(expectedError)\n@@ -85,7 +102,7 @@ describe('lab slice', () => {\ndescribe('completeLabStart', () => {\nit('should set status to loading', async () => {\n- const labStore = labSlice.default(undefined, labSlice.completeLabStart())\n+ const labStore = labSlice(undefined, completeLabStart())\nexpect(labStore.status).toEqual('loading')\n})\n@@ -95,7 +112,7 @@ describe('lab slice', () => {\nit('should set the lab and status to success', () => {\nconst expectedLab = { id: 'labId' } as Lab\n- const labStore = labSlice.default(undefined, labSlice.completeLabSuccess(expectedLab))\n+ const labStore = labSlice(undefined, completeLabSuccess(expectedLab))\nexpect(labStore.status).toEqual('success')\nexpect(labStore.lab).toEqual(expectedLab)\n@@ -105,7 +122,7 @@ describe('lab slice', () => {\ndescribe('completeLabError', () => {\nconst expectedError = { message: 'some message', result: 'some result error' }\n- const labStore = labSlice.default(undefined, labSlice.completeLabError(expectedError))\n+ const labStore = labSlice(undefined, completeLabError(expectedError))\nexpect(labStore.status).toEqual('error')\nexpect(labStore.error).toEqual(expectedError)\n@@ -113,7 +130,7 @@ describe('lab slice', () => {\ndescribe('cancelLabStart', () => {\nit('should set status to loading', async () => {\n- const labStore = labSlice.default(undefined, labSlice.cancelLabStart())\n+ const labStore = labSlice(undefined, cancelLabStart())\nexpect(labStore.status).toEqual('loading')\n})\n@@ -123,7 +140,7 @@ describe('lab slice', () => {\nit('should set the lab and status to success', () => {\nconst expectedLab = { id: 'labId' } as Lab\n- const labStore = labSlice.default(undefined, labSlice.cancelLabSuccess(expectedLab))\n+ const labStore = labSlice(undefined, cancelLabSuccess(expectedLab))\nexpect(labStore.status).toEqual('success')\nexpect(labStore.lab).toEqual(expectedLab)\n@@ -152,13 +169,13 @@ describe('lab slice', () => {\nit('should fetch the lab and patient', async () => {\nconst store = mockStore()\n- await store.dispatch(labSlice.fetchLab(mockLab.id))\n+ await store.dispatch(fetchLab(mockLab.id))\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.fetchLabStart())\n+ expect(actions[0]).toEqual(fetchLabStart())\nexpect(labRepositoryFindSpy).toHaveBeenCalledWith(mockLab.id)\nexpect(patientRepositorySpy).toHaveBeenCalledWith(mockLab.patientId)\n- expect(actions[1]).toEqual(labSlice.fetchLabSuccess({ lab: mockLab, patient: mockPatient }))\n+ expect(actions[1]).toEqual(fetchLabSuccess({ lab: mockLab, patient: mockPatient }))\n})\n})\n@@ -185,12 +202,12 @@ describe('lab slice', () => {\nconst store = mockStore()\n- await store.dispatch(labSlice.cancelLab(mockLab))\n+ await store.dispatch(cancelLab(mockLab))\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.cancelLabStart())\n+ expect(actions[0]).toEqual(cancelLabStart())\nexpect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedCanceledLab)\n- expect(actions[1]).toEqual(labSlice.cancelLabSuccess(expectedCanceledLab))\n+ expect(actions[1]).toEqual(cancelLabSuccess(expectedCanceledLab))\n})\nit('should call on success callback if provided', async () => {\n@@ -202,7 +219,7 @@ describe('lab slice', () => {\nconst store = mockStore()\nconst onSuccessSpy = jest.fn()\n- await store.dispatch(labSlice.cancelLab(mockLab, onSuccessSpy))\n+ await store.dispatch(cancelLab(mockLab, onSuccessSpy))\nexpect(onSuccessSpy).toHaveBeenCalledWith(expectedCanceledLab)\n})\n@@ -233,12 +250,12 @@ describe('lab slice', () => {\nconst store = mockStore()\n- await store.dispatch(labSlice.completeLab(mockLab))\n+ await store.dispatch(completeLab(mockLab))\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.completeLabStart())\n+ expect(actions[0]).toEqual(completeLabStart())\nexpect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedCompletedLab)\n- expect(actions[1]).toEqual(labSlice.completeLabSuccess(expectedCompletedLab))\n+ expect(actions[1]).toEqual(completeLabSuccess(expectedCompletedLab))\n})\nit('should call on success callback if provided', async () => {\n@@ -250,7 +267,7 @@ describe('lab slice', () => {\nconst store = mockStore()\nconst onSuccessSpy = jest.fn()\n- await store.dispatch(labSlice.completeLab(mockLab, onSuccessSpy))\n+ await store.dispatch(completeLab(mockLab, onSuccessSpy))\nexpect(onSuccessSpy).toHaveBeenCalledWith(expectedCompletedLab)\n})\n@@ -258,11 +275,11 @@ describe('lab slice', () => {\nit('should validate that the lab can be completed', async () => {\nconst store = mockStore()\nconst onSuccessSpy = jest.fn()\n- await store.dispatch(labSlice.completeLab({ id: 'labId' } as Lab, onSuccessSpy))\n+ await store.dispatch(completeLab({ id: 'labId' } as Lab, onSuccessSpy))\nconst actions = store.getActions()\nexpect(actions[1]).toEqual(\n- labSlice.completeLabError({\n+ completeLabError({\nresult: 'labs.requests.error.resultRequiredToComplete',\nmessage: 'labs.requests.error.unableToComplete',\n}),\n@@ -297,9 +314,9 @@ describe('lab slice', () => {\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.requestLabStart())\n+ expect(actions[0]).toEqual(requestLabStart())\nexpect(labRepositorySaveSpy).toHaveBeenCalledWith(expectedRequestedLab)\n- expect(actions[1]).toEqual(labSlice.requestLabSuccess(expectedRequestedLab))\n+ expect(actions[1]).toEqual(requestLabSuccess(expectedRequestedLab))\n})\nit('should execute the onSuccess callback if provided', async () => {\n@@ -318,9 +335,9 @@ describe('lab slice', () => {\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.requestLabStart())\n+ expect(actions[0]).toEqual(requestLabStart())\nexpect(actions[1]).toEqual(\n- labSlice.requestLabError({\n+ requestLabError({\npatient: 'labs.requests.error.patientRequired',\ntype: 'labs.requests.error.typeRequired',\nmessage: 'labs.requests.error.unableToRequest',\n@@ -354,19 +371,19 @@ describe('lab slice', () => {\nit('should update the lab', async () => {\nconst store = mockStore()\n- await store.dispatch(labSlice.updateLab(expectedUpdatedLab))\n+ await store.dispatch(updateLab(expectedUpdatedLab))\nconst actions = store.getActions()\n- expect(actions[0]).toEqual(labSlice.updateLabStart())\n+ expect(actions[0]).toEqual(updateLabStart())\nexpect(labRepositorySaveOrUpdateSpy).toHaveBeenCalledWith(expectedUpdatedLab)\n- expect(actions[1]).toEqual(labSlice.updateLabSuccess(expectedUpdatedLab))\n+ expect(actions[1]).toEqual(updateLabSuccess(expectedUpdatedLab))\n})\nit('should call the onSuccess callback if successful', async () => {\nconst store = mockStore()\nconst onSuccessSpy = jest.fn()\n- await store.dispatch(labSlice.updateLab(expectedUpdatedLab, onSuccessSpy))\n+ await store.dispatch(updateLab(expectedUpdatedLab, onSuccessSpy))\nexpect(onSuccessSpy).toHaveBeenCalledWith(expectedUpdatedLab)\n})\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test(labs): remove * as import |
288,323 | 21.04.2020 18:00:54 | 18,000 | f292926c46941159ba807bef3986f21a1ca34762 | feat(patients): set max date in date of birth date picker | [
{
"change_type": "MODIFY",
"old_path": ".env.example",
"new_path": ".env.example",
"diff": "-REACT_APP_HOSPITALRUN_API=http://0.0.0.0:3001\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/input/DatePickerWithLabelFormGroup.test.tsx",
"new_path": "src/__tests__/components/input/DatePickerWithLabelFormGroup.test.tsx",
"diff": "@@ -26,6 +26,7 @@ describe('date picker with label form group', () => {\nit('should render and date time picker', () => {\nconst expectedName = 'test'\n+ const expectedDate = new Date()\nconst wrapper = shallow(\n<DatePickerWithLabelFormGroup\nname={expectedName}\n@@ -33,11 +34,13 @@ describe('date picker with label form group', () => {\nvalue={new Date()}\nisEditable\nonChange={jest.fn()}\n+ maxDate={expectedDate}\n/>,\n)\nconst input = wrapper.find(DateTimePicker)\nexpect(input).toHaveLength(1)\n+ expect(input.prop('maxDate')).toEqual(expectedDate)\n})\nit('should render disabled is isDisable disabled is true', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/GeneralInformation.test.tsx",
"new_path": "src/__tests__/patients/GeneralInformation.test.tsx",
"diff": "@@ -51,6 +51,8 @@ describe('General Information, without isEditable', () => {\nlet history = createMemoryHistory()\nbeforeEach(() => {\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\n+ jest.restoreAllMocks()\nhistory = createMemoryHistory()\nwrapper = mount(\n<Router history={history}>\n@@ -59,10 +61,6 @@ describe('General Information, without isEditable', () => {\n)\n})\n- beforeEach(() => {\n- jest.restoreAllMocks()\n- })\n-\nit('should render the prefix', () => {\nconst prefixInput = wrapper.findWhere((w: any) => w.prop('name') === 'prefix')\nexpect(prefixInput.prop('value')).toEqual(patient.prefix)\n@@ -123,6 +121,7 @@ describe('General Information, without isEditable', () => {\nconst dateOfBirthInput = wrapper.findWhere((w: any) => w.prop('name') === 'dateOfBirth')\nexpect(dateOfBirthInput.prop('value')).toEqual(new Date(patient.dateOfBirth))\nexpect(dateOfBirthInput.prop('label')).toEqual('patient.dateOfBirth')\n+ expect(dateOfBirthInput.prop('maxDate')).toEqual(new Date(Date.now()))\nexpect(dateOfBirthInput.prop('isEditable')).toBeFalsy()\n})\n@@ -208,6 +207,8 @@ describe('General Information, isEditable', () => {\nconst onFieldChange = jest.fn()\nbeforeEach(() => {\n+ jest.restoreAllMocks()\n+ Date.now = jest.fn().mockReturnValue(new Date().valueOf())\nhistory = createMemoryHistory()\nwrapper = mount(\n<Router history={history}>\n@@ -216,10 +217,6 @@ describe('General Information, isEditable', () => {\n)\n})\n- beforeEach(() => {\n- jest.restoreAllMocks()\n- })\n-\nconst expectedPrefix = 'expectedPrefix'\nconst expectedGivenName = 'expectedGivenName'\nconst expectedFamilyName = 'expectedFamilyName'\n@@ -348,6 +345,7 @@ describe('General Information, isEditable', () => {\nexpect(dateOfBirthInput.prop('value')).toEqual(new Date(patient.dateOfBirth))\nexpect(dateOfBirthInput.prop('label')).toEqual('patient.dateOfBirth')\nexpect(dateOfBirthInput.prop('isEditable')).toBeTruthy()\n+ expect(dateOfBirthInput.prop('maxDate')).toEqual(new Date(Date.now()))\nact(() => {\ndateOfBirthInput.prop('onChange')(new Date(expectedDateOfBirth))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"new_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"diff": "@@ -10,10 +10,21 @@ interface Props {\nisRequired?: boolean\nfeedback?: string\nisInvalid?: boolean\n+ maxDate?: Date\n}\nconst DatePickerWithLabelFormGroup = (props: Props) => {\n- const { onChange, label, name, isEditable, value, isRequired, feedback, isInvalid } = props\n+ const {\n+ onChange,\n+ label,\n+ name,\n+ isEditable,\n+ value,\n+ isRequired,\n+ feedback,\n+ isInvalid,\n+ maxDate,\n+ } = props\nconst id = `${name}DatePicker`\nreturn (\n<div className=\"form-group\">\n@@ -22,6 +33,7 @@ const DatePickerWithLabelFormGroup = (props: Props) => {\ndateFormat=\"MM/dd/yyyy\"\ndateFormatCalendar=\"LLLL yyyy\"\ndropdownMode=\"scroll\"\n+ maxDate={maxDate}\nselected={value}\ntimeIntervals={30}\nwithPortal={false}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/GeneralInformation.tsx",
"new_path": "src/patients/GeneralInformation.tsx",
"diff": "@@ -167,6 +167,7 @@ const GeneralInformation = (props: Props) => {\n: undefined\n}\nisInvalid={invalidFields?.dateOfBirth}\n+ maxDate={new Date(Date.now().valueOf())}\nfeedback={feedbackFields?.dateOfBirth}\nonChange={(date: Date) => {\nonDateOfBirthChange(date)\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): set max date in date of birth date picker (#2002) |
288,334 | 22.04.2020 13:08:49 | -7,200 | 4cf2cbb8ecdb312a541217f1a7b56249dd0e3b49 | ci(node): add node 14 support on yarn stage | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci.yml",
"new_path": ".github/workflows/ci.yml",
"diff": "@@ -43,7 +43,7 @@ jobs:\nruns-on: ${{ matrix.os }}\nstrategy:\nmatrix:\n- node-version: [12.x, 13.x]\n+ node-version: [12.x, 14.x]\nos: [ubuntu-latest, windows-latest, macOS-latest]\n# exclude:\n# - os: windows-latest\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | ci(node): add node 14 support on yarn stage |
288,350 | 22.04.2020 22:43:29 | -19,080 | 88ec61c3c9afa1f9a1c1a7e62d7b84ed1cd72015 | feat(viewlabs): sort Labs by requestedOn field | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -13,6 +13,7 @@ import LabRepository from 'clients/db/LabRepository'\nimport Lab from 'model/Lab'\nimport format from 'date-fns/format'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\n+import SortRequest from 'clients/db/SortRequest'\nimport * as titleUtil from '../../page-header/useTitle'\nconst mockStore = configureMockStore([thunk])\n@@ -160,4 +161,37 @@ describe('View Labs', () => {\nexpect(history.location.pathname).toEqual(`/labs/${expectedLab.id}`)\n})\n})\n+\n+ describe('sort Request', () => {\n+ let findAllSpy: any\n+ beforeEach(async () => {\n+ const store = mockStore({\n+ title: '',\n+ user: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ })\n+ findAllSpy = jest.spyOn(LabRepository, 'findAll')\n+ findAllSpy.mockResolvedValue([])\n+ await act(async () => {\n+ await mount(\n+ <Provider store={store}>\n+ <Router history={createMemoryHistory()}>\n+ <ViewLabs />\n+ </Router>\n+ </Provider>,\n+ )\n+ })\n+ })\n+\n+ it('should have called findAll with sort request', () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [\n+ {\n+ field: 'requestedOn',\n+ direction: 'desc',\n+ },\n+ ],\n+ }\n+ expect(findAllSpy).toHaveBeenCalledWith(sortRequest)\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLabs.tsx",
"new_path": "src/labs/ViewLabs.tsx",
"diff": "@@ -6,6 +6,7 @@ import { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\nimport { Button } from '@hospitalrun/components'\nimport { useHistory } from 'react-router'\nimport LabRepository from 'clients/db/LabRepository'\n+import SortRequest from 'clients/db/SortRequest'\nimport Lab from 'model/Lab'\nimport { useSelector } from 'react-redux'\nimport Permissions from 'model/Permissions'\n@@ -38,7 +39,15 @@ const ViewLabs = () => {\nuseEffect(() => {\nconst fetch = async () => {\n- const fetchedLabs = await LabRepository.findAll()\n+ const sortRequest: SortRequest = {\n+ sorts: [\n+ {\n+ field: 'requestedOn',\n+ direction: 'desc',\n+ },\n+ ],\n+ }\n+ const fetchedLabs = await LabRepository.findAll(sortRequest)\nsetLabs(fetchedLabs)\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewlabs): sort Labs by requestedOn field (#2004) |
288,307 | 23.04.2020 01:28:54 | -3,600 | d5a16b115709725fc8d474def9df98d8b874fac3 | feat(appointments) reason field no longer labelled as a required | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/input/TextFieldWithLabelFormGroup.test.tsx",
"new_path": "src/__tests__/components/input/TextFieldWithLabelFormGroup.test.tsx",
"diff": "@@ -24,6 +24,25 @@ describe('text field with label form group', () => {\nexpect(label.prop('text')).toEqual(expectedName)\n})\n+ it('should render label as required if isRequired is true', () => {\n+ const expectedName = 'test'\n+ const expectedRequired = true\n+ const wrapper = shallow(\n+ <TextFieldWithLabelFormGroup\n+ name={expectedName}\n+ label=\"test\"\n+ value=\"\"\n+ isEditable\n+ isRequired={expectedRequired}\n+ onChange={jest.fn()}\n+ />,\n+ )\n+\n+ const label = wrapper.find(Label)\n+ expect(label).toHaveLength(1)\n+ expect(label.prop('isRequired')).toBeTruthy()\n+ })\n+\nit('should render a text field', () => {\nconst expectedName = 'test'\nconst wrapper = shallow(\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/input/TextFieldWithLabelFormGroup.tsx",
"new_path": "src/components/input/TextFieldWithLabelFormGroup.tsx",
"diff": "@@ -14,11 +14,11 @@ interface Props {\n}\nconst TextFieldWithLabelFormGroup = (props: Props) => {\n- const { value, label, name, isEditable, isInvalid, feedback, onChange } = props\n+ const { value, label, name, isEditable, isInvalid, isRequired, feedback, onChange } = props\nconst id = `${name}TextField`\nreturn (\n<div className=\"form-group\">\n- <Label text={label} htmlFor={id} isRequired />\n+ <Label text={label} htmlFor={id} isRequired={isRequired} />\n<TextField\nrows={4}\nvalue={value}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(appointments) reason field no longer labelled as a required (#2003) |
288,353 | 23.04.2020 09:47:43 | -7,200 | 224a63fdd8b8ec5b7125cc776f20215302b6f25a | fix(breadcrumb label): edit Appointment label on breadcrumb
Added mssing scheduling.appointments.editAppointment label and
scheduling.appointments.deleteAppointment label
Fix | [
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/scheduling/index.ts",
"new_path": "src/locales/enUs/translations/scheduling/index.ts",
"diff": "@@ -5,6 +5,8 @@ export default {\nlabel: 'Appointments',\nnew: 'New Appointment',\nschedule: 'Appointment Schedule',\n+ editAppointment: 'Edit Appointment',\n+ deleteAppointment: 'Delete Appointment',\n},\nappointment: {\nstartDate: 'Start Date',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(breadcrumb label): edit Appointment label on breadcrumb
Added mssing scheduling.appointments.editAppointment label and
scheduling.appointments.deleteAppointment label
Fix #1996 |
288,353 | 24.04.2020 14:42:24 | -7,200 | 2ce192bb6989b9ba4c804c339f519be72ec26c04 | feat(add french language): add French language ot locales list | [
{
"change_type": "MODIFY",
"old_path": "src/i18n.ts",
"new_path": "src/i18n.ts",
"diff": "@@ -6,6 +6,7 @@ import translationAR from './locales/ar/translations'\nimport translationDE from './locales/de/translations'\nimport translationEnUs from './locales/enUs/translations'\nimport translationES from './locales/es/translations'\n+import translationFR from './locales/fr/translations'\nimport translationIN from './locales/in/translations'\nimport translationJA from './locales/ja/translations'\nimport translationPtBR from './locales/ptBr/translations'\n@@ -25,6 +26,9 @@ const resources = {\nes: {\ntranslation: translationES,\n},\n+ fr: {\n+ translation: translationFR,\n+ },\nin: {\ntranslation: translationIN,\n},\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/fr/translations/dashboard/index.ts",
"diff": "+export default {\n+ dashboard: {\n+ label: 'Tableau de bord',\n+ },\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/fr/translations/index.ts",
"diff": "+import actions from './actions'\n+import dashboard from './dashboard'\n+import patient from './patient'\n+import patients from './patients'\n+import scheduling from './scheduling'\n+import states from './states'\n+import sex from './sex'\n+import labs from './labs'\n+\n+export default {\n+ ...actions,\n+ ...dashboard,\n+ ...patient,\n+ ...patients,\n+ ...scheduling,\n+ ...states,\n+ ...sex,\n+ ...labs,\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/fr/translations/sex/index.ts",
"diff": "+export default {\n+ sex: {\n+ male: 'Homme',\n+ female: 'Femme',\n+ other: 'Autre',\n+ unknown: 'Inconnu',\n+ },\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(add french language): add French language ot locales list
#1888 |
288,323 | 25.04.2020 22:56:28 | 18,000 | 5cfbc3295d2142f6e6787890b2915cbfb6868aa1 | fix: fixes warnings/errors appearing in console | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/HospitalRun.test.tsx",
"new_path": "src/__tests__/HospitalRun.test.tsx",
"diff": "@@ -411,7 +411,7 @@ describe('HospitalRun', () => {\n})\ndescribe('/labs', () => {\n- it('should render the Labs component when /labs is accessed', () => {\n+ it('should render the Labs component when /labs is accessed', async () => {\njest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\nconst store = mockStore({\ntitle: 'test',\n@@ -420,18 +420,22 @@ describe('HospitalRun', () => {\ncomponents: { sidebarCollapsed: false },\n})\n- const wrapper = mount(\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await mount(\n<Provider store={store}>\n<MemoryRouter initialEntries={['/labs']}>\n<HospitalRun />\n</MemoryRouter>\n</Provider>,\n)\n+ })\n+ wrapper.update()\nexpect(wrapper.find(ViewLabs)).toHaveLength(1)\n})\n- it('should render the dasboard if the user does not have permissions to view labs', () => {\n+ it('should render the dashboard if the user does not have permissions to view labs', () => {\njest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\nconst store = mockStore({\ntitle: 'test',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/page-header/ButtonBarProvider.test.tsx",
"new_path": "src/__tests__/page-header/ButtonBarProvider.test.tsx",
"diff": "import '../../__mocks__/matchMediaMock'\n-import React from 'react'\n+import React, { useEffect } from 'react'\nimport { renderHook } from '@testing-library/react-hooks'\nimport {\nButtonBarProvider,\n@@ -16,7 +16,10 @@ describe('Button Bar Provider', () => {\nconst { result } = renderHook(\n() => {\nconst update = useButtonToolbarSetter()\n+ useEffect(() => {\nupdate(expectedButtons)\n+ }, [update])\n+\nreturn useButtons()\n},\n{ wrapper },\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLab.tsx",
"new_path": "src/labs/ViewLab.tsx",
"diff": "@@ -98,14 +98,14 @@ const ViewLab = () => {\n}\nbuttons.push(\n- <Button className=\"mr-2\" color=\"success\" onClick={onUpdate}>\n+ <Button className=\"mr-2\" color=\"success\" onClick={onUpdate} key=\"actions.update\">\n{t('actions.update')}\n</Button>,\n)\nif (permissions.includes(Permissions.CompleteLab)) {\nbuttons.push(\n- <Button className=\"mr-2\" onClick={onComplete} color=\"primary\">\n+ <Button className=\"mr-2\" onClick={onComplete} color=\"primary\" key=\"labs.requests.complete\">\n{t('labs.requests.complete')}\n</Button>,\n)\n@@ -113,7 +113,7 @@ const ViewLab = () => {\nif (permissions.includes(Permissions.CancelLab)) {\nbuttons.push(\n- <Button onClick={onCancel} color=\"danger\">\n+ <Button onClick={onCancel} color=\"danger\" key=\"labs.requests.cancel\">\n{t('labs.requests.cancel')}\n</Button>,\n)\n@@ -199,7 +199,7 @@ const ViewLab = () => {\nvalue={labToView.result}\nisEditable={isEditable}\nisInvalid={!!error.result}\n- feedback={t(error.result || '')}\n+ feedback={t(error.result as string)}\nonChange={onResultChange}\n/>\n<TextFieldWithLabelFormGroup\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLabs.tsx",
"new_path": "src/labs/ViewLabs.tsx",
"diff": "-import React, { useState, useEffect } from 'react'\n+import React, { useState, useEffect, useCallback } from 'react'\nimport useTitle from 'page-header/useTitle'\nimport { useTranslation } from 'react-i18next'\nimport format from 'date-fns/format'\n@@ -21,21 +21,25 @@ const ViewLabs = () => {\nconst { permissions } = useSelector((state: RootState) => state.user)\nconst [labs, setLabs] = useState<Lab[]>([])\n- const getButtons = () => {\n+ const getButtons = useCallback(() => {\nconst buttons: React.ReactNode[] = []\nif (permissions.includes(Permissions.RequestLab)) {\nbuttons.push(\n- <Button icon=\"add\" onClick={() => history.push('/labs/new')} outlined color=\"success\">\n+ <Button\n+ icon=\"add\"\n+ onClick={() => history.push('/labs/new')}\n+ outlined\n+ color=\"success\"\n+ key=\"lab.requests.new\"\n+ >\n{t('labs.requests.new')}\n</Button>,\n)\n}\nreturn buttons\n- }\n-\n- setButtons(getButtons())\n+ }, [permissions, history, t])\nuseEffect(() => {\nconst fetch = async () => {\n@@ -51,8 +55,13 @@ const ViewLabs = () => {\nsetLabs(fetchedLabs)\n}\n+ setButtons(getButtons())\nfetch()\n- }, [])\n+\n+ return () => {\n+ setButtons([])\n+ }\n+ }, [getButtons, setButtons])\nconst onTableRowClick = (lab: Lab) => {\nhistory.push(`/labs/${lab.id}`)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/requests/NewLabRequest.tsx",
"new_path": "src/labs/requests/NewLabRequest.tsx",
"diff": "@@ -95,7 +95,7 @@ const NewLabRequest = () => {\nisRequired\nisEditable\nisInvalid={!!error.type}\n- feedback={t(error.type || '')}\n+ feedback={t(error.type as string)}\nvalue={newLabRequest.type}\nonChange={onLabTypeChange}\n/>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/Patients.tsx",
"new_path": "src/patients/list/Patients.tsx",
"diff": "@@ -22,17 +22,6 @@ const Patients = () => {\nconst { patients, isLoading } = useSelector((state: RootState) => state.patients)\nconst setButtonToolBar = useButtonToolbarSetter()\n- setButtonToolBar([\n- <Button\n- key=\"newPatientButton\"\n- outlined\n- color=\"success\"\n- icon=\"patient-add\"\n- onClick={() => history.push('/patients/new')}\n- >\n- {t('patients.newPatient')}\n- </Button>,\n- ])\nconst [searchText, setSearchText] = useState<string>('')\n@@ -45,14 +34,35 @@ const Patients = () => {\nuseEffect(() => {\ndispatch(fetchPatients())\n+ setButtonToolBar([\n+ <Button\n+ key=\"newPatientButton\"\n+ outlined\n+ color=\"success\"\n+ icon=\"patient-add\"\n+ onClick={() => history.push('/patients/new')}\n+ >\n+ {t('patients.newPatient')}\n+ </Button>,\n+ ])\n+\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, setButtonToolBar])\n+ }, [dispatch, setButtonToolBar, t, history])\nconst loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\n-\n- const listBody = (\n+ const table = (\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light \">\n+ <tr>\n+ <th>{t('patient.code')}</th>\n+ <th>{t('patient.givenName')}</th>\n+ <th>{t('patient.familyName')}</th>\n+ <th>{t('patient.sex')}</th>\n+ <th>{t('patient.dateOfBirth')}</th>\n+ </tr>\n+ </thead>\n<tbody>\n{patients.map((p) => (\n<tr key={p.id} onClick={() => history.push(`/patients/${p.id}`)}>\n@@ -64,20 +74,6 @@ const Patients = () => {\n</tr>\n))}\n</tbody>\n- )\n-\n- const list = (\n- <table className=\"table table-hover\">\n- <thead className=\"thead-light \">\n- <tr>\n- <th>{t('patient.code')}</th>\n- <th>{t('patient.givenName')}</th>\n- <th>{t('patient.familyName')}</th>\n- <th>{t('patient.sex')}</th>\n- <th>{t('patient.dateOfBirth')}</th>\n- </tr>\n- </thead>\n- {isLoading ? loadingIndicator : listBody}\n</table>\n)\n@@ -99,7 +95,7 @@ const Patients = () => {\n</Column>\n</Row>\n- <Row>{list}</Row>\n+ <Row> {isLoading ? loadingIndicator : table}</Row>\n</Container>\n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/view/ViewPatient.tsx",
"new_path": "src/patients/view/ViewPatient.tsx",
"diff": "@@ -40,6 +40,18 @@ const ViewPatient = () => {\nconst setButtonToolBar = useButtonToolbarSetter()\n+ const breadcrumbs = [\n+ { i18nKey: 'patients.label', location: '/patients' },\n+ { text: getPatientFullName(patient), location: `/patients/${patient.id}` },\n+ ]\n+ useAddBreadcrumbs(breadcrumbs, true)\n+\n+ const { id } = useParams()\n+ useEffect(() => {\n+ if (id) {\n+ dispatch(fetchPatient(id))\n+ }\n+\nconst buttons = []\nif (permissions.includes(Permissions.WritePatients)) {\nbuttons.push(\n@@ -59,22 +71,10 @@ const ViewPatient = () => {\nsetButtonToolBar(buttons)\n- const breadcrumbs = [\n- { i18nKey: 'patients.label', location: '/patients' },\n- { text: getPatientFullName(patient), location: `/patients/${patient.id}` },\n- ]\n- useAddBreadcrumbs(breadcrumbs, true)\n-\n- const { id } = useParams()\n- useEffect(() => {\n- if (id) {\n- dispatch(fetchPatient(id))\n- }\n-\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, id, setButtonToolBar])\n+ }, [dispatch, id, setButtonToolBar, history, patient.id, permissions, t])\nif (isLoading || !patient) {\nreturn <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\n"
},
{
"change_type": "MODIFY",
"old_path": "src/scheduling/appointments/Appointments.tsx",
"new_path": "src/scheduling/appointments/Appointments.tsx",
"diff": "@@ -28,6 +28,10 @@ const Appointments = () => {\nconst { appointments } = useSelector((state: RootState) => state.appointments)\nconst [events, setEvents] = useState<Event[]>([])\nconst setButtonToolBar = useButtonToolbarSetter()\n+ useAddBreadcrumbs(breadcrumbs, true)\n+\n+ useEffect(() => {\n+ dispatch(fetchAppointments())\nsetButtonToolBar([\n<Button\nkey=\"newAppointmentButton\"\n@@ -39,15 +43,11 @@ const Appointments = () => {\n{t('scheduling.appointments.new')}\n</Button>,\n])\n- useAddBreadcrumbs(breadcrumbs, true)\n-\n- useEffect(() => {\n- dispatch(fetchAppointments())\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, setButtonToolBar])\n+ }, [dispatch, setButtonToolBar, history, t])\nuseEffect(() => {\nconst getAppointments = async () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/scheduling/appointments/view/ViewAppointment.tsx",
"new_path": "src/scheduling/appointments/view/ViewAppointment.tsx",
"diff": "@@ -21,9 +21,14 @@ const ViewAppointment = () => {\nconst { appointment, patient, isLoading } = useSelector((state: RootState) => state.appointment)\nconst { permissions } = useSelector((state: RootState) => state.user)\nconst [showDeleteConfirmation, setShowDeleteConfirmation] = useState<boolean>(false)\n-\nconst setButtonToolBar = useButtonToolbarSetter()\n+ const breadcrumbs = [\n+ { i18nKey: 'scheduling.appointments.label', location: '/appointments' },\n+ { text: getAppointmentLabel(appointment), location: `/patients/${appointment.id}` },\n+ ]\n+ useAddBreadcrumbs(breadcrumbs, true)\n+\nconst onAppointmentDeleteButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {\nevent.preventDefault()\nsetShowDeleteConfirmation(true)\n@@ -39,6 +44,7 @@ const ViewAppointment = () => {\nsetShowDeleteConfirmation(false)\n}\n+ useEffect(() => {\nconst buttons = []\nif (permissions.includes(Permissions.WriteAppointments)) {\nbuttons.push(\n@@ -70,12 +76,7 @@ const ViewAppointment = () => {\n}\nsetButtonToolBar(buttons)\n-\n- const breadcrumbs = [\n- { i18nKey: 'scheduling.appointments.label', location: '/appointments' },\n- { text: getAppointmentLabel(appointment), location: `/patients/${appointment.id}` },\n- ]\n- useAddBreadcrumbs(breadcrumbs, true)\n+ }, [appointment.id, history, permissions, setButtonToolBar, t])\nuseEffect(() => {\nif (id) {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix: fixes warnings/errors appearing in console |
288,323 | 25.04.2020 23:03:59 | 18,000 | 6f5f9f97e8cf47a2f0d5ac3211d804f348ab561a | fix: adds missing translations | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/scheduling/appointments/new/NewAppointment.test.tsx",
"new_path": "src/__tests__/scheduling/appointments/new/NewAppointment.test.tsx",
"diff": "@@ -195,7 +195,7 @@ describe('New Appointment', () => {\nexpect(mockedComponents.Toast).toHaveBeenCalledWith(\n'success',\n'states.success',\n- `scheduling.appointment.successfullyCreated ${expectedNewAppointment.id}`,\n+ `scheduling.appointment.successfullyCreated`,\n)\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/scheduling/index.ts",
"new_path": "src/locales/enUs/translations/scheduling/index.ts",
"diff": "@@ -7,6 +7,7 @@ export default {\nschedule: 'Appointment Schedule',\neditAppointment: 'Edit Appointment',\ndeleteAppointment: 'Delete Appointment',\n+ viewAppointment: 'View Appointment',\n},\nappointment: {\nstartDate: 'Start Date',\n@@ -27,6 +28,8 @@ export default {\n},\nreason: 'Reason',\npatient: 'Patient',\n+ deleteConfirmationMessage: 'Are you sure that you want to delete this appointment?',\n+ successfullyCreated: 'Successfully created appointment.',\n},\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/scheduling/appointments/new/NewAppointment.tsx",
"new_path": "src/scheduling/appointments/new/NewAppointment.tsx",
"diff": "@@ -42,11 +42,7 @@ const NewAppointment = () => {\nconst onNewAppointmentSaveSuccess = (newAppointment: Appointment) => {\nhistory.push(`/appointments/${newAppointment.id}`)\n- Toast(\n- 'success',\n- t('states.success'),\n- `${t('scheduling.appointment.successfullyCreated')} ${newAppointment.id}`,\n- )\n+ Toast('success', t('states.success'), `${t('scheduling.appointment.successfullyCreated')}`)\n}\nconst onSave = () => {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix: adds missing translations |
288,323 | 23.04.2020 21:38:38 | 18,000 | e48a87c62bd9f323dcc455c58ea982ef8110063c | refactor(patients): rename files | [
{
"change_type": "MODIFY",
"old_path": "src/HospitalRun.tsx",
"new_path": "src/HospitalRun.tsx",
"diff": "@@ -13,7 +13,7 @@ import Labs from 'labs/Labs'\nimport Sidebar from './components/Sidebar'\nimport Permissions from './model/Permissions'\nimport Dashboard from './dashboard/Dashboard'\n-import Patients from './patients/list/Patients'\n+import ViewPatients from './patients/list/ViewPatients'\nimport NewPatient from './patients/new/NewPatient'\nimport EditPatient from './patients/edit/EditPatient'\nimport ViewPatient from './patients/view/ViewPatient'\n@@ -51,7 +51,7 @@ const HospitalRun = () => {\nisAuthenticated={permissions.includes(Permissions.ReadPatients)}\nexact\npath=\"/patients\"\n- component={Patients}\n+ component={ViewPatients}\n/>\n<PrivateRoute\nisAuthenticated={permissions.includes(Permissions.WritePatients)}\n"
},
{
"change_type": "RENAME",
"old_path": "src/__tests__/patients/list/Patients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -10,7 +10,7 @@ import { mocked } from 'ts-jest/utils'\nimport { act } from 'react-dom/test-utils'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\n-import Patients from '../../../patients/list/Patients'\n+import ViewPatients from '../../../patients/list/ViewPatients'\nimport PatientRepository from '../../../clients/db/PatientRepository'\nimport * as patientSlice from '../../../patients/patients-slice'\n@@ -41,7 +41,7 @@ describe('Patients', () => {\nreturn mount(\n<Provider store={store}>\n<MemoryRouter>\n- <Patients />\n+ <ViewPatients />\n</MemoryRouter>\n</Provider>,\n)\n"
},
{
"change_type": "RENAME",
"old_path": "src/patients/list/Patients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -13,7 +13,7 @@ import useDebounce from '../../hooks/debounce'\nconst breadcrumbs = [{ i18nKey: 'patients.label', location: '/patients' }]\n-const Patients = () => {\n+const ViewPatients = () => {\nconst { t } = useTranslation()\nconst history = useHistory()\nuseTitle(t('patients.label'))\n@@ -100,4 +100,4 @@ const Patients = () => {\n)\n}\n-export default Patients\n+export default ViewPatients\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(patients): rename files |
288,334 | 26.04.2020 20:45:18 | -7,200 | 6d1f5a4912dcd9cc905d1478db1f49fb3b824f2c | chore(deps): bump components from 1.2.0 to 1.3.0 | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"private\": false,\n\"license\": \"MIT\",\n\"dependencies\": {\n- \"@hospitalrun/components\": \"^1.2.0\",\n+ \"@hospitalrun/components\": \"^1.3.0\",\n\"@reduxjs/toolkit\": \"~1.3.0\",\n\"@types/pouchdb-find\": \"~6.3.4\",\n\"bootstrap\": \"~4.4.1\",\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | chore(deps): bump components from 1.2.0 to 1.3.0 |
288,261 | 26.04.2020 22:24:21 | -3,600 | 4a7515aa80312faa4a05fe5d74c8a74e50f8b6cf | feat(localization): add portuguese language | [
{
"change_type": "MODIFY",
"old_path": "src/locales/ptBr/translations/index.ts",
"new_path": "src/locales/ptBr/translations/index.ts",
"diff": "@@ -5,6 +5,7 @@ import patients from './patients'\nimport scheduling from './scheduling'\nimport states from './states'\nimport sex from './sex'\n+import labs from './labs'\nexport default {\n...actions,\n@@ -14,4 +15,5 @@ export default {\n...scheduling,\n...states,\n...sex,\n+ ...labs,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/ptBr/translations/patients/index.ts",
"new_path": "src/locales/ptBr/translations/patients/index.ts",
"diff": "export default {\npatients: {\nlabel: 'Pacientes',\n+ patientsList: 'Lista de pacientes',\nviewPatients: 'Exibir pacientes',\nviewPatient: 'Ver paciente',\nnewPatient: 'Novo Paciente',\n+ successfullyCreated: 'Paciente criado com sucesso',\n+ successfullyAddedNote: 'Adicionou uma nova nota com sucesso',\n+ successfullyAddedRelatedPerson: 'Adicionou uma pessoa relacionada com sucesso',\n},\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(localization): add portuguese language (#2018) |
288,350 | 28.04.2020 21:28:12 | -19,080 | dff2b3e44ee076f8154290fe9183106d6fe3f231 | feat(viewpatients): add paging feature in ViewPatients component
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -10,25 +10,39 @@ import { mocked } from 'ts-jest/utils'\nimport { act } from 'react-dom/test-utils'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\n+import Page from 'clients/Page'\n+import { Unsorted } from 'clients/db/SortRequest'\nimport ViewPatients from '../../../patients/list/ViewPatients'\nimport PatientRepository from '../../../clients/db/PatientRepository'\nimport * as patientSlice from '../../../patients/patients-slice'\n+import Patient from '../../../model/Patient'\n+import { UnpagedRequest } from '../../../clients/db/PageRequest'\nconst middlewares = [thunk]\nconst mockStore = configureStore(middlewares)\ndescribe('Patients', () => {\n- const patients = [\n+ const patients: Page<Patient> = {\n+ content: [\n{\nid: '123',\nfullName: 'test test',\n+ isApproximateDateOfBirth: false,\ngivenName: 'test',\nfamilyName: 'test',\ncode: 'P12345',\nsex: 'male',\ndateOfBirth: new Date().toISOString(),\n+ phoneNumber: '99999999',\n+ createdAt: new Date().toISOString(),\n+ updatedAt: new Date().toISOString(),\n+ rev: '',\n},\n- ]\n+ ],\n+ hasNext: false,\n+ hasPrevious: false,\n+ pageRequest: UnpagedRequest,\n+ }\nconst mockedPatientRepository = mocked(PatientRepository, true)\nconst setup = (isLoading?: boolean) => {\n@@ -36,6 +50,7 @@ describe('Patients', () => {\npatients: {\npatients,\nisLoading,\n+ pageRequest: UnpagedRequest,\n},\n})\nreturn mount(\n@@ -80,12 +95,12 @@ describe('Patients', () => {\nexpect(tableHeaders.at(3).text()).toEqual('patient.sex')\nexpect(tableHeaders.at(4).text()).toEqual('patient.dateOfBirth')\n- expect(tableColumns.at(0).text()).toEqual(patients[0].code)\n- expect(tableColumns.at(1).text()).toEqual(patients[0].givenName)\n- expect(tableColumns.at(2).text()).toEqual(patients[0].familyName)\n- expect(tableColumns.at(3).text()).toEqual(patients[0].sex)\n+ expect(tableColumns.at(0).text()).toEqual(patients.content[0].code)\n+ expect(tableColumns.at(1).text()).toEqual(patients.content[0].givenName)\n+ expect(tableColumns.at(2).text()).toEqual(patients.content[0].familyName)\n+ expect(tableColumns.at(3).text()).toEqual(patients.content[0].sex)\nexpect(tableColumns.at(4).text()).toEqual(\n- format(new Date(patients[0].dateOfBirth), 'yyyy-MM-dd'),\n+ format(new Date(patients.content[0].dateOfBirth), 'yyyy-MM-dd'),\n)\n})\n@@ -130,7 +145,11 @@ describe('Patients', () => {\nwrapper.update()\nexpect(searchPatientsSpy).toHaveBeenCalledTimes(1)\n- expect(searchPatientsSpy).toHaveBeenLastCalledWith(expectedSearchText)\n+ expect(searchPatientsSpy).toHaveBeenLastCalledWith(\n+ expectedSearchText,\n+ Unsorted,\n+ UnpagedRequest,\n+ )\n})\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/patients-slice.test.ts",
"new_path": "src/__tests__/patients/patients-slice.test.ts",
"diff": "import '../../__mocks__/matchMediaMock'\nimport { AnyAction } from 'redux'\nimport { mocked } from 'ts-jest/utils'\n+import { UnpagedRequest } from 'clients/db/PageRequest'\nimport patients, {\nfetchPatientsStart,\nfetchPatientsSuccess,\nsearchPatients,\n} from '../../patients/patients-slice'\n-import Patient from '../../model/Patient'\nimport PatientRepository from '../../clients/db/PatientRepository'\ndescribe('patients slice', () => {\n@@ -18,14 +18,34 @@ describe('patients slice', () => {\nit('should create the proper initial state with empty patients array', () => {\nconst patientsStore = patients(undefined, {} as AnyAction)\nexpect(patientsStore.isLoading).toBeFalsy()\n- expect(patientsStore.patients).toHaveLength(0)\n+ expect(patientsStore.patients.content).toHaveLength(0)\n})\nit('should handle the FETCH_PATIENTS_SUCCESS action', () => {\n- const expectedPatients = [{ id: '1234' }]\n+ const expectedPatients = {\n+ content: [\n+ {\n+ id: '123',\n+ fullName: 'test test',\n+ isApproximateDateOfBirth: false,\n+ givenName: 'test',\n+ familyName: 'test',\n+ code: 'P12345',\n+ sex: 'male',\n+ dateOfBirth: new Date().toISOString(),\n+ phoneNumber: '99999999',\n+ createdAt: new Date().toISOString(),\n+ updatedAt: new Date().toISOString(),\n+ rev: '',\n+ },\n+ ],\n+ hasNext: false,\n+ hasPrevious: false,\n+ pageRequest: UnpagedRequest,\n+ }\nconst patientsStore = patients(undefined, {\ntype: fetchPatientsSuccess.type,\n- payload: [{ id: '1234' }],\n+ payload: expectedPatients,\n})\nexpect(patientsStore.isLoading).toBeFalsy()\n@@ -43,39 +63,58 @@ describe('patients slice', () => {\nexpect(dispatch).toHaveBeenCalledWith({ type: fetchPatientsStart.type })\n})\n- it('should call the PatientRepository search method with the correct search criteria', async () => {\n+ it('should call the PatientRepository searchPaged method with the correct search criteria', async () => {\nconst dispatch = jest.fn()\nconst getState = jest.fn()\n- jest.spyOn(PatientRepository, 'search')\n+ jest.spyOn(PatientRepository, 'searchPaged')\nconst expectedSearchString = 'search string'\nawait searchPatients(expectedSearchString)(dispatch, getState, null)\n- expect(PatientRepository.search).toHaveBeenCalledWith(expectedSearchString)\n+ expect(PatientRepository.searchPaged).toHaveBeenCalledWith(\n+ expectedSearchString,\n+ UnpagedRequest,\n+ )\n})\n- it('should call the PatientRepository findAll method if there is no string text', async () => {\n+ it('should call the PatientRepository findAllPaged method if there is no string text', async () => {\nconst dispatch = jest.fn()\nconst getState = jest.fn()\n- jest.spyOn(PatientRepository, 'findAll')\n+ jest.spyOn(PatientRepository, 'findAllPaged')\nawait searchPatients('')(dispatch, getState, null)\n- expect(PatientRepository.findAll).toHaveBeenCalledTimes(1)\n+ expect(PatientRepository.findAllPaged).toHaveBeenCalledTimes(1)\n})\nit('should dispatch the FETCH_PATIENTS_SUCCESS action', async () => {\nconst dispatch = jest.fn()\nconst getState = jest.fn()\n- const expectedPatients = [\n+ const expectedPatients = {\n+ content: [\n{\n- id: '1234',\n+ id: '123',\n+ fullName: 'test test',\n+ isApproximateDateOfBirth: false,\n+ givenName: 'test',\n+ familyName: 'test',\n+ code: 'P12345',\n+ sex: 'male',\n+ dateOfBirth: new Date().toISOString(),\n+ phoneNumber: '99999999',\n+ createdAt: new Date().toISOString(),\n+ updatedAt: new Date().toISOString(),\n+ rev: '',\n},\n- ] as Patient[]\n+ ],\n+ hasNext: false,\n+ hasPrevious: false,\n+ pageRequest: UnpagedRequest,\n+ }\nconst mockedPatientRepository = mocked(PatientRepository, true)\n- mockedPatientRepository.search.mockResolvedValue(expectedPatients)\n+ mockedPatientRepository.searchPaged.mockResolvedValue(expectedPatients)\nawait searchPatients('search string')(dispatch, getState, null)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/Page.ts",
"diff": "+import AbstractDBModel from '../model/AbstractDBModel'\n+import PageRequest from './db/PageRequest'\n+\n+export default interface Page<T extends AbstractDBModel> {\n+ content: T[]\n+ hasNext?: boolean\n+ hasPrevious?: boolean\n+ pageRequest?: PageRequest\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/db/PageRequest.ts",
"diff": "+export default interface PageRequest {\n+ limit: number | undefined\n+ skip: number\n+}\n+export const UnpagedRequest: PageRequest = { limit: undefined, skip: 0 }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "import shortid from 'shortid'\n+import Page from 'clients/Page'\nimport Patient from '../../model/Patient'\nimport Repository from './Repository'\nimport { patients } from '../../config/pouchdb'\n+import PageRequest, { UnpagedRequest } from './PageRequest'\nconst formatPatientCode = (prefix: string, sequenceNumber: string) => `${prefix}${sequenceNumber}`\n@@ -10,6 +12,9 @@ const getPatientCode = (): string => formatPatientCode('P-', shortid.generate())\nexport class PatientRepository extends Repository<Patient> {\nconstructor() {\nsuper(patients)\n+ patients.createIndex({\n+ index: { fields: ['code', 'fullName'] },\n+ })\n}\nasync search(text: string): Promise<Patient[]> {\n@@ -29,6 +34,45 @@ export class PatientRepository extends Repository<Patient> {\n})\n}\n+ async searchPaged(\n+ text: string,\n+ pageRequest: PageRequest = UnpagedRequest,\n+ ): Promise<Page<Patient>> {\n+ return super\n+ .search({\n+ selector: {\n+ $or: [\n+ {\n+ fullName: {\n+ $regex: RegExp(text, 'i'),\n+ },\n+ },\n+ {\n+ code: text,\n+ },\n+ ],\n+ },\n+ skip: pageRequest.skip,\n+ limit: pageRequest.limit,\n+ })\n+ .then(\n+ (searchedData) =>\n+ new Promise<Page<Patient>>((resolve) => {\n+ const pagedResult: Page<Patient> = {\n+ content: searchedData,\n+ pageRequest,\n+ hasNext: pageRequest.limit !== undefined && searchedData.length === pageRequest.limit,\n+ hasPrevious: pageRequest.skip > 0,\n+ }\n+ resolve(pagedResult)\n+ }),\n+ )\n+ .catch((err) => {\n+ console.log(err)\n+ return err\n+ })\n+ }\n+\nasync save(entity: Patient): Promise<Patient> {\nconst patientCode = getPatientCode()\nentity.code = patientCode\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport { v4 as uuidv4 } from 'uuid'\n+import Page from 'clients/Page'\nimport AbstractDBModel from '../../model/AbstractDBModel'\nimport { Unsorted } from './SortRequest'\n+import PageRequest, { UnpagedRequest } from './PageRequest'\nfunction mapDocument(document: any): any {\nconst { _id, _rev, ...values } = document\n@@ -41,6 +43,35 @@ export default class Repository<T extends AbstractDBModel> {\nreturn result.docs.map(mapDocument)\n}\n+ async findAllPaged(sort = Unsorted, pageRequest: PageRequest = UnpagedRequest): Promise<Page<T>> {\n+ const selector: any = {\n+ _id: { $gt: null },\n+ }\n+\n+ sort.sorts.forEach((s) => {\n+ selector[s.field] = { $gt: null }\n+ })\n+\n+ const result = await this.db.find({\n+ selector,\n+ sort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\n+ limit: pageRequest.limit,\n+ skip: pageRequest.skip,\n+ })\n+ const mappedResult = result.docs.map(mapDocument)\n+\n+ const pagedResult: Page<T> = {\n+ content: mappedResult,\n+ hasNext: pageRequest.limit !== undefined && mappedResult.length === pageRequest.limit,\n+ hasPrevious: pageRequest.skip > 0,\n+ pageRequest: {\n+ skip: pageRequest.skip,\n+ limit: pageRequest.limit,\n+ },\n+ }\n+ return pagedResult\n+ }\n+\nasync search(criteria: any): Promise<T[]> {\nconst response = await this.db.find(criteria)\nreturn response.docs.map(mapDocument)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/components/PageComponent.tsx",
"diff": "+import React from 'react'\n+import { Button } from '@hospitalrun/components'\n+import { useTranslation } from 'react-i18next'\n+\n+const PageComponent = ({\n+ hasNext,\n+ hasPrevious,\n+ pageNumber,\n+ setPreviousPageRequest,\n+ setNextPageRequest,\n+}: any) => {\n+ const { t } = useTranslation()\n+\n+ return (\n+ <div style={{ textAlign: 'center' }}>\n+ <Button\n+ key=\"actions.previous\"\n+ outlined\n+ disabled={!hasPrevious}\n+ style={{ float: 'left' }}\n+ color=\"success\"\n+ onClick={setPreviousPageRequest}\n+ >\n+ {t('actions.previous')}\n+ </Button>\n+ <div style={{ display: 'inline-block' }}>\n+ {t('actions.page')} {pageNumber}\n+ </div>\n+ <Button\n+ key=\"actions.next\"\n+ outlined\n+ style={{ float: 'right' }}\n+ disabled={!hasNext}\n+ color=\"success\"\n+ onClick={setNextPageRequest}\n+ >\n+ {t('actions.next')}\n+ </Button>\n+ </div>\n+ )\n+}\n+export default PageComponent\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/actions/index.ts",
"new_path": "src/locales/enUs/translations/actions/index.ts",
"diff": "@@ -11,5 +11,8 @@ export default {\nlist: 'List',\nsearch: 'Search',\nconfirmDelete: 'Delete Confirmation',\n+ next: 'Next',\n+ previous: 'Previous',\n+ page: 'Page',\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -5,6 +5,9 @@ import { useTranslation } from 'react-i18next'\nimport { Spinner, Button, Container, Row, TextInput, Column } from '@hospitalrun/components'\nimport { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\n+import { Unsorted } from 'clients/db/SortRequest'\n+import PageRequest from 'clients/db/PageRequest'\n+import PageComponent from 'components/PageComponent'\nimport { RootState } from '../../store'\nimport { fetchPatients, searchPatients } from '../patients-slice'\nimport useTitle from '../../page-header/useTitle'\n@@ -19,20 +22,45 @@ const ViewPatients = () => {\nuseTitle(t('patients.label'))\nuseAddBreadcrumbs(breadcrumbs, true)\nconst dispatch = useDispatch()\n- const { patients, isLoading } = useSelector((state: RootState) => state.patients)\n+ const { patients, isLoading, pageRequest } = useSelector((state: RootState) => state.patients)\nconst setButtonToolBar = useButtonToolbarSetter()\n+ const [userPageRequest, setUserPageRequest] = useState<PageRequest>(pageRequest)\n+ const setNextPageRequest = () => {\n+ setUserPageRequest((p) => {\n+ if (p.limit) {\n+ const newPageRequest: PageRequest = {\n+ limit: p.limit,\n+ skip: p.skip + p.limit,\n+ }\n+ return newPageRequest\n+ }\n+ return p\n+ })\n+ }\n+\n+ const setPreviousPageRequest = () => {\n+ setUserPageRequest((p) => {\n+ if (p.limit) {\n+ return {\n+ limit: p.limit,\n+ skip: p.skip - p.limit,\n+ }\n+ }\n+ return p\n+ })\n+ }\nconst [searchText, setSearchText] = useState<string>('')\nconst debouncedSearchText = useDebounce(searchText, 500)\nuseEffect(() => {\n- dispatch(searchPatients(debouncedSearchText))\n- }, [dispatch, debouncedSearchText])\n+ dispatch(searchPatients(debouncedSearchText, Unsorted, userPageRequest))\n+ }, [dispatch, debouncedSearchText, userPageRequest])\nuseEffect(() => {\n- dispatch(fetchPatients())\n+ dispatch(fetchPatients(Unsorted, userPageRequest))\nsetButtonToolBar([\n<Button\n@@ -49,7 +77,7 @@ const ViewPatients = () => {\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, setButtonToolBar, t, history])\n+ }, [dispatch, setButtonToolBar, t, history, userPageRequest])\nconst loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\nconst table = (\n@@ -64,7 +92,7 @@ const ViewPatients = () => {\n</tr>\n</thead>\n<tbody>\n- {patients.map((p) => (\n+ {patients.content.map((p) => (\n<tr key={p.id} onClick={() => history.push(`/patients/${p.id}`)}>\n<td>{p.code}</td>\n<td>{p.givenName}</td>\n@@ -96,6 +124,13 @@ const ViewPatients = () => {\n</Row>\n<Row> {isLoading ? loadingIndicator : table}</Row>\n+ <PageComponent\n+ hasNext={patients.hasNext}\n+ hasPrevious={patients.hasPrevious}\n+ pageNumber={userPageRequest.limit && userPageRequest.skip / userPageRequest.limit + 1}\n+ setPreviousPageRequest={setPreviousPageRequest}\n+ setNextPageRequest={setNextPageRequest}\n+ />\n</Container>\n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patients-slice.ts",
"new_path": "src/patients/patients-slice.ts",
"diff": "import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import SortRequest, { Unsorted } from 'clients/db/SortRequest'\n+import PageRequest, { UnpagedRequest } from 'clients/db/PageRequest'\n+import Page from 'clients/Page'\nimport Patient from '../model/Patient'\nimport PatientRepository from '../clients/db/PatientRepository'\nimport { AppThunk } from '../store'\ninterface PatientsState {\nisLoading: boolean\n- patients: Patient[]\n+ patients: Page<Patient>\n+ pageRequest: PageRequest\n}\nconst initialState: PatientsState = {\nisLoading: false,\n- patients: [],\n+ patients: {\n+ content: [],\n+ hasNext: false,\n+ hasPrevious: false,\n+ pageRequest: {\n+ skip: 0,\n+ limit: 20,\n+ },\n+ },\n+ pageRequest: {\n+ skip: 0,\n+ limit: 20,\n+ },\n}\nfunction startLoading(state: PatientsState) {\n@@ -22,7 +38,7 @@ const patientsSlice = createSlice({\ninitialState,\nreducers: {\nfetchPatientsStart: startLoading,\n- fetchPatientsSuccess(state, { payload }: PayloadAction<Patient[]>) {\n+ fetchPatientsSuccess(state, { payload }: PayloadAction<Page<Patient>>) {\nstate.isLoading = false\nstate.patients = payload\n},\n@@ -30,20 +46,27 @@ const patientsSlice = createSlice({\n})\nexport const { fetchPatientsStart, fetchPatientsSuccess } = patientsSlice.actions\n-export const fetchPatients = (): AppThunk => async (dispatch) => {\n+export const fetchPatients = (\n+ sortRequest: SortRequest,\n+ pageRequest: PageRequest,\n+): AppThunk => async (dispatch) => {\ndispatch(fetchPatientsStart())\n- const patients = await PatientRepository.findAll()\n+ const patients = await PatientRepository.findAllPaged(sortRequest, pageRequest)\ndispatch(fetchPatientsSuccess(patients))\n}\n-export const searchPatients = (searchString: string): AppThunk => async (dispatch) => {\n+export const searchPatients = (\n+ searchString: string,\n+ sortRequest: SortRequest = Unsorted,\n+ pageRequest: PageRequest = UnpagedRequest,\n+): AppThunk => async (dispatch) => {\ndispatch(fetchPatientsStart())\nlet patients\nif (searchString.trim() === '') {\n- patients = await PatientRepository.findAll()\n+ patients = await PatientRepository.findAllPaged(sortRequest, pageRequest)\n} else {\n- patients = await PatientRepository.search(searchString)\n+ patients = await PatientRepository.searchPaged(searchString, pageRequest)\n}\ndispatch(fetchPatientsSuccess(patients))\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): add paging feature in ViewPatients component
feat #1969 |
288,350 | 28.04.2020 22:16:26 | -19,080 | c4109a470290843b39023e656db68845930174d0 | feat: add Sort request in ViewPatients
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -11,7 +11,6 @@ import { act } from 'react-dom/test-utils'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\nimport Page from 'clients/Page'\n-import { Unsorted } from 'clients/db/SortRequest'\nimport ViewPatients from '../../../patients/list/ViewPatients'\nimport PatientRepository from '../../../clients/db/PatientRepository'\nimport * as patientSlice from '../../../patients/patients-slice'\n@@ -147,8 +146,10 @@ describe('Patients', () => {\nexpect(searchPatientsSpy).toHaveBeenCalledTimes(1)\nexpect(searchPatientsSpy).toHaveBeenLastCalledWith(\nexpectedSearchText,\n- Unsorted,\n- UnpagedRequest,\n+ {\n+ sorts: [{ field: 'code', direction: 'desc' }],\n+ },\n+ { limit: 1, skip: 0 },\n)\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next'\nimport { Spinner, Button, Container, Row, TextInput, Column } from '@hospitalrun/components'\nimport { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\n-import { Unsorted } from 'clients/db/SortRequest'\n+import SortRequest from 'clients/db/SortRequest'\nimport PageRequest from 'clients/db/PageRequest'\nimport PageComponent from 'components/PageComponent'\nimport { RootState } from '../../store'\n@@ -22,10 +22,13 @@ const ViewPatients = () => {\nuseTitle(t('patients.label'))\nuseAddBreadcrumbs(breadcrumbs, true)\nconst dispatch = useDispatch()\n- const { patients, isLoading, pageRequest } = useSelector((state: RootState) => state.patients)\n+ const { patients, isLoading } = useSelector((state: RootState) => state.patients)\nconst setButtonToolBar = useButtonToolbarSetter()\n- const [userPageRequest, setUserPageRequest] = useState<PageRequest>(pageRequest)\n+ const [userPageRequest, setUserPageRequest] = useState<PageRequest>({\n+ skip: 0,\n+ limit: 1,\n+ })\nconst setNextPageRequest = () => {\nsetUserPageRequest((p) => {\n@@ -56,11 +59,17 @@ const ViewPatients = () => {\nconst debouncedSearchText = useDebounce(searchText, 500)\nuseEffect(() => {\n- dispatch(searchPatients(debouncedSearchText, Unsorted, userPageRequest))\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'code', direction: 'desc' }],\n+ }\n+ dispatch(searchPatients(debouncedSearchText, sortRequest, userPageRequest))\n}, [dispatch, debouncedSearchText, userPageRequest])\nuseEffect(() => {\n- dispatch(fetchPatients(Unsorted, userPageRequest))\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'code', direction: 'desc' }],\n+ }\n+ dispatch(fetchPatients(sortRequest, userPageRequest))\nsetButtonToolBar([\n<Button\n@@ -77,7 +86,7 @@ const ViewPatients = () => {\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, setButtonToolBar, t, history, userPageRequest])\n+ }, [dispatch, setButtonToolBar, t, history])\nconst loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\nconst table = (\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patients-slice.ts",
"new_path": "src/patients/patients-slice.ts",
"diff": "@@ -9,7 +9,6 @@ import { AppThunk } from '../store'\ninterface PatientsState {\nisLoading: boolean\npatients: Page<Patient>\n- pageRequest: PageRequest\n}\nconst initialState: PatientsState = {\n@@ -20,13 +19,9 @@ const initialState: PatientsState = {\nhasPrevious: false,\npageRequest: {\nskip: 0,\n- limit: 20,\n+ limit: 1,\n},\n},\n- pageRequest: {\n- skip: 0,\n- limit: 20,\n- },\n}\nfunction startLoading(state: PatientsState) {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat: add Sort request in ViewPatients
feat #1969 |
288,350 | 28.04.2020 22:38:28 | -19,080 | 11b6c8be0ee643bea6c33250c8adb36b8dafbf8f | fix(viewpatients.tsx): add userPageRequest in dependency array
fix | [
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -86,7 +86,7 @@ const ViewPatients = () => {\nreturn () => {\nsetButtonToolBar([])\n}\n- }, [dispatch, setButtonToolBar, t, history])\n+ }, [dispatch, setButtonToolBar, t, history, userPageRequest])\nconst loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\nconst table = (\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(viewpatients.tsx): add userPageRequest in dependency array
fix #1969 |
288,307 | 01.05.2020 00:20:04 | -3,600 | 1693e5f542b7bead83dd0495b2fb2dc4398b3319 | fix(patients): fixes search when using special characters | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"@types/pouchdb-find\": \"~6.3.4\",\n\"bootstrap\": \"~4.4.1\",\n\"date-fns\": \"~2.12.0\",\n+ \"escape-string-regexp\": \"~4.0.0\",\n\"i18next\": \"~19.4.0\",\n\"i18next-browser-languagedetector\": \"~4.1.0\",\n\"i18next-xhr-backend\": \"~3.2.2\",\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"new_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"diff": "@@ -39,6 +39,15 @@ describe('patient repository', () => {\nawait removeAllDocs()\n})\n+ it('should escape all special chars from search text', async () => {\n+ await patients.put({ _id: 'id9999', code: 'P00001', fullName: 'test -]?}(){*[\\\\$+.^test' })\n+\n+ const result = await PatientRepository.search('test -]?}(){*[\\\\$+.^test')\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].id).toEqual('id9999')\n+ })\n+\nit('should return all records that patient code matches search text', async () => {\n// same full name to prove that it is finding by patient code\nconst expectedPatientCode = 'P00001'\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "+import escapeStringRegexp from 'escape-string-regexp'\nimport shortid from 'shortid'\nimport Patient from '../../model/Patient'\nimport Repository from './Repository'\n@@ -13,12 +14,13 @@ export class PatientRepository extends Repository<Patient> {\n}\nasync search(text: string): Promise<Patient[]> {\n+ const escapedString = escapeStringRegexp(text)\nreturn super.search({\nselector: {\n$or: [\n{\nfullName: {\n- $regex: RegExp(text, 'i'),\n+ $regex: RegExp(escapedString, 'i'),\n},\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Sidebar.tsx",
"new_path": "src/components/Sidebar.tsx",
"diff": "@@ -55,22 +55,20 @@ const Sidebar = () => {\ncursor: 'pointer',\nfontSize: 'small',\nborderBottomWidth: 0,\n- color:\n- (splittedPath[1].includes('patients') || splittedPath[1].includes('appointments')) &&\n- splittedPath.length > 2\n- ? 'white'\n- : 'black',\n+ borderTopWidth: 0,\n+ color: 'black',\n+ padding: '.6rem 1.25rem',\n+ backgroundColor: 'rgba(245,245,245,1)',\n}\nconst listSubItemStyle: CSSProperties = {\ncursor: 'pointer',\nfontSize: 'small',\nborderBottomWidth: 0,\n- color:\n- (splittedPath[1].includes('patients') || splittedPath[1].includes('appointments')) &&\n- splittedPath.length < 3\n- ? 'white'\n- : 'black',\n+ borderTopWidth: 0,\n+ color: 'black',\n+ padding: '.6rem 1.25rem',\n+ backgroundColor: 'rgba(245,245,245,1)',\n}\nconst getDashboardLink = () => (\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(patients): fixes search when using special characters (#2012) |
288,323 | 30.04.2020 22:44:38 | 18,000 | 242e1a13c14f83b4a945dcccf554e26ead5622ff | feat(patient): add email and phone number validation | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"i18next\": \"~19.4.0\",\n\"i18next-browser-languagedetector\": \"~4.1.0\",\n\"i18next-xhr-backend\": \"~3.2.2\",\n- \"node-sass\": \"~4.14.0\",\n\"lodash\": \"^4.17.15\",\n+ \"node-sass\": \"~4.14.0\",\n\"pouchdb\": \"~7.2.1\",\n\"pouchdb-adapter-memory\": \"~7.2.1\",\n\"pouchdb-find\": \"~7.2.1\",\n\"redux-thunk\": \"~2.3.0\",\n\"shortid\": \"^2.2.15\",\n\"typescript\": \"~3.8.2\",\n- \"uuid\": \"^8.0.0\"\n+ \"uuid\": \"^8.0.0\",\n+ \"validator\": \"^13.0.0\"\n},\n\"repository\": {\n\"type\": \"git\",\n\"@types/redux-mock-store\": \"~1.0.1\",\n\"@types/shortid\": \"^0.0.29\",\n\"@types/uuid\": \"^7.0.0\",\n+ \"@types/validator\": \"~13.0.0\",\n\"@typescript-eslint/eslint-plugin\": \"~2.30.0\",\n\"@typescript-eslint/parser\": \"~2.30.0\",\n\"commitizen\": \"~4.0.3\",\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/GeneralInformation.test.tsx",
"new_path": "src/__tests__/patients/GeneralInformation.test.tsx",
"diff": "@@ -15,6 +15,8 @@ describe('Error handling', () => {\nmessage: 'some message',\ngivenName: 'given name message',\ndateOfBirth: 'date of birth message',\n+ phoneNumber: 'phone number message',\n+ email: 'email message',\n}\nconst history = createMemoryHistory()\nconst wrapper = mount(\n@@ -27,12 +29,18 @@ describe('Error handling', () => {\nconst errorMessage = wrapper.find(Alert)\nconst givenNameInput = wrapper.findWhere((w: any) => w.prop('name') === 'givenName')\nconst dateOfBirthInput = wrapper.findWhere((w: any) => w.prop('name') === 'dateOfBirth')\n+ const emailInput = wrapper.findWhere((w: any) => w.prop('name') === 'email')\n+ const phoneNumberInput = wrapper.findWhere((w: any) => w.prop('name') === 'phoneNumber')\nexpect(errorMessage).toBeTruthy()\nexpect(errorMessage.prop('message')).toMatch(error.message)\nexpect(givenNameInput.prop('isInvalid')).toBeTruthy()\nexpect(givenNameInput.prop('feedback')).toEqual(error.givenName)\nexpect(dateOfBirthInput.prop('isInvalid')).toBeTruthy()\nexpect(dateOfBirthInput.prop('feedback')).toEqual(error.dateOfBirth)\n+ expect(emailInput.prop('feedback')).toEqual(error.email)\n+ expect(emailInput.prop('isInvalid')).toBeTruthy()\n+ expect(phoneNumberInput.prop('feedback')).toEqual(error.phoneNumber)\n+ expect(phoneNumberInput.prop('isInvalid')).toBeTruthy()\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"new_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"diff": "@@ -30,7 +30,7 @@ describe('Edit Patient', () => {\ntype: 'charity',\noccupation: 'occupation',\npreferredLanguage: 'preferredLanguage',\n- phoneNumber: 'phoneNumber',\n+ phoneNumber: '123456789',\nemail: '[email protected]',\naddress: 'address',\ncode: 'P00001',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/patient-slice.test.ts",
"new_path": "src/__tests__/patients/patient-slice.test.ts",
"diff": "@@ -197,13 +197,12 @@ describe('patients slice', () => {\nexpect(onSuccessSpy).toHaveBeenCalledWith(expectedPatient)\n})\n- it('should validate the patient', async () => {\n+ it('should validate the patient required fields', async () => {\nconst store = mockStore()\nconst expectedPatientId = 'sliceId10'\nconst expectedPatient = {\nid: expectedPatientId,\ngivenName: undefined,\n- dateOfBirth: addDays(new Date(), 4).toISOString(),\n} as Patient\nconst saveOrUpdateSpy = jest\n.spyOn(PatientRepository, 'saveOrUpdate')\n@@ -218,10 +217,84 @@ describe('patients slice', () => {\ncreatePatientError({\nmessage: 'patient.errors.createPatientError',\ngivenName: 'patient.errors.patientGivenNameFeedback',\n+ }),\n+ )\n+ })\n+\n+ it('should validate that the patient birthday is not a future date', async () => {\n+ const store = mockStore()\n+ const expectedPatientId = 'sliceId10'\n+ const expectedPatient = {\n+ id: expectedPatientId,\n+ givenName: 'some given name',\n+ dateOfBirth: addDays(new Date(), 4).toISOString(),\n+ } as Patient\n+ const saveOrUpdateSpy = jest\n+ .spyOn(PatientRepository, 'saveOrUpdate')\n+ .mockResolvedValue(expectedPatient)\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(createPatient(expectedPatient, onSuccessSpy))\n+\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ expect(saveOrUpdateSpy).not.toHaveBeenCalled()\n+ expect(store.getActions()[1]).toEqual(\n+ createPatientError({\n+ message: 'patient.errors.createPatientError',\ndateOfBirth: 'patient.errors.patientDateOfBirthFeedback',\n}),\n)\n})\n+\n+ it('should validate that the patient email is a valid email', async () => {\n+ const store = mockStore()\n+ const expectedPatientId = 'sliceId10'\n+ const expectedPatient = {\n+ id: expectedPatientId,\n+ givenName: 'some given name',\n+ phoneNumber: 'not a phone number',\n+ } as Patient\n+ const saveOrUpdateSpy = jest\n+ .spyOn(PatientRepository, 'saveOrUpdate')\n+ .mockResolvedValue(expectedPatient)\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(createPatient(expectedPatient, onSuccessSpy))\n+\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ expect(saveOrUpdateSpy).not.toHaveBeenCalled()\n+ expect(store.getActions()[1]).toEqual(\n+ createPatientError({\n+ message: 'patient.errors.createPatientError',\n+ phoneNumber: 'patient.errors.invalidPhoneNumber',\n+ }),\n+ )\n+ })\n+\n+ it('should validate that the patient phone number is a valid phone number', async () => {\n+ const store = mockStore()\n+ const expectedPatientId = 'sliceId10'\n+ const expectedPatient = {\n+ id: expectedPatientId,\n+ givenName: 'some given name',\n+ phoneNumber: 'not a phone number',\n+ } as Patient\n+ const saveOrUpdateSpy = jest\n+ .spyOn(PatientRepository, 'saveOrUpdate')\n+ .mockResolvedValue(expectedPatient)\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(createPatient(expectedPatient, onSuccessSpy))\n+\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ expect(saveOrUpdateSpy).not.toHaveBeenCalled()\n+ expect(store.getActions()[1]).toEqual(\n+ createPatientError({\n+ message: 'patient.errors.createPatientError',\n+ phoneNumber: 'patient.errors.invalidPhoneNumber',\n+ }),\n+ )\n+ })\n})\ndescribe('fetch patient', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -94,6 +94,8 @@ export default {\nupdatePatientError: 'Could not update patient.',\npatientGivenNameFeedback: 'Given Name is required.',\npatientDateOfBirthFeedback: 'Date of Birth can not be greater than today',\n+ invalidEmail: 'Must be a valid email.',\n+ invalidPhoneNumber: 'Must be a valid phone number.',\n},\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/GeneralInformation.tsx",
"new_path": "src/patients/GeneralInformation.tsx",
"diff": "@@ -211,6 +211,8 @@ const GeneralInformation = (props: Props) => {\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'phoneNumber')\n}}\n+ feedback={t(error?.phoneNumber)}\n+ isInvalid={!!error?.phoneNumber}\ntype=\"tel\"\n/>\n</div>\n@@ -225,6 +227,8 @@ const GeneralInformation = (props: Props) => {\nonInputElementChange(event, 'email')\n}}\ntype=\"email\"\n+ feedback={t(error?.email)}\n+ isInvalid={!!error?.email}\n/>\n</div>\n</div>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patient-slice.ts",
"new_path": "src/patients/patient-slice.ts",
"diff": "import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport { isAfter, parseISO } from 'date-fns'\nimport _ from 'lodash'\n+import validator from 'validator'\nimport { uuid } from '../util/uuid'\nimport Patient from '../model/Patient'\nimport PatientRepository from '../clients/db/PatientRepository'\n@@ -27,6 +28,8 @@ interface Error {\nmessage?: string\ngivenName?: string\ndateOfBirth?: string\n+ email?: string\n+ phoneNumber?: string\n}\ninterface AddRelatedPersonError {\n@@ -150,6 +153,18 @@ function validatePatient(patient: Patient) {\n}\n}\n+ if (patient.email) {\n+ if (!validator.isEmail(patient.email)) {\n+ error.email = 'patient.errors.invalidEmail'\n+ }\n+ }\n+\n+ if (patient.phoneNumber) {\n+ if (!validator.isMobilePhone(patient.phoneNumber)) {\n+ error.phoneNumber = 'patient.errors.invalidPhoneNumber'\n+ }\n+ }\n+\nreturn error\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patient): add email and phone number validation |
288,334 | 01.05.2020 12:19:51 | -7,200 | e522406bdaa8bd1ea9cd8a99e4c36faf78ad2c7a | chore(deps): bump components | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"private\": false,\n\"license\": \"MIT\",\n\"dependencies\": {\n- \"@hospitalrun/components\": \"^1.3.0\",\n+ \"@hospitalrun/components\": \"^1.4.0\",\n\"@reduxjs/toolkit\": \"~1.3.0\",\n\"@types/pouchdb-find\": \"~6.3.4\",\n\"bootstrap\": \"~4.4.1\",\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | chore(deps): bump components |
288,350 | 01.05.2020 17:43:05 | -19,080 | 5308f5fc7fa358d13797dee5e6a78b724795f31b | feat(viewpatients): refactor code as recommended
Change Page interface, Fix failing tests
fix | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -64,7 +64,31 @@ describe('Patients', () => {\nbeforeEach(() => {\njest.resetAllMocks()\njest.spyOn(PatientRepository, 'findAll')\n+ jest.spyOn(PatientRepository, 'searchPaged')\n+ jest.spyOn(PatientRepository, 'findAllPaged')\n+\nmockedPatientRepository.findAll.mockResolvedValue([])\n+ mockedPatientRepository.findAllPaged.mockResolvedValue(\n+ new Promise<Page<Patient>>((resolve) => {\n+ const pagedResult: Page<Patient> = {\n+ content: [],\n+ hasPrevious: false,\n+ hasNext: false,\n+ }\n+ resolve(pagedResult)\n+ }),\n+ )\n+\n+ mockedPatientRepository.searchPaged.mockResolvedValue(\n+ new Promise<Page<Patient>>((resolve) => {\n+ const pagedResult: Page<Patient> = {\n+ content: [],\n+ hasPrevious: false,\n+ hasNext: false,\n+ }\n+ resolve(pagedResult)\n+ }),\n+ )\n})\ndescribe('layout', () => {\n@@ -147,9 +171,12 @@ describe('Patients', () => {\nexpect(searchPatientsSpy).toHaveBeenLastCalledWith(\nexpectedSearchText,\n{\n- sorts: [{ field: 'code', direction: 'desc' }],\n+ sorts: [\n+ { field: 'fullName', direction: 'asc' },\n+ { field: 'code', direction: 'asc' },\n+ ],\n},\n- { limit: 1, skip: 0 },\n+ { number: 1, size: 1 },\n)\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/patients-slice.test.ts",
"new_path": "src/__tests__/patients/patients-slice.test.ts",
"diff": "@@ -2,6 +2,8 @@ import '../../__mocks__/matchMediaMock'\nimport { AnyAction } from 'redux'\nimport { mocked } from 'ts-jest/utils'\nimport { UnpagedRequest } from 'clients/db/PageRequest'\n+import Page from 'clients/Page'\n+import Patient from 'model/Patient'\nimport patients, {\nfetchPatientsStart,\nfetchPatientsSuccess,\n@@ -54,6 +56,34 @@ describe('patients slice', () => {\n})\ndescribe('searchPatients', () => {\n+ beforeEach(() => {\n+ const mockedPatientRepository = mocked(PatientRepository, true)\n+ jest.spyOn(PatientRepository, 'findAllPaged')\n+ jest.spyOn(PatientRepository, 'searchPaged')\n+\n+ mockedPatientRepository.findAllPaged.mockResolvedValue(\n+ new Promise<Page<Patient>>((resolve) => {\n+ const pagedResult: Page<Patient> = {\n+ content: [],\n+ hasPrevious: false,\n+ hasNext: false,\n+ }\n+ resolve(pagedResult)\n+ }),\n+ )\n+\n+ mockedPatientRepository.searchPaged.mockResolvedValue(\n+ new Promise<Page<Patient>>((resolve) => {\n+ const pagedResult: Page<Patient> = {\n+ content: [],\n+ hasPrevious: false,\n+ hasNext: false,\n+ }\n+ resolve(pagedResult)\n+ }),\n+ )\n+ })\n+\nit('should dispatch the FETCH_PATIENTS_START action', async () => {\nconst dispatch = jest.fn()\nconst getState = jest.fn()\n@@ -91,36 +121,15 @@ describe('patients slice', () => {\nconst dispatch = jest.fn()\nconst getState = jest.fn()\n- const expectedPatients = {\n- content: [\n- {\n- id: '123',\n- fullName: 'test test',\n- isApproximateDateOfBirth: false,\n- givenName: 'test',\n- familyName: 'test',\n- code: 'P12345',\n- sex: 'male',\n- dateOfBirth: new Date().toISOString(),\n- phoneNumber: '99999999',\n- createdAt: new Date().toISOString(),\n- updatedAt: new Date().toISOString(),\n- rev: '',\n- },\n- ],\n- hasNext: false,\n- hasPrevious: false,\n- pageRequest: UnpagedRequest,\n- }\n-\n- const mockedPatientRepository = mocked(PatientRepository, true)\n- mockedPatientRepository.searchPaged.mockResolvedValue(expectedPatients)\n-\nawait searchPatients('search string')(dispatch, getState, null)\nexpect(dispatch).toHaveBeenLastCalledWith({\ntype: fetchPatientsSuccess.type,\n- payload: expectedPatients,\n+ payload: {\n+ content: [],\n+ hasPrevious: false,\n+ hasNext: false,\n+ },\n})\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/Page.ts",
"new_path": "src/clients/Page.ts",
"diff": "@@ -3,7 +3,7 @@ import PageRequest from './db/PageRequest'\nexport default interface Page<T extends AbstractDBModel> {\ncontent: T[]\n- hasNext?: boolean\n- hasPrevious?: boolean\n+ hasNext: boolean\n+ hasPrevious: boolean\npageRequest?: PageRequest\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "export default interface PageRequest {\n- limit: number | undefined\n- skip: number\n+ number: number | undefined\n+ size: number | undefined\n+}\n+export const UnpagedRequest: PageRequest = {\n+ number: undefined,\n+ size: undefined,\n}\n-export const UnpagedRequest: PageRequest = { limit: undefined, skip: 0 }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "@@ -4,6 +4,7 @@ import Patient from '../../model/Patient'\nimport Repository from './Repository'\nimport { patients } from '../../config/pouchdb'\nimport PageRequest, { UnpagedRequest } from './PageRequest'\n+import SortRequest, { Unsorted } from './SortRequest'\nconst formatPatientCode = (prefix: string, sequenceNumber: string) => `${prefix}${sequenceNumber}`\n@@ -13,7 +14,7 @@ export class PatientRepository extends Repository<Patient> {\nconstructor() {\nsuper(patients)\npatients.createIndex({\n- index: { fields: ['code', 'fullName'] },\n+ index: { fields: ['fullName', 'code'] },\n})\n}\n@@ -37,10 +38,9 @@ export class PatientRepository extends Repository<Patient> {\nasync searchPaged(\ntext: string,\npageRequest: PageRequest = UnpagedRequest,\n+ sortRequest: SortRequest = Unsorted,\n): Promise<Page<Patient>> {\n- return super\n- .search({\n- selector: {\n+ const selector: any = {\n$or: [\n{\nfullName: {\n@@ -51,26 +51,34 @@ export class PatientRepository extends Repository<Patient> {\ncode: text,\n},\n],\n- },\n- skip: pageRequest.skip,\n- limit: pageRequest.limit,\n- })\n- .then(\n- (searchedData) =>\n- new Promise<Page<Patient>>((resolve) => {\n- const pagedResult: Page<Patient> = {\n- content: searchedData,\n- pageRequest,\n- hasNext: pageRequest.limit !== undefined && searchedData.length === pageRequest.limit,\n- hasPrevious: pageRequest.skip > 0,\n}\n- resolve(pagedResult)\n- }),\n- )\n+ sortRequest.sorts.forEach((s) => {\n+ selector[s.field] = { $gt: null }\n+ })\n+\n+ const result = await super\n+ .search({\n+ selector,\n+ limit: pageRequest.size,\n+ skip:\n+ pageRequest.number && pageRequest.size ? (pageRequest.number - 1) * pageRequest.size : 0,\n+ sort:\n+ sortRequest.sorts.length > 0\n+ ? sortRequest.sorts.map((s) => ({ [s.field]: s.direction }))\n+ : undefined,\n+ })\n.catch((err) => {\nconsole.log(err)\nreturn err\n})\n+\n+ const pagedResult: Page<Patient> = {\n+ content: result,\n+ pageRequest,\n+ hasNext: pageRequest.size !== undefined && result.length === pageRequest.size,\n+ hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n+ }\n+ return pagedResult\n}\nasync save(entity: Patient): Promise<Patient> {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -55,18 +55,19 @@ export default class Repository<T extends AbstractDBModel> {\nconst result = await this.db.find({\nselector,\nsort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\n- limit: pageRequest.limit,\n- skip: pageRequest.skip,\n+ limit: pageRequest.size,\n+ skip:\n+ pageRequest.number && pageRequest.size ? (pageRequest.number - 1) * pageRequest.size : 0,\n})\nconst mappedResult = result.docs.map(mapDocument)\nconst pagedResult: Page<T> = {\ncontent: mappedResult,\n- hasNext: pageRequest.limit !== undefined && mappedResult.length === pageRequest.limit,\n- hasPrevious: pageRequest.skip > 0,\n+ hasNext: pageRequest.size !== undefined && mappedResult.length === pageRequest.size,\n+ hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\npageRequest: {\n- skip: pageRequest.skip,\n- limit: pageRequest.limit,\n+ size: pageRequest.size,\n+ number: pageRequest.number,\n},\n}\nreturn pagedResult\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -26,16 +26,16 @@ const ViewPatients = () => {\nconst setButtonToolBar = useButtonToolbarSetter()\nconst [userPageRequest, setUserPageRequest] = useState<PageRequest>({\n- skip: 0,\n- limit: 1,\n+ size: 1,\n+ number: 1,\n})\nconst setNextPageRequest = () => {\nsetUserPageRequest((p) => {\n- if (p.limit) {\n+ if (p && p.number && p.number >= 0 && p.size) {\nconst newPageRequest: PageRequest = {\n- limit: p.limit,\n- skip: p.skip + p.limit,\n+ number: p.number + 1,\n+ size: p.size,\n}\nreturn newPageRequest\n}\n@@ -45,10 +45,10 @@ const ViewPatients = () => {\nconst setPreviousPageRequest = () => {\nsetUserPageRequest((p) => {\n- if (p.limit) {\n+ if (p.number && p.size) {\nreturn {\n- limit: p.limit,\n- skip: p.skip - p.limit,\n+ number: p.number - 1,\n+ size: p.size,\n}\n}\nreturn p\n@@ -60,14 +60,20 @@ const ViewPatients = () => {\nuseEffect(() => {\nconst sortRequest: SortRequest = {\n- sorts: [{ field: 'code', direction: 'desc' }],\n+ sorts: [\n+ { field: 'fullName', direction: 'asc' },\n+ { field: 'code', direction: 'asc' },\n+ ],\n}\ndispatch(searchPatients(debouncedSearchText, sortRequest, userPageRequest))\n}, [dispatch, debouncedSearchText, userPageRequest])\nuseEffect(() => {\nconst sortRequest: SortRequest = {\n- sorts: [{ field: 'code', direction: 'desc' }],\n+ sorts: [\n+ { field: 'fullName', direction: 'asc' },\n+ { field: 'code', direction: 'asc' },\n+ ],\n}\ndispatch(fetchPatients(sortRequest, userPageRequest))\n@@ -136,7 +142,7 @@ const ViewPatients = () => {\n<PageComponent\nhasNext={patients.hasNext}\nhasPrevious={patients.hasPrevious}\n- pageNumber={userPageRequest.limit && userPageRequest.skip / userPageRequest.limit + 1}\n+ pageNumber={userPageRequest.number}\nsetPreviousPageRequest={setPreviousPageRequest}\nsetNextPageRequest={setNextPageRequest}\n/>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patients-slice.ts",
"new_path": "src/patients/patients-slice.ts",
"diff": "@@ -17,10 +17,6 @@ const initialState: PatientsState = {\ncontent: [],\nhasNext: false,\nhasPrevious: false,\n- pageRequest: {\n- skip: 0,\n- limit: 1,\n- },\n},\n}\n@@ -42,8 +38,8 @@ const patientsSlice = createSlice({\nexport const { fetchPatientsStart, fetchPatientsSuccess } = patientsSlice.actions\nexport const fetchPatients = (\n- sortRequest: SortRequest,\n- pageRequest: PageRequest,\n+ sortRequest: SortRequest = Unsorted,\n+ pageRequest: PageRequest = UnpagedRequest,\n): AppThunk => async (dispatch) => {\ndispatch(fetchPatientsStart())\nconst patients = await PatientRepository.findAllPaged(sortRequest, pageRequest)\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): refactor code as recommended
Change Page interface, Fix failing tests
fix #1969 |
288,347 | 02.05.2020 09:37:50 | -7,200 | 9ca5232632503fbefb5ffae4e4d23a10d44fc62c | feat(add new script for checking missing translations): translations
I add new dep for running typscript script(ts-node). I update the linter path for checking the new
folder scripts. With the command yarn translation:check you can check if some translations are
missing. All erros will print in the console
fix | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -21,7 +21,7 @@ module.exports = {\n},\nparser: '@typescript-eslint/parser',\nparserOptions: {\n- project: './tsconfig.json',\n+ project: ['./tsconfig.json', './scripts/tsconfig.json'],\ntsconfigRootDir: './',\n},\nsettings: {\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"prepublishOnly\": \"npm run build\",\n\"test\": \"react-scripts test --detectOpenHandles\",\n\"test:ci\": \"cross-env CI=true react-scripts test --passWithNoTests\",\n- \"lint\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\"\",\n- \"lint:fix\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" --fix\",\n+ \"lint\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\"\",\n+ \"lint:fix\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\" --fix\",\n\"lint-staged\": \"lint-staged\",\n\"commitlint\": \"commitlint\",\n- \"coveralls\": \"npm run test:ci -- --coverage --watchAll=false && cat ./coverage/lcov.info\"\n+ \"coveralls\": \"npm run test:ci -- --coverage --watchAll=false && cat ./coverage/lcov.info\",\n+ \"translation:check\": \"ts-node-script scripts/checkMissingTranslations.ts\"\n},\n\"browserslist\": {\n\"production\": [\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "report.20200502.093222.73540.0.001.json",
"diff": "+\n+{\n+ \"header\": {\n+ \"reportVersion\": 2,\n+ \"event\": \"Allocation failed - JavaScript heap out of memory\",\n+ \"trigger\": \"FatalError\",\n+ \"filename\": \"report.20200502.093222.73540.0.001.json\",\n+ \"dumpEventTime\": \"2020-05-02T09:32:22Z\",\n+ \"dumpEventTimeStamp\": \"1588404742883\",\n+ \"processId\": 73540,\n+ \"threadId\": null,\n+ \"cwd\": \"/Users/marcomoretti/Projects/opensoruce/hospitalrun-frontend\",\n+ \"commandLine\": [\n+ \"/usr/local/bin/node\",\n+ \"/Users/marcomoretti/Library/Application Support/JetBrains/Toolbox/apps/WebStorm/ch-0/201.6668.106/WebStorm.app/Contents/plugins/JavaScriptLanguage/jsLanguageServicesImpl/js-language-service.js\",\n+ \"-id=1588329429193\",\n+ \"-debug-name=typescript\"\n+ ],\n+ \"nodejsVersion\": \"v12.16.2\",\n+ \"wordSize\": 64,\n+ \"arch\": \"x64\",\n+ \"platform\": \"darwin\",\n+ \"componentVersions\": {\n+ \"node\": \"12.16.2\",\n+ \"v8\": \"7.8.279.23-node.34\",\n+ \"uv\": \"1.34.2\",\n+ \"zlib\": \"1.2.11\",\n+ \"brotli\": \"1.0.7\",\n+ \"ares\": \"1.15.0\",\n+ \"modules\": \"72\",\n+ \"nghttp2\": \"1.40.0\",\n+ \"napi\": \"5\",\n+ \"llhttp\": \"2.0.4\",\n+ \"http_parser\": \"2.9.3\",\n+ \"openssl\": \"1.1.1e\",\n+ \"cldr\": \"36.0\",\n+ \"icu\": \"65.1\",\n+ \"tz\": \"2019c\",\n+ \"unicode\": \"12.1\"\n+ },\n+ \"release\": {\n+ \"name\": \"node\",\n+ \"lts\": \"Erbium\",\n+ \"headersUrl\": \"https://nodejs.org/download/release/v12.16.2/node-v12.16.2-headers.tar.gz\",\n+ \"sourceUrl\": \"https://nodejs.org/download/release/v12.16.2/node-v12.16.2.tar.gz\"\n+ },\n+ \"osName\": \"Darwin\",\n+ \"osRelease\": \"19.4.0\",\n+ \"osVersion\": \"Darwin Kernel Version 19.4.0: Wed Mar 4 22:28:40 PST 2020; root:xnu-6153.101.6~15/RELEASE_X86_64\",\n+ \"osMachine\": \"x86_64\",\n+ \"cpus\": [\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 170871260,\n+ \"nice\": 0,\n+ \"sys\": 108802040,\n+ \"idle\": 1064377800,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 23518260,\n+ \"nice\": 0,\n+ \"sys\": 15214070,\n+ \"idle\": 1305316280,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 148958620,\n+ \"nice\": 0,\n+ \"sys\": 69924470,\n+ \"idle\": 1125165810,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 21378000,\n+ \"nice\": 0,\n+ \"sys\": 10219120,\n+ \"idle\": 1312451370,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 123761580,\n+ \"nice\": 0,\n+ \"sys\": 53897210,\n+ \"idle\": 1166389990,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 21588560,\n+ \"nice\": 0,\n+ \"sys\": 8980710,\n+ \"idle\": 1313479140,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 107123810,\n+ \"nice\": 0,\n+ \"sys\": 43481380,\n+ \"idle\": 1193443510,\n+ \"irq\": 0\n+ },\n+ {\n+ \"model\": \"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz\",\n+ \"speed\": 2700,\n+ \"user\": 22214630,\n+ \"nice\": 0,\n+ \"sys\": 8390440,\n+ \"idle\": 1313443260,\n+ \"irq\": 0\n+ }\n+ ],\n+ \"networkInterfaces\": [\n+ {\n+ \"name\": \"lo0\",\n+ \"internal\": true,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"127.0.0.1\",\n+ \"netmask\": \"255.0.0.0\",\n+ \"family\": \"IPv4\"\n+ },\n+ {\n+ \"name\": \"lo0\",\n+ \"internal\": true,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"::1\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 0\n+ },\n+ {\n+ \"name\": \"lo0\",\n+ \"internal\": true,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"fe80::1\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 1\n+ },\n+ {\n+ \"name\": \"en0\",\n+ \"internal\": false,\n+ \"mac\": \"78:4f:43:80:35:9c\",\n+ \"address\": \"fe80::1046:5fe3:8e4a:ba31\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 5\n+ },\n+ {\n+ \"name\": \"en0\",\n+ \"internal\": false,\n+ \"mac\": \"78:4f:43:80:35:9c\",\n+ \"address\": \"192.168.1.189\",\n+ \"netmask\": \"255.255.255.0\",\n+ \"family\": \"IPv4\"\n+ },\n+ {\n+ \"name\": \"en0\",\n+ \"internal\": false,\n+ \"mac\": \"78:4f:43:80:35:9c\",\n+ \"address\": \"2001:b07:6462:c652:100d:4cef:6739:101\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 0\n+ },\n+ {\n+ \"name\": \"en0\",\n+ \"internal\": false,\n+ \"mac\": \"78:4f:43:80:35:9c\",\n+ \"address\": \"2001:b07:6462:c652:2871:83f0:e3a3:c023\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 0\n+ },\n+ {\n+ \"name\": \"awdl0\",\n+ \"internal\": false,\n+ \"mac\": \"a2:93:e4:52:e2:5b\",\n+ \"address\": \"fe80::a093:e4ff:fe52:e25b\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 15\n+ },\n+ {\n+ \"name\": \"llw0\",\n+ \"internal\": false,\n+ \"mac\": \"a2:93:e4:52:e2:5b\",\n+ \"address\": \"fe80::a093:e4ff:fe52:e25b\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 16\n+ },\n+ {\n+ \"name\": \"utun0\",\n+ \"internal\": false,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"fe80::8236:539f:66b8:7a94\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 17\n+ },\n+ {\n+ \"name\": \"utun1\",\n+ \"internal\": false,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"fe80::ab9f:c9c6:dd7f:fdae\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 18\n+ },\n+ {\n+ \"name\": \"utun2\",\n+ \"internal\": false,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"fe80::930f:fe4d:fada:8c\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 19\n+ },\n+ {\n+ \"name\": \"utun3\",\n+ \"internal\": false,\n+ \"mac\": \"00:00:00:00:00:00\",\n+ \"address\": \"fe80::ec6f:e975:de9d:d512\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 20\n+ },\n+ {\n+ \"name\": \"en6\",\n+ \"internal\": false,\n+ \"mac\": \"ac:de:48:00:11:22\",\n+ \"address\": \"fe80::aede:48ff:fe00:1122\",\n+ \"netmask\": \"ffff:ffff:ffff:ffff::\",\n+ \"family\": \"IPv6\",\n+ \"scopeid\": 4\n+ }\n+ ],\n+ \"host\": \"MBP-di-Marco.lan\"\n+ },\n+ \"javascriptStack\": {\n+ \"message\": \"No stack.\",\n+ \"stack\": [\n+ \"Unavailable.\"\n+ ]\n+ },\n+ \"nativeStack\": [\n+ {\n+ \"pc\": \"0x00000001001636d3\",\n+ \"symbol\": \"report::TriggerNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, v8::Local<v8::String>) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x0000000100084d5a\",\n+ \"symbol\": \"node::OnFatalError(char const*, char const*) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x0000000100186477\",\n+ \"symbol\": \"v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x0000000100186417\",\n+ \"symbol\": \"v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x00000001003141c5\",\n+ \"symbol\": \"v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x0000000100315a3a\",\n+ \"symbol\": \"v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010031246c\",\n+ \"symbol\": \"v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010031026e\",\n+ \"symbol\": \"v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010031c13a\",\n+ \"symbol\": \"v8::internal::Heap::AllocateRawWithLightRetry(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010031c1c1\",\n+ \"symbol\": \"v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x00000001002e9dfa\",\n+ \"symbol\": \"v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010063f028\",\n+ \"symbol\": \"v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x000000010097d5b9\",\n+ \"symbol\": \"Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/usr/local/bin/node]\"\n+ },\n+ {\n+ \"pc\": \"0x0000000100904441\",\n+ \"symbol\": \"Builtins_GrowFastSmiOrObjectElements [/usr/local/bin/node]\"\n+ }\n+ ],\n+ \"javascriptHeap\": {\n+ \"totalMemory\": 2183659520,\n+ \"totalCommittedMemory\": 2166342576,\n+ \"usedMemory\": 2136066464,\n+ \"availableMemory\": 53900224,\n+ \"memoryLimit\": 2197815296,\n+ \"heapSpaces\": {\n+ \"read_only_space\": {\n+ \"memorySize\": 262144,\n+ \"committedMemory\": 33088,\n+ \"capacity\": 32808,\n+ \"used\": 32808,\n+ \"available\": 0\n+ },\n+ \"new_space\": {\n+ \"memorySize\": 33554432,\n+ \"committedMemory\": 17910120,\n+ \"capacity\": 16759296,\n+ \"used\": 6143600,\n+ \"available\": 10615696\n+ },\n+ \"old_space\": {\n+ \"memorySize\": 1988501504,\n+ \"committedMemory\": 1987577272,\n+ \"capacity\": 1982808168,\n+ \"used\": 1970438712,\n+ \"available\": 12369456\n+ },\n+ \"code_space\": {\n+ \"memorySize\": 5148672,\n+ \"committedMemory\": 4859904,\n+ \"capacity\": 4394112,\n+ \"used\": 4394112,\n+ \"available\": 0\n+ },\n+ \"map_space\": {\n+ \"memorySize\": 1314816,\n+ \"committedMemory\": 1084240,\n+ \"capacity\": 756480,\n+ \"used\": 756480,\n+ \"available\": 0\n+ },\n+ \"large_object_space\": {\n+ \"memorySize\": 154492928,\n+ \"committedMemory\": 154492928,\n+ \"capacity\": 153977168,\n+ \"used\": 153977168,\n+ \"available\": 0\n+ },\n+ \"code_large_object_space\": {\n+ \"memorySize\": 385024,\n+ \"committedMemory\": 385024,\n+ \"capacity\": 323584,\n+ \"used\": 323584,\n+ \"available\": 0\n+ },\n+ \"new_large_object_space\": {\n+ \"memorySize\": 0,\n+ \"committedMemory\": 0,\n+ \"capacity\": 16759296,\n+ \"used\": 0,\n+ \"available\": 16759296\n+ }\n+ }\n+ },\n+ \"resourceUsage\": {\n+ \"userCpuSeconds\": 1341.99,\n+ \"kernelCpuSeconds\": 566.013,\n+ \"cpuConsumptionPercent\": 2.53344,\n+ \"maxRss\": 2342430703616,\n+ \"pageFaults\": {\n+ \"IORequired\": 0,\n+ \"IONotRequired\": 11092751\n+ },\n+ \"fsActivity\": {\n+ \"reads\": 0,\n+ \"writes\": 0\n+ }\n+ },\n+ \"libuv\": [\n+ ],\n+ \"workers\": [\n+ ],\n+ \"environmentVariables\": {\n+ \"PATH\": \"/Users/marcomoretti/bin:/usr/local/bin:/System/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/marcomoretti/Library/Android/sdk/platform-tools:/Users/marcomoretti/flutter/bin:/Users/marcomoretti/Library/Python/3.7/bin\",\n+ \"SHELL\": \"/bin/zsh\",\n+ \"PAGER\": \"less\",\n+ \"LSCOLORS\": \"Gxfxcxdxbxegedabagacad\",\n+ \"OLDPWD\": \"/\",\n+ \"USER\": \"marcomoretti\",\n+ \"ZSH\": \"/Users/marcomoretti/.oh-my-zsh\",\n+ \"TMPDIR\": \"/var/folders/pb/n1md4_q53m5fc62nk744m0m00000gn/T/\",\n+ \"SSH_AUTH_SOCK\": \"/private/tmp/com.apple.launchd.Vf6PGfw5ga/Listeners\",\n+ \"XPC_FLAGS\": \"0x0\",\n+ \"VERSIONER_PYTHON_VERSION\": \"2.7\",\n+ \"__CF_USER_TEXT_ENCODING\": \"0x1F5:0x0:0x4\",\n+ \"LESS\": \"-R\",\n+ \"LOGNAME\": \"marcomoretti\",\n+ \"LC_CTYPE\": \"it_IT.UTF-8\",\n+ \"XPC_SERVICE_NAME\": \"com.jetbrains.WebStorm.4112\",\n+ \"PWD\": \"/Users/marcomoretti/Projects/opensoruce/hospitalrun-frontend\",\n+ \"HOME\": \"/Users/marcomoretti\"\n+ },\n+ \"userLimits\": {\n+ \"core_file_size_blocks\": {\n+ \"soft\": 0,\n+ \"hard\": \"unlimited\"\n+ },\n+ \"data_seg_size_kbytes\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ },\n+ \"file_size_blocks\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ },\n+ \"max_locked_memory_bytes\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ },\n+ \"max_memory_size_kbytes\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ },\n+ \"open_files\": {\n+ \"soft\": 24576,\n+ \"hard\": \"unlimited\"\n+ },\n+ \"stack_size_bytes\": {\n+ \"soft\": 8388608,\n+ \"hard\": 67104768\n+ },\n+ \"cpu_time_seconds\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ },\n+ \"max_user_processes\": {\n+ \"soft\": 2784,\n+ \"hard\": 4176\n+ },\n+ \"virtual_memory_kbytes\": {\n+ \"soft\": \"unlimited\",\n+ \"hard\": \"unlimited\"\n+ }\n+ },\n+ \"sharedObjects\": [\n+ \"/usr/local/bin/node\",\n+ \"/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation\",\n+ \"/usr/lib/libSystem.B.dylib\",\n+ \"/usr/lib/libc++.1.dylib\",\n+ \"/usr/lib/libobjc.A.dylib\",\n+ \"/usr/lib/libfakelink.dylib\",\n+ \"/usr/lib/libDiagnosticMessagesClient.dylib\",\n+ \"/usr/lib/libicucore.A.dylib\",\n+ \"/usr/lib/libz.1.dylib\",\n+ \"/usr/lib/libc++abi.dylib\",\n+ \"/usr/lib/system/libcache.dylib\",\n+ \"/usr/lib/system/libcommonCrypto.dylib\",\n+ \"/usr/lib/system/libcompiler_rt.dylib\",\n+ \"/usr/lib/system/libcopyfile.dylib\",\n+ \"/usr/lib/system/libcorecrypto.dylib\",\n+ \"/usr/lib/system/libdispatch.dylib\",\n+ \"/usr/lib/system/libdyld.dylib\",\n+ \"/usr/lib/system/libkeymgr.dylib\",\n+ \"/usr/lib/system/liblaunch.dylib\",\n+ \"/usr/lib/system/libmacho.dylib\",\n+ \"/usr/lib/system/libquarantine.dylib\",\n+ \"/usr/lib/system/libremovefile.dylib\",\n+ \"/usr/lib/system/libsystem_asl.dylib\",\n+ \"/usr/lib/system/libsystem_blocks.dylib\",\n+ \"/usr/lib/system/libsystem_c.dylib\",\n+ \"/usr/lib/system/libsystem_configuration.dylib\",\n+ \"/usr/lib/system/libsystem_coreservices.dylib\",\n+ \"/usr/lib/system/libsystem_darwin.dylib\",\n+ \"/usr/lib/system/libsystem_dnssd.dylib\",\n+ \"/usr/lib/system/libsystem_featureflags.dylib\",\n+ \"/usr/lib/system/libsystem_info.dylib\",\n+ \"/usr/lib/system/libsystem_m.dylib\",\n+ \"/usr/lib/system/libsystem_malloc.dylib\",\n+ \"/usr/lib/system/libsystem_networkextension.dylib\",\n+ \"/usr/lib/system/libsystem_notify.dylib\",\n+ \"/usr/lib/system/libsystem_sandbox.dylib\",\n+ \"/usr/lib/system/libsystem_secinit.dylib\",\n+ \"/usr/lib/system/libsystem_kernel.dylib\",\n+ \"/usr/lib/system/libsystem_platform.dylib\",\n+ \"/usr/lib/system/libsystem_pthread.dylib\",\n+ \"/usr/lib/system/libsystem_symptoms.dylib\",\n+ \"/usr/lib/system/libsystem_trace.dylib\",\n+ \"/usr/lib/system/libunwind.dylib\",\n+ \"/usr/lib/system/libxpc.dylib\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/CoreServices\",\n+ \"/System/Library/Frameworks/CFNetwork.framework/Versions/A/CFNetwork\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/FSEvents.framework/Versions/A/FSEvents\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/CarbonCore\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Metadata\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/OSServices.framework/Versions/A/OSServices\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/SearchKit.framework/Versions/A/SearchKit\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/AE.framework/Versions/A/AE\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/LaunchServices\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/DictionaryServices.framework/Versions/A/DictionaryServices\",\n+ \"/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/SharedFileList.framework/Versions/A/SharedFileList\",\n+ \"/System/Library/Frameworks/Foundation.framework/Versions/C/Foundation\",\n+ \"/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit\",\n+ \"/System/Library/Frameworks/SystemConfiguration.framework/Versions/A/SystemConfiguration\",\n+ \"/System/Library/Frameworks/Security.framework/Versions/A/Security\",\n+ \"/usr/lib/libsqlite3.dylib\",\n+ \"/usr/lib/libxml2.2.dylib\",\n+ \"/usr/lib/libnetwork.dylib\",\n+ \"/usr/lib/libapple_nghttp2.dylib\",\n+ \"/usr/lib/libauto.dylib\",\n+ \"/usr/lib/libcompression.dylib\",\n+ \"/System/Library/Frameworks/DiskArbitration.framework/Versions/A/DiskArbitration\",\n+ \"/usr/lib/libarchive.2.dylib\",\n+ \"/usr/lib/liblangid.dylib\",\n+ \"/usr/lib/libCRFSuite.dylib\",\n+ \"/usr/lib/liblzma.5.dylib\",\n+ \"/usr/lib/libenergytrace.dylib\",\n+ \"/usr/lib/libbsm.0.dylib\",\n+ \"/usr/lib/system/libkxld.dylib\",\n+ \"/System/Library/PrivateFrameworks/AppleFSCompression.framework/Versions/A/AppleFSCompression\",\n+ \"/usr/lib/libcoretls.dylib\",\n+ \"/usr/lib/libcoretls_cfhelpers.dylib\",\n+ \"/usr/lib/libpam.2.dylib\",\n+ \"/usr/lib/libxar.1.dylib\",\n+ \"/usr/lib/libbz2.1.0.dylib\",\n+ \"/usr/lib/libiconv.2.dylib\",\n+ \"/usr/lib/libcharset.1.dylib\",\n+ \"/usr/lib/libpcap.A.dylib\",\n+ \"/System/Library/Frameworks/NetFS.framework/Versions/A/NetFS\",\n+ \"/System/Library/PrivateFrameworks/NetAuth.framework/Versions/A/NetAuth\",\n+ \"/System/Library/PrivateFrameworks/login.framework/Versions/A/Frameworks/loginsupport.framework/Versions/A/loginsupport\",\n+ \"/System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC\",\n+ \"/System/Library/PrivateFrameworks/CoreNLP.framework/Versions/A/CoreNLP\",\n+ \"/System/Library/PrivateFrameworks/MetadataUtilities.framework/Versions/A/MetadataUtilities\",\n+ \"/usr/lib/libmecabra.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate\",\n+ \"/usr/lib/libmecab.dylib\",\n+ \"/usr/lib/libgermantok.dylib\",\n+ \"/usr/lib/libThaiTokenizer.dylib\",\n+ \"/usr/lib/libChineseTokenizer.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/vImage\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/vecLib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvMisc.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvDSP.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLinearAlgebra.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libSparseBLAS.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libQuadrature.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBNNS.dylib\",\n+ \"/System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libSparse.dylib\",\n+ \"/System/Library/PrivateFrameworks/LanguageModeling.framework/Versions/A/LanguageModeling\",\n+ \"/System/Library/PrivateFrameworks/CoreEmoji.framework/Versions/A/CoreEmoji\",\n+ \"/System/Library/PrivateFrameworks/LinguisticData.framework/Versions/A/LinguisticData\",\n+ \"/System/Library/PrivateFrameworks/Lexicon.framework/Versions/A/Lexicon\",\n+ \"/usr/lib/libcmph.dylib\",\n+ \"/System/Library/Frameworks/OpenDirectory.framework/Versions/A/Frameworks/CFOpenDirectory.framework/Versions/A/CFOpenDirectory\",\n+ \"/System/Library/Frameworks/OpenDirectory.framework/Versions/A/OpenDirectory\",\n+ \"/System/Library/PrivateFrameworks/APFS.framework/Versions/A/APFS\",\n+ \"/System/Library/Frameworks/SecurityFoundation.framework/Versions/A/SecurityFoundation\",\n+ \"/usr/lib/libutil.dylib\",\n+ \"/System/Library/PrivateFrameworks/CoreServicesStore.framework/Versions/A/CoreServicesStore\",\n+ \"/System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement\",\n+ \"/System/Library/PrivateFrameworks/BackgroundTaskManagement.framework/Versions/A/BackgroundTaskManagement\",\n+ \"/usr/lib/libxslt.1.dylib\"\n+ ]\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/tsconfig.json",
"diff": "+{\n+ \"extends\": \"../tsconfig.json\",\n+ \"include\": [\"./checkMissingTranslations.ts\"],\n+ \"compilerOptions\": {\n+ \"module\": \"commonjs\"\n+ }\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(add new script for checking missing translations): translations
I add new dep for running typscript script(ts-node). I update the linter path for checking the new
folder scripts. With the command yarn translation:check you can check if some translations are
missing. All erros will print in the console
fix #1919 |
288,334 | 02.05.2020 14:31:46 | -7,200 | e972aaebce02badce360645b3e722135b19f3056 | fix(moment): add resolutions key on package.json | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"typescript\": \"~3.8.2\",\n\"uuid\": \"^8.0.0\",\n\"validator\": \"^13.0.0\"\n+ },\n+ \"resolutions\": {\n+ \"moment\": \"2.24.0\"\n+ },\n+ \"comments\": {\n+ \"resolutions\": \"Added this key as temp fix https://github.com/moment/moment/issues/5484\",\n},\n\"repository\": {\n\"type\": \"git\",\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(moment): add resolutions key on package.json |
288,307 | 02.05.2020 14:08:45 | -3,600 | 254273f889fd0d24189c634226b6c07d8d043532 | feat(patients): escape string in appointments search
Fix
Fix
Fix
Fix | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/AppointmentRepository.test.ts",
"new_path": "src/__tests__/clients/db/AppointmentRepository.test.ts",
"diff": "import AppointmentRepository from 'clients/db/AppointmentRepository'\n-import { appointments } from 'config/pouchdb'\n+import { appointments, patients } from 'config/pouchdb'\nimport Appointment from 'model/Appointment'\nconst uuidV4Regex = /^[A-F\\d]{8}-[A-F\\d]{4}-4[A-F\\d]{3}-[89AB][A-F\\d]{3}-[A-F\\d]{12}$/i\n@@ -24,6 +24,21 @@ describe('Appointment Repository', () => {\n})\n})\n+ describe('searchPatientAppointments', () => {\n+ it('should escape all special chars from search text', async () => {\n+ await patients.put({ _id: 'id2222' })\n+ await appointments.put({ _id: 'id3333', patientId: 'id2222', location: 'id-]?}(){*[$+.^\\\\' })\n+\n+ const result = await AppointmentRepository.searchPatientAppointments(\n+ 'id2222',\n+ 'id-]?}(){*[$+.^\\\\',\n+ )\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].id).toEqual('id3333')\n+ })\n+ })\n+\ndescribe('save', () => {\nit('should create an id that is a uuid', async () => {\nconst newAppointment = await AppointmentRepository.save({\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/AppointmentRepository.ts",
"new_path": "src/clients/db/AppointmentRepository.ts",
"diff": "+import escapeStringRegexp from 'escape-string-regexp'\nimport Appointment from 'model/Appointment'\nimport { appointments } from 'config/pouchdb'\nimport Repository from './Repository'\n@@ -9,6 +10,7 @@ export class AppointmentRepository extends Repository<Appointment> {\n// Fuzzy search for patient appointments. Used for patient appointment search bar\nasync searchPatientAppointments(patientId: string, text: string): Promise<Appointment[]> {\n+ const escapedString = escapeStringRegexp(text)\nreturn super.search({\nselector: {\n$and: [\n@@ -19,17 +21,17 @@ export class AppointmentRepository extends Repository<Appointment> {\n$or: [\n{\nlocation: {\n- $regex: RegExp(text, 'i'),\n+ $regex: RegExp(escapedString, 'i'),\n},\n},\n{\nreason: {\n- $regex: RegExp(text, 'i'),\n+ $regex: RegExp(escapedString, 'i'),\n},\n},\n{\ntype: {\n- $regex: RegExp(text, 'i'),\n+ $regex: RegExp(escapedString, 'i'),\n},\n},\n],\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patients): escape string in appointments search (#2031)
Fix #1997
Fix #2003
Fix #1999
Fix #2029 |
288,323 | 26.04.2020 17:46:59 | 18,000 | 2e9e985c877db2f095ba11fb6900fc177283d5cc | feat(incidents): add incident related routing | [
{
"change_type": "MODIFY",
"old_path": "src/HospitalRun.tsx",
"new_path": "src/HospitalRun.tsx",
"diff": "@@ -17,6 +17,7 @@ import { RootState } from './store'\nimport Navbar from './components/Navbar'\nimport PrivateRoute from './components/PrivateRoute'\nimport Patients from './patients/Patients'\n+import Incidents from './incidents/Incidents'\nconst HospitalRun = () => {\nconst { title } = useSelector((state: RootState) => state.title)\n@@ -74,6 +75,7 @@ const HospitalRun = () => {\n/>\n<PrivateRoute isAuthenticated path=\"/patients\" component={Patients} />\n<PrivateRoute isAuthenticated path=\"/labs\" component={Labs} />\n+ <PrivateRoute isAuthenticated path=\"/incidents\" component={Incidents} />\n</Switch>\n</div>\n<Toaster autoClose={5000} hideProgressBar draggable />\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/HospitalRun.test.tsx",
"new_path": "src/__tests__/HospitalRun.test.tsx",
"diff": "@@ -20,6 +20,7 @@ import Patient from '../model/Patient'\nimport Appointment from '../model/Appointment'\nimport HospitalRun from '../HospitalRun'\nimport Permissions from '../model/Permissions'\n+import Incidents from '../incidents/Incidents'\nconst mockStore = configureMockStore([thunk])\n@@ -256,6 +257,52 @@ describe('HospitalRun', () => {\nexpect(wrapper.find(Dashboard)).toHaveLength(1)\n})\n})\n+\n+ describe('/incidents', () => {\n+ it('should render the Incidents component when /incidents is accessed', async () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.ViewIncidents] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents']}>\n+ <HospitalRun />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+ })\n+ wrapper.update()\n+\n+ expect(wrapper.find(Incidents)).toHaveLength(1)\n+ })\n+\n+ it('should render the dashboard if the user does not have permissions to view incidents', () => {\n+ jest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents']}>\n+ <HospitalRun />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(Incidents)).toHaveLength(0)\n+ expect(wrapper.find(Dashboard)).toHaveLength(1)\n+ })\n+ })\n})\ndescribe('layout', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Sidebar.test.tsx",
"new_path": "src/__tests__/components/Sidebar.test.tsx",
"diff": "@@ -326,4 +326,93 @@ describe('Sidebar', () => {\nexpect(history.location.pathname).toEqual('/labs')\n})\n})\n+\n+ describe('incident links', () => {\n+ it('should render the main incidents link', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(5).text().trim()).toEqual('incidents.label')\n+ })\n+\n+ it('should render the new incident report link', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(6).text().trim()).toEqual('incidents.reports.new')\n+ })\n+\n+ it('should render the incidents list link', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(7).text().trim()).toEqual('incidents.reports.label')\n+ })\n+\n+ it('main incidents link should be active when the current path is /incidents', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(5).prop('active')).toBeTruthy()\n+ })\n+\n+ it('should navigate to /incidents when the main incident link is clicked', () => {\n+ const wrapper = setup('/')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ act(() => {\n+ const onClick = listItems.at(5).prop('onClick') as any\n+ onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual('/incidents')\n+ })\n+\n+ it('new incident report link should be active when the current path is /incidents/new', () => {\n+ const wrapper = setup('/incidents/new')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(6).prop('active')).toBeTruthy()\n+ })\n+\n+ it('should navigate to /incidents/new when the new labs link is clicked', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ act(() => {\n+ const onClick = listItems.at(6).prop('onClick') as any\n+ onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual('/incidents/new')\n+ })\n+\n+ it('incidents list link should be active when the current path is /incidents', () => {\n+ const wrapper = setup('/incidents')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ expect(listItems.at(7).prop('active')).toBeTruthy()\n+ })\n+\n+ it('should navigate to /labs when the labs list link is clicked', () => {\n+ const wrapper = setup('/incidents/new')\n+\n+ const listItems = wrapper.find(ListItem)\n+\n+ act(() => {\n+ const onClick = listItems.at(7).prop('onClick') as any\n+ onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual('/incidents')\n+ })\n+ })\n})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/Incidents.test.tsx",
"diff": "+import '../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { MemoryRouter } from 'react-router'\n+import { Provider } from 'react-redux'\n+import thunk from 'redux-thunk'\n+import configureMockStore from 'redux-mock-store'\n+import { act } from '@testing-library/react'\n+import Permissions from 'model/Permissions'\n+import ViewIncident from '../../incidents/view/ViewIncident'\n+import Incidents from '../../incidents/Incidents'\n+import ReportIncident from '../../incidents/report/ReportIncident'\n+\n+const mockStore = configureMockStore([thunk])\n+\n+describe('Incidents', () => {\n+ describe('routing', () => {\n+ describe('/incidents/new', () => {\n+ it('should render the new lab request screen when /incidents/new is accessed', () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.ReportIncident] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents/new']}>\n+ <Incidents />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ReportIncident)).toHaveLength(1)\n+ })\n+\n+ it('should not navigate to /incidents/new if the user does not have RequestLab permissions', () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents/new']}>\n+ <Incidents />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ReportIncident)).toHaveLength(0)\n+ })\n+ })\n+\n+ describe('/incidents/:id', () => {\n+ it('should render the view lab screen when /incidents/:id is accessed', async () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [Permissions.ViewIncident] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ let wrapper: any\n+\n+ await act(async () => {\n+ wrapper = await mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents/1234']}>\n+ <Incidents />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewIncident)).toHaveLength(1)\n+ })\n+ })\n+\n+ it('should not navigate to /incidents/:id if the user does not have ViewIncident permissions', async () => {\n+ const store = mockStore({\n+ title: 'test',\n+ user: { permissions: [] },\n+ breadcrumbs: { breadcrumbs: [] },\n+ components: { sidebarCollapsed: false },\n+ })\n+\n+ const wrapper = await mount(\n+ <Provider store={store}>\n+ <MemoryRouter initialEntries={['/incidents/1234']}>\n+ <Incidents />\n+ </MemoryRouter>\n+ </Provider>,\n+ )\n+\n+ expect(wrapper.find(ViewIncident)).toHaveLength(0)\n+ })\n+ })\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/list/ViewIncidents.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { createMemoryHistory } from 'history'\n+import { act } from '@testing-library/react'\n+import { Provider } from 'react-redux'\n+import { Route, Router } from 'react-router'\n+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import Permissions from '../../../model/Permissions'\n+import * as titleUtil from '../../../page-header/useTitle'\n+import * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\n+import * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\n+import ViewIncidents from '../../../incidents/list/ViewIncidents'\n+\n+const mockStore = createMockStore([thunk])\n+\n+describe('View Incidents', () => {\n+ let history: any\n+\n+ let setButtonToolBarSpy: any\n+ const setup = async (permissions: Permissions[]) => {\n+ jest.resetAllMocks()\n+ jest.spyOn(breadcrumbUtil, 'default')\n+ setButtonToolBarSpy = jest.fn()\n+ jest.spyOn(titleUtil, 'default')\n+ jest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\n+\n+ history = createMemoryHistory()\n+ history.push(`/incidents`)\n+ const store = mockStore({\n+ title: '',\n+ user: {\n+ permissions,\n+ },\n+ })\n+\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await mount(\n+ <ButtonBarProvider.ButtonBarProvider>\n+ <Provider store={store}>\n+ <Router history={history}>\n+ <Route path=\"/incidents\">\n+ <ViewIncidents />\n+ </Route>\n+ </Router>\n+ </Provider>\n+ </ButtonBarProvider.ButtonBarProvider>,\n+ )\n+ })\n+ wrapper.update()\n+ return wrapper\n+ }\n+\n+ it('should set the title', async () => {\n+ await setup([Permissions.ViewIncidents])\n+\n+ expect(titleUtil.default).toHaveBeenCalledWith('incidents.reports.label')\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/report/ReportIncident.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { createMemoryHistory } from 'history'\n+import { act } from '@testing-library/react'\n+import { Provider } from 'react-redux'\n+import { Route, Router } from 'react-router'\n+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import Permissions from '../../../model/Permissions'\n+import * as titleUtil from '../../../page-header/useTitle'\n+import * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\n+import * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\n+import ReportIncident from '../../../incidents/report/ReportIncident'\n+\n+const mockStore = createMockStore([thunk])\n+\n+describe('Report Incident', () => {\n+ let history: any\n+\n+ let setButtonToolBarSpy: any\n+ const setup = async (permissions: Permissions[]) => {\n+ jest.resetAllMocks()\n+ jest.spyOn(breadcrumbUtil, 'default')\n+ setButtonToolBarSpy = jest.fn()\n+ jest.spyOn(titleUtil, 'default')\n+ jest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\n+\n+ history = createMemoryHistory()\n+ history.push(`/incidents/new`)\n+ const store = mockStore({\n+ title: '',\n+ user: {\n+ permissions,\n+ },\n+ })\n+\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await mount(\n+ <ButtonBarProvider.ButtonBarProvider>\n+ <Provider store={store}>\n+ <Router history={history}>\n+ <Route path=\"/incidents/new\">\n+ <ReportIncident />\n+ </Route>\n+ </Router>\n+ </Provider>\n+ </ButtonBarProvider.ButtonBarProvider>,\n+ )\n+ })\n+ wrapper.update()\n+ return wrapper\n+ }\n+\n+ it('should set the title', async () => {\n+ await setup([Permissions.ReportIncident])\n+\n+ expect(titleUtil.default).toHaveBeenCalledWith('incidents.reports.new')\n+ })\n+\n+ it('should set the breadcrumbs properly', async () => {\n+ await setup([Permissions.ReportIncident])\n+\n+ expect(breadcrumbUtil.default).toHaveBeenCalledWith([\n+ { i18nKey: 'incidents.reports.new', location: '/incidents/new' },\n+ ])\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/view/ViewIncident.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import { mount } from 'enzyme'\n+import { createMemoryHistory } from 'history'\n+import { act } from '@testing-library/react'\n+import { Provider } from 'react-redux'\n+import { Route, Router } from 'react-router'\n+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import Permissions from '../../../model/Permissions'\n+import * as titleUtil from '../../../page-header/useTitle'\n+import * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\n+import * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\n+import ViewIncident from '../../../incidents/view/ViewIncident'\n+\n+const mockStore = createMockStore([thunk])\n+\n+describe('View Incident', () => {\n+ let history: any\n+\n+ const setup = async (permissions: Permissions[]) => {\n+ jest.resetAllMocks()\n+ jest.spyOn(breadcrumbUtil, 'default')\n+ jest.spyOn(titleUtil, 'default')\n+\n+ history = createMemoryHistory()\n+ history.push(`/incidents/1234`)\n+ const store = mockStore({\n+ title: '',\n+ user: {\n+ permissions,\n+ },\n+ })\n+\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await mount(\n+ <ButtonBarProvider.ButtonBarProvider>\n+ <Provider store={store}>\n+ <Router history={history}>\n+ <Route path=\"/incidents/:id\">\n+ <ViewIncident />\n+ </Route>\n+ </Router>\n+ </Provider>\n+ </ButtonBarProvider.ButtonBarProvider>,\n+ )\n+ })\n+ wrapper.update()\n+ return wrapper\n+ }\n+\n+ it('should set the title', async () => {\n+ await setup([Permissions.ViewIncident])\n+\n+ expect(titleUtil.default).toHaveBeenCalledWith('incidents.reports.view')\n+ })\n+\n+ it('should set the breadcrumbs properly', async () => {\n+ await setup([Permissions.ViewIncident])\n+\n+ expect(breadcrumbUtil.default).toHaveBeenCalledWith([\n+ { i18nKey: 'incidents.reports.view', location: '/incidents/1234' },\n+ ])\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Sidebar.tsx",
"new_path": "src/components/Sidebar.tsx",
"diff": "@@ -39,6 +39,8 @@ const Sidebar = () => {\n? 'appointment'\n: splittedPath[1].includes('labs')\n? 'labs'\n+ : splittedPath[1].includes('incidents')\n+ ? 'incidents'\n: 'none',\n)\n@@ -230,6 +232,52 @@ const Sidebar = () => {\n</>\n)\n+ const getIncidentLinks = () => (\n+ <>\n+ <ListItem\n+ active={splittedPath[1].includes('incidents')}\n+ onClick={() => {\n+ navigateTo('/incidents')\n+ setExpansion('incidents')\n+ }}\n+ className=\"nav-item\"\n+ style={listItemStyle}\n+ >\n+ <Icon\n+ icon={\n+ splittedPath[1].includes('incidents') && expandedItem === 'incidents'\n+ ? 'down-arrow'\n+ : 'right-arrow'\n+ }\n+ style={expandibleArrow}\n+ />\n+ <Icon icon=\"lab\" /> {!sidebarCollapsed && t('incidents.label')}\n+ </ListItem>\n+ {splittedPath[1].includes('incidents') && expandedItem === 'incidents' && (\n+ <List layout=\"flush\" className=\"nav flex-column\">\n+ <ListItem\n+ className=\"nav-item\"\n+ style={listSubItemStyleNew}\n+ onClick={() => navigateTo('/incidents/new')}\n+ active={splittedPath[1].includes('incidents') && splittedPath.length > 2}\n+ >\n+ <Icon icon=\"add\" style={iconMargin} />\n+ {!sidebarCollapsed && t('incidents.reports.new')}\n+ </ListItem>\n+ <ListItem\n+ className=\"nav-item\"\n+ style={listSubItemStyle}\n+ onClick={() => navigateTo('/incidents')}\n+ active={splittedPath[1].includes('incidents') && splittedPath.length < 3}\n+ >\n+ <Icon icon=\"incident\" style={iconMargin} />\n+ {!sidebarCollapsed && t('incidents.reports.label')}\n+ </ListItem>\n+ </List>\n+ )}\n+ </>\n+ )\n+\nreturn (\n<nav\nclassName=\"col-md-2 d-none d-md-block bg-light sidebar\"\n@@ -251,6 +299,7 @@ const Sidebar = () => {\n{getPatientLinks()}\n{getAppointmentLinks()}\n{getLabLinks()}\n+ {getIncidentLinks()}\n</List>\n</div>\n</nav>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/Incidents.tsx",
"diff": "+import React from 'react'\n+import { Switch } from 'react-router'\n+import { useSelector } from 'react-redux'\n+import PrivateRoute from '../components/PrivateRoute'\n+import { RootState } from '../store'\n+import Permissions from '../model/Permissions'\n+import ViewIncidents from './list/ViewIncidents'\n+import ReportIncident from './report/ReportIncident'\n+import ViewIncident from './view/ViewIncident'\n+import useAddBreadcrumbs from '../breadcrumbs/useAddBreadcrumbs'\n+\n+const Incidents = () => {\n+ const { permissions } = useSelector((state: RootState) => state.user)\n+ const breadcrumbs = [\n+ {\n+ i18nKey: 'incidents.label',\n+ location: `/incidents`,\n+ },\n+ ]\n+ useAddBreadcrumbs(breadcrumbs, true)\n+\n+ return (\n+ <Switch>\n+ <PrivateRoute\n+ isAuthenticated={permissions.includes(Permissions.ViewIncidents)}\n+ exact\n+ path=\"/incidents\"\n+ component={ViewIncidents}\n+ />\n+ <PrivateRoute\n+ isAuthenticated={permissions.includes(Permissions.ReportIncident)}\n+ exact\n+ path=\"/incidents/new\"\n+ component={ReportIncident}\n+ />\n+ <PrivateRoute\n+ isAuthenticated={permissions.includes(Permissions.ViewIncident)}\n+ exact\n+ path=\"/incidents/:id\"\n+ component={ViewIncident}\n+ />\n+ </Switch>\n+ )\n+}\n+\n+export default Incidents\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/list/ViewIncidents.tsx",
"diff": "+import React from 'react'\n+import { useTranslation } from 'react-i18next'\n+import useTitle from '../../page-header/useTitle'\n+\n+const ViewIncidents = () => {\n+ const { t } = useTranslation()\n+ useTitle(t('incidents.reports.label'))\n+\n+ return <h1>Reported Incidents</h1>\n+}\n+\n+export default ViewIncidents\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/report/ReportIncident.tsx",
"diff": "+import React from 'react'\n+import { useTranslation } from 'react-i18next'\n+import useTitle from '../../page-header/useTitle'\n+import useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\n+\n+const ReportIncident = () => {\n+ const { t } = useTranslation()\n+ useTitle(t('incidents.reports.new'))\n+ const breadcrumbs = [\n+ {\n+ i18nKey: 'incidents.reports.new',\n+ location: `/incidents/new`,\n+ },\n+ ]\n+ useAddBreadcrumbs(breadcrumbs)\n+\n+ return <h1>Report Incident</h1>\n+}\n+\n+export default ReportIncident\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/view/ViewIncident.tsx",
"diff": "+import React from 'react'\n+import { useTranslation } from 'react-i18next'\n+import { useParams } from 'react-router'\n+import useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\n+import useTitle from '../../page-header/useTitle'\n+\n+const ViewIncident = () => {\n+ const { t } = useTranslation()\n+ const { id } = useParams()\n+ useTitle(t('incidents.reports.view'))\n+ const breadcrumbs = [\n+ {\n+ i18nKey: 'incidents.reports.view',\n+ location: `/incidents/${id}`,\n+ },\n+ ]\n+ useAddBreadcrumbs(breadcrumbs)\n+\n+ return <h1>View Incident</h1>\n+}\n+\n+export default ViewIncident\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/enUs/translations/incidents/index.ts",
"diff": "+export default {\n+ incidents: {\n+ label: 'Incidents',\n+ reports: {\n+ label: 'Reported Incidents',\n+ new: 'Report Incident',\n+ view: 'View Incident',\n+ },\n+ },\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/index.ts",
"new_path": "src/locales/enUs/translations/index.ts",
"diff": "@@ -6,6 +6,7 @@ import scheduling from './scheduling'\nimport states from './states'\nimport sex from './sex'\nimport labs from './labs'\n+import incidents from './incidents'\nexport default {\n...actions,\n@@ -16,4 +17,5 @@ export default {\n...states,\n...sex,\n...labs,\n+ ...incidents,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Permissions.ts",
"new_path": "src/model/Permissions.ts",
"diff": "@@ -11,6 +11,9 @@ enum Permissions {\nCompleteLab = 'complete:lab',\nViewLab = 'read:lab',\nViewLabs = 'read:labs',\n+ ViewIncidents = 'read:incidents',\n+ ViewIncident = 'read:incident',\n+ ReportIncident = 'write:incident',\n}\nexport default Permissions\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "@@ -19,6 +19,9 @@ const initialState: UserState = {\nPermissions.RequestLab,\nPermissions.CompleteLab,\nPermissions.CancelLab,\n+ Permissions.ViewIncident,\n+ Permissions.ViewIncidents,\n+ Permissions.ReportIncident,\n],\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incidents): add incident related routing |
288,323 | 30.04.2020 21:54:01 | 18,000 | 4a4a6821838982f51b94ff050ff5e614a95d8839 | feat(incidents): adds ability to report incident | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/Incidents.test.tsx",
"new_path": "src/__tests__/incidents/Incidents.test.tsx",
"diff": "@@ -22,6 +22,7 @@ describe('Incidents', () => {\nuser: { permissions: [Permissions.ReportIncident] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ incident: {},\n})\nconst wrapper = mount(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/incident-slice.test.ts",
"diff": "+import { AnyAction } from 'redux'\n+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import shortid from 'shortid'\n+import { addDays } from 'date-fns'\n+import incident, {\n+ reportIncidentStart,\n+ reportIncidentSuccess,\n+ reportIncidentError,\n+ reportIncident,\n+} from '../../incidents/incident-slice'\n+import Incident from '../../model/Incident'\n+import { RootState } from '../../store'\n+import IncidentRepository from '../../clients/db/IncidentRepository'\n+\n+const mockStore = createMockStore<RootState, any>([thunk])\n+\n+describe('incident slice', () => {\n+ describe('actions', () => {\n+ it('should default the store correctly', () => {\n+ const incidentStore = incident(undefined, {} as AnyAction)\n+ expect(incidentStore.status).toEqual('loading')\n+ expect(incidentStore.incident).toBeUndefined()\n+ expect(incidentStore.error).toBeUndefined()\n+ })\n+\n+ it('should handle the report incident start', () => {\n+ const incidentStore = incident(undefined, reportIncidentStart)\n+ expect(incidentStore.status).toEqual('loading')\n+ })\n+\n+ it('should handle the report incident success', () => {\n+ const expectedIncident = {\n+ id: 'some id',\n+ reportedOn: new Date().toISOString(),\n+ reportedBy: 'some user id',\n+ description: 'description',\n+ date: new Date().toISOString(),\n+ department: 'some department',\n+ category: 'category',\n+ categoryItem: 'categoryItem',\n+ code: 'some code',\n+ } as Incident\n+\n+ const incidentStore = incident(undefined, reportIncidentSuccess(expectedIncident))\n+ expect(incidentStore.status).toEqual('completed')\n+ expect(incidentStore.incident).toEqual(expectedIncident)\n+ expect(incidentStore.error).toBeUndefined()\n+ })\n+\n+ it('should handle the report incident error', () => {\n+ const expectedError = {\n+ date: 'some description error',\n+ description: 'some description error',\n+ }\n+\n+ const incidentStore = incident(undefined, reportIncidentError(expectedError))\n+ expect(incidentStore.status).toEqual('error')\n+ expect(incidentStore.error).toEqual(expectedError)\n+ })\n+ })\n+\n+ describe('report incident', () => {\n+ beforeEach(() => {\n+ jest.restoreAllMocks()\n+ })\n+\n+ it('should successfully create an incident', async () => {\n+ const expectedDate = new Date()\n+ const expectedShortId = '123456'\n+ Date.now = jest.fn().mockReturnValue(expectedDate)\n+ jest.spyOn(shortid, 'generate').mockReturnValue(expectedShortId)\n+ const onSuccessSpy = jest.fn()\n+ const newIncident = {\n+ description: 'description',\n+ date: expectedDate.toISOString(),\n+ department: 'some department',\n+ category: 'category',\n+ categoryItem: 'categoryItem',\n+ } as Incident\n+\n+ const expectedIncident = {\n+ ...newIncident,\n+ code: `I-${expectedShortId}`,\n+ reportedOn: expectedDate.toISOString(),\n+ reportedBy: 'some user id',\n+ }\n+\n+ jest.spyOn(IncidentRepository, 'save').mockResolvedValue(expectedIncident)\n+\n+ const store = mockStore({ user: { user: { id: expectedIncident.reportedBy } } })\n+\n+ await store.dispatch(reportIncident(newIncident, onSuccessSpy))\n+\n+ expect(store.getActions()[0]).toEqual(reportIncidentStart())\n+ expect(store.getActions()[1]).toEqual(reportIncidentSuccess(expectedIncident))\n+ expect(IncidentRepository.save).toHaveBeenCalledWith(expectedIncident)\n+ expect(onSuccessSpy).toHaveBeenLastCalledWith(expectedIncident)\n+ })\n+\n+ it('should validate the required fields apart of an incident', async () => {\n+ const onSuccessSpy = jest.fn()\n+ const newIncident = {} as Incident\n+ jest.spyOn(IncidentRepository, 'save')\n+ const expectedError = {\n+ date: 'incidents.reports.error.dateRequired',\n+ department: 'incidents.reports.error.departmentRequired',\n+ category: 'incidents.reports.error.categoryRequired',\n+ categoryItem: 'incidents.reports.error.categoryItemRequired',\n+ description: 'incidents.reports.error.descriptionRequired',\n+ }\n+\n+ const store = mockStore({ user: { user: { id: 'some id' } } })\n+\n+ await store.dispatch(reportIncident(newIncident, onSuccessSpy))\n+\n+ expect(store.getActions()[0]).toEqual(reportIncidentStart())\n+ expect(store.getActions()[1]).toEqual(reportIncidentError(expectedError))\n+ expect(IncidentRepository.save).not.toHaveBeenCalled()\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ })\n+\n+ it('should validate that the incident date is not a date in the future', async () => {\n+ const onSuccessSpy = jest.fn()\n+ const newIncident = {\n+ description: 'description',\n+ date: addDays(new Date(), 4),\n+ department: 'some department',\n+ category: 'category',\n+ categoryItem: 'categoryItem',\n+ } as Incident\n+ jest.spyOn(IncidentRepository, 'save')\n+ const expectedError = {\n+ date: 'incidents.reports.error.dateMustBeInThePast',\n+ }\n+\n+ const store = mockStore({ user: { user: { id: 'some id' } } })\n+\n+ await store.dispatch(reportIncident(newIncident, onSuccessSpy))\n+\n+ expect(store.getActions()[0]).toEqual(reportIncidentStart())\n+ expect(store.getActions()[1]).toEqual(reportIncidentError(expectedError))\n+ expect(IncidentRepository.save).not.toHaveBeenCalled()\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/report/ReportIncident.test.tsx",
"new_path": "src/__tests__/incidents/report/ReportIncident.test.tsx",
"diff": "@@ -7,11 +7,13 @@ import { Provider } from 'react-redux'\nimport { Route, Router } from 'react-router'\nimport createMockStore from 'redux-mock-store'\nimport thunk from 'redux-thunk'\n+import { Button } from '@hospitalrun/components'\nimport Permissions from '../../../model/Permissions'\nimport * as titleUtil from '../../../page-header/useTitle'\nimport * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\nimport * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\nimport ReportIncident from '../../../incidents/report/ReportIncident'\n+import IncidentRepository from '../../../clients/db/IncidentRepository'\nconst mockStore = createMockStore([thunk])\n@@ -19,7 +21,7 @@ describe('Report Incident', () => {\nlet history: any\nlet setButtonToolBarSpy: any\n- const setup = async (permissions: Permissions[]) => {\n+ const setup = async (permissions: Permissions[], error: any = {}) => {\njest.resetAllMocks()\njest.spyOn(breadcrumbUtil, 'default')\nsetButtonToolBarSpy = jest.fn()\n@@ -32,6 +34,12 @@ describe('Report Incident', () => {\ntitle: '',\nuser: {\npermissions,\n+ user: {\n+ id: 'some id',\n+ },\n+ },\n+ incident: {\n+ error,\n},\n})\n@@ -53,6 +61,7 @@ describe('Report Incident', () => {\nreturn wrapper\n}\n+ describe('layout', () => {\nit('should set the title', async () => {\nawait setup([Permissions.ReportIncident])\n@@ -66,4 +75,169 @@ describe('Report Incident', () => {\n{ i18nKey: 'incidents.reports.new', location: '/incidents/new' },\n])\n})\n+\n+ it('should have a date input', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const dateInput = wrapper.findWhere((w) => w.prop('name') === 'dateOfIncident')\n+\n+ expect(dateInput).toHaveLength(1)\n+ expect(dateInput.prop('label')).toEqual('incidents.reports.dateOfIncident')\n+ expect(dateInput.prop('isEditable')).toBeTruthy()\n+ expect(dateInput.prop('isRequired')).toBeTruthy()\n+ })\n+\n+ it('should have a department input', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const departmentInput = wrapper.findWhere((w) => w.prop('name') === 'department')\n+\n+ expect(departmentInput).toHaveLength(1)\n+ expect(departmentInput.prop('label')).toEqual('incidents.reports.department')\n+ expect(departmentInput.prop('isEditable')).toBeTruthy()\n+ expect(departmentInput.prop('isRequired')).toBeTruthy()\n+ })\n+\n+ it('should have a category input', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const categoryInput = wrapper.findWhere((w) => w.prop('name') === 'category')\n+\n+ expect(categoryInput).toHaveLength(1)\n+ expect(categoryInput.prop('label')).toEqual('incidents.reports.category')\n+ expect(categoryInput.prop('isEditable')).toBeTruthy()\n+ expect(categoryInput.prop('isRequired')).toBeTruthy()\n+ })\n+\n+ it('should have a category item input', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const categoryInput = wrapper.findWhere((w) => w.prop('name') === 'categoryItem')\n+\n+ expect(categoryInput).toHaveLength(1)\n+ expect(categoryInput.prop('label')).toEqual('incidents.reports.categoryItem')\n+ expect(categoryInput.prop('isEditable')).toBeTruthy()\n+ expect(categoryInput.prop('isRequired')).toBeTruthy()\n+ })\n+\n+ it('should have a description input', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+\n+ expect(descriptionInput).toHaveLength(1)\n+ expect(descriptionInput.prop('label')).toEqual('incidents.reports.description')\n+ expect(descriptionInput.prop('isEditable')).toBeTruthy()\n+ expect(descriptionInput.prop('isRequired')).toBeTruthy()\n+ })\n+ })\n+\n+ describe('error handling', () => {\n+ it('should display the error messages', async () => {\n+ const error = {\n+ date: 'some date error',\n+ department: 'some department error',\n+ category: 'some category error',\n+ categoryItem: 'some category item error',\n+ description: 'some description error',\n+ }\n+\n+ const wrapper = await setup([Permissions.ReportIncident], error)\n+\n+ const dateInput = wrapper.findWhere((w) => w.prop('name') === 'dateOfIncident')\n+ const departmentInput = wrapper.findWhere((w) => w.prop('name') === 'department')\n+ const categoryInput = wrapper.findWhere((w) => w.prop('name') === 'category')\n+ const categoryItemInput = wrapper.findWhere((w) => w.prop('name') === 'categoryItem')\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+\n+ expect(dateInput.prop('isInvalid')).toBeTruthy()\n+ expect(dateInput.prop('feedback')).toEqual(error.date)\n+\n+ expect(departmentInput.prop('isInvalid')).toBeTruthy()\n+ expect(departmentInput.prop('feedback')).toEqual(error.department)\n+\n+ expect(categoryInput.prop('isInvalid')).toBeTruthy()\n+ expect(categoryInput.prop('feedback')).toEqual(error.category)\n+\n+ expect(categoryItemInput.prop('isInvalid')).toBeTruthy()\n+ expect(categoryItemInput.prop('feedback')).toEqual(error.categoryItem)\n+\n+ expect(descriptionInput.prop('isInvalid')).toBeTruthy()\n+ expect(descriptionInput.prop('feedback')).toEqual(error.description)\n+ })\n+ })\n+\n+ describe('on save', () => {\n+ it('should dispatch the report incident action', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+ const expectedIncident = {\n+ date: new Date().toISOString(),\n+ department: 'some department',\n+ category: 'some category',\n+ categoryItem: 'some category item',\n+ description: 'some description',\n+ }\n+ jest\n+ .spyOn(IncidentRepository, 'save')\n+ .mockResolvedValue({ id: 'someId', ...expectedIncident })\n+\n+ const dateInput = wrapper.findWhere((w) => w.prop('name') === 'dateOfIncident')\n+ act(() => {\n+ const onChange = dateInput.prop('onChange')\n+ onChange(new Date(expectedIncident.date))\n+ })\n+\n+ const departmentInput = wrapper.findWhere((w) => w.prop('name') === 'department')\n+ act(() => {\n+ const onChange = departmentInput.prop('onChange')\n+ onChange({ currentTarget: { value: expectedIncident.department } })\n+ })\n+\n+ const categoryInput = wrapper.findWhere((w) => w.prop('name') === 'category')\n+ act(() => {\n+ const onChange = categoryInput.prop('onChange')\n+ onChange({ currentTarget: { value: expectedIncident.category } })\n+ })\n+\n+ const categoryItemInput = wrapper.findWhere((w) => w.prop('name') === 'categoryItem')\n+ act(() => {\n+ const onChange = categoryItemInput.prop('onChange')\n+ onChange({ currentTarget: { value: expectedIncident.categoryItem } })\n+ })\n+\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+ act(() => {\n+ const onChange = descriptionInput.prop('onChange')\n+ onChange({ currentTarget: { value: expectedIncident.description } })\n+ })\n+ wrapper.update()\n+\n+ const saveButton = wrapper.find(Button).at(0)\n+ await act(async () => {\n+ const onClick = saveButton.prop('onClick')\n+ onClick()\n+ })\n+\n+ expect(IncidentRepository.save).toHaveBeenCalledTimes(1)\n+ expect(IncidentRepository.save).toHaveBeenCalledWith(\n+ expect.objectContaining(expectedIncident),\n+ )\n+ expect(history.location.pathname).toEqual(`/incidents/someId`)\n+ })\n+ })\n+\n+ describe('on cancel', () => {\n+ it('should navigate to /incidents', async () => {\n+ const wrapper = await setup([Permissions.ReportIncident])\n+\n+ const cancelButton = wrapper.find(Button).at(1)\n+\n+ act(() => {\n+ const onClick = cancelButton.prop('onClick') as any\n+ onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual('/incidents')\n+ })\n+ })\n})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/clients/db/IncidentRepository.ts",
"diff": "+import Repository from './Repository'\n+import { incidents } from '../../config/pouchdb'\n+import Incident from '../../model/Incident'\n+\n+export class IncidentRepository extends Repository<Incident> {\n+ constructor() {\n+ super(incidents)\n+ }\n+}\n+\n+export default new IncidentRepository()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/input/DateTimePickerWithLabelFormGroup.tsx",
"new_path": "src/components/input/DateTimePickerWithLabelFormGroup.tsx",
"diff": "@@ -6,15 +6,18 @@ interface Props {\nlabel: string\nvalue: Date | undefined\nisEditable?: boolean\n+ isRequired?: boolean\nonChange?: (date: Date) => void\n+ feedback?: string\n+ isInvalid?: boolean\n}\nconst DateTimePickerWithLabelFormGroup = (props: Props) => {\n- const { onChange, label, name, isEditable, value } = props\n+ const { onChange, label, name, isEditable, value, isRequired, feedback, isInvalid } = props\nconst id = `${name}DateTimePicker`\nreturn (\n<div className=\"form-group\">\n- <Label text={label} isRequired htmlFor={id} />\n+ <Label text={label} isRequired={isRequired} htmlFor={id} />\n<DateTimePicker\ndateFormat=\"MM/dd/yyyy h:mm aa\"\ndateFormatCalendar=\"LLLL yyyy\"\n@@ -31,6 +34,8 @@ const DateTimePickerWithLabelFormGroup = (props: Props) => {\ntimeFormat=\"h:mm aa\"\ntimeIntervals={15}\nwithPortal={false}\n+ feedback={feedback}\n+ isInvalid={isInvalid}\n/>\n</div>\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/config/pouchdb.ts",
"new_path": "src/config/pouchdb.ts",
"diff": "@@ -29,3 +29,4 @@ function createDb(name: string) {\nexport const patients = createDb('patients')\nexport const appointments = createDb('appointments')\nexport const labs = createDb('labs')\n+export const incidents = createDb('incidents')\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/incident-slice.ts",
"diff": "+import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import { AppThunk } from 'store'\n+import { isAfter } from 'date-fns'\n+import { isEmpty } from 'lodash'\n+import shortid from 'shortid'\n+import Incident from '../model/Incident'\n+import IncidentRepository from '../clients/db/IncidentRepository'\n+\n+interface Error {\n+ date?: string\n+ department?: string\n+ category?: string\n+ categoryItem?: string\n+ description?: string\n+}\n+\n+interface IncidentState {\n+ error?: Error\n+ incident?: Incident\n+ status: 'loading' | 'error' | 'completed'\n+}\n+\n+const initialState: IncidentState = {\n+ error: undefined,\n+ incident: undefined,\n+ status: 'loading',\n+}\n+\n+function start(state: IncidentState) {\n+ state.status = 'loading'\n+}\n+\n+function finish(state: IncidentState, { payload }: PayloadAction<Incident>) {\n+ state.status = 'completed'\n+ state.incident = payload\n+ state.error = undefined\n+}\n+\n+function error(state: IncidentState, { payload }: PayloadAction<Error>) {\n+ state.status = 'error'\n+ state.error = payload\n+}\n+\n+const incidentSlice = createSlice({\n+ name: 'incident',\n+ initialState,\n+ reducers: {\n+ reportIncidentStart: start,\n+ reportIncidentSuccess: finish,\n+ reportIncidentError: error,\n+ },\n+})\n+\n+export const {\n+ reportIncidentStart,\n+ reportIncidentSuccess,\n+ reportIncidentError,\n+} = incidentSlice.actions\n+\n+function validateIncident(incident: Incident): Error {\n+ const newError: Error = {}\n+\n+ if (!incident.date) {\n+ newError.date = 'incidents.reports.error.dateRequired'\n+ } else if (isAfter(new Date(incident.date), new Date(Date.now()))) {\n+ newError.date = 'incidents.reports.error.dateMustBeInThePast'\n+ }\n+\n+ if (!incident.department) {\n+ newError.department = 'incidents.reports.error.departmentRequired'\n+ }\n+\n+ if (!incident.category) {\n+ newError.category = 'incidents.reports.error.categoryRequired'\n+ }\n+\n+ if (!incident.categoryItem) {\n+ newError.categoryItem = 'incidents.reports.error.categoryItemRequired'\n+ }\n+\n+ if (!incident.description) {\n+ newError.description = 'incidents.reports.error.descriptionRequired'\n+ }\n+\n+ return newError\n+}\n+\n+const formatIncidentCode = (prefix: string, sequenceNumber: string) => `${prefix}${sequenceNumber}`\n+const getIncidentCode = (): string => formatIncidentCode('I-', shortid.generate())\n+\n+export const reportIncident = (\n+ incident: Incident,\n+ onSuccess?: (incident: Incident) => void,\n+): AppThunk => async (dispatch, getState) => {\n+ dispatch(reportIncidentStart())\n+ const incidentError = validateIncident(incident)\n+ if (isEmpty(incidentError)) {\n+ incident.reportedOn = new Date(Date.now()).toISOString()\n+ incident.code = getIncidentCode()\n+ incident.reportedBy = getState().user.user.id\n+ const newIncident = await IncidentRepository.save(incident)\n+ await dispatch(reportIncidentSuccess(newIncident))\n+ if (onSuccess) {\n+ onSuccess(newIncident)\n+ }\n+ } else {\n+ dispatch(reportIncidentError(incidentError))\n+ }\n+}\n+\n+export default incidentSlice.reducer\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/report/ReportIncident.tsx",
"new_path": "src/incidents/report/ReportIncident.tsx",
"diff": "-import React from 'react'\n+import React, { useState } from 'react'\nimport { useTranslation } from 'react-i18next'\n+import { Button, Row, Column } from '@hospitalrun/components'\n+import { useHistory } from 'react-router'\n+import { useDispatch, useSelector } from 'react-redux'\nimport useTitle from '../../page-header/useTitle'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\n+import DateTimePickerWithLabelFormGroup from '../../components/input/DateTimePickerWithLabelFormGroup'\n+import TextFieldWithLabelFormGroup from '../../components/input/TextFieldWithLabelFormGroup'\n+import TextInputWithLabelFormGroup from '../../components/input/TextInputWithLabelFormGroup'\n+import { reportIncident } from '../incident-slice'\n+import Incident from '../../model/Incident'\n+import { RootState } from '../../store'\nconst ReportIncident = () => {\n+ const dispatch = useDispatch()\n+ const history = useHistory()\nconst { t } = useTranslation()\nuseTitle(t('incidents.reports.new'))\nconst breadcrumbs = [\n@@ -14,7 +25,122 @@ const ReportIncident = () => {\n]\nuseAddBreadcrumbs(breadcrumbs)\n- return <h1>Report Incident</h1>\n+ const { error } = useSelector((root: RootState) => root.incident)\n+ const [incident, setIncident] = useState({\n+ date: new Date().toISOString(),\n+ department: '',\n+ category: '',\n+ categoryItem: '',\n+ description: '',\n+ })\n+\n+ const onDateChange = (newDate: Date) => {\n+ setIncident((prevState) => ({\n+ ...prevState,\n+ date: newDate.toISOString(),\n+ }))\n+ }\n+\n+ const onTextInputChange = (text: string, name: string) => {\n+ setIncident((prevState) => ({\n+ ...prevState,\n+ [name]: text,\n+ }))\n+ }\n+\n+ const onSave = () => {\n+ const onSuccess = (newIncident: Incident) => {\n+ history.push(`/incidents/${newIncident.id}`)\n+ }\n+\n+ dispatch(reportIncident(incident as Incident, onSuccess))\n+ }\n+\n+ const onCancel = () => {\n+ history.push('/incidents')\n+ }\n+\n+ return (\n+ <form>\n+ <Row>\n+ <Column md={6}>\n+ <DateTimePickerWithLabelFormGroup\n+ name=\"dateOfIncident\"\n+ label={t('incidents.reports.dateOfIncident')}\n+ isEditable\n+ isRequired\n+ onChange={onDateChange}\n+ value={new Date(incident.date)}\n+ isInvalid={!!error?.date}\n+ feedback={t(error?.date as string)}\n+ />\n+ </Column>\n+ <Column md={6}>\n+ <TextInputWithLabelFormGroup\n+ label={t('incidents.reports.department')}\n+ name=\"department\"\n+ isRequired\n+ isEditable\n+ value={incident.department}\n+ onChange={(event) => onTextInputChange(event.currentTarget.value, 'department')}\n+ isInvalid={!!error?.department}\n+ feedback={t(error?.department as string)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column md={6}>\n+ <TextInputWithLabelFormGroup\n+ name=\"category\"\n+ label={t('incidents.reports.category')}\n+ isEditable\n+ isRequired\n+ value={incident.category}\n+ onChange={(event) => onTextInputChange(event.currentTarget.value, 'category')}\n+ isInvalid={!!error?.category}\n+ feedback={t(error?.category as string)}\n+ />\n+ </Column>\n+ <Column md={6}>\n+ <TextInputWithLabelFormGroup\n+ label={t('incidents.reports.categoryItem')}\n+ name=\"categoryItem\"\n+ isRequired\n+ isEditable\n+ value={incident.categoryItem}\n+ onChange={(event) => onTextInputChange(event.currentTarget.value, 'categoryItem')}\n+ isInvalid={!!error?.categoryItem}\n+ feedback={t(error?.categoryItem as string)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column md={12}>\n+ <TextFieldWithLabelFormGroup\n+ label={t('incidents.reports.description')}\n+ name=\"description\"\n+ isRequired\n+ isEditable\n+ value={incident.description}\n+ onChange={(event) => onTextInputChange(event.currentTarget.value, 'description')}\n+ isInvalid={!!error?.description}\n+ feedback={t(error?.description as string)}\n+ />\n+ </Column>\n+ </Row>\n+\n+ <div className=\"row float-right\">\n+ <div className=\"btn-group btn-group-lg mt-3\">\n+ <Button className=\"mr-2\" color=\"success\" onClick={onSave}>\n+ {t('incidents.actions.report')}\n+ </Button>\n+ <Button color=\"danger\" onClick={onCancel}>\n+ {t('actions.cancel')}\n+ </Button>\n+ </div>\n+ </div>\n+ </form>\n+ )\n}\nexport default ReportIncident\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/incidents/index.ts",
"new_path": "src/locales/enUs/translations/incidents/index.ts",
"diff": "export default {\nincidents: {\nlabel: 'Incidents',\n+ actions: {\n+ report: 'Report',\n+ },\nreports: {\nlabel: 'Reported Incidents',\nnew: 'Report Incident',\nview: 'View Incident',\n+ dateOfIncident: 'Date of Incident',\n+ department: 'Department',\n+ category: 'Category',\n+ categoryItem: 'Category Item',\n+ description: 'Description of Incident',\n+ error: {\n+ dateRequired: 'Date is required.',\n+ dateMustBeInThePast: 'Date must be in the past.',\n+ departmentRequired: 'Department is required.',\n+ categoryRequired: 'Category is required',\n+ categoryItemRequired: 'Category Item is required',\n+ descriptionRequired: 'Description is required',\n+ },\n},\n},\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/model/Incident.ts",
"diff": "+import AbstractDBModel from './AbstractDBModel'\n+\n+export default interface Incident extends AbstractDBModel {\n+ reportedBy: string\n+ reportedOn: string\n+ code: string\n+ date: string\n+ department: string\n+ category: string\n+ categoryItem: string\n+ description: string\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/model/User.ts",
"diff": "+import Name from './Name'\n+\n+export default interface User extends Name {\n+ id: string\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/store/index.ts",
"new_path": "src/store/index.ts",
"diff": "@@ -7,6 +7,7 @@ import appointments from '../scheduling/appointments/appointments-slice'\nimport title from '../page-header/title-slice'\nimport user from '../user/user-slice'\nimport lab from '../labs/lab-slice'\n+import incident from '../incidents/incident-slice'\nimport breadcrumbs from '../breadcrumbs/breadcrumbs-slice'\nimport components from '../components/component-slice'\n@@ -20,6 +21,7 @@ const reducer = combineReducers({\nbreadcrumbs,\ncomponents,\nlab,\n+ incident,\n})\nconst store = configureStore({\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport Permissions from '../model/Permissions'\n+import User from '../model/User'\ninterface UserState {\npermissions: Permissions[]\n+ user: User\n}\nconst initialState: UserState = {\n@@ -23,6 +25,11 @@ const initialState: UserState = {\nPermissions.ViewIncidents,\nPermissions.ReportIncident,\n],\n+ user: {\n+ id: 'some-hardcoded-id',\n+ givenName: 'HospitalRun',\n+ familyName: 'Fake User',\n+ } as User,\n}\nconst userSlice = createSlice({\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incidents): adds ability to report incident |
288,347 | 03.05.2020 08:05:09 | -7,200 | 75f998103cde809054d01b5d999dba557952bb09 | feat(checkmissingtranslations.ts): refactor | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"redux-mock-store\": \"~1.5.4\",\n\"source-map-explorer\": \"^2.2.2\",\n\"standard-version\": \"~7.1.0\",\n- \"ts-jest\": \"~24.3.0\"\n+ \"ts-jest\": \"~24.3.0\",\n+ \"ts-node\": \"^8.10.0\"\n},\n\"scripts\": {\n\"analyze\": \"source-map-explorer 'build/static/js/*.js'\",\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(checkmissingtranslations.ts): refactor |
288,347 | 03.05.2020 08:15:20 | -7,200 | 5ef3f7ec702331bb1bea14cd51a46e48a2a31ca2 | feat(checkmissintranslations.ts): run script before default ones
Run yarn translation:check before yarn start and yarn test | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"scripts\": {\n\"analyze\": \"source-map-explorer 'build/static/js/*.js'\",\n\"commit\": \"npx git-cz\",\n- \"start\": \"react-scripts start\",\n+ \"start\": \"yarn translation:check && react-scripts start\",\n\"build\": \"react-scripts build\",\n\"prepublishOnly\": \"npm run build\",\n- \"test\": \"react-scripts test --detectOpenHandles\",\n+ \"test\": \"yarn translation:check && react-scripts test --detectOpenHandles\",\n\"test:ci\": \"cross-env CI=true react-scripts test --passWithNoTests\",\n\"lint\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\"\",\n\"lint:fix\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\" --fix\",\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(checkmissintranslations.ts): run script before default ones
Run yarn translation:check before yarn start and yarn test |
288,347 | 03.05.2020 08:29:57 | -7,200 | ede7b2eca4046bc93dc47c43a73ef9007f2f1594 | feat(checkmissintranlations.ts): add colors to log
add library chalk to make logs more colored | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"@types/validator\": \"~13.0.0\",\n\"@typescript-eslint/eslint-plugin\": \"~2.30.0\",\n\"@typescript-eslint/parser\": \"~2.30.0\",\n+ \"chalk\": \"^4.0.0\",\n\"commitizen\": \"~4.0.3\",\n\"commitlint-config-cz\": \"~0.13.0\",\n\"cross-env\": \"~7.0.0\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/.eslintrc.js",
"diff": "+module.exports = {\n+ extends: '../.eslintrc.js',\n+ rules: {\n+ \"import/no-extraneous-dependencies\": [\"error\", {\"devDependencies\": true}]\n+ }\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(checkmissintranlations.ts): add colors to log
add library chalk to make logs more colored |
288,350 | 03.05.2020 12:31:24 | -19,080 | d1c55e7ab0bdcbe9a851751a747a6fe71714dc6a | feat(viewpatients): add a new field 'index', paging in next direction
New 'index' field is a combination of 'fullName' and 'code' so that uniqueness is guaranteed and
paging logic can relay on this field. A new field in PageRequest to store a reference field for
getting next page.
feat feat | [
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "export default interface PageRequest {\nnumber: number | undefined\nsize: number | undefined\n+ nextPageInfo: { [key: string]: string | null } | undefined\n+ direction: 'previous' | 'next' | null\n}\nexport const UnpagedRequest: PageRequest = {\nnumber: undefined,\nsize: undefined,\n+ nextPageInfo: undefined,\n+ direction: null,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "@@ -15,7 +15,7 @@ export class PatientRepository extends Repository<Patient> {\nconstructor() {\nsuper(patients)\npatients.createIndex({\n- index: { fields: ['fullName', 'code'] },\n+ index: { fields: ['index'] },\n})\n}\n@@ -86,6 +86,7 @@ export class PatientRepository extends Repository<Patient> {\nasync save(entity: Patient): Promise<Patient> {\nconst patientCode = getPatientCode()\nentity.code = patientCode\n+ entity.index = (entity.fullName ? entity.fullName : '') + patientCode\nreturn super.save(entity)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -47,27 +47,59 @@ export default class Repository<T extends AbstractDBModel> {\nconst selector: any = {\n_id: { $gt: null },\n}\n-\n+ if (pageRequest.direction === 'next') {\nsort.sorts.forEach((s) => {\n- selector[s.field] = { $gt: null }\n+ selector[s.field] = {\n+ $gte:\n+ pageRequest.nextPageInfo && pageRequest.nextPageInfo[s.field]\n+ ? pageRequest.nextPageInfo[s.field]\n+ : null,\n+ }\n})\n+ } else if (pageRequest.direction === 'previous') {\n+ sort.sorts.forEach((s) => {\n+ s.direction = s.direction === 'asc' ? 'desc' : 'asc'\n+ selector[s.field] = {\n+ $lte:\n+ pageRequest.nextPageInfo && pageRequest.nextPageInfo[s.field]\n+ ? pageRequest.nextPageInfo[s.field]\n+ : null,\n+ }\n+ })\n+ }\nconst result = await this.db.find({\nselector,\nsort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\n- limit: pageRequest.size,\n- skip:\n- pageRequest.number && pageRequest.size ? (pageRequest.number - 1) * pageRequest.size : 0,\n+ limit: pageRequest.size ? pageRequest.size + 1 : undefined,\n+ skip: pageRequest.direction === 'previous' ? pageRequest.size : undefined,\n})\nconst mappedResult = result.docs.map(mapDocument)\n+ if (pageRequest.direction === 'previous') {\n+ mappedResult.reverse()\n+ }\n+ const nextPageInfo: { [key: string]: string } = {}\n+\n+ if (mappedResult.length > 0) {\n+ sort.sorts.forEach((s) => {\n+ nextPageInfo[s.field] = mappedResult[mappedResult.length - 1][s.field]\n+ })\n+ }\n+\nconst pagedResult: Page<T> = {\n- content: mappedResult,\n- hasNext: pageRequest.size !== undefined && mappedResult.length === pageRequest.size,\n- hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n+ content:\n+ pageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1\n+ ? mappedResult.slice(0, mappedResult.length - 1)\n+ : mappedResult,\n+ hasNext: pageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1,\n+ // hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n+ hasPrevious: false,\npageRequest: {\nsize: pageRequest.size,\nnumber: pageRequest.number,\n+ nextPageInfo,\n+ direction: null,\n},\n}\nreturn pagedResult\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Patient.ts",
"new_path": "src/model/Patient.ts",
"diff": "@@ -18,4 +18,5 @@ export default interface Patient extends AbstractDBModel, Name, ContactInformati\nallergies?: Allergy[]\ndiagnoses?: Diagnosis[]\nnotes?: Note[]\n+ index: string\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/edit/EditPatient.tsx",
"new_path": "src/patients/edit/EditPatient.tsx",
"diff": "@@ -73,6 +73,8 @@ const EditPatient = () => {\n{\n...patient,\nfullName: getPatientName(patient.givenName, patient.familyName, patient.suffix),\n+ index:\n+ getPatientName(patient.givenName, patient.familyName, patient.suffix) + patient.code,\n},\nonSuccessfulSave,\n),\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -28,6 +28,8 @@ const ViewPatients = () => {\nconst [userPageRequest, setUserPageRequest] = useState<PageRequest>({\nsize: 1,\nnumber: 1,\n+ nextPageInfo: { index: null },\n+ direction: 'next',\n})\nconst setNextPageRequest = () => {\n@@ -36,6 +38,8 @@ const ViewPatients = () => {\nconst newPageRequest: PageRequest = {\nnumber: p.number + 1,\nsize: p.size,\n+ nextPageInfo: patients.pageRequest?.nextPageInfo,\n+ direction: 'next',\n}\nreturn newPageRequest\n}\n@@ -49,6 +53,8 @@ const ViewPatients = () => {\nreturn {\nnumber: p.number - 1,\nsize: p.size,\n+ nextPageInfo: patients.pageRequest?.nextPageInfo,\n+ direction: 'previous',\n}\n}\nreturn p\n@@ -60,20 +66,14 @@ const ViewPatients = () => {\nuseEffect(() => {\nconst sortRequest: SortRequest = {\n- sorts: [\n- { field: 'fullName', direction: 'asc' },\n- { field: 'code', direction: 'asc' },\n- ],\n+ sorts: [{ field: 'index', direction: 'asc' }],\n}\ndispatch(searchPatients(debouncedSearchText, sortRequest, userPageRequest))\n}, [dispatch, debouncedSearchText, userPageRequest])\nuseEffect(() => {\nconst sortRequest: SortRequest = {\n- sorts: [\n- { field: 'fullName', direction: 'asc' },\n- { field: 'code', direction: 'asc' },\n- ],\n+ sorts: [{ field: 'index', direction: 'asc' }],\n}\ndispatch(fetchPatients(sortRequest, userPageRequest))\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): add a new field 'index', paging in next direction
New 'index' field is a combination of 'fullName' and 'code' so that uniqueness is guaranteed and
paging logic can relay on this field. A new field in PageRequest to store a reference field for
getting next page.
feat #1969, feat #1967 |
288,350 | 03.05.2020 13:16:03 | -19,080 | 220ad9c6a8456c83e26b73e22828cd3a399b471b | test: fix failing tests
Fix failing tests after adding 'index' field and changes in PageRequest
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"new_path": "src/__tests__/patients/edit/EditPatient.test.tsx",
"diff": "@@ -35,6 +35,7 @@ describe('Edit Patient', () => {\naddress: 'address',\ncode: 'P00001',\ndateOfBirth: subDays(new Date(), 2).toISOString(),\n+ index: 'givenName familyName suffixP00001',\n} as Patient\nlet history: any\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -36,6 +36,7 @@ describe('Patients', () => {\ncreatedAt: new Date().toISOString(),\nupdatedAt: new Date().toISOString(),\nrev: '',\n+ index: 'test test P12345',\n},\n],\nhasNext: false,\n@@ -171,12 +172,9 @@ describe('Patients', () => {\nexpect(searchPatientsSpy).toHaveBeenLastCalledWith(\nexpectedSearchText,\n{\n- sorts: [\n- { field: 'fullName', direction: 'asc' },\n- { field: 'code', direction: 'asc' },\n- ],\n+ sorts: [{ field: 'index', direction: 'asc' }],\n},\n- { number: 1, size: 1 },\n+ { number: 1, size: 1, nextPageInfo: { index: null }, direction: 'next' },\n)\n})\n})\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test: fix failing tests
Fix failing tests after adding 'index' field and changes in PageRequest
feat #1969 |
288,347 | 03.05.2020 10:40:29 | -7,200 | 44f15f3a12b3a4252f70c745b37a1140c732d976 | feat(i18n): add italian translation | [
{
"change_type": "MODIFY",
"old_path": "src/i18n.ts",
"new_path": "src/i18n.ts",
"diff": "@@ -12,8 +12,12 @@ import translationJA from './locales/ja/translations'\nimport translationPtBR from './locales/ptBr/translations'\nimport translationRU from './locales/ru/translations'\nimport translationZR from './locales/zr/translations'\n+import translationIT from './locales/it/translations'\nconst resources = {\n+ it: {\n+ translation: translationIT,\n+ },\nar: {\ntranslation: translationAR,\n},\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/actions/index.ts",
"diff": "+export default {\n+ actions: {\n+ label: 'Azioni',\n+ edit: 'Modifica',\n+ save: 'Salva',\n+ update: 'Aggiorna',\n+ complete: 'Completa',\n+ delete: 'Rimuovi',\n+ cancel: 'Annulla',\n+ new: 'Nuovo',\n+ list: 'Lista',\n+ search: 'Cerca',\n+ confirmDelete: 'Conferma cancellazione',\n+ },\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/dashboard/index.ts",
"diff": "+export default {\n+ dashboard: {\n+ label: 'Dashboard',\n+ },\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/index.ts",
"diff": "+import actions from './actions'\n+import dashboard from './dashboard'\n+import patient from './patient'\n+import patients from './patients'\n+import scheduling from './scheduling'\n+import states from './states'\n+import sex from './sex'\n+import labs from './labs'\n+\n+export default {\n+ ...actions,\n+ ...dashboard,\n+ ...patient,\n+ ...patients,\n+ ...scheduling,\n+ ...states,\n+ ...sex,\n+ ...labs,\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/patients/index.ts",
"diff": "+export default {\n+ patients: {\n+ label: 'Pazienti',\n+ patientsList: 'Lista Pazienti',\n+ viewPatients: 'Vedi Pazienti',\n+ viewPatient: 'Vedi Paziente',\n+ newPatient: 'Nuovo Paziente',\n+ successfullyCreated: 'Paziente creato con successo',\n+ successfullyAddedNote: 'Note aggiunte con successo',\n+ successfullyAddedRelatedPerson: 'Relazione di parentela aggiunta con successo',\n+ },\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/sex/index.ts",
"diff": "+export default {\n+ sex: {\n+ male: 'Maschio',\n+ female: 'Femmina',\n+ other: 'Altro',\n+ unknown: 'Sconosciuto',\n+ },\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/it/translations/states/index.ts",
"diff": "+export default {\n+ states: {\n+ success: 'Successo!',\n+ error: 'Errore!',\n+ },\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(i18n): add italian translation (#2035) |
288,350 | 03.05.2020 14:24:07 | -19,080 | 52a59d3865444d37a2c605d2799346172fec2904 | feat(viewpatients): enables to navigation to previous page
Add a field in PageRequest to store refrence that will enable getting previous page.
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -174,7 +174,13 @@ describe('Patients', () => {\n{\nsorts: [{ field: 'index', direction: 'asc' }],\n},\n- { number: 1, size: 1, nextPageInfo: { index: null }, direction: 'next' },\n+ {\n+ number: 1,\n+ size: 1,\n+ nextPageInfo: { index: null },\n+ direction: 'next',\n+ previousPageInfo: { index: null },\n+ },\n)\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "@@ -2,6 +2,8 @@ export default interface PageRequest {\nnumber: number | undefined\nsize: number | undefined\nnextPageInfo: { [key: string]: string | null } | undefined\n+ previousPageInfo: { [key: string]: string | null } | undefined\n+\ndirection: 'previous' | 'next' | null\n}\nexport const UnpagedRequest: PageRequest = {\n@@ -9,4 +11,5 @@ export const UnpagedRequest: PageRequest = {\nsize: undefined,\nnextPageInfo: undefined,\ndirection: null,\n+ previousPageInfo: undefined,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -61,8 +61,8 @@ export default class Repository<T extends AbstractDBModel> {\ns.direction = s.direction === 'asc' ? 'desc' : 'asc'\nselector[s.field] = {\n$lte:\n- pageRequest.nextPageInfo && pageRequest.nextPageInfo[s.field]\n- ? pageRequest.nextPageInfo[s.field]\n+ pageRequest.previousPageInfo && pageRequest.previousPageInfo[s.field]\n+ ? pageRequest.previousPageInfo[s.field]\n: null,\n}\n})\n@@ -72,33 +72,36 @@ export default class Repository<T extends AbstractDBModel> {\nselector,\nsort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\nlimit: pageRequest.size ? pageRequest.size + 1 : undefined,\n- skip: pageRequest.direction === 'previous' ? pageRequest.size : undefined,\n})\nconst mappedResult = result.docs.map(mapDocument)\n-\nif (pageRequest.direction === 'previous') {\nmappedResult.reverse()\n}\n- const nextPageInfo: { [key: string]: string } = {}\n+ const nextPageInfo: { [key: string]: string } = {}\nif (mappedResult.length > 0) {\nsort.sorts.forEach((s) => {\nnextPageInfo[s.field] = mappedResult[mappedResult.length - 1][s.field]\n})\n}\n+ const previousPageInfo: { [key: string]: string } = {}\n+ sort.sorts.forEach((s) => {\n+ previousPageInfo[s.field] = mappedResult[0][s.field]\n+ })\n+\nconst pagedResult: Page<T> = {\ncontent:\npageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1\n? mappedResult.slice(0, mappedResult.length - 1)\n: mappedResult,\nhasNext: pageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1,\n- // hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n- hasPrevious: false,\n+ hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\npageRequest: {\nsize: pageRequest.size,\nnumber: pageRequest.number,\nnextPageInfo,\n+ previousPageInfo,\ndirection: null,\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -29,6 +29,7 @@ const ViewPatients = () => {\nsize: 1,\nnumber: 1,\nnextPageInfo: { index: null },\n+ previousPageInfo: { index: null },\ndirection: 'next',\n})\n@@ -39,6 +40,7 @@ const ViewPatients = () => {\nnumber: p.number + 1,\nsize: p.size,\nnextPageInfo: patients.pageRequest?.nextPageInfo,\n+ previousPageInfo: undefined,\ndirection: 'next',\n}\nreturn newPageRequest\n@@ -53,7 +55,8 @@ const ViewPatients = () => {\nreturn {\nnumber: p.number - 1,\nsize: p.size,\n- nextPageInfo: patients.pageRequest?.nextPageInfo,\n+ nextPageInfo: undefined,\n+ previousPageInfo: patients.pageRequest?.previousPageInfo,\ndirection: 'previous',\n}\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): enables to navigation to previous page
Add a field in PageRequest to store refrence that will enable getting previous page.
feat #1969 |
288,261 | 03.05.2020 18:42:22 | -3,600 | bb02fa20a23eab285c88cfe6ef16d28783d24ec6 | feat(patient): add input validation | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/patient-slice.test.ts",
"new_path": "src/__tests__/patients/patient-slice.test.ts",
"diff": "@@ -295,6 +295,37 @@ describe('patients slice', () => {\n}),\n)\n})\n+\n+ it('should validate fields that should only contian alpha characters', async () => {\n+ const store = mockStore()\n+ const expectedPatientId = 'sliceId10'\n+ const expectedPatient = {\n+ id: expectedPatientId,\n+ givenName: 'some given name',\n+ suffix: 'A123',\n+ familyName: 'B456',\n+ prefix: 'C987',\n+ preferredLanguage: 'D321',\n+ } as Patient\n+ const saveOrUpdateSpy = jest\n+ .spyOn(PatientRepository, 'saveOrUpdate')\n+ .mockResolvedValue(expectedPatient)\n+ const onSuccessSpy = jest.fn()\n+\n+ await store.dispatch(createPatient(expectedPatient, onSuccessSpy))\n+\n+ expect(onSuccessSpy).not.toHaveBeenCalled()\n+ expect(saveOrUpdateSpy).not.toHaveBeenCalled()\n+ expect(store.getActions()[1]).toEqual(\n+ createPatientError({\n+ message: 'patient.errors.createPatientError',\n+ suffix: 'patient.errors.patientNumInSuffixFeedback',\n+ familyName: 'patient.errors.patientNumInFamilyNameFeedback',\n+ prefix: 'patient.errors.patientNumInPrefixFeedback',\n+ preferredLanguage: 'patient.errors.patientNumInPreferredLanguageFeedback',\n+ }),\n+ )\n+ })\n})\ndescribe('fetch patient', () => {\n@@ -386,6 +417,10 @@ describe('patients slice', () => {\nid: expectedPatientId,\ngivenName: undefined,\ndateOfBirth: addDays(new Date(), 4).toISOString(),\n+ suffix: '061002',\n+ prefix: '061002',\n+ familyName: '061002',\n+ preferredLanguage: '061002',\n} as Patient\nconst saveOrUpdateSpy = jest\n.spyOn(PatientRepository, 'saveOrUpdate')\n@@ -401,6 +436,10 @@ describe('patients slice', () => {\nmessage: 'patient.errors.updatePatientError',\ngivenName: 'patient.errors.patientGivenNameFeedback',\ndateOfBirth: 'patient.errors.patientDateOfBirthFeedback',\n+ suffix: 'patient.errors.patientNumInSuffixFeedback',\n+ familyName: 'patient.errors.patientNumInFamilyNameFeedback',\n+ prefix: 'patient.errors.patientNumInPrefixFeedback',\n+ preferredLanguage: 'patient.errors.patientNumInPreferredLanguageFeedback',\n}),\n)\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -94,6 +94,10 @@ export default {\nupdatePatientError: 'Could not update patient.',\npatientGivenNameFeedback: 'Given Name is required.',\npatientDateOfBirthFeedback: 'Date of Birth can not be greater than today',\n+ patientNumInSuffixFeedback: 'Cannot contain numbers.',\n+ patientNumInPrefixFeedback: 'Cannot contain numbers.',\n+ patientNumInFamilyNameFeedback: 'Cannot contain numbers.',\n+ patientNumInPreferredLanguageFeedback: 'Cannot contain numbers.',\ninvalidEmail: 'Must be a valid email.',\ninvalidPhoneNumber: 'Must be a valid phone number.',\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/GeneralInformation.tsx",
"new_path": "src/patients/GeneralInformation.tsx",
"diff": "@@ -60,6 +60,8 @@ const GeneralInformation = (props: Props) => {\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'prefix')\n}}\n+ isInvalid={error?.prefix}\n+ feedback={t(error?.prefix)}\n/>\n</div>\n<div className=\"col-md-4\">\n@@ -85,6 +87,8 @@ const GeneralInformation = (props: Props) => {\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'familyName')\n}}\n+ isInvalid={error?.familyName}\n+ feedback={t(error?.familyName)}\n/>\n</div>\n<div className=\"col-md-2\">\n@@ -96,6 +100,8 @@ const GeneralInformation = (props: Props) => {\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'suffix')\n}}\n+ isInvalid={error?.suffix}\n+ feedback={t(error?.suffix)}\n/>\n</div>\n</div>\n@@ -195,6 +201,8 @@ const GeneralInformation = (props: Props) => {\nonChange={(event: React.ChangeEvent<HTMLInputElement>) => {\nonInputElementChange(event, 'preferredLanguage')\n}}\n+ isInvalid={error?.preferredLanguage}\n+ feedback={t(error?.preferredLanguage)}\n/>\n</div>\n</div>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patient-slice.ts",
"new_path": "src/patients/patient-slice.ts",
"diff": "@@ -28,6 +28,10 @@ interface Error {\nmessage?: string\ngivenName?: string\ndateOfBirth?: string\n+ suffix?: string\n+ prefix?: string\n+ familyName?: string\n+ preferredLanguage?: string\nemail?: string\nphoneNumber?: string\n}\n@@ -141,6 +145,8 @@ export const fetchPatient = (id: string): AppThunk => async (dispatch) => {\nfunction validatePatient(patient: Patient) {\nconst error: Error = {}\n+ const regexContainsNumber = /\\d/\n+\nif (!patient.givenName) {\nerror.givenName = 'patient.errors.patientGivenNameFeedback'\n}\n@@ -153,6 +159,30 @@ function validatePatient(patient: Patient) {\n}\n}\n+ if (patient.suffix) {\n+ if (regexContainsNumber.test(patient.suffix)) {\n+ error.suffix = 'patient.errors.patientNumInSuffixFeedback'\n+ }\n+ }\n+\n+ if (patient.prefix) {\n+ if (regexContainsNumber.test(patient.prefix)) {\n+ error.prefix = 'patient.errors.patientNumInPrefixFeedback'\n+ }\n+ }\n+\n+ if (patient.familyName) {\n+ if (regexContainsNumber.test(patient.familyName)) {\n+ error.familyName = 'patient.errors.patientNumInFamilyNameFeedback'\n+ }\n+ }\n+\n+ if (patient.preferredLanguage) {\n+ if (regexContainsNumber.test(patient.preferredLanguage)) {\n+ error.preferredLanguage = 'patient.errors.patientNumInPreferredLanguageFeedback'\n+ }\n+ }\n+\nif (patient.email) {\nif (!validator.isEmail(patient.email)) {\nerror.email = 'patient.errors.invalidEmail'\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(patient): add input validation (#2032) |
288,329 | 03.05.2020 19:54:22 | -7,200 | 4a1c7ed4a80265e55020f8b86fbec1aedf366330 | feat(viewpatient): added labs tab to ViewPatient | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"dependencies\": {\n\"@hospitalrun/components\": \"^1.4.0\",\n\"@reduxjs/toolkit\": \"~1.3.0\",\n+ \"@types/escape-string-regexp\": \"~2.0.1\",\n\"@types/pouchdb-find\": \"~6.3.4\",\n\"bootstrap\": \"~4.4.1\",\n\"date-fns\": \"~2.12.0\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/patients/labs/LabsTab.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import React from 'react'\n+import configureMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import { mount } from 'enzyme'\n+import { createMemoryHistory } from 'history'\n+import { Router } from 'react-router'\n+import { Provider } from 'react-redux'\n+import * as components from '@hospitalrun/components'\n+import format from 'date-fns/format'\n+import { act } from 'react-dom/test-utils'\n+import LabsTab from '../../../patients/labs/LabsTab'\n+import Patient from '../../../model/Patient'\n+import Lab from '../../../model/Lab'\n+import Permissions from '../../../model/Permissions'\n+import LabRepository from '../../../clients/db/LabRepository'\n+\n+const expectedPatient = {\n+ id: '123',\n+} as Patient\n+\n+const labs = [\n+ {\n+ id: 'labId',\n+ patientId: '123',\n+ type: 'type',\n+ status: 'requested',\n+ requestedOn: new Date().toISOString(),\n+ } as Lab,\n+]\n+\n+const mockStore = configureMockStore([thunk])\n+const history = createMemoryHistory()\n+\n+let user: any\n+let store: any\n+\n+const setup = (patient = expectedPatient, permissions = [Permissions.WritePatients]) => {\n+ user = { permissions }\n+ store = mockStore({ patient, user })\n+ jest.spyOn(LabRepository, 'findAllByPatientId').mockResolvedValue(labs)\n+ const wrapper = mount(\n+ <Router history={history}>\n+ <Provider store={store}>\n+ <LabsTab patientId={patient.id} />\n+ </Provider>\n+ </Router>,\n+ )\n+\n+ return wrapper\n+}\n+\n+describe('Labs Tab', () => {\n+ it('should list the patients labs', async () => {\n+ const expectedLabs = labs\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await setup()\n+ })\n+ wrapper.update()\n+\n+ const table = wrapper.find('table')\n+ const tableHeader = wrapper.find('thead')\n+ const tableHeaders = wrapper.find('th')\n+ const tableBody = wrapper.find('tbody')\n+ const tableData = wrapper.find('td')\n+\n+ expect(table).toHaveLength(1)\n+ expect(tableHeader).toHaveLength(1)\n+ expect(tableBody).toHaveLength(1)\n+ expect(tableHeaders.at(0).text()).toEqual('labs.lab.type')\n+ expect(tableHeaders.at(1).text()).toEqual('labs.lab.requestedOn')\n+ expect(tableHeaders.at(2).text()).toEqual('labs.lab.status')\n+ expect(tableData.at(0).text()).toEqual(expectedLabs[0].type)\n+ expect(tableData.at(1).text()).toEqual(\n+ format(new Date(expectedLabs[0].requestedOn), 'yyyy-MM-dd hh:mm a'),\n+ )\n+ expect(tableData.at(2).text()).toEqual(expectedLabs[0].status)\n+ })\n+\n+ it('should render a warning message if the patient does not have any labs', async () => {\n+ let wrapper: any\n+\n+ await act(async () => {\n+ wrapper = await setup({ ...expectedPatient })\n+ })\n+\n+ const alert = wrapper.find(components.Alert)\n+\n+ expect(alert).toHaveLength(1)\n+ expect(alert.prop('title')).toEqual('patient.labs.warning.noLabs')\n+ expect(alert.prop('message')).toEqual('patient.labs.noLabsMessage')\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/view/ViewPatient.test.tsx",
"new_path": "src/__tests__/patients/view/ViewPatient.test.tsx",
"diff": "@@ -21,6 +21,8 @@ import * as titleUtil from '../../../page-header/useTitle'\nimport ViewPatient from '../../../patients/view/ViewPatient'\nimport * as patientSlice from '../../../patients/patient-slice'\nimport Permissions from '../../../model/Permissions'\n+import LabsTab from '../../../patients/labs/LabsTab'\n+import LabRepository from '../../../clients/db/LabRepository'\nconst mockStore = configureMockStore([thunk])\n@@ -47,9 +49,9 @@ describe('ViewPatient', () => {\nconst setup = (permissions = [Permissions.ReadPatients]) => {\njest.spyOn(PatientRepository, 'find')\n+ jest.spyOn(LabRepository, 'findAllByPatientId').mockResolvedValue([])\nconst mockedPatientRepository = mocked(PatientRepository, true)\nmockedPatientRepository.find.mockResolvedValue(patient)\n-\nhistory = createMemoryHistory()\nstore = mockStore({\npatient: { patient },\n@@ -127,13 +129,14 @@ describe('ViewPatient', () => {\nconst tabs = tabsHeader.find(Tab)\nexpect(tabsHeader).toHaveLength(1)\n- expect(tabs).toHaveLength(6)\n+ expect(tabs).toHaveLength(7)\nexpect(tabs.at(0).prop('label')).toEqual('patient.generalInformation')\nexpect(tabs.at(1).prop('label')).toEqual('patient.relatedPersons.label')\nexpect(tabs.at(2).prop('label')).toEqual('scheduling.appointments.label')\nexpect(tabs.at(3).prop('label')).toEqual('patient.allergies.label')\nexpect(tabs.at(4).prop('label')).toEqual('patient.diagnoses.label')\nexpect(tabs.at(5).prop('label')).toEqual('patient.notes.label')\n+ expect(tabs.at(6).prop('label')).toEqual('patient.labs.label')\n})\nit('should mark the general information tab as active and render the general information component when route is /patients/:id', async () => {\n@@ -262,4 +265,28 @@ describe('ViewPatient', () => {\nexpect(notesTab).toHaveLength(1)\nexpect(notesTab.prop('patient')).toEqual(patient)\n})\n+\n+ it('should mark the labs tab as active when it is clicked and render the lab component when route is /patients/:id/labs', async () => {\n+ let wrapper: any\n+ await act(async () => {\n+ wrapper = await setup()\n+ })\n+\n+ await act(async () => {\n+ const tabsHeader = wrapper.find(TabsHeader)\n+ const tabs = tabsHeader.find(Tab)\n+ tabs.at(6).prop('onClick')()\n+ })\n+\n+ wrapper.update()\n+\n+ const tabsHeader = wrapper.find(TabsHeader)\n+ const tabs = tabsHeader.find(Tab)\n+ const labsTab = wrapper.find(LabsTab)\n+\n+ expect(history.location.pathname).toEqual(`/patients/${patient.id}/labs`)\n+ expect(tabs.at(6).prop('active')).toBeTruthy()\n+ expect(labsTab).toHaveLength(1)\n+ expect(labsTab.prop('patientId')).toEqual(patient.id)\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/scheduling/appointments/new/NewAppointment.test.tsx",
"new_path": "src/__tests__/scheduling/appointments/new/NewAppointment.test.tsx",
"diff": "@@ -18,6 +18,8 @@ import AppointmentDetailForm from 'scheduling/appointments/AppointmentDetailForm\nimport * as components from '@hospitalrun/components'\nimport * as titleUtil from '../../../../page-header/useTitle'\nimport * as appointmentSlice from '../../../../scheduling/appointments/appointment-slice'\n+import LabRepository from '../../../../clients/db/LabRepository'\n+import Lab from '../../../../model/Lab'\nconst mockStore = configureMockStore([thunk])\nconst mockedComponents = mocked(components, true)\n@@ -32,6 +34,7 @@ describe('New Appointment', () => {\nmocked(AppointmentRepository, true).save.mockResolvedValue(\nexpectedNewAppointment as Appointment,\n)\n+ jest.spyOn(LabRepository, 'findAllByPatientId').mockResolvedValue([] as Lab[])\nhistory = createMemoryHistory()\nstore = mockStore({\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/LabRepository.ts",
"new_path": "src/clients/db/LabRepository.ts",
"diff": "@@ -9,6 +9,18 @@ export class LabRepository extends Repository<Lab> {\nindex: { fields: ['requestedOn'] },\n})\n}\n+\n+ async findAllByPatientId(patientId: string): Promise<Lab[]> {\n+ return super.search({\n+ selector: {\n+ $and: [\n+ {\n+ patientId,\n+ },\n+ ],\n+ },\n+ })\n+ }\n}\nexport default new LabRepository()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -85,6 +85,14 @@ export default {\n},\naddNoteAbove: 'Add a note using the button above.',\n},\n+ labs: {\n+ label: 'Labs',\n+ new: 'Add New Lab',\n+ warning: {\n+ noLabs: 'No Labs',\n+ },\n+ noLabsMessage: 'No labs requests for this person.',\n+ },\ntypes: {\ncharity: 'Charity',\nprivate: 'Private',\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/patients/labs/LabsTab.tsx",
"diff": "+import React, { useEffect, useState } from 'react'\n+import { Alert } from '@hospitalrun/components'\n+import { useTranslation } from 'react-i18next'\n+import format from 'date-fns/format'\n+import { useHistory } from 'react-router'\n+import Lab from '../../model/Lab'\n+import LabRepository from '../../clients/db/LabRepository'\n+\n+interface Props {\n+ patientId: string\n+}\n+\n+const LabsTab = (props: Props) => {\n+ const history = useHistory()\n+ const { patientId } = props\n+ const { t } = useTranslation()\n+\n+ const [labs, setLabs] = useState<Lab[]>([])\n+\n+ useEffect(() => {\n+ const fetch = async () => {\n+ const fetchedLabs = await LabRepository.findAllByPatientId(patientId)\n+ setLabs(fetchedLabs)\n+ }\n+\n+ fetch()\n+ }, [patientId])\n+\n+ const onTableRowClick = (lab: Lab) => {\n+ history.push(`/labs/${lab.id}`)\n+ }\n+\n+ return (\n+ <div>\n+ {(!labs || labs.length === 0) && (\n+ <Alert\n+ color=\"warning\"\n+ title={t('patient.labs.warning.noLabs')}\n+ message={t('patient.labs.noLabsMessage')}\n+ />\n+ )}\n+ {labs && labs.length > 0 && (\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light\">\n+ <tr>\n+ <th>{t('labs.lab.type')}</th>\n+ <th>{t('labs.lab.requestedOn')}</th>\n+ <th>{t('labs.lab.status')}</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n+ {labs.map((lab) => (\n+ <tr onClick={() => onTableRowClick(lab)} key={lab.id}>\n+ <td>{lab.type}</td>\n+ <td>{format(new Date(lab.requestedOn), 'yyyy-MM-dd hh:mm a')}</td>\n+ <td>{lab.status}</td>\n+ </tr>\n+ ))}\n+ </tbody>\n+ </table>\n+ )}\n+ </div>\n+ )\n+}\n+\n+export default LabsTab\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/view/ViewPatient.tsx",
"new_path": "src/patients/view/ViewPatient.tsx",
"diff": "@@ -18,6 +18,7 @@ import RelatedPerson from '../related-persons/RelatedPersonTab'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\nimport AppointmentsList from '../appointments/AppointmentsList'\nimport Note from '../notes/NoteTab'\n+import Labs from '../labs/LabsTab'\nconst getPatientCode = (p: Patient): string => {\nif (p) {\n@@ -113,6 +114,11 @@ const ViewPatient = () => {\nlabel={t('patient.notes.label')}\nonClick={() => history.push(`/patients/${patient.id}/notes`)}\n/>\n+ <Tab\n+ active={location.pathname === `/patients/${patient.id}/labs`}\n+ label={t('patient.labs.label')}\n+ onClick={() => history.push(`/patients/${patient.id}/labs`)}\n+ />\n</TabsHeader>\n<Panel>\n<Route exact path=\"/patients/:id\">\n@@ -133,6 +139,9 @@ const ViewPatient = () => {\n<Route exact path=\"/patients/:id/notes\">\n<Note patient={patient} />\n</Route>\n+ <Route exact path=\"/patients/:id/labs\">\n+ <Labs patientId={patient.id} />\n+ </Route>\n</Panel>\n</div>\n)\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatient): added labs tab to ViewPatient (#1987) |
288,323 | 03.05.2020 14:52:49 | 18,000 | f11d8e90fe2752eba35fa2108e188053b89e6e8f | feat(incidents): adds ability to view all incidents | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/incidents/incidents-slice.test.ts",
"diff": "+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+import { AnyAction } from 'redux'\n+import { RootState } from '../../store'\n+import incidents, {\n+ fetchIncidents,\n+ fetchIncidentsStart,\n+ fetchIncidentsSuccess,\n+} from '../../incidents/incidents-slice'\n+import IncidentRepository from '../../clients/db/IncidentRepository'\n+import Incident from '../../model/Incident'\n+\n+const mockStore = createMockStore<RootState, any>([thunk])\n+\n+describe('Incidents Slice', () => {\n+ describe('actions', () => {\n+ it('should setup the default state correctly', () => {\n+ const incidentsStore = incidents(undefined, {} as AnyAction)\n+ expect(incidentsStore.status).toEqual('loading')\n+ expect(incidentsStore.incidents).toEqual([])\n+ })\n+\n+ it('should handle fetch incidents start', () => {\n+ const incidentsStore = incidents(undefined, fetchIncidentsStart())\n+ expect(incidentsStore.status).toEqual('loading')\n+ })\n+\n+ it('should handle fetch incidents success', () => {\n+ const expectedIncidents = [{ id: '123' }] as Incident[]\n+ const incidentsStore = incidents(undefined, fetchIncidentsSuccess(expectedIncidents))\n+ expect(incidentsStore.status).toEqual('completed')\n+ expect(incidentsStore.incidents).toEqual(expectedIncidents)\n+ })\n+\n+ describe('fetch incidents', () => {\n+ it('should fetch all of the incidents', async () => {\n+ const expectedIncidents = [{ id: '123' }] as Incident[]\n+ jest.spyOn(IncidentRepository, 'findAll').mockResolvedValue(expectedIncidents)\n+ const store = mockStore()\n+\n+ await store.dispatch(fetchIncidents())\n+\n+ expect(store.getActions()[0]).toEqual(fetchIncidentsStart())\n+ expect(IncidentRepository.findAll).toHaveBeenCalledTimes(1)\n+ expect(store.getActions()[1]).toEqual(fetchIncidentsSuccess(expectedIncidents))\n+ })\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/list/ViewIncidents.test.tsx",
"new_path": "src/__tests__/incidents/list/ViewIncidents.test.tsx",
"diff": "@@ -12,11 +12,24 @@ import * as titleUtil from '../../../page-header/useTitle'\nimport * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\nimport * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\nimport ViewIncidents from '../../../incidents/list/ViewIncidents'\n+import Incident from '../../../model/Incident'\n+import IncidentRepository from '../../../clients/db/IncidentRepository'\nconst mockStore = createMockStore([thunk])\ndescribe('View Incidents', () => {\nlet history: any\n+ const expectedDate = new Date(2020, 5, 3, 19, 48)\n+ const expectedIncidents = [\n+ {\n+ id: '123',\n+ code: 'some code',\n+ status: 'reported',\n+ reportedBy: 'some user id',\n+ date: expectedDate.toISOString(),\n+ reportedOn: expectedDate.toISOString(),\n+ },\n+ ] as Incident[]\nlet setButtonToolBarSpy: any\nconst setup = async (permissions: Permissions[]) => {\n@@ -25,6 +38,7 @@ describe('View Incidents', () => {\nsetButtonToolBarSpy = jest.fn()\njest.spyOn(titleUtil, 'default')\njest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\n+ jest.spyOn(IncidentRepository, 'findAll').mockResolvedValue(expectedIncidents)\nhistory = createMemoryHistory()\nhistory.push(`/incidents`)\n@@ -33,6 +47,9 @@ describe('View Incidents', () => {\nuser: {\npermissions,\n},\n+ incidents: {\n+ incidents: expectedIncidents,\n+ },\n})\nlet wrapper: any\n@@ -53,9 +70,48 @@ describe('View Incidents', () => {\nreturn wrapper\n}\n+ describe('layout', () => {\nit('should set the title', async () => {\nawait setup([Permissions.ViewIncidents])\nexpect(titleUtil.default).toHaveBeenCalledWith('incidents.reports.label')\n})\n+\n+ it('should render a table with the incidents', async () => {\n+ const wrapper = await setup([Permissions.ViewIncidents])\n+\n+ const table = wrapper.find('table')\n+ const tableHeader = table.find('thead')\n+ const tableBody = table.find('tbody')\n+ const tableHeaders = tableHeader.find('th')\n+ const tableColumns = tableBody.find('td')\n+\n+ expect(tableHeaders.at(0).text()).toEqual('incidents.reports.code')\n+ expect(tableHeaders.at(1).text()).toEqual('incidents.reports.dateOfIncident')\n+ expect(tableHeaders.at(2).text()).toEqual('incidents.reports.reportedBy')\n+ expect(tableHeaders.at(3).text()).toEqual('incidents.reports.reportedOn')\n+ expect(tableHeaders.at(4).text()).toEqual('incidents.reports.status')\n+\n+ expect(tableColumns.at(0).text()).toEqual(expectedIncidents[0].code)\n+ expect(tableColumns.at(1).text()).toEqual('2020-06-03 07:48 PM')\n+ expect(tableColumns.at(2).text()).toEqual(expectedIncidents[0].reportedBy)\n+ expect(tableColumns.at(3).text()).toEqual('2020-06-03 07:48 PM')\n+ expect(tableColumns.at(4).text()).toEqual(expectedIncidents[0].status)\n+ })\n+ })\n+\n+ describe('on table row click', () => {\n+ it('should navigate to the incident when the table row is clicked', async () => {\n+ const wrapper = await setup([Permissions.ViewIncidents])\n+\n+ const tr = wrapper.find('tr').at(1)\n+\n+ act(() => {\n+ const onClick = tr.prop('onClick')\n+ onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual(`/incidents/${expectedIncidents[0].id}`)\n+ })\n+ })\n})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/incidents-slice.ts",
"diff": "+import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import { AppThunk } from 'store'\n+import Incident from '../model/Incident'\n+import IncidentRepository from '../clients/db/IncidentRepository'\n+\n+interface IncidentsState {\n+ incidents: Incident[]\n+ status: 'loading' | 'completed'\n+}\n+\n+const initialState: IncidentsState = {\n+ incidents: [],\n+ status: 'loading',\n+}\n+\n+function start(state: IncidentsState) {\n+ state.status = 'loading'\n+}\n+\n+function finish(state: IncidentsState, { payload }: PayloadAction<Incident[]>) {\n+ state.status = 'completed'\n+ state.incidents = payload\n+}\n+\n+const incidentSlice = createSlice({\n+ name: 'lab',\n+ initialState,\n+ reducers: {\n+ fetchIncidentsStart: start,\n+ fetchIncidentsSuccess: finish,\n+ },\n+})\n+\n+export const { fetchIncidentsStart, fetchIncidentsSuccess } = incidentSlice.actions\n+\n+export const fetchIncidents = (): AppThunk => async (dispatch) => {\n+ dispatch(fetchIncidentsStart())\n+\n+ const incidents = await IncidentRepository.findAll()\n+\n+ dispatch(fetchIncidentsSuccess(incidents))\n+}\n+\n+export default incidentSlice.reducer\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/list/ViewIncidents.tsx",
"new_path": "src/incidents/list/ViewIncidents.tsx",
"diff": "-import React from 'react'\n+import React, { useEffect } from 'react'\nimport { useTranslation } from 'react-i18next'\n+import { useDispatch, useSelector } from 'react-redux'\n+import format from 'date-fns/format'\n+import { useHistory } from 'react-router'\nimport useTitle from '../../page-header/useTitle'\n+import { RootState } from '../../store'\n+import { fetchIncidents } from '../incidents-slice'\n+import Incident from '../../model/Incident'\nconst ViewIncidents = () => {\nconst { t } = useTranslation()\n+ const history = useHistory()\n+ const dispatch = useDispatch()\nuseTitle(t('incidents.reports.label'))\n- return <h1>Reported Incidents</h1>\n+ const { incidents } = useSelector((state: RootState) => state.incidents)\n+\n+ useEffect(() => {\n+ dispatch(fetchIncidents())\n+ }, [dispatch])\n+\n+ const onTableRowClick = (incident: Incident) => {\n+ history.push(`incidents/${incident.id}`)\n+ }\n+\n+ return (\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light\">\n+ <tr>\n+ <th>{t('incidents.reports.code')}</th>\n+ <th>{t('incidents.reports.dateOfIncident')}</th>\n+ <th>{t('incidents.reports.reportedBy')}</th>\n+ <th>{t('incidents.reports.reportedOn')}</th>\n+ <th>{t('incidents.reports.status')}</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n+ {incidents.map((incident: Incident) => (\n+ <tr onClick={() => onTableRowClick(incident)} key={incident.id}>\n+ <td>{incident.code}</td>\n+ <td>{format(new Date(incident.date), 'yyyy-MM-dd hh:mm a')}</td>\n+ <td>{incident.reportedBy}</td>\n+ <td>{format(new Date(incident.reportedOn), 'yyyy-MM-dd hh:mm a')}</td>\n+ <td>{incident.status}</td>\n+ </tr>\n+ ))}\n+ </tbody>\n+ </table>\n+ )\n}\nexport default ViewIncidents\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/incidents/index.ts",
"new_path": "src/locales/enUs/translations/incidents/index.ts",
"diff": "@@ -13,6 +13,10 @@ export default {\ncategory: 'Category',\ncategoryItem: 'Category Item',\ndescription: 'Description of Incident',\n+ code: 'Code',\n+ reportedBy: 'Reported By',\n+ reportedOn: 'Reported On',\n+ status: 'Status',\nerror: {\ndateRequired: 'Date is required.',\ndateMustBeInThePast: 'Date must be in the past.',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Incident.ts",
"new_path": "src/model/Incident.ts",
"diff": "@@ -9,4 +9,5 @@ export default interface Incident extends AbstractDBModel {\ncategory: string\ncategoryItem: string\ndescription: string\n+ status: 'reported'\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/store/index.ts",
"new_path": "src/store/index.ts",
"diff": "@@ -8,6 +8,7 @@ import title from '../page-header/title-slice'\nimport user from '../user/user-slice'\nimport lab from '../labs/lab-slice'\nimport incident from '../incidents/incident-slice'\n+import incidents from '../incidents/incidents-slice'\nimport breadcrumbs from '../breadcrumbs/breadcrumbs-slice'\nimport components from '../components/component-slice'\n@@ -22,6 +23,7 @@ const reducer = combineReducers({\ncomponents,\nlab,\nincident,\n+ incidents,\n})\nconst store = configureStore({\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incidents): adds ability to view all incidents |
288,323 | 03.05.2020 20:00:47 | 18,000 | 5887859542247573843fc5af980cd081f6cc6f25 | feat(incidents): add ability to view an incident | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/HospitalRun.test.tsx",
"new_path": "src/__tests__/HospitalRun.test.tsx",
"diff": "@@ -34,6 +34,7 @@ describe('HospitalRun', () => {\nappointments: { appointments: [] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ incidents: { incidents: [] },\n})\nconst wrapper = mount(\n@@ -265,6 +266,7 @@ describe('HospitalRun', () => {\nuser: { permissions: [Permissions.ViewIncidents] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ incidents: { incidents: [] },\n})\nlet wrapper: any\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/Incidents.test.tsx",
"new_path": "src/__tests__/incidents/Incidents.test.tsx",
"diff": "@@ -10,19 +10,28 @@ import Permissions from 'model/Permissions'\nimport ViewIncident from '../../incidents/view/ViewIncident'\nimport Incidents from '../../incidents/Incidents'\nimport ReportIncident from '../../incidents/report/ReportIncident'\n+import Incident from '../../model/Incident'\n+import IncidentRepository from '../../clients/db/IncidentRepository'\nconst mockStore = configureMockStore([thunk])\ndescribe('Incidents', () => {\ndescribe('routing', () => {\ndescribe('/incidents/new', () => {\n- it('should render the new lab request screen when /incidents/new is accessed', () => {\n+ it('should render the new incident screen when /incidents/new is accessed', () => {\n+ const expectedIncident = {\n+ id: '1234',\n+ code: '1234',\n+ } as Incident\n+ jest.spyOn(IncidentRepository, 'find').mockResolvedValue(expectedIncident)\nconst store = mockStore({\ntitle: 'test',\nuser: { permissions: [Permissions.ReportIncident] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n- incident: {},\n+ incident: {\n+ incident: expectedIncident,\n+ },\n})\nconst wrapper = mount(\n@@ -36,7 +45,7 @@ describe('Incidents', () => {\nexpect(wrapper.find(ReportIncident)).toHaveLength(1)\n})\n- it('should not navigate to /incidents/new if the user does not have RequestLab permissions', () => {\n+ it('should not navigate to /incidents/new if the user does not have ReportIncident permissions', () => {\nconst store = mockStore({\ntitle: 'test',\nuser: { permissions: [] },\n@@ -57,12 +66,20 @@ describe('Incidents', () => {\n})\ndescribe('/incidents/:id', () => {\n- it('should render the view lab screen when /incidents/:id is accessed', async () => {\n+ it('should render the view incident screen when /incidents/:id is accessed', async () => {\nconst store = mockStore({\ntitle: 'test',\nuser: { permissions: [Permissions.ViewIncident] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n+ incident: {\n+ incident: {\n+ id: '1234',\n+ code: '1234 ',\n+ date: new Date().toISOString(),\n+ reportedOn: new Date().toISOString(),\n+ },\n+ },\n})\nlet wrapper: any\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/incident-slice.test.ts",
"new_path": "src/__tests__/incidents/incident-slice.test.ts",
"diff": "@@ -8,10 +8,15 @@ import incident, {\nreportIncidentSuccess,\nreportIncidentError,\nreportIncident,\n+ fetchIncidentStart,\n+ fetchIncidentSuccess,\n+ fetchIncident,\n} from '../../incidents/incident-slice'\nimport Incident from '../../model/Incident'\nimport { RootState } from '../../store'\nimport IncidentRepository from '../../clients/db/IncidentRepository'\n+import Permissions from '../../model/Permissions'\n+import User from '../../model/User'\nconst mockStore = createMockStore<RootState, any>([thunk])\n@@ -58,6 +63,22 @@ describe('incident slice', () => {\nexpect(incidentStore.status).toEqual('error')\nexpect(incidentStore.error).toEqual(expectedError)\n})\n+\n+ it('should handle fetch incident start', () => {\n+ const incidentStore = incident(undefined, fetchIncidentStart())\n+ expect(incidentStore.status).toEqual('loading')\n+ })\n+\n+ it('should handle fetch incident success', () => {\n+ const expectedIncident = {\n+ id: '1234',\n+ code: 'some code',\n+ } as Incident\n+\n+ const incidentStore = incident(undefined, fetchIncidentSuccess(expectedIncident))\n+ expect(incidentStore.status).toEqual('completed')\n+ expect(incidentStore.incident).toEqual(expectedIncident)\n+ })\n})\ndescribe('report incident', () => {\n@@ -84,11 +105,17 @@ describe('incident slice', () => {\ncode: `I-${expectedShortId}`,\nreportedOn: expectedDate.toISOString(),\nreportedBy: 'some user id',\n- }\n+ status: 'reported',\n+ } as Incident\njest.spyOn(IncidentRepository, 'save').mockResolvedValue(expectedIncident)\n- const store = mockStore({ user: { user: { id: expectedIncident.reportedBy } } })\n+ const store = mockStore({\n+ user: {\n+ user: { id: expectedIncident.reportedBy } as User,\n+ permissions: [] as Permissions[],\n+ },\n+ } as any)\nawait store.dispatch(reportIncident(newIncident, onSuccessSpy))\n@@ -110,8 +137,12 @@ describe('incident slice', () => {\ndescription: 'incidents.reports.error.descriptionRequired',\n}\n- const store = mockStore({ user: { user: { id: 'some id' } } })\n-\n+ const store = mockStore({\n+ user: {\n+ user: { id: 'some id' } as User,\n+ permissions: [] as Permissions[],\n+ },\n+ } as any)\nawait store.dispatch(reportIncident(newIncident, onSuccessSpy))\nexpect(store.getActions()[0]).toEqual(reportIncidentStart())\n@@ -124,7 +155,7 @@ describe('incident slice', () => {\nconst onSuccessSpy = jest.fn()\nconst newIncident = {\ndescription: 'description',\n- date: addDays(new Date(), 4),\n+ date: addDays(new Date(), 4).toISOString(),\ndepartment: 'some department',\ncategory: 'category',\ncategoryItem: 'categoryItem',\n@@ -134,8 +165,12 @@ describe('incident slice', () => {\ndate: 'incidents.reports.error.dateMustBeInThePast',\n}\n- const store = mockStore({ user: { user: { id: 'some id' } } })\n-\n+ const store = mockStore({\n+ user: {\n+ user: { id: 'some id' } as User,\n+ permissions: [] as Permissions[],\n+ },\n+ } as any)\nawait store.dispatch(reportIncident(newIncident, onSuccessSpy))\nexpect(store.getActions()[0]).toEqual(reportIncidentStart())\n@@ -144,4 +179,26 @@ describe('incident slice', () => {\nexpect(onSuccessSpy).not.toHaveBeenCalled()\n})\n})\n+\n+ describe('fetch incident', () => {\n+ it('should fetch the incident', async () => {\n+ const expectedIncident = {\n+ id: '123',\n+ description: 'description',\n+ date: addDays(new Date(), 4).toISOString(),\n+ department: 'some department',\n+ category: 'category',\n+ categoryItem: 'categoryItem',\n+ } as Incident\n+ jest.spyOn(IncidentRepository, 'find').mockResolvedValue(expectedIncident)\n+\n+ const store = mockStore()\n+\n+ await store.dispatch(fetchIncident(expectedIncident.id))\n+\n+ expect(store.getActions()[0]).toEqual(fetchIncidentStart())\n+ expect(IncidentRepository.find).toHaveBeenCalledWith(expectedIncident.id)\n+ expect(store.getActions()[1]).toEqual(fetchIncidentSuccess(expectedIncident))\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/view/ViewIncident.test.tsx",
"new_path": "src/__tests__/incidents/view/ViewIncident.test.tsx",
"diff": "@@ -12,24 +12,44 @@ import * as titleUtil from '../../../page-header/useTitle'\nimport * as ButtonBarProvider from '../../../page-header/ButtonBarProvider'\nimport * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\nimport ViewIncident from '../../../incidents/view/ViewIncident'\n+import Incident from '../../../model/Incident'\n+import IncidentRepository from '../../../clients/db/IncidentRepository'\nconst mockStore = createMockStore([thunk])\ndescribe('View Incident', () => {\n+ const expectedDate = new Date(2020, 5, 1, 19, 48)\nlet history: any\n+ const expectedIncident = {\n+ id: '1234',\n+ code: 'some code',\n+ department: 'some department',\n+ description: 'some description',\n+ category: 'some category',\n+ categoryItem: 'some category item',\n+ status: 'reported',\n+ reportedBy: 'some user id',\n+ reportedOn: expectedDate.toISOString(),\n+ date: expectedDate.toISOString(),\n+ } as Incident\nconst setup = async (permissions: Permissions[]) => {\njest.resetAllMocks()\njest.spyOn(breadcrumbUtil, 'default')\njest.spyOn(titleUtil, 'default')\n+ jest.spyOn(IncidentRepository, 'find').mockResolvedValue(expectedIncident)\nhistory = createMemoryHistory()\nhistory.push(`/incidents/1234`)\n+\nconst store = mockStore({\ntitle: '',\nuser: {\npermissions,\n},\n+ incident: {\n+ incident: expectedIncident,\n+ },\n})\nlet wrapper: any\n@@ -50,17 +70,83 @@ describe('View Incident', () => {\nreturn wrapper\n}\n+ describe('layout', () => {\nit('should set the title', async () => {\nawait setup([Permissions.ViewIncident])\n- expect(titleUtil.default).toHaveBeenCalledWith('incidents.reports.view')\n+ expect(titleUtil.default).toHaveBeenCalledWith(expectedIncident.code)\n})\nit('should set the breadcrumbs properly', async () => {\nawait setup([Permissions.ViewIncident])\nexpect(breadcrumbUtil.default).toHaveBeenCalledWith([\n- { i18nKey: 'incidents.reports.view', location: '/incidents/1234' },\n+ { i18nKey: expectedIncident.code, location: '/incidents/1234' },\n])\n})\n+\n+ it('should render the date of incident', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const dateOfIncidentFormGroup = wrapper.find('.incident-date')\n+ expect(dateOfIncidentFormGroup.find('h4').text()).toEqual('incidents.reports.dateOfIncident')\n+ expect(dateOfIncidentFormGroup.find('h5').text()).toEqual('2020-06-01 07:48 PM')\n+ })\n+\n+ it('should render the status', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const dateOfIncidentFormGroup = wrapper.find('.incident-status')\n+ expect(dateOfIncidentFormGroup.find('h4').text()).toEqual('incidents.reports.status')\n+ expect(dateOfIncidentFormGroup.find('h5').text()).toEqual(expectedIncident.status)\n+ })\n+\n+ it('should render the reported by', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const dateOfIncidentFormGroup = wrapper.find('.incident-reported-by')\n+ expect(dateOfIncidentFormGroup.find('h4').text()).toEqual('incidents.reports.reportedBy')\n+ expect(dateOfIncidentFormGroup.find('h5').text()).toEqual(expectedIncident.reportedBy)\n+ })\n+\n+ it('should render the reported on', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const dateOfIncidentFormGroup = wrapper.find('.incident-reported-on')\n+ expect(dateOfIncidentFormGroup.find('h4').text()).toEqual('incidents.reports.reportedOn')\n+ expect(dateOfIncidentFormGroup.find('h5').text()).toEqual('2020-06-01 07:48 PM')\n+ })\n+\n+ it('should render the department', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const departmentInput = wrapper.findWhere((w: any) => w.prop('name') === 'department')\n+ expect(departmentInput.prop('label')).toEqual('incidents.reports.department')\n+ expect(departmentInput.prop('value')).toEqual(expectedIncident.department)\n+ })\n+\n+ it('should render the category', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const categoryInput = wrapper.findWhere((w: any) => w.prop('name') === 'category')\n+ expect(categoryInput.prop('label')).toEqual('incidents.reports.category')\n+ expect(categoryInput.prop('value')).toEqual(expectedIncident.category)\n+ })\n+\n+ it('should render the category item', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const categoryItemInput = wrapper.findWhere((w: any) => w.prop('name') === 'categoryItem')\n+ expect(categoryItemInput.prop('label')).toEqual('incidents.reports.categoryItem')\n+ expect(categoryItemInput.prop('value')).toEqual(expectedIncident.categoryItem)\n+ })\n+\n+ it('should render the description', async () => {\n+ const wrapper = await setup([Permissions.ViewIncident])\n+\n+ const descriptionTextInput = wrapper.findWhere((w: any) => w.prop('name') === 'description')\n+ expect(descriptionTextInput.prop('label')).toEqual('incidents.reports.description')\n+ expect(descriptionTextInput.prop('value')).toEqual(expectedIncident.description)\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/incident-slice.ts",
"new_path": "src/incidents/incident-slice.ts",
"diff": "@@ -45,6 +45,8 @@ const incidentSlice = createSlice({\nname: 'incident',\ninitialState,\nreducers: {\n+ fetchIncidentStart: start,\n+ fetchIncidentSuccess: finish,\nreportIncidentStart: start,\nreportIncidentSuccess: finish,\nreportIncidentError: error,\n@@ -52,11 +54,19 @@ const incidentSlice = createSlice({\n})\nexport const {\n+ fetchIncidentStart,\n+ fetchIncidentSuccess,\nreportIncidentStart,\nreportIncidentSuccess,\nreportIncidentError,\n} = incidentSlice.actions\n+export const fetchIncident = (id: string): AppThunk => async (dispatch) => {\n+ dispatch(fetchIncidentStart())\n+ const incident = await IncidentRepository.find(id)\n+ dispatch(fetchIncidentSuccess(incident))\n+}\n+\nfunction validateIncident(incident: Incident): Error {\nconst newError: Error = {}\n@@ -98,6 +108,7 @@ export const reportIncident = (\nincident.reportedOn = new Date(Date.now()).toISOString()\nincident.code = getIncidentCode()\nincident.reportedBy = getState().user.user.id\n+ incident.status = 'reported'\nconst newIncident = await IncidentRepository.save(incident)\nawait dispatch(reportIncidentSuccess(newIncident))\nif (onSuccess) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/view/ViewIncident.tsx",
"new_path": "src/incidents/view/ViewIncident.tsx",
"diff": "-import React from 'react'\n+import React, { useEffect } from 'react'\nimport { useTranslation } from 'react-i18next'\nimport { useParams } from 'react-router'\n+import { useDispatch, useSelector } from 'react-redux'\n+import { Column, Row } from '@hospitalrun/components'\n+import format from 'date-fns/format'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\nimport useTitle from '../../page-header/useTitle'\n+import { RootState } from '../../store'\n+import { fetchIncident } from '../incident-slice'\n+import TextInputWithLabelFormGroup from '../../components/input/TextInputWithLabelFormGroup'\n+import TextFieldWithLabelFormGroup from '../../components/input/TextFieldWithLabelFormGroup'\nconst ViewIncident = () => {\n+ const dispatch = useDispatch()\nconst { t } = useTranslation()\nconst { id } = useParams()\n- useTitle(t('incidents.reports.view'))\n+ const { incident } = useSelector((state: RootState) => state.incident)\n+ useTitle(incident ? incident.code : '')\nconst breadcrumbs = [\n{\n- i18nKey: 'incidents.reports.view',\n+ i18nKey: incident ? incident.code : '',\nlocation: `/incidents/${id}`,\n},\n]\nuseAddBreadcrumbs(breadcrumbs)\n- return <h1>View Incident</h1>\n+ useEffect(() => {\n+ if (id) {\n+ dispatch(fetchIncident(id))\n+ }\n+ }, [dispatch, id])\n+\n+ return (\n+ <>\n+ <Row>\n+ <Column>\n+ <div className=\"form-group incident-date\">\n+ <h4>{t('incidents.reports.dateOfIncident')}</h4>\n+ <h5>{format(new Date(incident?.date || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n+ </div>\n+ </Column>\n+ <Column>\n+ <div className=\"form-group incident-status\">\n+ <h4>{t('incidents.reports.status')}</h4>\n+ <h5>{incident?.status}</h5>\n+ </div>\n+ </Column>\n+ <Column>\n+ <div className=\"form-group incident-reported-by\">\n+ <h4>{t('incidents.reports.reportedBy')}</h4>\n+ <h5>{incident?.reportedBy}</h5>\n+ </div>\n+ </Column>\n+ <Column>\n+ <div className=\"form-group incident-reported-on\">\n+ <h4>{t('incidents.reports.reportedOn')}</h4>\n+ <h5>{format(new Date(incident?.reportedOn || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n+ </div>\n+ </Column>\n+ </Row>\n+ <div className=\"border-bottom mb-2\" />\n+ <Row>\n+ <Column md={12}>\n+ <TextInputWithLabelFormGroup\n+ label={t('incidents.reports.department')}\n+ name=\"department\"\n+ value={incident?.department}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column md={6}>\n+ <TextInputWithLabelFormGroup\n+ name=\"category\"\n+ label={t('incidents.reports.category')}\n+ value={incident?.category}\n+ />\n+ </Column>\n+ <Column md={6}>\n+ <TextInputWithLabelFormGroup\n+ label={t('incidents.reports.categoryItem')}\n+ name=\"categoryItem\"\n+ value={incident?.categoryItem}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column md={12}>\n+ <TextFieldWithLabelFormGroup\n+ label={t('incidents.reports.description')}\n+ name=\"description\"\n+ value={incident?.description}\n+ />\n+ </Column>\n+ </Row>\n+ </>\n+ )\n}\nexport default ViewIncident\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incidents): add ability to view an incident |
288,350 | 05.05.2020 05:28:58 | -19,080 | 9084411bc459abfd5e7003460ff2f1574cbbc243 | fix(viewpatients): call PatientRepository.findAll() only once | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -53,6 +53,18 @@ describe('Patients', () => {\nmockedPatientRepository.findAll.mockResolvedValue([])\n})\n+ describe('initalLoad', () => {\n+ afterEach(() => {\n+ jest.restoreAllMocks()\n+ })\n+\n+ it('should call fetchPatients only once', () => {\n+ setup()\n+ const findAllPagedSpy = jest.spyOn(PatientRepository, 'findAll')\n+ expect(findAllPagedSpy).toHaveBeenCalledTimes(1)\n+ })\n+ })\n+\ndescribe('layout', () => {\nafterEach(() => {\njest.restoreAllMocks()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -6,7 +6,7 @@ import { Spinner, Button, Container, Row, TextInput, Column } from '@hospitalrun\nimport { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\nimport { RootState } from '../../store'\n-import { fetchPatients, searchPatients } from '../patients-slice'\n+import { searchPatients } from '../patients-slice'\nimport useTitle from '../../page-header/useTitle'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\nimport useDebounce from '../../hooks/debounce'\n@@ -32,8 +32,6 @@ const ViewPatients = () => {\n}, [dispatch, debouncedSearchText])\nuseEffect(() => {\n- dispatch(fetchPatients())\n-\nsetButtonToolBar([\n<Button\nkey=\"newPatientButton\"\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(viewpatients): call PatientRepository.findAll() only once (#2044) |
288,350 | 06.05.2020 00:38:41 | -19,080 | b96680fbe1329384ed6eefa9e414803c781897dd | feat(viewpatients): add paging for search patients
Add paging for search patients
feat | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -67,3 +67,5 @@ typings/\npackage-lock.json\n.DS_Store\nyarn.lock\n+\n+.vscode/\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "@@ -3,7 +3,6 @@ export default interface PageRequest {\nsize: number | undefined\nnextPageInfo: { [key: string]: string | null } | undefined\npreviousPageInfo: { [key: string]: string | null } | undefined\n-\ndirection: 'previous' | 'next' | null\n}\nexport const UnpagedRequest: PageRequest = {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "@@ -57,7 +57,7 @@ export class PatientRepository extends Repository<Patient> {\nconst result = await super\n.search({\nselector,\n- limit: pageRequest.size,\n+ limit: pageRequest.size ? pageRequest.size + 1 : undefined,\nskip:\npageRequest.number && pageRequest.size ? (pageRequest.number - 1) * pageRequest.size : 0,\nsort:\n@@ -71,11 +71,19 @@ export class PatientRepository extends Repository<Patient> {\n})\nconst pagedResult: Page<Patient> = {\n- content: result,\n+ content: result.slice(\n+ 0,\n+ pageRequest.size\n+ ? result.length < pageRequest.size\n+ ? result.length\n+ : pageRequest.size\n+ : result.length,\n+ ),\npageRequest,\n- hasNext: pageRequest.size !== undefined && result.length === pageRequest.size,\n+ hasNext: pageRequest.size !== undefined && result.length === pageRequest.size + 1,\nhasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n}\n+\nreturn pagedResult\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/hooks/useUpdateEffect.ts",
"diff": "+import { useRef, useEffect } from 'react'\n+\n+export default function (effect: Function, dependencies: any[]) {\n+ const isInitialMount = useRef(true)\n+\n+ useEffect(() => {\n+ if (isInitialMount.current) {\n+ isInitialMount.current = false\n+ } else {\n+ effect()\n+ }\n+ }, dependencies)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "-import React, { useEffect, useState } from 'react'\n+import React, { useEffect, useState, useRef } from 'react'\nimport { useSelector, useDispatch } from 'react-redux'\nimport { useHistory } from 'react-router'\nimport { useTranslation } from 'react-i18next'\n@@ -8,6 +8,7 @@ import format from 'date-fns/format'\nimport SortRequest from 'clients/db/SortRequest'\nimport PageRequest from 'clients/db/PageRequest'\nimport PageComponent from 'components/PageComponent'\n+import useUpdateEffect from 'hooks/useUpdateEffect'\nimport { RootState } from '../../store'\nimport { searchPatients } from '../patients-slice'\nimport useTitle from '../../page-header/useTitle'\n@@ -25,7 +26,8 @@ const ViewPatients = () => {\nconst { patients, isLoading } = useSelector((state: RootState) => state.patients)\nconst setButtonToolBar = useButtonToolbarSetter()\n- const [userPageRequest, setUserPageRequest] = useState<PageRequest>({\n+\n+ const defaultPageRequest = useRef<PageRequest>({\nsize: 1,\nnumber: 1,\nnextPageInfo: { index: null },\n@@ -33,46 +35,53 @@ const ViewPatients = () => {\ndirection: 'next',\n})\n+ const [userPageRequest, setUserPageRequest] = useState<PageRequest>(defaultPageRequest.current)\n+\nconst setNextPageRequest = () => {\n- setUserPageRequest((p) => {\n- if (p && p.number && p.number >= 0 && p.size) {\n+ setUserPageRequest(() => {\nconst newPageRequest: PageRequest = {\n- number: p.number + 1,\n- size: p.size,\n+ number:\n+ patients.pageRequest && patients.pageRequest.number ? patients.pageRequest.number + 1 : 1,\n+ size: patients.pageRequest ? patients.pageRequest.size : undefined,\nnextPageInfo: patients.pageRequest?.nextPageInfo,\npreviousPageInfo: undefined,\ndirection: 'next',\n}\nreturn newPageRequest\n- }\n- return p\n})\n}\nconst setPreviousPageRequest = () => {\n- setUserPageRequest((p) => {\n- if (p.number && p.size) {\n- return {\n- number: p.number - 1,\n- size: p.size,\n+ setUserPageRequest(() => ({\n+ number:\n+ patients.pageRequest && patients.pageRequest.number ? patients.pageRequest.number - 1 : 1,\n+ size: patients.pageRequest ? patients.pageRequest.size : undefined,\nnextPageInfo: undefined,\npreviousPageInfo: patients.pageRequest?.previousPageInfo,\ndirection: 'previous',\n+ }))\n}\n- }\n- return p\n- })\n- }\n+\nconst [searchText, setSearchText] = useState<string>('')\nconst debouncedSearchText = useDebounce(searchText, 500)\n+ const debouncedSearchTextRef = useRef<string>('')\n+\n+ useUpdateEffect(() => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+ dispatch(searchPatients(debouncedSearchTextRef.current, sortRequest, userPageRequest))\n+ }, [dispatch, userPageRequest])\nuseEffect(() => {\nconst sortRequest: SortRequest = {\nsorts: [{ field: 'index', direction: 'asc' }],\n}\n- dispatch(searchPatients(debouncedSearchText, sortRequest, userPageRequest))\n- }, [dispatch, debouncedSearchText, userPageRequest])\n+\n+ debouncedSearchTextRef.current = debouncedSearchText\n+ dispatch(searchPatients(debouncedSearchText, sortRequest, defaultPageRequest.current))\n+ }, [dispatch, debouncedSearchText])\nuseEffect(() => {\nsetButtonToolBar([\n@@ -140,7 +149,7 @@ const ViewPatients = () => {\n<PageComponent\nhasNext={patients.hasNext}\nhasPrevious={patients.hasPrevious}\n- pageNumber={userPageRequest.number}\n+ pageNumber={patients.pageRequest ? patients.pageRequest.number : 1}\nsetPreviousPageRequest={setPreviousPageRequest}\nsetNextPageRequest={setNextPageRequest}\n/>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): add paging for search patients
Add paging for search patients
feat #1969 |
288,350 | 06.05.2020 01:10:52 | -19,080 | c453f01ae9e865e90a703b175586bc498d5e7c82 | refactor(useupdateeffect): disable warning
feat | [
{
"change_type": "MODIFY",
"old_path": "src/hooks/useUpdateEffect.ts",
"new_path": "src/hooks/useUpdateEffect.ts",
"diff": "@@ -6,8 +6,9 @@ export default function (effect: Function, dependencies: any[]) {\nuseEffect(() => {\nif (isInitialMount.current) {\nisInitialMount.current = false\n- } else {\n- effect()\n+ return\n}\n- }, dependencies)\n+ // eslint-disable-next-line consistent-return\n+ return effect && effect()\n+ }, dependencies) //eslint-disable-line\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(useupdateeffect): disable warning
feat #1969 |
288,324 | 05.05.2020 17:22:13 | 14,400 | 32e00f63a75dedca485ebbdbdd9bf6f279512f08 | test(appointments): add missing tests for AppointmentsList | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/appointments/AppointmentsList.test.tsx",
"new_path": "src/__tests__/patients/appointments/AppointmentsList.test.tsx",
"diff": "import '../../../__mocks__/matchMediaMock'\nimport React from 'react'\n-import { mount } from 'enzyme'\n+import { mount, ReactWrapper } from 'enzyme'\nimport { createMemoryHistory } from 'history'\nimport configureMockStore from 'redux-mock-store'\nimport thunk from 'redux-thunk'\n@@ -10,20 +10,30 @@ import { Provider } from 'react-redux'\nimport AppointmentsList from 'patients/appointments/AppointmentsList'\nimport * as components from '@hospitalrun/components'\nimport { act } from 'react-dom/test-utils'\n-// import PatientRepository from 'clients/db/PatientRepository' # Lint warning: 'PatientRepository' is defined but never used\n+import * as appointmentsSlice from '../../../scheduling/appointments/appointments-slice'\nconst expectedPatient = {\nid: '123',\n} as Patient\n+\nconst expectedAppointments = [\n+ {\n+ id: '456',\n+ rev: '1',\n+ patientId: '1234',\n+ startDateTime: new Date(2020, 1, 1, 9, 0, 0, 0).toISOString(),\n+ endDateTime: new Date(2020, 1, 1, 9, 30, 0, 0).toISOString(),\n+ location: 'location',\n+ reason: 'Follow Up',\n+ },\n{\nid: '123',\nrev: '1',\npatientId: '1234',\n- startDateTime: new Date().toISOString(),\n- endDateTime: new Date().toISOString(),\n+ startDateTime: new Date(2020, 1, 1, 8, 0, 0, 0).toISOString(),\n+ endDateTime: new Date(2020, 1, 1, 8, 30, 0, 0).toISOString(),\nlocation: 'location',\n- reason: 'reason',\n+ reason: 'Checkup',\n},\n]\n@@ -41,12 +51,40 @@ const setup = (patient = expectedPatient, appointments = expectedAppointments) =\n</Provider>\n</Router>,\n)\n-\nreturn wrapper\n}\ndescribe('AppointmentsList', () => {\n- describe('add new appointment button', () => {\n+ it('should render a list of appointments', () => {\n+ const wrapper = setup()\n+ const listItems: ReactWrapper = wrapper.find(components.ListItem)\n+\n+ expect(listItems.length === 2).toBeTruthy()\n+ expect(listItems.at(0).text()).toEqual(\n+ new Date(expectedAppointments[0].startDateTime).toLocaleString(),\n+ )\n+ expect(listItems.at(1).text()).toEqual(\n+ new Date(expectedAppointments[1].startDateTime).toLocaleString(),\n+ )\n+ })\n+\n+ it('should search for \"ch\" in the list', () => {\n+ jest.spyOn(appointmentsSlice, 'fetchPatientAppointments')\n+ const searchText = 'ch'\n+ const wrapper = setup()\n+\n+ const searchInput: ReactWrapper = wrapper.find('input').at(0)\n+ searchInput.simulate('change', { target: { value: searchText } })\n+\n+ wrapper.find('button').at(1).simulate('click')\n+\n+ expect(appointmentsSlice.fetchPatientAppointments).toHaveBeenCalledWith(\n+ expectedPatient.id,\n+ searchText,\n+ )\n+ })\n+\n+ describe('New appointment button', () => {\nit('should render a new appointment button', () => {\nconst wrapper = setup()\n@@ -59,7 +97,7 @@ describe('AppointmentsList', () => {\nconst wrapper = setup()\nact(() => {\n- wrapper.find(components.Button).at(0).prop('onClick')()\n+ wrapper.find(components.Button).at(0).simulate('click')\n})\nwrapper.update()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test(appointments): add missing tests for AppointmentsList |
288,406 | 06.05.2020 16:42:55 | 18,000 | 2b5c789bb6247c3fe62fad8818d7fa1a16034a5b | feat(labs): ability to filter by status on labs screen | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -67,3 +67,5 @@ typings/\npackage-lock.json\n.DS_Store\nyarn.lock\n+.vscode/launch.json\n+.vscode/tasks.json\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/HospitalRun.test.tsx",
"new_path": "src/__tests__/HospitalRun.test.tsx",
"diff": "@@ -23,6 +23,7 @@ describe('HospitalRun', () => {\nconst store = mockStore({\ntitle: 'test',\nuser: { permissions: [Permissions.ViewLabs] },\n+ labs: { labs: [] },\nbreadcrumbs: { breadcrumbs: [] },\ncomponents: { sidebarCollapsed: false },\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/LabRepository.test.ts",
"new_path": "src/__tests__/clients/db/LabRepository.test.ts",
"diff": "+/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport shortid from 'shortid'\n-import LabRepository from '../../../clients/db/LabRepository'\n+import { labs } from 'config/pouchdb'\n+import LabRepository from 'clients/db/LabRepository'\n+import SortRequest from 'clients/db/SortRequest'\nimport Lab from '../../../model/Lab'\n+interface SearchContainer {\n+ text: string\n+ status: 'requested' | 'completed' | 'canceled' | 'all'\n+ defaultSortRequest: SortRequest\n+}\n+\n+const removeAllDocs = async () => {\n+ const allDocs = await labs.allDocs({ include_docs: true })\n+ await Promise.all(\n+ allDocs.rows.map(async (row) => {\n+ if (row.doc) {\n+ await labs.remove(row.doc)\n+ }\n+ }),\n+ )\n+}\n+\n+const defaultSortRequest: SortRequest = {\n+ sorts: [\n+ {\n+ field: 'requestedOn',\n+ direction: 'desc',\n+ },\n+ ],\n+}\n+\n+const searchObject: SearchContainer = {\n+ text: '',\n+ status: 'all',\n+ defaultSortRequest,\n+}\n+\ndescribe('lab repository', () => {\n+ describe('find', () => {\n+ afterEach(async () => {\n+ await removeAllDocs()\n+ })\n+\n+ it('should return a lab with the correct data', async () => {\n+ // first lab to store is to have mock data to make sure we are getting the expected\n+ await labs.put({ _id: 'id1111' })\n+ const expectedLab = await labs.put({ _id: 'id2222' })\n+\n+ const actualLab = await LabRepository.find('id2222')\n+\n+ expect(actualLab).toBeDefined()\n+ expect(actualLab.id).toEqual(expectedLab.id)\n+ })\n+\nit('should generate a lab code', async () => {\nconst newLab = await LabRepository.save({\npatientId: '123',\n@@ -12,3 +63,108 @@ describe('lab repository', () => {\nexpect(shortid.isValid(newLab.code)).toBeTruthy()\n})\n})\n+\n+ describe('search', () => {\n+ it('should return all records that lab type matches search text', async () => {\n+ const expectedLabType = 'more tests'\n+ await labs.put({ _id: 'someId1', type: expectedLabType, status: 'requested' })\n+ await labs.put({ _id: 'someId2', type: 'P00002', status: 'requested' })\n+\n+ searchObject.text = expectedLabType\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].type).toEqual(expectedLabType)\n+ })\n+\n+ it('should return all records that contains search text in the type', async () => {\n+ const expectedLabType = 'Labs Tests'\n+ await labs.put({ _id: 'someId3', type: expectedLabType })\n+ await labs.put({ _id: 'someId4', type: 'Sencond Lab labs tests' })\n+ await labs.put({ _id: 'someId5', type: 'not found' })\n+\n+ searchObject.text = expectedLabType\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(2)\n+ expect(result[0].id).toEqual('someId3')\n+ expect(result[1].id).toEqual('someId4')\n+ })\n+\n+ it('should return all records that contains search text in code', async () => {\n+ const expectedLabCode = 'L-CODE-sam445Pl'\n+ await labs.put({ _id: 'theID13', type: 'Expected', code: 'L-CODE-sam445Pl' })\n+ await labs.put({ _id: 'theID14', type: 'Sencond Lab labs tests', code: 'L-4XXX' })\n+ await labs.put({ _id: 'theID15', type: 'not found', code: 'L-775YYxc' })\n+\n+ searchObject.text = expectedLabCode\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].id).toEqual('theID13')\n+ })\n+\n+ it('should match search criteria with case insesitive match', async () => {\n+ await labs.put({ _id: 'id3333', type: 'lab tests' })\n+ await labs.put({ _id: 'id4444', type: 'not found' })\n+\n+ searchObject.text = 'LAB TESTS'\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].id).toEqual('id3333')\n+ })\n+\n+ it('should return all records that matches an specific status', async () => {\n+ await labs.put({ _id: 'id5555', type: 'lab tests', status: 'requested' })\n+ await labs.put({ _id: 'id6666', type: 'lab tests', status: 'requested' })\n+ await labs.put({ _id: 'id7777', type: 'lab tests', status: 'completed' })\n+ await labs.put({ _id: 'id8888', type: 'not found', status: 'completed' })\n+\n+ searchObject.text = ''\n+ searchObject.status = 'completed'\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(2)\n+ expect(result[0].id).toEqual('id7777')\n+ expect(result[1].id).toEqual('id8888')\n+ })\n+\n+ it('should return records with search text and specific status', async () => {\n+ await labs.put({ _id: 'theID09', type: 'the specific lab', status: 'requested' })\n+ await labs.put({ _id: 'theID10', type: 'not found', status: 'cancelled' })\n+\n+ searchObject.text = 'the specific lab'\n+ searchObject.status = 'requested'\n+\n+ const result = await LabRepository.search(searchObject)\n+\n+ expect(result).toHaveLength(1)\n+ expect(result[0].id).toEqual('theID09')\n+ })\n+ })\n+\n+ describe('findAll', () => {\n+ afterEach(async () => {\n+ await removeAllDocs()\n+ })\n+ it('should find all labs in the database sorted by their requestedOn', async () => {\n+ const expectedLab1 = await labs.put({ _id: 'theID11' })\n+\n+ setTimeout(async () => {\n+ const expectedLab2 = await labs.put({ _id: 'theID12' })\n+\n+ const result = await LabRepository.findAll()\n+\n+ expect(result).toHaveLength(2)\n+ expect(result[0].id).toEqual(expectedLab1.id)\n+ expect(result[1].id).toEqual(expectedLab2.id)\n+ }, 1000)\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/ViewLabs.test.tsx",
"new_path": "src/__tests__/labs/ViewLabs.test.tsx",
"diff": "@@ -4,16 +4,17 @@ import { Provider } from 'react-redux'\nimport { Router } from 'react-router'\nimport ViewLabs from 'labs/ViewLabs'\nimport { mount, ReactWrapper } from 'enzyme'\n+import { TextInput, Select } from '@hospitalrun/components'\nimport configureMockStore from 'redux-mock-store'\nimport thunk from 'redux-thunk'\nimport { createMemoryHistory } from 'history'\nimport Permissions from 'model/Permissions'\nimport { act } from '@testing-library/react'\nimport LabRepository from 'clients/db/LabRepository'\n+import * as labsSlice from 'labs/labs-slice'\nimport Lab from 'model/Lab'\nimport format from 'date-fns/format'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\n-import SortRequest from 'clients/db/SortRequest'\nimport * as titleUtil from '../../page-header/useTitle'\nconst mockStore = configureMockStore([thunk])\n@@ -25,6 +26,7 @@ describe('View Labs', () => {\nconst store = mockStore({\ntitle: '',\nuser: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ labs: { labs: [] },\n})\ntitleSpy = jest.spyOn(titleUtil, 'default')\njest.spyOn(LabRepository, 'findAll').mockResolvedValue([])\n@@ -49,6 +51,7 @@ describe('View Labs', () => {\nconst store = mockStore({\ntitle: '',\nuser: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ labs: { labs: [] },\n})\nconst setButtonToolBarSpy = jest.fn()\njest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\n@@ -71,6 +74,7 @@ describe('View Labs', () => {\nconst store = mockStore({\ntitle: '',\nuser: { permissions: [Permissions.ViewLabs] },\n+ labs: { labs: [] },\n})\nconst setButtonToolBarSpy = jest.fn()\njest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\n@@ -106,6 +110,7 @@ describe('View Labs', () => {\nconst store = mockStore({\ntitle: '',\nuser: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ labs: { labs: [expectedLab] },\n})\nhistory = createMemoryHistory()\n@@ -167,36 +172,113 @@ describe('View Labs', () => {\n})\n})\n- describe('sort Request', () => {\n- let findAllSpy: any\n+ describe('dropdown', () => {\n+ it('should search for labs when dropdown changes', () => {\n+ const searchLabsSpy = jest.spyOn(labsSlice, 'searchLabs')\n+ let wrapper: ReactWrapper\n+ let history: any\n+ const expectedLab = {\n+ id: '1234',\n+ type: 'lab type',\n+ patientId: 'patientId',\n+ status: 'requested',\n+ requestedOn: '2020-03-30T04:43:20.102Z',\n+ } as Lab\n+\nbeforeEach(async () => {\nconst store = mockStore({\ntitle: '',\nuser: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ labs: { labs: [expectedLab] },\n})\n- findAllSpy = jest.spyOn(LabRepository, 'findAll')\n- findAllSpy.mockResolvedValue([])\n+ history = createMemoryHistory()\n+\nawait act(async () => {\n- await mount(\n+ wrapper = await mount(\n<Provider store={store}>\n- <Router history={createMemoryHistory()}>\n+ <Router history={history}>\n<ViewLabs />\n</Router>\n</Provider>,\n)\n})\n+\n+ searchLabsSpy.mockClear()\n+\n+ act(() => {\n+ const onChange = wrapper.find(Select).prop('onChange') as any\n+ onChange({\n+ target: {\n+ value: 'requested',\n+ },\n+ preventDefault: jest.fn(),\n+ })\n+ })\n+\n+ wrapper.update()\n+ expect(searchLabsSpy).toHaveBeenCalledTimes(1)\n+ })\n+ })\n})\n- it('should have called findAll with sort request', () => {\n- const sortRequest: SortRequest = {\n- sorts: [\n- {\n- field: 'requestedOn',\n- direction: 'desc',\n+ describe('search functionality', () => {\n+ beforeEach(() => jest.useFakeTimers())\n+\n+ afterEach(() => jest.useRealTimers())\n+\n+ it('should search for labs after the search text has not changed for 500 milliseconds', () => {\n+ const searchLabsSpy = jest.spyOn(labsSlice, 'searchLabs')\n+ let wrapper: ReactWrapper\n+ let history: any\n+ const expectedLab = {\n+ id: '1234',\n+ type: 'lab type',\n+ patientId: 'patientId',\n+ status: 'requested',\n+ requestedOn: '2020-03-30T04:43:20.102Z',\n+ } as Lab\n+\n+ beforeEach(async () => {\n+ const store = mockStore({\n+ title: '',\n+ user: { permissions: [Permissions.ViewLabs, Permissions.RequestLab] },\n+ labs: { labs: [expectedLab] },\n+ })\n+ history = createMemoryHistory()\n+\n+ jest.spyOn(LabRepository, 'findAll').mockResolvedValue([expectedLab])\n+ await act(async () => {\n+ wrapper = await mount(\n+ <Provider store={store}>\n+ <Router history={history}>\n+ <ViewLabs />\n+ </Router>\n+ </Provider>,\n+ )\n+ })\n+\n+ searchLabsSpy.mockClear()\n+ const expectedSearchText = 'search text'\n+\n+ act(() => {\n+ const onClick = wrapper.find(TextInput).prop('onChange') as any\n+ onClick({\n+ target: {\n+ value: expectedSearchText,\n},\n- ],\n- }\n- expect(findAllSpy).toHaveBeenCalledWith(sortRequest)\n+ preventDefault: jest.fn(),\n+ })\n+ })\n+\n+ act(() => {\n+ jest.advanceTimersByTime(500)\n+ })\n+\n+ wrapper.update()\n+\n+ expect(searchLabsSpy).toHaveBeenCalledTimes(1)\n+ expect(searchLabsSpy).toHaveBeenLastCalledWith(expectedSearchText)\n+ })\n})\n})\n})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/labs/labs.slice.test.ts",
"diff": "+import { AnyAction } from 'redux'\n+import { mocked } from 'ts-jest/utils'\n+import SortRequest from 'clients/db/SortRequest'\n+import labs, { fetchLabsStart, fetchLabsSuccess, searchLabs } from '../../labs/labs-slice'\n+import Lab from '../../model/Lab'\n+import LabRepository from '../../clients/db/LabRepository'\n+\n+interface SearchContainer {\n+ text: string\n+ status: 'requested' | 'completed' | 'canceled' | 'all'\n+ defaultSortRequest: SortRequest\n+}\n+\n+const defaultSortRequest: SortRequest = {\n+ sorts: [\n+ {\n+ field: 'requestedOn',\n+ direction: 'desc',\n+ },\n+ ],\n+}\n+\n+const expectedSearchObject: SearchContainer = {\n+ text: 'search string',\n+ status: 'all',\n+ defaultSortRequest,\n+}\n+\n+describe('labs slice', () => {\n+ beforeEach(() => {\n+ jest.resetAllMocks()\n+ })\n+\n+ describe('labs reducer', () => {\n+ it('should create the proper intial state with empty labs array', () => {\n+ const labsStore = labs(undefined, {} as AnyAction)\n+ expect(labsStore.isLoading).toBeFalsy()\n+ expect(labsStore.labs).toHaveLength(0)\n+ expect(labsStore.statusFilter).toEqual('all')\n+ })\n+\n+ it('it should handle the FETCH_LABS_SUCCESS action', () => {\n+ const expectedLabs = [{ id: '1234' }]\n+ const labsStore = labs(undefined, {\n+ type: fetchLabsSuccess.type,\n+ payload: expectedLabs,\n+ })\n+\n+ expect(labsStore.isLoading).toBeFalsy()\n+ expect(labsStore.labs).toEqual(expectedLabs)\n+ })\n+ })\n+\n+ describe('searchLabs', () => {\n+ it('should dispatch the FETCH_LABS_START action', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+\n+ await searchLabs('search string', 'all')(dispatch, getState, null)\n+\n+ expect(dispatch).toHaveBeenCalledWith({ type: fetchLabsStart.type })\n+ })\n+\n+ it('should call the LabRepository search method with the correct search criteria', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+ jest.spyOn(LabRepository, 'search')\n+\n+ await searchLabs(expectedSearchObject.text, expectedSearchObject.status)(\n+ dispatch,\n+ getState,\n+ null,\n+ )\n+\n+ expect(LabRepository.search).toHaveBeenCalledWith(expectedSearchObject)\n+ })\n+\n+ it('should call the LabRepository findAll method if there is no string text and status is set to all', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+ jest.spyOn(LabRepository, 'findAll')\n+\n+ await searchLabs('', expectedSearchObject.status)(dispatch, getState, null)\n+\n+ expect(LabRepository.findAll).toHaveBeenCalledTimes(1)\n+ })\n+\n+ it('should dispatch the FETCH_LABS_SUCCESS action', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+\n+ const expectedLabs = [\n+ {\n+ type: 'text',\n+ },\n+ ] as Lab[]\n+\n+ const mockedLabRepository = mocked(LabRepository, true)\n+ mockedLabRepository.search.mockResolvedValue(expectedLabs)\n+\n+ await searchLabs(expectedSearchObject.text, expectedSearchObject.status)(\n+ dispatch,\n+ getState,\n+ null,\n+ )\n+\n+ expect(dispatch).toHaveBeenLastCalledWith({\n+ type: fetchLabsSuccess.type,\n+ payload: expectedLabs,\n+ })\n+ })\n+ })\n+\n+ describe('sort Request', () => {\n+ it('should have called findAll with sort request in searchLabs method', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+ jest.spyOn(LabRepository, 'findAll')\n+\n+ await searchLabs('', expectedSearchObject.status)(dispatch, getState, null)\n+\n+ expect(LabRepository.findAll).toHaveBeenCalledWith(expectedSearchObject.defaultSortRequest)\n+ })\n+\n+ it('should include sorts in the search criteria', async () => {\n+ const dispatch = jest.fn()\n+ const getState = jest.fn()\n+ jest.spyOn(LabRepository, 'search')\n+\n+ await searchLabs(expectedSearchObject.text, expectedSearchObject.status)(\n+ dispatch,\n+ getState,\n+ null,\n+ )\n+\n+ expect(LabRepository.search).toHaveBeenCalledWith(expectedSearchObject)\n+ })\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/related-persons/RelatedPersons.test.tsx",
"new_path": "src/__tests__/patients/related-persons/RelatedPersons.test.tsx",
"diff": "@@ -14,7 +14,6 @@ import thunk from 'redux-thunk'\nimport { Provider } from 'react-redux'\nimport Permissions from 'model/Permissions'\nimport RelatedPerson from 'model/RelatedPerson'\n-import { Button } from '@hospitalrun/components'\nimport * as patientSlice from '../../../patients/patient-slice'\nconst mockStore = configureMockStore([thunk])\n@@ -137,7 +136,7 @@ describe('Related Persons Tab', () => {\nconst tableHeaders = wrapper.find('th')\nconst tableBody = wrapper.find('tbody')\nconst tableData = wrapper.find('td')\n- const deleteButton = tableData.at(3).find(Button)\n+ const deleteButton = tableData.at(3).find(components.Button)\nexpect(table).toHaveLength(1)\nexpect(tableHeader).toHaveLength(1)\nexpect(tableBody).toHaveLength(1)\n@@ -160,7 +159,7 @@ describe('Related Persons Tab', () => {\nconst table = wrapper.find('table')\nconst tableBody = table.find('tbody')\nconst tableData = tableBody.find('td')\n- const deleteButton = tableData.at(3).find(Button)\n+ const deleteButton = tableData.at(3).find(components.Button)\nawait act(async () => {\nconst onClick = deleteButton.prop('onClick')\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/LabRepository.ts",
"new_path": "src/clients/db/LabRepository.ts",
"diff": "@@ -2,12 +2,39 @@ import Lab from 'model/Lab'\nimport generateCode from '../../util/generateCode'\nimport Repository from './Repository'\nimport { labs } from '../../config/pouchdb'\n+import SortRequest from './SortRequest'\n+interface SearchContainer {\n+ text: string\n+ status: 'requested' | 'completed' | 'canceled' | 'all'\n+ defaultSortRequest: SortRequest\n+}\nexport class LabRepository extends Repository<Lab> {\nconstructor() {\nsuper(labs)\n- labs.createIndex({\n- index: { fields: ['requestedOn'] },\n+ }\n+\n+ async search(container: SearchContainer): Promise<Lab[]> {\n+ const searchValue = { $regex: RegExp(container.text, 'i') }\n+ const selector = {\n+ $and: [\n+ {\n+ $or: [\n+ {\n+ type: searchValue,\n+ },\n+ {\n+ code: searchValue,\n+ },\n+ ],\n+ },\n+ ...(container.status !== 'all' ? [{ status: container.status }] : [undefined]),\n+ ].filter((x) => x !== undefined),\n+ sorts: container.defaultSortRequest,\n+ }\n+\n+ return super.search({\n+ selector,\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport { v4 as uuidv4 } from 'uuid'\nimport AbstractDBModel from '../../model/AbstractDBModel'\n-import { Unsorted } from './SortRequest'\n+import SortRequest, { Unsorted } from './SortRequest'\nfunction mapDocument(document: any): any {\nconst { _id, _rev, ...values } = document\n@@ -33,6 +33,23 @@ export default class Repository<T extends AbstractDBModel> {\nselector[s.field] = { $gt: null }\n})\n+ // Adds an index to each of the fields coming from the sorting object\n+ // allowing the algorithm to sort by any given SortRequest, by avoiding the default index error (lack of index)\n+\n+ await Promise.all(\n+ sort.sorts.map(\n+ async (s): Promise<SortRequest> => {\n+ await this.db.createIndex({\n+ index: {\n+ fields: [s.field],\n+ },\n+ })\n+\n+ return sort\n+ },\n+ ),\n+ )\n+\nconst result = await this.db.find({\nselector,\nsort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Sidebar.tsx",
"new_path": "src/components/Sidebar.tsx",
"diff": "@@ -51,7 +51,7 @@ const Sidebar = () => {\nsetExpandedItem(item.toString())\n}\n- const listSubItemStyleNew: CSSProperties = {\n+ const listSubItemStyle: CSSProperties = {\ncursor: 'pointer',\nfontSize: 'small',\nborderBottomWidth: 0,\n@@ -61,7 +61,7 @@ const Sidebar = () => {\nbackgroundColor: 'rgba(245,245,245,1)',\n}\n- const listSubItemStyle: CSSProperties = {\n+ const listSubItemStyleNew: CSSProperties = {\ncursor: 'pointer',\nfontSize: 'small',\nborderBottomWidth: 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/ViewLabs.tsx",
"new_path": "src/labs/ViewLabs.tsx",
"diff": "import React, { useState, useEffect, useCallback } from 'react'\n+import { useSelector, useDispatch } from 'react-redux'\nimport useTitle from 'page-header/useTitle'\nimport { useTranslation } from 'react-i18next'\nimport format from 'date-fns/format'\nimport { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\n-import { Button } from '@hospitalrun/components'\n+import { Spinner, Button } from '@hospitalrun/components'\nimport { useHistory } from 'react-router'\n-import LabRepository from 'clients/db/LabRepository'\n-import SortRequest from 'clients/db/SortRequest'\nimport Lab from 'model/Lab'\n-import { useSelector } from 'react-redux'\nimport Permissions from 'model/Permissions'\n+import SelectWithLabelFormGroup from 'components/input/SelectWithLableFormGroup'\n+import TextInputWithLabelFormGroup from 'components/input/TextInputWithLabelFormGroup'\nimport { RootState } from '../store'\n+import { searchLabs } from './labs-slice'\n+import useDebounce from '../hooks/debounce'\n+\n+type filter = 'requested' | 'completed' | 'canceled' | 'all'\nconst ViewLabs = () => {\nconst { t } = useTranslation()\n@@ -19,7 +23,11 @@ const ViewLabs = () => {\nuseTitle(t('labs.label'))\nconst { permissions } = useSelector((state: RootState) => state.user)\n- const [labs, setLabs] = useState<Lab[]>([])\n+ const dispatch = useDispatch()\n+ const { labs, isLoading } = useSelector((state: RootState) => state.labs)\n+ const [searchFilter, setSearchFilter] = useState<filter>('all')\n+ const [searchText, setSearchText] = useState<string>('')\n+ const debouncedSearchText = useDebounce(searchText, 500)\nconst getButtons = useCallback(() => {\nconst buttons: React.ReactNode[] = []\n@@ -41,34 +49,85 @@ const ViewLabs = () => {\nreturn buttons\n}, [permissions, history, t])\n+ const setFilter = (filter: string) =>\n+ filter === 'requested'\n+ ? 'requested'\n+ : filter === 'completed'\n+ ? 'completed'\n+ : filter === 'canceled'\n+ ? 'canceled'\n+ : 'all'\n+\nuseEffect(() => {\n- const fetch = async () => {\n- const sortRequest: SortRequest = {\n- sorts: [\n- {\n- field: 'requestedOn',\n- direction: 'desc',\n- },\n- ],\n- }\n- const fetchedLabs = await LabRepository.findAll(sortRequest)\n- setLabs(fetchedLabs)\n- }\n+ dispatch(searchLabs(debouncedSearchText, searchFilter))\n+ }, [dispatch, debouncedSearchText, searchFilter])\n+ useEffect(() => {\nsetButtons(getButtons())\n- fetch()\n-\nreturn () => {\nsetButtons([])\n}\n- }, [getButtons, setButtons])\n+ }, [dispatch, getButtons, setButtons])\n+\n+ const loadingIndicator = <Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />\nconst onTableRowClick = (lab: Lab) => {\nhistory.push(`/labs/${lab.id}`)\n}\n+ const onSelectChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n+ setSearchFilter(setFilter(event.target.value))\n+ }\n+\n+ const onSearchBoxChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n+ setSearchText(event.target.value)\n+ }\n+\n+ const listBody = (\n+ <tbody>\n+ {labs.map((lab) => (\n+ <tr onClick={() => onTableRowClick(lab)} key={lab.id}>\n+ <td>{lab.code}</td>\n+ <td>{lab.type}</td>\n+ <td>{format(new Date(lab.requestedOn), 'yyyy-MM-dd hh:mm a')}</td>\n+ <td>{lab.status}</td>\n+ </tr>\n+ ))}\n+ </tbody>\n+ )\n+\nreturn (\n<>\n+ <div className=\"row\">\n+ <div className=\"col-md-3 col-lg-2\">\n+ <SelectWithLabelFormGroup\n+ name=\"type\"\n+ value={searchFilter}\n+ label={t('labs.filterTitle')}\n+ isEditable\n+ options={[\n+ { label: t('labs.status.requested'), value: 'requested' },\n+ { label: t('labs.status.completed'), value: 'completed' },\n+ { label: t('labs.status.canceled'), value: 'canceled' },\n+ { label: t('labs.filter.all'), value: 'all' },\n+ ]}\n+ onChange={(event: React.ChangeEvent<HTMLSelectElement>) => {\n+ onSelectChange(event)\n+ }}\n+ />\n+ </div>\n+ <div className=\"col\">\n+ <TextInputWithLabelFormGroup\n+ name=\"searchbox\"\n+ label=\"Search Labs\"\n+ placeholder=\"Search labs by type\"\n+ value={searchText}\n+ isEditable\n+ onChange={onSearchBoxChange}\n+ />\n+ </div>\n+ </div>\n+ <div className=\"row\">\n<table className=\"table table-hover\">\n<thead className=\"thead-light\">\n<tr>\n@@ -78,17 +137,9 @@ const ViewLabs = () => {\n<th>{t('labs.lab.status')}</th>\n</tr>\n</thead>\n- <tbody>\n- {labs.map((lab) => (\n- <tr onClick={() => onTableRowClick(lab)} key={lab.id}>\n- <td>{lab.code}</td>\n- <td>{lab.type}</td>\n- <td>{format(new Date(lab.requestedOn), 'yyyy-MM-dd hh:mm a')}</td>\n- <td>{lab.status}</td>\n- </tr>\n- ))}\n- </tbody>\n+ {isLoading ? loadingIndicator : listBody}\n</table>\n+ </div>\n</>\n)\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/labs/labs-slice.ts",
"diff": "+import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import Lab from '../model/Lab'\n+import LabRepository from '../clients/db/LabRepository'\n+import SortRequest from '../clients/db/SortRequest'\n+import { AppThunk } from '../store'\n+\n+interface LabsState {\n+ isLoading: boolean\n+ labs: Lab[]\n+ statusFilter: status\n+}\n+\n+type status = 'requested' | 'completed' | 'canceled' | 'all'\n+\n+const defaultSortRequest: SortRequest = {\n+ sorts: [\n+ {\n+ field: 'requestedOn',\n+ direction: 'desc',\n+ },\n+ ],\n+}\n+\n+const initialState: LabsState = {\n+ isLoading: false,\n+ labs: [],\n+ statusFilter: 'all',\n+}\n+\n+const startLoading = (state: LabsState) => {\n+ state.isLoading = true\n+}\n+\n+const labsSlice = createSlice({\n+ name: 'labs',\n+ initialState,\n+ reducers: {\n+ fetchLabsStart: startLoading,\n+ fetchLabsSuccess(state, { payload }: PayloadAction<Lab[]>) {\n+ state.isLoading = false\n+ state.labs = payload\n+ },\n+ },\n+})\n+export const { fetchLabsStart, fetchLabsSuccess } = labsSlice.actions\n+\n+export const searchLabs = (text: string, status: status): AppThunk => async (dispatch) => {\n+ dispatch(fetchLabsStart())\n+\n+ let labs\n+\n+ if (text.trim() === '' && status === initialState.statusFilter) {\n+ labs = await LabRepository.findAll(defaultSortRequest)\n+ } else {\n+ labs = await LabRepository.search({\n+ text,\n+ status,\n+ defaultSortRequest,\n+ })\n+ }\n+\n+ dispatch(fetchLabsSuccess(labs))\n+}\n+\n+export default labsSlice.reducer\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/labs/index.ts",
"new_path": "src/locales/enUs/translations/labs/index.ts",
"diff": "export default {\nlabs: {\nlabel: 'Labs',\n+ filterTitle: 'Filter by status',\n+ search: 'Search labs',\n+ status: {\n+ requested: 'Requested',\n+ completed: 'Completed',\n+ canceled: 'Canceled',\n+ },\n+ filter: {\n+ all: 'All statuses',\n+ },\nrequests: {\nlabel: 'Lab Requests',\nnew: 'New Lab Request',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/store/index.ts",
"new_path": "src/store/index.ts",
"diff": "@@ -7,6 +7,7 @@ import appointments from '../scheduling/appointments/appointments-slice'\nimport title from '../page-header/title-slice'\nimport user from '../user/user-slice'\nimport lab from '../labs/lab-slice'\n+import labs from '../labs/labs-slice'\nimport breadcrumbs from '../breadcrumbs/breadcrumbs-slice'\nimport components from '../components/component-slice'\n@@ -20,6 +21,7 @@ const reducer = combineReducers({\nbreadcrumbs,\ncomponents,\nlab,\n+ labs,\n})\nconst store = configureStore({\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(labs): ability to filter by status on labs screen (#2033) |
288,350 | 10.05.2020 23:24:20 | -19,080 | d7defb5e30c91a6dae43b3c8f0945ea5e7a2104c | test(patientrepository.test.ts): add test cases for paging
Add test suit for searchPaged and findAllPaged for PatientRepository
feat-#1969 | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"new_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"diff": "@@ -3,6 +3,8 @@ import PatientRepository from 'clients/db/PatientRepository'\nimport Patient from 'model/Patient'\nimport shortid from 'shortid'\nimport { getTime, isAfter } from 'date-fns'\n+import SortRequest from 'clients/db/SortRequest'\n+import PageRequest, { UnpagedRequest } from 'clients/db/PageRequest'\nconst uuidV4Regex = /^[A-F\\d]{8}-[A-F\\d]{4}-4[A-F\\d]{3}-[89AB][A-F\\d]{3}-[A-F\\d]{12}$/i\n@@ -223,4 +225,91 @@ describe('patient repository', () => {\nexpect(allDocs.total_rows).toEqual(0)\n})\n})\n+\n+ describe('findAllPaged', () => {\n+ const patientsData = [\n+ { _id: 'a', fullName: 'a', code: 'P-a', index: 'aP-a' },\n+ { _id: 'b', fullName: 'b', code: 'P-b', index: 'bP-b' },\n+ { _id: 'c', fullName: 'c', code: 'P-c', index: 'cP-c' },\n+ ]\n+\n+ afterEach(async () => {\n+ await removeAllDocs()\n+ })\n+\n+ beforeEach(async () => {\n+ await PatientRepository.createIndex()\n+ patientsData.forEach((patientData) => patients.put(patientData))\n+ })\n+\n+ it('should find all patients in the database', async () => {\n+ const result = await PatientRepository.findAllPaged()\n+\n+ expect(result.hasNext).toEqual(false)\n+ expect(result.hasPrevious).toEqual(false)\n+ expect(result.content).toHaveLength(patientsData.length)\n+ })\n+\n+ it('should find all patients in the database with sort request and page request', async () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+ const pageRequest: PageRequest = {\n+ number: 1,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: undefined,\n+ previousPageInfo: undefined,\n+ }\n+\n+ const result = await PatientRepository.findAllPaged(sortRequest, pageRequest)\n+\n+ expect(result.content).toHaveLength(1)\n+ expect(result.hasNext).toEqual(true)\n+ expect(result.hasPrevious).toEqual(false)\n+ expect(result.content.length).toEqual(1)\n+ expect(result.pageRequest?.nextPageInfo).toEqual({ index: 'bP-b' })\n+ })\n+ })\n+\n+ describe('searchPaged', () => {\n+ const patientsData = [\n+ { _id: 'a', fullName: 'a', code: 'P-a', index: 'aP-a' },\n+ { _id: 'b', fullName: 'b', code: 'P-b', index: 'bP-b' },\n+ { _id: 'c', fullName: 'c', code: 'P-c', index: 'cP-c' },\n+ ]\n+\n+ afterEach(async () => {\n+ await removeAllDocs()\n+ })\n+\n+ beforeEach(async () => {\n+ await PatientRepository.createIndex()\n+ patientsData.forEach((patientData) => patients.put(patientData))\n+ })\n+\n+ it('should search patient in the database', async () => {\n+ const result = await PatientRepository.searchPaged('a')\n+\n+ expect(result.content).toHaveLength(1)\n+ expect(result.hasNext).toEqual(false)\n+ expect(result.hasPrevious).toEqual(false)\n+\n+ expect(result.content.length).toEqual(1)\n+ })\n+\n+ it('should search patient in the database with sort request', async () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+\n+ const result = await PatientRepository.searchPaged('a', UnpagedRequest, sortRequest)\n+\n+ expect(result.content).toHaveLength(1)\n+ expect(result.hasNext).toEqual(false)\n+ expect(result.hasPrevious).toEqual(false)\n+\n+ expect(result.content.length).toEqual(1)\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "@@ -93,6 +93,12 @@ export class PatientRepository extends Repository<Patient> {\nentity.index = (entity.fullName ? entity.fullName : '') + patientCode\nreturn super.save(entity)\n}\n+\n+ async createIndex() {\n+ return this.db.createIndex({\n+ index: { fields: ['index'] },\n+ })\n+ }\n}\nexport default new PatientRepository()\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test(patientrepository.test.ts): add test cases for paging
Add test suit for searchPaged and findAllPaged for PatientRepository
feat-#1969 |
288,333 | 11.05.2020 10:56:16 | 25,200 | 52d30a3ec1cc27c2ee2ec8827dce331180203461 | fix(datetime): datetime pickers are bigger now | [
{
"change_type": "MODIFY",
"old_path": "src/index.css",
"new_path": "src/index.css",
"diff": "@@ -97,3 +97,7 @@ code {\n.button-toolbar > button {\nmargin-left: .5rem;\n}\n+\n+.react-datepicker-wrapper {\n+ flex-grow: 1;\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/GeneralInformation.tsx",
"new_path": "src/patients/GeneralInformation.tsx",
"diff": "@@ -140,7 +140,7 @@ const GeneralInformation = (props: Props) => {\n</div>\n</div>\n<div className=\"row\">\n- <div className=\"col-md-4\">\n+ <div className=\"col\">\n{patient.isApproximateDateOfBirth ? (\n<TextInputWithLabelFormGroup\nlabel={t('patient.approximateAge')}\n@@ -169,7 +169,7 @@ const GeneralInformation = (props: Props) => {\n/>\n)}\n</div>\n- <div className=\"col-md-2\">\n+ <div className=\"col\">\n<div className=\"form-group\">\n<Checkbox\nlabel={t('patient.unknownDateOfBirth')}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(datetime): datetime pickers are bigger now (#2056) |
288,307 | 11.05.2020 19:08:09 | -3,600 | b159d7ada730976583d416b0f44d38a186abe4cd | feat(datepicker): add year selector dropdown | [
{
"change_type": "MODIFY",
"old_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"new_path": "src/components/input/DatePickerWithLabelFormGroup.tsx",
"diff": "@@ -40,6 +40,7 @@ const DatePickerWithLabelFormGroup = (props: Props) => {\ndisabled={!isEditable}\nfeedback={feedback}\nisInvalid={isInvalid}\n+ showYearDropdown\nonChange={(inputDate) => {\nif (onChange) {\nonChange(inputDate)\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(datepicker): add year selector dropdown (#2060) |
288,350 | 12.05.2020 19:36:47 | -19,080 | 71ac1ca96aeeb2b5ee2807179b5afe0899395ab5 | refactor(patientrepository): changes for findAllPaged
'direction' field is now optional. 'nextPageInfo' and 'previousPageInfo' in Page can be undefined.
Add tests.
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"new_path": "src/__tests__/clients/db/PatientRepository.test.ts",
"diff": "@@ -267,9 +267,115 @@ describe('patient repository', () => {\nexpect(result.content).toHaveLength(1)\nexpect(result.hasNext).toEqual(true)\nexpect(result.hasPrevious).toEqual(false)\n- expect(result.content.length).toEqual(1)\nexpect(result.pageRequest?.nextPageInfo).toEqual({ index: 'bP-b' })\n})\n+\n+ it('page request less than number of records', async () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+\n+ const pageRequest: PageRequest = {\n+ number: 1,\n+ size: 4,\n+ direction: 'next',\n+ nextPageInfo: undefined,\n+ previousPageInfo: undefined,\n+ }\n+\n+ const result = await PatientRepository.findAllPaged(sortRequest, pageRequest)\n+\n+ expect(result.content).toHaveLength(patientsData.length)\n+ expect(result.hasNext).toEqual(false)\n+ expect(result.hasPrevious).toEqual(false)\n+ expect(result.pageRequest?.nextPageInfo).toBe(undefined)\n+ expect(result.pageRequest?.previousPageInfo).toBe(undefined)\n+ })\n+\n+ it('go till last page', async () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+ const pageRequest1: PageRequest = {\n+ number: 1,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: undefined,\n+ previousPageInfo: undefined,\n+ }\n+\n+ const result1 = await PatientRepository.findAllPaged(sortRequest, pageRequest1)\n+\n+ const pageRequest2: PageRequest = {\n+ number: 2,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: result1.pageRequest?.nextPageInfo,\n+ previousPageInfo: undefined,\n+ }\n+ const result2 = await PatientRepository.findAllPaged(sortRequest, pageRequest2)\n+\n+ expect(result2.hasPrevious).toBe(true)\n+ expect(result2.hasNext).toBe(true)\n+\n+ const pageRequest3: PageRequest = {\n+ number: 2,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: result2.pageRequest?.nextPageInfo,\n+ previousPageInfo: undefined,\n+ }\n+ const result3 = await PatientRepository.findAllPaged(sortRequest, pageRequest3)\n+\n+ expect(result3.content).toHaveLength(1)\n+ expect(result3.hasNext).toEqual(false)\n+ expect(result3.hasPrevious).toEqual(true)\n+ expect(result3.content.length).toEqual(1)\n+ expect(result3.pageRequest?.previousPageInfo).toEqual({ index: 'cP-c' })\n+ })\n+\n+ it('go to previous page', async () => {\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+ const pageRequest1: PageRequest = {\n+ number: 1,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: undefined,\n+ previousPageInfo: undefined,\n+ }\n+\n+ const result1 = await PatientRepository.findAllPaged(sortRequest, pageRequest1)\n+\n+ const pageRequest2: PageRequest = {\n+ number: 2,\n+ size: 1,\n+ direction: 'next',\n+ nextPageInfo: result1.pageRequest?.nextPageInfo,\n+ previousPageInfo: undefined,\n+ }\n+ const result2 = await PatientRepository.findAllPaged(sortRequest, pageRequest2)\n+\n+ expect(result2.hasPrevious).toBe(true)\n+ expect(result2.hasNext).toBe(true)\n+\n+ const pageRequest3: PageRequest = {\n+ number: 1,\n+ size: 1,\n+ direction: 'previous',\n+ nextPageInfo: undefined,\n+ previousPageInfo: result2.pageRequest?.previousPageInfo,\n+ }\n+ const result3 = await PatientRepository.findAllPaged(sortRequest, pageRequest3)\n+\n+ expect(result3.content).toHaveLength(1)\n+ expect(result3.hasNext).toEqual(true)\n+ expect(result3.hasPrevious).toEqual(false)\n+ expect(result3.content.length).toEqual(1)\n+ expect(result3.content[0].index).toEqual('aP-a')\n+ expect(result3.pageRequest?.nextPageInfo).toEqual({ index: 'bP-b' })\n+ })\n})\ndescribe('searchPaged', () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "@@ -3,12 +3,11 @@ export default interface PageRequest {\nsize: number | undefined\nnextPageInfo: { [key: string]: string | null } | undefined\npreviousPageInfo: { [key: string]: string | null } | undefined\n- direction: 'previous' | 'next' | null\n+ direction?: 'previous' | 'next'\n}\nexport const UnpagedRequest: PageRequest = {\nnumber: undefined,\nsize: undefined,\nnextPageInfo: undefined,\n- direction: null,\npreviousPageInfo: undefined,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -73,6 +73,7 @@ export default class Repository<T extends AbstractDBModel> {\nsort: sort.sorts.length > 0 ? sort.sorts.map((s) => ({ [s.field]: s.direction })) : undefined,\nlimit: pageRequest.size ? pageRequest.size + 1 : undefined,\n})\n+\nconst mappedResult = result.docs.map(mapDocument)\nif (pageRequest.direction === 'previous') {\nmappedResult.reverse()\n@@ -90,19 +91,22 @@ export default class Repository<T extends AbstractDBModel> {\npreviousPageInfo[s.field] = mappedResult[0][s.field]\n})\n+ const hasNext: boolean =\n+ pageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1\n+ const hasPrevious: boolean = pageRequest.number !== undefined && pageRequest.number > 1\n+\nconst pagedResult: Page<T> = {\ncontent:\npageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1\n? mappedResult.slice(0, mappedResult.length - 1)\n: mappedResult,\n- hasNext: pageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1,\n- hasPrevious: pageRequest.number !== undefined && pageRequest.number > 1,\n+ hasNext,\n+ hasPrevious,\npageRequest: {\nsize: pageRequest.size,\nnumber: pageRequest.number,\n- nextPageInfo,\n- previousPageInfo,\n- direction: null,\n+ nextPageInfo: hasNext ? nextPageInfo : undefined,\n+ previousPageInfo: hasPrevious ? previousPageInfo : undefined,\n},\n}\nreturn pagedResult\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(patientrepository): changes for findAllPaged
'direction' field is now optional. 'nextPageInfo' and 'previousPageInfo' in Page can be undefined.
Add tests.
feat #1969 |
288,350 | 14.05.2020 18:01:03 | -19,080 | 7411ad09ee680e5a691fdd34f1ca33c452398f1b | feat(pagecomponent): user can change page size
Add option to change the page size.
feat | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "@@ -11,6 +11,7 @@ import { act } from 'react-dom/test-utils'\nimport * as ButtonBarProvider from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\nimport Page from 'clients/Page'\n+import { defaultPageSize } from 'components/PageComponent'\nimport ViewPatients from '../../../patients/list/ViewPatients'\nimport PatientRepository from '../../../clients/db/PatientRepository'\nimport * as patientSlice from '../../../patients/patients-slice'\n@@ -188,7 +189,7 @@ describe('Patients', () => {\n},\n{\nnumber: 1,\n- size: 1,\n+ size: defaultPageSize.value,\nnextPageInfo: { index: null },\ndirection: 'next',\npreviousPageInfo: { index: null },\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/PageComponent.tsx",
"new_path": "src/components/PageComponent.tsx",
"diff": "import React from 'react'\n-import { Button } from '@hospitalrun/components'\n+import { Button, Select } from '@hospitalrun/components'\nimport { useTranslation } from 'react-i18next'\n+const pageSizes = [\n+ { label: '25', value: 25 },\n+ { label: '50', value: 50 },\n+ { label: '100', value: 100 },\n+ { label: '200', value: 200 },\n+ { label: 'All', value: undefined },\n+]\n+\n+export const defaultPageSize = pageSizes[0]\n+\nconst PageComponent = ({\nhasNext,\nhasPrevious,\npageNumber,\nsetPreviousPageRequest,\nsetNextPageRequest,\n+ onPageSizeChange,\n}: any) => {\nconst { t } = useTranslation()\n@@ -17,25 +28,34 @@ const PageComponent = ({\nkey=\"actions.previous\"\noutlined\ndisabled={!hasPrevious}\n- style={{ float: 'left' }}\n+ style={{ float: 'left', marginRight: '5px' }}\ncolor=\"success\"\nonClick={setPreviousPageRequest}\n>\n{t('actions.previous')}\n</Button>\n- <div style={{ display: 'inline-block' }}>\n- {t('actions.page')} {pageNumber}\n- </div>\n<Button\nkey=\"actions.next\"\noutlined\n- style={{ float: 'right' }}\n+ style={{ float: 'left' }}\ndisabled={!hasNext}\ncolor=\"success\"\nonClick={setNextPageRequest}\n>\n{t('actions.next')}\n</Button>\n+ <div style={{ display: 'inline-block' }}>\n+ {t('actions.page')} {pageNumber}\n+ </div>\n+ <div className=\"row float-right\">\n+ <Select onChange={onPageSizeChange} defaultValue={defaultPageSize.label}>\n+ {pageSizes.map((pageSize) => (\n+ <option key={pageSize.label} value={pageSize.value}>\n+ {pageSize.label}\n+ </option>\n+ ))}\n+ </Select>\n+ </div>\n</div>\n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/list/ViewPatients.tsx",
"new_path": "src/patients/list/ViewPatients.tsx",
"diff": "@@ -7,7 +7,7 @@ import { useButtonToolbarSetter } from 'page-header/ButtonBarProvider'\nimport format from 'date-fns/format'\nimport SortRequest from 'clients/db/SortRequest'\nimport PageRequest from 'clients/db/PageRequest'\n-import PageComponent from 'components/PageComponent'\n+import PageComponent, { defaultPageSize } from 'components/PageComponent'\nimport useUpdateEffect from 'hooks/useUpdateEffect'\nimport { RootState } from '../../store'\nimport { searchPatients } from '../patients-slice'\n@@ -28,7 +28,7 @@ const ViewPatients = () => {\nconst setButtonToolBar = useButtonToolbarSetter()\nconst defaultPageRequest = useRef<PageRequest>({\n- size: 1,\n+ size: defaultPageSize.value,\nnumber: 1,\nnextPageInfo: { index: null },\npreviousPageInfo: { index: null },\n@@ -131,7 +131,19 @@ const ViewPatients = () => {\nsetSearchText(event.target.value)\n}\n+ const onPageSizeChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n+ const newPageSize = parseInt(event.target.value, 10)\n+ setUserPageRequest(() => ({\n+ size: newPageSize,\n+ number: 1,\n+ nextPageInfo: { index: null },\n+ previousPageInfo: { index: null },\n+ direction: 'next',\n+ }))\n+ }\n+\nreturn (\n+ <div>\n<Container>\n<Row>\n<Column md={12}>\n@@ -146,14 +158,16 @@ const ViewPatients = () => {\n</Row>\n<Row> {isLoading ? loadingIndicator : table}</Row>\n+ </Container>\n<PageComponent\nhasNext={patients.hasNext}\nhasPrevious={patients.hasPrevious}\npageNumber={patients.pageRequest ? patients.pageRequest.number : 1}\nsetPreviousPageRequest={setPreviousPageRequest}\nsetNextPageRequest={setNextPageRequest}\n+ onPageSizeChange={onPageSizeChange}\n/>\n- </Container>\n+ </div>\n)\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(pagecomponent): user can change page size
Add option to change the page size.
feat #1969 |
288,347 | 17.05.2020 11:24:24 | -7,200 | c791de39fa8c67d875f8fb1aa99baf164691b5eb | feat(newlabrequest): add requestBy to model
Add new field into the model. The field is auto filled by system when a new lab request is created.
The new field will contain the user id of the current user
fix | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/lab-slice.test.ts",
"new_path": "src/__tests__/labs/lab-slice.test.ts",
"diff": "@@ -304,11 +304,19 @@ describe('lab slice', () => {\n})\nit('should request a new lab', async () => {\n- const store = mockStore()\n+ const store = mockStore({\n+ user: {\n+ user: {\n+ id: 'fake id',\n+ },\n+ },\n+ } as any)\n+\nconst expectedRequestedLab = {\n...mockLab,\nrequestedOn: new Date(Date.now()).toISOString(),\nstatus: 'requested',\n+ requestedBy: store.getState().user.user.id,\n} as Lab\nawait store.dispatch(requestLab(mockLab))\n@@ -321,7 +329,13 @@ describe('lab slice', () => {\n})\nit('should execute the onSuccess callback if provided', async () => {\n- const store = mockStore()\n+ const store = mockStore({\n+ user: {\n+ user: {\n+ id: 'fake id',\n+ },\n+ },\n+ } as any)\nconst onSuccessSpy = jest.fn()\nawait store.dispatch(requestLab(mockLab, onSuccessSpy))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"new_path": "src/__tests__/labs/requests/NewLabRequest.test.tsx",
"diff": "@@ -27,7 +27,10 @@ describe('New Lab Request', () => {\nconst history = createMemoryHistory()\nbeforeEach(() => {\n- const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\n+ const store = mockStore({\n+ title: '',\n+ lab: { status: 'loading', error: {} },\n+ })\ntitleSpy = jest.spyOn(titleUtil, 'default')\nhistory.push('/labs/new')\n@@ -197,7 +200,11 @@ describe('New Lab Request', () => {\n.mockResolvedValue([{ id: expectedLab.patientId, fullName: 'some full name' }] as Patient[])\nhistory.push('/labs/new')\n- const store = mockStore({ title: '', lab: { status: 'loading', error: {} } })\n+ const store = mockStore({\n+ title: '',\n+ lab: { status: 'loading', error: {} },\n+ user: { user: { id: 'fake id' } },\n+ })\nwrapper = mount(\n<Provider store={store}>\n<Router history={history}>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/lab-slice.ts",
"new_path": "src/labs/lab-slice.ts",
"diff": "@@ -105,6 +105,7 @@ const validateLabRequest = (newLab: Lab): Error => {\nexport const requestLab = (newLab: Lab, onSuccess?: (lab: Lab) => void): AppThunk => async (\ndispatch,\n+ getState,\n) => {\ndispatch(requestLabStart())\n@@ -115,6 +116,7 @@ export const requestLab = (newLab: Lab, onSuccess?: (lab: Lab) => void): AppThun\n} else {\nnewLab.status = 'requested'\nnewLab.requestedOn = new Date(Date.now().valueOf()).toISOString()\n+ newLab.requestedBy = getState().user.user.id\nconst requestedLab = await LabRepository.save(newLab)\ndispatch(requestLabSuccess(requestedLab))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Lab.ts",
"new_path": "src/model/Lab.ts",
"diff": "@@ -4,6 +4,7 @@ export default interface Lab extends AbstractDBModel {\ncode: string\npatientId: string\ntype: string\n+ requestedBy: string\nnotes?: string\nresult?: string\nstatus: 'requested' | 'completed' | 'canceled'\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(newlabrequest): add requestBy to model
Add new field into the model. The field is auto filled by system when a new lab request is created.
The new field will contain the user id of the current user
fix #2082 |
288,347 | 20.05.2020 02:16:17 | -7,200 | d1fb94078494a048f9d8aae5ac1b803f429dc07e | fix(incidents): add loading during fetch phase | [
{
"change_type": "MODIFY",
"old_path": "src/incidents/view/ViewIncident.tsx",
"new_path": "src/incidents/view/ViewIncident.tsx",
"diff": "-import { Column, Row } from '@hospitalrun/components'\n+import { Column, Row, Spinner } from '@hospitalrun/components'\nimport format from 'date-fns/format'\nimport React, { useEffect } from 'react'\nimport { useTranslation } from 'react-i18next'\n@@ -31,32 +31,32 @@ const ViewIncident = () => {\ndispatch(fetchIncident(id))\n}\n}, [dispatch, id])\n-\n+ if (incident) {\nreturn (\n<>\n<Row>\n<Column>\n<div className=\"form-group incident-date\">\n<h4>{t('incidents.reports.dateOfIncident')}</h4>\n- <h5>{format(new Date(incident?.date || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n+ <h5>{format(new Date(incident.date || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n</div>\n</Column>\n<Column>\n<div className=\"form-group incident-status\">\n<h4>{t('incidents.reports.status')}</h4>\n- <h5>{incident?.status}</h5>\n+ <h5>{incident.status}</h5>\n</div>\n</Column>\n<Column>\n<div className=\"form-group incident-reported-by\">\n<h4>{t('incidents.reports.reportedBy')}</h4>\n- <h5>{incident?.reportedBy}</h5>\n+ <h5>{incident.reportedBy}</h5>\n</div>\n</Column>\n<Column>\n<div className=\"form-group incident-reported-on\">\n<h4>{t('incidents.reports.reportedOn')}</h4>\n- <h5>{format(new Date(incident?.reportedOn || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n+ <h5>{format(new Date(incident.reportedOn || ''), 'yyyy-MM-dd hh:mm a')}</h5>\n</div>\n</Column>\n</Row>\n@@ -66,7 +66,7 @@ const ViewIncident = () => {\n<TextInputWithLabelFormGroup\nlabel={t('incidents.reports.department')}\nname=\"department\"\n- value={incident?.department}\n+ value={incident.department}\n/>\n</Column>\n</Row>\n@@ -75,14 +75,14 @@ const ViewIncident = () => {\n<TextInputWithLabelFormGroup\nname=\"category\"\nlabel={t('incidents.reports.category')}\n- value={incident?.category}\n+ value={incident.category}\n/>\n</Column>\n<Column md={6}>\n<TextInputWithLabelFormGroup\nlabel={t('incidents.reports.categoryItem')}\nname=\"categoryItem\"\n- value={incident?.categoryItem}\n+ value={incident.categoryItem}\n/>\n</Column>\n</Row>\n@@ -91,12 +91,14 @@ const ViewIncident = () => {\n<TextFieldWithLabelFormGroup\nlabel={t('incidents.reports.description')}\nname=\"description\"\n- value={incident?.description}\n+ value={incident.description}\n/>\n</Column>\n</Row>\n</>\n)\n}\n+ return <Spinner type=\"BarLoader\" loading />\n+}\nexport default ViewIncident\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(incidents): add loading during fetch phase (#2085) |
288,347 | 20.05.2020 02:41:01 | -7,200 | 5309a859a4b19617f44183b1d70d0f36af6206d8 | feat(incidents): filter incidents | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/incidents-slice.test.ts",
"new_path": "src/__tests__/incidents/incidents-slice.test.ts",
"diff": "@@ -3,10 +3,11 @@ import createMockStore from 'redux-mock-store'\nimport thunk from 'redux-thunk'\nimport IncidentRepository from '../../clients/db/IncidentRepository'\n+import IncidentFilter from '../../incidents/IncidentFilter'\nimport incidents, {\n- fetchIncidents,\nfetchIncidentsStart,\nfetchIncidentsSuccess,\n+ searchIncidents,\n} from '../../incidents/incidents-slice'\nimport Incident from '../../model/Incident'\nimport { RootState } from '../../store'\n@@ -39,12 +40,24 @@ describe('Incidents Slice', () => {\njest.spyOn(IncidentRepository, 'findAll').mockResolvedValue(expectedIncidents)\nconst store = mockStore()\n- await store.dispatch(fetchIncidents())\n+ await store.dispatch(searchIncidents(IncidentFilter.all))\nexpect(store.getActions()[0]).toEqual(fetchIncidentsStart())\nexpect(IncidentRepository.findAll).toHaveBeenCalledTimes(1)\nexpect(store.getActions()[1]).toEqual(fetchIncidentsSuccess(expectedIncidents))\n})\n+\n+ it('should fetch incidents filtering by status', async () => {\n+ const expectedIncidents = [{ id: '123' }] as Incident[]\n+ jest.spyOn(IncidentRepository, 'search').mockResolvedValue(expectedIncidents)\n+ const store = mockStore()\n+\n+ await store.dispatch(searchIncidents(IncidentFilter.reported))\n+\n+ expect(store.getActions()[0]).toEqual(fetchIncidentsStart())\n+ expect(IncidentRepository.search).toHaveBeenCalledTimes(1)\n+ expect(store.getActions()[1]).toEqual(fetchIncidentsSuccess(expectedIncidents))\n+ })\n})\n})\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/incidents/list/ViewIncidents.test.tsx",
"new_path": "src/__tests__/incidents/list/ViewIncidents.test.tsx",
"diff": "@@ -11,6 +11,7 @@ import thunk from 'redux-thunk'\nimport * as breadcrumbUtil from '../../../breadcrumbs/useAddBreadcrumbs'\nimport IncidentRepository from '../../../clients/db/IncidentRepository'\n+import IncidentFilter from '../../../incidents/IncidentFilter'\nimport ViewIncidents from '../../../incidents/list/ViewIncidents'\nimport Incident from '../../../model/Incident'\nimport Permissions from '../../../model/Permissions'\n@@ -42,6 +43,7 @@ describe('View Incidents', () => {\njest.spyOn(titleUtil, 'default')\njest.spyOn(ButtonBarProvider, 'useButtonToolbarSetter').mockReturnValue(setButtonToolBarSpy)\njest.spyOn(IncidentRepository, 'findAll').mockResolvedValue(expectedIncidents)\n+ jest.spyOn(IncidentRepository, 'search').mockResolvedValue(expectedIncidents)\nhistory = createMemoryHistory()\nhistory.push(`/incidents`)\n@@ -72,7 +74,27 @@ describe('View Incidents', () => {\nwrapper.update()\nreturn wrapper\n}\n+ it('should filter incidents by status=reported on first load ', async () => {\n+ const wrapper = await setup([Permissions.ViewIncidents])\n+ const filterSelect = wrapper.find('select')\n+ expect(filterSelect.props().value).toBe(IncidentFilter.reported)\n+\n+ expect(IncidentRepository.search).toHaveBeenCalled()\n+ expect(IncidentRepository.search).toHaveBeenCalledWith({ status: IncidentFilter.reported })\n+ })\n+ it('should call IncidentRepository after changing filter', async () => {\n+ const wrapper = await setup([Permissions.ViewIncidents])\n+ const filterSelect = wrapper.find('select')\n+ expect(IncidentRepository.findAll).not.toHaveBeenCalled()\n+\n+ filterSelect.simulate('change', { target: { value: IncidentFilter.all } })\n+ expect(IncidentRepository.findAll).toHaveBeenCalled()\n+ filterSelect.simulate('change', { target: { value: IncidentFilter.reported } })\n+\n+ expect(IncidentRepository.search).toHaveBeenCalledTimes(2)\n+ expect(IncidentRepository.search).toHaveBeenLastCalledWith({ status: IncidentFilter.reported })\n+ })\ndescribe('layout', () => {\nit('should set the title', async () => {\nawait setup([Permissions.ViewIncidents])\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/IncidentRepository.ts",
"new_path": "src/clients/db/IncidentRepository.ts",
"diff": "import { incidents } from '../../config/pouchdb'\n+import IncidentFilter from '../../incidents/IncidentFilter'\nimport Incident from '../../model/Incident'\nimport Repository from './Repository'\n+interface SearchOptions {\n+ status: IncidentFilter\n+}\nclass IncidentRepository extends Repository<Incident> {\nconstructor() {\nsuper(incidents)\n}\n+\n+ async search(options: SearchOptions): Promise<Incident[]> {\n+ return super.search(IncidentRepository.getSearchCriteria(options))\n+ }\n+\n+ private static getSearchCriteria(options: SearchOptions): any {\n+ const statusFilter = options.status !== IncidentFilter.all ? [{ status: options.status }] : []\n+ const selector = {\n+ $and: statusFilter,\n+ }\n+ return {\n+ selector,\n+ }\n+ }\n}\nexport default new IncidentRepository()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/incidents/IncidentFilter.ts",
"diff": "+enum IncidentFilter {\n+ reported = 'reported',\n+ all = 'all',\n+}\n+\n+export default IncidentFilter\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/incidents-slice.ts",
"new_path": "src/incidents/incidents-slice.ts",
"diff": "@@ -3,6 +3,7 @@ import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport IncidentRepository from '../clients/db/IncidentRepository'\nimport Incident from '../model/Incident'\nimport { AppThunk } from '../store'\n+import IncidentFilter from './IncidentFilter'\ninterface IncidentsState {\nincidents: Incident[]\n@@ -34,10 +35,16 @@ const incidentSlice = createSlice({\nexport const { fetchIncidentsStart, fetchIncidentsSuccess } = incidentSlice.actions\n-export const fetchIncidents = (): AppThunk => async (dispatch) => {\n+export const searchIncidents = (status: IncidentFilter): AppThunk => async (dispatch) => {\ndispatch(fetchIncidentsStart())\n-\n- const incidents = await IncidentRepository.findAll()\n+ let incidents\n+ if (status === IncidentFilter.all) {\n+ incidents = await IncidentRepository.findAll()\n+ } else {\n+ incidents = await IncidentRepository.search({\n+ status,\n+ })\n+ }\ndispatch(fetchIncidentsSuccess(incidents))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/list/ViewIncidents.tsx",
"new_path": "src/incidents/list/ViewIncidents.tsx",
"diff": "import format from 'date-fns/format'\n-import React, { useEffect } from 'react'\n+import React, { useEffect, useState } from 'react'\nimport { useTranslation } from 'react-i18next'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { useHistory } from 'react-router-dom'\n+import SelectWithLabelFormGroup from '../../components/input/SelectWithLableFormGroup'\nimport Incident from '../../model/Incident'\nimport useTitle from '../../page-header/useTitle'\nimport { RootState } from '../../store'\n-import { fetchIncidents } from '../incidents-slice'\n+import IncidentFilter from '../IncidentFilter'\n+import { searchIncidents } from '../incidents-slice'\nconst ViewIncidents = () => {\nconst { t } = useTranslation()\nconst history = useHistory()\nconst dispatch = useDispatch()\nuseTitle(t('incidents.reports.label'))\n-\n+ const [searchFilter, setSearchFilter] = useState(IncidentFilter.reported)\nconst { incidents } = useSelector((state: RootState) => state.incidents)\nuseEffect(() => {\n- dispatch(fetchIncidents())\n- }, [dispatch])\n+ dispatch(searchIncidents(searchFilter))\n+ }, [dispatch, searchFilter])\nconst onTableRowClick = (incident: Incident) => {\nhistory.push(`incidents/${incident.id}`)\n}\n+ const onFilterChange = (event: React.ChangeEvent<HTMLSelectElement>) => {\n+ setSearchFilter(event.target.value as IncidentFilter)\n+ }\n+\n+ const filterOptions = Object.values(IncidentFilter).map((filter) => ({\n+ label: t(`incidents.status.${filter}`),\n+ value: `${filter}`,\n+ }))\n+\nreturn (\n+ <>\n+ <div className=\"row\">\n+ <div className=\"col-md-3 col-lg-2\">\n+ <SelectWithLabelFormGroup\n+ name=\"type\"\n+ value={searchFilter}\n+ label={t('incidents.filterTitle')}\n+ isEditable\n+ options={filterOptions}\n+ onChange={onFilterChange}\n+ />\n+ </div>\n+ </div>\n+ <div className=\"row\">\n<table className=\"table table-hover\">\n<thead className=\"thead-light\">\n<tr>\n@@ -48,6 +73,8 @@ const ViewIncidents = () => {\n))}\n</tbody>\n</table>\n+ </div>\n+ </>\n)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/incidents/index.ts",
"new_path": "src/locales/enUs/translations/incidents/index.ts",
"diff": "export default {\nincidents: {\n+ filterTitle: ' Filter by status',\nlabel: 'Incidents',\nactions: {\nreport: 'Report',\n},\n+ status: {\n+ reported: 'reported',\n+ all: 'all',\n+ },\nreports: {\nlabel: 'Reported Incidents',\nnew: 'Report Incident',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incidents): filter incidents (#2087) |
288,350 | 20.05.2020 17:50:14 | -19,080 | 671ad02d6992727f73c777f673a6c305fd57b1b2 | feat(viewpatients): add Tests, Fix bug
feat | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/components/PageComponent.test.tsx",
"diff": "+import '../../__mocks__/matchMediaMock'\n+import { Button, Select } from '@hospitalrun/components'\n+import { mount } from 'enzyme'\n+import React from 'react'\n+\n+import PageComponent, { defaultPageSize } from '../../components/PageComponent'\n+\n+describe('PageComponenet test', () => {\n+ it('should render PageComponent Component', () => {\n+ const wrapper = mount(\n+ <PageComponent\n+ hasNext={false}\n+ hasPrevious={false}\n+ pageNumber={1}\n+ setPreviousPageRequest={jest.fn()}\n+ setNextPageRequest={jest.fn()}\n+ onPageSizeChange={jest.fn()}\n+ />,\n+ )\n+ const buttons = wrapper.find(Button)\n+ expect(buttons).toHaveLength(2)\n+ expect(buttons.at(0).prop('disabled')).toBeTruthy()\n+ expect(buttons.at(1).prop('disabled')).toBeTruthy()\n+\n+ const select = wrapper.find(Select)\n+ expect(select.prop('defaultValue')).toEqual(defaultPageSize.value?.toString())\n+\n+ const options = select.find('option')\n+ expect(options).toHaveLength(5)\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/hooks/useUpdateEffect.test.ts",
"diff": "+import { renderHook } from '@testing-library/react-hooks'\n+\n+import useUpdateEffect from '../../hooks/useUpdateEffect'\n+\n+describe('useUpdateEffect', () => {\n+ it('should call the function after udpate', () => {\n+ const mockFn = jest.fn()\n+ let someVal = 'someVal'\n+ const { rerender } = renderHook(() => useUpdateEffect(mockFn, [someVal]))\n+ expect(mockFn).not.toHaveBeenCalled()\n+ someVal = 'newVal'\n+ rerender()\n+ expect(mockFn).toHaveBeenCalledTimes(1)\n+ })\n+})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"new_path": "src/__tests__/patients/list/ViewPatients.test.tsx",
"diff": "import '../../../__mocks__/matchMediaMock'\n-import { TextInput, Spinner } from '@hospitalrun/components'\n+import { TextInput, Spinner, Select } from '@hospitalrun/components'\nimport format from 'date-fns/format'\nimport { mount } from 'enzyme'\nimport React from 'react'\n@@ -13,6 +13,7 @@ import { mocked } from 'ts-jest/utils'\nimport { UnpagedRequest } from '../../../clients/db/PageRequest'\nimport PatientRepository from '../../../clients/db/PatientRepository'\n+import SortRequest from '../../../clients/db/SortRequest'\nimport Page from '../../../clients/Page'\nimport { defaultPageSize } from '../../../components/PageComponent'\nimport Patient from '../../../model/Patient'\n@@ -155,6 +156,47 @@ describe('Patients', () => {\n})\n})\n+ describe('change page size', () => {\n+ afterEach(() => {\n+ jest.restoreAllMocks()\n+ })\n+ it('should call the change handler on change', () => {\n+ const searchPagedSpy = jest.spyOn(patientSlice, 'searchPatients')\n+ const wrapper = setup()\n+ const sortRequest: SortRequest = {\n+ sorts: [{ field: 'index', direction: 'asc' }],\n+ }\n+\n+ expect(searchPagedSpy).toBeCalledWith('', sortRequest, {\n+ direction: 'next',\n+ nextPageInfo: { index: null },\n+ number: 1,\n+ previousPageInfo: { index: null },\n+ size: defaultPageSize.value,\n+ })\n+\n+ act(() => {\n+ ;(wrapper.find(Select).prop('onChange') as any)({\n+ target: {\n+ value: '50',\n+ },\n+ } as React.ChangeEvent<HTMLInputElement>)\n+ })\n+\n+ wrapper.update()\n+\n+ expect(searchPagedSpy).toHaveBeenCalledTimes(2)\n+\n+ expect(searchPagedSpy).toBeCalledWith('', sortRequest, {\n+ direction: 'next',\n+ nextPageInfo: { index: null },\n+ number: 1,\n+ previousPageInfo: { index: null },\n+ size: 50,\n+ })\n+ })\n+ })\n+\ndescribe('search functionality', () => {\nbeforeEach(() => jest.useFakeTimers())\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "@@ -98,16 +98,16 @@ export default class Repository<T extends AbstractDBModel> {\n}\nconst nextPageInfo: { [key: string]: string } = {}\n+ const previousPageInfo: { [key: string]: string } = {}\n+\nif (mappedResult.length > 0) {\nsort.sorts.forEach((s) => {\nnextPageInfo[s.field] = mappedResult[mappedResult.length - 1][s.field]\n})\n- }\n-\n- const previousPageInfo: { [key: string]: string } = {}\nsort.sorts.forEach((s) => {\npreviousPageInfo[s.field] = mappedResult[0][s.field]\n})\n+ }\nconst hasNext: boolean =\npageRequest.size !== undefined && mappedResult.length === pageRequest.size + 1\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(viewpatients): add Tests, Fix bug
feat #1969 |
288,334 | 23.05.2020 14:50:32 | -7,200 | b3a0c17609d3b722fdde6f537cf1f0a929f03da8 | ci(action): add auto approve | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/auto-approve.yml",
"diff": "+name: v\n+\n+on:\n+ pull_request\n+\n+jobs:\n+ auto-approve:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: hmarr/[email protected]\n+ if: github.actor == 'dependabot[bot]' || github.actor == 'dependabot-preview[bot]'\n+ with:\n+ github-token: \"${{ secrets.GITHUB_TOKEN }}\"\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | ci(action): add auto approve |
288,334 | 23.05.2020 15:08:12 | -7,200 | be3ba9547399e363cc69a6d57d10db3edf74506a | ci(action): remove auto approve action | [
{
"change_type": "DELETE",
"old_path": ".github/workflows/auto-approve.yml",
"new_path": null,
"diff": "-name: Auto approve\n-\n-on:\n- pull_request\n-\n-jobs:\n- auto-approve:\n- runs-on: ubuntu-latest\n- steps:\n- - uses: hmarr/[email protected]\n- if: github.actor == 'dependabot[bot]' || github.actor == 'dependabot-preview[bot]'\n- with:\n- github-token: \"${{ secrets.GITHUB_TOKEN }}\"\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | ci(action): remove auto approve action |
288,334 | 23.05.2020 19:20:12 | -7,200 | 64613948ab534c776cb1aee0c24f5d8eff60ff7d | ci(yarn): remove yarn job | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci.yml",
"new_path": ".github/workflows/ci.yml",
"diff": "@@ -62,32 +62,3 @@ jobs:\n- name: Run tests\nrun: |\nnpm run test:ci\n-\n- yarn:\n- runs-on: ${{ matrix.os }}\n- strategy:\n- matrix:\n- node-version: [12.x]\n- os: [ubuntu-latest, windows-latest, macOS-latest]\n- steps:\n- - run: git config --global core.autocrlf false # this is needed to prevent git changing EOL after cloning on Windows OS\n- - uses: actions/checkout@v2\n- - name: Use Node.js\n- uses: actions/setup-node@v1\n- with:\n- node-version: ${{ matrix.node-version }}\n- - name: Init yarn\n- run: |\n- npm install -g yarn\n- - name: Install with yarn\n- run: |\n- yarn install\n- - name: Lint code\n- run: |\n- yarn lint\n- - name: Build\n- run: |\n- yarn build\n- - name: Run tests\n- run: |\n- yarn test:ci\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | ci(yarn): remove yarn job |
288,334 | 24.05.2020 13:24:54 | -7,200 | af6d9639208b9ccc663f6e4088f3814bf4766a01 | refactor(i18n): edit chinese and indonesian ISO 639-1 codes | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -31,8 +31,12 @@ Contributions are always welcome. Before contributing please read our [contribut\n1. Fork this repository to your own GitHub account and then clone it to your local device\n2. Navigate to the cloned folder: `cd hospitalrun-frontend`\n-3. Install the dependencies: `yarn`\n-4. Run `yarn run start` to build and watch for code changes\n+3. Install the dependencies: `npm install`\n+4. Run `npm run start` to build and watch for code changes\n+\n+## Translation\n+\n+Use the stadards in [this readme](https://github.com/HospitalRun/hospitalrun-frontend/tree/master/src/locales/README.md).\n## Online one-click setup for contributing\n@@ -77,13 +81,13 @@ To fix this issue, add `SKIP_PREFLIGHT_CHECK=true` to the `.env` file.\n## Running Tests and Linter\n-`yarn test:ci` will run the entire test suite\n+`npm run test:ci` will run the entire test suite\n-`yarn test` will run the test suite in watch mode\n+`npm run test` will run the test suite in watch mode\n-`yarn lint` will run the linter\n+`npm run lint` will run the linter\n-`yarn lint:fix` will run the linter and fix fixable errors\n+`npm run lint:fix` will run the linter and fix fixable errors\n## Useful Developer Tools\n@@ -98,7 +102,7 @@ In order to optimize the workflow and to prevent multiple contributors working o\n## How to commit\n-This repo uses Conventional Commits. Commitizen is mandatory for making proper commits. Once you have staged your changes, can run `npm run commit` or `yarn commit` from the root directory in order to commit following our standards.\n+This repo uses Conventional Commits. Commitizen is mandatory for making proper commits. Once you have staged your changes, can run `npm run commit` from the root directory in order to commit following our standards.\n<hr />\n"
},
{
"change_type": "MODIFY",
"old_path": "src/i18n.ts",
"new_path": "src/i18n.ts",
"diff": "@@ -7,12 +7,12 @@ import translationDE from './locales/de/translations'\nimport translationEnUs from './locales/enUs/translations'\nimport translationES from './locales/es/translations'\nimport translationFR from './locales/fr/translations'\n-import translationIN from './locales/in/translations'\n+import translationID from './locales/id/translations'\nimport translationIT from './locales/it/translations'\nimport translationJA from './locales/ja/translations'\nimport translationPtBR from './locales/ptBr/translations'\nimport translationRU from './locales/ru/translations'\n-import translationZR from './locales/zr/translations'\n+import translationZhCN from './locales/zhCN/translations'\nconst resources = {\nit: {\n@@ -33,20 +33,20 @@ const resources = {\nfr: {\ntranslation: translationFR,\n},\n- in: {\n- translation: translationIN,\n+ id: {\n+ translation: translationID,\n},\nja: {\ntranslation: translationJA,\n},\n- pt: {\n+ ptBR: {\ntranslation: translationPtBR,\n},\nru: {\ntranslation: translationRU,\n},\n- zr: {\n- translation: translationZR,\n+ zhCN: {\n+ translation: translationZhCN,\n},\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/README.md",
"diff": "+# Codes to use to identify languages\n+\n+The [IETF language tags](http://en.wikipedia.org/wiki/IETF_language_tag) are made up of [ISO 639](http://en.wikipedia.org/wiki/ISO_639) standards for representing language names and [ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) standards for representing country codes. A sample list:\n+\n+| English name for language | Tag |\n+| :------------------------ | :---- |\n+| English | en |\n+| English (United States) | en-US |\n+| English (Great Britain) | en-GB |\n+| French | fr |\n+| German | de |\n+| Polish | pl |\n+| Dutch | nl |\n+| Finnish | fi |\n+| Swedish | sv |\n+| Italian | it |\n+| Spanish (Spain) | es |\n+| Portuguese (Portugal) | pt |\n+| Russian | ru |\n+| Portuguese (Brazil) | pt-BR |\n+| Spanish (Mexico) | es-MX |\n+| Chinese (PRC) | zh-CN |\n+| Chinese (Taiwan) | zh-TW |\n+| Japanese | ja |\n+| Korean | ko |\n+\n+Use these two reference lists to create new languages.\n+\n+[ISO 639-1](https://datahub.io/core/language-codes/r/0.html)\n+\n+[IETF Language Types](https://datahub.io/core/language-codes/r/3.html)\n"
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/actions/index.ts",
"new_path": "src/locales/id/translations/actions/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/dashboard/index.ts",
"new_path": "src/locales/id/translations/dashboard/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/index.ts",
"new_path": "src/locales/id/translations/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/labs/index.ts",
"new_path": "src/locales/id/translations/labs/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/patient/index.ts",
"new_path": "src/locales/id/translations/patient/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/in/translations/patients/index.ts",
"new_path": "src/locales/id/translations/patients/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/zr/translations/actions/index.ts",
"new_path": "src/locales/zhCN/translations/actions/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/zr/translations/dashboard/index.ts",
"new_path": "src/locales/zhCN/translations/dashboard/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/zr/translations/index.ts",
"new_path": "src/locales/zhCN/translations/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/zr/translations/labs/index.ts",
"new_path": "src/locales/zhCN/translations/labs/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "src/locales/zr/translations/patient/index.ts",
"new_path": "src/locales/zhCN/translations/patient/index.ts",
"diff": ""
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(i18n): edit chinese and indonesian ISO 639-1 codes |
288,356 | 26.05.2020 02:19:31 | -7,200 | ce25987e60d0fb2760430137463bd8b011131637 | (i18n) German Translation
Updated German Translation | [
{
"change_type": "MODIFY",
"old_path": "src/locales/de/translations/index.ts",
"new_path": "src/locales/de/translations/index.ts",
"diff": "import actions from './actions'\nimport dashboard from './dashboard'\n+import incidents from './incidents'\n+import labs from './labs'\nimport patient from './patient'\nimport patients from './patients'\n+import scheduling from './scheduling'\n+import sex from './sex'\n+import states from './states'\nexport default {\n...actions,\n...dashboard,\n...patient,\n...patients,\n+ ...scheduling,\n+ ...states,\n+ ...sex,\n+ ...labs,\n+ ...incidents,\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/de/translations/states/index.ts",
"diff": "+export default {\n+ states: {\n+ success: 'Erfolg!',\n+ error: 'Fehler!',\n+ },\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | (i18n) German Translation
Updated German Translation |
288,249 | 29.05.2020 16:48:37 | 25,200 | b1a8cdf3e3288f6084592f583407ea89cebd5134 | feat(navbar): add shortcut icon to the create pages | [
{
"change_type": "MODIFY",
"old_path": "src/components/Navbar.tsx",
"new_path": "src/components/Navbar.tsx",
"diff": "import { Navbar as HospitalRunNavbar } from '@hospitalrun/components'\nimport React from 'react'\nimport { useTranslation } from 'react-i18next'\n+import { useSelector } from 'react-redux'\nimport { useHistory } from 'react-router-dom'\n+import Permissions from '../model/Permissions'\n+import { RootState } from '../store'\n+\nconst Navbar = () => {\n+ const { permissions } = useSelector((state: RootState) => state.user)\nconst { t } = useTranslation()\nconst history = useHistory()\n+\n+ const addPages = [\n+ {\n+ permission: Permissions.WritePatients,\n+ label: t('patients.newPatient'),\n+ path: '/patients/new',\n+ },\n+ {\n+ permission: Permissions.WriteAppointments,\n+ label: t('scheduling.appointments.new'),\n+ path: '/appointments/new',\n+ },\n+ {\n+ permission: Permissions.RequestLab,\n+ label: t('labs.requests.new'),\n+ path: '/labs/new',\n+ },\n+ {\n+ permission: Permissions.ReportIncident,\n+ label: t('incidents.reports.new'),\n+ path: '/incidents/new',\n+ },\n+ ]\n+\n+ const addDropdownList: { type: string; label: string; onClick: () => void }[] = []\n+ addPages.forEach((page) => {\n+ if (permissions.includes(page.permission)) {\n+ addDropdownList.push({\n+ type: 'link',\n+ label: page.label,\n+ onClick: () => {\n+ history.push(page.path)\n+ },\n+ })\n+ }\n+ })\n+\nreturn (\n<HospitalRunNavbar\nbg=\"dark\"\n@@ -100,6 +142,16 @@ const Navbar = () => {\nonClickButton: () => undefined,\nonChangeInput: () => undefined,\n},\n+ {\n+ type: 'link-list-icon',\n+ alignRight: true,\n+ children: addDropdownList,\n+ className: 'pl-4',\n+ iconClassName: 'align-bottom',\n+ label: 'Add',\n+ name: 'add',\n+ size: 'lg',\n+ },\n{\ntype: 'link-list-icon',\nalignRight: true,\n@@ -112,7 +164,7 @@ const Navbar = () => {\n},\n},\n],\n- className: 'pl-4',\n+ className: 'pl-2',\niconClassName: 'align-bottom',\nlabel: 'Patient',\nname: 'patient',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(navbar): add shortcut icon to the create pages |
288,249 | 29.05.2020 19:41:21 | 25,200 | ea1eef9601e37faf821cb6c56fd6abc565dee602 | test(navbar): add permissions to test | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Navbar.test.tsx",
"new_path": "src/__tests__/components/Navbar.test.tsx",
"diff": "@@ -3,23 +3,59 @@ import '../../__mocks__/matchMediaMock'\nimport { Navbar as HospitalRunNavbar } from '@hospitalrun/components'\nimport { mount } from 'enzyme'\nimport { createMemoryHistory } from 'history'\n+import _ from 'lodash'\nimport React from 'react'\nimport { act } from 'react-dom/test-utils'\n+import { Provider } from 'react-redux'\nimport { Router } from 'react-router-dom'\n+import createMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\nimport Navbar from '../../components/Navbar'\n+import Permissions from '../../model/Permissions'\n+import { RootState } from '../../store'\n+\n+const mockStore = createMockStore<RootState, any>([thunk])\ndescribe('Navbar', () => {\nconst history = createMemoryHistory()\n- const setup = () =>\n- mount(\n+\n+ const setup = (permissions: Permissions[]) => {\n+ const store = mockStore({\n+ title: '',\n+ user: { permissions },\n+ } as any)\n+\n+ const wrapper = mount(\n<Router history={history}>\n+ <Provider store={store}>\n<Navbar />\n+ </Provider>\n</Router>,\n)\n+ return wrapper\n+ }\n- const wrapper = setup()\n+ const allPermissions = [\n+ Permissions.ReadPatients,\n+ Permissions.WritePatients,\n+ Permissions.ReadAppointments,\n+ Permissions.WriteAppointments,\n+ Permissions.DeleteAppointment,\n+ Permissions.AddAllergy,\n+ Permissions.AddDiagnosis,\n+ Permissions.RequestLab,\n+ Permissions.CancelLab,\n+ Permissions.CompleteLab,\n+ Permissions.ViewLab,\n+ Permissions.ViewLabs,\n+ Permissions.ViewIncidents,\n+ Permissions.ViewIncident,\n+ Permissions.ReportIncident,\n+ ]\n+ const wrapper = setup(allPermissions)\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const wrapperNoLabIncidentPermission = setup(_.cloneDeep(allPermissions).slice(0, 6))\nit('should render a HospitalRun Navbar', () => {\nexpect(hospitalRunNavbar).toHaveLength(1)\n@@ -142,4 +178,24 @@ describe('Navbar', () => {\nexpect(children.props.children[1].props.children).toEqual('actions.search')\n})\n})\n+\n+ describe('add new', () => {\n+ let addNew = hospitalRunNavbar.find('.add-new')\n+ let children = addNew.first().props().children as any\n+\n+ it('should show a shortcut if user has a permission', () => {\n+ expect(children[0].props.children).toEqual('patients.newPatient')\n+ })\n+\n+ // Without Lab or Incident permissions\n+ addNew = wrapperNoLabIncidentPermission.find(HospitalRunNavbar).find('.add-new')\n+ children = addNew.first().props().children as any\n+\n+ it('should not show a shortcut if user does not have a permission', () => {\n+ children.forEach((option: any) => {\n+ expect(option.props.children).not.toEqual('labs.requests.new')\n+ expect(option.props.children).not.toEqual('incidents.requests.new')\n+ })\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Navbar.tsx",
"new_path": "src/components/Navbar.tsx",
"diff": "@@ -146,7 +146,7 @@ const Navbar = () => {\ntype: 'link-list-icon',\nalignRight: true,\nchildren: addDropdownList,\n- className: 'pl-4',\n+ className: 'pl-4 add-new',\niconClassName: 'align-bottom',\nlabel: 'Add',\nname: 'add',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test(navbar): add permissions to test |
288,249 | 29.05.2020 19:56:42 | 25,200 | cd9e4bd6e289ca15f3c9e092a873aeb1ede2cf6b | refactor(navbar): optimize addDropdownList generation | [
{
"change_type": "MODIFY",
"old_path": "src/components/Navbar.tsx",
"new_path": "src/components/Navbar.tsx",
"diff": "@@ -35,18 +35,15 @@ const Navbar = () => {\n},\n]\n- const addDropdownList: { type: string; label: string; onClick: () => void }[] = []\n- addPages.forEach((page) => {\n- if (permissions.includes(page.permission)) {\n- addDropdownList.push({\n+ const addDropdownList: { type: string; label: string; onClick: () => void }[] = addPages\n+ .filter((page) => permissions.includes(page.permission))\n+ .map((page) => ({\ntype: 'link',\nlabel: page.label,\nonClick: () => {\nhistory.push(page.path)\n},\n- })\n- }\n- })\n+ }))\nreturn (\n<HospitalRunNavbar\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(navbar): optimize addDropdownList generation |
288,249 | 29.05.2020 20:52:25 | 25,200 | 860fb8c1fbec248c6a442b28f960bd3874bddfba | test(navbar): each it gets its own wrapper | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Navbar.test.tsx",
"new_path": "src/__tests__/components/Navbar.test.tsx",
"diff": "@@ -3,7 +3,7 @@ import '../../__mocks__/matchMediaMock'\nimport { Navbar as HospitalRunNavbar } from '@hospitalrun/components'\nimport { mount } from 'enzyme'\nimport { createMemoryHistory } from 'history'\n-import _ from 'lodash'\n+import cloneDeep from 'lodash/cloneDeep'\nimport React from 'react'\nimport { act } from 'react-dom/test-utils'\nimport { Provider } from 'react-redux'\n@@ -53,22 +53,27 @@ describe('Navbar', () => {\nPermissions.ViewIncident,\nPermissions.ReportIncident,\n]\n+\n+ it('should render a HospitalRun Navbar', () => {\nconst wrapper = setup(allPermissions)\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const wrapperNoLabIncidentPermission = setup(_.cloneDeep(allPermissions).slice(0, 6))\n- it('should render a HospitalRun Navbar', () => {\nexpect(hospitalRunNavbar).toHaveLength(1)\n})\ndescribe('header', () => {\n+ it('should render a HospitalRun Navbar with the navbar header', () => {\n+ const wrapper = setup(allPermissions)\nconst header = wrapper.find('.nav-header')\nconst { children } = header.first().props() as any\n- it('should render a HospitalRun Navbar with the navbar header', () => {\nexpect(children.props.children).toEqual('HospitalRun')\n})\n+\nit('should navigate to / when the header is clicked', () => {\n+ const wrapper = setup(allPermissions)\n+ const header = wrapper.find('.nav-header')\n+\nact(() => {\nconst onClick = header.first().prop('onClick') as any\nonClick()\n@@ -79,22 +84,36 @@ describe('Navbar', () => {\n})\ndescribe('patients', () => {\n+ it('should render a patients link list', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\nconst patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\nconst { children } = patientsLinkList.first().props() as any\n- it('should render a patients link list', () => {\nexpect(patientsLinkList.first().props().title).toEqual('patients.label')\nexpect(children[0].props.children).toEqual('actions.list')\nexpect(children[1].props.children).toEqual('actions.new')\n})\n+\nit('should navigate to /patients when the list option is selected', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n+ const { children } = patientsLinkList.first().props() as any\n+\nact(() => {\nchildren[0].props.onClick()\n})\nexpect(history.location.pathname).toEqual('/patients')\n})\n+\nit('should navigate to /patients/new when the list option is selected', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n+ const { children } = patientsLinkList.first().props() as any\n+\nact(() => {\nchildren[1].props.onClick()\n})\n@@ -104,32 +123,37 @@ describe('Navbar', () => {\n})\ndescribe('scheduling', () => {\n+ it('should render a scheduling dropdown', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\nconst scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n+ const { children } = scheduleLinkList.first().props() as any\n- it('should render a scheduling dropdown', () => {\nexpect(scheduleLinkList.first().props().title).toEqual('scheduling.label')\n-\n- const children = scheduleLinkList.first().props().children as any[]\n- const firstChild = children[0] as any\n- const secondChild = children[1] as any\n-\nif (scheduleLinkList.first().props().children) {\n- expect(firstChild.props.children).toEqual('scheduling.appointments.label')\n- expect(secondChild.props.children).toEqual('scheduling.appointments.new')\n+ expect(children[0].props.children).toEqual('scheduling.appointments.label')\n+ expect(children[1].props.children).toEqual('scheduling.appointments.new')\n}\n})\nit('should navigate to to /appointments when the appointment list option is selected', () => {\n- const children = scheduleLinkList.first().props().children as any[]\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n+ const { children } = scheduleLinkList.first().props() as any\nact(() => {\nchildren[0].props.onClick()\n})\n+\nexpect(history.location.pathname).toEqual('/appointments')\n})\nit('should navigate to /appointments/new when the new appointment list option is selected', () => {\n- const children = scheduleLinkList.first().props().children as any[]\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n+ const { children } = scheduleLinkList.first().props() as any\nact(() => {\nchildren[1].props.onClick()\n@@ -140,16 +164,23 @@ describe('Navbar', () => {\n})\ndescribe('labs', () => {\n+ it('should render a labs dropdown', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\nconst labsLinkList = hospitalRunNavbar.find('.labs-link-list')\nconst { children } = labsLinkList.first().props() as any\n- it('should render a labs dropdown', () => {\nexpect(labsLinkList.first().props().title).toEqual('labs.label')\nexpect(children[0].props.children).toEqual('labs.label')\nexpect(children[1].props.children).toEqual('labs.requests.new')\n})\nit('should navigate to to /labs when the labs list option is selected', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n+ const { children } = labsLinkList.first().props() as any\n+\nact(() => {\nchildren[0].props.onClick()\n})\n@@ -158,6 +189,11 @@ describe('Navbar', () => {\n})\nit('should navigate to /labs/new when the new labs list option is selected', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n+ const { children } = labsLinkList.first().props() as any\n+\nact(() => {\nchildren[1].props.onClick()\n})\n@@ -167,31 +203,42 @@ describe('Navbar', () => {\n})\ndescribe('search', () => {\n+ it('should render Search as the search box placeholder', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\nconst navSearch = hospitalRunNavbar.find('.nav-search')\nconst { children } = navSearch.first().props() as any\n- it('should render Search as the search box placeholder', () => {\nexpect(children.props.children[0].props.placeholder).toEqual('actions.search')\n})\nit('should render Search as the search button label', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const navSearch = hospitalRunNavbar.find('.nav-search')\n+ const { children } = navSearch.first().props() as any\n+\nexpect(children.props.children[1].props.children).toEqual('actions.search')\n})\n})\ndescribe('add new', () => {\n- let addNew = hospitalRunNavbar.find('.add-new')\n- let children = addNew.first().props().children as any\n-\nit('should show a shortcut if user has a permission', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const addNew = hospitalRunNavbar.find('.add-new')\n+ const { children } = addNew.first().props() as any\n+\nexpect(children[0].props.children).toEqual('patients.newPatient')\n})\n- // Without Lab or Incident permissions\n- addNew = wrapperNoLabIncidentPermission.find(HospitalRunNavbar).find('.add-new')\n- children = addNew.first().props().children as any\n-\nit('should not show a shortcut if user does not have a permission', () => {\n+ // exclude labs and incidents permissions\n+ const wrapper = setup(cloneDeep(allPermissions).slice(0, 6))\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const addNew = hospitalRunNavbar.find('.add-new')\n+ const { children } = addNew.first().props() as any\n+\nchildren.forEach((option: any) => {\nexpect(option.props.children).not.toEqual('labs.requests.new')\nexpect(option.props.children).not.toEqual('incidents.requests.new')\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test(navbar): each it gets its own wrapper |
288,350 | 31.05.2020 22:03:43 | -19,080 | 6d15f9fe91af0407066bba430e70d770a1a2fe96 | refactor(pagerequest): add new line
feat | [
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PageRequest.ts",
"new_path": "src/clients/db/PageRequest.ts",
"diff": "@@ -5,6 +5,7 @@ export default interface PageRequest {\npreviousPageInfo: { [key: string]: string | null } | undefined\ndirection?: 'previous' | 'next'\n}\n+\nexport const UnpagedRequest: PageRequest = {\nnumber: undefined,\nsize: undefined,\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(pagerequest): add new line
feat #1969 |
288,347 | 02.06.2020 15:36:21 | -7,200 | c0d31385b5b894455cad85f6a8b9af6c3ae52e88 | [i18n] add edit patient for all languages | [
{
"change_type": "MODIFY",
"old_path": "src/locales/de/translations/patients/index.ts",
"new_path": "src/locales/de/translations/patients/index.ts",
"diff": "@@ -3,6 +3,7 @@ export default {\nlabel: 'Patienten',\nviewPatients: 'Patienten anzeigen',\nviewPatient: 'Patient anzeigen',\n+ editPatient: 'Patient bearbeiten',\nnewPatient: 'Neuer Patient',\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/es/translations/patients/index.ts",
"new_path": "src/locales/es/translations/patients/index.ts",
"diff": "@@ -3,6 +3,7 @@ export default {\nlabel: 'Pacientes',\nviewPatients: 'Ver pacientes',\nviewPatient: 'Ver pacientes',\n+ editPatient: 'Editar paciente',\nnewPatient: 'Nuevo paciente',\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/id/translations/patients/index.ts",
"new_path": "src/locales/id/translations/patients/index.ts",
"diff": "@@ -3,6 +3,7 @@ export default {\nlabel: 'Pasien',\nviewPatients: 'Lihat Pasien',\nviewPatient: 'Lihat Pasien',\n+ editPatient: 'Ganti Pasien',\nnewPatient: 'Pasien Baru',\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/ptBr/translations/patients/index.ts",
"new_path": "src/locales/ptBr/translations/patients/index.ts",
"diff": "@@ -5,6 +5,7 @@ export default {\nviewPatients: 'Exibir pacientes',\nviewPatient: 'Ver paciente',\nnewPatient: 'Novo Paciente',\n+ editPatient: 'Mudar paciente',\nsuccessfullyCreated: 'Paciente criado com sucesso',\nsuccessfullyAddedNote: 'Adicionou uma nova nota com sucesso',\nsuccessfullyAddedRelatedPerson: 'Adicionou uma pessoa relacionada com sucesso',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | [i18n] add edit patient for all languages (#2028) |
288,333 | 02.06.2020 14:49:34 | 25,200 | 43cafa6da8334bf41440588ce71a27b42b73ef9d | feat(incident): Added Report Incident button | [
{
"change_type": "MODIFY",
"old_path": "src/incidents/list/ViewIncidents.tsx",
"new_path": "src/incidents/list/ViewIncidents.tsx",
"diff": "+import { Button } from '@hospitalrun/components'\nimport format from 'date-fns/format'\nimport React, { useEffect, useState } from 'react'\nimport { useTranslation } from 'react-i18next'\n@@ -6,6 +7,7 @@ import { useHistory } from 'react-router-dom'\nimport SelectWithLabelFormGroup from '../../components/input/SelectWithLableFormGroup'\nimport Incident from '../../model/Incident'\n+import { useButtonToolbarSetter } from '../../page-header/ButtonBarProvider'\nimport useTitle from '../../page-header/useTitle'\nimport { RootState } from '../../store'\nimport IncidentFilter from '../IncidentFilter'\n@@ -19,6 +21,25 @@ const ViewIncidents = () => {\nconst [searchFilter, setSearchFilter] = useState(IncidentFilter.reported)\nconst { incidents } = useSelector((state: RootState) => state.incidents)\n+ const setButtonToolBar = useButtonToolbarSetter()\n+ useEffect(() => {\n+ setButtonToolBar([\n+ <Button\n+ key=\"newIncidentButton\"\n+ outlined\n+ color=\"success\"\n+ icon=\"add\"\n+ onClick={() => history.push('/incidents/new')}\n+ >\n+ {t('incidents.reports.new')}\n+ </Button>,\n+ ])\n+\n+ return () => {\n+ setButtonToolBar([])\n+ }\n+ }, [dispatch, setButtonToolBar, t, history])\n+\nuseEffect(() => {\ndispatch(searchIncidents(searchFilter))\n}, [dispatch, searchFilter])\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(incident): Added Report Incident button |
288,323 | 19.05.2020 23:15:49 | 18,000 | 0aa0cf93b3f9e3153592684ce05babee2e0c5379 | feat(careplan): adds ability to add a new care plan | [
{
"change_type": "MODIFY",
"old_path": "src/components/input/SelectWithLableFormGroup.tsx",
"new_path": "src/components/input/SelectWithLableFormGroup.tsx",
"diff": "@@ -10,18 +10,37 @@ interface Props {\nvalue: string\nlabel: string\nname: string\n+ isRequired?: boolean\nisEditable?: boolean\noptions: Option[]\nonChange?: (event: React.ChangeEvent<HTMLSelectElement>) => void\n+ feedback?: string\n+ isInvalid?: boolean\n}\nconst SelectWithLabelFormGroup = (props: Props) => {\n- const { value, label, name, isEditable, options, onChange } = props\n+ const {\n+ value,\n+ label,\n+ name,\n+ isEditable,\n+ options,\n+ onChange,\n+ isRequired,\n+ feedback,\n+ isInvalid,\n+ } = props\nconst id = `${name}Select`\nreturn (\n<div className=\"form-group\">\n- <Label text={label} htmlFor={id} />\n- <Select disabled={!isEditable} onChange={onChange} value={value}>\n+ <Label text={label} htmlFor={id} isRequired={isRequired} />\n+ <Select\n+ disabled={!isEditable}\n+ onChange={onChange}\n+ value={value}\n+ feedback={feedback}\n+ isInvalid={isInvalid}\n+ >\n<option disabled value=\"\">\n-- Choose --\n</option>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -93,6 +93,18 @@ export default {\n},\nnoLabsMessage: 'No labs requests for this person.',\n},\n+ carePlan: {\n+ new: 'Add Care Plan',\n+ label: 'Care Plans',\n+ title: 'Title',\n+ description: 'Description',\n+ status: 'Status',\n+ condition: 'Condition',\n+ intent: 'Intent',\n+ startDate: 'Start Date',\n+ endDate: 'End Date',\n+ note: 'Note',\n+ },\ntypes: {\ncharity: 'Charity',\nprivate: 'Private',\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/model/CarePlan.ts",
"diff": "+export enum CarePlanStatus {\n+ Draft = 'draft',\n+ Active = 'active',\n+ OnHold = 'on hold',\n+ Revoked = 'revoked',\n+ Completed = 'completed',\n+ Unknown = 'unknown',\n+}\n+\n+export enum CarePlanIntent {\n+ Proposal = 'proposal',\n+ Plan = 'plan',\n+ Order = 'order',\n+ Option = 'option',\n+}\n+\n+export default interface CarePlan {\n+ id: string\n+ status: CarePlanStatus\n+ intent: CarePlanIntent\n+ title: string\n+ description: string\n+ startDate: string\n+ endDate: string\n+ createdOn: string\n+ diagnosisId: string\n+ note: string\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Patient.ts",
"new_path": "src/model/Patient.ts",
"diff": "import AbstractDBModel from './AbstractDBModel'\nimport Allergy from './Allergy'\n+import CarePlan from './CarePlan'\nimport ContactInformation from './ContactInformation'\nimport Diagnosis from './Diagnosis'\nimport Name from './Name'\n@@ -18,4 +19,5 @@ export default interface Patient extends AbstractDBModel, Name, ContactInformati\nallergies?: Allergy[]\ndiagnoses?: Diagnosis[]\nnotes?: Note[]\n+ carePlans: CarePlan[]\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/model/Permissions.ts",
"new_path": "src/model/Permissions.ts",
"diff": "@@ -14,6 +14,8 @@ enum Permissions {\nViewIncidents = 'read:incidents',\nViewIncident = 'read:incident',\nReportIncident = 'write:incident',\n+ AddCarePlan = 'write:care_plan',\n+ ReadCarePlan = 'read:care_plan',\n}\nexport default Permissions\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/patients/care-plans/AddCarePlanModal.tsx",
"diff": "+import { Modal, Column, Row } from '@hospitalrun/components'\n+import { addMonths } from 'date-fns'\n+import React, { useState, useEffect } from 'react'\n+import { useTranslation } from 'react-i18next'\n+import { useDispatch, useSelector } from 'react-redux'\n+\n+import DatePickerWithLabelFormGroup from '../../components/input/DatePickerWithLabelFormGroup'\n+import SelectWithLabelFormGroup from '../../components/input/SelectWithLableFormGroup'\n+import TextFieldWithLabelFormGroup from '../../components/input/TextFieldWithLabelFormGroup'\n+import TextInputWithLabelFormGroup from '../../components/input/TextInputWithLabelFormGroup'\n+import CarePlan, { CarePlanIntent, CarePlanStatus } from '../../model/CarePlan'\n+import { RootState } from '../../store'\n+import { addCarePlan } from '../patient-slice'\n+\n+interface Props {\n+ show: boolean\n+ onCloseButtonClick: () => void\n+}\n+\n+const initialCarePlanState = {\n+ title: '',\n+ description: '',\n+ startDate: new Date().toISOString(),\n+ endDate: addMonths(new Date(), 1).toISOString(),\n+ note: '',\n+ intent: '',\n+ status: '',\n+ diagnosisId: '',\n+}\n+\n+const AddCarePlanModal = (props: Props) => {\n+ const { show, onCloseButtonClick } = props\n+ const dispatch = useDispatch()\n+ const { t } = useTranslation()\n+ const { carePlanError, patient } = useSelector((state: RootState) => state.patient)\n+ const [carePlan, setCarePlan] = useState(initialCarePlanState)\n+\n+ useEffect(() => {\n+ setCarePlan(initialCarePlanState)\n+ }, [show])\n+\n+ const onFieldChange = (name: string, value: string) => {\n+ setCarePlan((previousCarePlan) => ({\n+ ...previousCarePlan,\n+ [name]: value,\n+ }))\n+ }\n+\n+ const onSaveButtonClick = () => {\n+ dispatch(addCarePlan(patient.id, carePlan as CarePlan))\n+ }\n+\n+ const onClose = () => {\n+ onCloseButtonClick()\n+ }\n+\n+ const body = (\n+ <>\n+ <form>\n+ <Row>\n+ <Column sm={12}>\n+ <TextInputWithLabelFormGroup\n+ isRequired\n+ value={carePlan.title}\n+ label={t('patient.carePlan.title')}\n+ name=\"title\"\n+ feedback={carePlanError?.title}\n+ isInvalid={!!carePlanError?.title}\n+ isEditable\n+ onChange={(event) => onFieldChange('title', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <TextFieldWithLabelFormGroup\n+ isRequired\n+ value={carePlan.description}\n+ label={t('patient.carePlan.description')}\n+ name=\"title\"\n+ feedback={carePlanError?.description}\n+ isInvalid={!!carePlanError?.description}\n+ isEditable\n+ onChange={(event) => onFieldChange('description', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.diagnosisId}\n+ label={t('patient.carePlan.condition')}\n+ name=\"title\"\n+ feedback={carePlanError?.condition}\n+ isInvalid={!!carePlanError?.condition}\n+ isEditable\n+ onChange={(event) => onFieldChange('diagnosisId', event.currentTarget.value)}\n+ options={patient.diagnoses?.map((d) => ({ label: d.name, value: d.id })) || []}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={6}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.status}\n+ label={t('patient.carePlangi.condition')}\n+ name=\"status\"\n+ feedback={carePlanError?.status}\n+ isInvalid={!!carePlanError?.status}\n+ isEditable\n+ options={Object.values(CarePlanStatus).map((v) => ({ label: v, value: v }))}\n+ onChange={(event) => onFieldChange('status', event.currentTarget.value)}\n+ />\n+ </Column>\n+ <Column sm={6}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.intent}\n+ label={t('patient.carePlan.intent')}\n+ name=\"intent\"\n+ feedback={carePlanError?.intent}\n+ isInvalid={!!carePlanError?.intent}\n+ isEditable\n+ options={Object.values(CarePlanIntent).map((v) => ({ label: v, value: v }))}\n+ onChange={(event) => onFieldChange('intent', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={6}>\n+ <DatePickerWithLabelFormGroup\n+ isRequired\n+ value={carePlan.startDate ? new Date(carePlan.startDate) : new Date()}\n+ label={t('patient.carePlan.startDate')}\n+ name=\"startDate\"\n+ feedback={carePlanError?.startDate}\n+ isInvalid={!!carePlanError?.startDate}\n+ isEditable\n+ onChange={(date) => onFieldChange('startDate', date.toISOString())}\n+ />\n+ </Column>\n+ <Column sm={6}>\n+ <DatePickerWithLabelFormGroup\n+ isRequired\n+ value={carePlan.endDate ? new Date(carePlan.endDate) : new Date()}\n+ label={t('patient.carePlan.endDate')}\n+ name=\"endDate\"\n+ feedback={carePlanError?.endDate}\n+ isInvalid={!!carePlanError?.endDate}\n+ isEditable\n+ onChange={(date) => onFieldChange('endDate', date.toISOString())}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <TextFieldWithLabelFormGroup\n+ isRequired\n+ value={carePlan.note}\n+ label={t('patient.carePlan.note')}\n+ name=\"note\"\n+ feedback={carePlanError?.note}\n+ isInvalid={!!carePlanError?.note}\n+ isEditable\n+ onChange={(event) => onFieldChange('note', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ </form>\n+ </>\n+ )\n+\n+ return (\n+ <Modal\n+ show={show}\n+ toggle={onClose}\n+ title={t('patient.carePlan.new')}\n+ body={body}\n+ closeButton={{\n+ children: t('actions.cancel'),\n+ color: 'danger',\n+ onClick: onClose,\n+ }}\n+ successButton={{\n+ children: t('patient.carePlan.new'),\n+ color: 'success',\n+ icon: 'add',\n+ iconLocation: 'left',\n+ onClick: onSaveButtonClick,\n+ }}\n+ />\n+ )\n+}\n+\n+export default AddCarePlanModal\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/patients/care-plans/CarePlanTab.tsx",
"diff": "+import { Button } from '@hospitalrun/components'\n+import format from 'date-fns/format'\n+import React, { useState } from 'react'\n+import { useTranslation } from 'react-i18next'\n+import { useSelector } from 'react-redux'\n+\n+import Permissions from '../../model/Permissions'\n+import { RootState } from '../../store'\n+import AddCarePlanModal from './AddCarePlanModal'\n+\n+interface Props {\n+ patientId: string\n+}\n+\n+export const CarePlanTab = (props: Props) => {\n+ const { t } = useTranslation()\n+\n+ const { permissions } = useSelector((state: RootState) => state.user)\n+ const { patient } = useSelector((state: RootState) => state.patient)\n+ const [showAddCarePlanModal, setShowAddCarePlanModal] = useState(false)\n+ const { patientId } = props\n+ console.log(patientId)\n+ console.log(patient.carePlans)\n+ return (\n+ <>\n+ <div className=\"row\">\n+ <div className=\"col-md-12 d-flex justify-content-end\">\n+ {permissions.includes(Permissions.AddCarePlan) && (\n+ <Button\n+ outlined\n+ color=\"success\"\n+ icon=\"add\"\n+ iconLocation=\"left\"\n+ onClick={() => setShowAddCarePlanModal(true)}\n+ >\n+ {t('patient.carePlan.new')}\n+ </Button>\n+ )}\n+ </div>\n+ </div>\n+ <br />\n+ <table className=\"table table-hover\">\n+ <thead className=\"thead-light \">\n+ <tr>\n+ <th>{t('patient.carePlan.title')}</th>\n+ <th>{t('patient.carePlan.startDate')}</th>\n+ <th>{t('patient.carePlan.endDate')}</th>\n+ <th>{t('patient.carePlan.status')}</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n+ {patient.carePlans?.map((carePlan) => (\n+ <tr key={carePlan.id}>\n+ <td>{carePlan.title}</td>\n+ <td>{format(new Date(carePlan.startDate), 'yyyy-MM-dd')}</td>\n+ <td>{format(new Date(carePlan.endDate), 'yyyy-MM-dd')}</td>\n+ <td>{carePlan.status}</td>\n+ </tr>\n+ ))}\n+ </tbody>\n+ </table>\n+ <AddCarePlanModal\n+ show={showAddCarePlanModal}\n+ onCloseButtonClick={() => setShowAddCarePlanModal(false)}\n+ />\n+ </>\n+ )\n+}\n+\n+export default CarePlanTab\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patient-slice.ts",
"new_path": "src/patients/patient-slice.ts",
"diff": "@@ -5,6 +5,7 @@ import validator from 'validator'\nimport PatientRepository from '../clients/db/PatientRepository'\nimport Allergy from '../model/Allergy'\n+import CarePlan from '../model/CarePlan'\nimport Diagnosis from '../model/Diagnosis'\nimport Note from '../model/Note'\nimport Patient from '../model/Patient'\n@@ -23,6 +24,7 @@ interface PatientState {\ndiagnosisError?: AddDiagnosisError\nnoteError?: AddNoteError\nrelatedPersonError?: AddRelatedPersonError\n+ carePlanError?: AddCarePlanError\n}\ninterface Error {\n@@ -59,6 +61,17 @@ interface AddNoteError {\nnote?: string\n}\n+interface AddCarePlanError {\n+ title?: string\n+ description?: string\n+ status?: string\n+ intent?: string\n+ startDate?: string\n+ endDate?: string\n+ note?: string\n+ condition?: string\n+}\n+\nconst initialState: PatientState = {\nstatus: 'loading',\nisUpdatedSuccessfully: false,\n@@ -70,6 +83,7 @@ const initialState: PatientState = {\ndiagnosisError: undefined,\nnoteError: undefined,\nrelatedPersonError: undefined,\n+ carePlanError: undefined,\n}\nfunction start(state: PatientState) {\n@@ -377,4 +391,21 @@ export const addNote = (\n}\n}\n+export const addCarePlan = (\n+ patientId: string,\n+ carePlan: CarePlan,\n+ onSuccess?: (patient: Patient) => void,\n+): AppThunk => async (dispatch) => {\n+ const patient = await PatientRepository.find(patientId)\n+ const carePlans = patient.carePlans || ([] as CarePlan[])\n+ carePlans.push({\n+ id: uuid(),\n+ createdOn: new Date(Date.now().valueOf()).toISOString(),\n+ ...carePlan,\n+ })\n+ patient.carePlans = carePlans\n+\n+ await dispatch(updatePatient(patient, onSuccess))\n+}\n+\nexport default patientSlice.reducer\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/view/ViewPatient.tsx",
"new_path": "src/patients/view/ViewPatient.tsx",
"diff": "@@ -19,6 +19,7 @@ import Note from '../notes/NoteTab'\nimport { fetchPatient } from '../patient-slice'\nimport RelatedPerson from '../related-persons/RelatedPersonTab'\nimport { getPatientFullName } from '../util/patient-name-util'\n+import CarePlanTab from \"../care-plans/CarePlanTab\";\nconst getPatientCode = (p: Patient): string => {\nif (p) {\n@@ -119,6 +120,11 @@ const ViewPatient = () => {\nlabel={t('patient.labs.label')}\nonClick={() => history.push(`/patients/${patient.id}/labs`)}\n/>\n+ <Tab\n+ active={location.pathname === `/patients/${patient.id}/care-plans`}\n+ label={t('patient.carePlan.label')}\n+ onClick={() => history.push(`/patients/${patient.id}/care-plans`)}\n+ />\n</TabsHeader>\n<Panel>\n<Route exact path=\"/patients/:id\">\n@@ -142,6 +148,9 @@ const ViewPatient = () => {\n<Route exact path=\"/patients/:id/labs\">\n<Labs patientId={patient.id} />\n</Route>\n+ <Route exact path=\"/patients/:id/care-plans\">\n+ <CarePlanTab patientId={patient.id} />\n+ </Route>\n</Panel>\n</div>\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "@@ -25,6 +25,8 @@ const initialState: UserState = {\nPermissions.ViewIncident,\nPermissions.ViewIncidents,\nPermissions.ReportIncident,\n+ Permissions.AddCarePlan,\n+ Permissions.ReadCarePlan\n],\nuser: {\nid: 'some-hardcoded-id',\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(careplan): adds ability to add a new care plan |
288,323 | 01.06.2020 23:04:47 | 18,000 | e96eb835c37c0d4174ee8a8878286fbabda309c8 | feat(care-plan): add care plan form and tests | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/patients/care-plans/CarePlanForm.test.tsx",
"diff": "+import '../../../__mocks__/matchMediaMock'\n+import { addDays } from 'date-fns'\n+import { mount } from 'enzyme'\n+import React from 'react'\n+import { act } from 'react-dom/test-utils'\n+\n+import CarePlan, { CarePlanIntent, CarePlanStatus } from '../../../model/CarePlan'\n+import Diagnosis from '../../../model/Diagnosis'\n+import Patient from '../../../model/Patient'\n+import CarePlanForm from '../../../patients/care-plans/CarePlanForm'\n+\n+describe('Care Plan Form', () => {\n+ let onCarePlanChangeSpy: any\n+ const diagnosis: Diagnosis = {\n+ id: '123',\n+ name: 'some diagnosis name',\n+ diagnosisDate: new Date().toISOString(),\n+ }\n+ const carePlan: CarePlan = {\n+ id: 'id',\n+ title: 'title',\n+ description: 'description',\n+ status: CarePlanStatus.Active,\n+ intent: CarePlanIntent.Option,\n+ startDate: new Date().toISOString(),\n+ endDate: new Date().toISOString(),\n+ diagnosisId: diagnosis.id,\n+ createdOn: new Date().toISOString(),\n+ note: 'note',\n+ }\n+ const setup = (disabled = false, initializeCarePlan = true, error?: any) => {\n+ onCarePlanChangeSpy = jest.fn()\n+ const mockPatient = { id: '123', diagnoses: [diagnosis] } as Patient\n+ const wrapper = mount(\n+ <CarePlanForm\n+ patient={mockPatient}\n+ onChange={onCarePlanChangeSpy}\n+ carePlan={initializeCarePlan ? carePlan : {}}\n+ disabled={disabled}\n+ carePlanError={error}\n+ />,\n+ )\n+ return { wrapper }\n+ }\n+\n+ it('should render a title input', () => {\n+ const { wrapper } = setup()\n+\n+ const titleInput = wrapper.findWhere((w) => w.prop('name') === 'title')\n+\n+ expect(titleInput).toHaveLength(1)\n+ expect(titleInput.prop('patient.carePlan.title'))\n+ expect(titleInput.prop('isRequired')).toBeTruthy()\n+ expect(titleInput.prop('value')).toEqual(carePlan.title)\n+ })\n+\n+ it('should call the on change handler when condition changes', () => {\n+ const expectedNewTitle = 'some new title'\n+ const { wrapper } = setup(false, false)\n+ act(() => {\n+ const titleInput = wrapper.findWhere((w) => w.prop('name') === 'title')\n+ const onChange = titleInput.prop('onChange') as any\n+ onChange({ currentTarget: { value: expectedNewTitle } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ title: expectedNewTitle })\n+ })\n+\n+ it('should render a description input', () => {\n+ const { wrapper } = setup()\n+\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+\n+ expect(descriptionInput).toHaveLength(1)\n+ expect(descriptionInput.prop('patient.carePlan.description'))\n+ expect(descriptionInput.prop('isRequired')).toBeTruthy()\n+ expect(descriptionInput.prop('value')).toEqual(carePlan.description)\n+ })\n+\n+ it('should call the on change handler when condition changes', () => {\n+ const expectedNewDescription = 'some new description'\n+ const { wrapper } = setup(false, false)\n+ act(() => {\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+ const onChange = descriptionInput.prop('onChange') as any\n+ onChange({ currentTarget: { value: expectedNewDescription } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ description: expectedNewDescription })\n+ })\n+\n+ it('should render a condition selector with the diagnoses from the patient', () => {\n+ const { wrapper } = setup()\n+\n+ const conditionSelector = wrapper.findWhere((w) => w.prop('name') === 'condition')\n+\n+ expect(conditionSelector).toHaveLength(1)\n+ expect(conditionSelector.prop('patient.carePlan.condition'))\n+ expect(conditionSelector.prop('isRequired')).toBeTruthy()\n+ expect(conditionSelector.prop('value')).toEqual(carePlan.diagnosisId)\n+ expect(conditionSelector.prop('options')).toEqual([\n+ { value: diagnosis.id, label: diagnosis.name },\n+ ])\n+ })\n+\n+ it('should call the on change handler when condition changes', () => {\n+ const expectedNewCondition = 'some new condition'\n+ const { wrapper } = setup(false, false)\n+ act(() => {\n+ const conditionSelector = wrapper.findWhere((w) => w.prop('name') === 'condition')\n+ const onChange = conditionSelector.prop('onChange') as any\n+ onChange({ currentTarget: { value: expectedNewCondition } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ diagnosisId: expectedNewCondition })\n+ })\n+\n+ it('should render a status selector', () => {\n+ const { wrapper } = setup()\n+\n+ const statusSelector = wrapper.findWhere((w) => w.prop('name') === 'status')\n+\n+ expect(statusSelector).toHaveLength(1)\n+ expect(statusSelector.prop('patient.carePlan.status'))\n+ expect(statusSelector.prop('isRequired')).toBeTruthy()\n+ expect(statusSelector.prop('value')).toEqual(carePlan.status)\n+ expect(statusSelector.prop('options')).toEqual(\n+ Object.values(CarePlanStatus).map((v) => ({ label: v, value: v })),\n+ )\n+ })\n+\n+ it('should call the on change handler when status changes', () => {\n+ const expectedNewStatus = CarePlanStatus.Revoked\n+ const { wrapper } = setup(false, false)\n+ act(() => {\n+ const statusSelector = wrapper.findWhere((w) => w.prop('name') === 'status')\n+ const onChange = statusSelector.prop('onChange') as any\n+ onChange({ currentTarget: { value: expectedNewStatus } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ status: expectedNewStatus })\n+ })\n+\n+ it('should render an intent selector', () => {\n+ const { wrapper } = setup()\n+\n+ const intentSelector = wrapper.findWhere((w) => w.prop('name') === 'intent')\n+\n+ expect(intentSelector).toHaveLength(1)\n+ expect(intentSelector.prop('patient.carePlan.intent'))\n+ expect(intentSelector.prop('isRequired')).toBeTruthy()\n+ expect(intentSelector.prop('value')).toEqual(carePlan.intent)\n+ expect(intentSelector.prop('options')).toEqual(\n+ Object.values(CarePlanIntent).map((v) => ({ label: v, value: v })),\n+ )\n+ })\n+\n+ it('should call the on change handler when intent changes', () => {\n+ const newIntent = CarePlanIntent.Proposal\n+ const { wrapper } = setup(false, false)\n+ act(() => {\n+ const intentSelector = wrapper.findWhere((w) => w.prop('name') === 'intent')\n+ const onChange = intentSelector.prop('onChange') as any\n+ onChange({ currentTarget: { value: newIntent } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ intent: newIntent })\n+ })\n+\n+ it('should render a start date picker', () => {\n+ const { wrapper } = setup()\n+\n+ const startDatePicker = wrapper.findWhere((w) => w.prop('name') === 'startDate')\n+\n+ expect(startDatePicker).toHaveLength(1)\n+ expect(startDatePicker.prop('patient.carePlan.startDate'))\n+ expect(startDatePicker.prop('isRequired')).toBeTruthy()\n+ expect(startDatePicker.prop('value')).toEqual(new Date(carePlan.startDate))\n+ })\n+\n+ it('should call the on change handler when start date changes', () => {\n+ const expectedNewStartDate = addDays(1, new Date().getDate())\n+ const { wrapper } = setup(false, false)\n+\n+ const startDatePicker = wrapper.findWhere((w) => w.prop('name') === 'startDate')\n+ act(() => {\n+ const onChange = startDatePicker.prop('onChange') as any\n+ onChange(expectedNewStartDate)\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({\n+ startDate: expectedNewStartDate.toISOString(),\n+ })\n+ })\n+\n+ it('should render an end date picker', () => {\n+ const { wrapper } = setup()\n+\n+ const endDatePicker = wrapper.findWhere((w) => w.prop('name') === 'endDate')\n+\n+ expect(endDatePicker).toHaveLength(1)\n+ expect(endDatePicker.prop('patient.carePlan.endDate'))\n+ expect(endDatePicker.prop('isRequired')).toBeTruthy()\n+ expect(endDatePicker.prop('value')).toEqual(new Date(carePlan.endDate))\n+ })\n+\n+ it('should call the on change handler when end date changes', () => {\n+ const expectedNewEndDate = addDays(1, new Date().getDate())\n+ const { wrapper } = setup(false, false)\n+\n+ const endDatePicker = wrapper.findWhere((w) => w.prop('name') === 'endDate')\n+ act(() => {\n+ const onChange = endDatePicker.prop('onChange') as any\n+ onChange(expectedNewEndDate)\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({\n+ endDate: expectedNewEndDate.toISOString(),\n+ })\n+ })\n+\n+ it('should render a note input', () => {\n+ const { wrapper } = setup()\n+\n+ const noteInput = wrapper.findWhere((w) => w.prop('name') === 'note')\n+ expect(noteInput).toHaveLength(1)\n+ expect(noteInput.prop('patient.carePlan.note'))\n+ expect(noteInput.prop('isRequired')).toBeTruthy()\n+ expect(noteInput.prop('value')).toEqual(carePlan.note)\n+ })\n+\n+ it('should call the on change handler when note changes', () => {\n+ const expectedNewNote = 'some new note'\n+ const { wrapper } = setup(false, false)\n+\n+ const noteInput = wrapper.findWhere((w) => w.prop('name') === 'note')\n+ act(() => {\n+ const onChange = noteInput.prop('onChange') as any\n+ onChange({ currentTarget: { value: expectedNewNote } })\n+ })\n+\n+ expect(onCarePlanChangeSpy).toHaveBeenCalledWith({ note: expectedNewNote })\n+ })\n+\n+ it('should render all of the fields as disabled if the form is disabled', () => {\n+ const { wrapper } = setup(true)\n+ const titleInput = wrapper.findWhere((w) => w.prop('name') === 'title')\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+ const conditionSelector = wrapper.findWhere((w) => w.prop('name') === 'condition')\n+ const statusSelector = wrapper.findWhere((w) => w.prop('name') === 'status')\n+ const intentSelector = wrapper.findWhere((w) => w.prop('name') === 'intent')\n+ const startDatePicker = wrapper.findWhere((w) => w.prop('name') === 'startDate')\n+ const endDatePicker = wrapper.findWhere((w) => w.prop('name') === 'endDate')\n+ const noteInput = wrapper.findWhere((w) => w.prop('name') === 'note')\n+\n+ expect(titleInput.prop('isEditable')).toBeFalsy()\n+ expect(descriptionInput.prop('isEditable')).toBeFalsy()\n+ expect(conditionSelector.prop('isEditable')).toBeFalsy()\n+ expect(statusSelector.prop('isEditable')).toBeFalsy()\n+ expect(intentSelector.prop('isEditable')).toBeFalsy()\n+ expect(startDatePicker.prop('isEditable')).toBeFalsy()\n+ expect(endDatePicker.prop('isEditable')).toBeFalsy()\n+ expect(noteInput.prop('isEditable')).toBeFalsy()\n+ })\n+\n+ it('should render the form fields in an error state', () => {\n+ const expectedError = {\n+ title: 'some title error',\n+ description: 'some description error',\n+ status: 'some status error',\n+ intent: 'some intent error',\n+ startDate: 'some start date error',\n+ endDate: 'some end date error',\n+ note: 'some note error',\n+ condition: 'some condition error',\n+ }\n+\n+ const { wrapper } = setup(false, false, expectedError)\n+\n+ const titleInput = wrapper.findWhere((w) => w.prop('name') === 'title')\n+ const descriptionInput = wrapper.findWhere((w) => w.prop('name') === 'description')\n+ const conditionSelector = wrapper.findWhere((w) => w.prop('name') === 'condition')\n+ const statusSelector = wrapper.findWhere((w) => w.prop('name') === 'status')\n+ const intentSelector = wrapper.findWhere((w) => w.prop('name') === 'intent')\n+ const startDatePicker = wrapper.findWhere((w) => w.prop('name') === 'startDate')\n+ const endDatePicker = wrapper.findWhere((w) => w.prop('name') === 'endDate')\n+ const noteInput = wrapper.findWhere((w) => w.prop('name') === 'note')\n+\n+ expect(titleInput.prop('isInvalid')).toBeTruthy()\n+ expect(titleInput.prop('feedback')).toEqual(expectedError.title)\n+\n+ expect(descriptionInput.prop('isInvalid')).toBeTruthy()\n+ expect(descriptionInput.prop('feedback')).toEqual(expectedError.description)\n+\n+ expect(conditionSelector.prop('isInvalid')).toBeTruthy()\n+ expect(conditionSelector.prop('feedback')).toEqual(expectedError.condition)\n+\n+ expect(statusSelector.prop('isInvalid')).toBeTruthy()\n+ expect(statusSelector.prop('feedback')).toEqual(expectedError.status)\n+\n+ expect(intentSelector.prop('isInvalid')).toBeTruthy()\n+ expect(intentSelector.prop('feedback')).toEqual(expectedError.intent)\n+\n+ expect(startDatePicker.prop('isInvalid')).toBeTruthy()\n+ expect(startDatePicker.prop('feedback')).toEqual(expectedError.startDate)\n+\n+ expect(endDatePicker.prop('isInvalid')).toBeTruthy()\n+ expect(endDatePicker.prop('feedback')).toEqual(expectedError.endDate)\n+\n+ expect(noteInput.prop('isInvalid')).toBeTruthy()\n+ expect(noteInput.prop('feedback')).toEqual(expectedError.note)\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/patients/care-plans/CarePlanForm.tsx",
"diff": "+import { Column, Row } from '@hospitalrun/components'\n+import React from 'react'\n+import { useTranslation } from 'react-i18next'\n+\n+import DatePickerWithLabelFormGroup from '../../components/input/DatePickerWithLabelFormGroup'\n+import SelectWithLabelFormGroup from '../../components/input/SelectWithLableFormGroup'\n+import TextFieldWithLabelFormGroup from '../../components/input/TextFieldWithLabelFormGroup'\n+import TextInputWithLabelFormGroup from '../../components/input/TextInputWithLabelFormGroup'\n+import CarePlan, { CarePlanIntent, CarePlanStatus } from '../../model/CarePlan'\n+import Patient from '../../model/Patient'\n+\n+interface Error {\n+ title?: string\n+ description?: string\n+ status?: string\n+ intent?: string\n+ startDate?: string\n+ endDate?: string\n+ note?: string\n+ condition?: string\n+}\n+interface Props {\n+ patient: Patient\n+ carePlan: Partial<CarePlan>\n+ carePlanError?: Error\n+ onChange: (newCarePlan: Partial<CarePlan>) => void\n+ disabled: boolean\n+}\n+\n+const CarePlanForm = (props: Props) => {\n+ const { t } = useTranslation()\n+ const { patient, carePlan, carePlanError, disabled, onChange } = props\n+\n+ const onFieldChange = (name: string, value: string | CarePlanStatus | CarePlanIntent) => {\n+ const newCarePlan = {\n+ ...carePlan,\n+ [name]: value,\n+ }\n+ onChange(newCarePlan)\n+ }\n+\n+ return (\n+ <form>\n+ <Row>\n+ <Column sm={12}>\n+ <TextInputWithLabelFormGroup\n+ isRequired\n+ value={carePlan.title}\n+ label={t('patient.carePlan.title')}\n+ name=\"title\"\n+ feedback={carePlanError?.title}\n+ isInvalid={!!carePlanError?.title}\n+ isEditable={!disabled}\n+ onChange={(event) => onFieldChange('title', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <TextFieldWithLabelFormGroup\n+ isRequired\n+ value={carePlan.description}\n+ label={t('patient.carePlan.description')}\n+ name=\"description\"\n+ feedback={carePlanError?.description}\n+ isInvalid={!!carePlanError?.description}\n+ isEditable={!disabled}\n+ onChange={(event) => onFieldChange('description', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.diagnosisId}\n+ label={t('patient.carePlan.condition')}\n+ name=\"condition\"\n+ feedback={carePlanError?.condition}\n+ isInvalid={!!carePlanError?.condition}\n+ isEditable={!disabled}\n+ onChange={(event) => onFieldChange('diagnosisId', event.currentTarget.value)}\n+ options={patient.diagnoses?.map((d) => ({ label: d.name, value: d.id })) || []}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={6}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.status}\n+ label={t('patient.carePlan.status')}\n+ name=\"status\"\n+ feedback={carePlanError?.status}\n+ isInvalid={!!carePlanError?.status}\n+ isEditable={!disabled}\n+ options={Object.values(CarePlanStatus).map((v) => ({ label: v, value: v }))}\n+ onChange={(event) => onFieldChange('status', event.currentTarget.value)}\n+ />\n+ </Column>\n+ <Column sm={6}>\n+ <SelectWithLabelFormGroup\n+ isRequired\n+ value={carePlan.intent}\n+ label={t('patient.carePlan.intent')}\n+ name=\"intent\"\n+ feedback={carePlanError?.intent}\n+ isInvalid={!!carePlanError?.intent}\n+ isEditable={!disabled}\n+ options={Object.values(CarePlanIntent).map((v) => ({ label: v, value: v }))}\n+ onChange={(event) => onFieldChange('intent', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={6}>\n+ <DatePickerWithLabelFormGroup\n+ isRequired\n+ value={carePlan.startDate ? new Date(carePlan.startDate) : new Date()}\n+ label={t('patient.carePlan.startDate')}\n+ name=\"startDate\"\n+ feedback={carePlanError?.startDate}\n+ isInvalid={!!carePlanError?.startDate}\n+ isEditable={!disabled}\n+ onChange={(date) => onFieldChange('startDate', date.toISOString())}\n+ />\n+ </Column>\n+ <Column sm={6}>\n+ <DatePickerWithLabelFormGroup\n+ isRequired\n+ value={carePlan.endDate ? new Date(carePlan.endDate) : new Date()}\n+ label={t('patient.carePlan.endDate')}\n+ name=\"endDate\"\n+ feedback={carePlanError?.endDate}\n+ isInvalid={!!carePlanError?.endDate}\n+ isEditable={!disabled}\n+ onChange={(date) => onFieldChange('endDate', date.toISOString())}\n+ />\n+ </Column>\n+ </Row>\n+ <Row>\n+ <Column sm={12}>\n+ <TextFieldWithLabelFormGroup\n+ isRequired\n+ value={carePlan.note}\n+ label={t('patient.carePlan.note')}\n+ name=\"note\"\n+ feedback={carePlanError?.note}\n+ isInvalid={!!carePlanError?.note}\n+ isEditable={!disabled}\n+ onChange={(event) => onFieldChange('note', event.currentTarget.value)}\n+ />\n+ </Column>\n+ </Row>\n+ </form>\n+ )\n+}\n+\n+CarePlanForm.defaultProps = {\n+ disabled: false,\n+}\n+\n+export default CarePlanForm\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(care-plan): add care plan form and tests |
288,323 | 03.06.2020 22:15:58 | 18,000 | 72a5bede7862c72eecb068c0c20141ef619a8f27 | feat(care plan): fix internationalization | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/patient-slice.test.ts",
"new_path": "src/__tests__/patients/patient-slice.test.ts",
"diff": "@@ -686,15 +686,15 @@ describe('patients slice', () => {\nit('should validate the required fields', async () => {\nconst expectedError = {\n- message: 'patient.carePlans.error.unableToAdd',\n- title: 'patient.carePlans.error.titleRequired',\n- description: 'patient.carePlans.error.descriptionRequired',\n- status: 'patient.carePlans.error.statusRequired',\n- intent: 'patient.carePlans.error.intentRequired',\n- startDate: 'patient.carePlans.error.startDateRequired',\n- endDate: 'patient.carePlans.error.endDateRequired',\n- condition: 'patient.carePlans.error.conditionRequired',\n- note: 'patient.carePlans.error.noteRequired',\n+ message: 'patient.carePlan.error.unableToAdd',\n+ title: 'patient.carePlan.error.titleRequired',\n+ description: 'patient.carePlan.error.descriptionRequired',\n+ status: 'patient.carePlan.error.statusRequired',\n+ intent: 'patient.carePlan.error.intentRequired',\n+ startDate: 'patient.carePlan.error.startDateRequired',\n+ endDate: 'patient.carePlan.error.endDateRequired',\n+ condition: 'patient.carePlan.error.conditionRequired',\n+ note: 'patient.carePlan.error.noteRequired',\n}\nconst store = mockStore()\nconst expectedCarePlan = {} as CarePlan\n@@ -719,7 +719,7 @@ describe('patients slice', () => {\nexpect(store.getActions()[0]).toEqual(\naddCarePlanError(\nexpect.objectContaining({\n- endDate: 'patient.carePlans.error.endDateMustBeAfterStartDate',\n+ endDate: 'patient.carePlan.error.endDateMustBeAfterStartDate',\n}),\n),\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/patient/index.ts",
"new_path": "src/locales/enUs/translations/patient/index.ts",
"diff": "@@ -104,6 +104,16 @@ export default {\nstartDate: 'Start Date',\nendDate: 'End Date',\nnote: 'Note',\n+ error: {\n+ unableToAdd: 'Unable to add a new care plan.',\n+ titleRequired: 'Title is required.',\n+ descriptionRequired: 'Description is required.',\n+ conditionRequired: 'Condition is required.',\n+ statusRequired: 'Status is required.',\n+ intentRequired: 'Intent is required.',\n+ startDate: 'Start date is required.',\n+ endDate: 'End date is required',\n+ }\n},\ntypes: {\ncharity: 'Charity',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/care-plans/CarePlanForm.tsx",
"new_path": "src/patients/care-plans/CarePlanForm.tsx",
"diff": "@@ -44,7 +44,7 @@ const CarePlanForm = (props: Props) => {\nreturn (\n<form>\n- {carePlanError?.message && <Alert color=\"danger\" message={carePlanError.message} />}\n+ {carePlanError?.message && <Alert color=\"danger\" message={t(carePlanError.message)} />}\n<Row>\n<Column sm={12}>\n<TextInputWithLabelFormGroup\n@@ -52,7 +52,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.title}\nlabel={t('patient.carePlan.title')}\nname=\"title\"\n- feedback={carePlanError?.title}\n+ feedback={t(carePlanError?.title || '')}\nisInvalid={!!carePlanError?.title}\nisEditable={!disabled}\nonChange={(event) => onFieldChange('title', event.currentTarget.value)}\n@@ -66,7 +66,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.description}\nlabel={t('patient.carePlan.description')}\nname=\"description\"\n- feedback={carePlanError?.description}\n+ feedback={t(carePlanError?.description || '')}\nisInvalid={!!carePlanError?.description}\nisEditable={!disabled}\nonChange={(event) => onFieldChange('description', event.currentTarget.value)}\n@@ -80,7 +80,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.diagnosisId}\nlabel={t('patient.carePlan.condition')}\nname=\"condition\"\n- feedback={carePlanError?.condition}\n+ feedback={t(carePlanError?.condition || '')}\nisInvalid={!!carePlanError?.condition}\nisEditable={!disabled}\nonChange={(event) => onFieldChange('diagnosisId', event.currentTarget.value)}\n@@ -95,7 +95,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.status}\nlabel={t('patient.carePlan.status')}\nname=\"status\"\n- feedback={carePlanError?.status}\n+ feedback={t(carePlanError?.status || '')}\nisInvalid={!!carePlanError?.status}\nisEditable={!disabled}\noptions={Object.values(CarePlanStatus).map((v) => ({ label: v, value: v }))}\n@@ -108,7 +108,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.intent}\nlabel={t('patient.carePlan.intent')}\nname=\"intent\"\n- feedback={carePlanError?.intent}\n+ feedback={t(carePlanError?.intent || '')}\nisInvalid={!!carePlanError?.intent}\nisEditable={!disabled}\noptions={Object.values(CarePlanIntent).map((v) => ({ label: v, value: v }))}\n@@ -123,7 +123,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.startDate ? new Date(carePlan.startDate) : new Date()}\nlabel={t('patient.carePlan.startDate')}\nname=\"startDate\"\n- feedback={carePlanError?.startDate}\n+ feedback={t(carePlanError?.startDate || '')}\nisInvalid={!!carePlanError?.startDate}\nisEditable={!disabled}\nonChange={(date) => onFieldChange('startDate', date.toISOString())}\n@@ -135,7 +135,7 @@ const CarePlanForm = (props: Props) => {\nvalue={carePlan.endDate ? new Date(carePlan.endDate) : new Date()}\nlabel={t('patient.carePlan.endDate')}\nname=\"endDate\"\n- feedback={carePlanError?.endDate}\n+ feedback={t(carePlanError?.endDate || '')}\nisInvalid={!!carePlanError?.endDate}\nisEditable={!disabled}\nonChange={(date) => onFieldChange('endDate', date.toISOString())}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/patient-slice.ts",
"new_path": "src/patients/patient-slice.ts",
"diff": "@@ -401,41 +401,41 @@ function validateCarePlan(carePlan: CarePlan): AddCarePlanError {\nconst error: AddCarePlanError = {}\nif (!carePlan.title) {\n- error.title = 'patient.carePlans.error.titleRequired'\n+ error.title = 'patient.carePlan.error.titleRequired'\n}\nif (!carePlan.description) {\n- error.description = 'patient.carePlans.error.descriptionRequired'\n+ error.description = 'patient.carePlan.error.descriptionRequired'\n}\nif (!carePlan.status) {\n- error.status = 'patient.carePlans.error.statusRequired'\n+ error.status = 'patient.carePlan.error.statusRequired'\n}\nif (!carePlan.intent) {\n- error.intent = 'patient.carePlans.error.intentRequired'\n+ error.intent = 'patient.carePlan.error.intentRequired'\n}\nif (!carePlan.startDate) {\n- error.startDate = 'patient.carePlans.error.startDateRequired'\n+ error.startDate = 'patient.carePlan.error.startDateRequired'\n}\nif (!carePlan.endDate) {\n- error.endDate = 'patient.carePlans.error.endDateRequired'\n+ error.endDate = 'patient.carePlan.error.endDateRequired'\n}\nif (carePlan.startDate && carePlan.endDate) {\nif (isBefore(new Date(carePlan.endDate), new Date(carePlan.startDate))) {\n- error.endDate = 'patient.carePlans.error.endDateMustBeAfterStartDate'\n+ error.endDate = 'patient.carePlan.error.endDateMustBeAfterStartDate'\n}\n}\nif (!carePlan.diagnosisId) {\n- error.condition = 'patient.carePlans.error.conditionRequired'\n+ error.condition = 'patient.carePlan.error.conditionRequired'\n}\nif (!carePlan.note) {\n- error.note = 'patient.carePlans.error.noteRequired'\n+ error.note = 'patient.carePlan.error.noteRequired'\n}\nreturn error\n@@ -459,7 +459,7 @@ export const addCarePlan = (\nawait dispatch(updatePatient(patient, onSuccess))\n} else {\n- carePlanError.message = 'patient.carePlans.error.unableToAdd'\n+ carePlanError.message = 'patient.carePlan.error.unableToAdd'\ndispatch(addCarePlanError(carePlanError))\n}\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(care plan): fix internationalization |
288,364 | 07.06.2020 07:01:55 | -7,200 | fa5bcb6a86ae082de789aca84a938bc7f99a8ca7 | feat(network-status): Notify users when they're working offline | [
{
"change_type": "MODIFY",
"old_path": "src/HospitalRun.tsx",
"new_path": "src/HospitalRun.tsx",
"diff": "@@ -5,6 +5,7 @@ import { Switch, Route } from 'react-router-dom'\nimport Breadcrumbs from './breadcrumbs/Breadcrumbs'\nimport Navbar from './components/Navbar'\n+import { NetworkStatusMessage } from './components/network-status'\nimport PrivateRoute from './components/PrivateRoute'\nimport Sidebar from './components/Sidebar'\nimport Dashboard from './dashboard/Dashboard'\n@@ -23,6 +24,7 @@ const HospitalRun = () => {\nreturn (\n<div>\n+ <NetworkStatusMessage />\n<Navbar />\n<div className=\"container-fluid\">\n<Sidebar />\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/__tests__/components/network-status/NetworkStatusMessage.test.tsx",
"diff": "+import { render, shallow } from 'enzyme'\n+import React from 'react'\n+\n+import { useTranslation } from '../../../__mocks__/react-i18next'\n+import { NetworkStatusMessage } from '../../../components/network-status'\n+import { useNetworkStatus } from '../../../components/network-status/useNetworkStatus'\n+\n+jest.mock('../../../components/network-status/useNetworkStatus')\n+const useNetworkStatusMock = (useNetworkStatus as unknown) as jest.MockInstance<\n+ ReturnType<typeof useNetworkStatus>,\n+ any\n+>\n+\n+const englishTranslationsMock = {\n+ 'networkStatus.offline': 'you are working in offline mode',\n+ 'networkStatus.online': 'you are back online',\n+}\n+\n+const useTranslationReturnValue = useTranslation() as any\n+useTranslationReturnValue.t = (key: keyof typeof englishTranslationsMock) =>\n+ englishTranslationsMock[key]\n+const { t } = useTranslationReturnValue\n+\n+describe('NetworkStatusMessage', () => {\n+ it('returns null if the app has always been online', () => {\n+ useNetworkStatusMock.mockReturnValue({\n+ isOnline: true,\n+ wasOffline: false,\n+ })\n+ const wrapper = shallow(<NetworkStatusMessage />)\n+ expect(wrapper.equals(null as any)).toBe(true)\n+ })\n+ it(`shows the message \"${t('networkStatus.offline')}\" if the app goes offline`, () => {\n+ useNetworkStatusMock.mockReturnValue({\n+ isOnline: false,\n+ wasOffline: false,\n+ })\n+ const wrapper = render(<NetworkStatusMessage />)\n+ expect(wrapper.text()).toContain(t('networkStatus.offline'))\n+ })\n+ it(`shows the message \"${t(\n+ 'networkStatus.online',\n+ )}\" if the app goes back online after it was offline`, () => {\n+ useNetworkStatusMock.mockReturnValue({\n+ isOnline: true,\n+ wasOffline: true,\n+ })\n+ const wrapper = render(<NetworkStatusMessage />)\n+ expect(wrapper.text()).toContain(t('networkStatus.online'))\n+ })\n+})\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/components/network-status/NetworkStatusMessage.tsx",
"diff": "+import React, { useState } from 'react'\n+import { useTranslation } from 'react-i18next'\n+\n+import { useNetworkStatus } from './useNetworkStatus'\n+\n+const ONLINE_COLOR = 'rgba(0, 255, 0, 0.55)'\n+const OFFLINE_COLOR = 'rgba(255, 0, 0, 0.65)'\n+const OPACITY_TRANSITION_TIME = 4000\n+const BASE_STYLE = {\n+ height: '50px',\n+ pointerEvents: 'none' as 'none',\n+ transition: `opacity ${OPACITY_TRANSITION_TIME}ms ease-in`,\n+}\n+\n+export const NetworkStatusMessage = () => {\n+ const { t } = useTranslation()\n+ const { isOnline, wasOffline } = useNetworkStatus()\n+ const [shouldRender, setShouldRender] = useState(true)\n+ const [opacity, setOpacity] = useState(1)\n+\n+ if (isOnline && !wasOffline) {\n+ return null\n+ }\n+\n+ if (!isOnline && opacity !== 1) {\n+ setShouldRender(true)\n+ setOpacity(1)\n+ }\n+\n+ if (isOnline && wasOffline && opacity !== 0) {\n+ setOpacity(0)\n+ setTimeout(() => {\n+ setShouldRender(false)\n+ }, OPACITY_TRANSITION_TIME)\n+ }\n+\n+ if (!shouldRender) {\n+ return null\n+ }\n+\n+ const style = {\n+ ...BASE_STYLE,\n+ backgroundColor: isOnline ? ONLINE_COLOR : OFFLINE_COLOR,\n+ opacity,\n+ }\n+\n+ return (\n+ <div\n+ className={`fixed-bottom d-flex justify-content-center align-items-center ${\n+ isOnline ? 'online' : 'offline'\n+ }`}\n+ style={style}\n+ >\n+ {isOnline ? t('networkStatus.online') : t('networkStatus.offline')}\n+ </div>\n+ )\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/components/network-status/index.ts",
"diff": "+export { NetworkStatusMessage } from './NetworkStatusMessage'\n+export { useNetworkStatus } from './useNetworkStatus'\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/components/network-status/types.ts",
"diff": "+export interface NetworkStatus {\n+ isOnline: boolean\n+ wasOffline: boolean\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/components/network-status/useNetworkStatus.ts",
"diff": "+import { useState, useEffect } from 'react'\n+\n+import { NetworkStatus } from './types'\n+\n+export const useNetworkStatus = (): NetworkStatus => {\n+ const isOnline = navigator.onLine\n+ const [networkStatus, setNetworkStatus] = useState({\n+ isOnline,\n+ wasOffline: !isOnline,\n+ })\n+ const handleOnline = () => {\n+ setNetworkStatus((prevState) => ({ ...prevState, isOnline: true }))\n+ }\n+ const handleOffline = () => {\n+ setNetworkStatus((prevState) => ({ ...prevState, isOnline: false, wasOffline: true }))\n+ }\n+ useEffect(() => {\n+ window.addEventListener('online', handleOnline)\n+ window.addEventListener('offline', handleOffline)\n+\n+ return () => {\n+ window.removeEventListener('online', handleOnline)\n+ window.removeEventListener('offline', handleOffline)\n+ }\n+ }, [])\n+\n+ return networkStatus\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/locales/enUs/translations/index.ts",
"new_path": "src/locales/enUs/translations/index.ts",
"diff": "@@ -2,6 +2,7 @@ import actions from './actions'\nimport dashboard from './dashboard'\nimport incidents from './incidents'\nimport labs from './labs'\n+import networkStatus from './network-status'\nimport patient from './patient'\nimport patients from './patients'\nimport scheduling from './scheduling'\n@@ -12,6 +13,7 @@ import states from './states'\nexport default {\n...actions,\n...dashboard,\n+ ...networkStatus,\n...patient,\n...patients,\n...scheduling,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/enUs/translations/network-status/index.ts",
"diff": "+export default {\n+ networkStatus: {\n+ offline: 'you are working in offline mode',\n+ online: 'you are back online',\n+ },\n+}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | feat(network-status): Notify users when they're working offline (#2109) |
288,347 | 08.06.2020 16:03:14 | -7,200 | b3da0ee430d127b697e58a4a760691342a3253b7 | refactor(checktranslations): run script as js file
now ts-node library is no need anymore because the script is compiled to javascript | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "build\n+bin\n# Logs\nlogs\n*.log\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"redux-mock-store\": \"~1.5.4\",\n\"source-map-explorer\": \"^2.2.2\",\n\"standard-version\": \"~8.0.0\",\n- \"ts-jest\": \"~24.3.0\",\n- \"ts-node\": \"^8.10.0\"\n+ \"ts-jest\": \"~24.3.0\"\n},\n\"scripts\": {\n\"analyze\": \"source-map-explorer 'build/static/js/*.js'\",\n\"lint-staged\": \"lint-staged\",\n\"commitlint\": \"commitlint\",\n\"coveralls\": \"npm run test:ci -- --coverage --watchAll=false && cat ./coverage/lcov.info\",\n- \"translation:check\": \"ts-node-script scripts/checkMissingTranslations.ts\"\n+ \"translation:check\": \"cd scripts && tsc && node ../bin/scripts/checkMissingTranslations.js\"\n},\n\"browserslist\": {\n\"production\": [\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/checkMissingTranslations.ts",
"new_path": "scripts/checkMissingTranslations.ts",
"diff": "import chalk from 'chalk'\n-import { Resource, ResourceKey } from 'i18next'\n+import { ResourceKey } from 'i18next'\n-import translationAR from '../src/locales/ar/translations'\n-import translationDE from '../src/locales/de/translations'\n-import translationEnUs from '../src/locales/enUs/translations'\n-import translationES from '../src/locales/es/translations'\n-import translationFR from '../src/locales/fr/translations'\n-import translationIN from '../src/locales/in/translations'\n-import translationIT from '../src/locales/it/translations'\n-import translationJA from '../src/locales/ja/translations'\n-import translationPtBR from '../src/locales/ptBr/translations'\n-import translationRU from '../src/locales/ru/translations'\n-import translationZR from '../src/locales/zr/translations'\n-\n-const resources: Resource = {\n- it: {\n- translation: translationIT,\n- },\n- ar: {\n- translation: translationAR,\n- },\n- de: {\n- translation: translationDE,\n- },\n- en: {\n- translation: translationEnUs,\n- },\n- es: {\n- translation: translationES,\n- },\n- fr: {\n- translation: translationFR,\n- },\n- in: {\n- translation: translationIN,\n- },\n- ja: {\n- translation: translationJA,\n- },\n- pt: {\n- translation: translationPtBR,\n- },\n- ru: {\n- translation: translationRU,\n- },\n- zr: {\n- translation: translationZR,\n- },\n-}\n+import resources from '../src/locales'\nconst error = chalk.bold.red\nconst warning = chalk.keyword('orange')\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/tsconfig.json",
"new_path": "scripts/tsconfig.json",
"diff": "{\n\"include\": [\"./checkMissingTranslations.ts\"],\n\"compilerOptions\": {\n- \"declaration\": true,\n- \"declarationDir\": \"./dist\",\n\"module\": \"commonjs\",\n- \"outDir\": \"./dist\",\n+ \"outDir\": \"../bin\",\n\"target\": \"es5\"\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/i18n.ts",
"new_path": "src/i18n.ts",
"diff": "@@ -2,64 +2,7 @@ import i18n from 'i18next'\nimport LanguageDetector from 'i18next-browser-languagedetector'\nimport { initReactI18next } from 'react-i18next'\n-import translationAR from './locales/ar/translations'\n-import translationDE from './locales/de/translations'\n-import translationEnUs from './locales/enUs/translations'\n-import translationES from './locales/es/translations'\n-import translationFR from './locales/fr/translations'\n-import translationID from './locales/id/translations'\n-import translationIT from './locales/it/translations'\n-import translationJA from './locales/ja/translations'\n-import translationPtBR from './locales/ptBr/translations'\n-import translationRU from './locales/ru/translations'\n-import translationZhCN from './locales/zhCN/translations'\n-\n-const resources: { [language: string]: any } = {\n- it: {\n- name: 'Italian',\n- translation: translationIT,\n- },\n- ar: {\n- name: 'Arabic',\n- translation: translationAR,\n- },\n- de: {\n- name: 'German',\n- translation: translationDE,\n- },\n- en: {\n- name: 'English, American',\n- translation: translationEnUs,\n- },\n- es: {\n- name: 'Spanish',\n- translation: translationES,\n- },\n- fr: {\n- name: 'French',\n- translation: translationFR,\n- },\n- id: {\n- name: 'Indonesian',\n- translation: translationID,\n- },\n- ja: {\n- name: 'Japanese',\n- translation: translationJA,\n- },\n- ptBR: {\n- name: 'Portuguese',\n- translation: translationPtBR,\n- },\n- ru: {\n- name: 'Russian',\n- translation: translationRU,\n- },\n- zhCN: {\n- name: 'Chinese',\n- translation: translationZhCN,\n- },\n-}\n+import resources from './locales'\ni18n\n// load translation using xhr -> see /public/locales\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/locales/index.ts",
"diff": "+import { Resource } from 'i18next'\n+\n+import translationAR from './ar/translations'\n+import translationDE from './de/translations'\n+import translationEnUs from './enUs/translations'\n+import translationES from './es/translations'\n+import translationFR from './fr/translations'\n+import translationID from './id/translations'\n+import translationIT from './it/translations'\n+import translationJA from './ja/translations'\n+import translationPtBR from './ptBr/translations'\n+import translationRU from './ru/translations'\n+import translationZhCN from './zhCN/translations'\n+\n+const resources: Resource = {\n+ it: {\n+ name: 'Italian',\n+ translation: translationIT,\n+ },\n+ ar: {\n+ name: 'Arabic',\n+ translation: translationAR,\n+ },\n+ de: {\n+ name: 'German',\n+ translation: translationDE,\n+ },\n+ en: {\n+ name: 'English, American',\n+ translation: translationEnUs,\n+ },\n+ es: {\n+ name: 'Spanish',\n+ translation: translationES,\n+ },\n+ fr: {\n+ name: 'French',\n+ translation: translationFR,\n+ },\n+ id: {\n+ name: 'Indonesian',\n+ translation: translationID,\n+ },\n+ ja: {\n+ name: 'Japanese',\n+ translation: translationJA,\n+ },\n+ ptBR: {\n+ name: 'Portuguese',\n+ translation: translationPtBR,\n+ },\n+ ru: {\n+ name: 'Russian',\n+ translation: translationRU,\n+ },\n+ zhCN: {\n+ name: 'Chinese',\n+ translation: translationZhCN,\n+ },\n+}\n+\n+export default resources\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | refactor(checktranslations): run script as js file
now ts-node library is no need anymore because the script is compiled to javascript |
288,394 | 08.06.2020 15:17:09 | 25,200 | 391271a23a3cdd66f27911aafb729c4add10c171 | fix(navbar): Make Navbar mobile-friendly | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/components/Navbar.test.tsx",
"new_path": "src/__tests__/components/Navbar.test.tsx",
"diff": "@@ -54,151 +54,66 @@ describe('Navbar', () => {\nPermissions.ReportIncident,\n]\n- it('should render a HospitalRun Navbar', () => {\n+ describe('hamberger', () => {\n+ it('should render a hamberger link list', () => {\nconst wrapper = setup(allPermissions)\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const hamberger = hospitalRunNavbar.find('.nav-hamberger')\n+ const { children } = hamberger.first().props() as any\n- expect(hospitalRunNavbar).toHaveLength(1)\n- })\n-\n- describe('header', () => {\n- it('should render a HospitalRun Navbar with the navbar header', () => {\n- const wrapper = setup(allPermissions)\n- const header = wrapper.find('.nav-header')\n- const { children } = header.first().props() as any\n-\n- expect(children.props.children).toEqual('HospitalRun')\n- })\n-\n- it('should navigate to / when the header is clicked', () => {\n- const wrapper = setup(allPermissions)\n- const header = wrapper.find('.nav-header')\n-\n- act(() => {\n- const onClick = header.first().prop('onClick') as any\n- onClick()\n+ expect(children[0].props.children).toEqual('dashboard.label')\n+ expect(children[1].props.children).toEqual('patients.newPatient')\n+ expect(children[children.length - 1].props.children).toEqual('settings.label')\n})\n- expect(history.location.pathname).toEqual('/')\n- })\n- })\n-\n- describe('patients', () => {\n- it('should render a patients link list', () => {\n- const wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n- const { children } = patientsLinkList.first().props() as any\n-\n- expect(patientsLinkList.first().props().title).toEqual('patients.label')\n- expect(children[0].props.children).toEqual('actions.list')\n- expect(children[1].props.children).toEqual('actions.new')\n- })\n-\n- it('should navigate to /patients when the list option is selected', () => {\n- const wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n- const { children } = patientsLinkList.first().props() as any\n-\n- act(() => {\n- children[0].props.onClick()\n- })\n-\n- expect(history.location.pathname).toEqual('/patients')\n- })\n-\n- it('should navigate to /patients/new when the list option is selected', () => {\n- const wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const patientsLinkList = hospitalRunNavbar.find('.patients-link-list')\n- const { children } = patientsLinkList.first().props() as any\n-\n- act(() => {\n- children[1].props.onClick()\n- })\n-\n- expect(history.location.pathname).toEqual('/patients/new')\n- })\n- })\n-\n- describe('scheduling', () => {\n- it('should render a scheduling dropdown', () => {\n- const wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n- const { children } = scheduleLinkList.first().props() as any\n-\n- expect(scheduleLinkList.first().props().title).toEqual('scheduling.label')\n- if (scheduleLinkList.first().props().children) {\n- expect(children[0].props.children).toEqual('scheduling.appointments.label')\n- expect(children[1].props.children).toEqual('scheduling.appointments.new')\n- }\n- })\n-\n- it('should navigate to to /appointments when the appointment list option is selected', () => {\n- const wrapper = setup(allPermissions)\n+ it('should not show an item if user does not have a permission', () => {\n+ // exclude labs and incidents permissions\n+ const wrapper = setup(cloneDeep(allPermissions).slice(0, 6))\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n- const { children } = scheduleLinkList.first().props() as any\n+ const hamberger = hospitalRunNavbar.find('.nav-hamberger')\n+ const { children } = hamberger.first().props() as any\n+\n+ const labels = [\n+ 'labs.requests.new',\n+ 'labs.requests.label',\n+ 'incidents.reports.new',\n+ 'incidents.reports.label',\n+ ]\n- act(() => {\n- children[0].props.onClick()\n+ children.forEach((option: any) => {\n+ labels.forEach((label) => {\n+ expect(option.props.children).not.toEqual(label)\n})\n-\n- expect(history.location.pathname).toEqual('/appointments')\n})\n-\n- it('should navigate to /appointments/new when the new appointment list option is selected', () => {\n- const wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const scheduleLinkList = hospitalRunNavbar.find('.scheduling-link-list')\n- const { children } = scheduleLinkList.first().props() as any\n-\n- act(() => {\n- children[1].props.onClick()\n- })\n-\n- expect(history.location.pathname).toEqual('/appointments/new')\n})\n})\n- describe('labs', () => {\n- it('should render a labs dropdown', () => {\n+ it('should render a HospitalRun Navbar', () => {\nconst wrapper = setup(allPermissions)\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n- const { children } = labsLinkList.first().props() as any\n- expect(labsLinkList.first().props().title).toEqual('labs.label')\n- expect(children[0].props.children).toEqual('labs.label')\n- expect(children[1].props.children).toEqual('labs.requests.new')\n+ expect(hospitalRunNavbar).toHaveLength(1)\n})\n- it('should navigate to to /labs when the labs list option is selected', () => {\n+ describe('header', () => {\n+ it('should render a HospitalRun Navbar with the navbar header', () => {\nconst wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n- const { children } = labsLinkList.first().props() as any\n-\n- act(() => {\n- children[0].props.onClick()\n- })\n+ const header = wrapper.find('.nav-header')\n+ const { children } = header.first().props() as any\n- expect(history.location.pathname).toEqual('/labs')\n+ expect(children.props.children).toEqual('HospitalRun')\n})\n- it('should navigate to /labs/new when the new labs list option is selected', () => {\n+ it('should navigate to / when the header is clicked', () => {\nconst wrapper = setup(allPermissions)\n- const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const labsLinkList = hospitalRunNavbar.find('.labs-link-list')\n- const { children } = labsLinkList.first().props() as any\n+ const header = wrapper.find('.nav-header')\nact(() => {\n- children[1].props.onClick()\n+ const onClick = header.first().prop('onClick') as any\n+ onClick()\n})\n- expect(history.location.pathname).toEqual('/labs/new')\n+ expect(history.location.pathname).toEqual('/')\n})\n})\n@@ -226,7 +141,7 @@ describe('Navbar', () => {\nit('should show a shortcut if user has a permission', () => {\nconst wrapper = setup(allPermissions)\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const addNew = hospitalRunNavbar.find('.add-new')\n+ const addNew = hospitalRunNavbar.find('.nav-add-new')\nconst { children } = addNew.first().props() as any\nexpect(children[0].props.children).toEqual('patients.newPatient')\n@@ -236,7 +151,7 @@ describe('Navbar', () => {\n// exclude labs and incidents permissions\nconst wrapper = setup(cloneDeep(allPermissions).slice(0, 6))\nconst hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n- const addNew = hospitalRunNavbar.find('.add-new')\n+ const addNew = hospitalRunNavbar.find('.nav-add-new')\nconst { children } = addNew.first().props() as any\nchildren.forEach((option: any) => {\n@@ -245,4 +160,28 @@ describe('Navbar', () => {\n})\n})\n})\n+\n+ describe('account', () => {\n+ it('should render an account link list', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const accountLinkList = hospitalRunNavbar.find('.nav-account')\n+ const { children } = accountLinkList.first().props() as any\n+\n+ expect(children[0].props.children).toEqual('settings.label')\n+ })\n+\n+ it('should navigate to /settings when the list option is selected', () => {\n+ const wrapper = setup(allPermissions)\n+ const hospitalRunNavbar = wrapper.find(HospitalRunNavbar)\n+ const accountLinkList = hospitalRunNavbar.find('.nav-account')\n+ const { children } = accountLinkList.first().props() as any\n+\n+ act(() => {\n+ children[0].props.onClick()\n+ })\n+\n+ expect(history.location.pathname).toEqual('/settings')\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Navbar.tsx",
"new_path": "src/components/Navbar.tsx",
"diff": "@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'\nimport { useSelector } from 'react-redux'\nimport { useHistory } from 'react-router-dom'\n-import Permissions from '../model/Permissions'\n+import pageMap, { Page } from '../pageMap'\nimport { RootState } from '../store'\nconst Navbar = () => {\n@@ -12,50 +12,45 @@ const Navbar = () => {\nconst { t } = useTranslation()\nconst history = useHistory()\n- const addPages = [\n- {\n- permission: Permissions.WritePatients,\n- label: t('patients.newPatient'),\n- path: '/patients/new',\n- },\n- {\n- permission: Permissions.WriteAppointments,\n- label: t('scheduling.appointments.new'),\n- path: '/appointments/new',\n- },\n- {\n- permission: Permissions.RequestLab,\n- label: t('labs.requests.new'),\n- path: '/labs/new',\n- },\n- {\n- permission: Permissions.ReportIncident,\n- label: t('incidents.reports.new'),\n- path: '/incidents/new',\n- },\n- ]\n+ const navigateTo = (location: string) => {\n+ history.push(location)\n+ }\n- const addDropdownList: { type: string; label: string; onClick: () => void }[] = addPages\n- .filter((page) => permissions.includes(page.permission))\n+ function getDropdownListOfPages(pages: Page[]) {\n+ return pages\n+ .filter((page) => !page.permission || permissions.includes(page.permission))\n.map((page) => ({\ntype: 'link',\n- label: page.label,\n+ label: t(page.label),\nonClick: () => {\n- history.push(page.path)\n+ navigateTo(page.path)\n},\n}))\n+ }\n+\n+ // For Mobile, hamburger menu\n+ const hambergerPages = Object.keys(pageMap).map((key) => pageMap[key])\n+\n+ // For Desktop, add shortcuts menu\n+ const addPages = [pageMap.newPatient, pageMap.newAppointment, pageMap.newLab, pageMap.newIncident]\nreturn (\n<HospitalRunNavbar\nbg=\"dark\"\nvariant=\"dark\"\nnavItems={[\n+ {\n+ children: getDropdownListOfPages(hambergerPages),\n+ label: '',\n+ type: 'link-list',\n+ className: 'nav-hamberger pr-4 d-md-none',\n+ },\n{\ntype: 'image',\nsrc:\n'data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53%0D%0AMy5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5r%0D%0AIiB2aWV3Qm94PSIwIDAgMjk5IDI5OSI+PGRlZnM+PHN0eWxlPi5jbHMtMXtmaWxsOnVybCgjbGlu%0D%0AZWFyLWdyYWRpZW50KTt9PC9zdHlsZT48bGluZWFyR3JhZGllbnQgaWQ9ImxpbmVhci1ncmFkaWVu%0D%0AdCIgeDE9IjcyLjU4IiB5MT0iMTYuMDQiIHgyPSIyMjcuMzEiIHkyPSIyODQuMDIiIGdyYWRpZW50%0D%0AVW5pdHM9InVzZXJTcGFjZU9uVXNlIj48c3RvcCBvZmZzZXQ9IjAuMDEiIHN0b3AtY29sb3I9IiM2%0D%0AMGQxYmIiLz48c3RvcCBvZmZzZXQ9IjAuNSIgc3RvcC1jb2xvcj0iIzFhYmM5YyIvPjxzdG9wIG9m%0D%0AZnNldD0iMSIgc3RvcC1jb2xvcj0iIzAwOWI5ZSIvPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjx0%0D%0AaXRsZT5jcm9zcy1pY29uPC90aXRsZT48cGF0aCBpZD0iY3Jvc3MiIGNsYXNzPSJjbHMtMSIgZD0i%0D%0ATTI5Mi45NCw5Ny40NkgyMDUuM1Y3LjA2QTYuNTYsNi41NiwwLDAsMCwxOTguNzQuNUgxMDEuMjZB%0D%0ANi41Niw2LjU2LDAsMCwwLDk0LjcsNy4wNnY5MC40SDcuMDZBNi41OCw2LjU4LDAsMCwwLC41LDEw%0D%0ANFYxOTYuM2E2LjIzLDYuMjMsMCwwLDAsNi4yMyw2LjI0aDg4djkwLjRhNi41Niw2LjU2LDAsMCww%0D%0ALDYuNTYsNi41Nmg5Ny40OGE2LjU2LDYuNTYsMCwwLDAsNi41Ni02LjU2di05MC40aDg4YTYuMjMs%0D%0ANi4yMywwLDAsMCw2LjIzLTYuMjRWMTA0QTYuNTgsNi41OCwwLDAsMCwyOTIuOTQsOTcuNDZaIiB0%0D%0AcmFuc2Zvcm09InRyYW5zbGF0ZSgtMC41IC0wLjUpIi8+PC9zdmc+',\nonClick: () => {\n- history.push('/')\n+ navigateTo('/')\n},\nclassName: 'nav-icon',\n},\n@@ -63,77 +58,14 @@ const Navbar = () => {\ntype: 'header',\nlabel: 'HospitalRun',\nonClick: () => {\n- history.push('/')\n+ navigateTo('/')\n},\nclassName: 'nav-header',\n},\n- {\n- type: 'link-list',\n- label: t('patients.label'),\n- className: 'patients-link-list d-md-none d-block',\n- children: [\n- {\n- type: 'link',\n- label: t('actions.list'),\n- onClick: () => {\n- history.push('/patients')\n- },\n- },\n- {\n- type: 'link',\n- label: t('actions.new'),\n- onClick: () => {\n- history.push('/patients/new')\n- },\n- },\n- ],\n- },\n- {\n- type: 'link-list',\n- label: t('scheduling.label'),\n- className: 'scheduling-link-list d-md-none d-block',\n- children: [\n- {\n- type: 'link',\n- label: t('scheduling.appointments.label'),\n- onClick: () => {\n- history.push('/appointments')\n- },\n- },\n- {\n- type: 'link',\n- label: t('scheduling.appointments.new'),\n- onClick: () => {\n- history.push('/appointments/new')\n- },\n- },\n- ],\n- },\n- {\n- type: 'link-list',\n- label: t('labs.label'),\n- className: 'labs-link-list d-md-none d-block',\n- children: [\n- {\n- type: 'link',\n- label: t('labs.label'),\n- onClick: () => {\n- history.push('/labs')\n- },\n- },\n- {\n- type: 'link',\n- label: t('labs.requests.new'),\n- onClick: () => {\n- history.push('/labs/new')\n- },\n- },\n- ],\n- },\n{\ntype: 'search',\nplaceholderText: t('actions.search'),\n- className: 'ml-auto nav-search',\n+ className: 'ml-auto d-none d-md-block nav-search',\nbuttonText: t('actions.search'),\nbuttonColor: 'secondary',\nonClickButton: () => undefined,\n@@ -142,8 +74,8 @@ const Navbar = () => {\n{\ntype: 'link-list-icon',\nalignRight: true,\n- children: addDropdownList,\n- className: 'pl-4 add-new',\n+ children: getDropdownListOfPages(addPages),\n+ className: 'pl-4 nav-add-new d-none d-md-block',\niconClassName: 'align-bottom',\nlabel: 'Add',\nname: 'add',\n@@ -157,11 +89,11 @@ const Navbar = () => {\ntype: 'link',\nlabel: t('settings.label'),\nonClick: () => {\n- history.push('/settings')\n+ navigateTo('/settings')\n},\n},\n],\n- className: 'pl-2',\n+ className: 'pl-2 d-none d-md-block nav-account',\niconClassName: 'align-bottom',\nlabel: 'Patient',\nname: 'patient',\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/pageMap.tsx",
"diff": "+import Permissions from './model/Permissions'\n+\n+type Page = { permission: Permissions | null; label: string; path: string }\n+\n+const pageMap: {\n+ [key: string]: Page\n+} = {\n+ dashboard: {\n+ permission: null,\n+ label: 'dashboard.label',\n+ path: '/',\n+ },\n+ newPatient: {\n+ permission: Permissions.WritePatients,\n+ label: 'patients.newPatient',\n+ path: '/patients/new',\n+ },\n+ viewPatients: {\n+ permission: Permissions.ReadPatients,\n+ label: 'patients.patientsList',\n+ path: '/patients',\n+ },\n+ newAppointment: {\n+ permission: Permissions.WriteAppointments,\n+ label: 'scheduling.appointments.new',\n+ path: '/appointments/new',\n+ },\n+ viewAppointments: {\n+ permission: Permissions.ReadAppointments,\n+ label: 'scheduling.appointments.schedule',\n+ path: '/appointments',\n+ },\n+ newLab: {\n+ permission: Permissions.RequestLab,\n+ label: 'labs.requests.new',\n+ path: '/labs/new',\n+ },\n+ viewLabs: {\n+ permission: Permissions.ViewLabs,\n+ label: 'labs.requests.label',\n+ path: '/labs',\n+ },\n+ newIncident: {\n+ permission: Permissions.ReportIncident,\n+ label: 'incidents.reports.new',\n+ path: '/incidents/new',\n+ },\n+ viewIncidents: {\n+ permission: Permissions.ViewIncidents,\n+ label: 'incidents.reports.label',\n+ path: '/incidents',\n+ },\n+ settings: {\n+ permission: null,\n+ label: 'settings.label',\n+ path: '/settings',\n+ },\n+}\n+\n+export default pageMap\n+export type { Page }\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "@@ -4,7 +4,7 @@ import Permissions from '../model/Permissions'\nimport User from '../model/User'\ninterface UserState {\n- permissions: Permissions[]\n+ permissions: (Permissions | null)[]\nuser: User\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(navbar): Make Navbar mobile-friendly (#2118)
Co-authored-by: HospitalRun Bot <[email protected]>
Co-authored-by: Matteo Vivona <[email protected]> |
288,347 | 10.06.2020 10:45:14 | -7,200 | 30bb1587125e1d208ffb68e6f8ec9d4aab09a291 | fix(i18n): fix build | [
{
"change_type": "MODIFY",
"old_path": "src/locales/index.ts",
"new_path": "src/locales/index.ts",
"diff": "-import { Resource } from 'i18next'\n-\nimport translationAR from './ar/translations'\nimport translationDE from './de/translations'\nimport translationEnUs from './enUs/translations'\n@@ -12,7 +10,7 @@ import translationPtBR from './ptBr/translations'\nimport translationRU from './ru/translations'\nimport translationZhCN from './zhCN/translations'\n-const resources: Resource = {\n+const resources: { [language: string]: any } = {\nit: {\nname: 'Italian',\ntranslation: translationIT,\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(i18n): fix build |
288,297 | 16.06.2020 10:04:39 | -7,200 | 653202870b4eafad6f960136b63ef76639ca005c | fix(toolchain): extends scripts tsconfig.json from base one
re | [
{
"change_type": "MODIFY",
"old_path": "scripts/tsconfig.json",
"new_path": "scripts/tsconfig.json",
"diff": "{\n- \"include\": [\"./checkMissingTranslations.ts\"],\n+ \"extends\": \"../tsconfig.json\",\n+ \"include\": [\n+ \"./checkMissingTranslations.ts\"\n+ ],\n\"compilerOptions\": {\n\"module\": \"commonjs\",\n\"outDir\": \"../bin\",\n- \"target\": \"es5\"\n+ \"target\": \"es5\",\n+ \"sourceMap\": false\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tsconfig.json",
"new_path": "tsconfig.json",
"diff": "\"resolveJsonModule\": true,\n\"importHelpers\": true,\n\"jsx\": \"react\",\n- // \"baseUrl\": \"./src\",\n\"allowJs\": true,\n\"skipLibCheck\": true,\n\"noEmit\": true,\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(toolchain): extends scripts tsconfig.json from base one
re #2113 |
288,297 | 16.06.2020 18:00:58 | -7,200 | d0c35db60aef95d0892fe7650960635eeda25df8 | fix(toolchain): fix broken deps and updates translate-check script | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -21,18 +21,18 @@ module.exports = {\n},\nparser: '@typescript-eslint/parser',\nparserOptions: {\n- project: ['./tsconfig.json', './scripts/tsconfig.json'],\n+ project: ['./tsconfig.json', './check-translations/tsconfig.json'],\ntsconfigRootDir: './',\n},\nsettings: {\n'import/resolver': {\nnode: {\nextensions: ['.js', '.jsx', '.ts', '.tsx'],\n- moduleDirectory: [\"node_modules\"],\n+ moduleDirectory: ['node_modules'],\n},\n- \"typescript\": {\n+ typescript: {\nalwaysTryTypes: true,\n- }\n+ },\n},\n'import/parsers': {\n'@typescript-eslint/parser': ['.ts', '.tsx'],\n@@ -61,19 +61,17 @@ module.exports = {\n'no-nested-ternary': 'off',\n'import/no-unresolved': 'off',\n'import/extensions': ['error', 'never'],\n- 'import/order': [\"error\", {\n- \"groups\": [\n- \"external\",\n- [\"sibling\",\"parent\",\"internal\"],\n- \"builtin\",\n- \"unknown\",\n- ],\n- \"newlines-between\": \"always\",\n- \"alphabetize\": {\n- \"order\": 'asc',\n- \"caseInsensitive\": true,\n+ 'import/order': [\n+ 'error',\n+ {\n+ groups: ['external', ['sibling', 'parent', 'internal'], 'builtin', 'unknown'],\n+ 'newlines-between': 'always',\n+ alphabetize: {\n+ order: 'asc',\n+ caseInsensitive: true,\n},\n- }],\n+ },\n+ ],\ncurly: ['error', 'all'],\n},\n}\n"
},
{
"change_type": "RENAME",
"old_path": "scripts/.eslintrc.js",
"new_path": "check-translations/.eslintrc.js",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "scripts/checkMissingTranslations.ts",
"new_path": "check-translations/index.ts",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "scripts/tsconfig.json",
"new_path": "check-translations/tsconfig.json",
"diff": "{\n\"extends\": \"../tsconfig.json\",\n\"include\": [\n- \"./checkMissingTranslations.ts\"\n+ \"./index.ts\"\n],\n\"compilerOptions\": {\n\"module\": \"commonjs\",\n- \"outDir\": \"../bin\",\n+ \"outDir\": \"compiled\",\n\"target\": \"es5\",\n- \"sourceMap\": false\n+ \"sourceMap\": false,\n+ \"noEmit\": false\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"react-dom\": \"~16.13.0\",\n\"react-i18next\": \"~11.5.0\",\n\"react-redux\": \"~7.2.0\",\n- \"react-router\": \"~5.1.2\",\n- \"react-router-dom\": \"~5.1.2\",\n+ \"react-router\": \"~5.2.0\",\n+ \"react-router-dom\": \"~5.2.0\",\n\"react-scripts\": \"~3.4.0\",\n\"redux\": \"~4.0.5\",\n\"redux-thunk\": \"~2.3.0\",\n\"shortid\": \"^2.2.15\",\n- \"typescript\": \"~3.8.2\",\n+ \"typescript\": \"~3.8.3\",\n\"uuid\": \"^8.0.0\",\n\"validator\": \"^13.0.0\"\n},\n\"@commitlint/config-conventional\": \"~8.3.4\",\n\"@commitlint/core\": \"~8.3.5\",\n\"@commitlint/prompt\": \"~8.3.5\",\n- \"@testing-library/react\": \"~10.1.0\",\n+ \"@testing-library/react\": \"~10.2.1\",\n\"@testing-library/react-hooks\": \"~3.3.0\",\n\"@types/enzyme\": \"^3.10.5\",\n\"@types/jest\": \"~26.0.0\",\n\"@types/shortid\": \"^0.0.29\",\n\"@types/uuid\": \"^8.0.0\",\n\"@types/validator\": \"~13.0.0\",\n- \"@typescript-eslint/eslint-plugin\": \"~2.34.0\",\n- \"@typescript-eslint/parser\": \"~2.34.0\",\n+ \"@typescript-eslint/eslint-plugin\": \"~3.3.0\",\n+ \"@typescript-eslint/parser\": \"~3.3.0\",\n\"chalk\": \"^4.0.0\",\n\"commitizen\": \"~4.1.2\",\n\"commitlint-config-cz\": \"~0.13.0\",\n\"eslint-plugin-jsx-a11y\": \"~6.2.3\",\n\"eslint-plugin-prettier\": \"~3.1.2\",\n\"eslint-plugin-react\": \"~7.20.0\",\n- \"eslint-plugin-react-hooks\": \"~2.5.0\",\n+ \"eslint-plugin-react-hooks\": \"~4.0.4\",\n\"history\": \"~4.10.1\",\n\"husky\": \"~4.2.1\",\n\"jest\": \"~24.9.0\",\n\"memdown\": \"~5.1.0\",\n\"prettier\": \"~2.0.4\",\n\"redux-mock-store\": \"~1.5.4\",\n+ \"rimraf\": \"~3.0.2\",\n\"source-map-explorer\": \"^2.2.2\",\n\"standard-version\": \"~8.0.0\",\n- \"ts-jest\": \"~24.3.0\"\n+ \"ts-jest\": \"~26.1.0\"\n},\n\"scripts\": {\n\"analyze\": \"source-map-explorer 'build/static/js/*.js'\",\n\"commit\": \"npx git-cz\",\n- \"start\": \"yarn translation:check && react-scripts start\",\n+ \"start\": \"npm run translation:check && react-scripts start\",\n\"build\": \"react-scripts build\",\n+ \"update\": \"npx npm-check -u\",\n\"prepublishOnly\": \"npm run build\",\n- \"test\": \"yarn translation:check && react-scripts test --detectOpenHandles\",\n+ \"test\": \"npm run translation:check && react-scripts test --detectOpenHandles\",\n\"test:ci\": \"cross-env CI=true react-scripts test --passWithNoTests\",\n- \"lint\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\"\",\n- \"lint:fix\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"scripts/**/*.{js,ts}\\\" --fix\",\n+ \"lint\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"check-translations/**/*.{js,ts}\\\"\",\n+ \"lint:fix\": \"eslint \\\"src/**/*.{js,jsx,ts,tsx}\\\" \\\"check-translations/**/*.{js,ts}\\\" --fix\",\n\"lint-staged\": \"lint-staged\",\n\"commitlint\": \"commitlint\",\n\"coveralls\": \"npm run test:ci -- --coverage --watchAll=false && cat ./coverage/lcov.info\",\n- \"translation:check\": \"cd scripts && tsc && node ../bin/scripts/checkMissingTranslations.js\"\n+ \"remove-compiled-translations\": \"rimraf ./check-translations/compiled\",\n+ \"pretranslation:check\": \"npm run remove-compiled-translations\",\n+ \"translation:check\": \"tsc -p ./check-translations/tsconfig.json && node ./check-translations/compiled/check-translations/index.js\",\n+ \"posttranslation:check\": \"npm run remove-compiled-translations\"\n},\n\"browserslist\": {\n\"production\": [\n"
},
{
"change_type": "MODIFY",
"old_path": "src/__tests__/clients/db/LabRepository.test.ts",
"new_path": "src/__tests__/clients/db/LabRepository.test.ts",
"diff": "-/* eslint \"@typescript-eslint/camelcase\": \"off\" */\n-\nimport shortid from 'shortid'\nimport LabRepository from '../../../clients/db/LabRepository'\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/Repository.ts",
"new_path": "src/clients/db/Repository.ts",
"diff": "-/* eslint \"@typescript-eslint/camelcase\": \"off\" */\nimport { v4 as uuidv4 } from 'uuid'\nimport AbstractDBModel from '../../model/AbstractDBModel'\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/network-status/NetworkStatusMessage.tsx",
"new_path": "src/components/network-status/NetworkStatusMessage.tsx",
"diff": "@@ -8,7 +8,7 @@ const OFFLINE_COLOR = 'rgba(255, 0, 0, 0.65)'\nconst OPACITY_TRANSITION_TIME = 4000\nconst BASE_STYLE = {\nheight: '50px',\n- pointerEvents: 'none' as 'none',\n+ pointerEvents: 'none' as const,\ntransition: `opacity ${OPACITY_TRANSITION_TIME}ms ease-in`,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/custom-pouchdb.d.ts",
"new_path": "src/custom-pouchdb.d.ts",
"diff": "+/* eslint-disable camelcase */\ndeclare namespace PouchDB {\ninterface SearchQuery<Content> {\n// Search string\n@@ -16,8 +17,8 @@ declare namespace PouchDB {\nfilter?: (content: Content) => boolean\n- include_docs?: boolean\nhighlighting?: boolean\n+ include_docs?: boolean\nhighlighting_pre?: string\nhighlighting_post?: string\n@@ -36,10 +37,11 @@ declare namespace PouchDB {\ninterface SearchResponse<T> {\nrows: Array<SearchRow<T>>\n+\ntotal_rows: number\n}\n- interface Database<Content extends {} = {}> {\n+ interface Database<Content extends Record<string, unknown> = Record<string, unknown>> {\nsearch(query: SearchQuery<Content>): SearchResponse<Content>\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/hooks/useUpdateEffect.ts",
"new_path": "src/hooks/useUpdateEffect.ts",
"diff": "-import { useRef, useEffect } from 'react'\n+import { useRef, useEffect, EffectCallback } from 'react'\n-export default function (effect: Function, dependencies: any[]) {\n+export default function (effect: EffectCallback, dependencies: any[]): void {\nconst isInitialMount = useRef(true)\nuseEffect(() => {\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix(toolchain): fix broken deps and updates translate-check script |
288,334 | 16.06.2020 19:02:31 | -7,200 | e4607df6cd86636f20fca68bffbe0a52ad7d1f94 | ci(node): add node 14 on windows and mac | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/ci.yml",
"new_path": ".github/workflows/ci.yml",
"diff": "@@ -7,8 +7,7 @@ jobs:\nruns-on: ${{ matrix.os }}\nstrategy:\nmatrix:\n- # node-version: [12.x, 14.x]\n- node-version: [12.x]\n+ node-version: [12.x, 14.x]\nos: [ubuntu-latest, windows-latest, macOS-latest]\nsteps:\n- run: git config --global core.autocrlf false # this is needed to prevent git changing EOL after cloning on Windows OS\n@@ -36,29 +35,3 @@ jobs:\nwith:\ngithub-token: ${{ secrets.GITHUB_TOKEN }}\npath-to-lcov: ./coverage/lcov.info\n-\n- npm-node14:\n- runs-on: ${{ matrix.os }}\n- strategy:\n- matrix:\n- node-version: [14.x]\n- os: [ubuntu-latest]\n- steps:\n- - run: git config --global core.autocrlf false # this is needed to prevent git changing EOL after cloning on Windows OS\n- - uses: actions/checkout@v2\n- - name: Use Node.js\n- uses: actions/setup-node@v1\n- with:\n- node-version: ${{ matrix.node-version }}\n- - name: Install with npm\n- run: |\n- npm install\n- - name: Lint code\n- run: |\n- npm run lint\n- - name: Build\n- run: |\n- npm run build\n- - name: Run tests\n- run: |\n- npm run test:ci\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | ci(node): add node 14 on windows and mac (#2131) |
288,323 | 13.06.2020 19:55:27 | 18,000 | 5157a47095e458e6cefd2ce3c1783b4b4019cb1b | working login example | [
{
"change_type": "MODIFY",
"old_path": "src/App.tsx",
"new_path": "src/App.tsx",
"diff": "import { Spinner } from '@hospitalrun/components'\nimport React, { Suspense } from 'react'\nimport { Provider } from 'react-redux'\n-import { BrowserRouter } from 'react-router-dom'\n+import { BrowserRouter, Route, Switch } from 'react-router-dom'\nimport HospitalRun from './HospitalRun'\n+import Login from './login/Login'\nimport store from './store'\nconst App: React.FC = () => (\n<div>\n<Provider store={store}>\n- <Suspense fallback={<Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />}>\n<BrowserRouter>\n- <HospitalRun />\n- </BrowserRouter>\n+ <Suspense fallback={<Spinner color=\"blue\" loading size={[10, 25]} type=\"ScaleLoader\" />}>\n+ <Switch>\n+ <Route exact path=\"/login\" component={Login} />\n+ <Route path=\"/\" component={HospitalRun} />\n+ </Switch>\n</Suspense>\n+ </BrowserRouter>\n</Provider>\n</div>\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/HospitalRun.tsx",
"new_path": "src/HospitalRun.tsx",
"diff": "import { Toaster } from '@hospitalrun/components'\nimport React from 'react'\nimport { useSelector } from 'react-redux'\n-import { Switch, Route } from 'react-router-dom'\n+import { Redirect, Route, Switch } from 'react-router-dom'\nimport Breadcrumbs from './breadcrumbs/Breadcrumbs'\nimport Navbar from './components/Navbar'\nimport { NetworkStatusMessage } from './components/network-status'\n-import PrivateRoute from './components/PrivateRoute'\nimport Sidebar from './components/Sidebar'\nimport Dashboard from './dashboard/Dashboard'\nimport Incidents from './incidents/Incidents'\n@@ -21,6 +20,11 @@ import { RootState } from './store'\nconst HospitalRun = () => {\nconst { title } = useSelector((state: RootState) => state.title)\nconst { sidebarCollapsed } = useSelector((state: RootState) => state.components)\n+ const { user } = useSelector((root: RootState) => root.user)\n+\n+ if (user === undefined) {\n+ return <Redirect to=\"/login\" />\n+ }\nreturn (\n<div>\n@@ -43,12 +47,12 @@ const HospitalRun = () => {\n<Breadcrumbs />\n<div>\n<Switch>\n- <Route exact path=\"/\" component={Dashboard} />\n- <PrivateRoute isAuthenticated path=\"/appointments\" component={Appointments} />\n- <PrivateRoute isAuthenticated path=\"/patients\" component={Patients} />\n- <PrivateRoute isAuthenticated path=\"/labs\" component={Labs} />\n- <PrivateRoute isAuthenticated path=\"/incidents\" component={Incidents} />\n- <PrivateRoute isAuthenticated path=\"/settings\" component={Settings} />\n+ <Route path=\"/\" component={Dashboard} />\n+ <Route exact path=\"/appointments\" component={Appointments} />\n+ <Route exact path=\"/patients\" component={Patients} />\n+ <Route exact path=\"/labs\" component={Labs} />\n+ <Route exact path=\"/incidents\" component={Incidents} />\n+ <Route exact path=\"/settings\" component={Settings} />\n</Switch>\n</div>\n<Toaster autoClose={5000} hideProgressBar draggable />\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/AppointmentRepository.ts",
"new_path": "src/clients/db/AppointmentRepository.ts",
"diff": "import escapeStringRegexp from 'escape-string-regexp'\n-import { appointments } from '../../config/pouchdb'\n+import { localDb } from '../../config/pouchdb'\nimport Appointment from '../../model/Appointment'\nimport Repository from './Repository'\nclass AppointmentRepository extends Repository<Appointment> {\nconstructor() {\n- super(appointments)\n+ super(localDb)\n}\n// Fuzzy search for patient appointments. Used for patient appointment search bar\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/IncidentRepository.ts",
"new_path": "src/clients/db/IncidentRepository.ts",
"diff": "-import { incidents } from '../../config/pouchdb'\n+import { localDb } from '../../config/pouchdb'\nimport IncidentFilter from '../../incidents/IncidentFilter'\nimport Incident from '../../model/Incident'\nimport Repository from './Repository'\n@@ -8,7 +8,7 @@ interface SearchOptions {\n}\nclass IncidentRepository extends Repository<Incident> {\nconstructor() {\n- super(incidents)\n+ super(localDb)\n}\nasync search(options: SearchOptions): Promise<Incident[]> {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/LabRepository.ts",
"new_path": "src/clients/db/LabRepository.ts",
"diff": "-import { labs } from '../../config/pouchdb'\n+import { localDb } from '../../config/pouchdb'\nimport Lab from '../../model/Lab'\nimport generateCode from '../../util/generateCode'\nimport Repository from './Repository'\n@@ -11,7 +11,7 @@ interface SearchContainer {\n}\nclass LabRepository extends Repository<Lab> {\nconstructor() {\n- super(labs)\n+ super(localDb)\n}\nasync search(container: SearchContainer): Promise<Lab[]> {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/clients/db/PatientRepository.ts",
"new_path": "src/clients/db/PatientRepository.ts",
"diff": "import escapeStringRegexp from 'escape-string-regexp'\n-import { patients } from '../../config/pouchdb'\n+import { localDb } from '../../config/pouchdb'\nimport Patient from '../../model/Patient'\nimport generateCode from '../../util/generateCode'\nimport Page from '../Page'\n@@ -10,8 +10,8 @@ import SortRequest, { Unsorted } from './SortRequest'\nclass PatientRepository extends Repository<Patient> {\nconstructor() {\n- super(patients)\n- patients.createIndex({\n+ super(localDb)\n+ localDb.createIndex({\nindex: { fields: ['index'] },\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/Navbar.tsx",
"new_path": "src/components/Navbar.tsx",
"diff": "import { Navbar as HospitalRunNavbar } from '@hospitalrun/components'\nimport React from 'react'\nimport { useTranslation } from 'react-i18next'\n-import { useSelector } from 'react-redux'\n+import { useDispatch, useSelector } from 'react-redux'\nimport { useHistory } from 'react-router-dom'\nimport pageMap, { Page } from '../pageMap'\nimport { RootState } from '../store'\n+import {logout} from \"../user/user-slice\";\nconst Navbar = () => {\n- const { permissions } = useSelector((state: RootState) => state.user)\n- const { t } = useTranslation()\n+ const dispatch = useDispatch()\nconst history = useHistory()\n+ const { t } = useTranslation()\n+ const { permissions } = useSelector((state: RootState) => state.user)\nconst navigateTo = (location: string) => {\nhistory.push(location)\n@@ -92,6 +94,14 @@ const Navbar = () => {\nnavigateTo('/settings')\n},\n},\n+ {\n+ type: 'link',\n+ label: t('logout'),\n+ onClick: () => {\n+ dispatch(logout())\n+ navigateTo('/login')\n+ },\n+ },\n],\nclassName: 'pl-2 d-none d-md-block nav-account',\niconClassName: 'align-bottom',\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/PrivateRoute.tsx",
"new_path": "src/components/PrivateRoute.tsx",
"diff": "@@ -3,7 +3,11 @@ import { Route, Redirect } from 'react-router-dom'\nconst PrivateRoute = ({ component, isAuthenticated, ...rest }: any) => {\nconst routeComponent = (props: any) =>\n- isAuthenticated ? React.createElement(component, props) : <Redirect to={{ pathname: '/' }} />\n+ isAuthenticated ? (\n+ React.createElement(component, props)\n+ ) : (\n+ <Redirect to={{ pathname: '/login' }} />\n+ )\nreturn <Route {...rest} render={routeComponent} />\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/components/input/TextInputWithLabelFormGroup.tsx",
"new_path": "src/components/input/TextInputWithLabelFormGroup.tsx",
"diff": "@@ -6,7 +6,7 @@ interface Props {\nlabel?: string\nname: string\nisEditable?: boolean\n- type: 'text' | 'email' | 'number' | 'tel'\n+ type: 'text' | 'email' | 'number' | 'tel' | 'password'\nplaceholder?: string\nonChange?: (event: React.ChangeEvent<HTMLInputElement>) => void\nisRequired?: boolean\n"
},
{
"change_type": "MODIFY",
"old_path": "src/config/pouchdb.ts",
"new_path": "src/config/pouchdb.ts",
"diff": "@@ -3,30 +3,27 @@ import PouchDB from 'pouchdb'\n/* eslint-disable */\nconst memoryAdapter = require('pouchdb-adapter-memory')\nconst search = require('pouchdb-quick-search')\n+const relationalPouch = require('relational-pouch')\nimport PouchdbFind from 'pouchdb-find'\n+import PouchAuth from 'pouchdb-authentication'\n/* eslint-enable */\nPouchDB.plugin(search)\nPouchDB.plugin(memoryAdapter)\n+PouchDB.plugin(relationalPouch)\nPouchDB.plugin(PouchdbFind)\n+PouchDB.plugin(PouchAuth)\n-function createDb(name: string) {\n- if (process.env.NODE_ENV === 'test') {\n- return new PouchDB(name, { adapter: 'memory' })\n- }\n+export const remoteDb = new PouchDB(`${process.env.REACT_APP_HOSPITALRUN_API}/hospitalrun`, {\n+ skip_setup: true,\n+})\n- const db = new PouchDB(name)\n- db.sync(`${process.env.REACT_APP_HOSPITALRUN_API}/_db/${name}`, {\n- live: true,\n- retry: true,\n- }).on('change', (info) => {\n+export const localDb = new PouchDB('local_hospitalrun')\n+localDb\n+ .sync(remoteDb, { live: true, retry: true })\n+ .on('change', (info) => {\nconsole.log(info)\n})\n-\n- return db\n-}\n-\n-export const patients = createDb('patients')\n-export const appointments = createDb('appointments')\n-export const labs = createDb('labs')\n-export const incidents = createDb('incidents')\n+ .on('error', (info) => {\n+ console.error(info)\n+ })\n"
},
{
"change_type": "ADD",
"old_path": "src/images/logo-on-transparent.png",
"new_path": "src/images/logo-on-transparent.png",
"diff": "Binary files /dev/null and b/src/images/logo-on-transparent.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "src/incidents/incident-slice.ts",
"new_path": "src/incidents/incident-slice.ts",
"diff": "@@ -108,7 +108,7 @@ export const reportIncident = (\nif (isEmpty(incidentError)) {\nincident.reportedOn = new Date(Date.now()).toISOString()\nincident.code = getIncidentCode()\n- incident.reportedBy = getState().user.user.id\n+ incident.reportedBy = getState().user.user?.id || ''\nincident.status = 'reported'\nconst newIncident = await IncidentRepository.save(incident)\nawait dispatch(reportIncidentSuccess(newIncident))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/index.tsx",
"new_path": "src/index.tsx",
"diff": "@@ -5,6 +5,7 @@ import '@hospitalrun/components/scss/main.scss'\nimport './index.css'\nimport App from './App'\nimport * as serviceWorker from './serviceWorker'\n+\nimport './i18n'\nReactDOM.render(<App />, document.getElementById('root'))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/labs/lab-slice.ts",
"new_path": "src/labs/lab-slice.ts",
"diff": "@@ -116,7 +116,7 @@ export const requestLab = (newLab: Lab, onSuccess?: (lab: Lab) => void): AppThun\n} else {\nnewLab.status = 'requested'\nnewLab.requestedOn = new Date(Date.now().valueOf()).toISOString()\n- newLab.requestedBy = getState().user.user.id\n+ newLab.requestedBy = getState().user.user?.id || ''\nconst requestedLab = await LabRepository.save(newLab)\ndispatch(requestLabSuccess(requestedLab))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/login/Login.tsx",
"diff": "+import { Alert, Container, Panel } from '@hospitalrun/components'\n+import React, { useEffect, useState } from 'react'\n+import Button from 'react-bootstrap/Button'\n+import { useDispatch, useSelector } from 'react-redux'\n+import { Redirect } from 'react-router-dom'\n+\n+import TextInputWithLabelFormGroup from '../components/input/TextInputWithLabelFormGroup'\n+import { remoteDb } from '../config/pouchdb'\n+import logo from '../images/logo-on-transparent.png'\n+import { RootState } from '../store'\n+import { getCurrentSession, login } from '../user/user-slice'\n+\n+const Login = () => {\n+ const dispatch = useDispatch()\n+ const [username, setUsername] = useState('')\n+ const [password, setPassword] = useState('')\n+ const { loginError, user } = useSelector((root: RootState) => root.user)\n+ const [loading, setLoading] = useState(true)\n+\n+ useEffect(() => {\n+ const init = async () => {\n+ const session = await remoteDb.getSession()\n+ console.log(session)\n+ if (session.userCtx.name) {\n+ await dispatch(getCurrentSession(session.userCtx.name))\n+ }\n+ setLoading(false)\n+ }\n+\n+ init()\n+ }, [dispatch])\n+\n+ const onUsernameChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n+ const { value } = event.currentTarget\n+ setUsername(value)\n+ }\n+\n+ const onPasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n+ const { value } = event.currentTarget\n+ setPassword(value)\n+ }\n+\n+ const onSignInClick = async () => {\n+ await dispatch(login(username, password))\n+ }\n+\n+ if (loading) {\n+ return null\n+ }\n+\n+ if (user) {\n+ return <Redirect to=\"/\" />\n+ }\n+\n+ return (\n+ <>\n+ <Container className=\"container align-items-center\" style={{ width: '50%' }}>\n+ <img src={logo} alt=\"HospitalRun\" style={{ width: '100%', textAlign: 'center' }} />\n+ <form>\n+ <Panel title=\"Please Sign In\" color=\"primary\">\n+ {loginError && <Alert color=\"danger\" message={loginError} title=\"Unable to login\" />}\n+ <TextInputWithLabelFormGroup\n+ isEditable\n+ label=\"username\"\n+ name=\"username\"\n+ value={username}\n+ onChange={onUsernameChange}\n+ />\n+ <TextInputWithLabelFormGroup\n+ isEditable\n+ type=\"password\"\n+ label=\"password\"\n+ name=\"password\"\n+ value={password}\n+ onChange={onPasswordChange}\n+ />\n+ <Button block onClick={onSignInClick}>\n+ Sign In\n+ </Button>\n+ </Panel>\n+ </form>\n+ </Container>\n+ </>\n+ )\n+}\n+\n+export default Login\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "import { createSlice, PayloadAction } from '@reduxjs/toolkit'\n+import { remoteDb } from '../config/pouchdb'\nimport Permissions from '../model/Permissions'\nimport User from '../model/User'\n+import { AppThunk } from '../store'\ninterface UserState {\npermissions: (Permissions | null)[]\n- user: User\n+ user?: User\n+ loginError?: string\n}\nconst initialState: UserState = {\n@@ -28,11 +31,6 @@ const initialState: UserState = {\nPermissions.AddCarePlan,\nPermissions.ReadCarePlan,\n],\n- user: {\n- id: 'some-hardcoded-id',\n- givenName: 'HospitalRun',\n- familyName: 'Fake User',\n- } as User,\n}\nconst userSlice = createSlice({\n@@ -42,9 +40,48 @@ const userSlice = createSlice({\nfetchPermissions(state, { payload }: PayloadAction<Permissions[]>) {\nstate.permissions = payload\n},\n+ loginSuccess(state, { payload }: PayloadAction<User>) {\n+ state.user = payload\n+ },\n+ loginError(state, { payload }: PayloadAction<string>) {\n+ state.loginError = payload\n+ },\n+ logoutSuccess(state) {\n+ state.user = undefined\n+ },\n},\n})\n-export const { fetchPermissions } = userSlice.actions\n+export const { fetchPermissions, loginError, loginSuccess, logoutSuccess } = userSlice.actions\n+\n+export const getCurrentSession = (username: string): AppThunk => async (dispatch) => {\n+ const user = await remoteDb.getUser(username)\n+ dispatch(\n+ loginSuccess({\n+ id: user._id,\n+ givenName: (user as any).metadata.givenName,\n+ familyName: (user as any).metadata.familyName,\n+ }),\n+ )\n+}\n+\n+export const login = (username: string, password: string): AppThunk => async (dispatch) => {\n+ console.log(`login ${username} : ${password}`)\n+ try {\n+ const response = await remoteDb.logIn(username, password)\n+ dispatch(getCurrentSession(response.name))\n+ } catch (error) {\n+ console.log(error.status)\n+ if (error.status === '401') {\n+ dispatch(loginError('Username or password is incorrect.'))\n+ }\n+ }\n+ console.log(dispatch)\n+}\n+\n+export const logout = (): AppThunk => async (dispatch) => {\n+ await remoteDb.logOut()\n+ dispatch(logoutSuccess())\n+}\nexport default userSlice.reducer\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | working login example |
288,323 | 13.06.2020 23:22:54 | 18,000 | 4b79036bc05ec61dc2120413ab20c800863fa546 | fix care plan routing | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/patients/care-plans/ViewCarePlan.test.tsx",
"new_path": "src/__tests__/patients/care-plans/ViewCarePlan.test.tsx",
"diff": "@@ -22,7 +22,7 @@ describe('View Care Plan', () => {\n} as Patient\nconst setup = () => {\n- const store = mockStore({ patient: { patient } } as any)\n+ const store = mockStore({ patient: { patient }, user: { user: { id: '123' } } } as any)\nconst history = createMemoryHistory()\nhistory.push(`/patients/${patient.id}/care-plans/${patient.carePlans[0].id}`)\nconst wrapper = mount(\n"
},
{
"change_type": "MODIFY",
"old_path": "src/config/pouchdb.ts",
"new_path": "src/config/pouchdb.ts",
"diff": "@@ -14,19 +14,27 @@ PouchDB.plugin(RelationalPouch)\nPouchDB.plugin(PouchdbFind)\nPouchDB.plugin(PouchAuth)\n-export const remoteDb = new PouchDB(`${process.env.REACT_APP_HOSPITALRUN_API}/hospitalrun`, {\n+let serverDb\n+let localDb\n+\n+if (process.env.NODE_ENV === 'test') {\n+ serverDb = new PouchDB('hospitalrun', { adapter: 'memory' })\n+ localDb = new PouchDB('local_hospitalrun', { adapter: 'memory' })\n+} else {\n+ serverDb = new PouchDB(`${process.env.REACT_APP_HOSPITALRUN_API}/hospitalrun`, {\nskip_setup: true,\n})\n-const localDb = new PouchDB('local_hospitalrun')\n+ localDb = new PouchDB('local_hospitalrun')\nlocalDb\n- .sync(remoteDb, { live: true, retry: true })\n+ .sync(serverDb, { live: true, retry: true })\n.on('change', (info) => {\nconsole.log(info)\n})\n.on('error', (info) => {\nconsole.error(info)\n})\n+}\nexport const schema = [\n{\n@@ -54,5 +62,5 @@ export const schema = [\nrelations: { patient: { belongsTo: 'patient' } },\n},\n]\n-\nexport const relationalDb = localDb.setSchema(schema)\n+export const remoteDb = serverDb as PouchDB.Database\n"
},
{
"change_type": "MODIFY",
"old_path": "src/login/Login.tsx",
"new_path": "src/login/Login.tsx",
"diff": "@@ -20,7 +20,6 @@ const Login = () => {\nuseEffect(() => {\nconst init = async () => {\nconst session = await remoteDb.getSession()\n- console.log(session)\nif (session.userCtx.name) {\nawait dispatch(getCurrentSession(session.userCtx.name))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/care-plans/CarePlanTab.tsx",
"new_path": "src/patients/care-plans/CarePlanTab.tsx",
"diff": "@@ -2,7 +2,7 @@ import { Button } from '@hospitalrun/components'\nimport React, { useState } from 'react'\nimport { useTranslation } from 'react-i18next'\nimport { useSelector } from 'react-redux'\n-import { Route, Switch } from 'react-router-dom'\n+import { Route, Switch, useRouteMatch } from 'react-router-dom'\nimport Permissions from '../../model/Permissions'\nimport { RootState } from '../../store'\n@@ -12,6 +12,7 @@ import ViewCarePlan from './ViewCarePlan'\nconst CarePlanTab = () => {\nconst { t } = useTranslation()\n+ const { path } = useRouteMatch()\nconst { permissions } = useSelector((state: RootState) => state.user)\nconst [showAddCarePlanModal, setShowAddCarePlanModal] = useState(false)\nreturn (\n@@ -33,10 +34,10 @@ const CarePlanTab = () => {\n</div>\n<br />\n<Switch>\n- <Route exact path=\"/patients/:id/care-plans\">\n+ <Route exact path={path}>\n<CarePlanTable />\n</Route>\n- <Route exact path=\"/patients/:id/care-plans/:carePlanId\">\n+ <Route exact path={`${path}/:carePlanId`}>\n<ViewCarePlan />\n</Route>\n</Switch>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/care-plans/ViewCarePlan.tsx",
"new_path": "src/patients/care-plans/ViewCarePlan.tsx",
"diff": "import findLast from 'lodash/findLast'\nimport React, { useEffect, useState } from 'react'\nimport { useSelector } from 'react-redux'\n-import { useParams } from 'react-router'\n+import { useParams } from 'react-router-dom'\nimport CarePlan from '../../model/CarePlan'\nimport { RootState } from '../../store'\n"
},
{
"change_type": "MODIFY",
"old_path": "src/patients/view/ViewPatient.tsx",
"new_path": "src/patients/view/ViewPatient.tsx",
"diff": "@@ -2,7 +2,14 @@ import { Panel, Spinner, TabsHeader, Tab, Button } from '@hospitalrun/components\nimport React, { useEffect } from 'react'\nimport { useTranslation } from 'react-i18next'\nimport { useDispatch, useSelector } from 'react-redux'\n-import { useParams, withRouter, Route, useHistory, useLocation } from 'react-router-dom'\n+import {\n+ useParams,\n+ withRouter,\n+ Route,\n+ useHistory,\n+ useLocation,\n+ useRouteMatch\n+} from 'react-router-dom'\nimport useAddBreadcrumbs from '../../breadcrumbs/useAddBreadcrumbs'\nimport Patient from '../../model/Patient'\n@@ -34,6 +41,7 @@ const ViewPatient = () => {\nconst history = useHistory()\nconst dispatch = useDispatch()\nconst location = useLocation()\n+ const { path } = useRouteMatch()\nconst { patient, status } = useSelector((state: RootState) => state.patient)\nconst { permissions } = useSelector((state: RootState) => state.user)\n@@ -127,28 +135,28 @@ const ViewPatient = () => {\n/>\n</TabsHeader>\n<Panel>\n- <Route exact path=\"/patients/:id\">\n+ <Route exact path={path}>\n<GeneralInformation patient={patient} />\n</Route>\n- <Route exact path=\"/patients/:id/relatedpersons\">\n+ <Route exact path={`${path}/relatedpersons`}>\n<RelatedPerson patient={patient} />\n</Route>\n- <Route exact path=\"/patients/:id/appointments\">\n+ <Route exact path={`${path}/appointments`}>\n<AppointmentsList patientId={patient.id} />\n</Route>\n- <Route exact path=\"/patients/:id/allergies\">\n+ <Route exact path={`${path}/allergies`}>\n<Allergies patient={patient} />\n</Route>\n- <Route exact path=\"/patients/:id/diagnoses\">\n+ <Route exact path={`${path}/diagnoses`}>\n<Diagnoses patient={patient} />\n</Route>\n- <Route exact path=\"/patients/:id/notes\">\n+ <Route exact path={`${path}/notes`}>\n<Note patient={patient} />\n</Route>\n- <Route exact path=\"/patients/:id/labs\">\n+ <Route exact path={`${path}/labs`}>\n<Labs patientId={patient.id} />\n</Route>\n- <Route path=\"/patients/:id/care-plans\">\n+ <Route path={`${path}/care-plans`}>\n<CarePlanTab />\n</Route>\n</Panel>\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | fix care plan routing |
288,323 | 17.06.2020 20:21:45 | 18,000 | 0e1b0919c79d4d8f7cd90916c58c2e9e8502084f | test: add tests for auth in user slice | [
{
"change_type": "MODIFY",
"old_path": "src/__tests__/user/user-slice.test.ts",
"new_path": "src/__tests__/user/user-slice.test.ts",
"diff": "+import configureMockStore from 'redux-mock-store'\n+import thunk from 'redux-thunk'\n+\n+import { remoteDb } from '../../config/pouchdb'\nimport Permissions from '../../model/Permissions'\n-import user, { fetchPermissions } from '../../user/user-slice'\n+import { RootState } from '../../store'\n+import user, {\n+ fetchPermissions,\n+ getCurrentSession,\n+ login,\n+ loginSuccess,\n+ loginError,\n+ logout,\n+ logoutSuccess,\n+} from '../../user/user-slice'\n+\n+const mockStore = configureMockStore<RootState, any>([thunk])\ndescribe('user slice', () => {\n+ describe('reducers', () => {\nit('should handle the FETCH_PERMISSIONS action', () => {\nconst expectedPermissions = [Permissions.ReadPatients, Permissions.WritePatients]\nconst userStore = user(undefined, {\n@@ -11,4 +27,134 @@ describe('user slice', () => {\nexpect(userStore.permissions).toEqual(expectedPermissions)\n})\n+\n+ it('should handle the LOGIN_SUCCESS action', () => {\n+ const expectedUser = {\n+ familyName: 'firstName',\n+ givenName: 'lastName',\n+ id: 'id',\n+ }\n+ const expectedPermissions = [Permissions.WritePatients]\n+ const userStore = user(undefined, {\n+ type: loginSuccess.type,\n+ payload: { user: expectedUser, permissions: expectedPermissions },\n+ })\n+\n+ expect(userStore.user).toEqual(expectedUser)\n+ })\n+\n+ it('should handle the login error', () => {\n+ const expectedError = 'error'\n+ const userStore = user(undefined, {\n+ type: loginError.type,\n+ payload: expectedError,\n+ })\n+\n+ expect(userStore.loginError).toEqual(expectedError)\n+ })\n+\n+ it('should handle the logout success', () => {\n+ const userStore = user(\n+ { user: { givenName: 'given', familyName: 'family', id: 'id' }, permissions: [] },\n+ {\n+ type: logoutSuccess.type,\n+ },\n+ )\n+\n+ expect(userStore.user).toEqual(undefined)\n+ expect(userStore.permissions).toEqual([])\n+ })\n+ })\n+\n+ describe('login', () => {\n+ beforeEach(() => {\n+ jest.resetAllMocks()\n+ })\n+\n+ it('should login with the username and password', async () => {\n+ jest.spyOn(remoteDb, 'logIn').mockResolvedValue({ name: 'test', ok: true })\n+ jest.spyOn(remoteDb, 'getUser').mockResolvedValue({\n+ _id: 'userId',\n+ metadata: {\n+ givenName: 'test',\n+ familyName: 'user',\n+ },\n+ } as any)\n+ const store = mockStore()\n+ const expectedUsername = 'test'\n+ const expectedPassword = 'password'\n+\n+ await store.dispatch(login(expectedUsername, expectedPassword))\n+\n+ expect(remoteDb.logIn).toHaveBeenCalledTimes(1)\n+ expect(remoteDb.logIn).toHaveBeenLastCalledWith(expectedUsername, expectedPassword)\n+ expect(remoteDb.getUser).toHaveBeenCalledWith(expectedUsername)\n+ expect(store.getActions()[0]).toEqual({\n+ type: loginSuccess.type,\n+ payload: expect.objectContaining({\n+ user: { familyName: 'user', givenName: 'test', id: 'userId' },\n+ }),\n+ })\n+ })\n+\n+ it('should dispatch login error if login was not successful', async () => {\n+ jest.spyOn(remoteDb, 'logIn').mockRejectedValue({ status: '401' })\n+ jest.spyOn(remoteDb, 'getUser').mockResolvedValue({\n+ _id: 'userId',\n+ metadata: {\n+ givenName: 'test',\n+ familyName: 'user',\n+ },\n+ } as any)\n+ const store = mockStore()\n+\n+ await store.dispatch(login('user', 'password'))\n+\n+ expect(remoteDb.getUser).not.toHaveBeenCalled()\n+ expect(store.getActions()[0]).toEqual({\n+ type: loginError.type,\n+ payload: 'user.login.error',\n+ })\n+ })\n+ })\n+\n+ describe('logout', () => {\n+ beforeEach(() => {\n+ jest.resetAllMocks()\n+ })\n+\n+ it('should logout the user', async () => {\n+ jest.spyOn(remoteDb, 'logOut').mockImplementation(jest.fn())\n+ const store = mockStore()\n+\n+ await store.dispatch(logout())\n+\n+ expect(remoteDb.logOut).toHaveBeenCalledTimes(1)\n+ expect(store.getActions()[0]).toEqual({ type: logoutSuccess.type })\n+ })\n+ })\n+\n+ describe('getCurrentSession', () => {\n+ it('should get the detail of the current user and update the store', async () => {\n+ jest.spyOn(remoteDb, 'getUser').mockResolvedValue({\n+ _id: 'userId',\n+ metadata: {\n+ givenName: 'test',\n+ familyName: 'user',\n+ },\n+ } as any)\n+ const store = mockStore()\n+ const expectedUsername = 'test'\n+\n+ await store.dispatch(getCurrentSession(expectedUsername))\n+\n+ expect(remoteDb.getUser).toHaveBeenCalledWith(expectedUsername)\n+ expect(store.getActions()[0]).toEqual({\n+ type: loginSuccess.type,\n+ payload: expect.objectContaining({\n+ user: { familyName: 'user', givenName: 'test', id: 'userId' },\n+ }),\n+ })\n+ })\n+ })\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "src/login/Login.tsx",
"new_path": "src/login/Login.tsx",
"diff": "@@ -19,10 +19,14 @@ const Login = () => {\nuseEffect(() => {\nconst init = async () => {\n+ try {\nconst session = await remoteDb.getSession()\nif (session.userCtx.name) {\nawait dispatch(getCurrentSession(session.userCtx.name))\n}\n+ } catch (e) {\n+ console.log(e)\n+ }\nsetLoading(false)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/user/user-slice.ts",
"new_path": "src/user/user-slice.ts",
"diff": "@@ -40,14 +40,19 @@ const userSlice = createSlice({\nfetchPermissions(state, { payload }: PayloadAction<Permissions[]>) {\nstate.permissions = payload\n},\n- loginSuccess(state, { payload }: PayloadAction<User>) {\n- state.user = payload\n+ loginSuccess(\n+ state,\n+ { payload }: PayloadAction<{ user: User; permissions: (Permissions | null)[] }>,\n+ ) {\n+ state.user = payload.user\n+ state.permissions = initialState.permissions\n},\nloginError(state, { payload }: PayloadAction<string>) {\nstate.loginError = payload\n},\nlogoutSuccess(state) {\nstate.user = undefined\n+ state.permissions = []\n},\n},\n})\n@@ -58,9 +63,12 @@ export const getCurrentSession = (username: string): AppThunk => async (dispatch\nconst user = await remoteDb.getUser(username)\ndispatch(\nloginSuccess({\n+ user: {\nid: user._id,\ngivenName: (user as any).metadata.givenName,\nfamilyName: (user as any).metadata.familyName,\n+ },\n+ permissions: initialState.permissions,\n}),\n)\n}\n@@ -68,10 +76,20 @@ export const getCurrentSession = (username: string): AppThunk => async (dispatch\nexport const login = (username: string, password: string): AppThunk => async (dispatch) => {\ntry {\nconst response = await remoteDb.logIn(username, password)\n- dispatch(getCurrentSession(response.name))\n+ const user = await remoteDb.getUser(response.name)\n+ dispatch(\n+ loginSuccess({\n+ user: {\n+ id: user._id,\n+ givenName: (user as any).metadata.givenName,\n+ familyName: (user as any).metadata.familyName,\n+ },\n+ permissions: initialState.permissions,\n+ }),\n+ )\n} catch (error) {\nif (error.status === '401') {\n- dispatch(loginError('Username or password is incorrect.'))\n+ dispatch(loginError('user.login.error'))\n}\n}\n}\n"
}
] | TypeScript | MIT License | hospitalrun/hospitalrun-frontend | test: add tests for auth in user slice |
Subsets and Splits