Extra fields now finished for filaments
This commit is contained in:
@@ -1,11 +1,20 @@
|
||||
import React from "react";
|
||||
import { IResourceComponentsProps, useTranslate } from "@refinedev/core";
|
||||
import { HttpError, IResourceComponentsProps, useTranslate } from "@refinedev/core";
|
||||
import { Create, useForm, useSelect } from "@refinedev/antd";
|
||||
import { Form, Input, Select, InputNumber, ColorPicker, Button } from "antd";
|
||||
import TextArea from "antd/es/input/TextArea";
|
||||
import { numberFormatter, numberParser } from "../../utils/parsing";
|
||||
import { IVendor } from "../vendors/model";
|
||||
import { IFilament } from "./model";
|
||||
import { EntityType, FieldType, useGetFields } from "../../utils/queryFields";
|
||||
import { ExtraFieldFormItem, StringifiedExtras } from "../../components/extraFields";
|
||||
import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
// IFilamentParsedExtras is the same as IFilament, but with the extra field parsed into its real types
|
||||
type IFilamentParsedExtras = Omit<IFilament, "extra"> & { extra?: { [key: string]: unknown } };
|
||||
|
||||
interface CreateOrCloneProps {
|
||||
mode: "create" | "clone";
|
||||
@@ -13,10 +22,20 @@ interface CreateOrCloneProps {
|
||||
|
||||
export const FilamentCreate: React.FC<IResourceComponentsProps & CreateOrCloneProps> = (props) => {
|
||||
const t = useTranslate();
|
||||
const extraFields = useGetFields(EntityType.filament);
|
||||
|
||||
const { form, formProps, formLoading, onFinish, redirect } = useForm<IFilament>();
|
||||
const { form, formProps, formLoading, onFinish, redirect } = useForm<
|
||||
IFilament,
|
||||
HttpError,
|
||||
IFilamentParsedExtras,
|
||||
IFilamentParsedExtras
|
||||
>();
|
||||
|
||||
if (props.mode === "clone" && formProps.initialValues) {
|
||||
if (!formProps.initialValues) {
|
||||
formProps.initialValues = {};
|
||||
}
|
||||
|
||||
if (props.mode === "clone") {
|
||||
// Fix the vendor_id
|
||||
if (formProps.initialValues.vendor) {
|
||||
formProps.initialValues.vendor_id = formProps.initialValues.vendor.id;
|
||||
@@ -24,7 +43,7 @@ export const FilamentCreate: React.FC<IResourceComponentsProps & CreateOrClonePr
|
||||
}
|
||||
|
||||
const handleSubmit = async (redirectTo: "list" | "edit" | "create") => {
|
||||
const values = await form.validateFields();
|
||||
const values = StringifiedExtras(await form.validateFields());
|
||||
await onFinish(values);
|
||||
redirect(redirectTo, (values as IFilament).id);
|
||||
};
|
||||
@@ -34,6 +53,21 @@ export const FilamentCreate: React.FC<IResourceComponentsProps & CreateOrClonePr
|
||||
optionLabel: "name",
|
||||
});
|
||||
|
||||
// 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) {
|
||||
let parsedValue = JSON.parse(field.default_value as string);
|
||||
if (field.field_type === FieldType.datetime) {
|
||||
parsedValue = dayjs(parsedValue);
|
||||
}
|
||||
|
||||
form.setFieldsValue({ extra: { [field.key]: parsedValue } });
|
||||
}
|
||||
});
|
||||
}, [form, extraFields.data, formProps.initialValues]);
|
||||
|
||||
return (
|
||||
<Create
|
||||
title={props.mode === "create" ? t("filament.titles.create") : t("filament.titles.clone")}
|
||||
@@ -229,6 +263,9 @@ export const FilamentCreate: React.FC<IResourceComponentsProps & CreateOrClonePr
|
||||
>
|
||||
<TextArea maxLength={1024} />
|
||||
</Form.Item>
|
||||
{extraFields.data?.map((field, index) => (
|
||||
<ExtraFieldFormItem key={index} field={field} />
|
||||
))}
|
||||
</Form>
|
||||
</Create>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from "react";
|
||||
import { IResourceComponentsProps, useTranslate } from "@refinedev/core";
|
||||
import { HttpError, IResourceComponentsProps, useTranslate } from "@refinedev/core";
|
||||
import { Edit, useForm, useSelect } from "@refinedev/antd";
|
||||
import { Form, Input, DatePicker, Select, InputNumber, ColorPicker, message, Alert } from "antd";
|
||||
import dayjs from "dayjs";
|
||||
@@ -7,30 +7,62 @@ import TextArea from "antd/es/input/TextArea";
|
||||
import { numberFormatter, numberParser } from "../../utils/parsing";
|
||||
import { IVendor } from "../vendors/model";
|
||||
import { IFilament } from "./model";
|
||||
import { EntityType, useGetFields } from "../../utils/queryFields";
|
||||
import { ExtraFieldFormItem, StringifiedExtras } from "../../components/extraFields";
|
||||
import { ParsedExtras } from "../../components/extraFields";
|
||||
|
||||
// IFilamentParsedExtras is the same as IFilament, but with the extra field parsed into its real types
|
||||
type IFilamentParsedExtras = Omit<IFilament, "extra"> & { extra?: { [key: string]: unknown } };
|
||||
|
||||
/*
|
||||
The API returns the extra fields as JSON values, but we need to parse them into their real types
|
||||
in order for Ant design's form to work properly. ParsedExtras does this for us.
|
||||
We also need to stringify them again before sending them back to the API, which is done by overriding
|
||||
the form's onFinish method. Form.Item's normalize should do this, but it doesn't seem to work.
|
||||
*/
|
||||
|
||||
export const FilamentEdit: React.FC<IResourceComponentsProps> = () => {
|
||||
const t = useTranslate();
|
||||
const [messageApi, contextHolder] = message.useMessage();
|
||||
const [hasChanged, setHasChanged] = useState(false);
|
||||
const extraFields = useGetFields(EntityType.filament);
|
||||
|
||||
const { formProps, saveButtonProps } = useForm<IFilament>({
|
||||
const { formProps, saveButtonProps } = useForm<IFilament, HttpError, IFilamentParsedExtras, IFilamentParsedExtras>({
|
||||
liveMode: "manual",
|
||||
onLiveEvent() {
|
||||
// Warn the user if the filament has been updated since the form was opened
|
||||
messageApi.warning(t("filament.form.filament_updated"));
|
||||
setHasChanged(true);
|
||||
},
|
||||
queryOptions: {
|
||||
select(data) {
|
||||
return {
|
||||
data: ParsedExtras(data.data),
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Get vendor selection options
|
||||
const { selectProps } = useSelect<IVendor>({
|
||||
resource: "vendor",
|
||||
optionLabel: "name",
|
||||
});
|
||||
|
||||
// Add the vendor_id field to the form
|
||||
if (formProps.initialValues) {
|
||||
formProps.initialValues["vendor_id"] = formProps.initialValues["vendor"]?.id;
|
||||
}
|
||||
|
||||
// Override the form's onFinish method to stringify the extra fields
|
||||
const originalOnFinish = formProps.onFinish;
|
||||
formProps.onFinish = (allValues: IFilamentParsedExtras) => {
|
||||
if (allValues !== undefined && allValues !== null) {
|
||||
allValues = StringifiedExtras(allValues);
|
||||
}
|
||||
originalOnFinish?.(allValues);
|
||||
};
|
||||
|
||||
return (
|
||||
<Edit saveButtonProps={saveButtonProps}>
|
||||
{contextHolder}
|
||||
@@ -246,6 +278,9 @@ export const FilamentEdit: React.FC<IResourceComponentsProps> = () => {
|
||||
>
|
||||
<TextArea maxLength={1024} />
|
||||
</Form.Item>
|
||||
{extraFields.data?.map((field, index) => (
|
||||
<ExtraFieldFormItem key={index} field={field} />
|
||||
))}
|
||||
</Form>
|
||||
{hasChanged && <Alert description={t("filament.form.filament_updated")} type="warning" showIcon />}
|
||||
</Edit>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
SortedColumn,
|
||||
SpoolIconColumn,
|
||||
ActionsColumn,
|
||||
CustomFieldColumn,
|
||||
} from "../../components/column";
|
||||
import {
|
||||
useSpoolmanArticleNumbers,
|
||||
@@ -24,9 +25,13 @@ import {
|
||||
} from "../../components/otherModels";
|
||||
import { useLiveify } from "../../components/liveify";
|
||||
import { removeUndefined } from "../../utils/filtering";
|
||||
import { EntityType, useGetFields } from "../../utils/queryFields";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
dayjs.extend(utc);
|
||||
|
||||
// Extra is a key-value dict
|
||||
|
||||
interface IFilamentCollapsed extends Omit<IFilament, "vendor"> {
|
||||
"vendor.name": string | null;
|
||||
}
|
||||
@@ -71,6 +76,10 @@ const defaultColumns = allColumns.filter(
|
||||
export const FilamentList: React.FC<IResourceComponentsProps> = () => {
|
||||
const t = useTranslate();
|
||||
const invalidate = useInvalidate();
|
||||
const navigate = useNavigate();
|
||||
const extraFields = useGetFields(EntityType.filament);
|
||||
|
||||
const allColumnsWithExtraFields = [...allColumns, ...(extraFields.data?.map((field) => "extra." + field.key) ?? [])];
|
||||
|
||||
// Load initial state
|
||||
const initialState = useInitialTableState(namespace);
|
||||
@@ -145,6 +154,15 @@ export const FilamentList: React.FC<IResourceComponentsProps> = () => {
|
||||
{ name: t("buttons.clone"), icon: <PlusSquareOutlined />, link: cloneUrl("filament", record.id) },
|
||||
];
|
||||
|
||||
const commonProps = {
|
||||
t,
|
||||
navigate,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
};
|
||||
|
||||
return (
|
||||
<List
|
||||
headerButtons={({ defaultButtons }) => (
|
||||
@@ -163,10 +181,20 @@ export const FilamentList: React.FC<IResourceComponentsProps> = () => {
|
||||
<Dropdown
|
||||
trigger={["click"]}
|
||||
menu={{
|
||||
items: allColumns.map((column_id) => ({
|
||||
key: column_id,
|
||||
label: t(translateColumnI18nKey(column_id)),
|
||||
})),
|
||||
items: allColumnsWithExtraFields.map((column_id) => {
|
||||
if (column_id.indexOf("extra.") === 0) {
|
||||
const extraField = extraFields.data?.find((field) => "extra." + field.key === column_id);
|
||||
return {
|
||||
key: column_id,
|
||||
label: extraField?.name ?? column_id,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
key: column_id,
|
||||
label: t(translateColumnI18nKey(column_id)),
|
||||
};
|
||||
}),
|
||||
selectedKeys: showColumns,
|
||||
selectable: true,
|
||||
multiple: true,
|
||||
@@ -195,129 +223,107 @@ export const FilamentList: React.FC<IResourceComponentsProps> = () => {
|
||||
rowKey="id"
|
||||
columns={removeUndefined([
|
||||
SortedColumn({
|
||||
...commonProps,
|
||||
id: "id",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 70,
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
...commonProps,
|
||||
id: "vendor.name",
|
||||
i18nkey: "filament.fields.vendor_name",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanVendors(),
|
||||
}),
|
||||
SpoolIconColumn({
|
||||
...commonProps,
|
||||
id: "name",
|
||||
i18ncat: "filament",
|
||||
color: (record: IFilamentCollapsed) => record.color_hex,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanFilamentNames(),
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
...commonProps,
|
||||
id: "material",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanMaterials(),
|
||||
width: 110,
|
||||
}),
|
||||
SortedColumn({
|
||||
...commonProps,
|
||||
id: "price",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 80,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "density",
|
||||
i18ncat: "filament",
|
||||
unit: "g/cm³",
|
||||
decimals: 2,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 2,
|
||||
width: 100,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "diameter",
|
||||
i18ncat: "filament",
|
||||
unit: "mm",
|
||||
decimals: 2,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 2,
|
||||
width: 100,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "weight",
|
||||
i18ncat: "filament",
|
||||
unit: "g",
|
||||
decimals: 1,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 1,
|
||||
width: 100,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "spool_weight",
|
||||
i18ncat: "filament",
|
||||
unit: "g",
|
||||
decimals: 1,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 1,
|
||||
width: 100,
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
...commonProps,
|
||||
id: "article_number",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanArticleNumbers(),
|
||||
width: 130,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "settings_extruder_temp",
|
||||
i18ncat: "filament",
|
||||
unit: "°C",
|
||||
decimals: 0,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 0,
|
||||
width: 100,
|
||||
}),
|
||||
NumberColumn({
|
||||
...commonProps,
|
||||
id: "settings_bed_temp",
|
||||
i18ncat: "filament",
|
||||
unit: "°C",
|
||||
decimals: 0,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
maxDecimals: 0,
|
||||
width: 100,
|
||||
}),
|
||||
DateColumn({
|
||||
...commonProps,
|
||||
id: "registered",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
}),
|
||||
...(extraFields.data?.map((field) => {
|
||||
return CustomFieldColumn({
|
||||
...commonProps,
|
||||
field,
|
||||
});
|
||||
}) ?? []),
|
||||
RichColumn({
|
||||
...commonProps,
|
||||
id: "comment",
|
||||
i18ncat: "filament",
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 150,
|
||||
}),
|
||||
ActionsColumn(actions),
|
||||
|
||||
@@ -16,4 +16,5 @@ export interface IFilament {
|
||||
settings_extruder_temp?: number;
|
||||
settings_bed_temp?: number;
|
||||
color_hex?: string;
|
||||
extra: { [key: string]: string };
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import utc from "dayjs/plugin/utc";
|
||||
import { IFilament } from "./model";
|
||||
import { enrichText } from "../../utils/parsing";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { EntityType, useGetFields } from "../../utils/queryFields";
|
||||
import { ExtraFieldDisplay } from "../../components/extraFields";
|
||||
dayjs.extend(utc);
|
||||
|
||||
const { Title } = Typography;
|
||||
@@ -15,6 +17,7 @@ const { Title } = Typography;
|
||||
export const FilamentShow: React.FC<IResourceComponentsProps> = () => {
|
||||
const t = useTranslate();
|
||||
const navigate = useNavigate();
|
||||
const extraFields = useGetFields(EntityType.filament);
|
||||
const { queryResult } = useShow<IFilament>({
|
||||
liveMode: "auto",
|
||||
});
|
||||
@@ -74,8 +77,6 @@ export const FilamentShow: React.FC<IResourceComponentsProps> = () => {
|
||||
/>
|
||||
<Title level={5}>{t("filament.fields.name")}</Title>
|
||||
<TextField value={record?.name} />
|
||||
{/* <Title level={5}>{t("filament.fields.id")}</Title>
|
||||
{vendorIsLoading ? <>Loading...</> : <>{vendorData?.data?.id}</>} */}
|
||||
<Title level={5}>{t("filament.fields.color_hex")}</Title>
|
||||
<TextField value={record?.color_hex} />
|
||||
<Title level={5}>{t("filament.fields.material")}</Title>
|
||||
@@ -134,6 +135,9 @@ export const FilamentShow: React.FC<IResourceComponentsProps> = () => {
|
||||
<TextField value={record?.article_number} />
|
||||
<Title level={5}>{t("filament.fields.comment")}</Title>
|
||||
<TextField value={enrichText(record?.comment)} />
|
||||
{extraFields?.data?.map((field, index) => (
|
||||
<ExtraFieldDisplay key={index} field={field} value={record?.extra[field.key]} />
|
||||
))}
|
||||
</Show>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
DatePicker,
|
||||
Flex,
|
||||
Form,
|
||||
FormInstance,
|
||||
@@ -13,7 +12,7 @@ import {
|
||||
Table,
|
||||
message,
|
||||
} from "antd";
|
||||
import { EntityType, Field, FieldType, useDeleteField, useGetFields, useSetField } from "./queryFields";
|
||||
import { EntityType, Field, FieldType, useDeleteField, useGetFields, useSetField } from "../../utils/queryFields";
|
||||
import { useTranslate } from "@refinedev/core";
|
||||
import { useState } from "react";
|
||||
import { ColumnType } from "antd/es/table";
|
||||
@@ -25,13 +24,15 @@ import dayjs from "dayjs";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import advancedFormat from "dayjs/plugin/advancedFormat";
|
||||
import { DateTimePicker } from "../../components/dateTimePicker";
|
||||
import { InputNumberRange } from "../../components/inputNumberRange";
|
||||
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
dayjs.extend(advancedFormat);
|
||||
|
||||
// Localized date time format with timezone
|
||||
const dateTimeFormat = "YYYY-MM-DD HH:mm:ss z";
|
||||
const dateTimeFormat = "YYYY-MM-DD HH:mm:ss";
|
||||
|
||||
interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
|
||||
record: FieldHolder;
|
||||
@@ -194,19 +195,19 @@ const EditableCell: React.FC<EditableCellProps> = ({ record, editing, dataIndex,
|
||||
type: "number",
|
||||
});
|
||||
} else if (fieldType === FieldType.integer_range) {
|
||||
inputNode = <Input placeholder="Example: 180 - 210" />;
|
||||
inputNode = <InputNumberRange precision={0} />;
|
||||
rules.push({
|
||||
type: "string",
|
||||
pattern: /^-?\d+\s*-\s*-?\d+$/,
|
||||
type: "array",
|
||||
len: 2,
|
||||
});
|
||||
} else if (fieldType === FieldType.float_range) {
|
||||
inputNode = <Input placeholder="Example: 1.34 - 2.90" />;
|
||||
inputNode = <InputNumberRange precision={3} />;
|
||||
rules.push({
|
||||
type: "string",
|
||||
pattern: /^-?\d+([.,]\d+)?\s*-\s*-?\d+([.,]\d+)?$/,
|
||||
type: "array",
|
||||
len: 2,
|
||||
});
|
||||
} else if (fieldType === FieldType.datetime) {
|
||||
inputNode = <DatePicker format={dateTimeFormat} showTime={{ use12Hours: false }} />;
|
||||
inputNode = <DateTimePicker />;
|
||||
} else if (fieldType === FieldType.choice) {
|
||||
inputNode = (
|
||||
<Select
|
||||
@@ -300,23 +301,12 @@ export function ExtraFieldsSettings() {
|
||||
|
||||
const edit = (record: Partial<Field> & { key: React.Key }) => {
|
||||
const values = { ...record };
|
||||
console.log(values);
|
||||
|
||||
if (values.default_value && typeof values.default_value === "string") {
|
||||
const def = JSON.parse(values.default_value);
|
||||
if (Array.isArray(def)) {
|
||||
if (values.field_type === FieldType.choice) {
|
||||
values.default_value = def.join(", ");
|
||||
} else if (values.field_type === FieldType.integer_range || values.field_type === FieldType.float_range) {
|
||||
values.default_value = `${def[0]} - ${def[1]}`;
|
||||
} else {
|
||||
values.default_value = undefined;
|
||||
}
|
||||
} else if (values.field_type === FieldType.datetime) {
|
||||
// Parse as dayjs
|
||||
values.default_value = dayjs(def);
|
||||
} else if (values.field_type === FieldType.boolean) {
|
||||
if (values.field_type === FieldType.boolean) {
|
||||
values.default_value = def ? true : false;
|
||||
} else if (values.field_type === FieldType.text) {
|
||||
} else {
|
||||
values.default_value = def;
|
||||
}
|
||||
} else {
|
||||
@@ -383,24 +373,16 @@ export function ExtraFieldsSettings() {
|
||||
// Do some value conversions
|
||||
try {
|
||||
// Convert float and integer range to array using the validation regex
|
||||
if (updatedField.field_type === FieldType.float_range && typeof updatedField.default_value === "string") {
|
||||
const pattern = /^(-?\d+(?:[.,]\d+)?)\s*-\s*(-?\d+(?:[.,]\d+)?)$/;
|
||||
const matches = updatedField.default_value.match(pattern);
|
||||
if (matches) {
|
||||
const val1 = parseFloat(matches[1].replace(",", "."));
|
||||
const val2 = parseFloat(matches[2].replace(",", "."));
|
||||
updatedField.default_value = JSON.stringify([Math.min(val1, val2), Math.max(val1, val2)]);
|
||||
}
|
||||
} else if (
|
||||
updatedField.field_type === FieldType.integer_range &&
|
||||
typeof updatedField.default_value === "string"
|
||||
if (
|
||||
(updatedField.field_type === FieldType.float_range || updatedField.field_type === FieldType.integer_range) &&
|
||||
updatedField.default_value !== undefined
|
||||
) {
|
||||
const pattern = /^(-?\d+)\s*-\s*(-?\d+)$/;
|
||||
const matches = updatedField.default_value.match(pattern);
|
||||
if (matches) {
|
||||
const val1 = parseInt(matches[1]);
|
||||
const val2 = parseInt(matches[2]);
|
||||
updatedField.default_value = JSON.stringify([Math.min(val1, val2), Math.max(val1, val2)]);
|
||||
if (Array.isArray(updatedField.default_value)) {
|
||||
const val1 = updatedField.default_value[0];
|
||||
const val2 = updatedField.default_value[1];
|
||||
updatedField.default_value = JSON.stringify([val1, val2]);
|
||||
} else {
|
||||
console.warn("Invalid default_value for range", updatedField.default_value);
|
||||
}
|
||||
} else {
|
||||
// Just stringify all other values
|
||||
@@ -441,8 +423,6 @@ export function ExtraFieldsSettings() {
|
||||
|
||||
// Submit it!
|
||||
try {
|
||||
console.log(updatedField);
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
setField.reset();
|
||||
@@ -511,7 +491,7 @@ export function ExtraFieldsSettings() {
|
||||
(Array.isArray(val) && record.field.field_type === FieldType.integer_range) ||
|
||||
record.field.field_type === FieldType.float_range
|
||||
) {
|
||||
return `${val[0]} - ${val[1]}`;
|
||||
return `${val[0]} \u2013 ${val[1]}`;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from "react";
|
||||
import { useTranslate } from "@refinedev/core";
|
||||
import { Button, Form, Input, message } from "antd";
|
||||
import { useGetSettings, useSetSetting } from "./querySettings";
|
||||
import { useGetSettings, useSetSetting } from "../../utils/querySettings";
|
||||
|
||||
export function GeneralSettings() {
|
||||
const settings = useGetSettings();
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export enum FieldType {
|
||||
text = "text",
|
||||
integer = "integer",
|
||||
integer_range = "integer_range",
|
||||
float = "float",
|
||||
float_range = "float_range",
|
||||
datetime = "datetime",
|
||||
boolean = "boolean",
|
||||
choice = "choice",
|
||||
}
|
||||
|
||||
export enum EntityType {
|
||||
vendor = "vendor",
|
||||
filament = "filament",
|
||||
spool = "spool",
|
||||
}
|
||||
|
||||
export interface FieldParameters {
|
||||
name: string;
|
||||
order: number;
|
||||
unit?: string;
|
||||
field_type: FieldType;
|
||||
default_value?: string | boolean | dayjs.Dayjs;
|
||||
choices?: string[];
|
||||
multi_choice?: boolean;
|
||||
}
|
||||
|
||||
export interface Field extends FieldParameters {
|
||||
key: string;
|
||||
entity_type: EntityType;
|
||||
}
|
||||
|
||||
export function useGetFields(entity_type: EntityType) {
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useQuery<Field[]>({
|
||||
queryKey: ["fields", entity_type],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`${apiEndpoint}/field/${entity_type}`);
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetField(entity_type: EntityType) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useMutation<Field[], unknown, { key: string; params: FieldParameters }, { previousFields?: Field[] }>({
|
||||
mutationFn: async ({ key, params }) => {
|
||||
const response = await fetch(`${apiEndpoint}/field/${entity_type}/${key}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(params),
|
||||
});
|
||||
|
||||
// Throw error if response is not ok
|
||||
if (!response.ok) {
|
||||
throw new Error((await response.json()).message);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
onMutate: async ({ key, params }) => {
|
||||
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
|
||||
await queryClient.cancelQueries(["fields", entity_type]);
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousFields = queryClient.getQueryData<Field[]>(["fields", entity_type]);
|
||||
|
||||
// Optimistically update to the new value
|
||||
queryClient.setQueryData<Field[]>(["fields", entity_type], (old) => {
|
||||
if (!old) {
|
||||
return [
|
||||
{
|
||||
key: key,
|
||||
entity_type: entity_type,
|
||||
...params,
|
||||
},
|
||||
];
|
||||
}
|
||||
return old.map((field) => {
|
||||
if (field.key === key) {
|
||||
return { ...field, ...params };
|
||||
}
|
||||
return field;
|
||||
});
|
||||
});
|
||||
|
||||
// Return a context object with the snapshotted value
|
||||
return { previousFields };
|
||||
},
|
||||
onError: (_err, _newFields, context) => {
|
||||
// Rollback to the previous value
|
||||
if (context?.previousFields) {
|
||||
queryClient.setQueryData(["fields", entity_type], context.previousFields);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
// Invalidate and refetch
|
||||
queryClient.invalidateQueries(["fields", entity_type]);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteField(entity_type: EntityType) {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useMutation<Field[], unknown, string>({
|
||||
mutationFn: async (key) => {
|
||||
const response = await fetch(`${apiEndpoint}/field/${entity_type}/${key}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
// Throw error if response is not ok
|
||||
if (!response.ok) {
|
||||
throw new Error((await response.json()).message);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Invalidate and refetch
|
||||
queryClient.invalidateQueries(["fields", entity_type]);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
interface SettingResponseValue {
|
||||
value: string;
|
||||
is_set: boolean;
|
||||
type: string;
|
||||
}
|
||||
|
||||
interface SettingsResponse {
|
||||
[key: string]: SettingResponseValue;
|
||||
}
|
||||
|
||||
export function useGetSettings() {
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useQuery<SettingsResponse>({
|
||||
queryKey: ["settings"],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`${apiEndpoint}/setting`);
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useGetSetting(key: string) {
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useQuery<SettingResponseValue>({
|
||||
queryKey: ["settings", key],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`${apiEndpoint}/setting/${key}`);
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSetSetting() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const apiEndpoint = import.meta.env.VITE_APIURL;
|
||||
return useMutation<SettingResponseValue, unknown, { key: string; value: unknown }>({
|
||||
mutationFn: async ({ key, value }) => {
|
||||
const response = await fetch(`${apiEndpoint}/setting/${key}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(value),
|
||||
});
|
||||
|
||||
// Throw error if response is not ok
|
||||
if (!response.ok) {
|
||||
throw new Error((await response.json()).message);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
},
|
||||
onSuccess: (_data, { key }) => {
|
||||
// Invalidate and refetch
|
||||
queryClient.invalidateQueries(["settings", key]);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -52,7 +52,7 @@ function collapseSpool(element: ISpool): ISpoolCollapsed {
|
||||
} else {
|
||||
filament_name = element.filament.name ?? element.filament.id.toString();
|
||||
}
|
||||
if (!element.price){
|
||||
if (!element.price) {
|
||||
element.price = element.filament.price;
|
||||
}
|
||||
return {
|
||||
@@ -306,6 +306,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
tableState,
|
||||
dataId: "filament.id",
|
||||
filterValueQuery: useSpoolmanFilamentFilter(),
|
||||
sorter: true,
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
id: "filament.material",
|
||||
@@ -315,6 +316,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanMaterials(),
|
||||
width: 120,
|
||||
sorter: true,
|
||||
}),
|
||||
SortedColumn({
|
||||
id: "price",
|
||||
@@ -328,43 +330,47 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
id: "used_weight",
|
||||
i18ncat: "spool",
|
||||
unit: "g",
|
||||
decimals: 1,
|
||||
maxDecimals: 1,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 110,
|
||||
sorter: true,
|
||||
}),
|
||||
NumberColumn({
|
||||
id: "remaining_weight",
|
||||
i18ncat: "spool",
|
||||
unit: "g",
|
||||
decimals: 1,
|
||||
maxDecimals: 1,
|
||||
defaultText: t("unknown"),
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 110,
|
||||
sorter: true,
|
||||
}),
|
||||
NumberColumn({
|
||||
id: "used_length",
|
||||
i18ncat: "spool",
|
||||
unit: "mm",
|
||||
decimals: 1,
|
||||
maxDecimals: 1,
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 120,
|
||||
sorter: true,
|
||||
}),
|
||||
NumberColumn({
|
||||
id: "remaining_length",
|
||||
i18ncat: "spool",
|
||||
unit: "mm",
|
||||
decimals: 1,
|
||||
maxDecimals: 1,
|
||||
defaultText: t("unknown"),
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 120,
|
||||
sorter: true,
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
id: "location",
|
||||
@@ -374,6 +380,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanLocations(),
|
||||
width: 120,
|
||||
sorter: true,
|
||||
}),
|
||||
FilteredQueryColumn({
|
||||
id: "lot_nr",
|
||||
@@ -383,6 +390,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
tableState,
|
||||
filterValueQuery: useSpoolmanLotNumbers(),
|
||||
width: 120,
|
||||
sorter: true,
|
||||
}),
|
||||
DateColumn({
|
||||
id: "first_used",
|
||||
@@ -390,6 +398,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
}),
|
||||
DateColumn({
|
||||
id: "last_used",
|
||||
@@ -397,6 +406,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
}),
|
||||
DateColumn({
|
||||
id: "registered",
|
||||
@@ -404,6 +414,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
}),
|
||||
RichColumn({
|
||||
id: "comment",
|
||||
@@ -412,6 +423,7 @@ export const SpoolList: React.FC<IResourceComponentsProps> = () => {
|
||||
dataSource,
|
||||
tableState,
|
||||
width: 150,
|
||||
sorter: true,
|
||||
}),
|
||||
ActionsColumn(actions),
|
||||
])}
|
||||
|
||||
2
client/src/pages/vendors/list.tsx
vendored
2
client/src/pages/vendors/list.tsx
vendored
@@ -152,6 +152,7 @@ export const VendorList: React.FC<IResourceComponentsProps> = () => {
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
}),
|
||||
RichColumn({
|
||||
id: "comment",
|
||||
@@ -159,6 +160,7 @@ export const VendorList: React.FC<IResourceComponentsProps> = () => {
|
||||
actions,
|
||||
dataSource,
|
||||
tableState,
|
||||
sorter: true,
|
||||
}),
|
||||
ActionsColumn<IVendor>(actions),
|
||||
])}
|
||||
|
||||
Reference in New Issue
Block a user