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

vessel group report vessels table #2809

Merged
Show file tree
Hide file tree
Changes from all 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
66 changes: 7 additions & 59 deletions apps/fishing-map/features/area-report/reports.selectors.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createSelector } from '@reduxjs/toolkit'
import { groupBy, sum, uniq, uniqBy } from 'es-toolkit'
import sumBy from 'lodash/sumBy'
import { matchSorter } from 'match-sorter'
import { t } from 'i18next'
import { FeatureCollection, MultiPolygon } from 'geojson'
import { Dataset, DatasetTypes, ReportVessel } from '@globalfishingwatch/api-types'
Expand Down Expand Up @@ -32,10 +31,11 @@ import {
getBufferedArea,
getBufferedFeature,
getReportCategoryFromDataview,
getVesselsFiltered,
} from 'features/area-report/reports.utils'
import { ReportCategory } from 'types'
import { createDeepEqualSelector } from 'utils/selectors'
import { EMPTY_FIELD_PLACEHOLDER, getVesselGearType } from 'utils/info'
import { EMPTY_FIELD_PLACEHOLDER, getVesselGearTypeLabel } from 'utils/info'
import { sortStrings } from 'utils/shared'
import { Area, AreaGeometry, selectAreas } from 'features/areas/areas.slice'
import {
Expand Down Expand Up @@ -226,7 +226,7 @@ export const selectReportVesselsListWithAllInfo = createSelector(
flagTranslatedClean: cleanFlagState(
t(`flags:${vesselActivity[0]?.flag as string}` as any, vesselActivity[0]?.flag)
),
geartype: getVesselGearType({ geartypes: vesselActivity[0]?.geartype }),
geartype: getVesselGearTypeLabel({ geartypes: vesselActivity[0]?.geartype }),
vesselType: t(
`vessel.veeselTypes.${vesselActivity[0]?.vesselType}` as any,
vesselActivity[0]?.vesselType
Expand All @@ -243,7 +243,7 @@ function cleanVesselOrGearType({ value, property }: CleanVesselOrGearTypeParams)
const valuesCleanTranslated = valuesClean
.map((value) => {
if (property === 'geartype') {
return getVesselGearType({ geartypes: value })
return getVesselGearTypeLabel({ geartypes: value })
}
return t(`vessel.vesselTypes.${value?.toLowerCase()}` as any, value)
})
Expand All @@ -257,65 +257,13 @@ export function cleanFlagState(flagState: string) {
return flagState.replace(/,/g, '')
}

type FilterProperty = 'name' | 'flag' | 'mmsi' | 'gear' | 'type'
const FILTER_PROPERTIES: Record<FilterProperty, string[]> = {
name: ['shipName'],
flag: ['flag', 'flagTranslated', 'flagTranslatedClean'],
mmsi: ['mmsi'],
gear: ['geartype'],
type: ['vesselType'],
}

export function getVesselsFiltered(vessels: ReportVesselWithDatasets[], filter: string) {
if (!filter || !filter.length) {
return vessels
}

const filterBlocks = filter
.replace(/ ,/g, ',')
.replace(/ , /g, ',')
.replace(/, /g, ',')
.split(',')
.filter((block) => block.length)

if (!filterBlocks.length) {
return vessels
}

return filterBlocks
.reduce((vessels, block) => {
const propertiesToMatch =
block.includes(':') && FILTER_PROPERTIES[block.split(':')[0] as FilterProperty]
const words = (propertiesToMatch ? (block.split(':')[1] as FilterProperty) : block)
.replace('-', '')
.split('|')
.map((word) => word.trim())
.filter((word) => word.length)
const matched = words.flatMap((w) =>
matchSorter(vessels, w, {
keys: propertiesToMatch || Object.values(FILTER_PROPERTIES).flat(),
threshold: matchSorter.rankings.CONTAINS,
})
)
const uniqMatched = block.includes('|') ? Array.from(new Set([...matched])) : matched
if (block.startsWith('-')) {
const uniqMatchedIds = new Set<string>()
uniqMatched.forEach(({ vesselId = '' }) => {
uniqMatchedIds.add(vesselId)
})
return vessels.filter(({ vesselId = '' }) => !uniqMatchedIds.has(vesselId))
} else {
return uniqMatched
}
}, vessels)
.sort((a, b) => b.value - a.value)
}

export const selectReportVesselsFiltered = createSelector(
[selectReportVesselsList, selectReportVesselFilter],
(vessels, filter) => {
if (!vessels?.length) return null
return getVesselsFiltered(vessels, filter)
return getVesselsFiltered<ReportVesselWithDatasets>(vessels, filter).sort(
(a, b) => b.value - a.value
)
}
)

Expand Down
64 changes: 64 additions & 0 deletions apps/fishing-map/features/area-report/reports.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { featureCollection, multiPolygon } from '@turf/helpers'
import { difference, dissolve } from '@turf/turf'
import { Feature, FeatureCollection, MultiPolygon, Polygon } from 'geojson'
import { parse } from 'qs'
import { matchSorter } from 'match-sorter'
import { UrlDataviewInstance } from '@globalfishingwatch/dataviews-client'
import { Dataview, DataviewCategory, EXCLUDE_FILTER_ID } from '@globalfishingwatch/api-types'
import { getFeatureBuffer, wrapGeometryBbox } from '@globalfishingwatch/data-transforms'
Expand All @@ -20,6 +21,7 @@ import {
import { Bbox, BufferOperation, BufferUnit, ReportCategory } from 'types'
import { Area, AreaGeometry } from 'features/areas/areas.slice'
import { IdentityVesselData, VesselDataIdentity } from 'features/vessel/vessel.slice'
import { VesselGroupReportVesselParsed } from 'features/vessel-group-report/vessels/vessel-group-report-vessels.types'
import {
DEFAULT_BUFFER_OPERATION,
DEFAULT_POINT_BUFFER_UNIT,
Expand Down Expand Up @@ -306,3 +308,65 @@ export function parseReportVesselsToIdentity(
})
return identityVessels
}

export type FilterProperty = 'name' | 'flag' | 'mmsi' | 'gear' | 'type'
export const FILTER_PROPERTIES: Record<FilterProperty, string[]> = {
name: ['shipName'],
flag: ['flag', 'flagTranslated', 'flagTranslatedClean'],
mmsi: ['mmsi'],
gear: ['geartype'],
type: ['vesselType'],
}

export function getVesselsFiltered<
Vessel = ReportVesselWithDatasets | VesselGroupReportVesselParsed
>(vessels: Vessel[], filter: string, filterProperties = FILTER_PROPERTIES) {
if (!filter || !filter.length) {
return vessels
}

const filterBlocks = filter
.replace(/ ,/g, ',')
.replace(/ , /g, ',')
.replace(/, /g, ',')
.split(',')
.filter((block) => block.length)

if (!filterBlocks.length) {
return vessels
}

return filterBlocks.reduce((vessels, block) => {
const propertiesToMatch =
block.includes(':') && filterProperties[block.split(':')[0] as FilterProperty]
const words = (propertiesToMatch ? (block.split(':')[1] as FilterProperty) : block)
.replace('-', '')
.split('|')
.map((word) => word.trim())
.filter((word) => word.length)
const matched = words.flatMap((w) =>
matchSorter(vessels, w, {
keys: propertiesToMatch || Object.values(filterProperties).flat(),
threshold: matchSorter.rankings.CONTAINS,
})
)
const uniqMatched = block.includes('|') ? Array.from(new Set([...matched])) : matched
if (block.startsWith('-')) {
const uniqMatchedIds = new Set<string>()
uniqMatched.forEach((vessel) => {
const id =
(vessel as ReportVesselWithDatasets).vesselId ||
(vessel as VesselGroupReportVesselParsed).id
uniqMatchedIds.add(id)
})
return vessels.filter((vessel) => {
const id =
(vessel as ReportVesselWithDatasets).vesselId ||
(vessel as VesselGroupReportVesselParsed).id
return !uniqMatchedIds.has(id)
})
} else {
return uniqMatched
}
}, vessels) as Vessel[]
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ReportVesselsGraphSelector from 'features/area-report/vessels/ReportVesse
import {
selectActiveReportDataviews,
selectReportCategory,
selectReportVesselFilter,
} from 'features/app/selectors/app.reports.selector'
import { ReportCategory } from 'types'
import ReportSummaryTags from 'features/area-report/summary/ReportSummaryTags'
Expand All @@ -24,6 +25,7 @@ type ReportVesselTableProps = {
export default function ReportVessels({ activityUnit, reportName }: ReportVesselTableProps) {
const { t } = useTranslation()
const reportCategory = useSelector(selectReportCategory)
const reportVesselFilter = useSelector(selectReportVesselFilter)
const dataviews = useSelector(selectActiveReportDataviews)
const commonProperties = useMemo(() => {
return getCommonProperties(dataviews).filter(
Expand Down Expand Up @@ -53,7 +55,11 @@ export default function ReportVessels({ activityUnit, reportName }: ReportVessel
))}
</div>
<ReportVesselsGraph />
<ReportVesselsFilter />
<ReportVesselsFilter
filter={reportVesselFilter}
filterQueryParam="reportVesselFilter"
pageQueryParam="reportVesselPage"
/>
<ReportVesselsTable activityUnit={activityUnit} reportName={reportName} />
</div>
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import React, { useEffect, useState, Fragment } from 'react'
import { useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import { useDebounce } from 'use-debounce'
import { InputText, Tooltip } from '@globalfishingwatch/ui-components'
import { selectReportVesselFilter } from 'features/app/selectors/app.reports.selector'
import { useLocationConnect } from 'routes/routes.hook'
import { TrackCategory, trackEvent } from 'features/app/analytics.hooks'
import styles from './ReportVesselsFilter.module.css'

type ReportVesselsFilterProps = {}
type ReportVesselsFilterProps = {
filter: string
filterQueryParam: string
pageQueryParam: string
}

export default function ReportVesselsFilter(props: ReportVesselsFilterProps) {
export default function ReportVesselsFilter({
filter,
filterQueryParam,
pageQueryParam,
}: ReportVesselsFilterProps) {
const { t } = useTranslation()
const reportVesselFilter = useSelector(selectReportVesselFilter)
const { dispatchQueryParams } = useLocationConnect()
const [query, setQuery] = useState(reportVesselFilter)
const [query, setQuery] = useState(filter)
const [debouncedQuery] = useDebounce(query, 200)

useEffect(() => {
dispatchQueryParams({ reportVesselFilter: debouncedQuery, reportVesselPage: 0 })
dispatchQueryParams({ [filterQueryParam]: debouncedQuery, [pageQueryParam]: 0 })
trackEvent({
category: TrackCategory.Analysis,
action: 'Type search into vessel list',
Expand All @@ -28,11 +33,11 @@ export default function ReportVesselsFilter(props: ReportVesselsFilterProps) {
}, [debouncedQuery])

useEffect(() => {
if (reportVesselFilter !== query) {
setQuery(reportVesselFilter)
if (filter !== query) {
setQuery(filter)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reportVesselFilter])
}, [filter])

return (
<div className={styles.inputContainer}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
REPORT_VESSELS_GRAPH_VESSELTYPE,
} from 'data/config'
import { EMPTY_API_VALUES, OTHERS_CATEGORY_LABEL } from 'features/area-report/reports.config'
import { getVesselGearType } from 'utils/info'
import { getVesselGearTypeLabel } from 'utils/info'
import {
cleanFlagState,
selectReportDataviewsWithPermissions,
Expand Down Expand Up @@ -48,7 +48,7 @@ const ReportGraphTooltip = (props: any) => {
let translatedLabel = ''
if (EMPTY_API_VALUES.includes(label)) translatedLabel = t('common.unknown', 'Unknown')
else if (type === 'geartype') {
translatedLabel = getVesselGearType({ geartypes: label })
translatedLabel = getVesselGearTypeLabel({ geartypes: label })
} else {
translatedLabel = t(`flags:${label}` as any, label)
}
Expand Down Expand Up @@ -88,7 +88,7 @@ const CustomTick = (props: any) => {
if (EMPTY_API_VALUES.includes(label)) return t('analysis.unknown', 'Unknown')
switch (selectedReportVesselGraph) {
case 'geartype':
return getVesselGearType({ geartypes: label })
return getVesselGearTypeLabel({ geartypes: label })
case 'vesselType':
return `${t(`vessel.vesselTypes.${label?.toLowerCase()}` as any, label)}`
case 'flag':
Expand Down
6 changes: 3 additions & 3 deletions apps/fishing-map/features/datasets/datasets.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { capitalize, sortFields } from 'utils/shared'
import { t } from 'features/i18n/i18n'
import { PUBLIC_SUFIX, FULL_SUFIX, DEFAULT_TIME_RANGE } from 'data/config'
import { getFlags, getFlagsByIds } from 'utils/flags'
import { getVesselGearType, getVesselShipType } from 'utils/info'
import { getVesselGearTypeLabel, getVesselShipTypeLabel } from 'utils/info'
import { getDatasetNameTranslated } from 'features/i18n/utils.datasets'
import { formatI18nNumber } from 'features/i18n/i18nNumber'
import styles from '../vessel-groups/VesselGroupModal.module.css'
Expand Down Expand Up @@ -732,9 +732,9 @@ export const getCommonSchemaFieldsInDataview = (
if (label === field) {
if (schema === 'geartypes' || schema === 'geartype') {
// There is an fixed list of gearTypes independant of the dataset
label = getVesselGearType({ geartypes: field as string })
label = getVesselGearTypeLabel({ geartypes: field as string })
} else if (schema === 'vessel_type') {
label = getVesselShipType({ shiptypes: field as string })
label = getVesselShipTypeLabel({ shiptypes: field as string })
} else if (
dataview.category !== DataviewCategory.Context &&
schema !== 'vessel_id' &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
import { isBathymetryDataview } from 'features/dataviews/dataviews.utils'
import { selectDownloadActiveTabId } from 'features/download/downloadActivity.slice'
import { HeatmapDownloadTab } from 'features/download/downloadActivity.config'
import { selectViewOnlyVesselGroup } from 'features/vessel-group-report/vessel.config.selectors'
import { selectViewOnlyVesselGroup } from 'features/vessel-group-report/vessel-group.config.selectors'
import {
selectContextAreasDataviews,
selectActivityDataviews,
Expand Down
1 change: 0 additions & 1 deletion apps/fishing-map/features/map/map-interactions.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,6 @@ export const useClickedEventConnect = () => {
}
)

console.log('heatmapFeatures:', heatmapFeatures)
if (heatmapFeatures?.length) {
dispatch(setHintDismissed('clickingOnAGridCellToShowVessels'))
const heatmapProperties = heatmapFeatures.map((feature) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import {
EMPTY_FIELD_PLACEHOLDER,
formatInfoField,
getDetectionsTimestamps,
getVesselGearType,
getVesselGearTypeLabel,
getVesselOtherNamesLabel,
getVesselShipType,
getVesselShipTypeLabel,
} from 'utils/info'
import { getDatasetLabel } from 'features/datasets/datasets.utils'
import I18nNumber from 'features/i18n/i18nNumber'
Expand Down Expand Up @@ -163,10 +163,10 @@ function VesselsTable({
const vesselFlag = getVesselProperty(vessel, 'flag', getVesselPropertyParams)

const vesselType = isPresenceActivity
? getVesselShipType({
? getVesselShipTypeLabel({
shiptypes: getVesselProperty(vessel, 'shiptypes', getVesselPropertyParams),
})
: getVesselGearType({
: getVesselGearTypeLabel({
geartypes: getVesselProperty(vessel, 'geartypes', getVesselPropertyParams),
})

Expand Down
8 changes: 5 additions & 3 deletions apps/fishing-map/features/search/SearchDownload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { unparse as unparseCSV } from 'papaparse'
import { saveAs } from 'file-saver'
import { IconButton } from '@globalfishingwatch/ui-components'
import { getSearchIdentityResolved, getVesselProperty } from 'features/vessel/vessel.utils'
import { formatInfoField, getVesselGearType, getVesselShipType } from 'utils/info'
import { formatInfoField, getVesselGearTypeLabel, getVesselShipTypeLabel } from 'utils/info'
import { TrackCategory, trackEvent } from 'features/app/analytics.hooks'
import { selectSearchResults, selectSelectedVessels } from './search.slice'

Expand All @@ -22,8 +22,10 @@ function SearchDownload() {
imo: getVesselProperty(vessel, 'imo'),
'call sign': getVesselProperty(vessel, 'callsign'),
flag: t(`flags:${getVesselProperty(vessel, 'flag')}` as any),
'vessel type': getVesselShipType({ shiptypes: getVesselProperty(vessel, 'shiptypes') }),
'gear type': getVesselGearType({
'vessel type': getVesselShipTypeLabel({
shiptypes: getVesselProperty(vessel, 'shiptypes'),
}),
'gear type': getVesselGearTypeLabel({
geartypes: getVesselProperty(vessel, 'geartypes'),
}),
owner: formatInfoField(getVesselProperty(vessel, 'owner'), 'owner'),
Expand Down
Loading
Loading