Main branch changes
This commit is contained in:
39
src/api/missionsUpload.ts
Normal file
39
src/api/missionsUpload.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
export interface UploadMissionRequest {
|
||||||
|
missionFile: File;
|
||||||
|
difficulty: number;
|
||||||
|
tags?: string[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const buildUploadMissionFormData = (
|
||||||
|
request: UploadMissionRequest,
|
||||||
|
): FormData => {
|
||||||
|
const formData = new FormData();
|
||||||
|
|
||||||
|
formData.append('missionFile', request.missionFile);
|
||||||
|
formData.append('difficulty', request.difficulty.toString());
|
||||||
|
|
||||||
|
// tags:
|
||||||
|
// - undefined => fromArchive (do not include tags key at all)
|
||||||
|
// - [] => empty list (not reliably representable via multipart without backend support)
|
||||||
|
// - [..] => custom tags, repeated keys
|
||||||
|
if (Array.isArray(request.tags)) {
|
||||||
|
request.tags.forEach((tag) => formData.append('tags', tag));
|
||||||
|
}
|
||||||
|
|
||||||
|
return formData;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getProblemXmlMissingNameMessage = (responseData: unknown) => {
|
||||||
|
const asText =
|
||||||
|
typeof responseData === 'string'
|
||||||
|
? responseData
|
||||||
|
: responseData == null
|
||||||
|
? ''
|
||||||
|
: JSON.stringify(responseData);
|
||||||
|
|
||||||
|
if (/problem\.xml/i.test(asText) || /Mission name was not found/i.test(asText)) {
|
||||||
|
return 'В архиве отсутствует имя в problem.xml';
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
@@ -15,8 +15,8 @@ interface ModalProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const modalbgVariants = {
|
const modalbgVariants = {
|
||||||
closed: { opacity: 0 },
|
closed: { opacity: 0, backdropFilter: 'blur(0px)' },
|
||||||
open: { opacity: 1 },
|
open: { opacity: 1, backdropFilter: 'blur(6px)' },
|
||||||
};
|
};
|
||||||
|
|
||||||
const modalVariants = {
|
const modalVariants = {
|
||||||
@@ -47,13 +47,15 @@ export const Modal: React.FC<ModalProps> = ({
|
|||||||
exit={modalbgVariants.closed}
|
exit={modalbgVariants.closed}
|
||||||
transition={{ duration: 0.15 }}
|
transition={{ duration: 0.15 }}
|
||||||
className={cn(
|
className={cn(
|
||||||
' fixed top-0 left-0 h-svh w-svw backdrop-filter transition-[background-color,backdrop-filter,opacity] z-50',
|
'fixed top-0 left-0 h-svh w-svw z-50',
|
||||||
backdrop == 'blur' && open && 'backdrop-blur-sm',
|
backdrop === 'opaque' && 'bg-[#00000055]',
|
||||||
backdrop == 'opaque' &&
|
|
||||||
open &&
|
|
||||||
'bg-[#00000055] pointer-events-none',
|
|
||||||
)}
|
)}
|
||||||
></motion.div>
|
style={
|
||||||
|
backdrop === 'blur'
|
||||||
|
? undefined
|
||||||
|
: { backdropFilter: 'none' }
|
||||||
|
}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
<div className="fixed top-0 left-0 h-svh w-svw flex items-center justify-center pointer-events-none z-50">
|
<div className="fixed top-0 left-0 h-svh w-svw flex items-center justify-center pointer-events-none z-50">
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
|
||||||
import axios from '../../axios';
|
import axios from '../../axios';
|
||||||
import { toastError } from '../../lib/toastNotification';
|
import { toastError } from '../../lib/toastNotification';
|
||||||
|
import {
|
||||||
|
buildUploadMissionFormData,
|
||||||
|
getProblemXmlMissingNameMessage,
|
||||||
|
UploadMissionRequest,
|
||||||
|
} from '../../api/missionsUpload';
|
||||||
|
|
||||||
// ─── Типы ────────────────────────────────────────────
|
// ─── Типы ────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -148,27 +153,45 @@ export const fetchMyMissions = createAsyncThunk(
|
|||||||
export const uploadMission = createAsyncThunk(
|
export const uploadMission = createAsyncThunk(
|
||||||
'missions/uploadMission',
|
'missions/uploadMission',
|
||||||
async (
|
async (
|
||||||
{
|
request: UploadMissionRequest,
|
||||||
file,
|
|
||||||
name,
|
|
||||||
difficulty,
|
|
||||||
tags,
|
|
||||||
}: { file: File; name: string; difficulty: number; tags: string[] },
|
|
||||||
{ rejectWithValue },
|
{ rejectWithValue },
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
const formData = new FormData();
|
const formData = buildUploadMissionFormData(request);
|
||||||
formData.append('MissionFile', file);
|
|
||||||
formData.append('Name', name);
|
|
||||||
formData.append('Difficulty', difficulty.toString());
|
|
||||||
tags.forEach((tag) => formData.append('Tags', tag));
|
|
||||||
|
|
||||||
const response = await axios.post('/missions/upload', formData, {
|
const response = await axios.post('/missions/upload', formData, {
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
headers: { 'Content-Type': 'multipart/form-data' },
|
||||||
});
|
});
|
||||||
return response.data; // Mission
|
return response.data; // Mission
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
return rejectWithValue(err.response?.data);
|
const status = err?.response?.status;
|
||||||
|
const responseData = err?.response?.data;
|
||||||
|
|
||||||
|
if (status === 400) {
|
||||||
|
const msg = getProblemXmlMissingNameMessage(responseData);
|
||||||
|
if (msg) {
|
||||||
|
return rejectWithValue({
|
||||||
|
errors: {
|
||||||
|
missionFile: [msg],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (responseData?.errors) {
|
||||||
|
return rejectWithValue(responseData);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fallback =
|
||||||
|
typeof responseData === 'string'
|
||||||
|
? responseData
|
||||||
|
: 'Не удалось загрузить миссию';
|
||||||
|
|
||||||
|
return rejectWithValue({
|
||||||
|
errors: {
|
||||||
|
general: [fallback],
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -351,17 +374,19 @@ const missionsSlice = createSlice({
|
|||||||
(state, action: PayloadAction<any>) => {
|
(state, action: PayloadAction<any>) => {
|
||||||
state.statuses.upload = 'failed';
|
state.statuses.upload = 'failed';
|
||||||
|
|
||||||
const errors = action.payload.errors as Record<
|
const errors = action.payload?.errors as
|
||||||
string,
|
| Record<string, string[]>
|
||||||
string[]
|
| undefined;
|
||||||
>;
|
if (errors) {
|
||||||
Object.values(errors).forEach((messages) => {
|
Object.values(errors).forEach((messages) => {
|
||||||
messages.forEach((msg) => {
|
messages.forEach((msg) => {
|
||||||
toastError(msg);
|
toastError(msg);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
state.create.errors = errors;
|
state.create.errors = errors;
|
||||||
|
} else {
|
||||||
|
toastError('Не удалось загрузить миссию');
|
||||||
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { toastSuccess } from '../../../lib/toastNotification';
|
|||||||
import { cn } from '../../../lib/cn';
|
import { cn } from '../../../lib/cn';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import { NumberInput } from '../../../components/input/NumberInput';
|
import { NumberInput } from '../../../components/input/NumberInput';
|
||||||
|
import { DropDownList, DropDownListItem } from '../../../components/input/DropDownList';
|
||||||
|
|
||||||
interface ModalCreateProps {
|
interface ModalCreateProps {
|
||||||
active: boolean;
|
active: boolean;
|
||||||
@@ -19,23 +20,37 @@ interface ModalCreateProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
||||||
const [name, setName] = useState<string>('');
|
type TagsMode = 'fromArchive' | 'none' | 'custom';
|
||||||
const [difficulty, setDifficulty] = useState<number>(1);
|
const [difficulty, setDifficulty] = useState<number>(1);
|
||||||
const [file, setFile] = useState<File | null>(null);
|
const [file, setFile] = useState<File | null>(null);
|
||||||
const [tagInput, setTagInput] = useState<string>('');
|
const [tagInput, setTagInput] = useState<string>('');
|
||||||
const [tags, setTags] = useState<string[]>([]);
|
const [tags, setTags] = useState<string[]>([]);
|
||||||
|
const [tagsMode, setTagsMode] = useState<TagsMode>('fromArchive');
|
||||||
|
|
||||||
const status = useAppSelector((state) => state.missions.statuses.upload);
|
const status = useAppSelector((state) => state.missions.statuses.upload);
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
|
|
||||||
const [clickSubmit, setClickSubmit] = useState<boolean>(false);
|
const [clickSubmit, setClickSubmit] = useState<boolean>(false);
|
||||||
|
|
||||||
const addTag = () => {
|
const normalizeTags = (raw: string[]): string[] => {
|
||||||
const newTag = tagInput.trim();
|
const result: string[] = [];
|
||||||
if (newTag && !tags.includes(newTag)) {
|
const seen = new Set<string>();
|
||||||
setTags([...tags, newTag]);
|
for (const t of raw) {
|
||||||
setTagInput('');
|
const trimmed = t.trim();
|
||||||
|
if (!trimmed) continue;
|
||||||
|
const key = trimmed.toLowerCase();
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
result.push(trimmed);
|
||||||
}
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
const addTag = () => {
|
||||||
|
const parts = tagInput.split(',').map((v) => v.trim());
|
||||||
|
const next = normalizeTags([...tags, ...parts]);
|
||||||
|
setTags(next);
|
||||||
|
setTagInput('');
|
||||||
};
|
};
|
||||||
|
|
||||||
const removeTag = (tagToRemove: string) => {
|
const removeTag = (tagToRemove: string) => {
|
||||||
@@ -51,16 +66,27 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
setClickSubmit(true);
|
setClickSubmit(true);
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
dispatch(uploadMission({ file, name, difficulty, tags }));
|
|
||||||
|
const payloadTags =
|
||||||
|
tagsMode === 'custom' ? normalizeTags(tags) : undefined;
|
||||||
|
|
||||||
|
dispatch(
|
||||||
|
uploadMission({
|
||||||
|
missionFile: file,
|
||||||
|
difficulty,
|
||||||
|
tags: payloadTags,
|
||||||
|
}),
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (status === 'successful') {
|
if (status === 'successful') {
|
||||||
toastSuccess('Миссия создана!');
|
toastSuccess('Миссия создана!');
|
||||||
setName('');
|
|
||||||
setDifficulty(1);
|
setDifficulty(1);
|
||||||
setTags([]);
|
setTags([]);
|
||||||
setFile(null);
|
setFile(null);
|
||||||
|
setTagInput('');
|
||||||
|
setTagsMode('fromArchive');
|
||||||
dispatch(setMissionsStatus({ key: 'upload', status: 'idle' }));
|
dispatch(setMissionsStatus({ key: 'upload', status: 'idle' }));
|
||||||
setActive(false);
|
setActive(false);
|
||||||
}
|
}
|
||||||
@@ -73,12 +99,32 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
dispatch(setMissionsStatus({ key: 'upload', status: 'idle' }));
|
dispatch(setMissionsStatus({ key: 'upload', status: 'idle' }));
|
||||||
}, [active]);
|
}, [active]);
|
||||||
|
|
||||||
const getNameErrorMessage = (): string => {
|
const getDifficultyErrorMessage = (): string => {
|
||||||
if (!clickSubmit) return '';
|
if (!clickSubmit) return '';
|
||||||
if (name == '') return 'Поле не может быть пустым';
|
if (!Number.isFinite(difficulty) || difficulty < 1)
|
||||||
|
return 'Укажите сложность (минимум 1)';
|
||||||
return '';
|
return '';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const tagsModeItems: DropDownListItem[] = [
|
||||||
|
{ text: 'Теги: из архива', value: 'fromArchive' },
|
||||||
|
{ text: 'Теги: без тегов', value: 'none' },
|
||||||
|
{ text: 'Теги: свои', value: 'custom' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const isTagsMode = (v: string): v is TagsMode =>
|
||||||
|
v === 'fromArchive' || v === 'none' || v === 'custom';
|
||||||
|
|
||||||
|
const currentTagsModeItem =
|
||||||
|
tagsModeItems.find((i) => i.value === tagsMode) ?? tagsModeItems[0];
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tagsMode === 'none') {
|
||||||
|
setTags([]);
|
||||||
|
setTagInput('');
|
||||||
|
}
|
||||||
|
}, [tagsMode]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
className="bg-liquid-background border-liquid-lighter border-[2px] p-[25px] rounded-[20px] text-liquid-white"
|
||||||
@@ -89,18 +135,6 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
<div className="w-[500px]">
|
<div className="w-[500px]">
|
||||||
<div className="font-bold text-[30px]">Добавить задачу</div>
|
<div className="font-bold text-[30px]">Добавить задачу</div>
|
||||||
|
|
||||||
<Input
|
|
||||||
name="name"
|
|
||||||
autocomplete="name"
|
|
||||||
className="mt-[10px]"
|
|
||||||
type="text"
|
|
||||||
label="Название"
|
|
||||||
defaultState={name}
|
|
||||||
onChange={setName}
|
|
||||||
placeholder="В яблочко"
|
|
||||||
error={getNameErrorMessage()}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<NumberInput
|
<NumberInput
|
||||||
name="difficulty"
|
name="difficulty"
|
||||||
className="mt-[10px]"
|
className="mt-[10px]"
|
||||||
@@ -110,6 +144,7 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
maxValue={3500}
|
maxValue={3500}
|
||||||
onChange={(v) => setDifficulty(v)}
|
onChange={(v) => setDifficulty(v)}
|
||||||
placeholder="1"
|
placeholder="1"
|
||||||
|
error={getDifficultyErrorMessage()}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="mt-4">
|
<div className="mt-4">
|
||||||
@@ -137,16 +172,38 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
|
|
||||||
{/* Теги */}
|
{/* Теги */}
|
||||||
<div className="mb-[50px] max-w-[600px]">
|
<div className="mb-[50px] max-w-[600px]">
|
||||||
|
<div className="mt-[20px]">
|
||||||
|
<div className="text-[18px] text-liquid-white font-medium h-[23px] mb-[10px]">
|
||||||
|
Режим тегов
|
||||||
|
</div>
|
||||||
|
<DropDownList
|
||||||
|
items={tagsModeItems}
|
||||||
|
defaultState={currentTagsModeItem}
|
||||||
|
onChange={(v) => {
|
||||||
|
if (isTagsMode(v)) setTagsMode(v);
|
||||||
|
}}
|
||||||
|
weight="w-full"
|
||||||
|
/>
|
||||||
|
{tagsMode === 'none' && (
|
||||||
|
<div className="text-liquid-red text-[14px] mt-[8px] whitespace-pre-line">
|
||||||
|
Пустой список тегов сейчас не поддерживается в multipart.
|
||||||
|
Будет использован режим “из архива”.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tagsMode === 'custom' && (
|
||||||
|
<>
|
||||||
<div className="grid grid-cols-[1fr,140px] items-end gap-2">
|
<div className="grid grid-cols-[1fr,140px] items-end gap-2">
|
||||||
<Input
|
<Input
|
||||||
name="articleTag"
|
name="missionTags"
|
||||||
autocomplete="articleTag"
|
autocomplete="missionTags"
|
||||||
className="mt-[20px] max-w-[600px]"
|
className="mt-[20px] max-w-[600px]"
|
||||||
type="text"
|
type="text"
|
||||||
label="Теги"
|
label="Теги (через запятую)"
|
||||||
onChange={(v) => setTagInput(v)}
|
onChange={(v) => setTagInput(v)}
|
||||||
defaultState={tagInput}
|
defaultState={tagInput}
|
||||||
placeholder="arrays"
|
placeholder="arrays, dp"
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter') addTag();
|
if (e.key === 'Enter') addTag();
|
||||||
}}
|
}}
|
||||||
@@ -173,6 +230,8 @@ const ModalCreate: FC<ModalCreateProps> = ({ active, setActive }) => {
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
|
|||||||
Reference in New Issue
Block a user