Skip to content

Commit

Permalink
Further feature/FSR-1287 changes (#856)
Browse files Browse the repository at this point in the history
* auto refresh. updated TA tests

* sonar fixes

* some sonar fixes

* refactor autorefresh. add unit tests

* conditional callback

* use <output> element

* latest level refactor and  unit tests

* fix test

* remove console logs

* move update in to test

---------

Co-authored-by: Ash <[email protected]>
  • Loading branch information
Keyurx11 and Ash authored Oct 15, 2024
1 parent cce7bfb commit 6d1b4f7
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 74 deletions.
40 changes: 8 additions & 32 deletions server/src/js/components/latest-levels-auto-refresh.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ class LatestLevelsAutoRefresh {
}

updateTimeAgo = () => {
console.log('--updateTimeAgo() started')

setTimeout(() => {
this.renderTimeAgo()
this.timeAgoInterval = setInterval(this.renderTimeAgo, 60000)
Expand All @@ -40,23 +38,17 @@ class LatestLevelsAutoRefresh {
renderTimeAgo = () => {
const elements = document.querySelectorAll('[data-item-time]')

elements.forEach((element, index) => {
console.log('element', index)
elements.forEach(element => {
const timeAgoText = element.textContent
const timeAgoValue = parseInt(timeAgoText, 10)

console.log('--currentTime', timeAgoText)

if (!timeAgoText.includes('hour')) {
element.textContent = `${timeAgoValue + 1} minutes ago`
console.log('--newTime', element.textContent)
}
})
}

fetchRiverLevels = (callback) => {
console.log('fetchRiverLevels...')

this.liveStatusMessages = []

fetch(window.location.href)
Expand All @@ -75,8 +67,6 @@ class LatestLevelsAutoRefresh {
}
})
.catch(error => {
console.error('Error updating levels:', error)

this.liveStatusMessages.push('There was an error getting the latest level')
})
.finally(() => {
Expand All @@ -88,14 +78,17 @@ class LatestLevelsAutoRefresh {
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')

const status = doc.querySelector('[data-severity-status]')?.getAttribute('data-severity-status')

if (!status) {
return window.location.reload()
}

// Get elements from fetched content
const fetchedElements = Array.from(doc.querySelectorAll('.defra-live .defra-live__item'))

// Check if any elements are missing in the fetched data
const isMissingElements = this.latestLevels.length !== fetchedElements.length
console.log('isMissingElements', isMissingElements, this.latestLevels.length, fetchedElements.length)
console.log('latestLevels', this.latestLevels)
console.log('fetchedElements', fetchedElements)

if (isMissingElements) {
return this.liveStatusMessages.push('Warnings have been removed, please refresh the page.')
Expand All @@ -112,30 +105,21 @@ class LatestLevelsAutoRefresh {

const currentItem = document.querySelector(`[data-item-id="${itemId}"]`)

console.log('fetchedElement', itemId, itemRiverName, itemRiverAgency)

if (currentItem) {
const currentTime = currentItem.querySelector('[data-item-time]')
const currentValue = currentItem.querySelector('[data-item-value]')
const currentStatus = currentItem.getAttribute('data-item-status')

console.log('--currentValue', currentValue?.textContent, currentStatus)
console.log('--fetchedValue', fetchedValue?.textContent, fetchedStatus)
console.log('--requires update?', fetchedValue?.textContent !== currentValue?.textContent)

if (fetchedStatus === currentStatus) {
if (fetchedValue?.textContent !== currentValue?.textContent) {
console.log('--new value fetched')
clearInterval(this.timeAgoInterval)
console.log('--interval cleared')

currentValue.textContent = fetchedValue.textContent

this.liveStatusMessages.push(`The ${itemRiverName} at ${itemRiverAgency} level was ${fetchedValue.textContent} metres ${fetchedTime.textContent}`)

this.updateTimeAgo()
} else {
console.log('--no change')
}

currentTime.textContent = fetchedTime.textContent
} else {
Expand All @@ -144,8 +128,6 @@ class LatestLevelsAutoRefresh {
} else {
this.liveStatusMessages.push('Please refresh the page')
}

console.log('-------------------\n')
})
}

Expand All @@ -158,9 +140,6 @@ class LatestLevelsAutoRefresh {
// Find the next target minute
const nextTargetMinute = this.targetMinutes.find(minute => minute > nowMinute) ?? this.targetMinutes[0]

console.log('--Current minute:', nowMinute)
console.log('--Next target minute:', nextTargetMinute)

// Create the next target date based on the next target minute
const nextTargetDate = new Date(now)
nextTargetDate.setMinutes(nextTargetMinute)
Expand All @@ -174,9 +153,6 @@ class LatestLevelsAutoRefresh {
// Calculate delay correctly from now
const delay = nextTargetDate.getTime() - now.getTime()

console.log('--delay (calc)', Math.round(delay / 1000 / 60))
console.log(`Next update scheduled in ${Math.round(delay / 1000 / 60)} minutes at ${nextTargetDate.toLocaleTimeString()}\n\n`)

// Schedule the next update
this.timeout = setTimeout(() => {
this.fetchRiverLevels()
Expand Down
3 changes: 2 additions & 1 deletion server/views/partials/latest-levels.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<div class="govuk-visually-hidden" role="status" data-live-status></div>
<output class="govuk-visually-hidden" data-live-status></output>

<div class="defra-live">
<h2 class="defra-live__title">Latest level{% if model.latestLevels.length > 1 %}s{% endif %}</h2>
Expand Down Expand Up @@ -37,3 +37,4 @@ <h2 class="defra-live__title">Latest level{% if model.latestLevels.length > 1 %}
autorefresh.nextUpdate()
})()
</script>

2 changes: 1 addition & 1 deletion server/views/target-area.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<!-- FIRST BANNER FOR ACTIVE ALERTS/WARNING -->
<div class="defra-flood-status govuk-!-margin-bottom-3">
{% if model.flood and model.severity.id < 4 %}
<div class="defra-flood-status-item defra-flood-status-item--{{model.severity.hash}}">
<div class="defra-flood-status-item defra-flood-status-item--{{model.severity.hash}}" data-severity-status="{{model.severity.hash}}">
<span class="defra-flood-status-item__icon">
{{model.severity.icon | safe }}
</span>
Expand Down
18 changes: 9 additions & 9 deletions test/routes/target-area.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ lab.experiment('Target-area tests', () => {

// Latest level (single threshold)
Code.expect(response.payload).to.contain('<h2 class="defra-live__title">Latest level</h2>')
Code.expect(response.payload).to.contain('<p>The River Derwent level at Derby St Marys was 0.54 metres. Property flooding is possible when it goes above 3.30 metres.')
Code.expect(response.payload).to.contain('<a href="/station/2138?tid=1746074">Monitor the latest level at Derby St Marys</a>')
Code.expect(response.payload).to.contain('The River Derwent level at Derby St Marys was <span data-item-value>0.54</span> metres. Property flooding is possible when it goes above 3.30 metres.')
Code.expect(response.payload).to.contain('<a href="/station/2138">Monitor the latest level at Derby St Marys</a>')
Code.expect(response.payload).to.match(/<div class="defra-flood-status-item__text">\s*<strong>Flooding is possible - <a class="govuk-link" href="https:\/\/www\.gov\.uk\/guidance\/flood-alerts-and-warnings-what-they-are-and-what-to-do#flood-alert">\s*be prepared\s*<\/a><\/strong>\s*<\/div>/)
Code.expect(response.payload).to.contain('30 minutes ago')

Expand Down Expand Up @@ -191,11 +191,11 @@ lab.experiment('Target-area tests', () => {
// latests levels (multi)
// console.log('DEFRA Live Elements:', response.payload.match(/<div class="defra-live[^>]*>[\s\S]*?<\/div>/g)) // Keep for debugging
Code.expect(response.payload).to.contain('<h2 class="defra-live__title">Latest levels</h2>')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Eastcote Road was 0.35 metres. Property flooding is possible when it goes above 1.40 metres.')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Avenue Road was 0.18 metres. Property flooding is possible when it goes above 1.46 metres.')
Code.expect(response.payload).to.contain('<a href="/station/7173?tid=1747543">Monitor the River Pinn level at Avenue Road</a>')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Moss Close was 0.13 metres. Property flooding is possible when it goes above 1.15 metres.')
Code.expect(response.payload).to.contain('<a href="/station/7201?tid=1747541">Monitor the River Pinn level at Moss Close</a>')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Eastcote Road was <span data-item-value>0.35</span> metres. Property flooding is possible when it goes above 1.40 metres.')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Avenue Road was <span data-item-value>0.18</span> metres. Property flooding is possible when it goes above 1.46 metres.')
Code.expect(response.payload).to.contain(' <a href="/station/7173">Monitor the River Pinn level at Avenue Road</a>')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Moss Close was <span data-item-value>0.13</span> metres. Property flooding is possible when it goes above 1.15 metres.')
Code.expect(response.payload).to.contain('<a href="/station/7201">Monitor the River Pinn level at Moss Close</a>')
})
lab.test('Check flood severity banner link for Flood warning', async () => {
const floodService = require('../../server/services/flood')
Expand Down Expand Up @@ -759,7 +759,7 @@ lab.experiment('Target-area tests', () => {
Code.expect(response.statusCode).to.equal(200)

Code.expect(response.payload).to.contain('<h2 class="defra-live__title">Latest level</h2>')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Eastcote Road was 0.35 metres. Property flooding is possible when it goes above 1.40 metres.')
Code.expect(response.payload).to.contain('<p>The River Pinn level at Eastcote Road was <span data-item-value>0.35</span> metres. Property flooding is possible when it goes above 1.40 metres.')
Code.expect(response.payload).to.contain('<p class="defra-live__supplementary">This level will update automatically</p>')
})

Expand Down Expand Up @@ -956,7 +956,7 @@ lab.experiment('Target-area tests', () => {
Code.expect(response.statusCode).to.equal(200)

Code.expect(response.payload).to.contain('<h2 class="defra-live__title">Latest level</h2>')
Code.expect(response.payload).to.contain('<p>The River Welsh level at Welsh Station was 0.35 metres. Property flooding is possible when it goes above 1.40 metres.\n \n </p>')
Code.expect(response.payload).to.contain('<p>The River Welsh level at Welsh Station was <span data-item-value>0.35</span> metres. Property flooding is possible when it goes above 1.40 metres.\n \n </p>')
Code.expect(response.payload).to.contain('<a href="/station/7201">Monitor the latest level at Welsh Station (Natural Resources Wales)</a>')
Code.expect(response.payload).to.contain('<p class="defra-live__supplementary">This level will update automatically</p>')
})
Expand Down
74 changes: 43 additions & 31 deletions test/src/js/components/latest-levels-auto-refresh.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,6 @@ const lab = script()
const { describe, it, before, afterEach } = lab
exports.lab = lab

const htmlNewUpdate = {
ok: true,
text: () => `
<div class="defra-live">
<div class="defra-live__item" data-item-status="Active" data-item-name="River Thames" data-item-agency="London" data-item-id="1000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>15 minutes ago</strong>
</p>
<p>The River Thames level at London was <span data-item-value>0.10</span> metres. Property flooding is possible when it goes above 4.00 metres.</p>
<p>
<a href="/station/1000">Monitor the latest level at London</a>
</p>
</div>
<div class="defra-live__item" data-item-status="Active" data-item-name="Sea Cut" data-item-agency="Mowthorpe" data-item-id="2000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>15 minutes ago</strong>
</p>
<p>The Sea Cut level at Mowthorpe was <span data-item-value>0.20</span> metres. Property flooding is possible when it goes above 2.00 metres.</p>
<p>
<a href="/station/2000">Monitor the latest level at Mowthorpe</a>
</p>
</div>
</div>
`
}

describe('latestLevels', () => {
let window
let document
Expand All @@ -42,8 +15,8 @@ describe('latestLevels', () => {

before(() => {
const html = `
<div role="status" data-live-status></div>
<div class="defra-live">
<output data-live-status></output>
<div class="defra-live" data-severity-status="3">
<div class="defra-live__item" data-item-status="Active" data-item-name="River Thames" data-item-agency="London" data-item-id="1000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>20 minutes ago</strong>
Expand Down Expand Up @@ -97,7 +70,32 @@ describe('latestLevels', () => {
})

it('should fetch levels and update the DOM with the new values', () => {
mockFetch.returns(Promise.resolve(htmlNewUpdate))
mockFetch.returns(Promise.resolve({
ok: true,
text: () => `
<div class="defra-live" data-severity-status="3">
<div class="defra-live__item" data-item-status="Active" data-item-name="River Thames" data-item-agency="London" data-item-id="1000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>15 minutes ago</strong>
</p>
<p>The River Thames level at London was <span data-item-value>0.10</span> metres. Property flooding is possible when it goes above 4.00 metres.</p>
<p>
<a href="/station/1000">Monitor the latest level at London</a>
</p>
</div>
<div class="defra-live__item" data-item-status="Active" data-item-name="Sea Cut" data-item-agency="Mowthorpe" data-item-id="2000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>15 minutes ago</strong>
</p>
<p>The Sea Cut level at Mowthorpe was <span data-item-value>0.20</span> metres. Property flooding is possible when it goes above 2.00 metres.</p>
<p>
<a href="/station/2000">Monitor the latest level at Mowthorpe</a>
</p>
</div>
</div>
`
}))

const ll = new window.LatestLevelsAutoRefresh()

Expand All @@ -113,7 +111,21 @@ describe('latestLevels', () => {
})

it('should set accessibility message when there are missing elements fetched', () => {
mockFetch.returns(Promise.resolve({ ok: true, text: () => '<div class="defra-live"></div>' }))
mockFetch.returns(Promise.resolve({
ok: true,
text: () => `
<div class="defra-live" data-severity-status="3">
<div class="defra-live__item" data-item-status="Active" data-item-name="River Thames" data-item-agency="London" data-item-id="1000">
<p class="defra-flood-meta defra-flood-meta--no-border govuk-!-margin-bottom-0">
<strong data-item-time>15 minutes ago</strong>
</p>
<p>The River Thames level at London was <span data-item-value>0.10</span> metres. Property flooding is possible when it goes above 4.00 metres.</p>
<p>
<a href="/station/1000">Monitor the latest level at London</a>
</p>
</div>
</div>`
}))

const ll = new window.LatestLevelsAutoRefresh()

Expand Down

0 comments on commit 6d1b4f7

Please sign in to comment.