Skip to content

Commit

Permalink
A bit of code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbyqiz448 committed Feb 28, 2024
1 parent af9955f commit 140969b
Show file tree
Hide file tree
Showing 2 changed files with 157 additions and 174 deletions.
Original file line number Diff line number Diff line change
@@ -1,199 +1,183 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState } from 'react';
import { useSimpleTabularView } from '@opensrp/react-utils';
import { RouteComponentProps } from 'react-router';
import { ILocation } from '@smile-cdr/fhirts/dist/FHIR-R4/interfaces/ILocation';
import { locationResourceType, URL_LOCATION_UNIT_EDIT, URL_LOCATION_UNIT_ADD } from '../../constants';
import {
BrokenPage,
useSearchParams,
TableLayout,
viewDetailsQuery,
PageHeader,
SearchForm,
locationResourceType,
URL_LOCATION_UNIT_EDIT,
URL_LOCATION_UNIT_ADD,
} from '../../constants';
import {
BrokenPage,
useSearchParams,
TableLayout,
viewDetailsQuery,
PageHeader,
SearchForm,
} from '@opensrp/react-utils';
import { Dictionary } from '@onaio/utils';
import { Helmet } from 'react-helmet';
import { useTranslation } from '../../mls';
import { Row, Col, Button, Divider, Dropdown, Popconfirm } from 'antd';
import { Row, Col, Button, Divider, Dropdown } from 'antd';
import { useHistory, Link } from 'react-router-dom';
import { RbacCheck, useUserRole } from '@opensrp/rbac';
import type { MenuProps } from 'antd';
import { MoreOutlined, PlusOutlined } from '@ant-design/icons';
import { LocationUnitDetail } from '../LocationUnitDetail';



interface RouteParams {
locationId: string | undefined;
locationId: string | undefined;
}

interface Props {
fhirBaseURL: string;
LocationPageSize: number;
fhirBaseURL: string;
LocationPageSize: number;
}

const getSearchParams = () => {
return { "_include": "Location:partof" };
return { _include: 'Location:partof' };
};

export type LocationListPropTypes = Props & RouteComponentProps<RouteParams>;



export const AllLocationListFlat: React.FC<LocationListPropTypes> = (props) => {
const { fhirBaseURL } = props;
const { t } = useTranslation();
const history = useHistory();
const [detailId, setDetailId] = useState<string>('');
const { addParam, sParams } = useSearchParams();
const userRole = useUserRole();
const resourceId = sParams.get(viewDetailsQuery) ?? undefined;

const {
queryValues: { data, isFetching, isLoading, error, refetch },
tablePaginationProps,
searchFormProps,
} = useSimpleTabularView<ILocation>(fhirBaseURL, locationResourceType, getSearchParams());

if (error && !data) {
return <BrokenPage errorMessage={(error as Error).message} />;
}

// this is for debugging
useEffect(() => {
console.log("Component mounted");
console.log("Data:", data);
console.log("Is Fetching:", isFetching);
console.log("Is Loading:", isLoading);
console.log("Error:", error);

return () => {
console.log("Component unmounted");
};
}, [data, isFetching, isLoading, error]);
// TODO delete this (useEffect)


const tableData: any[] = (data?.records ?? []).map((datum: Dictionary) => ({
key: datum.id,
id: datum.id,
name: datum.name,
}));

type TableData = typeof tableData[0];


const getItems = (record: TableData): MenuProps['items'] => {
return [

{
key: '1',
permissions: [],
label: (
<Button type="link" onClick={() => addParam(viewDetailsQuery, record.id)}>
View Details
</Button>
),
},
]
.filter((item) => userRole.hasPermissions(item.permissions))
.map((item) => {
const { permissions, ...rest } = item;
return rest;
});
};

const columns = [
// {
// title: t('Name'),
// dataIndex: 'name' as const,
// editable: true,
// },
{
title: t('Type'),
dataIndex: 'resourceType' as const,
editable: true,
},
{
title: t('Status'),
dataIndex: 'status' as const,
editable: true,
},
{
title: t('Parent'),
dataIndex: 'parent' as const,
editable: true,
},
{
title: t('Actions'),
width: '10%',

// eslint-disable-next-line react/display-name
render: (_: unknown, record: TableData) => (
<span className="d-flex align-items-center">
<RbacCheck permissions={['Location.update']}>
<>
<Link to={`${URL_LOCATION_UNIT_EDIT}/${record.id.toString()}`} className="m-0 p-1">
{t('Edit')}
</Link>
<Divider type="vertical" />
</>
</RbacCheck>
<Dropdown
menu={{ items: getItems(record) }}
placement="bottomRight"
arrow
trigger={['click']}
>
<MoreOutlined className="more-options" data-testid="action-dropdown" />
</Dropdown>
</span>
),
},
];



const tableProps = {
datasource: tableData,
columns,
loading: isFetching || isLoading,
pagination: tablePaginationProps,
};

return (
<div className="content-section">
<Helmet>
<title>{t('All Locations List')}</title>
</Helmet>
<PageHeader title={t('All Locations Flat')} />
<Row className="list-view">
<Col className="main-content">
<div className="main-content__header">
<SearchForm {...searchFormProps} />
<RbacCheck permissions={['Location.create']}>
<Link to={URL_LOCATION_UNIT_ADD}>
<Button type="primary" onClick={() => history.push(URL_LOCATION_UNIT_ADD)}>
<PlusOutlined />
{t('Add Location')}
</Button>
</Link>
</RbacCheck>
</div>
<TableLayout {...tableProps} />
</Col>
{detailId ? (
<LocationUnitDetail
fhirBaseUrl={fhirBaseURL}
onClose={() => setDetailId('')}
detailId={detailId}
/>
) : null}
</Row>
</div>
);
const { fhirBaseURL } = props;
const { t } = useTranslation();
const history = useHistory();
const [detailId, setDetailId] = useState<string>('');
const { addParam, sParams } = useSearchParams();
const userRole = useUserRole();
const resourceId = sParams.get(viewDetailsQuery) ?? undefined;

Check failure on line 50 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

'resourceId' is assigned a value but never used. Allowed unused vars must match /^_/u

const {
queryValues: { data, isFetching, isLoading, error, refetch },

Check failure on line 53 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

'refetch' is assigned a value but never used. Allowed unused vars must match /^_/u
tablePaginationProps,
searchFormProps,
} = useSimpleTabularView<ILocation>(fhirBaseURL, locationResourceType, getSearchParams());

if (error && !data) {
return <BrokenPage errorMessage={(error as Error).message} />;
}


Check failure on line 62 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

Replace `⏎··useEffect(()·=>·{⏎··` with `useEffect(()·=>·{`
useEffect(() => {

Check failure on line 63 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render

Check failure on line 63 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

Unexpected empty arrow function
}, [data, isFetching, isLoading, error]);

const tableData: any[] = (data?.records ?? []).map((datum: Dictionary) => ({

Check warning on line 66 in packages/fhir-location-management/src/components/AllLocationListFlat/index.tsx

View workflow job for this annotation

GitHub Actions / test (16.17.0, ubuntu-latest)

Unexpected any. Specify a different type
key: datum.id,
id: datum.id,
name: datum.name,
type: datum.physicalType.coding[0].display,
status: datum.status,
parent: datum.partOf,
}));

type TableData = typeof tableData[0];

const getItems = (record: TableData): MenuProps['items'] => {
return [
{
key: '1',
permissions: [],
label: (
<Button type="link" onClick={() => addParam(viewDetailsQuery, record.id)}>
View Details
</Button>
),
},
]
.filter((item) => userRole.hasPermissions(item.permissions))
.map((item) => {
const { permissions, ...rest } = item;
return rest;
});
};

const columns = [
{
title: t('Name'),
dataIndex: 'name' as const,
editable: true,
},
{
title: t('Type'),
dataIndex: 'type' as const,
editable: true,
},
{
title: t('Status'),
dataIndex: 'status' as const,
editable: true,
},
{
title: t('Parent'),
dataIndex: 'parent' as const,
editable: true,
},
{
title: t('Actions'),
width: '10%',

// eslint-disable-next-line react/display-name
render: (_: unknown, record: TableData) => (
<span className="d-flex align-items-center">
<RbacCheck permissions={['Location.update']}>
<>
<Link to={`${URL_LOCATION_UNIT_EDIT}/${record.id.toString()}`} className="m-0 p-1">
{t('Edit')}
</Link>
<Divider type="vertical" />
</>
</RbacCheck>
<Dropdown
menu={{ items: getItems(record) }}
placement="bottomRight"
arrow
trigger={['click']}
>
<MoreOutlined className="more-options" data-testid="action-dropdown" />
</Dropdown>
</span>
),
},
];

const tableProps = {
datasource: tableData,
columns,
loading: isFetching || isLoading,
pagination: tablePaginationProps,
};

return (
<div className="content-section">
<Helmet>
<title>{t('All Locations List')}</title>
</Helmet>
<PageHeader title={t('All Locations Flat')} />
<Row className="list-view">
<Col className="main-content">
<div className="main-content__header">
<SearchForm {...searchFormProps} />
<RbacCheck permissions={['Location.create']}>
<Link to={URL_LOCATION_UNIT_ADD}>
<Button type="primary" onClick={() => history.push(URL_LOCATION_UNIT_ADD)}>
<PlusOutlined />
{t('Add Location')}
</Button>
</Link>
</RbacCheck>
</div>
<TableLayout {...tableProps} />
</Col>
{detailId ? (
<LocationUnitDetail
fhirBaseUrl={fhirBaseURL}
onClose={() => setDetailId('')}
detailId={detailId}
/>
) : null}
</Row>
</div>
);
};




3 changes: 1 addition & 2 deletions packages/location-management/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import LocationUnitGroupAddEdit from './components/LocationUnitGroupAddEdit';
import Tree from './components/LocationTree';
import { FormInstances } from './components/LocationForm/utils';


export * as locationHierachyDucks from './ducks/location-hierarchy';
export * as updatedLocationHierachyDucks from './ducks/locationHierarchy';
export * from './ducks/types';
Expand All @@ -18,4 +17,4 @@ export * from './ducks/locationHierarchy/utils';
export * from './helpers/dataLoaders';
export * from './ducks/locationHierarchy/types';
export * from './ducks/location-units';
export * from '../../fhir-location-management/src/components/AllLocationListFlat'
export * from '../../fhir-location-management/src/components/AllLocationListFlat';

0 comments on commit 140969b

Please sign in to comment.