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

LF-4166 (4): Implement end to end animal creation flow #3397

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
19eb066
LF-4166 Add missing properties to Animal/Batch types
SayakaOno Aug 27, 2024
c7e41f8
LF-4166 Correct organic status Option type
SayakaOno Aug 27, 2024
5f7e8f9
LF-4166 Correct addAnimalBatches mutation request body type
SayakaOno Aug 27, 2024
50b9556
LF-4166 Create format functions for animal and batch
SayakaOno Aug 27, 2024
6fcb104
LF-4166 Implement onSave function in AddAnimals
SayakaOno Aug 27, 2024
1c7b4dc
LF-4166 Fix format animal/batch functions
SayakaOno Aug 27, 2024
2582ce0
LF-4166 Fix dates' format in Animal model
SayakaOno Aug 28, 2024
b694cca
LF-4166 Finalize organic status type
SayakaOno Aug 28, 2024
6c9ff30
LF-4166 Rename animal util functions
SayakaOno Aug 28, 2024
5260f26
LF-4166 Create PostAnimalBatch type
SayakaOno Aug 28, 2024
b266c93
LF-4166 Correct types
SayakaOno Aug 28, 2024
8d85441
LF-4166 Move birth_date to origin section in format function
SayakaOno Aug 28, 2024
9f9560b
LF-4166 Add missing properties to AnimalBatch type
SayakaOno Aug 28, 2024
032ed32
LF-4166 Fix animal batch POST request body and type
SayakaOno Aug 29, 2024
2baba57
Merge branch 'integration' into LF-4166/Complete_Implement_End-to-End…
SayakaOno Aug 29, 2024
9fc8d20
Apply suggestions from code review
SayakaOno Aug 30, 2024
ad2b487
LF-4166 Create OrganicStatus type
SayakaOno Aug 30, 2024
e7e4078
LF-4166 /animal_type_use_relationship
SayakaOno Aug 30, 2024
1211b98
Filter uses in animal details
SayakaOno Aug 30, 2024
f73d909
Adjust add animal summary image width
SayakaOno Aug 30, 2024
79566c6
Merge pull request #3402 from LiteFarmOrg/Add_animal_fix
Duncan-Brain Sep 3, 2024
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
6 changes: 3 additions & 3 deletions packages/api/src/models/animalModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,14 @@ class Animal extends baseModel {
custom_breed_id: { type: ['integer', 'null'] },
sex_id: { type: ['integer', 'null'] },
name: { type: ['string', 'null'] },
birth_date: { type: ['string', 'null'], format: 'date' },
birth_date: { type: ['string', 'null'], format: 'date-time' },
identifier: { type: ['string', 'null'] },
identifier_color_id: { type: ['integer', 'null'] },
origin_id: { type: ['integer', 'null'] },
dam: { type: ['string', 'null'] },
sire: { type: ['string', 'null'] },
brought_in_date: { type: ['string', 'null'], format: 'date' },
weaning_date: { type: ['string', 'null'], format: 'date' },
brought_in_date: { type: ['string', 'null'], format: 'date-time' },
weaning_date: { type: ['string', 'null'], format: 'date-time' },
notes: { type: ['string', 'null'] },
photo_url: { type: ['string', 'null'] },
animal_removal_reason_id: { type: ['integer', 'null'] },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@

.imageContainer {
padding-top: 32px;
width: 488px;
max-width: 488px;
overflow: hidden;
flex: 1;

@include md-breakpoint {
order: 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,16 @@ import {
DetailsFields,
} from '../types';
import { AnimalOrBatchKeys } from '../../types';
import { useGetAnimalUsesQuery } from '../../../../store/api/apiSlice';
import { parseUniqueDefaultId } from '../../../../util/animal';

export const usePopulateDetails = (
replace: UseFieldArrayReplace<AddAnimalsFormFields, 'details'>,
) => {
const { getValues } = useFormContext<AddAnimalsFormFields>();

const { data: uses = [] } = useGetAnimalUsesQuery();

useEffect(() => {
const detailsArray: AnimalDetailsFormFields[] = [];

Expand Down Expand Up @@ -86,6 +90,17 @@ export const usePopulateDetails = (

return updatedData.map((entity, index) => {
const origData = trimmedOrigGroup[index] || {};
const currentDefaultTypeId = parseUniqueDefaultId(entity.type.value);
if (currentDefaultTypeId && origData.use) {
const { use: oldUse } = origData;
const useIdsForType =
uses
.find(({ default_type_id }) => currentDefaultTypeId === default_type_id)
?.uses.map(({ id }) => id) || [];
const updatedUse = oldUse.filter(({ value }) => useIdsForType.includes(value));
origData.use = updatedUse;
}

return {
...origData,
...entity,
Expand Down
40 changes: 30 additions & 10 deletions packages/webapp/src/containers/Animals/AddAnimals/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,16 @@ import { MultiStepForm, VARIANT } from '../../../components/Form/MultiStepForm';
import AddAnimalBasics, { animalBasicsDefaultValues } from './AddAnimalBasics';
import AddAnimalDetails from './AddAnimalDetails';
import AddAnimalSummary from './AddAnimalSummary';
import { useAddAnimalBatchesMutation, useAddAnimalsMutation } from '../../../store/api/apiSlice';
import {
useAddAnimalBatchesMutation,
useAddAnimalsMutation,
useGetAnimalOriginsQuery,
} from '../../../store/api/apiSlice';
import { Animal, AnimalBatch } from '../../../store/api/types';
import { enqueueErrorSnackbar } from '../../Snackbar/snackbarSlice';
import { formatAnimalDetailsToDBStructure, formatBatchDetailsToDBStructure } from './utils';
import { AnimalDetailsFormFields } from './types';
import { AnimalOrBatchKeys } from '../types';

export const STEPS = {
BASICS: 'basics',
Expand All @@ -45,24 +51,42 @@ function AddAnimals({ isCompactSideMenu, history }: AddAnimalsProps) {
const [addAnimals] = useAddAnimalsMutation();
const [addAnimalBatches] = useAddAnimalBatchesMutation();

const { data: orgins = [] } = useGetAnimalOriginsQuery();

const onSave = async (
data: any,
onGoForward: () => void,
setFormResultData: (data: any) => void,
) => {
const formattedAnimals = formatAnimalDetailsToDBStructure([]);
const formattedBatches = formatBatchDetailsToDBStructure([]);
const details = data[STEPS.DETAILS] as AnimalDetailsFormFields[];
const broughtInId = orgins.find((origin) => origin.key === 'BROUGHT_IN')?.id;

const formattedAnimals: Partial<Animal>[] = [];
const formattedBatches: Partial<AnimalBatch>[] = [];

details.forEach((animalOrBatch) => {
if (animalOrBatch.animal_or_batch === AnimalOrBatchKeys.ANIMAL) {
formattedAnimals.push(formatAnimalDetailsToDBStructure(animalOrBatch, broughtInId));
} else {
formattedBatches.push(formatBatchDetailsToDBStructure(animalOrBatch, broughtInId));
}
});

let animalsResult: Animal[] = [];
let batchesResult: AnimalBatch[] = [];

try {
animalsResult = await addAnimals(formattedAnimals).unwrap();
if (formattedAnimals.length) {
animalsResult = await addAnimals(formattedAnimals).unwrap();
}
} catch (e) {
console.error(e);
dispatch(enqueueErrorSnackbar(t('message:ANIMALS.FAILED_CREATE_ANIMALS')));
}
try {
batchesResult = await addAnimalBatches(formattedBatches).unwrap();
if (formattedBatches.length) {
batchesResult = await addAnimalBatches(formattedBatches).unwrap();
}
} catch (e) {
console.error(e);
dispatch(enqueueErrorSnackbar(t('message:ANIMALS.FAILED_CREATE_BATCHES')));
Expand All @@ -72,11 +96,7 @@ function AddAnimals({ isCompactSideMenu, history }: AddAnimalsProps) {
return;
}

const resultData: { animals: Animal[]; batches: AnimalBatch[] } = {
animals: animalsResult,
batches: batchesResult,
};
setFormResultData(resultData);
setFormResultData({ animals: animalsResult, batches: batchesResult });
onGoForward();
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { TFunction } from 'react-i18next';
import { STEPS } from '../AddAnimals';
import type { Option as AnimalSelectOption } from '../../../components/Animals/AddAnimalsFormCard/AnimalSelect';
import type { Details as SexDetailsType } from '../../../components/Form/SexDetails/SexDetailsPopover';
import { OrganicStatus } from '../../../types';

export const BasicsFields = {
TYPE: 'type',
Expand Down Expand Up @@ -89,7 +90,7 @@ export type Option = {
[DetailsFields.USE]: ReactSelectOption<number>;
[DetailsFields.TAG_COLOR]: ReactSelectOption<number>;
[DetailsFields.TAG_TYPE]: ReactSelectOption<number>;
[DetailsFields.ORGANIC_STATUS]: ReactSelectOption<'Non-Organic' | 'Transitional' | 'Organic'>;
[DetailsFields.ORGANIC_STATUS]: ReactSelectOption<OrganicStatus>;
[DetailsFields.SEX]: ReactSelectOption<number>;
[DetailsFields.ORIGIN]: ReactSelectOption<number>;
};
Expand Down
146 changes: 136 additions & 10 deletions packages/webapp/src/containers/Animals/AddAnimals/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,6 @@
*/

import i18n from '../../../locales/i18n';

import {
AnimalSummary,
BatchSummary,
} from '../../../components/Animals/AddAnimalsSummaryCard/types';
import {
Animal,
AnimalBatch,
Expand All @@ -28,15 +23,146 @@ import {
DefaultAnimalBreed,
DefaultAnimalType,
} from '../../../store/api/types';
import { toLocalISOString } from '../../../util/moment';
import { DetailsFields, type AnimalDetailsFormFields } from './types';
import {
AnimalSummary,
BatchSummary,
} from '../../../components/Animals/AddAnimalsSummaryCard/types';
import { chooseAnimalBreedLabel, chooseAnimalTypeLabel } from '../Inventory/useAnimalInventory';

// TODO
export const formatAnimalDetailsToDBStructure = (data: any) => {
return data;
const formatFormTypeOrBreed = (
typeOrBreed: 'type' | 'breed',
data?: { label: string; value: string; __isNew__?: boolean },
kathyavini marked this conversation as resolved.
Show resolved Hide resolved
) => {
if (!data?.value) {
return {};
}
if (data.__isNew__) {
return { [`${typeOrBreed}_name`]: data.label };
}
const [defaultOrCustom, id] = data.value.split('_');

return { [`${defaultOrCustom}_${typeOrBreed}_id`]: +id };
};

const formatFormSexDetailsAndCount = (data: AnimalDetailsFormFields): Partial<AnimalBatch> => {
if (!data[DetailsFields.SEX_DETAILS] || !data[DetailsFields.SEX_DETAILS].length) {
return { count: data[DetailsFields.COUNT]! };
}

return {
count: data[DetailsFields.COUNT]!,
sex_detail: data[DetailsFields.SEX_DETAILS].map(({ id, count }) => {
return { sex_id: id, count };
}),
};
};

const formatFormUse = (
isAnimal: boolean,
use: AnimalDetailsFormFields[DetailsFields.USE],
otherUse: AnimalDetailsFormFields[DetailsFields.OTHER_USE],
) => {
if (!use || !use.length) {
return {};
}

const key = `animal${isAnimal ? '' : '_batch'}_use_relationships`;

const useRelations: { use_id: number; other_use?: string }[] = [];

use.forEach(({ value: useId, key }, index: number) => {
useRelations.push({ use_id: useId });
if (key === 'OTHER' && otherUse) {
useRelations[index].other_use = otherUse;
}
});

return { [key]: useRelations };
};

const convertFormDate = (date?: string): string | undefined => {
if (!date) {
return undefined;
}
return toLocalISOString(date);
};

const formatOrigin = (
data: AnimalDetailsFormFields,
broughtInId?: number,
): Partial<Animal | AnimalBatch> => {
if (!broughtInId && !data[DetailsFields.ORIGIN]) {
return { birth_date: convertFormDate(data[DetailsFields.DATE_OF_BIRTH]) };
}

const isBroughtIn = broughtInId === data[DetailsFields.ORIGIN];

return {
birth_date: convertFormDate(data[DetailsFields.DATE_OF_BIRTH]),
origin_id: data[DetailsFields.ORIGIN],
...(isBroughtIn
? {
brought_in_date: convertFormDate(data[DetailsFields.BROUGHT_IN_DATE]),
supplier: data[DetailsFields.SUPPLIER],
price: data[DetailsFields.PRICE] ? +data[DetailsFields.PRICE] : undefined,
}
: {
dam: data[DetailsFields.DAM],
sire: data[DetailsFields.SIRE],
}),
};
};

const formatCommonDetails = (
isAnimal: boolean,
data: AnimalDetailsFormFields,
broughtInId?: number,
): Partial<Animal | AnimalBatch> => {
return {
// General
...formatFormTypeOrBreed('type', data[DetailsFields.TYPE]),
...formatFormTypeOrBreed('breed', data[DetailsFields.BREED]),
...(isAnimal ? { sex_id: data[DetailsFields.SEX] } : formatFormSexDetailsAndCount(data)),
...formatFormUse(isAnimal, data[DetailsFields.USE], data[DetailsFields.OTHER_USE]),

// Other
organic_status: data[DetailsFields.ORGANIC_STATUS]?.value,
notes: data[DetailsFields.OTHER_DETAILS],
photo_url: data[DetailsFields.ANIMAL_IMAGE],

// Origin
...formatOrigin(data, broughtInId),

// Unique (animal) | General (batch)
name: data[DetailsFields.NAME],
};
};

export const formatAnimalDetailsToDBStructure = (
data: AnimalDetailsFormFields,
broughtInId?: number,
): Partial<Animal> => {
return {
...formatCommonDetails(true, data, broughtInId),

// Other
weaning_date: convertFormDate(data[DetailsFields.WEANING_DATE]),

// Unique
identifier: data[DetailsFields.TAG_NUMBER],
identifier_type_id: data[DetailsFields.TAG_TYPE]?.value,
identifier_color_id: data[DetailsFields.TAG_COLOR]?.value,
identifier_type_other: data[DetailsFields.TAG_TYPE_INFO],
};
};

export const formatBatchDetailsToDBStructure = (data: any) => {
return data;
export const formatBatchDetailsToDBStructure = (
data: AnimalDetailsFormFields,
broughtInId?: number,
): Partial<AnimalBatch> => {
return formatCommonDetails(false, data, broughtInId);
};

export const getSexMap = (
Expand Down
14 changes: 14 additions & 0 deletions packages/webapp/src/store/api/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

import { TASK_TYPES } from '../../../containers/Task/constants';
import { OrganicStatus } from '../../../types';

// If we don't necessarily want to type an endpoint
export type Result = Array<{ [key: string]: any }>;
Expand All @@ -30,6 +31,8 @@ export interface Animal {
group_ids: number[];
id: number;
identifier: string | null;
identifier_type_id: number | null;
identifier_type_other: string | null;
identifier_color_id: number | null;
internal_identifier: number;
name: string | null;
Expand All @@ -39,15 +42,21 @@ export interface Animal {
sex_id: number;
sire: string | null;
weaning_date: string | null;
organic_status: OrganicStatus;
supplier: string | null;
price: number | null;
animal_removal_reason_id: number | null;
removal_explanation: string | null;
removal_date: string | null;
}

export interface AnimalBatch {
birth_date: string | null;
brought_in_date: string | null;
count: number;
custom_breed_id: number | null;
custom_type_id: number | null;
dam: string | null;
default_breed_id: number | null;
default_type_id: number | null;
farm_id: string;
Expand All @@ -56,8 +65,13 @@ export interface AnimalBatch {
internal_identifier: number;
name: string | null;
notes: string | null;
origin_id: number;
photo_url: string | null;
sex_detail: { sex_id: number; count: number }[];
sire: string | null;
organic_status: OrganicStatus;
supplier: string | null;
price: number | null;
animal_removal_reason_id: number | null;
removal_explanation: string | null;
removal_date: string | null;
Expand Down
Loading
Loading