import React, { useState } from "react"; import { HttpError, IResourceComponentsProps, useTranslate } from "@refinedev/core"; import { Create, useForm, useSelect } from "@refinedev/antd"; import { Form, Input, DatePicker, Select, InputNumber, Radio, Divider, Button, Typography } from "antd"; import dayjs from "dayjs"; import TextArea from "antd/es/input/TextArea"; import { IFilament } from "../filaments/model"; import { ISpool, ISpoolParsedExtras, WeightToEnter } from "./model"; import { formatLength, formatWeight, numberFormatter, numberParser } from "../../utils/parsing"; import { useSpoolmanLocations } from "../../components/otherModels"; import { MinusOutlined, PlusOutlined } from "@ant-design/icons"; import "../../utils/overrides.css"; import { EntityType, useGetFields } from "../../utils/queryFields"; import { ExtraFieldFormItem, StringifiedExtras } from "../../components/extraFields"; import utc from "dayjs/plugin/utc"; import { getCurrencySymbol, useCurrency } from "../../utils/settings"; import { useGetExternalDBFilaments } from "../../utils/queryExternalDB"; dayjs.extend(utc); interface CreateOrCloneProps { mode: "create" | "clone"; } function formatFilamentLabel(name: string, diameter: number, vendorName?: string, material?: string, weight?: number) { const portions = []; if (vendorName) { portions.push(vendorName); } portions.push(name); const extras = []; if (material) { extras.push(material); } extras.push(formatLength(diameter)); if (weight) { extras.push(formatWeight(weight)); } return `${portions.join(" - ")} (${extras.join(" ")})`; } /** * Performs a case-insensitive search for the given query in the given string. * The query is broken down into words and the search is performed on each word. */ function selectSearchMatches(query: string, test: string): boolean { const words = query.toLowerCase().split(" "); return words.every((word) => test.toLowerCase().includes(word)); } export const SpoolCreate: React.FC = (props) => { const t = useTranslate(); const extraFields = useGetFields(EntityType.spool); const currency = useCurrency(); const externalFilaments = useGetExternalDBFilaments(); const { form, formProps, formLoading, onFinish, redirect } = useForm< ISpool, HttpError, ISpoolParsedExtras, ISpoolParsedExtras >({ redirect: false, warnWhenUnsavedChanges: false, }); if (!formProps.initialValues) { formProps.initialValues = {}; } const initialWeightValue = Form.useWatch("initial_weight", form); const spoolWeightValue = Form.useWatch("spool_weight", form); if (props.mode === "clone") { // Clear out the values that we don't want to clone formProps.initialValues.first_used = null; formProps.initialValues.last_used = null; formProps.initialValues.used_weight = 0; // Fix the filament_id if (formProps.initialValues.filament) { formProps.initialValues.filament_id = formProps.initialValues.filament.id; } } // If the query variable filament_id is set, set the filament_id field to that value const query = new URLSearchParams(window.location.search); const filament_id = query.get("filament_id"); if (filament_id) { formProps.initialValues.filament_id = parseInt(filament_id); } const handleSubmit = async (redirectTo: "list" | "edit" | "create") => { const values = StringifiedExtras(await form.validateFields()); if (quantity > 1) { const submit = Array(quantity).fill(values); // queue multiple creates this way for now Refine doesn't seem to map Arrays to createMany or multiple creates like it says it does submit.forEach(async (r) => await onFinish(r)); } else { await onFinish(values); } redirect(redirectTo, (values as ISpool).id); }; const { queryResult: filamentsQuery } = useSelect({ resource: "filament", }); // Use useEffect to update the form's initialValues when the extra fields are loaded // This is necessary because the form is rendered before the extra fields are loaded React.useEffect(() => { extraFields.data?.forEach((field) => { if (formProps.initialValues && field.default_value) { const parsedValue = JSON.parse(field.default_value as string); form.setFieldsValue({ extra: { [field.key]: parsedValue } }); } }); }, [form, extraFields.data, formProps.initialValues]); const filamentSelectInternal = filamentsQuery.data?.data.map((item) => { return { label: formatFilamentLabel( item.name ?? `ID ${item.id}`, item.diameter, item.vendor?.name, item.material, item.weight ), value: item.id, weight: item.weight, spool_weight: item.spool_weight, }; }); filamentSelectInternal?.sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: "base" })); const filamentSelectExternal = externalFilaments.data?.map((item) => { return { label: formatFilamentLabel(item.name, item.diameter, item.manufacturer, item.material, item.weight), value: item.id, weight: item.weight, spool_weight: item.spool_weight, }; }); filamentSelectExternal?.sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: "base" })); const filamentSelectOptions = [ { title: "Internal", label: Internal, options: filamentSelectInternal ?? [], }, { title: "External", label: External, options: filamentSelectExternal ?? [], }, ]; const [weightToEnter, setWeightToEnter] = useState(1); const [usedWeight, setUsedWeight] = useState(0); const selectedFilamentID = Form.useWatch("filament_id", form); const selectedFilament = filamentSelectInternal?.find((obj) => { return obj.value === selectedFilamentID; }); const filamentChange = (newID: number) => { const newSelectedFilament = filamentSelectInternal?.find((obj) => { return obj.value === newID; }); const initial_weight = initialWeightValue ?? 0; const spool_weight = spoolWeightValue ?? 0; const newFilamentWeight = newSelectedFilament?.weight || 0; const newSpoolWeight = newSelectedFilament?.spool_weight || 0; const currentCalculatedFilamentWeight = getTotalWeightFromFilament(); if ((initial_weight === 0 || initial_weight === currentCalculatedFilamentWeight) && newFilamentWeight > 0) { form.setFieldValue("initial_weight", newFilamentWeight); } if ((spool_weight === 0 || spool_weight === (selectedFilament?.spool_weight ?? 0)) && newSpoolWeight > 0) { form.setFieldValue("spool_weight", newSpoolWeight); } }; const weightChange = (weight: number) => { setUsedWeight(weight); form.setFieldsValue({ used_weight: weight, }); }; const locations = useSpoolmanLocations(true); const [newLocation, setNewLocation] = useState(""); const allLocations = [...(locations.data || [])]; if (newLocation.trim() && !allLocations.includes(newLocation)) { allLocations.push(newLocation.trim()); } const [quantity, setQuantity] = useState(1); const incrementQty = () => { setQuantity(quantity + 1); }; const decrementQty = () => { setQuantity(quantity - 1); }; const getSpoolWeight = (): number => { return spoolWeightValue ?? selectedFilament?.spool_weight ?? 0; }; const getFilamentWeight = (): number => { return initialWeightValue ?? selectedFilament?.weight ?? 0; }; const getGrossWeight = (): number => { const net_weight = getFilamentWeight(); const spool_weight = getSpoolWeight(); return net_weight + spool_weight; }; const getTotalWeightFromFilament = (): number => { return (selectedFilament?.weight ?? 0) + (selectedFilament?.spool_weight ?? 0); }; const getMeasuredWeight = (): number => { const grossWeight = getGrossWeight(); return grossWeight - usedWeight; }; const getRemainingWeight = (): number => { const initial_weight = getFilamentWeight(); return initial_weight - usedWeight; }; const isMeasuredWeightEnabled = (): boolean => { if (!isRemainingWeightEnabled()) { return false; } const spool_weight = spoolWeightValue; return spool_weight || selectedFilament?.spool_weight ? true : false; }; const isRemainingWeightEnabled = (): boolean => { const initial_weight = initialWeightValue; if (initial_weight) { return true; } return selectedFilament?.weight ? true : false; }; React.useEffect(() => { if (weightToEnter >= WeightToEnter.measured_weight) { if (!isMeasuredWeightEnabled()) { setWeightToEnter(WeightToEnter.remaining_weight); return; } } if (weightToEnter >= WeightToEnter.remaining_weight) { if (!isRemainingWeightEnabled()) { setWeightToEnter(WeightToEnter.used_weight); return; } } }, [selectedFilament]); return ( ( <>
)} >
({ value: value ? dayjs(value) : undefined, })} > ({ value: value ? dayjs(value) : undefined, })} > ( <> {menu} setNewLocation(event.target.value)} /> )} loading={locations.isLoading} options={allLocations.map((item) => ({ label: item, value: item }))} />