Skip to content

Commit

Permalink
Merge pull request #1860 from Plant-for-the-Planet-org/feature/treema…
Browse files Browse the repository at this point in the history
…pper-import-errors

Resolve TS errors: TreeMapper
  • Loading branch information
mohitb35 committed Sep 27, 2023
2 parents 301891b + 7db8fe0 commit 418df20
Show file tree
Hide file tree
Showing 13 changed files with 266 additions and 162 deletions.
34 changes: 34 additions & 0 deletions src/features/common/types/plantLocation.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DateString } from './common';
import { Polygon, Point } from 'geojson';
import { Links } from './payments';

export interface PlantLocationBase {
hid: string;
Expand Down Expand Up @@ -144,3 +145,36 @@ export interface Species {
scientificName: string;
scientificSpecies: string;
}

interface Filters {
all: string;
'location-partial': string;
'location-complete': string;
'location-single': string;
'location-multi': string;
'location-sample': string;
'revision-pending': string;
}

export interface ExtendedScopePlantLocations {
items: PlantLocation[] | SamplePlantLocation[];
total: number;
count: number;
_links: Links;
_filters: Filters;
}
export interface SpeciesSuggestionType {
id: string;
name: string;
scientificName: string;
}

export type SampleTree = {
plantingDate: Date;
treeTag: string;
height: string;
diameter: string;
otherSpecies: string;
latitude: string;
longitude: string;
};
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,11 @@ export const TreePlanted = () => {
| WeeksCategories
| MonthsCategories
| YearsCategories
| string
) {
if (typeof value === 'string') {
return value; // Return the string value directly
}
return value ? value.label : '';
},
},
Expand Down
82 changes: 55 additions & 27 deletions src/features/user/TreeMapper/Import/components/PlantingLocation.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import React, { ReactElement } from 'react';
import { Controller, useForm, useFieldArray, Control } from 'react-hook-form';
import {
Controller,
useForm,
useFieldArray,
FieldErrors,
FieldArrayWithId,
Control,
} from 'react-hook-form';
import styles from '../Import.module.scss';
import { useTranslation } from 'next-i18next';
import { localeMapForDate } from '../../../../../utils/language/getLanguageName';
Expand All @@ -23,7 +30,14 @@ import themeProperties from '../../../../../theme/themeProperties';
import { handleError, APIError } from '@planet-sdk/common';
import { ErrorHandlingContext } from '../../../../common/Layout/ErrorHandlingContext';
import { MapProject } from '../../../../common/types/ProjectPropsContextInterface';
import {
FeatureCollection,
GeoJsonProperties,
Geometry,
GeometryObject,
} from 'geojson';
import { Species } from '../../../../common/types/plantLocation';
import { PlantLocation } from '../../Treemapper';

const dialogSx: SxProps = {
'& .MuiButtonBase-root.MuiPickersDay-root.Mui-selected': {
Expand All @@ -46,9 +60,9 @@ interface SpeciesProps {
index: number;
t: Function;
remove: Function;
errors: any;
item: Record<'id', string>;
control: Control<any, any>;
errors: FieldErrors<PlantLocation>;
item: FieldArrayWithId<PlantLocation, 'plantedSpecies', 'id'>;
control: Control<PlantLocation>;
}

function PlantedSpecies({
Expand All @@ -64,7 +78,7 @@ function PlantedSpecies({
<div className={styles.speciesNameField}>
{/* <SpeciesSelect label={t('treemapper:species')} name={`plantedSpecies[${index}].species`} mySpecies={mySpecies} control={control} /> */}
<Controller
name={`plantedSpecies[${index}].otherSpecies`}
name={`plantedSpecies.${index}.otherSpecies`}
control={control}
rules={{
required:
Expand All @@ -79,46 +93,45 @@ function PlantedSpecies({
value={value}
error={
errors.plantedSpecies &&
errors.plantedSpecies[index]?.otherSpecies
errors.plantedSpecies[index]?.otherSpecies !== undefined
}
helperText={
errors.plantedSpecies &&
errors.plantedSpecies[index]?.otherSpecies &&
errors.plantedSpecies[index]?.otherSpecies.message
(errors.plantedSpecies[index]?.otherSpecies?.message ?? '')
}
/>
)}
/>
</div>
<div className={styles.speciesCountField}>
<Controller
name={`plantedSpecies[${index}].treeCount`}
name={`plantedSpecies.${index}.treeCount`}
control={control}
rules={{
required: index > 0 ? false : t('treemapper:treesRequired'),
validate: (value: any) => {
return parseInt(value, 10) >= 1
? true
: t('treemapper:treesRequired');
validate: (value) => {
return Number(value) >= 1 ? true : t('treemapper:treesRequired');
},
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextField
label={t('treemapper:count')}
variant="outlined"
onChange={(e: any) => {
onChange={(e) => {
e.target.value = e.target.value.replace(/[^0-9]/g, '');
onChange(e.target.value);
}}
value={value > 0 ? value : ''}
onBlur={onBlur}
error={
errors.plantedSpecies && errors.plantedSpecies[index]?.treeCount
errors.plantedSpecies &&
errors.plantedSpecies[index]?.treeCount !== undefined
}
helperText={
errors.plantedSpecies &&
errors.plantedSpecies[index]?.treeCount &&
errors.plantedSpecies[index]?.treeCount.message
(errors.plantedSpecies[index]?.treeCount?.message ?? '')
}
/>
)}
Expand All @@ -141,9 +154,9 @@ function PlantedSpecies({
interface Props {
handleNext: () => void;
userLang: string;
plantLocation: any;
plantLocation: PlantLocation | null;
setPlantLocation: Function;
geoJson: any;
geoJson: Geometry | null;
setGeoJson: Function;
activeMethod: string;
setActiveMethod: Function;
Expand All @@ -170,7 +183,7 @@ export default function PlantingLocation({

const { t } = useTranslation(['treemapper', 'common', 'maps']);
const defaultValues = {
plantDate: new Date(),
plantDate: '',
plantProject: '',
geometry: {},
plantedSpecies: [
Expand Down Expand Up @@ -227,8 +240,12 @@ export default function PlantingLocation({
}
}, [contextLoaded]);

const normalizeGeoJson = (geoJson: any) => {
if (gjv.isGeoJSONObject(geoJson) && geoJson.features?.length > 0) {
const normalizeGeoJson = (geoJson: GeometryObject | FeatureCollection) => {
if (
gjv.isGeoJSONObject(geoJson) &&
'features' in geoJson &&
geoJson.features?.length > 0
) {
const flattened = flatten(geoJson);
if (flattened.features[0]?.geometry?.type === 'Polygon') {
setGeoJsonError(false);
Expand All @@ -246,8 +263,8 @@ export default function PlantingLocation({
}
};

const onDrop = React.useCallback((acceptedFiles: File[]) => {
acceptedFiles.forEach((file) => {
const onDrop = React.useCallback((acceptedFiles) => {
acceptedFiles.forEach((file: File) => {
const reader = new FileReader();
reader.readAsText(file);
reader.onabort = () => console.log('file reading was aborted');
Expand Down Expand Up @@ -304,15 +321,15 @@ export default function PlantingLocation({
onFileDialogCancel: () => setIsUploadingData(false),
});

const onSubmit = async (data: any) => {
const onSubmit = async (data: PlantLocation) => {
if (geoJson) {
setIsUploadingData(true);
const submitData = {
type: 'multi',
captureMode: 'external',
geometry: geoJson,
plantedSpecies: data.plantedSpecies,
plantDate: data.plantDate.toISOString(),
plantDate: new Date(data.plantDate).toISOString(),
registrationDate: new Date().toISOString(),
plantProject: data.plantProject,
};
Expand Down Expand Up @@ -366,7 +383,11 @@ export default function PlantingLocation({
<JSONInput
id="json-editor"
placeholder={geoJson}
onChange={(json: any) => normalizeGeoJson(json.jsObject)}
onChange={(json: {
jsObject:
| Geometry
| FeatureCollection<Geometry, GeoJsonProperties>;
}) => normalizeGeoJson(json.jsObject)}
locale={locale}
height="220px"
width="100%"
Expand Down Expand Up @@ -437,7 +458,7 @@ export default function PlantingLocation({
onChange={onChange}
onBlur={onBlur}
value={value}
error={errors.plantProject}
error={errors.plantProject !== undefined}
helperText={errors.plantProject && errors.plantProject.message}
>
{projects.map((option) => (
Expand Down Expand Up @@ -477,7 +498,8 @@ export default function PlantingLocation({
fields.map((item, index) => {
return (
<PlantedSpecies
key={index}
// Use id instead of index to prevent rerenders as per rhf guidelines
key={item.id}
index={index}
t={t}
remove={remove}
Expand All @@ -492,6 +514,12 @@ export default function PlantingLocation({
append({
otherSpecies: '',
treeCount: 0,
// Set to default or empty value for type match
scientificName: '',
created: '',
scientificSpecies: '',
id: '',
updated: '',
});
}}
className={styles.addSpeciesButton}
Expand Down
42 changes: 18 additions & 24 deletions src/features/user/TreeMapper/Import/components/ReviewSubmit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ import styles from '../Import.module.scss';
import { useTranslation } from 'next-i18next';
import formatDate from '../../../../../utils/countryCurrency/getFormattedDate';
import { useRouter } from 'next/router';
import { PlantLocation } from '../../Treemapper';
import { Button } from '@mui/material';
import { PlantLocation } from '../../Treemapper';

interface Props {
plantLocation: PlantLocation | null;
plantLocation: PlantLocation;
handleBack: () => void;
errorMessage: string;
setErrorMessage: (errorMessage: string) => void;
Expand All @@ -16,8 +16,6 @@ interface Props {
export default function ReviewSubmit({
plantLocation,
handleBack,
errorMessage,
setErrorMessage,
}: Props): ReactElement {
const router = useRouter();
const { t } = useTranslation(['treemapper', 'common']);
Expand Down Expand Up @@ -80,7 +78,7 @@ export default function ReviewSubmit({
<div className={styles.gridItemValue}>
<span>
{plantLocation.plantedSpecies
? plantLocation.plantedSpecies.map((species: any) => {
? plantLocation.plantedSpecies.map((species) => {
return (
<p key={species.id}>
{species.treeCount}{' '}
Expand All @@ -102,25 +100,21 @@ export default function ReviewSubmit({
<p className={styles.gridItemTitle}>{t('sampleTrees')}</p>
<div className={styles.gridItemValue}>
{plantLocation.samplePlantLocations &&
plantLocation.samplePlantLocations.map(
(spl: any, index: number) => {
return (
<div key={index} className={styles.value}>
{index + 1}.{' '}
<span className={styles.link}>
{spl.otherSpecies}
</span>
<br />
{spl.tag
? `${t('maps:tag')} #${spl.tag} • `
: null}
{spl?.measurements?.height}
{t('maps:meterHigh')}{spl?.measurements?.width}
{t('maps:cmWide')}
</div>
);
}
)}
plantLocation.samplePlantLocations.map((spl, index) => {
return (
<div key={index} className={styles.value}>
{index + 1}.{' '}
<span className={styles.link}>
{'otherSpecies' in spl && spl.otherSpecies}
</span>
<br />
{spl.tag ? `${t('maps:tag')} #${spl.tag} • ` : null}
{spl?.measurements?.height}
{t('maps:meterHigh')}{spl?.measurements?.width}
{t('maps:cmWide')}
</div>
);
})}
</div>
</>
) : (
Expand Down

0 comments on commit 418df20

Please sign in to comment.