Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

482 dataset details page provision level view table #609

Merged

Conversation

GeorgeGoodall-GovUk
Copy link
Contributor

@GeorgeGoodall-GovUk GeorgeGoodall-GovUk commented Oct 31, 2024

What type of PR is this? (check all applicable)

  • Feature
  • Refactor

Description

This adds a data table displaying all entities for a given lpa/dataset

Related Tickets & Documents

QA Instructions, Screenshots, Recordings

image

Preview Link: https://submit-pr-609.herokuapp.com/organisations/local-authority:LBH/article-4-direction-area/data/1

It could be worth testing the pagination, as well as several different datasets

Added/updated tests?

  • Yes

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new middleware for handling dataset data views, including pagination and data fetching capabilities.
    • Added routes for retrieving dataset data with and without pagination.
    • New template for displaying data related to organisations and datasets.
  • Improvements

    • Enhanced error handling and validation across middleware functions.
    • Updated navigation components to reflect a shift from "issues" to "tasks."
    • Improved test cases to validate new navigation structures and ensure accurate rendering of task counts.
    • Updated dataset overview and task list templates to utilise task_count instead of issue_count.
    • Added pagination parameters and improved handling of dataset specifications in templates.
  • Documentation

    • Added comments to clarify the expected structure of parameters in templates.

@GeorgeGoodall-GovUk GeorgeGoodall-GovUk linked an issue Oct 31, 2024 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily adding new middleware functions and modifying existing ones. Key updates include the addition of getDatasetDataviewMiddleware in the OrganisationsController, new middleware functions in common.middleware.js, and the creation of a new dataview.middleware.js file. Additionally, it updates route handlers for dataset data retrieval and modifies templates to reflect changes in terminology from "issue" to "task". Tests are also updated to align with these changes, ensuring robust coverage of the new functionalities.

Changes

File Change Summary
src/controllers/OrganisationsController.js Added getDatasetDataviewMiddleware to the exported middleware functions.
src/middleware/common.middleware.js Introduced several new middleware functions: getIsPageNumberInRange, createPaginationTemplateParams, addDatabaseFieldToSpecification, replaceUnderscoreInSpecification, pullOutDatasetSpecification, extractJsonFieldFromEntities, replaceUnderscoreInEntities, and setDefaultParams. Updated existing functions for enhanced error handling and pagination capabilities.
src/middleware/datasetOverview.middleware.js Removed pullOutDatasetSpecification function and updated prepareDatasetOverviewTemplateParams to replace datasetSpecification with specification and issueCount with taskCount.
src/middleware/dataview.middleware.js Created new middleware module with functions for handling data view requests, including fetchSpecification, fetchEntitiesCount, setTotalPages, fetchEntities, fetchFieldMappings, setPaginationOptions, constructTableParams, and prepareTemplateParams.
src/middleware/issueDetails.middleware.js Added getIsPageNumberInRange and removed isPageNumberInRange. Updated imports accordingly.
src/routes/organisations.js Added two new GET routes for retrieving dataset data with and without pagination using getDatasetDataviewMiddleware.
src/routes/schemas.js Renamed issueCount to taskCount in OrgDatasetOverview schema.
src/views/components/dataset-navigation.html Updated notification badge condition from params.issue_count to params.task_count and added a new navigation item for viewing data associated with the dataset.
src/views/components/table.html Added documentation comment block detailing the expected structure of the params object for the table macro.
src/views/organisations/dataset-overview.html Renamed parameter issue_count to task_count in the call to datasetNavigation.
src/views/organisations/datasetTaskList.html Renamed parameter issue_count to task_count in the call to datasetNavigation.
src/views/organisations/dataview.html Introduced a new template for displaying data related to organizations and datasets, including navigation and pagination components.
test/unit/datasetTaskListPage.test.js Modified expected number of navigation links from 2 to 3 in the dataset navigation section.
test/unit/middleware/common.middleware.test.js Introduced comprehensive unit tests for various middleware functions in common.middleware.
test/unit/middleware/datasetOverview.middleware.test.js Removed tests for the pullOutDatasetSpecification function and updated tests for prepareDatasetOverviewTemplateParams to reflect parameter changes.
test/unit/middleware/dataview.middleware.test.js Created a new test suite for the dataview.middleware module, validating the functionality of several middleware functions.
test/unit/views/components/dataset-navigation.test.js Updated test cases to reflect the change from "issue" to "task" terminology, including updates to expected outputs.
test/unit/views/organisations/dataset-overview.test.js Updated expected number of dataset navigation links from 2 to 3 and added a test case for rendering a map section for mappable datasets.

Assessment against linked issues

Objective Addressed Explanation
Display a table showing data for resources submitted for a dataset (#482)
Paginate the results for performance on the dataset details page (#482)

Possibly related PRs

  • fix: a few type errors #589: This PR modifies src/middleware/common.middleware.js, which is relevant because the main PR also involves middleware changes in src/controllers/OrganisationsController.js, specifically adding a new middleware function.
  • update 'no-errors' page design & content #610: This PR updates the 'no-errors' page design and content, which is related to the main PR's focus on enhancing the organisationsController functionality, as both involve improving user-facing components.
  • 572 move guidance pages into submit service #613: This PR moves guidance pages into the submit service, which aligns with the main PR's objective of enhancing the organisationsController by adding new middleware that may interact with guidance-related functionalities.

Suggested reviewers

  • rosado

🐇 In the code we hop,
New middleware we drop!
From issues to tasks we glide,
In templates, changes abide.
With pagination in sight,
Our data takes flight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Oct 31, 2024

Coverage Report

Status Category Percentage Covered / Total
🔵 Lines 68.38% 4388 / 6417
🔵 Statements 68.38% 4388 / 6417
🔵 Functions 66.78% 187 / 280
🔵 Branches 82.62% 542 / 656
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
src/controllers/OrganisationsController.js 0% 0% 0% 0% 1-19
src/controllers/resultsController.js 87.5% 95% 100% 87.5% 45-53, 74-75
src/middleware/common.middleware.js 89.52% 94.44% 40% 89.52% 18-27, 31, 52-53, 65-67, 78, 94-100, 157-159, 265-267, 290-292
src/middleware/datasetOverview.middleware.js 61.32% 52.63% 16.66% 61.32% 8-28, 41-88, 120
src/middleware/dataview.middleware.js 98.91% 89.47% 54.54% 98.91% 39-40
src/middleware/issueDetails.middleware.js 75.31% 62.5% 41.66% 75.31% 44-57, 69-81, 94-117, 129-135, 233-239, 253-256, 259-262, 266-270
src/routes/organisations.js 0% 0% 0% 0% 1-16
src/routes/schemas.js 100% 100% 100% 100%
Generated in workflow #235 for commit fc6013d by the Vitest Coverage Report Action

@DilwoarH
Copy link
Contributor

DilwoarH commented Nov 8, 2024

One minor comment about the isNan change but otherwise looks good to me.

@alextea are you happy with the implementation?

If you are - happy to approve

@CharliePatterson
Copy link
Contributor

All LGTM 🙌

@alextea
Copy link
Contributor

alextea commented Nov 11, 2024

Can we make the column names in the table headings use the same format as the guidance: lowercase, hyphen-separated eg: article-4-direction, end-date, start-date

@eveleighoj eveleighoj temporarily deployed to submit-pr-609 November 12, 2024 10:38 Inactive
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (1)
src/controllers/resultsController.js (1)

Line range hint 11-82: Consider refactoring the locals method for improved maintainability

The locals method handles multiple responsibilities including request state management, error handling, and table parameter construction. Consider breaking it down into smaller, focused methods:

class ResultsController extends PageController {
+  async buildTableParams(responseDetails, requestData) {
+    const rows = this._processRows(responseDetails, requestData);
+    return {
+      columns: responseDetails.getColumns().map(column => prettifyColumnName(column)),
+      rows,
+      fields: responseDetails.getFields()
+    };
+  }
+
+  _processRows(responseDetails, requestData) {
+    let rows = responseDetails.getRowsWithVerboseColumns(requestData.hasErrors());
+    return rows.map(this._filterErrorSeverity);
+  }
+
+  _filterErrorSeverity({ columns, ...rest }) {
+    const columnsOnlyErrors = Object.fromEntries(
+      Object.entries(columns).map(([key, value]) => {
+        const error = value.error?.severity === 'error' ? value.error : undefined;
+        return [key, { ...value, error }];
+      })
+    );
+    return { ...rest, columns: columnsOnlyErrors };
+  }

   async locals(req, res, next) {
     // existing implementation but calling new methods
   }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f08845e and fc6013d.

📒 Files selected for processing (6)
  • src/controllers/resultsController.js (2 hunks)
  • src/routes/schemas.js (5 hunks)
  • src/views/components/table.html (3 hunks)
  • test/unit/errorsPage.test.js (1 hunks)
  • test/unit/noErrorsPage.test.js (1 hunks)
  • test/unit/resultsController.test.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/routes/schemas.js
  • src/views/components/table.html
🔇 Additional comments (3)
src/controllers/resultsController.js (2)

3-3: LGTM: Clean import addition

The import of the prettifyColumnName utility follows proper ES6 module syntax and project conventions.


63-63: Verify column name formatting implementation

The column name formatting looks good, but let's ensure the prettifyColumnName function handles all possible column name formats correctly.

✅ Verification successful

Column name formatting implementation is robust and well-tested

The prettifyColumnName function is well-implemented with comprehensive test coverage that handles:

  • Capitalisation of first words
  • Special handling of "URL" text
  • Various delimiter scenarios (hyphens and spaces)
  • Mixed format cases

The implementation aligns perfectly with the table display requirements and includes proper test cases for all edge cases.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check prettifyColumnName implementation and usage
# Look for the implementation and any test coverage

echo "Checking prettifyColumnName implementation:"
rg -A 5 "export.*prettifyColumnName" src/filters/

echo "\nChecking test coverage:"
rg -l "prettifyColumnName" "test/"

echo "\nChecking current column names in use:"
ast-grep --pattern 'getColumns()' -f .js

Length of output: 809


Script:

#!/bin/bash
# Let's check the implementation and test coverage more thoroughly

echo "Checking prettifyColumnName implementation:"
cat src/filters/prettifyColumnName.js

echo -e "\nChecking test cases:"
cat test/unit/prettifyColumnName.test.js

echo -e "\nChecking actual column usage:"
ast-grep --pattern 'getColumns()'

Length of output: 1726

test/unit/errorsPage.test.js (1)

78-78: Verify column header formatting consistency

The removal of prettifyColumnName from the test assertion suggests that column formatting is now handled at the controller level. Let's ensure this aligns with the table styling requirements mentioned in the PR comments.

Run the following script to verify column header formatting across the application:

✅ Verification successful

Column header formatting is consistently implemented

The verification shows that column header formatting is properly handled:

  • The prettifyColumnName function is used in ResultsController to format column headers before they reach the view
  • The test file correctly expects the formatted headers since they are transformed at the controller level
  • Other tests (integration and unit) consistently use prettifyColumnName for header validation
  • The table component in src/views/components/table.html receives and displays the pre-formatted column headers
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent column header formatting implementation
# Expected results: Column headers should follow lowercase, hyphen-separated format

# Check for column header formatting in controllers
ast-grep --pattern 'prettifyColumnName($$$)'

# Check for direct column header usage in templates
rg -g '*.html' -A 2 'govuk-table__header'

Length of output: 4339

@@ -65,7 +65,7 @@ describe('no Errors Page', () => {
const columnHeaders = tHead.querySelectorAll('.govuk-table__header')

params.options.tableParams.columns.forEach((header, i) => {
expect(columnHeaders[i].textContent).toContain(prettifyColumnName(header))
expect(columnHeaders[i].textContent).toContain(header)
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Restore column header formatting validation

The removal of prettifyColumnName from the column header validation seems inconsistent with:

  1. The PR requirements for specific column name formatting (lowercase, hyphen-separated)
  2. The continued use of prettifyColumnName for error message validation
  3. Alex's feedback about following the guidance format for column names

This change might allow tests to pass even when column headers don't follow the required format.

Apply this diff to restore the formatting check:

-      expect(columnHeaders[i].textContent).toContain(header)
+      expect(columnHeaders[i].textContent).toContain(prettifyColumnName(header))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(columnHeaders[i].textContent).toContain(header)
expect(columnHeaders[i].textContent).toContain(prettifyColumnName(header))

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't want this anymore as alex requested that the table contains spec fields sometimes

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GeorgeGoodall-GovUk, understood. Since the table may contain specification fields as per Alex's request, it's appropriate to remove the prettifyColumnName function from the column header validation in test/unit/noErrorsPage.test.js. Thanks for the clarification.


✏️ Learnings added
Learnt from: GeorgeGoodall-GovUk
PR: digital-land/submit#609
File: test/unit/noErrorsPage.test.js:68-68
Timestamp: 2024-11-12T10:54:09.278Z
Learning: In `test/unit/noErrorsPage.test.js`, avoid using `prettifyColumnName` for column headers because the table can contain spec fields, as requested by Alex.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

test/unit/resultsController.test.js Show resolved Hide resolved
Comment on lines +112 to +113
getColumns: () => ['mock Columns'],
getFields: () => ['mock fields'],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure consistent casing in mock data

The mock data uses inconsistent casing between 'mock Columns' and 'mock fields'. This could lead to test failures and makes the test harder to maintain.

Apply this diff to maintain consistent casing:

-          getColumns: () => ['mock Columns'],
-          getFields: () => ['mock fields'],
+          getColumns: () => ['mock-columns'],
+          getFields: () => ['mock-fields'],
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getColumns: () => ['mock Columns'],
getFields: () => ['mock fields'],
getColumns: () => ['mock-columns'],
getFields: () => ['mock-fields'],

Copy link
Contributor

@DilwoarH DilwoarH left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a comment from Code rabbit - up to you if you want to address

@GeorgeGoodall-GovUk GeorgeGoodall-GovUk merged commit aa56b11 into main Nov 12, 2024
5 checks passed
@DilwoarH DilwoarH deleted the 482-dataset-details-page-provision-level-view-table branch November 12, 2024 11:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Dataset details page: Provision-level view table
6 participants