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

fix(regulations-admin): Fixing bugs in editor and admin flow #17027

Merged
merged 5 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { ReferenceText } from './impacts/ReferenceText'
import { DraftChangeForm, DraftImpactForm } from '../state/types'
import { makeDraftAppendixForm } from '../state/makeFields'
import { hasAnyChange } from '../utils/formatAmendingUtils'
import { usePristineRegulations } from '../utils/hooks'

const updateText =
'Ósamræmi er í texta stofnreglugerðar og breytingareglugerðar. Texti breytingareglugerðar þarf að samræmast breytingum sem gerðar hafa verið á stofnreglugerð, eigi breytingarnar að færast inn með réttum hætti.'
Expand All @@ -38,12 +39,13 @@ export const EditBasics = () => {
const { draft, actions, ministries } = useDraftingState()
const [editorKey, setEditorKey] = useState('initial')
const [titleError, setTitleError] = useState<string | undefined>(undefined)
const [hasUpdated, setHasUpdated] = useState<boolean>(false)
const [hasUpdatedAppendix, setHasUpdatedAppendix] = useState<boolean>(false)
const [references, setReferences] = useState<DraftImpactForm[]>()
const [isModalVisible, setIsModalVisible] = useState<boolean>(true)
const [hasConfirmed, setHasConfirmed] = useState<boolean>(false)
const [hasSeenModal, setHasSeenModal] = useState<boolean>(false)
const { removePristineRegulation, isPristineRegulation } =
usePristineRegulations()

const { text, appendixes } = draft
const { updateState } = actions
Expand Down Expand Up @@ -120,13 +122,6 @@ export const EditBasics = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [draft.impacts])

useEffect(() => {
if (!hasUpdatedAppendix && hasUpdated) {
updateAppendixes()
setHasUpdatedAppendix(true)
}
}, [hasUpdated, hasUpdatedAppendix])

const updateAppendixes = () => {
// FORMAT AMENDING REGULATION APPENDIXES
const impactArray = Object.values(draft.impacts).flat()
Expand Down Expand Up @@ -167,9 +162,17 @@ export const EditBasics = () => {
const additionString = additions.join('') as HTMLText
updateState('text', additionString)

setHasUpdated(true)
// Update appendixes
if (!hasUpdatedAppendix) {
updateAppendixes()
setHasUpdatedAppendix(true)
}

// Remove from session storage
removePristineRegulation(draft.id)
}

const shouldShowModal = isPristineRegulation(draft.id)
return (
<>
<Box marginBottom={3}>
Expand Down Expand Up @@ -328,7 +331,7 @@ export const EditBasics = () => {
)}
</AccordionItem>
</Accordion>
{!hasUpdated ? (
{shouldShowModal ? (
<ConfirmModal
isVisible={
draft.type.value === RegulationDraftTypes.amending &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export const LawChaptersSelect = () => {
const chaptersField = draft.lawChapters
const activeChapters = chaptersField.value

const { data: mentionedList /*, loading , error */ } =
useRegulationListQuery(draft.mentioned)
// const { data: mentionedList /*, loading , error */ } =
// useRegulationListQuery(draft.mentioned)

const lawChaptersOptions = useLawChapterOptions(
lawChapters.list,
Expand All @@ -47,16 +47,17 @@ export const LawChaptersSelect = () => {
)

// Auto fill lawChapters if there are mentions and no lawchapters present
useEffect(() => {
if (mentionedList?.length && !draft.lawChapters.value.length) {
mentionedList.forEach((mention) => {
mention.lawChapters?.forEach((ch) => {
actions.updateLawChapterProp('add', ch.slug)
})
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mentionedList])
// REMOVE FOR NOW. NOT SHOWING CORRECT RESULTS. MIGHT WANT TO REVISIT
// useEffect(() => {
// if (mentionedList?.length && !draft.lawChapters.value.length) {
// mentionedList.forEach((mention) => {
// mention.lawChapters?.forEach((ch) => {
// actions.updateLawChapterProp('add', ch.slug)
// })
// })
// }
// // eslint-disable-next-line react-hooks/exhaustive-deps
// }, [mentionedList])

return (
<Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
GridRow,
GridColumn,
Text,
toast,
} from '@island.is/island-ui/core'
import { useEffect, useState, useMemo } from 'react'
import {
Expand Down Expand Up @@ -51,7 +52,10 @@ import {
updateFieldValue,
validateImpact,
} from '../../state/validations'
import { useGetRegulationHistory } from '../../utils/hooks'
import {
useGetRegulationHistory,
usePristineRegulations,
} from '../../utils/hooks'
import { DraftRegulationChange } from '@island.is/regulations/admin'
import { useLocale } from '@island.is/localization'
import { cleanTitle } from '@island.is/regulations-tools/cleanTitle'
Expand All @@ -74,6 +78,7 @@ export const EditChange = (props: EditChangeProp) => {
const today = useMemo(() => new Date(), [])
const [minDate, setMinDate] = useState<Date | undefined>()
const [showChangeForm, setShowChangeForm] = useState(false)
const { addPristineRegulation } = usePristineRegulations()

// Target regulation for impact
const [activeRegulation, setActiveRegulation] = useState<
Expand Down Expand Up @@ -280,7 +285,12 @@ export const EditChange = (props: EditChangeProp) => {
}
return { success: true, error: undefined }
})
.then(() => {
addPristineRegulation(draft.id)
closeModal(true)
})
.catch((error) => {
toast.error(t(msg.errorOnSaveReg))
return { success: false, error: error as Error }
})
} else {
Expand All @@ -306,12 +316,15 @@ export const EditChange = (props: EditChangeProp) => {
}
return { success: true, error: undefined }
})
.then(() => {
addPristineRegulation(draft.id)
closeModal(true)
})
.catch((error) => {
toast.error(t(msg.errorOnSaveReg))
return { success: false, error: error as Error }
})
}

closeModal(true)
}

const localActions = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import { useEffect, useState } from 'react'

import { impactMsgs } from '../../lib/messages'
import { useLocale } from '@island.is/localization'
import { RegulationOptionList, RegulationType } from '@island.is/regulations'
import {
RegulationOption,
RegulationOptionList,
RegulationType,
} from '@island.is/regulations'
import { DraftImpactName } from '@island.is/regulations/admin'

import { AsyncSearch, Option, Text } from '@island.is/island-ui/core'
Expand Down Expand Up @@ -39,10 +43,24 @@ export const ImpactAmendingSelection = ({
RegulationSearchListQuery,
{
onCompleted: (data) => {
setResults(
(data.getRegulationsOptionSearch as RegulationOptionList) ||
undefined,
)
// The search results need to be reordered so that the objects with titles containing the input string are first
const results = data.getRegulationsOptionSearch
const reorderedResults = value
? [
// Objects with titles containing the input string
...results.filter((obj: RegulationOption) =>
obj.title.toLowerCase().includes(value.toLowerCase()),
),
// The rest of the objects
...results.filter(
(obj: RegulationOption) =>
!obj.title.toLowerCase().includes(value.toLowerCase()),
),
]
: results // If value is undefined, keep the original order

setIsLoading(false)
setResults((reorderedResults as RegulationOptionList) || undefined)
},
fetchPolicy: 'no-cache',
},
Expand All @@ -64,7 +82,6 @@ export const ImpactAmendingSelection = ({
variables: { input: { q: value, iA: false, iR: false } },
})
}
setIsLoading(false)
},
600,
[value],
Expand Down
5 changes: 5 additions & 0 deletions libs/portals/admin/regulations-admin/src/lib/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,11 @@ export const errorMsgs = defineMessages({
id: 'ap.regulations-admin:title-is-too-long',
defaultMessage: 'Titill reglugerðar er of langur.',
},
errorOnSaveReg: {
id: 'ap.regulations-admin:error-on-save-reg',
defaultMessage:
'Villa kom upp við að vista texta. Vinsamlegast afritið texta og reynið aftur síðar.',
},
})

export const homeMessages = defineMessages({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ import flatten from 'lodash/flatten'
import uniq from 'lodash/uniq'
import {
allSameDay,
containsAnyTitleClass,
extractArticleTitleDisplay,
formatDate,
getArticleTitleType,
getArticleTypeText,
getTextWithSpaces,
groupElementsByArticleTitleFromDiv,
hasAnyChange,
hasSubtitle,
isGildisTaka,
removeRegPrefix,
updateAppendixWording,
Expand Down Expand Up @@ -203,13 +207,21 @@ export const formatAmendingRegBody = (
const testGroup: {
arr: HTMLText[]
original?: HTMLText[]
title: string
titleObject: {
text: string
hasSubtitle: boolean
type: 'article' | 'chapter' | 'subchapter'
}
isDeletion?: boolean
isAddition?: boolean
} = {
arr: [],
original: [],
title: '',
titleObject: {
text: '',
hasSubtitle: false,
type: 'article',
},
isDeletion: undefined,
isAddition: undefined,
}
Expand All @@ -218,16 +230,19 @@ export const formatAmendingRegBody = (
let pushHtml = '' as HTMLText

let isParagraph = false
let isArticleTitle = false
let isSectionTitle = false
let isNumberList = false
let isLetterList = false
if (element.classList.contains('article__title')) {
const containsAnyTitle = containsAnyTitleClass(element)
if (containsAnyTitle) {
const clone = element.cloneNode(true)

const textContent = getTextWithSpaces(clone)
articleTitle = extractArticleTitleDisplay(textContent)
testGroup.title = articleTitle
isArticleTitle = true
testGroup.titleObject.hasSubtitle = hasSubtitle(textContent)
testGroup.titleObject.type = getArticleTitleType(element)
testGroup.titleObject.text = articleTitle
isSectionTitle = true
paragraph = 0 // Reset paragraph count for the new article
} else if (element.nodeName.toLowerCase() === 'p') {
paragraph++
Expand All @@ -249,7 +264,7 @@ export const formatAmendingRegBody = (
const elementType =
isLetterList || isNumberList
? 'lidur'
: isArticleTitle
: isSectionTitle
? 'greinTitle'
: undefined

Expand All @@ -275,7 +290,7 @@ export const formatAmendingRegBody = (
// Paragraph was deleted
pushHtml =
`<p>${paragraph}. mgr. ${articleTitle} ${regNameDisplay} fellur brott.</p>` as HTMLText
} else if (isArticleTitle) {
} else if (isSectionTitle) {
// Title was deleted
pushHtml =
`<p>Fyrirsögn ${articleTitle} ${regNameDisplay} fellur brott.</p>` as HTMLText
Expand Down Expand Up @@ -304,7 +319,7 @@ export const formatAmendingRegBody = (
paragraph - 1
}. mgr. ${articleTitle} ${regNameDisplay} kemur ný málsgrein sem orðast svo:</p><p>${newText}</p>` as HTMLText)
: (`<p>Á undan 1. mgr. ${articleTitle} ${regNameDisplay} kemur ný málsgrein svohljóðandi: </p><p>${newText}</p>` as HTMLText)
} else if (isArticleTitle) {
} else if (isSectionTitle) {
// Title was added
testGroup.original?.push(`<p>${newText}</p>` as HTMLText)
pushHtml =
Expand Down Expand Up @@ -337,7 +352,7 @@ export const formatAmendingRegBody = (
// Change detected. Not additon, not deletion.
testGroup.isDeletion = false
testGroup.isAddition = false
if (isArticleTitle) {
if (isSectionTitle) {
// Title was changed
pushHtml =
`<p>Fyrirsögn ${articleTitle} ${regNameDisplay} breytist og orðast svo:</p><p>${newText}</p>` as HTMLText
Expand Down Expand Up @@ -365,7 +380,7 @@ export const formatAmendingRegBody = (
}
})
if (testGroup.isDeletion === true) {
const articleTitleNumber = testGroup.title
const articleTitleNumber = testGroup.titleObject.text

additionArray.push([
`<p>${articleTitleNumber} ${regNameDisplay} fellur brott.</p>` as HTMLText,
Expand All @@ -376,7 +391,7 @@ export const formatAmendingRegBody = (
if (prevArticle.length > 0) {
prevArticleTitle = prevArticle[0]?.innerText
}
const articleTitleNumber = testGroup.title
const articleTitleNumber = testGroup.titleObject.text
const originalTextArray = testGroup.original?.length
? flatten(testGroup.original)
: []
Expand All @@ -395,8 +410,13 @@ export const formatAmendingRegBody = (
: ''
}

const articleTypeText = getArticleTypeText(testGroup.titleObject.type)
additionArray.push([
`<p>Á eftir ${prevArticleTitleNumber} ${regNameDisplay} kemur ný grein, ${articleTitleNumber}, ásamt fyrirsögn, svohljóðandi:</p> ${articleDisplayText}` as HTMLText,
`<p>Á eftir ${prevArticleTitleNumber} ${regNameDisplay} kemur ${articleTypeText}, ${
articleTitleNumber ? articleTitleNumber + ',' : ''
}${
testGroup.titleObject.hasSubtitle ? ' ásamt fyrirsögn,' : ''
} svohljóðandi:</p> ${articleDisplayText}` as HTMLText,
])
} else {
additionArray.push(testGroup.arr)
Expand Down
Loading
Loading