Skip to content

Commit

Permalink
feat: enable history on ccbc communities
Browse files Browse the repository at this point in the history
  • Loading branch information
RRanath committed Jan 3, 2025
1 parent 48b22c4 commit ee2c7f6
Show file tree
Hide file tree
Showing 14 changed files with 726 additions and 26 deletions.
45 changes: 29 additions & 16 deletions app/components/Analyst/CBC/History/CbcHistoryCommunitiesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,35 @@ import styled from 'styled-components';
interface Props {
action: string;
communities: any[];
isCbc: boolean;
}

interface TableProps {
isCbc: boolean;
isDeleted?: boolean;
}

const StyledCommunitiesContainer = styled.div`
display: flex;
align-items: center;
`;

const StyledLeftContainer = styled.div`
const StyledLeftContainer = styled.div<TableProps>`
padding-right: 2%;
width: 250px;
width: ${(props) => (props.isCbc ? '250px' : '300px')};
`;

const StyledTable = styled.table`
const StyledTable = styled.table<TableProps>`
th {
border: none;
}
tbody > tr {
border-bottom: thin dashed;
text-decoration: ${(props) => (props.isDeleted ? 'line-through' : 'none')};
border-color: ${(props) => props.theme.color.borderGrey};
td {
width: 200px;
max-width: 200px;
width: ${(props) => (props.isCbc ? '200px' : '350px')};
max-width: ${(props) => (props.isCbc ? '200px' : '350px')};
border: none;
}
}
Expand All @@ -37,22 +44,26 @@ const StyledIdCell = styled.td`

const CbcHistoryCommunitiesTable: React.FC<Props> = ({
action,
communities,
communities = [],
isCbc = true,
}) => {
return (
<StyledCommunitiesContainer
style={{ display: 'flex', alignItems: 'center' }}
>
<StyledLeftContainer>{`${action} community location data`}</StyledLeftContainer>
<StyledLeftContainer
isCbc={isCbc}
isDeleted={action === 'Deleted'}
>{`${action} community location data`}</StyledLeftContainer>
<div>
<StyledTable>
<StyledTable isCbc={isCbc} isDeleted={action === 'Deleted'}>
<thead>
<tr>
<th>Economic Region</th>
<th>Regional District</th>
<th>Geographic Name</th>
<th>Type</th>
<th>ID</th>
{isCbc && <th>Geographic Name</th>}
{isCbc && <th>Type</th>}
{isCbc && <th>ID</th>}
</tr>
</thead>
<tbody>
Expand All @@ -64,11 +75,13 @@ const CbcHistoryCommunitiesTable: React.FC<Props> = ({
>
<td>{community.economic_region}</td>
<td>{community.regional_district}</td>
<td>{community.bc_geographic_name}</td>
<td>{community.geographic_type}</td>
<StyledIdCell>
{community.communities_source_data_id}
</StyledIdCell>
{isCbc && <td>{community.bc_geographic_name}</td>}
{isCbc && <td>{community.geographic_type}</td>}
{isCbc && (
<StyledIdCell>
{community.communities_source_data_id}
</StyledIdCell>
)}
</tr>
))}
</tbody>
Expand Down
41 changes: 41 additions & 0 deletions app/components/Analyst/History/HistoryContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ import gis from 'formSchema/uiSchema/history/gis';
import gisAssessmentHhSchema from 'formSchema/uiSchema/history/gisAssessmentHh';
import applicationSowDataSchema from 'formSchema/uiSchema/history/applicationSowData';
import applicationAnnounced from 'formSchema/uiSchema/history/applicationAnnounced';
import { processArrayDiff } from 'components/DiffTable';
import communities from 'formSchema/uiSchema/history/communities';
import StatusPill from '../../StatusPill';
import HistoryDetails from './HistoryDetails';
import HistoryAttachment from './HistoryAttachment';
import HistoryFile from './HistoryFile';
import CbcHistoryCommunitiesTable from '../CBC/History/CbcHistoryCommunitiesTable';

const StyledContent = styled.span`
display: flex;
Expand Down Expand Up @@ -68,6 +71,13 @@ const filterArrays = (obj: Record<string, any>): Record<string, any> => {
return Object.fromEntries(filteredEntries);
};

const processCommunity = (values) => {
return values?.map((community) => ({
economic_region: community.er,
regional_district: community.rd,
}));
};

const HistoryContent = ({
historyItem,
prevHistoryItem,
Expand Down Expand Up @@ -972,6 +982,37 @@ const HistoryContent = ({
);
}

if (tableName === 'communities') {
const user =
createdBy === 1 && op === 'INSERT' ? 'The system' : displayName;
const changes = diff(prevHistoryItem?.record || {}, record);
const [newArray, oldArray] = processArrayDiff(
changes,
communities.applicationCommunities
);

return (
<>
<StyledContent data-testid="history-content-communities">
<span>
{user} updated the coverage area for the project which resulted in a
change to <b>Community Location Data</b> on {createdAtFormatted}
</span>
</StyledContent>
<CbcHistoryCommunitiesTable
action="Added"
communities={processCommunity(newArray)}
isCbc={false}
/>
<CbcHistoryCommunitiesTable
action="Deleted"
communities={processCommunity(oldArray)}
isCbc={false}
/>
</>
);
}

return null;
};

Expand Down
1 change: 1 addition & 0 deletions app/components/Analyst/History/HistoryIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const iconMap = {
application_community_progress_report_data: faTreeCity,
application_milestone_data: faSignsPost,
application_project_type: faWifi,
communities: faClipboardList,
};

interface Props {
Expand Down
11 changes: 11 additions & 0 deletions app/components/Analyst/History/HistoryTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { graphql, useFragment } from 'react-relay';
import { getFiscalQuarter, getFiscalYear } from 'utils/fiscalFormat';
import { HistoryTable_query$key } from '__generated__/HistoryTable_query.graphql';
import { useMemo, useState } from 'react';
import isEqual from 'lodash.isequal';
import HistoryRow from './HistoryRow';
import HistoryFilter, {
filterByType,
Expand Down Expand Up @@ -240,6 +241,16 @@ const HistoryTable: React.FC<Props> = ({ query }) => {
}

const prevHistoryItem = prevItems.length > 0 ? prevItems[0] : {};
// Skipping duplicate history items for communities
if (
historyItem?.tableName === 'communities' &&
isEqual(
prevHistoryItem.record?.application_er,
historyItem.record?.application_er
)
) {
return null;
}
// using index + recordId for key as just recordId was causing strange duplicate record bug for delete history item until page refresh
return (
<HistoryRow
Expand Down
44 changes: 44 additions & 0 deletions app/components/DiffTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,50 @@ const generateDiffTable = (
) : null;
};

function createObjectFromSchema(schema, data) {
const keys = Object.keys(schema.properties);
return keys.reduce((acc, key) => {
acc[key] = data[key];
return acc;
}, {});
}

export const processArrayDiff = (changes, schema) => {
const newArray = [];
const oldArray = [];

const entries = Object.entries(changes);
entries.forEach(([key, value]) => {
if (key.endsWith('__added') && Array.isArray(value)) {
newArray.push(...value);
} else if (key.endsWith('__deleted') && Array.isArray(value)) {
oldArray.push(...value);
} else if (Array.isArray(value)) {
value.forEach(([prefix, diffValue]) => {
if (prefix === '-') {
oldArray.push(diffValue);
} else if (prefix === '~') {
['__old', '__new'].forEach((childKey, idx) => {
const newObject = createObjectFromSchema(schema, {
er: diffValue.er[childKey],
rd: diffValue.rd[childKey],
});
if (idx === 0) {
oldArray.push(newObject);
} else {
newArray.push(newObject);
}
});
} else if (prefix === '+') {
newArray.push(diffValue);
}
});
}
});

return [newArray, oldArray];
};

interface Props {
changes: any;
diffSchema: any;
Expand Down
14 changes: 14 additions & 0 deletions app/formSchema/uiSchema/history/communities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const communities = {
applicationCommunities: {
properties: {
er: {
title: 'Economic Regions',
},
rd: {
title: 'Regional Districts',
},
},
},
};

export default communities;
2 changes: 2 additions & 0 deletions app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
"jsonlint": "^1.6.3",
"jsonwebtoken": "^9.0.2",
"lightship": "7.2.0",
"lodash.isequal": "^4.5.0",
"luxon": "^3.5.0",
"material-react-table": "2.13",
"morgan": "^1.10.0",
Expand Down Expand Up @@ -131,6 +132,7 @@
"@types/express": "^4.17.21",
"@types/jest": "^28.1.6",
"@types/json-diff": "^1.0.3",
"@types/lodash.isequal": "^4.5.8",
"@types/luxon": "^3.4.2",
"@types/node": "20.14.14",
"@types/react": "18.3.12",
Expand Down
7 changes: 7 additions & 0 deletions app/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4033,6 +4033,13 @@
dependencies:
"@types/node" "*"

"@types/lodash.isequal@^4.5.8":
version "4.5.8"
resolved "https://registry.yarnpkg.com/@types/lodash.isequal/-/lodash.isequal-4.5.8.tgz#b30bb6ff6a5f6c19b3daf389d649ac7f7a250499"
integrity sha512-uput6pg4E/tj2LGxCZo9+y27JNyB2OZuuI/T5F+ylVDYuqICLG2/ktjxx0v6GvVntAf8TvEzeQLcV0ffRirXuA==
dependencies:
"@types/lodash" "*"

"@types/[email protected]":
version "4.5.0"
resolved "https://registry.yarnpkg.com/@types/lodash.template/-/lodash.template-4.5.0.tgz#277654af717ed37ce2687c69f8f221c550276b7a"
Expand Down
34 changes: 26 additions & 8 deletions cron/shp/sql/create_application_rd.sql
Original file line number Diff line number Diff line change
@@ -1,26 +1,44 @@
-- Step 1: Drop the table if it exists
DROP TABLE IF EXISTS ccbc_public.application_rd;

-- Step 2: Create table for Regional Districts (RD)
-- Step 2: Create the table explicitly with an auto-incrementing primary key and audit columns
CREATE TABLE ccbc_public.application_rd (
id SERIAL PRIMARY KEY, -- Auto-incrementing primary key
application_id INTEGER,
ccbc_number TEXT,
rd TEXT,
er TEXT,
created_by INTEGER DEFAULT NULL, -- User ID who created the record
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), -- Timestamp when the record was created
updated_by INTEGER DEFAULT NULL, -- User ID who last updated the record
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NULL, -- Timestamp when the record was last updated
archived_by INTEGER DEFAULT NULL, -- User ID who archived the record
archived_at TIMESTAMP WITH TIME ZONE DEFAULT NULL -- Timestamp when the record was archived
);

SELECT audit.enable_tracking('ccbc_public.application_rd'::regclass);

-- Step 3: Populate the table with data
WITH rd_regions AS (
SELECT
s.ccbc_numbe AS ccbc_number,
r.aa_name AS rd
r.aa_name AS rd,
er.cnmcrgnnm AS er
FROM
ccbc_public.ccbc_applications_coverages s
LEFT JOIN
ccbc_public.regional_districts r ON ST_Intersects(ST_makeValid(s.geom), r.geom)
ORDER BY
LEFT JOIN
ccbc_public.economic_regions er ON (ST_Area(ST_Intersection(ST_MakeValid(er.geom), ST_MakeValid(r.geom))) / ST_Area(ST_MakeValid(r.geom))) > 0.8
ORDER BY
s.ccbc_numbe
)

-- Step 3: Join with the application table to get the application_id and insert into new table
INSERT INTO ccbc_public.application_rd (application_id, ccbc_number, rd, er)
SELECT
a.id as application_id,
rd.ccbc_number,
rd.rd
INTO
ccbc_public.application_rd
rd.rd,
rd.er
FROM
rd_regions rd
JOIN
Expand Down
14 changes: 13 additions & 1 deletion db/deploy/computed_columns/application_history.sql
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,19 @@ union all
from ccbc_public.record_version as v
inner join ccbc_public.ccbc_user u on u.id = (v.record->>'updated_by')::int
where v.op='UPDATE' and v.table_name='application_dependencies' and v.record->>'archived_by' is null
and v.record->>'application_id'=application.id::varchar(10);
and v.record->>'application_id'=application.id::varchar(10)

union all
select application.id, v.created_at, v.op, v.table_name, (array_agg(v.record_id))[1] AS record_id,
jsonb_build_object('application_rd', jsonb_agg(jsonb_build_object('er', v.record->'er', 'rd', v.record->'rd'))) as record,
jsonb_agg(v.old_record) AS old_record,
MAX(v.record->>'application_rd') AS item,
u.family_name, u.given_name, u.session_sub, u.external_analyst, v.created_by
from ccbc_public.record_version as v
inner join ccbc_public.ccbc_user u on v.created_by=u.id
where v.op='INSERT' and v.table_name='application_rd' and v.record->>'archived_by' is null
and v.record->>'application_id'=application.id::varchar(10)
group by v.created_at, v.op, v.table_name, u.family_name, u.given_name, u.session_sub, u.external_analyst, v.created_by;

$$ language sql stable;

Expand Down
Loading

0 comments on commit ee2c7f6

Please sign in to comment.