add prettier code formater

This commit is contained in:
2026-02-15 11:32:30 +01:00
parent 11b3a926d2
commit 627ddfc464
61 changed files with 7471 additions and 7312 deletions

View File

@@ -1,51 +1,47 @@
module.exports = { module.exports = {
root: true, root: true,
parser: '@typescript-eslint/parser', parser: "@typescript-eslint/parser",
parserOptions: { parserOptions: {
ecmaVersion: 'latest', ecmaVersion: "latest",
sourceType: 'module', sourceType: "module",
ecmaFeatures: { ecmaFeatures: {
jsx: true, jsx: true,
}, },
project: './tsconfig.json', // Required for type-aware rules project: "./tsconfig.json", // Required for type-aware rules
}, },
env: { env: {
browser: true, browser: true,
es2021: true, es2021: true,
node: true, node: true,
}, },
plugins: [ plugins: ["react", "react-hooks", "@typescript-eslint", "jsx-a11y", "import", "unused-imports"],
'react',
'react-hooks',
'@typescript-eslint',
'jsx-a11y',
'import',
'unused-imports',
],
extends: [ extends: [
'eslint:recommended', "eslint:recommended",
'plugin:react/recommended', "plugin:react/recommended",
'plugin:react-hooks/recommended', "plugin:react-hooks/recommended",
'plugin:@typescript-eslint/recommended', "plugin:@typescript-eslint/recommended",
'plugin:@typescript-eslint/recommended-requiring-type-checking', "plugin:@typescript-eslint/recommended-requiring-type-checking",
'plugin:jsx-a11y/recommended', "plugin:jsx-a11y/recommended",
'plugin:import/errors', "plugin:import/errors",
'plugin:import/warnings', "plugin:import/warnings",
'plugin:import/typescript', "plugin:import/typescript",
'prettier', "prettier",
], ],
rules: { rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }], "@typescript-eslint/no-unused-vars": [
'@typescript-eslint/no-explicit-any': 'error', "error",
'@typescript-eslint/explicit-function-return-type': ['error', { allowExpressions: false }], { argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
'@typescript-eslint/strict-boolean-expressions': 'error', ],
'@typescript-eslint/no-floating-promises': 'error', "@typescript-eslint/no-explicit-any": "error",
'@typescript-eslint/consistent-type-imports': ['error', { prefer: 'type-imports' }], "@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: false }],
'@typescript-eslint/no-misused-promises': 'error', "@typescript-eslint/strict-boolean-expressions": "error",
'@typescript-eslint/prefer-readonly': 'error', "@typescript-eslint/no-floating-promises": "error",
'@typescript-eslint/explicit-module-boundary-types': 'error', "@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports" }],
'@typescript-eslint/typedef': [ "@typescript-eslint/no-misused-promises": "error",
'error', "@typescript-eslint/prefer-readonly": "error",
"@typescript-eslint/explicit-module-boundary-types": "error",
"@typescript-eslint/typedef": [
"error",
{ {
arrayDestructuring: true, arrayDestructuring: true,
arrowParameter: true, arrowParameter: true,
@@ -58,46 +54,49 @@ module.exports = {
}, },
], ],
'react/react-in-jsx-scope': 'off', "react/react-in-jsx-scope": "off",
'react/prop-types': 'off', "react/prop-types": "off",
'react/jsx-uses-react': 'off', "react/jsx-uses-react": "off",
'react/jsx-uses-vars': 'error', "react/jsx-uses-vars": "error",
'react/jsx-no-useless-fragment': 'error', "react/jsx-no-useless-fragment": "error",
'react/self-closing-comp': 'error', "react/self-closing-comp": "error",
'react-hooks/rules-of-hooks': 'error', "react-hooks/rules-of-hooks": "error",
'react-hooks/exhaustive-deps': 'error', "react-hooks/exhaustive-deps": "error",
'jsx-a11y/no-noninteractive-element-interactions': 'error', "jsx-a11y/no-noninteractive-element-interactions": "error",
'jsx-a11y/anchor-is-valid': 'error', "jsx-a11y/anchor-is-valid": "error",
'jsx-a11y/click-events-have-key-events': 'error', "jsx-a11y/click-events-have-key-events": "error",
'import/order': [ "import/order": [
'error', "error",
{ {
groups: [['builtin', 'external'], ['internal', 'parent', 'sibling', 'index']], groups: [
'newlines-between': 'always', ["builtin", "external"],
alphabetize: { order: 'asc', caseInsensitive: true }, ["internal", "parent", "sibling", "index"],
],
"newlines-between": "always",
alphabetize: { order: "asc", caseInsensitive: true },
}, },
], ],
'import/no-unresolved': 'error', "import/no-unresolved": "error",
'import/no-duplicates': 'error', "import/no-duplicates": "error",
'unused-imports/no-unused-imports-ts': 'error', "unused-imports/no-unused-imports-ts": "error",
'no-console': ['warn', { allow: ['warn', 'error'] }], "no-console": ["warn", { allow: ["warn", "error"] }],
'no-debugger': 'error', "no-debugger": "error",
'eqeqeq': ['error', 'always'], eqeqeq: ["error", "always"],
'curly': 'error', curly: "error",
'semi': ['error', 'always'], semi: ["error", "always"],
'quotes': ['error', 'single', { avoidEscape: true }], quotes: ["error", "single", { avoidEscape: true }],
'prefer-const': 'error', "prefer-const": "error",
'no-var': 'error', "no-var": "error",
}, },
settings: { settings: {
react: { react: {
version: 'detect', version: "detect",
}, },
'import/resolver': { "import/resolver": {
typescript: {}, typescript: {},
}, },
}, },

8
frontend/.prettierignore Normal file
View File

@@ -0,0 +1,8 @@
node_modules
dist
build
coverage
.next
out
public
*.lock

13
frontend/.prettierrc Normal file
View File

@@ -0,0 +1,13 @@
{
"semi": true,
"singleQuote": false,
"jsxSingleQuote": false,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always",
"endOfLine": "lf"
}

View File

@@ -17,9 +17,9 @@ If you are developing a production application, we recommend updating the config
```js ```js
export default defineConfig([ export default defineConfig([
globalIgnores(['dist']), globalIgnores(["dist"]),
{ {
files: ['**/*.{ts,tsx}'], files: ["**/*.{ts,tsx}"],
extends: [ extends: [
// Other configs... // Other configs...
@@ -34,40 +34,40 @@ export default defineConfig([
], ],
languageOptions: { languageOptions: {
parserOptions: { parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'], project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname, tsconfigRootDir: import.meta.dirname,
}, },
// other options... // other options...
}, },
}, },
]) ]);
``` ```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js ```js
// eslint.config.js // eslint.config.js
import reactX from 'eslint-plugin-react-x' import reactX from "eslint-plugin-react-x";
import reactDom from 'eslint-plugin-react-dom' import reactDom from "eslint-plugin-react-dom";
export default defineConfig([ export default defineConfig([
globalIgnores(['dist']), globalIgnores(["dist"]),
{ {
files: ['**/*.{ts,tsx}'], files: ["**/*.{ts,tsx}"],
extends: [ extends: [
// Other configs... // Other configs...
// Enable lint rules for React // Enable lint rules for React
reactX.configs['recommended-typescript'], reactX.configs["recommended-typescript"],
// Enable lint rules for React DOM // Enable lint rules for React DOM
reactDom.configs.recommended, reactDom.configs.recommended,
], ],
languageOptions: { languageOptions: {
parserOptions: { parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'], project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname, tsconfigRootDir: import.meta.dirname,
}, },
// other options... // other options...
}, },
}, },
]) ]);
``` ```

View File

@@ -1,14 +1,14 @@
import js from '@eslint/js' import js from "@eslint/js";
import globals from 'globals' import globals from "globals";
import reactHooks from 'eslint-plugin-react-hooks' import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from 'eslint-plugin-react-refresh' import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from 'typescript-eslint' import tseslint from "typescript-eslint";
import { defineConfig, globalIgnores } from 'eslint/config' import { defineConfig, globalIgnores } from "eslint/config";
export default defineConfig([ export default defineConfig([
globalIgnores(['dist']), globalIgnores(["dist"]),
{ {
files: ['**/*.{ts,tsx}'], files: ["**/*.{ts,tsx}"],
extends: [ extends: [
js.configs.recommended, js.configs.recommended,
tseslint.configs.recommended, tseslint.configs.recommended,
@@ -20,4 +20,4 @@ export default defineConfig([
globals: globals.browser, globals: globals.browser,
}, },
}, },
]) ]);

View File

@@ -41,6 +41,7 @@
"postcss": "^8.5.6", "postcss": "^8.5.6",
"postcss-preset-mantine": "^1.18.0", "postcss-preset-mantine": "^1.18.0",
"postcss-simple-vars": "^7.0.1", "postcss-simple-vars": "^7.0.1",
"prettier": "3.8.1",
"typescript": "~5.9.3", "typescript": "~5.9.3",
"typescript-eslint": "^8.48.0", "typescript-eslint": "^8.48.0",
"vite": "^7.3.1" "vite": "^7.3.1"
@@ -3332,6 +3333,22 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/prettier": {
"version": "3.8.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz",
"integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prop-types": { "node_modules/prop-types": {
"version": "15.8.1", "version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",

View File

@@ -7,6 +7,7 @@
"dev": "vite", "dev": "vite",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"format": "prettier . --write",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@@ -43,6 +44,7 @@
"postcss": "^8.5.6", "postcss": "^8.5.6",
"postcss-preset-mantine": "^1.18.0", "postcss-preset-mantine": "^1.18.0",
"postcss-simple-vars": "^7.0.1", "postcss-simple-vars": "^7.0.1",
"prettier": "3.8.1",
"typescript": "~5.9.3", "typescript": "~5.9.3",
"typescript-eslint": "^8.48.0", "typescript-eslint": "^8.48.0",
"vite": "^7.3.1" "vite": "^7.3.1"

View File

@@ -1,13 +1,13 @@
module.exports = { module.exports = {
plugins: { plugins: {
'postcss-preset-mantine': {}, "postcss-preset-mantine": {},
'postcss-simple-vars': { "postcss-simple-vars": {
variables: { variables: {
'mantine-breakpoint-xs': '36em', "mantine-breakpoint-xs": "36em",
'mantine-breakpoint-sm': '48em', "mantine-breakpoint-sm": "48em",
'mantine-breakpoint-md': '62em', "mantine-breakpoint-md": "62em",
'mantine-breakpoint-lg': '75em', "mantine-breakpoint-lg": "75em",
'mantine-breakpoint-xl': '88em', "mantine-breakpoint-xl": "88em",
}, },
}, },
}, },

View File

@@ -1,7 +1,3 @@
export function Footer() { export function Footer() {
return ( return <footer></footer>;
<footer>
</footer>
);
} }

View File

@@ -4,26 +4,18 @@ import type { Form } from "@/services/resources/forms";
export type FormCardProps = { export type FormCardProps = {
form: Form; form: Form;
} };
export function FormCard({ form }: FormCardProps) { export function FormCard({ form }: FormCardProps) {
return ( return (
<Paper <Paper shadow="xl" p="xl" miw={{ base: "100vw", md: "25vw", lg: "20vw" }}>
shadow="xl"
p="xl"
miw={{base: "100vw", md: "25vw", lg:"20vw"}}
>
<Box <Box
component={Link} component={Link}
to={`/form/${form.id}`} to={`/form/${form.id}`}
style={{ textDecoration: "none", color: "black" }} style={{ textDecoration: "none", color: "black" }}
> >
<Group justify="space-between" wrap="nowrap"> <Group justify="space-between" wrap="nowrap">
<Title <Title order={3} textWrap="wrap" lineClamp={1}>
order={3}
textWrap="wrap"
lineClamp={1}
>
{form.name} {form.name}
</Title> </Title>
<Badge>{form.season}</Badge> <Badge>{form.season}</Badge>
@@ -34,6 +26,5 @@ export function FormCard({form}: FormCardProps) {
</Group> </Group>
</Box> </Box>
</Paper> </Paper>
); );
} }

View File

@@ -7,19 +7,19 @@ export type FilterFormsProps = {
productors: string[]; productors: string[];
filters: URLSearchParams; filters: URLSearchParams;
onFilterChange: (values: string[], filter: string) => void; onFilterChange: (values: string[], filter: string) => void;
} };
export default function FilterForms({ export default function FilterForms({
seasons, seasons,
productors, productors,
filters, filters,
onFilterChange onFilterChange,
}: FilterFormsProps) { }: FilterFormsProps) {
const defaultProductors = useMemo(() => { const defaultProductors = useMemo(() => {
return filters.getAll("productors") return filters.getAll("productors");
}, [filters]); }, [filters]);
const defaultSeasons = useMemo(() => { const defaultSeasons = useMemo(() => {
return filters.getAll("seasons") return filters.getAll("seasons");
}, [filters]); }, [filters]);
return ( return (
@@ -30,7 +30,7 @@ export default function FilterForms({
data={seasons} data={seasons}
defaultValue={defaultSeasons} defaultValue={defaultSeasons}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'seasons') onFilterChange(values, "seasons");
}} }}
clearable clearable
/> />
@@ -40,7 +40,7 @@ export default function FilterForms({
data={productors} data={productors}
defaultValue={defaultProductors} defaultValue={defaultProductors}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'productors') onFilterChange(values, "productors");
}} }}
clearable clearable
/> />

View File

@@ -1,4 +1,12 @@
import { Button, Group, Modal, NumberInput, Select, TextInput, type ModalBaseProps } from "@mantine/core"; import {
Button,
Group,
Modal,
NumberInput,
Select,
TextInput,
type ModalBaseProps,
} from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { DatePickerInput } from "@mantine/dates"; import { DatePickerInput } from "@mantine/dates";
import { IconCancel, IconEdit, IconPlus } from "@tabler/icons-react"; import { IconCancel, IconEdit, IconPlus } from "@tabler/icons-react";
@@ -10,14 +18,9 @@ import type { Form, FormInputs } from "@/services/resources/forms";
export type FormModalProps = ModalBaseProps & { export type FormModalProps = ModalBaseProps & {
currentForm?: Form; currentForm?: Form;
handleSubmit: (form: FormInputs, id?: number) => void; handleSubmit: (form: FormInputs, id?: number) => void;
} };
export default function FormModal({ export default function FormModal({ opened, onClose, currentForm, handleSubmit }: FormModalProps) {
opened,
onClose,
currentForm,
handleSubmit
}: FormModalProps) {
const { data: productors } = useGetProductors(); const { data: productors } = useGetProductors();
const { data: users } = useGetUsers(); const { data: users } = useGetUsers();
@@ -33,40 +36,50 @@ export default function FormModal({
}, },
validate: { validate: {
name: (value) => name: (value) =>
!value ? `${t("a name", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a name", { capfirst: true })} ${t("is required")}` : null,
season: (value) => season: (value) =>
!value ? `${t("a season", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a season", { capfirst: true })} ${t("is required")}` : null,
start: (value) => start: (value) =>
!value ? `${t("a start date", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a start date", { capfirst: true })} ${t("is required")}` : null,
end: (value) => end: (value) =>
!value ? `${t("a end date", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a end date", { capfirst: true })} ${t("is required")}` : null,
productor_id: (value) => productor_id: (value) =>
!value ? `${t("a productor", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a productor", { capfirst: true })} ${t("is required")}` : null,
referer_id: (value) => referer_id: (value) =>
!value ? `${t("a referer", {capfirst: true})} ${t('is required')}` : null !value ? `${t("a referer", { capfirst: true })} ${t("is required")}` : null,
} },
}); });
const usersSelect = useMemo(() => { const usersSelect = useMemo(() => {
return users?.map(user => ({value: String(user.id), label: `${user.name}`})) return users?.map((user) => ({
value: String(user.id),
label: `${user.name}`,
}));
}, [users]); }, [users]);
const productorsSelect = useMemo(() => { const productorsSelect = useMemo(() => {
return productors?.map(prod => ({value: String(prod.id), label: `${prod.name}`})) return productors?.map((prod) => ({
value: String(prod.id),
label: `${prod.name}`,
}));
}, [productors]); }, [productors]);
return ( return (
<Modal <Modal
opened={opened} opened={opened}
onClose={onClose} onClose={onClose}
title={currentForm ? t("edit form", {capfirst: true}) : t('create form', {capfirst: true})} title={
currentForm
? t("edit form", { capfirst: true })
: t("create form", { capfirst: true })
}
> >
<TextInput <TextInput
label={t("form name", { capfirst: true })} label={t("form name", { capfirst: true })}
placeholder={t("form name", { capfirst: true })} placeholder={t("form name", { capfirst: true })}
radius="sm" radius="sm"
withAsterisk withAsterisk
{...form.getInputProps('name')} {...form.getInputProps("name")}
/> />
<TextInput <TextInput
label={t("contract season", { capfirst: true })} label={t("contract season", { capfirst: true })}
@@ -74,20 +87,20 @@ export default function FormModal({
description={t("contract season recommandation", { capfirst: true })} description={t("contract season recommandation", { capfirst: true })}
radius="sm" radius="sm"
withAsterisk withAsterisk
{...form.getInputProps('season')} {...form.getInputProps("season")}
/> />
<Group grow> <Group grow>
<DatePickerInput <DatePickerInput
label={t("start date", { capfirst: true })} label={t("start date", { capfirst: true })}
placeholder={t("start date", { capfirst: true })} placeholder={t("start date", { capfirst: true })}
withAsterisk withAsterisk
{...form.getInputProps('start')} {...form.getInputProps("start")}
/> />
<DatePickerInput <DatePickerInput
label={t("end date", { capfirst: true })} label={t("end date", { capfirst: true })}
placeholder={t("end date", { capfirst: true })} placeholder={t("end date", { capfirst: true })}
withAsterisk withAsterisk
{...form.getInputProps('end')} {...form.getInputProps("end")}
/> />
</Group> </Group>
<Select <Select
@@ -99,7 +112,7 @@ export default function FormModal({
allowDeselect allowDeselect
searchable searchable
data={usersSelect || []} data={usersSelect || []}
{...form.getInputProps('referer_id')} {...form.getInputProps("referer_id")}
/> />
<Select <Select
label={t("productor", { capfirst: true })} label={t("productor", { capfirst: true })}
@@ -110,14 +123,17 @@ export default function FormModal({
allowDeselect allowDeselect
searchable searchable
data={productorsSelect || []} data={productorsSelect || []}
{...form.getInputProps('productor_id')} {...form.getInputProps("productor_id")}
/> />
<NumberInput <NumberInput
label={t("minimum shipment value", { capfirst: true })} label={t("minimum shipment value", { capfirst: true })}
placeholder={t("minimum shipment value", { capfirst: true })} placeholder={t("minimum shipment value", { capfirst: true })}
description={t("some contracts require a minimum value per shipment, ignore this field if it's not the case", {capfirst: true})} description={t(
"some contracts require a minimum value per shipment, ignore this field if it's not the case",
{ capfirst: true },
)}
radius="sm" radius="sm"
{...form.getInputProps('minimum_shipment_value')} {...form.getInputProps("minimum_shipment_value")}
/> />
<Group mt="sm" justify="space-between"> <Group mt="sm" justify="space-between">
<Button <Button
@@ -129,18 +145,28 @@ export default function FormModal({
form.clearErrors(); form.clearErrors();
onClose(); onClose();
}} }}
>{t("cancel", {capfirst: true})}</Button> >
{t("cancel", { capfirst: true })}
</Button>
<Button <Button
variant="filled" variant="filled"
aria-label={currentForm ? t("edit form", {capfirst: true}) : t('create form', {capfirst: true})} aria-label={
currentForm
? t("edit form", { capfirst: true })
: t("create form", { capfirst: true })
}
leftSection={currentForm ? <IconEdit /> : <IconPlus />} leftSection={currentForm ? <IconEdit /> : <IconPlus />}
onClick={() => { onClick={() => {
form.validate(); form.validate();
if (form.isValid()) { if (form.isValid()) {
handleSubmit(form.getValues(), currentForm?.id) handleSubmit(form.getValues(), currentForm?.id);
} }
}} }}
>{currentForm ? t("edit form", {capfirst: true}) : t('create form', {capfirst: true})}</Button> >
{currentForm
? t("edit form", { capfirst: true })
: t("create form", { capfirst: true })}
</Button>
</Group> </Group>
</Modal> </Modal>
); );

View File

@@ -7,11 +7,9 @@ import type { Form } from "@/services/resources/forms";
export type FormRowProps = { export type FormRowProps = {
form: Form; form: Form;
} };
export default function FormRow({ export default function FormRow({ form }: FormRowProps) {
form,
}: FormRowProps) {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const deleteMutation = useDeleteForm(); const deleteMutation = useDeleteForm();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -31,7 +29,9 @@ export default function FormRow({
mr="5" mr="5"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/forms/${form.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/forms/${form.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconEdit /> <IconEdit />

View File

@@ -5,11 +5,11 @@ export type InputLabelProps = {
label: string; label: string;
info: string; info: string;
isRequired?: boolean; isRequired?: boolean;
} };
export function InputLabel({ label, info, isRequired }: InputLabelProps) { export function InputLabel({ label, info, isRequired }: InputLabelProps) {
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
<Tooltip label={info}> <Tooltip label={info}>
<ActionIcon variant="transparent" size="xs" color="gray"> <ActionIcon variant="transparent" size="xs" color="gray">
<IconInfoCircle size={16} /> <IconInfoCircle size={16} />
@@ -17,12 +17,8 @@ export function InputLabel({label, info, isRequired}: InputLabelProps) {
</Tooltip> </Tooltip>
<span> <span>
{label} {label}
{ {isRequired ? <span style={{ color: "red" }}> *</span> : null}
isRequired ?
<span style={{ color: 'red' }}> *</span> : null
}
</span> </span>
</div> </div>
); );
} }

View File

@@ -8,16 +8,12 @@ export function Navbar() {
return ( return (
<nav> <nav>
<Group> <Group>
<NavLink <NavLink className={"navLink"} aria-label={t("home")} to="/">
className={"navLink"}
aria-label={t('home')}
to="/"
>
{t("home", { capfirst: true })} {t("home", { capfirst: true })}
</NavLink> </NavLink>
<NavLink <NavLink
className={"navLink"} className={"navLink"}
aria-label={t('dashboard')} aria-label={t("dashboard")}
to="/dashboard/productors" to="/dashboard/productors"
> >
{t("dashboard", { capfirst: true })} {t("dashboard", { capfirst: true })}

View File

@@ -7,19 +7,19 @@ export type ProductorsFiltersProps = {
types: string[]; types: string[];
filters: URLSearchParams; filters: URLSearchParams;
onFilterChange: (values: string[], filter: string) => void; onFilterChange: (values: string[], filter: string) => void;
} };
export default function ProductorsFilter({ export default function ProductorsFilter({
names, names,
types, types,
filters, filters,
onFilterChange onFilterChange,
}: ProductorsFiltersProps) { }: ProductorsFiltersProps) {
const defaultNames = useMemo(() => { const defaultNames = useMemo(() => {
return filters.getAll("names") return filters.getAll("names");
}, [filters]); }, [filters]);
const defaultTypes = useMemo(() => { const defaultTypes = useMemo(() => {
return filters.getAll("types") return filters.getAll("types");
}, [filters]); }, [filters]);
return ( return (
@@ -30,7 +30,7 @@ export default function ProductorsFilter({
data={names} data={names}
defaultValue={defaultNames} defaultValue={defaultNames}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'names') onFilterChange(values, "names");
}} }}
clearable clearable
searchable searchable
@@ -41,7 +41,7 @@ export default function ProductorsFilter({
data={types} data={types}
defaultValue={defaultTypes} defaultValue={defaultTypes}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'types') onFilterChange(values, "types");
}} }}
clearable clearable
searchable searchable

View File

@@ -1,19 +1,31 @@
import { Button, Group, Modal, MultiSelect, TextInput, Title, type ModalBaseProps } from "@mantine/core"; import {
Button,
Group,
Modal,
MultiSelect,
TextInput,
Title,
type ModalBaseProps,
} from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { useForm } from "@mantine/form"; import { useForm } from "@mantine/form";
import { IconCancel } from "@tabler/icons-react"; import { IconCancel } from "@tabler/icons-react";
import { PaymentMethods, type Productor, type ProductorInputs } from "@/services/resources/productors"; import {
PaymentMethods,
type Productor,
type ProductorInputs,
} from "@/services/resources/productors";
export type ProductorModalProps = ModalBaseProps & { export type ProductorModalProps = ModalBaseProps & {
currentProductor?: Productor; currentProductor?: Productor;
handleSubmit: (productor: ProductorInputs, id?: number) => void; handleSubmit: (productor: ProductorInputs, id?: number) => void;
} };
export function ProductorModal({ export function ProductorModal({
opened, opened,
onClose, onClose,
currentProductor, currentProductor,
handleSubmit handleSubmit,
}: ProductorModalProps) { }: ProductorModalProps) {
const form = useForm<ProductorInputs>({ const form = useForm<ProductorInputs>({
initialValues: { initialValues: {
@@ -28,16 +40,12 @@ export function ProductorModal({
address: (value) => address: (value) =>
!value ? `${t("address", { capfirst: true })} ${t("is required")}` : null, !value ? `${t("address", { capfirst: true })} ${t("is required")}` : null,
type: (value) => type: (value) =>
!value ? `${t("type", {capfirst: true})} ${t("is required")}` : null !value ? `${t("type", { capfirst: true })} ${t("is required")}` : null,
} },
}); });
return ( return (
<Modal <Modal opened={opened} onClose={onClose} title={t("create productor", { capfirst: true })}>
opened={opened}
onClose={onClose}
title={t("create productor", {capfirst: true})}
>
<Title order={4}>{t("Informations", { capfirst: true })}</Title> <Title order={4}>{t("Informations", { capfirst: true })}</Title>
<TextInput <TextInput
label={t("productor name", { capfirst: true })} label={t("productor name", { capfirst: true })}
@@ -68,41 +76,44 @@ export function ProductorModal({
data={PaymentMethods} data={PaymentMethods}
clearable clearable
searchable searchable
value={form.values.payment_methods.map(p => p.name)} value={form.values.payment_methods.map((p) => p.name)}
onChange={(names) => { onChange={(names) => {
form.setFieldValue("payment_methods", names.map(name => { form.setFieldValue(
const existing = form.values.payment_methods.find(p => p.name === name); "payment_methods",
return existing ?? { names.map((name) => {
const existing = form.values.payment_methods.find(
(p) => p.name === name,
);
return (
existing ?? {
name, name,
details: "" details: "",
}; }
})); );
}),
);
}} }}
/> />
{ {form.values.payment_methods.map((method, index) => (
form.values.payment_methods.map((method, index) => (
<TextInput <TextInput
key={index} key={index}
label={ label={
method.name === "cheque" ? method.name === "cheque"
t("order name", {capfirst: true}) : ? t("order name", { capfirst: true })
method.name === "transfer" ? : method.name === "transfer"
t("IBAN") : ? t("IBAN")
t("details", {capfirst: true}) : t("details", { capfirst: true })
} }
placeholder={ placeholder={
method.name === "cheque" ? method.name === "cheque"
t("order name", {capfirst: true}) : ? t("order name", { capfirst: true })
method.name === "transfer" ? : method.name === "transfer"
t("IBAN") : ? t("IBAN")
t("details", {capfirst: true}) : t("details", { capfirst: true })
} }
{...form.getInputProps( {...form.getInputProps(`payment_methods.${index}.details`)}
`payment_methods.${index}.details`
)}
/> />
)) ))}
}
<Group mt="sm" justify="space-between"> <Group mt="sm" justify="space-between">
<Button <Button
variant="filled" variant="filled"
@@ -113,17 +124,27 @@ export function ProductorModal({
form.clearErrors(); form.clearErrors();
onClose(); onClose();
}} }}
>{t("cancel", {capfirst: true})}</Button> >
{t("cancel", { capfirst: true })}
</Button>
<Button <Button
variant="filled" variant="filled"
aria-label={currentProductor ? t("edit productor", {capfirst: true}) : t("create productor", {capfirst: true})} aria-label={
currentProductor
? t("edit productor", { capfirst: true })
: t("create productor", { capfirst: true })
}
onClick={() => { onClick={() => {
form.validate(); form.validate();
if (form.isValid()) { if (form.isValid()) {
handleSubmit(form.getValues(), currentProductor?.id) handleSubmit(form.getValues(), currentProductor?.id);
} }
}} }}
>{currentProductor ? t("edit productor", {capfirst: true}) : t("create productor", {capfirst: true})}</Button> >
{currentProductor
? t("edit productor", { capfirst: true })
: t("create productor", { capfirst: true })}
</Button>
</Group> </Group>
</Modal> </Modal>
); );

View File

@@ -7,11 +7,9 @@ import { useNavigate, useSearchParams } from "react-router";
export type ProductorRowProps = { export type ProductorRowProps = {
productor: Productor; productor: Productor;
} };
export default function ProductorRow({ export default function ProductorRow({ productor }: ProductorRowProps) {
productor,
}: ProductorRowProps) {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const deleteMutation = useDeleteProductor(); const deleteMutation = useDeleteProductor();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -22,13 +20,11 @@ export default function ProductorRow({
<Table.Td>{productor.type}</Table.Td> <Table.Td>{productor.type}</Table.Td>
<Table.Td>{productor.address}</Table.Td> <Table.Td>{productor.address}</Table.Td>
<Table.Td> <Table.Td>
{ {productor.payment_methods.map((value) => (
productor.payment_methods.map((value) =>(
<Badge key={value.name} ml="xs"> <Badge key={value.name} ml="xs">
{t(value.name, { capfirst: true })} {t(value.name, { capfirst: true })}
</Badge> </Badge>
)) ))}
}
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
<Tooltip label={t("edit productor", { capfirst: true })}> <Tooltip label={t("edit productor", { capfirst: true })}>
@@ -37,7 +33,9 @@ export default function ProductorRow({
mr="5" mr="5"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/productors/${productor.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/productors/${productor.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconEdit /> <IconEdit />
@@ -57,6 +55,5 @@ export default function ProductorRow({
</Tooltip> </Tooltip>
</Table.Td> </Table.Td>
</Table.Tr> </Table.Tr>
); );
} }

View File

@@ -7,19 +7,19 @@ export type ProductsFiltersProps = {
productors: string[]; productors: string[];
filters: URLSearchParams; filters: URLSearchParams;
onFilterChange: (values: string[], filter: string) => void; onFilterChange: (values: string[], filter: string) => void;
} };
export default function ProductsFilters({ export default function ProductsFilters({
names, names,
productors, productors,
filters, filters,
onFilterChange onFilterChange,
}: ProductsFiltersProps) { }: ProductsFiltersProps) {
const defaultNames = useMemo(() => { const defaultNames = useMemo(() => {
return filters.getAll("names") return filters.getAll("names");
}, [filters]); }, [filters]);
const defaultProductors = useMemo(() => { const defaultProductors = useMemo(() => {
return filters.getAll("productors") return filters.getAll("productors");
}, [filters]); }, [filters]);
return ( return (
@@ -30,7 +30,7 @@ export default function ProductsFilters({
data={names} data={names}
defaultValue={defaultNames} defaultValue={defaultNames}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'names') onFilterChange(values, "names");
}} }}
clearable clearable
searchable searchable
@@ -41,7 +41,7 @@ export default function ProductsFilters({
data={productors} data={productors}
defaultValue={defaultProductors} defaultValue={defaultProductors}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'productors') onFilterChange(values, "productors");
}} }}
clearable clearable
searchable searchable

View File

@@ -8,36 +8,33 @@ export type ProductFormProps = {
inputForm: UseFormReturnType<Record<string, string | number>>; inputForm: UseFormReturnType<Record<string, string | number>>;
product: Product; product: Product;
shipment?: Shipment; shipment?: Shipment;
} };
export function ProductForm({ export function ProductForm({ inputForm, product, shipment }: ProductFormProps) {
inputForm,
product,
shipment,
}: ProductFormProps) {
return ( return (
<Group mb="sm" grow> <Group mb="sm" grow>
<NumberInput <NumberInput
label={ label={`${product.name}
`${product.name}
${product.quantity || ""}${product.quantity ? product.quantity_unit : ""} ${product.quantity || ""}${product.quantity ? product.quantity_unit : ""}
${ ${
product.price ? product.price
Intl.NumberFormat( ? Intl.NumberFormat("fr-FR", {
"fr-FR", style: "currency",
{style: "currency", currency: "EUR"} currency: "EUR",
).format(product.price) : }).format(product.price)
product.price_kg && Intl.NumberFormat( : product.price_kg &&
"fr-FR", Intl.NumberFormat("fr-FR", {
{style: "currency", currency: "EUR"} style: "currency",
).format(product.price_kg) currency: "EUR",
}).format(product.price_kg)
} }
${product.price ? `/ ${t(ProductUnit[product.unit])}` : "/ kg"}` ${product.price ? `/ ${t(ProductUnit[product.unit])}` : "/ kg"}`}
} description={`${t("enter quantity", { capfirst: true })} ${t("in")} ${t(ProductUnit[product.unit])}`}
description={`${t("enter quantity", {capfirst: true})} ${t('in')} ${t(ProductUnit[product.unit])}`}
aria-label={t("enter quantity")} aria-label={t("enter quantity")}
placeholder={`${t("enter quantity", {capfirst: true})} ${t('in')} ${t(ProductUnit[product.unit])}`} placeholder={`${t("enter quantity", { capfirst: true })} ${t("in")} ${t(ProductUnit[product.unit])}`}
{...inputForm.getInputProps(shipment ? `planned-${shipment.id}-${product.id}` : `recurrent-${product.id}`)} {...inputForm.getInputProps(
shipment ? `planned-${shipment.id}-${product.id}` : `recurrent-${product.id}`,
)}
/> />
</Group> </Group>
); );

View File

@@ -1,8 +1,22 @@
import { Button, Group, Modal, NumberInput, Select, TextInput, Title, type ModalBaseProps } from "@mantine/core"; import {
Button,
Group,
Modal,
NumberInput,
Select,
TextInput,
Title,
type ModalBaseProps,
} from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { useForm } from "@mantine/form"; import { useForm } from "@mantine/form";
import { IconCancel } from "@tabler/icons-react"; import { IconCancel } from "@tabler/icons-react";
import { ProductQuantityUnit, ProductUnit, type Product, type ProductInputs } from "@/services/resources/products"; import {
ProductQuantityUnit,
ProductUnit,
type Product,
type ProductInputs,
} from "@/services/resources/products";
import { useMemo } from "react"; import { useMemo } from "react";
import { useGetProductors } from "@/services/api"; import { useGetProductors } from "@/services/api";
import { InputLabel } from "@/components/Label"; import { InputLabel } from "@/components/Label";
@@ -10,14 +24,9 @@ import { InputLabel } from "@/components/Label";
export type ProductModalProps = ModalBaseProps & { export type ProductModalProps = ModalBaseProps & {
currentProduct?: Product; currentProduct?: Product;
handleSubmit: (product: ProductInputs, id?: number) => void; handleSubmit: (product: ProductInputs, id?: number) => void;
} };
export function ProductModal({ export function ProductModal({ opened, onClose, currentProduct, handleSubmit }: ProductModalProps) {
opened,
onClose,
currentProduct,
handleSubmit
}: ProductModalProps) {
const { data: productors } = useGetProductors(); const { data: productors } = useGetProductors();
const form = useForm<ProductInputs>({ const form = useForm<ProductInputs>({
initialValues: { initialValues: {
@@ -32,30 +41,33 @@ export function ProductModal({
}, },
validate: { validate: {
name: (value) => name: (value) =>
!value ? `${t("name", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("name", { capfirst: true })} ${t("is required")}` : null,
unit: (value) => unit: (value) =>
!value ? `${t("unit", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("unit", { capfirst: true })} ${t("is required")}` : null,
price: (value, values) => price: (value, values) =>
!value && !values.price_kg ? `${t("price or price_kg", {capfirst: true})} ${t('is required')}` : null, !value && !values.price_kg
? `${t("price or price_kg", { capfirst: true })} ${t("is required")}`
: null,
price_kg: (value, values) => price_kg: (value, values) =>
!value && !values.price ? `${t("price or price_kg", {capfirst: true})} ${t('is required')}` : null, !value && !values.price
? `${t("price or price_kg", { capfirst: true })} ${t("is required")}`
: null,
type: (value) => type: (value) =>
!value ? `${t("type", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("type", { capfirst: true })} ${t("is required")}` : null,
productor_id: (value) => productor_id: (value) =>
!value ? `${t("productor", {capfirst: true})} ${t('is required')}` : null !value ? `${t("productor", { capfirst: true })} ${t("is required")}` : null,
}, },
}); });
const productorsSelect = useMemo(() => { const productorsSelect = useMemo(() => {
return productors?.map(productor => ({value: String(productor.id), label: `${productor.name}`})) return productors?.map((productor) => ({
value: String(productor.id),
label: `${productor.name}`,
}));
}, [productors]); }, [productors]);
return ( return (
<Modal <Modal opened={opened} onClose={onClose} title={t("create product", { capfirst: true })}>
opened={opened}
onClose={onClose}
title={t("create product", {capfirst: true})}
>
<Title order={4}>{t("informations", { capfirst: true })}</Title> <Title order={4}>{t("informations", { capfirst: true })}</Title>
<Select <Select
label={t("productor", { capfirst: true })} label={t("productor", { capfirst: true })}
@@ -65,20 +77,23 @@ export function ProductModal({
clearable clearable
searchable searchable
data={productorsSelect || []} data={productorsSelect || []}
{...form.getInputProps('productor_id')} {...form.getInputProps("productor_id")}
/> />
<Group grow> <Group grow>
<TextInput <TextInput
label={t("product name", { capfirst: true })} label={t("product name", { capfirst: true })}
placeholder={t("product name", { capfirst: true })} placeholder={t("product name", { capfirst: true })}
radius="sm" radius="sm"
{...form.getInputProps('name')} {...form.getInputProps("name")}
/> />
<Select <Select
label={ label={
<InputLabel <InputLabel
label={t("product type", { capfirst: true })} label={t("product type", { capfirst: true })}
info={t("recurrent product is for all shipments, planned product is for a specific shipment (see shipment form)", {capfirst: true})} info={t(
"recurrent product is for all shipments, planned product is for a specific shipment (see shipment form)",
{ capfirst: true },
)}
isRequired isRequired
/> />
} }
@@ -88,34 +103,40 @@ export function ProductModal({
clearable clearable
data={[ data={[
{ value: "1", label: t("planned", { capfirst: true }) }, { value: "1", label: t("planned", { capfirst: true }) },
{value: "2", label: t("recurrent", {capfirst: true})} { value: "2", label: t("recurrent", { capfirst: true }) },
]} ]}
{...form.getInputProps('type')} {...form.getInputProps("type")}
/> />
</Group> </Group>
<Select <Select
label={t("product unit", { capfirst: true })} label={t("product unit", { capfirst: true })}
placeholder={t("product unit", { capfirst: true })} placeholder={t("product unit", { capfirst: true })}
description={t("the product unit will be assigned to the quantity requested in the form", { capfirst: true})} description={t(
"the product unit will be assigned to the quantity requested in the form",
{ capfirst: true },
)}
radius="sm" radius="sm"
withAsterisk withAsterisk
searchable searchable
clearable clearable
data={Object.entries(ProductUnit).map(([key, value]) => ({value: key, label: t(value, {capfirst: true})}))} data={Object.entries(ProductUnit).map(([key, value]) => ({
{...form.getInputProps('unit')} value: key,
label: t(value, { capfirst: true }),
}))}
{...form.getInputProps("unit")}
/> />
<Group grow> <Group grow>
<NumberInput <NumberInput
label={t("product price", { capfirst: true })} label={t("product price", { capfirst: true })}
placeholder={t("product price", { capfirst: true })} placeholder={t("product price", { capfirst: true })}
radius="sm" radius="sm"
{...form.getInputProps('price')} {...form.getInputProps("price")}
/> />
<NumberInput <NumberInput
label={t("product price kg", { capfirst: true })} label={t("product price kg", { capfirst: true })}
placeholder={t("product price kg", { capfirst: true })} placeholder={t("product price kg", { capfirst: true })}
radius="sm" radius="sm"
{...form.getInputProps('price_kg')} {...form.getInputProps("price_kg")}
/> />
</Group> </Group>
<Group grow> <Group grow>
@@ -123,7 +144,7 @@ export function ProductModal({
label={t("product quantity", { capfirst: true })} label={t("product quantity", { capfirst: true })}
placeholder={t("product quantity", { capfirst: true })} placeholder={t("product quantity", { capfirst: true })}
radius="sm" radius="sm"
{...form.getInputProps('quantity', {capfirst: true})} {...form.getInputProps("quantity", { capfirst: true })}
/> />
<Select <Select
label={t("product quantity unit", { capfirst: true })} label={t("product quantity unit", { capfirst: true })}
@@ -131,10 +152,12 @@ export function ProductModal({
radius="sm" radius="sm"
clearable clearable
searchable searchable
data={Object.entries(ProductQuantityUnit).map(([key, value]) => ({value: key, label: t(value, {capfirst: true})}))} data={Object.entries(ProductQuantityUnit).map(([key, value]) => ({
{...form.getInputProps('quantity_unit', {capfirst: true})} value: key,
label: t(value, { capfirst: true }),
}))}
{...form.getInputProps("quantity_unit", { capfirst: true })}
/> />
</Group> </Group>
<Group mt="sm" justify="space-between"> <Group mt="sm" justify="space-between">
<Button <Button
@@ -146,17 +169,27 @@ export function ProductModal({
form.clearErrors(); form.clearErrors();
onClose(); onClose();
}} }}
>{t("cancel", {capfirst: true})}</Button> >
{t("cancel", { capfirst: true })}
</Button>
<Button <Button
variant="filled" variant="filled"
aria-label={currentProduct ? t("edit product", {capfirst: true}) : t('create product', {capfirst: true})} aria-label={
currentProduct
? t("edit product", { capfirst: true })
: t("create product", { capfirst: true })
}
onClick={() => { onClick={() => {
form.validate(); form.validate();
if (form.isValid()) { if (form.isValid()) {
handleSubmit(form.getValues(), currentProduct?.id) handleSubmit(form.getValues(), currentProduct?.id);
} }
}} }}
>{currentProduct ? t("edit product", {capfirst: true}) : t('create product', {capfirst: true})}</Button> >
{currentProduct
? t("edit product", { capfirst: true })
: t("create product", { capfirst: true })}
</Button>
</Group> </Group>
</Modal> </Modal>
); );

View File

@@ -7,11 +7,9 @@ import { useNavigate, useSearchParams } from "react-router";
export type ProductRowProps = { export type ProductRowProps = {
product: Product; product: Product;
} };
export default function ProductRow({ export default function ProductRow({ product }: ProductRowProps) {
product,
}: ProductRowProps) {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const deleteMutation = useDeleteProduct(); const deleteMutation = useDeleteProduct();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -21,25 +19,25 @@ export default function ProductRow({
<Table.Td>{product.name}</Table.Td> <Table.Td>{product.name}</Table.Td>
<Table.Td>{t(ProductType[product.type])}</Table.Td> <Table.Td>{t(ProductType[product.type])}</Table.Td>
<Table.Td> <Table.Td>
{ {product.price
product.price ? ? Intl.NumberFormat("fr-FR", {
Intl.NumberFormat( style: "currency",
"fr-FR", currency: "EUR",
{style: "currency", currency: "EUR"} }).format(product.price)
).format(product.price) : null : null}
}
</Table.Td> </Table.Td>
<Table.Td> <Table.Td>
{ {product.price_kg
product.price_kg ? ? `${Intl.NumberFormat("fr-FR", {
`${Intl.NumberFormat( style: "currency",
"fr-FR", currency: "EUR",
{style: "currency", currency: "EUR"} }).format(product.price_kg)}/kg`
).format(product.price_kg)}/kg` : null : null}
</Table.Td>
} <Table.Td>
{product.quantity}
{product.quantity_unit}
</Table.Td> </Table.Td>
<Table.Td>{product.quantity}{product.quantity_unit}</Table.Td>
<Table.Td>{t(ProductUnit[product.unit], { capfirst: true })}</Table.Td> <Table.Td>{t(ProductUnit[product.unit], { capfirst: true })}</Table.Td>
<Table.Td> <Table.Td>
<Tooltip label={t("edit product", { capfirst: true })}> <Tooltip label={t("edit product", { capfirst: true })}>
@@ -48,7 +46,9 @@ export default function ProductRow({
mr="5" mr="5"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/products/${product.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/products/${product.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconEdit /> <IconEdit />
@@ -68,6 +68,5 @@ export default function ProductRow({
</Tooltip> </Tooltip>
</Table.Td> </Table.Td>
</Table.Tr> </Table.Tr>
); );
} }

View File

@@ -7,19 +7,19 @@ export type ShipmentFiltersProps = {
forms: string[]; forms: string[];
filters: URLSearchParams; filters: URLSearchParams;
onFilterChange: (values: string[], filter: string) => void; onFilterChange: (values: string[], filter: string) => void;
} };
export default function ShipmentsFilters({ export default function ShipmentsFilters({
names, names,
forms, forms,
filters, filters,
onFilterChange onFilterChange,
}: ShipmentFiltersProps) { }: ShipmentFiltersProps) {
const defaultNames = useMemo(() => { const defaultNames = useMemo(() => {
return filters.getAll("names") return filters.getAll("names");
}, [filters]); }, [filters]);
const defaultForms = useMemo(() => { const defaultForms = useMemo(() => {
return filters.getAll("forms") return filters.getAll("forms");
}, [filters]); }, [filters]);
return ( return (
@@ -30,7 +30,7 @@ export default function ShipmentsFilters({
data={names} data={names}
defaultValue={defaultNames} defaultValue={defaultNames}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'names') onFilterChange(values, "names");
}} }}
clearable clearable
searchable searchable
@@ -41,7 +41,7 @@ export default function ShipmentsFilters({
data={forms} data={forms}
defaultValue={defaultForms} defaultValue={defaultForms}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'forms') onFilterChange(values, "forms");
}} }}
clearable clearable
searchable searchable

View File

@@ -11,7 +11,7 @@ export type ShipmentFormProps = {
shipment: Shipment; shipment: Shipment;
minimumPrice?: number | null; minimumPrice?: number | null;
index: number; index: number;
} };
export default function ShipmentForm({ export default function ShipmentForm({
shipment, shipment,
@@ -20,20 +20,16 @@ export default function ShipmentForm({
minimumPrice, minimumPrice,
}: ShipmentFormProps) { }: ShipmentFormProps) {
const shipmentPrice = useMemo(() => { const shipmentPrice = useMemo(() => {
const values = Object const values = Object.entries(inputForm.getValues()).filter(
.entries(inputForm.getValues()) ([key]) => key.includes("planned") && key.split("-")[1] === String(shipment.id),
.filter(([key]) =>
key.includes("planned") &&
key.split("-")[1] === String(shipment.id)
); );
return computePrices(values, shipment.products); return computePrices(values, shipment.products);
}, [inputForm, shipment.products, shipment.id]); }, [inputForm, shipment.products, shipment.id]);
const priceRequirement = useMemo(() => { const priceRequirement = useMemo(() => {
if (!minimumPrice) if (!minimumPrice) return false;
return false; return minimumPrice ? shipmentPrice < minimumPrice : true;
return minimumPrice ? shipmentPrice < minimumPrice : true }, [shipmentPrice, minimumPrice]);
}, [shipmentPrice, minimumPrice])
return ( return (
<Accordion.Item value={String(index)}> <Accordion.Item value={String(index)}>
@@ -41,43 +37,37 @@ export default function ShipmentForm({
<Group justify="space-between"> <Group justify="space-between">
<Text>{shipment.name}</Text> <Text>{shipment.name}</Text>
<Stack gap={0}> <Stack gap={0}>
<Text c={priceRequirement ? "red" : "green"}>{ <Text c={priceRequirement ? "red" : "green"}>
Intl.NumberFormat( {Intl.NumberFormat("fr-FR", {
"fr-FR", style: "currency",
{style: "currency", currency: "EUR"} currency: "EUR",
).format(shipmentPrice) }).format(shipmentPrice)}
}</Text> </Text>
{ {priceRequirement ? (
priceRequirement ?
<Text c="red" size="sm"> <Text c="red" size="sm">
{`${t("minimum price for this shipment should be at least", { capfirst: true })} ${minimumPrice}`} {`${t("minimum price for this shipment should be at least", { capfirst: true })} ${minimumPrice}`}
</Text> : </Text>
null ) : null}
}
</Stack> </Stack>
<Text mr="lg"> <Text mr="lg">
{`${ {`${new Date(shipment.date).toLocaleDateString("fr-FR", {
new Date(shipment.date).toLocaleDateString("fr-FR", {
weekday: "long", weekday: "long",
year: "numeric", year: "numeric",
month: "long", month: "long",
day: "numeric", day: "numeric",
}) })}`}
}`}
</Text> </Text>
</Group> </Group>
</Accordion.Control> </Accordion.Control>
<Accordion.Panel> <Accordion.Panel>
{ {shipment?.products.map((product) => (
shipment?.products.map((product) => (
<ProductForm <ProductForm
key={product.id} key={product.id}
product={product} product={product}
shipment={shipment} shipment={shipment}
inputForm={inputForm} inputForm={inputForm}
/> />
)) ))}
}
</Accordion.Panel> </Accordion.Panel>
</Accordion.Item> </Accordion.Item>
); );

View File

@@ -1,4 +1,12 @@
import { Button, Group, Modal, MultiSelect, Select, TextInput, type ModalBaseProps } from "@mantine/core"; import {
Button,
Group,
Modal,
MultiSelect,
Select,
TextInput,
type ModalBaseProps,
} from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { DatePickerInput } from "@mantine/dates"; import { DatePickerInput } from "@mantine/dates";
import { IconCancel } from "@tabler/icons-react"; import { IconCancel } from "@tabler/icons-react";
@@ -10,49 +18,54 @@ import { useGetForms, useGetProductors, useGetProducts } from "@/services/api";
export type ShipmentModalProps = ModalBaseProps & { export type ShipmentModalProps = ModalBaseProps & {
currentShipment?: Shipment; currentShipment?: Shipment;
handleSubmit: (shipment: ShipmentInputs, id?: number) => void; handleSubmit: (shipment: ShipmentInputs, id?: number) => void;
} };
export default function ShipmentModal({ export default function ShipmentModal({
opened, opened,
onClose, onClose,
currentShipment, currentShipment,
handleSubmit handleSubmit,
}: ShipmentModalProps) { }: ShipmentModalProps) {
const form = useForm<ShipmentInputs>({ const form = useForm<ShipmentInputs>({
initialValues: { initialValues: {
name: currentShipment?.name ?? "", name: currentShipment?.name ?? "",
date: currentShipment?.date ?? null, date: currentShipment?.date ?? null,
form_id: currentShipment ? String(currentShipment?.form_id) : "", form_id: currentShipment ? String(currentShipment?.form_id) : "",
product_ids: currentShipment?.products.map((el) => (String(el.id))) ?? [] product_ids: currentShipment?.products.map((el) => String(el.id)) ?? [],
}, },
validate: { validate: {
name: (value) => name: (value) =>
!value ? `${t("a name", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a name", { capfirst: true })} ${t("is required")}` : null,
date: (value) => date: (value) =>
!value ? `${t("a shipment date", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a shipment date", { capfirst: true })} ${t("is required")}` : null,
form_id: (value) => form_id: (value) =>
!value ? `${t("a form", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("a form", { capfirst: true })} ${t("is required")}` : null,
} },
}); });
const { data: allForms } = useGetForms(); const { data: allForms } = useGetForms();
const { data: allProducts } = useGetProducts(new URLSearchParams("types=1")); const { data: allProducts } = useGetProducts(new URLSearchParams("types=1"));
const { data: allProductors } = useGetProductors() const { data: allProductors } = useGetProductors();
const formsSelect = useMemo(() => { const formsSelect = useMemo(() => {
return allForms?.map(currentForm => ({value: String(currentForm.id), label: `${currentForm.name} ${currentForm.season}`})) return allForms?.map((currentForm) => ({
value: String(currentForm.id),
label: `${currentForm.name} ${currentForm.season}`,
}));
}, [allForms]); }, [allForms]);
const productsSelect = useMemo(() => { const productsSelect = useMemo(() => {
if (!allProducts) if (!allProducts) return;
return; return allProductors?.map((productor) => {
return allProductors?.map(productor => {
return { return {
group: productor.name, group: productor.name,
items: allProducts items: allProducts
.filter((product) => product.productor.id === productor.id) .filter((product) => product.productor.id === productor.id)
.map((product) => ({value: String(product.id), label: `${product.name}`})) .map((product) => ({
} value: String(product.id),
label: `${product.name}`,
})),
};
}); });
}, [allProductors, allProducts]); }, [allProductors, allProducts]);
@@ -60,20 +73,20 @@ export default function ShipmentModal({
<Modal <Modal
opened={opened} opened={opened}
onClose={onClose} onClose={onClose}
title={currentShipment ? t("edit shipment") : t('create shipment')} title={currentShipment ? t("edit shipment") : t("create shipment")}
> >
<TextInput <TextInput
label={t("shipment name", { capfirst: true })} label={t("shipment name", { capfirst: true })}
placeholder={t("shipment name", { capfirst: true })} placeholder={t("shipment name", { capfirst: true })}
radius="sm" radius="sm"
withAsterisk withAsterisk
{...form.getInputProps('name')} {...form.getInputProps("name")}
/> />
<DatePickerInput <DatePickerInput
label={t("shipment date", { capfirst: true })} label={t("shipment date", { capfirst: true })}
placeholder={t("shipment date", { capfirst: true })} placeholder={t("shipment date", { capfirst: true })}
withAsterisk withAsterisk
{...form.getInputProps('date')} {...form.getInputProps("date")}
/> />
<Select <Select
label={t("shipment form", { capfirst: true })} label={t("shipment form", { capfirst: true })}
@@ -82,16 +95,19 @@ export default function ShipmentModal({
data={formsSelect || []} data={formsSelect || []}
clearable clearable
withAsterisk withAsterisk
{...form.getInputProps('form_id')} {...form.getInputProps("form_id")}
/> />
<MultiSelect <MultiSelect
label={t("shipment products", { capfirst: true })} label={t("shipment products", { capfirst: true })}
placeholder={t("shipment products", { capfirst: true })} placeholder={t("shipment products", { capfirst: true })}
description={t("shipment products is necessary only for planned products (if all products are recurrent leave empty)", {capfirst: true})} description={t(
"shipment products is necessary only for planned products (if all products are recurrent leave empty)",
{ capfirst: true },
)}
data={productsSelect || []} data={productsSelect || []}
clearable clearable
searchable searchable
{...form.getInputProps('product_ids')} {...form.getInputProps("product_ids")}
/> />
<Group mt="sm" justify="space-between"> <Group mt="sm" justify="space-between">
<Button <Button
@@ -103,17 +119,27 @@ export default function ShipmentModal({
form.clearErrors(); form.clearErrors();
onClose(); onClose();
}} }}
>{t("cancel", {capfirst: true})}</Button> >
{t("cancel", { capfirst: true })}
</Button>
<Button <Button
variant="filled" variant="filled"
aria-label={currentShipment ? t("edit shipment", {capfirst: true}) : t('create shipment', {capfirst: true})} aria-label={
currentShipment
? t("edit shipment", { capfirst: true })
: t("create shipment", { capfirst: true })
}
onClick={() => { onClick={() => {
form.validate(); form.validate();
if (form.isValid()) { if (form.isValid()) {
handleSubmit(form.getValues(), currentShipment?.id) handleSubmit(form.getValues(), currentShipment?.id);
} }
}} }}
>{currentShipment ? t("edit shipment", {capfirst: true}) : t('create shipment', {capfirst: true})}</Button> >
{currentShipment
? t("edit shipment", { capfirst: true })
: t("create shipment", { capfirst: true })}
</Button>
</Group> </Group>
</Modal> </Modal>
); );

View File

@@ -7,11 +7,9 @@ import type { Shipment } from "@/services/resources/shipments";
export type ShipmentRowProps = { export type ShipmentRowProps = {
shipment: Shipment; shipment: Shipment;
} };
export default function ShipmentRow({ export default function ShipmentRow({ shipment }: ShipmentRowProps) {
shipment,
}: ShipmentRowProps) {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const deleteMutation = useDeleteShipment(); const deleteMutation = useDeleteShipment();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -28,7 +26,9 @@ export default function ShipmentRow({
mr="5" mr="5"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/shipments/${shipment.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/shipments/${shipment.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconEdit /> <IconEdit />

View File

@@ -6,15 +6,11 @@ export type UserFiltersProps = {
names: string[]; names: string[];
filters: URLSearchParams; filters: URLSearchParams;
onFilterChange: (values: string[], filter: string) => void; onFilterChange: (values: string[], filter: string) => void;
} };
export default function UserFilters({ export default function UserFilters({ names, filters, onFilterChange }: UserFiltersProps) {
names,
filters,
onFilterChange
}: UserFiltersProps) {
const defaultNames = useMemo(() => { const defaultNames = useMemo(() => {
return filters.getAll("names") return filters.getAll("names");
}, [filters]); }, [filters]);
return ( return (
@@ -25,7 +21,7 @@ export default function UserFilters({
data={names} data={names}
defaultValue={defaultNames} defaultValue={defaultNames}
onChange={(values: string[]) => { onChange={(values: string[]) => {
onFilterChange(values, 'names') onFilterChange(values, "names");
}} }}
clearable clearable
/> />

View File

@@ -7,47 +7,38 @@ import { type User, type UserInputs } from "@/services/resources/users";
export type UserModalProps = ModalBaseProps & { export type UserModalProps = ModalBaseProps & {
currentUser?: User; currentUser?: User;
handleSubmit: (user: UserInputs, id?: number) => void; handleSubmit: (user: UserInputs, id?: number) => void;
} };
export function UserModal({ export function UserModal({ opened, onClose, currentUser, handleSubmit }: UserModalProps) {
opened,
onClose,
currentUser,
handleSubmit
}: UserModalProps) {
const form = useForm<UserInputs>({ const form = useForm<UserInputs>({
initialValues: { initialValues: {
name: currentUser?.name ?? "", name: currentUser?.name ?? "",
email: currentUser?.email ?? "" email: currentUser?.email ?? "",
}, },
validate: { validate: {
name: (value) => name: (value) =>
!value ? `${t("name", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("name", { capfirst: true })} ${t("is required")}` : null,
email: (value) => email: (value) =>
!value ? `${t("email", {capfirst: true})} ${t('is required')}` : null, !value ? `${t("email", { capfirst: true })} ${t("is required")}` : null,
} },
}); });
return ( return (
<Modal <Modal opened={opened} onClose={onClose} title={t("create user", { capfirst: true })}>
opened={opened}
onClose={onClose}
title={t("create user", {capfirst: true})}
>
<Title order={4}>{t("informations", { capfirst: true })}</Title> <Title order={4}>{t("informations", { capfirst: true })}</Title>
<TextInput <TextInput
label={t("user name", { capfirst: true })} label={t("user name", { capfirst: true })}
placeholder={t("user name", { capfirst: true })} placeholder={t("user name", { capfirst: true })}
radius="sm" radius="sm"
withAsterisk withAsterisk
{...form.getInputProps('name')} {...form.getInputProps("name")}
/> />
<TextInput <TextInput
label={t("user email", { capfirst: true })} label={t("user email", { capfirst: true })}
placeholder={t("user email", { capfirst: true })} placeholder={t("user email", { capfirst: true })}
radius="sm" radius="sm"
withAsterisk withAsterisk
{...form.getInputProps('email')} {...form.getInputProps("email")}
/> />
<Group mt="sm" justify="space-between"> <Group mt="sm" justify="space-between">
<Button <Button
@@ -59,17 +50,27 @@ export function UserModal({
form.clearErrors(); form.clearErrors();
onClose(); onClose();
}} }}
>{t("cancel", {capfirst: true})}</Button> >
{t("cancel", { capfirst: true })}
</Button>
<Button <Button
variant="filled" variant="filled"
aria-label={currentUser ? t("edit user", {capfirst: true}) : t('create user', {capfirst: true})} aria-label={
currentUser
? t("edit user", { capfirst: true })
: t("create user", { capfirst: true })
}
onClick={() => { onClick={() => {
form.validate(); form.validate();
if (form.isValid()) { if (form.isValid()) {
handleSubmit(form.getValues(), currentUser?.id) handleSubmit(form.getValues(), currentUser?.id);
} }
}} }}
>{currentUser ? t("edit user", {capfirst: true}) : t('create user', {capfirst: true})}</Button> >
{currentUser
? t("edit user", { capfirst: true })
: t("create user", { capfirst: true })}
</Button>
</Group> </Group>
</Modal> </Modal>
); );

View File

@@ -7,11 +7,9 @@ import { useNavigate, useSearchParams } from "react-router";
export type UserRowProps = { export type UserRowProps = {
user: User; user: User;
} };
export default function UserRow({ export default function UserRow({ user }: UserRowProps) {
user,
}: UserRowProps) {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const deleteMutation = useDeleteUser(); const deleteMutation = useDeleteUser();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -27,7 +25,9 @@ export default function UserRow({
mr="5" mr="5"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/users/${user.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/users/${user.id}/edit${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconEdit /> <IconEdit />
@@ -47,6 +47,5 @@ export default function UserRow({
</Tooltip> </Tooltip>
</Table.Td> </Table.Td>
</Table.Tr> </Table.Tr>
); );
} }

View File

@@ -1,4 +1,4 @@
export const Config = { export const Config = {
backend_uri: import.meta.env.VITE_API_URL, backend_uri: import.meta.env.VITE_API_URL,
debug: import.meta.env.NODE_ENV === "development" debug: import.meta.env.NODE_ENV === "development",
} };

View File

@@ -30,17 +30,13 @@ i18next
.then(() => { .then(() => {
[Settings.defaultLocale] = i18next.language.split("-"); [Settings.defaultLocale] = i18next.language.split("-");
i18next.services.formatter?.add( i18next.services.formatter?.add("capfirst", (value) => {
"capfirst",
(value) => {
if (typeof value !== "string" || !value.length) { if (typeof value !== "string" || !value.length) {
return value; return value;
} }
return value.charAt(0).toUpperCase() + value.slice(1); return value.charAt(0).toUpperCase() + value.slice(1);
}
);
}); });
});
export function t(message: string, params?: Record<string, unknown>) { export function t(message: string, params?: Record<string, unknown>) {
const result = i18next.t(message, params); const result = i18next.t(message, params);

View File

@@ -4,12 +4,12 @@ import { RouterProvider } from "react-router";
import { router } from "@/router.tsx"; import { router } from "@/router.tsx";
import { MantineProvider } from "@mantine/core"; import { MantineProvider } from "@mantine/core";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import '@mantine/core/styles.css'; import "@mantine/core/styles.css";
import '@mantine/dates/styles.css'; import "@mantine/dates/styles.css";
import '@mantine/notifications/styles.css'; import "@mantine/notifications/styles.css";
import { Notifications } from "@mantine/notifications"; import { Notifications } from "@mantine/notifications";
const queryClient = new QueryClient() const queryClient = new QueryClient();
createRoot(document.getElementById("root")!).render( createRoot(document.getElementById("root")!).render(
<StrictMode> <StrictMode>
@@ -19,5 +19,5 @@ createRoot(document.getElementById("root")!).render(
<RouterProvider router={router} /> <RouterProvider router={router} />
</MantineProvider> </MantineProvider>
</QueryClientProvider> </QueryClientProvider>
</StrictMode> </StrictMode>,
); );

View File

@@ -3,7 +3,18 @@ import ShipmentForm from "@/components/Shipments/Form";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { useCreateContract, useGetForm } from "@/services/api"; import { useCreateContract, useGetForm } from "@/services/api";
import { type Product } from "@/services/resources/products"; import { type Product } from "@/services/resources/products";
import { Accordion, Button, Group, List, Loader, Overlay, Stack, Text, TextInput, Title } from "@mantine/core"; import {
Accordion,
Button,
Group,
List,
Loader,
Overlay,
Stack,
Text,
TextInput,
Title,
} from "@mantine/core";
import { useForm } from "@mantine/form"; import { useForm } from "@mantine/form";
import { IconMail, IconPhone, IconUser } from "@tabler/icons-react"; import { IconMail, IconPhone, IconUser } from "@tabler/icons-react";
import { useCallback, useMemo, useRef } from "react"; import { useCallback, useMemo, useRef } from "react";
@@ -21,17 +32,21 @@ export function Contract() {
phone: "", phone: "",
}, },
validate: { validate: {
firstname: (value) => !value ? `${t("a firstname", {capfirst: true})} ${t("is required")}` : null, firstname: (value) =>
lastname: (value) => !value ? `${t("a lastname", {capfirst: true})} ${t("is required")}` : null, !value ? `${t("a firstname", { capfirst: true })} ${t("is required")}` : null,
email: (value) => !value ? `${t("a email", {capfirst: true})} ${t("is required")}` : null, lastname: (value) =>
phone: (value) => !value ? `${t("a phone", {capfirst: true})} ${t("is required")}` : null, !value ? `${t("a lastname", { capfirst: true })} ${t("is required")}` : null,
} email: (value) =>
!value ? `${t("a email", { capfirst: true })} ${t("is required")}` : null,
phone: (value) =>
!value ? `${t("a phone", { capfirst: true })} ${t("is required")}` : null,
},
}); });
const createContractMutation = useCreateContract(); const createContractMutation = useCreateContract();
const productsRecurent = useMemo(() => { const productsRecurent = useMemo(() => {
return form?.productor?.products.filter((el) => el.type === "2") return form?.productor?.products.filter((el) => el.type === "2");
}, [form]); }, [form]);
const shipments = useMemo(() => { const shipments = useMemo(() => {
@@ -40,7 +55,7 @@ export function Contract() {
const allProducts = useMemo(() => { const allProducts = useMemo(() => {
return form?.productor?.products; return form?.productor?.products;
}, [form]) }, [form]);
const price = useMemo(() => { const price = useMemo(() => {
if (!allProducts) { if (!allProducts) {
@@ -54,17 +69,16 @@ export function Contract() {
firstname: null, firstname: null,
lastname: null, lastname: null,
email: null, email: null,
phone: null phone: null,
}); });
const isShipmentsMinimumValue = useCallback(() => { const isShipmentsMinimumValue = useCallback(() => {
if (!form) if (!form) return false;
return false;
const shipmentErrors = form.shipments const shipmentErrors = form.shipments
.map((shipment) => { .map((shipment) => {
const total = computePrices( const total = computePrices(
Object.entries(inputForm.getValues()), Object.entries(inputForm.getValues()),
shipment.products shipment.products,
); );
if (total < (form?.minimum_shipment_value || 0)) { if (total < (form?.minimum_shipment_value || 0)) {
return shipment.id; return shipment.id;
@@ -75,9 +89,9 @@ export function Contract() {
return shipmentErrors.length === 0; return shipmentErrors.length === 0;
}, [form, inputForm]); }, [form, inputForm]);
const withDefaultValues = useCallback((values: Record<string, number | string>) => { const withDefaultValues = useCallback(
if (!productsRecurent || !form) (values: Record<string, number | string>) => {
return {}; if (!productsRecurent || !form) return {};
const result = { ...values }; const result = { ...values };
productsRecurent.forEach((product: Product) => { productsRecurent.forEach((product: Product) => {
@@ -93,11 +107,13 @@ export function Contract() {
if (result[key] === undefined || result[key] === "") { if (result[key] === undefined || result[key] === "") {
result[key] = 0; result[key] = 0;
} }
}) });
}); });
return result; return result;
}, [productsRecurent, form]); },
[productsRecurent, form],
);
const handleSubmit = useCallback(async () => { const handleSubmit = useCallback(async () => {
const errors = inputForm.validate(); const errors = inputForm.validate();
@@ -108,35 +124,37 @@ export function Contract() {
const contract = { const contract = {
form_id: form.id, form_id: form.id,
contract: withDefaultValues(inputForm.getValues()), contract: withDefaultValues(inputForm.getValues()),
} };
await createContractMutation.mutateAsync(contract); await createContractMutation.mutateAsync(contract);
} else { } else {
const firstErrorField = Object.keys(errors.errors)[0]; const firstErrorField = Object.keys(errors.errors)[0];
const ref = inputRefs.current[firstErrorField]; const ref = inputRefs.current[firstErrorField];
ref?.scrollIntoView({ behavior: "smooth", block: "center" }); ref?.scrollIntoView({ behavior: "smooth", block: "center" });
} }
}, [inputForm, inputRefs, isShipmentsMinimumValue, form, createContractMutation, withDefaultValues]); }, [
inputForm,
inputRefs,
isShipmentsMinimumValue,
form,
createContractMutation,
withDefaultValues,
]);
if (!form || !shipments || !productsRecurent) if (!form || !shipments || !productsRecurent)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
return ( return (
<Stack w={{ base: "100%", md: "80%", lg: "50%" }}> <Stack w={{ base: "100%", md: "80%", lg: "50%" }}>
<Title order={2}>{form.name}</Title> <Title order={2}>{form.name}</Title>
<Title order={3}>{t("informations", { capfirst: true })}</Title> <Title order={3}>{t("informations", { capfirst: true })}</Title>
<Text size="sm"> <Text size="sm">
{t("all theses informations are for contract generation", {capfirst: true})} {t("all theses informations are for contract generation", {
capfirst: true,
})}
</Text> </Text>
<Group grow> <Group grow>
<TextInput <TextInput
@@ -146,8 +164,10 @@ export function Contract() {
withAsterisk withAsterisk
required required
leftSection={<IconUser />} leftSection={<IconUser />}
{...inputForm.getInputProps('firstname')} {...inputForm.getInputProps("firstname")}
ref={(el) => {inputRefs.current.firstname = el}} ref={(el) => {
inputRefs.current.firstname = el;
}}
/> />
<TextInput <TextInput
label={t("lastname", { capfirst: true })} label={t("lastname", { capfirst: true })}
@@ -156,8 +176,10 @@ export function Contract() {
withAsterisk withAsterisk
required required
leftSection={<IconUser />} leftSection={<IconUser />}
{...inputForm.getInputProps('lastname')} {...inputForm.getInputProps("lastname")}
ref={(el) => {inputRefs.current.lastname = el}} ref={(el) => {
inputRefs.current.lastname = el;
}}
/> />
</Group> </Group>
<Group grow> <Group grow>
@@ -168,8 +190,10 @@ export function Contract() {
withAsterisk withAsterisk
required required
leftSection={<IconMail />} leftSection={<IconMail />}
{...inputForm.getInputProps('email')} {...inputForm.getInputProps("email")}
ref={(el) => {inputRefs.current.email = el}} ref={(el) => {
inputRefs.current.email = el;
}}
/> />
<TextInput <TextInput
label={t("phone", { capfirst: true })} label={t("phone", { capfirst: true })}
@@ -178,53 +202,46 @@ export function Contract() {
withAsterisk withAsterisk
required required
leftSection={<IconPhone />} leftSection={<IconPhone />}
{...inputForm.getInputProps('phone')} {...inputForm.getInputProps("phone")}
ref={(el) => {inputRefs.current.phone = el}} ref={(el) => {
inputRefs.current.phone = el;
}}
/> />
</Group> </Group>
<Title order={3}>{t('shipments', {capfirst: true})}</Title> <Title order={3}>{t("shipments", { capfirst: true })}</Title>
<Text>{`${t("there is", { capfirst: true })} ${shipments.length} ${shipments.length > 1 ? t("shipments") : t("shipment")} ${t("for this contract")}`}</Text> <Text>{`${t("there is", { capfirst: true })} ${shipments.length} ${shipments.length > 1 ? t("shipments") : t("shipment")} ${t("for this contract")}`}</Text>
<List> <List>
{ {shipments.map((shipment) => (
shipments.map(shipment => ( <List.Item key={shipment.id}>
<List.Item key={shipment.id}>{`${shipment.name} : {`${shipment.name} :
${ ${new Date(shipment.date).toLocaleDateString("fr-FR", {
new Date(shipment.date).toLocaleDateString("fr-FR", {
weekday: "long", weekday: "long",
year: "numeric", year: "numeric",
month: "long", month: "long",
day: "numeric", day: "numeric",
}) })}`}
}`}
</List.Item> </List.Item>
)) ))}
}
</List> </List>
{ {productsRecurent.length > 0 ? (
productsRecurent.length > 0 ?
<> <>
<Title order={3}>{t('recurrent products', {capfirst: true})}</Title> <Title order={3}>{t("recurrent products", { capfirst: true })}</Title>
<Text size="sm">{t('your selection in this category will apply for all shipments', {capfirst: true})}</Text> <Text size="sm">
{ {t("your selection in this category will apply for all shipments", {
productsRecurent.map((product) => ( capfirst: true,
<ProductForm })}
key={product.id} </Text>
product={product} {productsRecurent.map((product) => (
inputForm={inputForm} <ProductForm key={product.id} product={product} inputForm={inputForm} />
/> ))}
)) </>
} ) : null}
</> : {shipments.some((shipment) => shipment.products.length > 0) ? (
null
}
{
shipments.some(shipment => shipment.products.length > 0) ?
<> <>
<Title order={3}>{t("planned products")}</Title> <Title order={3}>{t("planned products")}</Title>
<Text>{t("select products per shipment")}</Text> <Text>{t("select products per shipment")}</Text>
<Accordion defaultValue={"0"}> <Accordion defaultValue={"0"}>
{ {shipments.map((shipment, index) => (
shipments.map((shipment, index) => (
<ShipmentForm <ShipmentForm
minimumPrice={form.minimum_shipment_value} minimumPrice={form.minimum_shipment_value}
shipment={shipment} shipment={shipment}
@@ -232,12 +249,10 @@ export function Contract() {
inputForm={inputForm} inputForm={inputForm}
key={shipment.id} key={shipment.id}
/> />
)) ))}
}
</Accordion> </Accordion>
</> : </>
null ) : null}
}
<Overlay <Overlay
bg={"lightGray"} bg={"lightGray"}
h="10vh" h="10vh"
@@ -250,19 +265,17 @@ export function Contract() {
bottom: "0px", bottom: "0px",
}} }}
> >
<Text>{ <Text>
t("total", {capfirst: true})} : {Intl.NumberFormat( {t("total", { capfirst: true })} :{" "}
"fr-FR", {Intl.NumberFormat("fr-FR", {
{style: "currency", currency: "EUR"} style: "currency",
).format(price)} currency: "EUR",
}).format(price)}
</Text> </Text>
<Button <Button aria-label={t("submit contract")} onClick={handleSubmit}>
aria-label={t('submit contract')} {t("submit contract")}
onClick={handleSubmit}
>
{t('submit contract')}
</Button> </Button>
</Overlay> </Overlay>
</Stack> </Stack>
) );
} }

View File

@@ -1,6 +1,10 @@
import type { Product } from "@/services/resources/products"; import type { Product } from "@/services/resources/products";
export function computePrices(values: [string, string | number][], products: Product[], nbShipment?: number) { export function computePrices(
values: [string, string | number][],
products: Product[],
nbShipment?: number,
) {
return values.reduce((prev, [key, value]) => { return values.reduce((prev, [key, value]) => {
const keyArray = key.split("-"); const keyArray = key.split("-");
const productId = Number(keyArray[keyArray.length - 1]); const productId = Number(keyArray[keyArray.length - 1]);
@@ -11,7 +15,9 @@ export function computePrices(values: [string, string | number][], products: Pro
const isRecurent = key.includes("recurrent") && nbShipment; const isRecurent = key.includes("recurrent") && nbShipment;
const productPrice = Number(product.price || product.price_kg); const productPrice = Number(product.price || product.price_kg);
const productQuantityUnit = product.unit === "2" ? 1 : 1000; const productQuantityUnit = product.unit === "2" ? 1 : 1000;
const productQuantity = Number(product.price ? Number(value) : Number(value) / productQuantityUnit); const productQuantity = Number(
return(prev + productPrice * productQuantity * (isRecurent ? nbShipment : 1)); product.price ? Number(value) : Number(value) / productQuantityUnit,
);
return prev + productPrice * productQuantity * (isRecurent ? nbShipment : 1);
}, 0); }, 0);
} }

View File

@@ -10,7 +10,7 @@ export default function Dashboard() {
<Tabs <Tabs
w={{ base: "100%", md: "80%", lg: "60%" }} w={{ base: "100%", md: "80%", lg: "60%" }}
orientation={"horizontal"} orientation={"horizontal"}
value={location.pathname.split('/')[2]} value={location.pathname.split("/")[2]}
defaultValue={"productors"} defaultValue={"productors"}
onChange={(value) => navigate(`/dashboard/${value}`)} onChange={(value) => navigate(`/dashboard/${value}`)}
> >

View File

@@ -19,36 +19,40 @@ export function Forms() {
const editId = useMemo(() => { const editId = useMemo(() => {
if (isEdit) { if (isEdit) {
return location.pathname.split("/")[3] return location.pathname.split("/")[3];
} }
return null return null;
}, [location, isEdit]) }, [location, isEdit]);
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
navigate(`/dashboard/forms${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(`/dashboard/forms${searchParams ? `?${searchParams.toString()}` : ""}`);
}, [navigate, searchParams]); }, [navigate, searchParams]);
const { isPending, data } = useGetForms(searchParams); const { isPending, data } = useGetForms(searchParams);
const { data: currentForm } = useGetForm(Number(editId), { enabled: !!editId }); const { data: currentForm } = useGetForm(Number(editId), {
enabled: !!editId,
});
const { data: allForms } = useGetForms(); const { data: allForms } = useGetForms();
const seasons = useMemo(() => { const seasons = useMemo(() => {
return allForms?.map((form: Form) => (form.season)) return allForms
.filter((season, index, array) => array.indexOf(season) === index) ?.map((form: Form) => form.season)
}, [allForms]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allForms]);
const productors = useMemo(() => { const productors = useMemo(() => {
return allForms?.map((form: Form) => (form.productor.name)) return allForms
.filter((productor, index, array) => array.indexOf(productor) === index) ?.map((form: Form) => form.productor.name)
}, [allForms]) .filter((productor, index, array) => array.indexOf(productor) === index);
}, [allForms]);
const createFormMutation = useCreateForm(); const createFormMutation = useCreateForm();
const editFormMutation = useEditForm(); const editFormMutation = useEditForm();
const handleCreateForm = useCallback(async (form: FormInputs) => { const handleCreateForm = useCallback(
if (!form.start || !form.end) async (form: FormInputs) => {
return; if (!form.start || !form.end) return;
await createFormMutation.mutateAsync({ await createFormMutation.mutateAsync({
...form, ...form,
start: form?.start, start: form?.start,
@@ -58,11 +62,13 @@ export function Forms() {
minimum_shipment_value: Number(form.minimum_shipment_value), minimum_shipment_value: Number(form.minimum_shipment_value),
}); });
closeModal(); closeModal();
}, [createFormMutation, closeModal]); },
[createFormMutation, closeModal],
);
const handleEditForm = useCallback(async (form: FormInputs, id?: number) => { const handleEditForm = useCallback(
if (!id) async (form: FormInputs, id?: number) => {
return; if (!id) return;
await editFormMutation.mutateAsync({ await editFormMutation.mutateAsync({
id: id, id: id,
form: { form: {
@@ -72,36 +78,32 @@ export function Forms() {
productor_id: Number(form.productor_id), productor_id: Number(form.productor_id),
referer_id: Number(form.referer_id), referer_id: Number(form.referer_id),
minimum_shipment_value: Number(form.minimum_shipment_value), minimum_shipment_value: Number(form.minimum_shipment_value),
} },
}); });
closeModal(); closeModal();
}, [editFormMutation, closeModal]); },
[editFormMutation, closeModal],
);
const onFilterChange = useCallback(( const onFilterChange = useCallback(
values: string[], (values: string[], filter: string) => {
filter: string setSearchParams((prev) => {
) => {
setSearchParams(prev => {
const params = new URLSearchParams(prev); const params = new URLSearchParams(prev);
params.delete(filter) params.delete(filter);
values.forEach(value => { values.forEach((value) => {
params.append(filter, value); params.append(filter, value);
}); });
return params; return params;
}); });
}, [setSearchParams]) },
[setSearchParams],
);
if (!data || isPending) if (!data || isPending)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
@@ -114,7 +116,9 @@ export function Forms() {
<ActionIcon <ActionIcon
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/forms/create${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/forms/create${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconPlus /> <IconPlus />
@@ -154,14 +158,9 @@ export function Forms() {
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
{ {data.map((form) => (
data.map((form) => ( <FormRow form={form} key={form.id} />
<FormRow ))}
form={form}
key={form.id}
/>
))
}
</Table.Tbody> </Table.Tbody>
</Table> </Table>
</ScrollArea> </ScrollArea>

View File

@@ -9,13 +9,13 @@ export function Home() {
return ( return (
<Flex gap="md" wrap="wrap" justify="center"> <Flex gap="md" wrap="wrap" justify="center">
{ {allForms && allForms?.length > 0 ? (
allForms && allForms?.length > 0 ? allForms.map((form: Form) => <FormCard form={form} key={form.id} />)
allForms.map((form: Form) => ( ) : (
<FormCard form={form} key={form.id}/> <Text mt="lg" size="lg">
)) : {t("there is no contract for now", { capfirst: true })}
<Text mt="lg" size="lg">{t("there is no contract for now",{capfirst: true})}</Text> </Text>
} )}
</Flex> </Flex>
); );
} }

View File

@@ -4,16 +4,16 @@ import { IconHome } from "@tabler/icons-react";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
export function NotFound() { export function NotFound() {
const navigate = useNavigate() const navigate = useNavigate();
return ( return (
<Stack justify="center" align="center"> <Stack justify="center" align="center">
<Title order={2}>{t("oops", { capfirst: true })}</Title> <Title order={2}>{t("oops", { capfirst: true })}</Title>
<Text>{t('this page does not exists', {capfirst: true})}</Text> <Text>{t("this page does not exists", { capfirst: true })}</Text>
<Tooltip label={t('back to home', {capfirst: true})}> <Tooltip label={t("back to home", { capfirst: true })}>
<ActionIcon <ActionIcon
aria-label={t("back to home", { capfirst: true })} aria-label={t("back to home", { capfirst: true })}
onClick={() => { onClick={() => {
navigate('/') navigate("/");
}} }}
> >
<IconHome /> <IconHome />

View File

@@ -1,6 +1,11 @@
import { ActionIcon, Group, Loader, ScrollArea, Stack, Table, Title, Tooltip } from "@mantine/core"; import { ActionIcon, Group, Loader, ScrollArea, Stack, Table, Title, Tooltip } from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { useCreateProductor, useEditProductor, useGetProductor, useGetProductors } from "@/services/api"; import {
useCreateProductor,
useEditProductor,
useGetProductor,
useGetProductors,
} from "@/services/api";
import { IconPlus } from "@tabler/icons-react"; import { IconPlus } from "@tabler/icons-react";
import ProductorRow from "@/components/Productors/Row"; import ProductorRow from "@/components/Productors/Row";
import { useLocation, useNavigate, useSearchParams } from "react-router"; import { useLocation, useNavigate, useSearchParams } from "react-router";
@@ -19,69 +24,76 @@ export default function Productors() {
const editId = useMemo(() => { const editId = useMemo(() => {
if (isEdit) { if (isEdit) {
return location.pathname.split("/")[3] return location.pathname.split("/")[3];
} }
return null return null;
}, [location, isEdit]) }, [location, isEdit]);
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
navigate(`/dashboard/productors${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(`/dashboard/productors${searchParams ? `?${searchParams.toString()}` : ""}`);
}, [navigate, searchParams]); }, [navigate, searchParams]);
const { data: productors, isPending } = useGetProductors(searchParams); const { data: productors, isPending } = useGetProductors(searchParams);
const { data: currentProductor } = useGetProductor(Number(editId), { enabled: !!editId }); const { data: currentProductor } = useGetProductor(Number(editId), {
enabled: !!editId,
});
const { data: allProductors } = useGetProductors(); const { data: allProductors } = useGetProductors();
const names = useMemo(() => { const names = useMemo(() => {
return allProductors?.map((productor: Productor) => (productor.name)) return allProductors
.filter((season, index, array) => array.indexOf(season) === index) ?.map((productor: Productor) => productor.name)
}, [allProductors]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allProductors]);
const types = useMemo(() => { const types = useMemo(() => {
return allProductors?.map((productor: Productor) => (productor.type)) return allProductors
.filter((productor, index, array) => array.indexOf(productor) === index) ?.map((productor: Productor) => productor.type)
}, [allProductors]) .filter((productor, index, array) => array.indexOf(productor) === index);
}, [allProductors]);
const createProductorMutation = useCreateProductor(); const createProductorMutation = useCreateProductor();
const editProductorMutation = useEditProductor(); const editProductorMutation = useEditProductor();
const handleCreateProductor = useCallback(async (productor: ProductorInputs) => { const handleCreateProductor = useCallback(
async (productor: ProductorInputs) => {
await createProductorMutation.mutateAsync({ await createProductorMutation.mutateAsync({
...productor ...productor,
}); });
closeModal(); closeModal();
}, [createProductorMutation, closeModal]); },
[createProductorMutation, closeModal],
);
const handleEditProductor = useCallback(async (productor: ProductorInputs, id?: number) => { const handleEditProductor = useCallback(
if (!id) async (productor: ProductorInputs, id?: number) => {
return; if (!id) return;
await editProductorMutation.mutateAsync({ await editProductorMutation.mutateAsync({
id: id, id: id,
productor: productor productor: productor,
}); });
closeModal(); closeModal();
}, [editProductorMutation, closeModal]); },
[editProductorMutation, closeModal],
);
const onFilterChange = useCallback((values: string[], filter: string) => { const onFilterChange = useCallback(
setSearchParams(prev => { (values: string[], filter: string) => {
setSearchParams((prev) => {
const params = new URLSearchParams(prev); const params = new URLSearchParams(prev);
params.delete(filter) params.delete(filter);
values.forEach(value => { values.forEach((value) => {
params.append(filter, value); params.append(filter, value);
}); });
return params; return params;
}); });
}, [setSearchParams]) },
[setSearchParams],
);
if (!productors || isPending) if (!productors || isPending)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
@@ -94,7 +106,9 @@ export default function Productors() {
<ActionIcon <ActionIcon
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/productors/create${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/productors/create${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconPlus /> <IconPlus />
@@ -132,14 +146,9 @@ export default function Productors() {
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
{ {productors.map((productor) => (
productors.map((productor) => ( <ProductorRow productor={productor} key={productor.id} />
<ProductorRow ))}
productor={productor}
key={productor.id}
/>
))
}
</Table.Tbody> </Table.Tbody>
</Table> </Table>
</ScrollArea> </ScrollArea>

View File

@@ -6,7 +6,11 @@ import ProductRow from "@/components/Products/Row";
import { useLocation, useNavigate, useSearchParams } from "react-router"; import { useLocation, useNavigate, useSearchParams } from "react-router";
import { ProductModal } from "@/components/Products/Modal"; import { ProductModal } from "@/components/Products/Modal";
import { useCallback, useMemo } from "react"; import { useCallback, useMemo } from "react";
import { productCreateFromProductInputs, type Product, type ProductInputs } from "@/services/resources/products"; import {
productCreateFromProductInputs,
type Product,
type ProductInputs,
} from "@/services/resources/products";
import ProductsFilters from "@/components/Products/Filter"; import ProductsFilters from "@/components/Products/Filter";
export default function Products() { export default function Products() {
@@ -19,67 +23,74 @@ export default function Products() {
const editId = useMemo(() => { const editId = useMemo(() => {
if (isEdit) { if (isEdit) {
return location.pathname.split("/")[3] return location.pathname.split("/")[3];
} }
return null return null;
}, [location, isEdit]) }, [location, isEdit]);
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
navigate(`/dashboard/products${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(`/dashboard/products${searchParams ? `?${searchParams.toString()}` : ""}`);
}, [navigate, searchParams]); }, [navigate, searchParams]);
const { data: products, isPending } = useGetProducts(searchParams); const { data: products, isPending } = useGetProducts(searchParams);
const { data: currentProduct } = useGetProduct(Number(editId), { enabled: !!editId }); const { data: currentProduct } = useGetProduct(Number(editId), {
enabled: !!editId,
});
const { data: allProducts } = useGetProducts(); const { data: allProducts } = useGetProducts();
const names = useMemo(() => { const names = useMemo(() => {
return allProducts?.map((product: Product) => (product.name)) return allProducts
.filter((season, index, array) => array.indexOf(season) === index) ?.map((product: Product) => product.name)
}, [allProducts]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allProducts]);
const productors = useMemo(() => { const productors = useMemo(() => {
return allProducts?.map((product: Product) => (product.productor.name)) return allProducts
.filter((productor, index, array) => array.indexOf(productor) === index) ?.map((product: Product) => product.productor.name)
}, [allProducts]) .filter((productor, index, array) => array.indexOf(productor) === index);
}, [allProducts]);
const createProductMutation = useCreateProduct(); const createProductMutation = useCreateProduct();
const editProductMutation = useEditProduct(); const editProductMutation = useEditProduct();
const handleCreateProduct = useCallback(async (product: ProductInputs) => { const handleCreateProduct = useCallback(
async (product: ProductInputs) => {
await createProductMutation.mutateAsync(productCreateFromProductInputs(product)); await createProductMutation.mutateAsync(productCreateFromProductInputs(product));
closeModal(); closeModal();
}, [createProductMutation, closeModal]); },
[createProductMutation, closeModal],
);
const handleEditProduct = useCallback(async (product: ProductInputs, id?: number) => { const handleEditProduct = useCallback(
if (!id) async (product: ProductInputs, id?: number) => {
return; if (!id) return;
await editProductMutation.mutateAsync({ await editProductMutation.mutateAsync({
id: id, id: id,
product: productCreateFromProductInputs(product) product: productCreateFromProductInputs(product),
}); });
closeModal(); closeModal();
}, [editProductMutation, closeModal]); },
[editProductMutation, closeModal],
);
const onFilterChange = useCallback((values: string[], filter: string) => { const onFilterChange = useCallback(
setSearchParams(prev => { (values: string[], filter: string) => {
setSearchParams((prev) => {
const params = new URLSearchParams(prev); const params = new URLSearchParams(prev);
params.delete(filter); params.delete(filter);
values.forEach(value => { values.forEach((value) => {
params.append(filter, value); params.append(filter, value);
}); });
return params; return params;
}); });
}, [setSearchParams]) },
[setSearchParams],
);
if (!products || isPending) if (!products || isPending)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
@@ -92,7 +103,9 @@ export default function Products() {
<ActionIcon <ActionIcon
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/products/create${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/products/create${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconPlus /> <IconPlus />
@@ -132,14 +145,9 @@ export default function Products() {
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
{ {products.map((product) => (
products.map((product) => ( <ProductRow product={product} key={product.id} />
<ProductRow ))}
product={product}
key={product.id}
/>
))
}
</Table.Tbody> </Table.Tbody>
</Table> </Table>
</ScrollArea> </ScrollArea>

View File

@@ -1,11 +1,20 @@
import { ActionIcon, Group, Loader, ScrollArea, Stack, Table, Title, Tooltip } from "@mantine/core"; import { ActionIcon, Group, Loader, ScrollArea, Stack, Table, Title, Tooltip } from "@mantine/core";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
import { useCreateShipment, useEditShipment, useGetShipment, useGetShipments } from "@/services/api"; import {
useCreateShipment,
useEditShipment,
useGetShipment,
useGetShipments,
} from "@/services/api";
import { IconPlus } from "@tabler/icons-react"; import { IconPlus } from "@tabler/icons-react";
import ShipmentRow from "@/components/Shipments/Row"; import ShipmentRow from "@/components/Shipments/Row";
import { useLocation, useNavigate, useSearchParams } from "react-router"; import { useLocation, useNavigate, useSearchParams } from "react-router";
import { useCallback, useMemo } from "react"; import { useCallback, useMemo } from "react";
import { shipmentCreateFromShipmentInputs, type Shipment, type ShipmentInputs } from "@/services/resources/shipments"; import {
shipmentCreateFromShipmentInputs,
type Shipment,
type ShipmentInputs,
} from "@/services/resources/shipments";
import ShipmentModal from "@/components/Shipments/Modal"; import ShipmentModal from "@/components/Shipments/Modal";
import ShipmentsFilters from "@/components/Shipments/Filter"; import ShipmentsFilters from "@/components/Shipments/Filter";
@@ -19,67 +28,74 @@ export default function Shipments() {
const editId = useMemo(() => { const editId = useMemo(() => {
if (isEdit) { if (isEdit) {
return location.pathname.split("/")[3] return location.pathname.split("/")[3];
} }
return null return null;
}, [location, isEdit]) }, [location, isEdit]);
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
navigate(`/dashboard/shipments${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(`/dashboard/shipments${searchParams ? `?${searchParams.toString()}` : ""}`);
}, [navigate, searchParams]); }, [navigate, searchParams]);
const { data: shipments, isPending } = useGetShipments(searchParams); const { data: shipments, isPending } = useGetShipments(searchParams);
const { data: currentShipment } = useGetShipment(Number(editId), { enabled: !!editId }); const { data: currentShipment } = useGetShipment(Number(editId), {
enabled: !!editId,
});
const { data: allShipments } = useGetShipments(); const { data: allShipments } = useGetShipments();
const names = useMemo(() => { const names = useMemo(() => {
return allShipments?.map((shipment: Shipment) => (shipment.name)) return allShipments
.filter((season, index, array) => array.indexOf(season) === index) ?.map((shipment: Shipment) => shipment.name)
}, [allShipments]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allShipments]);
const forms = useMemo(() => { const forms = useMemo(() => {
return allShipments?.map((shipment: Shipment) => (shipment.form.name)) return allShipments
.filter((season, index, array) => array.indexOf(season) === index) ?.map((shipment: Shipment) => shipment.form.name)
}, [allShipments]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allShipments]);
const createShipmentMutation = useCreateShipment(); const createShipmentMutation = useCreateShipment();
const editShipmentMutation = useEditShipment(); const editShipmentMutation = useEditShipment();
const handleCreateShipment = useCallback(async (shipment: ShipmentInputs) => { const handleCreateShipment = useCallback(
async (shipment: ShipmentInputs) => {
await createShipmentMutation.mutateAsync(shipmentCreateFromShipmentInputs(shipment)); await createShipmentMutation.mutateAsync(shipmentCreateFromShipmentInputs(shipment));
closeModal(); closeModal();
}, [createShipmentMutation, closeModal]); },
[createShipmentMutation, closeModal],
);
const handleEditShipment = useCallback(async (shipment: ShipmentInputs, id?: number) => { const handleEditShipment = useCallback(
if (!id) async (shipment: ShipmentInputs, id?: number) => {
return; if (!id) return;
await editShipmentMutation.mutateAsync({ await editShipmentMutation.mutateAsync({
id: id, id: id,
shipment: shipmentCreateFromShipmentInputs(shipment) shipment: shipmentCreateFromShipmentInputs(shipment),
}); });
closeModal(); closeModal();
}, [editShipmentMutation, closeModal]); },
[editShipmentMutation, closeModal],
);
const onFilterChange = useCallback((values: string[], filter: string) => { const onFilterChange = useCallback(
setSearchParams(prev => { (values: string[], filter: string) => {
setSearchParams((prev) => {
const params = new URLSearchParams(prev); const params = new URLSearchParams(prev);
params.delete(filter) params.delete(filter);
values.forEach(value => { values.forEach((value) => {
params.append(filter, value); params.append(filter, value);
}); });
return params; return params;
}); });
}, [setSearchParams]) },
[setSearchParams],
);
if (!shipments || isPending) if (!shipments || isPending)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
@@ -92,7 +108,9 @@ export default function Shipments() {
<ActionIcon <ActionIcon
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/shipments/create${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/shipments/create${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconPlus /> <IconPlus />
@@ -129,14 +147,9 @@ export default function Shipments() {
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
{ {shipments.map((shipment) => (
shipments.map((shipment) => ( <ShipmentRow shipment={shipment} key={shipment.id} />
<ShipmentRow ))}
shipment={shipment}
key={shipment.id}
/>
))
}
</Table.Tbody> </Table.Tbody>
</Table> </Table>
</ScrollArea> </ScrollArea>

View File

@@ -1,5 +1,3 @@
export default function Templates() { export default function Templates() {
return ( return <></>;
<></>
);
} }

View File

@@ -19,63 +19,69 @@ export default function Users() {
const editId = useMemo(() => { const editId = useMemo(() => {
if (isEdit) { if (isEdit) {
return location.pathname.split("/")[3] return location.pathname.split("/")[3];
} }
return null return null;
}, [location, isEdit]) }, [location, isEdit]);
const closeModal = useCallback(() => { const closeModal = useCallback(() => {
navigate(`/dashboard/users${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(`/dashboard/users${searchParams ? `?${searchParams.toString()}` : ""}`);
}, [navigate, searchParams]); }, [navigate, searchParams]);
const { data: users, isPending } = useGetUsers(searchParams); const { data: users, isPending } = useGetUsers(searchParams);
const { data: currentUser } = useGetUser(Number(editId), { enabled: !!editId }); const { data: currentUser } = useGetUser(Number(editId), {
enabled: !!editId,
});
const { data: allUsers } = useGetUsers(); const { data: allUsers } = useGetUsers();
const names = useMemo(() => { const names = useMemo(() => {
return allUsers?.map((user: User) => (user.name)) return allUsers
.filter((season, index, array) => array.indexOf(season) === index) ?.map((user: User) => user.name)
}, [allUsers]) .filter((season, index, array) => array.indexOf(season) === index);
}, [allUsers]);
const createUserMutation = useCreateUser(); const createUserMutation = useCreateUser();
const editUserMutation = useEditUser(); const editUserMutation = useEditUser();
const handleCreateUser = useCallback(async (user: UserInputs) => { const handleCreateUser = useCallback(
async (user: UserInputs) => {
await createUserMutation.mutateAsync(user); await createUserMutation.mutateAsync(user);
closeModal(); closeModal();
}, [createUserMutation, closeModal]); },
[createUserMutation, closeModal],
);
const handleEditUser = useCallback(async (user: UserInputs, id?: number) => { const handleEditUser = useCallback(
if (!id) async (user: UserInputs, id?: number) => {
return; if (!id) return;
await editUserMutation.mutateAsync({ await editUserMutation.mutateAsync({
id: id, id: id,
user: user user: user,
}); });
closeModal(); closeModal();
}, [editUserMutation, closeModal]); },
[editUserMutation, closeModal],
);
const onFilterChange = useCallback((values: string[], filter: string) => { const onFilterChange = useCallback(
setSearchParams(prev => { (values: string[], filter: string) => {
setSearchParams((prev) => {
const params = new URLSearchParams(prev); const params = new URLSearchParams(prev);
params.delete(filter); params.delete(filter);
values.forEach(value => { values.forEach((value) => {
params.append(filter, value); params.append(filter, value);
}); });
return params; return params;
}); });
}, [setSearchParams]) },
[setSearchParams],
);
if (!users || isPending) if (!users || isPending)
return ( return (
<Group <Group align="center" justify="center" h="80vh" w="100%">
align="center"
justify="center"
h="80vh"
w="100%"
>
<Loader color="pink" /> <Loader color="pink" />
</Group> </Group>
); );
@@ -88,7 +94,9 @@ export default function Users() {
<ActionIcon <ActionIcon
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
navigate(`/dashboard/users/create${searchParams ? `?${searchParams.toString()}` : ""}`); navigate(
`/dashboard/users/create${searchParams ? `?${searchParams.toString()}` : ""}`,
);
}} }}
> >
<IconPlus /> <IconPlus />
@@ -123,14 +131,9 @@ export default function Users() {
</Table.Tr> </Table.Tr>
</Table.Thead> </Table.Thead>
<Table.Tbody> <Table.Tbody>
{ {users.map((user) => (
users.map((user) => ( <UserRow user={user} key={user.id} />
<UserRow ))}
user={user}
key={user.id}
/>
))
}
</Table.Tbody> </Table.Tbody>
</Table> </Table>
</ScrollArea> </ScrollArea>

View File

@@ -1,6 +1,4 @@
import { import { createBrowserRouter } from "react-router";
createBrowserRouter,
} from "react-router";
import Root from "@/root"; import Root from "@/root";
import { Home } from "@/pages/Home"; import { Home } from "@/pages/Home";
@@ -22,7 +20,8 @@ export const router = createBrowserRouter([
{ index: true, Component: Home }, { index: true, Component: Home },
{ path: "/forms", Component: Forms }, { path: "/forms", Component: Forms },
{ {
path: "/dashboard", Component: Dashboard, path: "/dashboard",
Component: Dashboard,
children: [ children: [
{ path: "productors", Component: Productors }, { path: "productors", Component: Productors },
{ path: "productors/create", Component: Productors }, { path: "productors/create", Component: Productors },
@@ -40,7 +39,7 @@ export const router = createBrowserRouter([
{ path: "shipments", Component: Shipments }, { path: "shipments", Component: Shipments },
{ path: "shipments/:id/edit", Component: Shipments }, { path: "shipments/:id/edit", Component: Shipments },
{ path: "shipments/create", Component: Shipments }, { path: "shipments/create", Component: Shipments },
] ],
}, },
{ path: "/form/:id", Component: Contract }, { path: "/form/:id", Component: Contract },
], ],

View File

@@ -1,8 +1,18 @@
import { useMutation, useQuery, useQueryClient,type DefinedInitialDataOptions,type UseQueryResult } from "@tanstack/react-query"; import {
useMutation,
useQuery,
useQueryClient,
type DefinedInitialDataOptions,
type UseQueryResult,
} from "@tanstack/react-query";
import { Config } from "@/config/config"; import { Config } from "@/config/config";
import type { Form, FormCreate, FormEditPayload } from "@/services/resources/forms"; import type { Form, FormCreate, FormEditPayload } from "@/services/resources/forms";
import type { Shipment, ShipmentCreate, ShipmentEditPayload } from "@/services/resources/shipments"; import type { Shipment, ShipmentCreate, ShipmentEditPayload } from "@/services/resources/shipments";
import type { Productor, ProductorCreate, ProductorEditPayload } from "@/services/resources/productors"; import type {
Productor,
ProductorCreate,
ProductorEditPayload,
} from "@/services/resources/productors";
import type { User, UserCreate, UserEditPayload } from "@/services/resources/users"; import type { User, UserCreate, UserEditPayload } from "@/services/resources/users";
import type { Product, ProductCreate, ProductEditPayload } from "./resources/products"; import type { Product, ProductCreate, ProductEditPayload } from "./resources/products";
import type { ContractCreate } from "./resources/contracts"; import type { ContractCreate } from "./resources/contracts";
@@ -10,37 +20,37 @@ import { notifications } from "@mantine/notifications";
import { t } from "@/config/i18n"; import { t } from "@/config/i18n";
export function useGetShipments(filters?: URLSearchParams): UseQueryResult<Shipment[], Error> { export function useGetShipments(filters?: URLSearchParams): UseQueryResult<Shipment[], Error> {
const queryString = filters?.toString() const queryString = filters?.toString();
return useQuery<Shipment[]>({ return useQuery<Shipment[]>({
queryKey: ['shipments', queryString], queryKey: ["shipments", queryString],
queryFn: () => ( queryFn: () =>
fetch(`${Config.backend_uri}/shipments${filters ? `?${queryString}` : ""}`) fetch(`${Config.backend_uri}/shipments${filters ? `?${queryString}` : ""}`).then(
.then((res) => res.json()) (res) => res.json(),
), ),
}); });
} }
export function useGetShipment(id?: number, options?: Partial<DefinedInitialDataOptions<Shipment, Error, Shipment, readonly unknown[]>>): UseQueryResult<Shipment, Error> { export function useGetShipment(
id?: number,
options?: Partial<DefinedInitialDataOptions<Shipment, Error, Shipment, readonly unknown[]>>,
): UseQueryResult<Shipment, Error> {
return useQuery<Shipment>({ return useQuery<Shipment>({
queryKey: ['shipment'], queryKey: ["shipment"],
queryFn: () => ( queryFn: () => fetch(`${Config.backend_uri}/shipments/${id}`).then((res) => res.json()),
fetch(`${Config.backend_uri}/shipments/${id}`)
.then((res) => res.json())
),
enabled: !!id, enabled: !!id,
...options, ...options,
}); });
} }
export function useCreateShipment() { export function useCreateShipment() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newShipment: ShipmentCreate) => { mutationFn: (newShipment: ShipmentCreate) => {
return fetch(`${Config.backend_uri}/shipments`, { return fetch(`${Config.backend_uri}/shipments`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newShipment), body: JSON.stringify(newShipment),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -50,27 +60,27 @@ export function useCreateShipment() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully created shipment", { capfirst: true }), message: t("successfully created shipment", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['shipments'] }) await queryClient.invalidateQueries({ queryKey: ["shipments"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing shipment`, { capfirst: true }), message: error?.message || t(`error editing shipment`, { capfirst: true }),
color: "red" color: "red",
});
},
}); });
}
})
} }
export function useEditShipment() { export function useEditShipment() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ shipment, id }: ShipmentEditPayload) => { mutationFn: ({ shipment, id }: ShipmentEditPayload) => {
return fetch(`${Config.backend_uri}/shipments/${id}`, { return fetch(`${Config.backend_uri}/shipments/${id}`, {
method: 'PUT', method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(shipment), body: JSON.stringify(shipment),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -80,26 +90,26 @@ export function useEditShipment() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully edited shipment", { capfirst: true }), message: t("successfully edited shipment", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['shipments'] }) await queryClient.invalidateQueries({ queryKey: ["shipments"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing shipment`, { capfirst: true }), message: error?.message || t(`error editing shipment`, { capfirst: true }),
color: "red" color: "red",
});
},
}); });
}
})
} }
export function useDeleteShipment() { export function useDeleteShipment() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (id: number) => { mutationFn: (id: number) => {
return fetch(`${Config.backend_uri}/shipments/${id}`, { return fetch(`${Config.backend_uri}/shipments/${id}`, {
method: 'DELETE', method: "DELETE",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
}).then((res) => res.json()); }).then((res) => res.json());
}, },
@@ -108,50 +118,50 @@ export function useDeleteShipment() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully deleted shipment", { capfirst: true }), message: t("successfully deleted shipment", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['shipments'] }) await queryClient.invalidateQueries({ queryKey: ["shipments"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error deleting shipment`, { capfirst: true }), message: error?.message || t(`error deleting shipment`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useGetProductors(filters?: URLSearchParams): UseQueryResult<Productor[], Error> { export function useGetProductors(filters?: URLSearchParams): UseQueryResult<Productor[], Error> {
const queryString = filters?.toString() const queryString = filters?.toString();
return useQuery<Productor[]>({ return useQuery<Productor[]>({
queryKey: ['productors', queryString], queryKey: ["productors", queryString],
queryFn: () => ( queryFn: () =>
fetch(`${Config.backend_uri}/productors${filters ? `?${queryString}` : ""}`) fetch(`${Config.backend_uri}/productors${filters ? `?${queryString}` : ""}`).then(
.then((res) => res.json()) (res) => res.json(),
), ),
}); });
} }
export function useGetProductor(id?: number, options?: Partial<DefinedInitialDataOptions<Productor, Error, Productor, readonly unknown[]>>) { export function useGetProductor(
id?: number,
options?: Partial<DefinedInitialDataOptions<Productor, Error, Productor, readonly unknown[]>>,
) {
return useQuery<Productor>({ return useQuery<Productor>({
queryKey: ['productor'], queryKey: ["productor"],
queryFn: () => ( queryFn: () => fetch(`${Config.backend_uri}/productors/${id}`).then((res) => res.json()),
fetch(`${Config.backend_uri}/productors/${id}`)
.then((res) => res.json())
),
enabled: !!id, enabled: !!id,
...options, ...options,
}); });
} }
export function useCreateProductor() { export function useCreateProductor() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newProductor: ProductorCreate) => { mutationFn: (newProductor: ProductorCreate) => {
return fetch(`${Config.backend_uri}/productors`, { return fetch(`${Config.backend_uri}/productors`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newProductor), body: JSON.stringify(newProductor),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -161,27 +171,27 @@ export function useCreateProductor() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully created productor", { capfirst: true }), message: t("successfully created productor", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['productors'] }) await queryClient.invalidateQueries({ queryKey: ["productors"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing productor`, { capfirst: true }), message: error?.message || t(`error editing productor`, { capfirst: true }),
color: "red" color: "red",
});
},
}); });
}
})
} }
export function useEditProductor() { export function useEditProductor() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ productor, id }: ProductorEditPayload) => { mutationFn: ({ productor, id }: ProductorEditPayload) => {
return fetch(`${Config.backend_uri}/productors/${id}`, { return fetch(`${Config.backend_uri}/productors/${id}`, {
method: 'PUT', method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(productor), body: JSON.stringify(productor),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -191,26 +201,26 @@ export function useEditProductor() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully edited productor", { capfirst: true }), message: t("successfully edited productor", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['productors'] }) await queryClient.invalidateQueries({ queryKey: ["productors"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing productor`, { capfirst: true }), message: error?.message || t(`error editing productor`, { capfirst: true }),
color: "red" color: "red",
});
},
}); });
}
})
} }
export function useDeleteProductor() { export function useDeleteProductor() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (id: number) => { mutationFn: (id: number) => {
return fetch(`${Config.backend_uri}/productors/${id}`, { return fetch(`${Config.backend_uri}/productors/${id}`, {
method: 'DELETE', method: "DELETE",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
}).then((res) => res.json()); }).then((res) => res.json());
}, },
@@ -219,68 +229,68 @@ export function useDeleteProductor() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully deleted productor", { capfirst: true }), message: t("successfully deleted productor", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['productors'] }) await queryClient.invalidateQueries({ queryKey: ["productors"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error deleting productor`, { capfirst: true }), message: error?.message || t(`error deleting productor`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useGetForm(id?: number, options?: Partial<DefinedInitialDataOptions<Form, Error, Form, readonly unknown[]>>) { export function useGetForm(
id?: number,
options?: Partial<DefinedInitialDataOptions<Form, Error, Form, readonly unknown[]>>,
) {
return useQuery<Form>({ return useQuery<Form>({
queryKey: ['form'], queryKey: ["form"],
queryFn: () => ( queryFn: () => fetch(`${Config.backend_uri}/forms/${id}`).then((res) => res.json()),
fetch(`${Config.backend_uri}/forms/${id}`)
.then((res) => res.json())
),
enabled: !!id, enabled: !!id,
...options, ...options,
}); });
} }
export function useGetForms(filters?: URLSearchParams): UseQueryResult<Form[], Error> { export function useGetForms(filters?: URLSearchParams): UseQueryResult<Form[], Error> {
const queryString = filters?.toString() const queryString = filters?.toString();
return useQuery<Form[]>({ return useQuery<Form[]>({
queryKey: ['forms', queryString], queryKey: ["forms", queryString],
queryFn: () => ( queryFn: () =>
fetch(`${Config.backend_uri}/forms${filters ? `?${queryString}` : ""}`) fetch(`${Config.backend_uri}/forms${filters ? `?${queryString}` : ""}`).then((res) =>
.then((res) => res.json()) res.json(),
), ),
}); });
} }
export function useCreateForm() { export function useCreateForm() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newForm: FormCreate) => { mutationFn: (newForm: FormCreate) => {
return fetch(`${Config.backend_uri}/forms`, { return fetch(`${Config.backend_uri}/forms`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newForm), body: JSON.stringify(newForm),
}).then((res) => res.json()); }).then((res) => res.json());
}, },
onSuccess: async () => { onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ['forms'] }) await queryClient.invalidateQueries({ queryKey: ["forms"] });
} },
}); });
} }
export function useDeleteForm() { export function useDeleteForm() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (id: number) => { mutationFn: (id: number) => {
return fetch(`${Config.backend_uri}/forms/${id}`, { return fetch(`${Config.backend_uri}/forms/${id}`, {
method: 'DELETE', method: "DELETE",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
}).then((res) => res.json()); }).then((res) => res.json());
}, },
@@ -289,27 +299,27 @@ export function useDeleteForm() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully deleted form", { capfirst: true }), message: t("successfully deleted form", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['forms'] }) await queryClient.invalidateQueries({ queryKey: ["forms"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error deleting form`, { capfirst: true }), message: error?.message || t(`error deleting form`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useEditForm() { export function useEditForm() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ id, form }: FormEditPayload) => { mutationFn: ({ id, form }: FormEditPayload) => {
return fetch(`${Config.backend_uri}/forms/${id}`, { return fetch(`${Config.backend_uri}/forms/${id}`, {
method: 'PUT', method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(form), body: JSON.stringify(form),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -319,50 +329,50 @@ export function useEditForm() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully edited form", { capfirst: true }), message: t("successfully edited form", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['forms'] }) await queryClient.invalidateQueries({ queryKey: ["forms"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing form`, { capfirst: true }), message: error?.message || t(`error editing form`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useGetProduct(id?: number, options?: Partial<DefinedInitialDataOptions<Product, Error, Product, readonly unknown[]>>) { export function useGetProduct(
id?: number,
options?: Partial<DefinedInitialDataOptions<Product, Error, Product, readonly unknown[]>>,
) {
return useQuery<Product>({ return useQuery<Product>({
queryKey: ['product'], queryKey: ["product"],
queryFn: () => ( queryFn: () => fetch(`${Config.backend_uri}/products/${id}`).then((res) => res.json()),
fetch(`${Config.backend_uri}/products/${id}`)
.then((res) => res.json())
),
enabled: !!id, enabled: !!id,
...options, ...options,
}); });
} }
export function useGetProducts(filters?: URLSearchParams): UseQueryResult<Product[], Error> { export function useGetProducts(filters?: URLSearchParams): UseQueryResult<Product[], Error> {
const queryString = filters?.toString() const queryString = filters?.toString();
return useQuery<Product[]>({ return useQuery<Product[]>({
queryKey: ['products', queryString], queryKey: ["products", queryString],
queryFn: () => ( queryFn: () =>
fetch(`${Config.backend_uri}/products${filters ? `?${queryString}` : ""}`) fetch(`${Config.backend_uri}/products${filters ? `?${queryString}` : ""}`).then((res) =>
.then((res) => res.json()) res.json(),
), ),
}); });
} }
export function useCreateProduct() { export function useCreateProduct() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newProduct: ProductCreate) => { mutationFn: (newProduct: ProductCreate) => {
return fetch(`${Config.backend_uri}/products`, { return fetch(`${Config.backend_uri}/products`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newProduct), body: JSON.stringify(newProduct),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -372,26 +382,26 @@ export function useCreateProduct() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully created product", { capfirst: true }), message: t("successfully created product", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['products'] }) await queryClient.invalidateQueries({ queryKey: ["products"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing product`, { capfirst: true }), message: error?.message || t(`error editing product`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useDeleteProduct() { export function useDeleteProduct() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (id: number) => { mutationFn: (id: number) => {
return fetch(`${Config.backend_uri}/products/${id}`, { return fetch(`${Config.backend_uri}/products/${id}`, {
method: 'DELETE', method: "DELETE",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
}).then((res) => res.json()); }).then((res) => res.json());
}, },
@@ -400,27 +410,27 @@ export function useDeleteProduct() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully deleted product", { capfirst: true }), message: t("successfully deleted product", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['products'] }) await queryClient.invalidateQueries({ queryKey: ["products"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error deleting product`, { capfirst: true }), message: error?.message || t(`error deleting product`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useEditProduct() { export function useEditProduct() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ id, product }: ProductEditPayload) => { mutationFn: ({ id, product }: ProductEditPayload) => {
return fetch(`${Config.backend_uri}/products/${id}`, { return fetch(`${Config.backend_uri}/products/${id}`, {
method: 'PUT', method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(product), body: JSON.stringify(product),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -430,50 +440,50 @@ export function useEditProduct() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully edited product", { capfirst: true }), message: t("successfully edited product", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['products'] }) await queryClient.invalidateQueries({ queryKey: ["products"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing product`, { capfirst: true }), message: error?.message || t(`error editing product`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useGetUser(id?: number, options?: Partial<DefinedInitialDataOptions<User, Error, User, readonly unknown[]>>) { export function useGetUser(
id?: number,
options?: Partial<DefinedInitialDataOptions<User, Error, User, readonly unknown[]>>,
) {
return useQuery<User>({ return useQuery<User>({
queryKey: ['user'], queryKey: ["user"],
queryFn: () => ( queryFn: () => fetch(`${Config.backend_uri}/users/${id}`).then((res) => res.json()),
fetch(`${Config.backend_uri}/users/${id}`)
.then((res) => res.json())
),
enabled: !!id, enabled: !!id,
...options, ...options,
}); });
} }
export function useGetUsers(filters?: URLSearchParams): UseQueryResult<User[], Error> { export function useGetUsers(filters?: URLSearchParams): UseQueryResult<User[], Error> {
const queryString = filters?.toString() const queryString = filters?.toString();
return useQuery<User[]>({ return useQuery<User[]>({
queryKey: ['users', queryString], queryKey: ["users", queryString],
queryFn: () => ( queryFn: () =>
fetch(`${Config.backend_uri}/users${filters ? `?${queryString}` : ""}`) fetch(`${Config.backend_uri}/users${filters ? `?${queryString}` : ""}`).then((res) =>
.then((res) => res.json()) res.json(),
), ),
}); });
} }
export function useCreateUser() { export function useCreateUser() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newUser: UserCreate) => { mutationFn: (newUser: UserCreate) => {
return fetch(`${Config.backend_uri}/users`, { return fetch(`${Config.backend_uri}/users`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newUser), body: JSON.stringify(newUser),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -483,26 +493,26 @@ export function useCreateUser() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully created user", { capfirst: true }), message: t("successfully created user", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['users'] }) await queryClient.invalidateQueries({ queryKey: ["users"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing user`, { capfirst: true }), message: error?.message || t(`error editing user`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useDeleteUser() { export function useDeleteUser() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (id: number) => { mutationFn: (id: number) => {
return fetch(`${Config.backend_uri}/users/${id}`, { return fetch(`${Config.backend_uri}/users/${id}`, {
method: 'DELETE', method: "DELETE",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
}).then((res) => res.json()); }).then((res) => res.json());
}, },
@@ -511,27 +521,27 @@ export function useDeleteUser() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully deleted user", { capfirst: true }), message: t("successfully deleted user", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['users'] }) await queryClient.invalidateQueries({ queryKey: ["users"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error deleting user`, { capfirst: true }), message: error?.message || t(`error deleting user`, { capfirst: true }),
color: "red" color: "red",
}); });
} },
}); });
} }
export function useEditUser() { export function useEditUser() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: ({ id, user }: UserEditPayload) => { mutationFn: ({ id, user }: UserEditPayload) => {
return fetch(`${Config.backend_uri}/users/${id}`, { return fetch(`${Config.backend_uri}/users/${id}`, {
method: 'PUT', method: "PUT",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(user), body: JSON.stringify(user),
}).then((res) => res.json()); }).then((res) => res.json());
@@ -541,28 +551,27 @@ export function useEditUser() {
title: t("success", { capfirst: true }), title: t("success", { capfirst: true }),
message: t("successfully edited user", { capfirst: true }), message: t("successfully edited user", { capfirst: true }),
}); });
await queryClient.invalidateQueries({ queryKey: ['users'] }) await queryClient.invalidateQueries({ queryKey: ["users"] });
}, },
onError: (error) => { onError: (error) => {
notifications.show({ notifications.show({
title: t("error", { capfirst: true }), title: t("error", { capfirst: true }),
message: error?.message || t(`error editing user`, { capfirst: true }), message: error?.message || t(`error editing user`, { capfirst: true }),
color: "red" color: "red",
});
},
}); });
} }
});
}
export function useCreateContract() { export function useCreateContract() {
const queryClient = useQueryClient() const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (newContract: ContractCreate) => { mutationFn: (newContract: ContractCreate) => {
return fetch(`${Config.backend_uri}/contracts`, { return fetch(`${Config.backend_uri}/contracts`, {
method: 'POST', method: "POST",
headers: { headers: {
"Content-Type": "application/json" "Content-Type": "application/json",
}, },
body: JSON.stringify(newContract), body: JSON.stringify(newContract),
}).then(async (res) => await res.blob()); }).then(async (res) => await res.blob());
@@ -575,6 +584,6 @@ export function useCreateContract() {
link.click(); link.click();
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
await queryClient.invalidateQueries({ queryKey: ["contracts"] }); await queryClient.invalidateQueries({ queryKey: ["contracts"] });
} },
}); });
} }

View File

@@ -1,4 +1,4 @@
export type ContractCreate = { export type ContractCreate = {
form_id: number; form_id: number;
contract: Record<string, string | number | null>; contract: Record<string, string | number | null>;
} };

View File

@@ -12,7 +12,7 @@ export type Form = {
referer: User; referer: User;
shipments: Shipment[]; shipments: Shipment[];
minimum_shipment_value: number | null; minimum_shipment_value: number | null;
} };
export type FormCreate = { export type FormCreate = {
name: string; name: string;
@@ -22,7 +22,7 @@ export type FormCreate = {
productor_id: number; productor_id: number;
referer_id: number; referer_id: number;
minimum_shipment_value: number | null; minimum_shipment_value: number | null;
} };
export type FormEdit = { export type FormEdit = {
name?: string | null; name?: string | null;
@@ -32,12 +32,12 @@ export type FormEdit = {
productor_id?: number | null; productor_id?: number | null;
referer_id?: number | null; referer_id?: number | null;
minimum_shipment_value: number | null; minimum_shipment_value: number | null;
} };
export type FormEditPayload = { export type FormEditPayload = {
id: number; id: number;
form: FormEdit; form: FormEdit;
} };
export type FormInputs = { export type FormInputs = {
name: string; name: string;
@@ -47,4 +47,4 @@ export type FormInputs = {
productor_id: string; productor_id: string;
referer_id: string; referer_id: string;
minimum_shipment_value: number | string | null; minimum_shipment_value: number | string | null;
} };

View File

@@ -4,12 +4,12 @@ import type { Product } from "./products";
export const PaymentMethods = [ export const PaymentMethods = [
{ value: "cheque", label: t("cheque", { capfirst: true }) }, { value: "cheque", label: t("cheque", { capfirst: true }) },
{ value: "transfer", label: t("transfer", { capfirst: true }) }, { value: "transfer", label: t("transfer", { capfirst: true }) },
] ];
export type PaymentMethod = { export type PaymentMethod = {
name: string; name: string;
details: string; details: string;
} };
export type Productor = { export type Productor = {
id: number; id: number;
@@ -17,31 +17,31 @@ export type Productor = {
address: string; address: string;
payment_methods: PaymentMethod[]; payment_methods: PaymentMethod[];
type: string; type: string;
products: Product[] products: Product[];
} };
export type ProductorCreate = { export type ProductorCreate = {
name: string; name: string;
address: string; address: string;
payment_methods: PaymentMethod[]; payment_methods: PaymentMethod[];
type: string; type: string;
} };
export type ProductorEdit = { export type ProductorEdit = {
name: string | null; name: string | null;
address: string | null; address: string | null;
payment_methods: PaymentMethod[]; payment_methods: PaymentMethod[];
type: string | null; type: string | null;
} };
export type ProductorInputs = { export type ProductorInputs = {
name: string; name: string;
address: string; address: string;
type: string; type: string;
payment_methods: PaymentMethod[]; payment_methods: PaymentMethod[];
} };
export type ProductorEditPayload = { export type ProductorEditPayload = {
productor: ProductorEdit; productor: ProductorEdit;
id: number; id: number;
} };

View File

@@ -16,11 +16,11 @@ export const ProductUnit = {
}; };
export const ProductQuantityUnit = { export const ProductQuantityUnit = {
"ml": "mililiter", ml: "mililiter",
"L": "liter", L: "liter",
"g": "grams", g: "grams",
"kg": "kilo" kg: "kilo",
} };
export type Product = { export type Product = {
id: number; id: number;
@@ -33,7 +33,7 @@ export type Product = {
quantity_unit: string | null; quantity_unit: string | null;
type: ProductTypeKey; type: ProductTypeKey;
shipments: Shipment[]; shipments: Shipment[];
} };
export type ProductCreate = { export type ProductCreate = {
productor_id: number; productor_id: number;
@@ -44,7 +44,7 @@ export type ProductCreate = {
quantity: number | null; quantity: number | null;
quantity_unit: string | null; quantity_unit: string | null;
type: string; type: string;
} };
export type ProductEdit = { export type ProductEdit = {
productor_id: number | null; productor_id: number | null;
@@ -55,7 +55,7 @@ export type ProductEdit = {
quantity: number | null; quantity: number | null;
quantity_unit: string | null; quantity_unit: string | null;
type: string | null; type: string | null;
} };
export type ProductInputs = { export type ProductInputs = {
productor_id: string | null; productor_id: string | null;
@@ -66,12 +66,12 @@ export type ProductInputs = {
quantity: number | string | null; quantity: number | string | null;
quantity_unit: string | null; quantity_unit: string | null;
type: string | null; type: string | null;
} };
export type ProductEditPayload = { export type ProductEditPayload = {
product: ProductEdit; product: ProductEdit;
id: number; id: number;
} };
export function productToProductInputs(product: Product): ProductInputs { export function productToProductInputs(product: Product): ProductInputs {
return { return {
@@ -92,9 +92,15 @@ export function productCreateFromProductInputs(productInput: ProductInputs): Pro
name: productInput.name, name: productInput.name,
unit: productInput.unit!, unit: productInput.unit!,
price: productInput.price === "" || !productInput.price ? null : Number(productInput.price), price: productInput.price === "" || !productInput.price ? null : Number(productInput.price),
price_kg: productInput.price_kg === "" || !productInput.price_kg ? null : Number(productInput.price_kg), price_kg:
quantity: productInput.quantity === "" || !productInput.quantity ? null : Number(productInput.quantity), productInput.price_kg === "" || !productInput.price_kg
? null
: Number(productInput.price_kg),
quantity:
productInput.quantity === "" || !productInput.quantity
? null
: Number(productInput.quantity),
quantity_unit: productInput.quantity_unit, quantity_unit: productInput.quantity_unit,
type: productInput.type!, type: productInput.type!,
} };
} }

View File

@@ -8,39 +8,39 @@ export type Shipment = {
form: Form; form: Form;
form_id: number; form_id: number;
products: Product[]; products: Product[];
} };
export type ShipmentCreate = { export type ShipmentCreate = {
name: string; name: string;
date: string; date: string;
form_id: number; form_id: number;
product_ids: number[]; product_ids: number[];
} };
export type ShipmentEdit = { export type ShipmentEdit = {
name: string | null; name: string | null;
date: string | null; date: string | null;
form_id: number | null; form_id: number | null;
product_ids: number[]; product_ids: number[];
} };
export type ShipmentEditPayload = { export type ShipmentEditPayload = {
id: number; id: number;
shipment: ShipmentEdit; shipment: ShipmentEdit;
} };
export type ShipmentInputs = { export type ShipmentInputs = {
name: string | null; name: string | null;
date: string | null; date: string | null;
form_id: string | null; form_id: string | null;
product_ids: string[]; product_ids: string[];
} };
export function shipmentToShipmentInputs(shipment: Shipment): ShipmentInputs { export function shipmentToShipmentInputs(shipment: Shipment): ShipmentInputs {
return { return {
...shipment, ...shipment,
form_id: String(shipment.form_id), form_id: String(shipment.form_id),
product_ids: shipment.products.map((el) => (String(el.id))) product_ids: shipment.products.map((el) => String(el.id)),
}; };
} }
@@ -49,6 +49,6 @@ export function shipmentCreateFromShipmentInputs(shipmentInput: ShipmentInputs):
name: shipmentInput.name!, name: shipmentInput.name!,
date: shipmentInput.date!, date: shipmentInput.date!,
form_id: Number(shipmentInput.form_id), form_id: Number(shipmentInput.form_id),
product_ids: shipmentInput.product_ids.map(el => (Number(el))), product_ids: shipmentInput.product_ids.map((el) => Number(el)),
} };
} }

View File

@@ -5,24 +5,24 @@ export type User = {
name: string; name: string;
email: string; email: string;
products: Product[]; products: Product[];
} };
export type UserInputs = { export type UserInputs = {
email: string; email: string;
name: string; name: string;
} };
export type UserCreate = { export type UserCreate = {
email: string | null; email: string | null;
name: string | null; name: string | null;
} };
export type UserEdit = { export type UserEdit = {
email: string | null; email: string | null;
name: string | null; name: string | null;
} };
export type UserEditPayload = { export type UserEditPayload = {
user: UserEdit; user: UserEdit;
id: number; id: number;
} };

View File

@@ -1,4 +1,4 @@
import { createTheme } from '@mantine/core'; import { createTheme } from "@mantine/core";
export const theme = createTheme({ export const theme = createTheme({
/** Put your mantine theme override here */ /** Put your mantine theme override here */

View File

@@ -1,7 +1,4 @@
{ {
"files": [], "files": [],
"references": [ "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
} }

View File

@@ -1,18 +1,18 @@
import { defineConfig } from 'vite' import { defineConfig } from "vite";
import react from '@vitejs/plugin-react' import react from "@vitejs/plugin-react";
import path from 'path'; import path from "path";
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
resolve: { resolve: {
alias: { alias: {
'@': path.resolve(__dirname, 'src'), "@": path.resolve(__dirname, "src"),
}, },
}, },
server: { server: {
watch: { watch: {
usePolling: true, usePolling: true,
}, },
} },
}) });