Skip to content

Commit

Permalink
Merge pull request #3299 from LiteFarmOrg/LF-4221js-and-LF-4249-adjus…
Browse files Browse the repository at this point in the history
…ts-branch

LF-4221 and LF-4249 Adjustments
  • Loading branch information
kathyavini authored Jul 18, 2024
2 parents 91f61fd + 4f620b0 commit 7aca0f1
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 69 deletions.
4 changes: 2 additions & 2 deletions packages/webapp/src/components/Form/NumberInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { ReactNode } from 'react';
import InputBase, { type InputBaseSharedProps } from '../InputBase';
import NumberInputStepper from './NumberInputStepper';
import useNumberInput, { NumberInputOptions } from './useNumberInput';
import { FieldValues, UseControllerProps, useController } from 'react-hook-form';
import { FieldValues, UseControllerProps, useController, get } from 'react-hook-form';

export type NumberInputProps<T extends FieldValues> = UseControllerProps<T> &
InputBaseSharedProps &
Expand Down Expand Up @@ -60,7 +60,7 @@ export default function NumberInput<T extends FieldValues>({
}: NumberInputProps<T>) {
const { field, fieldState, formState } = useController({ name, control, rules, defaultValue });
const { inputProps, reset, numericValue, increment, decrement } = useNumberInput({
initialValue: defaultValue || formState.defaultValues?.[name],
initialValue: get(formState.defaultValues, name) || defaultValue,
allowDecimal,
decimalDigits,
locale,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@ const SoilAmendmentProductCard = ({
</>
)}
<QuantityApplicationRate
productId={PRODUCT_ID}
system={system}
locations={locations}
isReadOnly={isReadOnly}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,21 @@ export interface Location {
}

export type QuantityApplicationRateProps = {
productId: number | string;
isReadOnly: boolean;
system: 'metric' | 'imperial';
locations: Location[];
namePrefix?: string;
};

const QuantityApplicationRate = ({
productId,
isReadOnly,
system, // measurementSelector
locations,
namePrefix = '',
}: QuantityApplicationRateProps) => {
const { t } = useTranslation();

const { control, getValues, setValue, register, watch, formState } = useFormContext();
const { control, getValues, setValue, register, watch } = useFormContext();

const WEIGHT = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.WEIGHT}`;
const VOLUME = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.VOLUME}`;
Expand Down Expand Up @@ -106,7 +104,7 @@ const QuantityApplicationRate = ({
const {
updateApplicationRate,
updateQuantity,
onPercentLocationChange,
updateTotalArea,
previewStringValue,
previewStringUnit,
} = useQuantityApplicationRate({
Expand Down Expand Up @@ -180,7 +178,7 @@ const QuantityApplicationRate = ({
<KeyboardArrowDownIcon className={styles.expandIcon} />
</TextButton>

<Collapse id={`application_rate-${productId}`} in={isExpanded} timeout="auto">
<Collapse id={'application_rate'} in={isExpanded} timeout="auto">
<div className={styles.sectionBody}>
<div className={styles.locationSection}>
<NumberInput
Expand All @@ -190,9 +188,9 @@ const QuantityApplicationRate = ({
min={0.0001}
max={100}
rules={{ required: t('common:REQUIRED') }}
onChange={onPercentLocationChange}
onChange={updateTotalArea}
disabled={isReadOnly}
defaultValue={formState.defaultValues?.[PERCENT_OF_LOCATION_AMENDED] || 100}
defaultValue={100}
/>
<SwapIcon />
{/* @ts-ignore */}
Expand All @@ -208,7 +206,6 @@ const QuantityApplicationRate = ({
hookFromWatch={watch}
control={control}
mode={'onChange'}
defaultValue={formState.defaultValues?.[TOTAL_AREA_AMENDED] || total_area}
disabled
required
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
* GNU General Public License for more details, see <https://www.gnu.org/licenses/>.
*/

import { useEffect, useState } from 'react';
import { TASK_PRODUCT_FIELD_NAMES, UnitOption } from '../types';
import { useEffect, useMemo } from 'react';
import { TASK_PRODUCT_FIELD_NAMES } from '../types';
import { getUnitOptionMap } from '../../../../util/convert-units/getUnitOptionMap';
import { convertFn, getDefaultUnit, location_area } from '../../../../util/convert-units/unit';
import { roundToTwoDecimal } from '../../../../util';
Expand All @@ -36,6 +36,7 @@ export const useQuantityApplicationRate = ({
isWeight,
namePrefix,
}: UseQuantityApplicationRate) => {
const PERCENT_OF_LOCATION_AMENDED = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.PERCENT_OF_LOCATION_AMENDED}`;
const TOTAL_AREA_AMENDED = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.TOTAL_AREA_AMENDED}`;
const TOTAL_AREA_AMENDED_UNIT = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.TOTAL_AREA_AMENDED_UNIT}`;
const VOLUME = `${namePrefix}.${TASK_PRODUCT_FIELD_NAMES.VOLUME}`;
Expand All @@ -49,22 +50,15 @@ export const useQuantityApplicationRate = ({

const { setValue, getValues, watch } = useFormContext();

const [
application_area_unit,
weight_unit,
volume_unit,
application_rate_weight_unit,
application_rate_volume_unit,
] = watch([
TOTAL_AREA_AMENDED_UNIT,
WEIGHT_UNIT,
VOLUME_UNIT,
APPLICATION_RATE_WEIGHT_UNIT,
APPLICATION_RATE_VOLUME_UNIT,
]);
const [weight_unit, volume_unit, application_rate_weight_unit, application_rate_volume_unit] =
watch([WEIGHT_UNIT, VOLUME_UNIT, APPLICATION_RATE_WEIGHT_UNIT, APPLICATION_RATE_VOLUME_UNIT]);

useEffect(() => {
updateTotalArea(getValues(PERCENT_OF_LOCATION_AMENDED));
}, []);

/* Update application area + rate based on percent of location */
const onPercentLocationChange = (percent_of_location: number) => {
const updateTotalArea = (percent_of_location: number) => {
const calculatedArea = (total_area * Math.min(percent_of_location || 100, 100)) / 100;
setValue(TOTAL_AREA_AMENDED, calculatedArea);

Expand Down Expand Up @@ -138,34 +132,39 @@ export const useQuantityApplicationRate = ({
updateQuantity();
}, [application_rate_weight_unit, application_rate_volume_unit]);

/* For the preview string, replicate the conversion the unit component would do if the value had been displayed in a <Unit /> rather than a string. However, don't update upon changes to application_area_unit beyond the initial undefined > defined change */
const [previewStringValue, setPreviewStringValue] = useState<number | null>(null);
const [previewStringUnit, setPreviewStringUnit] = useState<string | null>(null);
/* For the preview string, replicate the conversion the unit component would do if the value had been displayed in a <Unit /> rather than a string */
const previewStrings = useMemo(() => {
let previewStringUnit;
let previewStringValue;

useEffect(() => {
if (application_area_unit && previewStringValue === null) {
/* if the user-selected unit is in the wrong system (e.g. metric stored value but farm on imperial), use the <Unit /> converted unit */
const unit =
if (total_area) {
previewStringUnit =
total_area_unit && location_area[system].units.includes(total_area_unit)
? getUnitOptionMap()[total_area_unit]
: application_area_unit;
: /* @ts-ignore */
getUnitOptionMap()[getDefaultUnit(location_area, total_area, system).displayUnit];

const value =
previewStringValue =
total_area &&
roundToTwoDecimal(
convertFn(location_area[system], total_area, location_area.databaseUnit, unit.value),
convertFn(
location_area[system],
total_area,
location_area.databaseUnit,
previewStringUnit.value,
),
);

setPreviewStringValue(value);
setPreviewStringUnit(unit.label);
previewStringUnit = previewStringUnit.label;
}
}, [location_area, application_area_unit]);

return { previewStringUnit, previewStringValue };
}, [total_area]);

return {
previewStringValue,
previewStringUnit,
previewStringValue: previewStrings.previewStringValue,
previewStringUnit: previewStrings.previewStringUnit,
updateApplicationRate,
updateQuantity,
onPercentLocationChange,
updateTotalArea,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ interface ProductFields {

const FIELD_NAME = 'soil_amendment_task_products';

const defaultValues = {
export const defaultValues = {
[TASK_PRODUCT_FIELD_NAMES.PRODUCT_ID]: undefined,
[TASK_PRODUCT_FIELD_NAMES.PURPOSES]: [],
[TASK_PRODUCT_FIELD_NAMES.IS_WEIGHT]: true,
};

const AddSoilAmendmentProducts = ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import PureHarvestingTask from '../HarvestingTask';
import PurePestControlTask from '../PestControlTask';
import PureIrrigationTask from '../PureIrrigationTask';
import PureSoilAmendmentTask from '../SoilAmendmentTask';
import { defaultValues as soilAmendmentProductDefaultValues } from '../AddSoilAmendmentProducts';

export default function PureTaskDetails({
handleGoBack,
Expand All @@ -38,7 +39,7 @@ export default function PureTaskDetails({
const defaults = {
CLEANING_TASK: { cleaning_task: { agent_used: false } },
SOIL_AMENDMENT_TASK: {
soil_amendment_task_products: [{}],
soil_amendment_task_products: [soilAmendmentProductDefaultValues],
},
};

Expand Down
40 changes: 17 additions & 23 deletions packages/webapp/src/util/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,16 @@ type FormSoilAmendmentTaskProduct = {
purposes: number[];
other_purpose?: string;
weight?: number;
weight_unit?: UnitOption;
weight_unit?: UnitOption | string;
volume?: number;
volume_unit?: UnitOption;
volume_unit?: UnitOption | string;
percent_of_location_amended: number;
total_area_amended: number;
total_area_amended_unit?: UnitOption;
total_area_amended_unit?: UnitOption | string;
application_rate_weight?: number;
application_rate_weight_unit?: UnitOption;
application_rate_weight_unit?: UnitOption | string;
application_rate_volume?: number;
application_rate_volume_unit?: UnitOption;
application_rate_volume_unit?: UnitOption | string;
is_weight: boolean;
[key: string]: any;
};
Expand Down Expand Up @@ -93,23 +93,17 @@ export const formatSoilAmendmentTaskToFormStructure = (
formattedTaskProduct.purposes.push(purpose_id);
});

const unitOptions: { [key: string]: UnitOption } = getUnitOptionMap();

return {
...formattedTaskProduct,
weight_unit: isWeight && rest.weight_unit ? unitOptions[rest.weight_unit] : undefined,
volume_unit: !isWeight && rest.volume_unit ? unitOptions[rest.volume_unit] : undefined,
total_area_amended_unit: rest.total_area_amended_unit
? unitOptions[rest.total_area_amended_unit]
weight_unit: isWeight ? rest.weight_unit : undefined,
volume_unit: !isWeight ? rest.volume_unit : undefined,
total_area_amended_unit: rest.total_area_amended_unit || undefined,
application_rate_weight_unit: rest.application_rate_weight
? rest.application_rate_weight_unit
: undefined,
application_rate_volume_unit: rest.application_rate_volume
? rest.application_rate_volume_unit
: undefined,
application_rate_weight_unit:
rest.application_rate_weight && rest.application_rate_weight_unit
? unitOptions[rest.application_rate_weight_unit]
: undefined,
application_rate_volume_unit:
rest.application_rate_volume && rest.application_rate_volume_unit
? unitOptions[rest.application_rate_volume_unit]
: undefined,
};
},
);
Expand Down Expand Up @@ -154,14 +148,14 @@ export const formatSoilAmendmentProductToDBStructure = (
return {
...rest,
weight: is_weight ? rest.weight : undefined,
weight_unit: is_weight ? rest.weight_unit?.value : undefined,
weight_unit: is_weight ? (rest.weight_unit as UnitOption)?.value : undefined,
application_rate_weight_unit: is_weight
? rest.application_rate_weight_unit?.value
? (rest.application_rate_weight_unit as UnitOption)?.value
: undefined,
volume: !is_weight ? rest.volume : undefined,
volume_unit: !is_weight ? rest.volume_unit?.value : undefined,
volume_unit: !is_weight ? (rest.volume_unit as UnitOption)?.value : undefined,
application_rate_volume_unit: !is_weight
? rest.application_rate_volume_unit?.value
? (rest.application_rate_volume_unit as UnitOption)?.value
: undefined,
purpose_relationships: formatPurposeIdsToRelationships(
purposeIds,
Expand Down

0 comments on commit 7aca0f1

Please sign in to comment.