Skip to content

Commit

Permalink
MIM-1723: Moved code from service to part
Browse files Browse the repository at this point in the history
  • Loading branch information
ssb-cgn committed Jan 19, 2024
1 parent cc304dc commit 6a8b174
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import JSONstat from 'jsonstat-toolkit/import.mjs'
import { type Dataset, type Data, type Dimension } from '/lib/types/jsonstat-toolkit'
import { fetchStatbankApiDataQuery } from '/lib/ssb/dataset/statbankApi/statbankApi'

export const get = (req: XP.Request): XP.Response => {
const dimensionCode: string = req.params.code ?? ''
const urlOrId: string = req.params.urlOrId ?? ''
const query: string = req.params.json ?? ''

export function getStatbankApiData(
dimensionCode: string,
urlOrId: string,
query: string
): SimpleStatbankResult | undefined {
const statbankApiData: JSONstat = fetchStatbankApiDataQuery(urlOrId, query)
const dataset: Dataset | null = statbankApiData ? JSONstat(statbankApiData).Dataset('dataset') : null
const filterDimensionCode: Dimension | null = dataset?.Dimension(dimensionCode) as Dimension | null
Expand All @@ -16,7 +16,7 @@ export const get = (req: XP.Request): XP.Response => {
const timeDimensions: Array<string> = filterDimensionTime?.id as Array<string>

try {
const result = dataDimensions.map(function (dataDimension) {
const result: DimensionData[] = dataDimensions.map(function (dataDimension: string) {
const values = timeDimensions.map((timeDimension) => {
const data: Data | null = dataset?.Data({
[dimensionCode]: dataDimension,
Expand All @@ -25,6 +25,7 @@ export const get = (req: XP.Request): XP.Response => {

return data.value ?? data.status
})

return {
displayName: filterDimensionCode?.Category(dataDimension)?.label,
dataCode: dataDimension, // Hvis vi må ta høyde for at de dytter inn mer enn en dimensjon her må det hånderes
Expand All @@ -33,16 +34,22 @@ export const get = (req: XP.Request): XP.Response => {
})

return {
status: 200,
contentType: 'application/json',
body: { tid: timeDimensions[0], data: result },
time: timeDimensions[0],
data: result,
}
} catch (error) {
log.error(error)
return {
status: 404,
contentType: 'application/json',
body: 'query, table or code is wrong',
}
log.error('getStatbankApiData failed: ' + error)
return undefined
}
}

export interface SimpleStatbankResult {
time: string
data: DimensionData[]
}

interface DimensionData {
displayName: string
dataCode: string
value: (string | number)[]
}
5 changes: 0 additions & 5 deletions src/main/resources/services/simpleStatbank/simpleStatbank.xml

This file was deleted.

90 changes: 28 additions & 62 deletions src/main/resources/site/parts/simpleStatbank/simpleStatbank.jsx
Original file line number Diff line number Diff line change
@@ -1,71 +1,22 @@
import React, { useState, useEffect } from 'react'
import React, { useState } from 'react'
import PropTypes from 'prop-types'
import { Row, Col } from 'react-bootstrap'
import { Dropdown, Divider } from '@statisticsnorway/ssb-component-library'
import axios from 'axios'

function SimpleStatbank(props) {
const {
icon,
altText,
ingress,
placeholder,
resultLayout,
simpleStatbankServiceUrl,
json,
code,
urlOrId,
selectDisplay,
} = props
const { icon, altText, ingress, placeholder, resultLayout, selectDisplay, statbankApiData } = props

// TODO: Hentet denne fra richText-part. Kan denne saniteres?
const textIngress = <span dangerouslySetInnerHTML={{ __html: ingress }} />

const [selectedValue, setSelectedValue] = useState(null)
const [loading, setLoading] = useState(true)
const [data, setData] = useState([])
const [time, setTime] = useState(null)

useEffect(() => {
if (simpleStatbankServiceUrl && json && code && urlOrId) {
fetchTableData()
}
}, [simpleStatbankServiceUrl, json, code, urlOrId])

function handleChange(value) {
if (value) {
setSelectedValue(value)
}
}

function fetchTableData() {
setLoading(true)
axios
.get(simpleStatbankServiceUrl, {
params: {
urlOrId,
code,
json,
},
})
.then((res) => {
if (res?.data?.data) {
const items = res.data.data.map((element) => ({
id: element.dataCode,
title: selectDisplay == 'text' ? element.displayName : `${element.dataCode}: ${element.displayName}`,
value: element.value,
}))
setTime(res.data.tid)
setData(items)
}
})
.catch((err) => {
console.log(err)
})
.finally(() => {
setLoading(false)
})
}

function renderIcon(icon, altText) {
if (!!icon) {
return (
Expand All @@ -81,7 +32,7 @@ function SimpleStatbank(props) {
function renderResult() {
if (selectedValue) {
const result = Number(selectedValue.value) > 0 ? selectedValue.value : '-'
const resultView = resultLayout.replace('{value}', result).replace('{time}', time)
const resultView = resultLayout.replace('{value}', result).replace('{time}', statbankApiData.time)
const textResult = <span dangerouslySetInnerHTML={{ __html: resultView }} />
return (
<div>
Expand All @@ -92,19 +43,30 @@ function SimpleStatbank(props) {
}
}

function addDropdown() {
const items = statbankApiData
? statbankApiData.data.map((element) => ({
id: element.dataCode,
title: selectDisplay == 'text' ? element.displayName : `${element.dataCode}: ${element.displayName}`,
value: element.value,
}))
: []
return (
<Dropdown
header={textIngress}
searchable
items={items}
onSelect={handleChange}
placeholder={statbankApiData ? placeholder : 'Ingen data'}
/>
)
}

function renderForm() {
return (
<Row className='content'>
{renderIcon(icon, altText)}
<Col>
<Dropdown
header={textIngress}
searchable
items={data}
onSelect={handleChange}
placeholder={loading ? 'loading...' : placeholder}
/>
</Col>
<Col>{addDropdown()}</Col>
</Row>
)
}
Expand All @@ -128,6 +90,10 @@ SimpleStatbank.propTypes = {
code: PropTypes.string,
urlOrId: PropTypes.string,
selectDisplay: PropTypes.string,
statbankApiData: PropTypes.objectOf({
time: PropTypes.string,
data: PropTypes.object,
}),
}

export default (props) => <SimpleStatbank {...props} />
25 changes: 13 additions & 12 deletions src/main/resources/site/parts/simpleStatbank/simpleStatbank.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { getComponent, serviceUrl } from '/lib/xp/portal'
import { getComponent } from '/lib/xp/portal'
import { renderError } from '/lib/ssb/error/error'
import { render } from '/lib/enonic/react4xp'
import { imageUrl, getImageAlt } from '/lib/ssb/utils/imageUtils'
import { isEnabled } from '/lib/featureToggle'
import { getStatbankApiData, type SimpleStatbankResult } from '/lib/ssb/parts/simpleStatbank'

export function get(req: XP.Request) {
try {
Expand All @@ -19,10 +20,10 @@ export function preview(req: XP.Request) {
function getImageUrl(icon?: string) {
return icon
? imageUrl({
id: icon,
scale: 'block(100,100)',
format: 'jpg',
})
id: icon,
scale: 'block(100,100)',
format: 'jpg',
})
: null
}

Expand All @@ -34,23 +35,23 @@ function renderPart(req: XP.Request): XP.Response {
if (!isEnabled('simple-statbank-part', false, 'ssb')) return { body: '' }

const part = getComponent<XP.PartComponent.SimpleStatbank>()

if (!part) throw Error('No part found')

const simpleStatbankServiceUrl: string = serviceUrl({
service: 'simpleStatbank',
})
const statbankApiData: SimpleStatbankResult | undefined = getStatbankApiData(
part.config.code,
part.config.urlOrId,
part.config.json
)

const props = {
icon: getImageUrl(part.config.icon),
ingress: part.config.ingress,
placeholder: part.config.placeholder ?? '',
altText: getImageAltText(part.config.icon),
resultLayout: part.config.resultText,
simpleStatbankServiceUrl,
json: part.config.json,
urlOrId: part.config.urlOrId,
code: part.config.code,
selectDisplay: part.config.selectDisplay,
statbankApiData,
}

return render('site/parts/simpleStatbank/simpleStatbank', props, req, {
Expand Down

0 comments on commit 6a8b174

Please sign in to comment.