198 lines
6.6 KiB
TypeScript
198 lines
6.6 KiB
TypeScript
'use client';
|
|
import { useState, useCallback, useEffect } from 'react';
|
|
import {
|
|
CheckDocumentRequestResponse,
|
|
PlagiarismFormErrors,
|
|
PlagiarismFormState,
|
|
SubmissionState,
|
|
} from './types';
|
|
import { isFormValid, validatePlagiarismForm } from './validation';
|
|
import { toast } from 'react-toastify';
|
|
import { useUserPlagiatStore } from '@/shared/zustand/user';
|
|
import { useMutation } from '@tanstack/react-query';
|
|
import { links } from '@/shared/request/links';
|
|
import { apiRequest } from '@/shared/request/apiRequest';
|
|
import { PriceCalculate } from '@/features/modals/paymentModal/lib/types';
|
|
import { SERTIFICATE_PRICE, PLAGIAT_SERVICE_FEE } from '@/shared/lib/metadata';
|
|
// import { fromTheme } from 'tailwind-merge';
|
|
|
|
// ─── Initial States ──────────────────────────────────────────────────────────
|
|
|
|
const INITIAL_FORM: PlagiarismFormState = {
|
|
title: '',
|
|
file: null,
|
|
certificate: true,
|
|
text: '',
|
|
type: 0,
|
|
};
|
|
|
|
const PRICE: PriceCalculate = {
|
|
service_fee: PLAGIAT_SERVICE_FEE,
|
|
certificate: SERTIFICATE_PRICE,
|
|
discount: 0,
|
|
total_price: 0,
|
|
};
|
|
|
|
const INITIAL_SUBMISSION: SubmissionState = {
|
|
status: 'idle',
|
|
error: null,
|
|
};
|
|
|
|
// ─── Hook ────────────────────────────────────────────────────────────────────
|
|
|
|
export function usePlagiarismForm() {
|
|
const user = useUserPlagiatStore((state) => state.user);
|
|
const [localUser, setLocalUser] = useState<{
|
|
id: number;
|
|
name: string;
|
|
surname: string;
|
|
} | null>(null);
|
|
useEffect(() => {
|
|
const data = localStorage.getItem('user');
|
|
|
|
if (data) {
|
|
setLocalUser(JSON.parse(data));
|
|
} else {
|
|
setLocalUser(null);
|
|
}
|
|
}, [user]);
|
|
const [form, setForm] = useState<PlagiarismFormState>(INITIAL_FORM);
|
|
const [errors, setErrors] = useState<PlagiarismFormErrors>({});
|
|
const [isPaymentOpen, setIsPaymentOpen] = useState(false);
|
|
const [submission, setSubmission] =
|
|
useState<SubmissionState>(INITIAL_SUBMISSION);
|
|
const [order_id, setOrder_id] = useState<number>(0);
|
|
const [prices, setPrices] = useState<PriceCalculate>(PRICE);
|
|
|
|
const checkdocumentRequest = useMutation({
|
|
mutationKey: ['plagiarismCheck'],
|
|
mutationFn: (data: FormData) =>
|
|
apiRequest('POST', links.plagiarismCheck, data),
|
|
onSuccess: (res) => {
|
|
console.log('uploda: ', res);
|
|
const resdata = res.data as CheckDocumentRequestResponse;
|
|
const priceInfo: PriceCalculate = {
|
|
total_price: resdata?.total_price || 0,
|
|
discount: resdata?.discount || 0,
|
|
certificate: form.certificate ? SERTIFICATE_PRICE : 0,
|
|
service_fee: PLAGIAT_SERVICE_FEE,
|
|
};
|
|
setPrices(priceInfo);
|
|
console.log('order_id:', resdata.id);
|
|
setOrder_id(resdata.order_id);
|
|
setSubmission({ status: 'success', error: null });
|
|
setForm(INITIAL_FORM);
|
|
setIsPaymentOpen(true);
|
|
},
|
|
onError: (err) => {
|
|
const message =
|
|
err instanceof Error ? err.message : 'An unexpected error occurred.';
|
|
setSubmission({ status: 'error', error: message });
|
|
},
|
|
});
|
|
|
|
const payment = useMutation({
|
|
mutationKey: ['payload'],
|
|
mutationFn: ({ order_id }: { order_id: number }) =>
|
|
apiRequest<{ payment_link: string }>('POST', links.demo_pay(order_id)),
|
|
onSuccess: (res) => {
|
|
console.log('payment res: ', res);
|
|
window.open(res.data.payment_link, '_self');
|
|
setIsPaymentOpen(false);
|
|
},
|
|
onError: (err) => {
|
|
const message =
|
|
err instanceof Error ? err.message : 'An unexpected error occurred.';
|
|
setSubmission({ status: 'error', error: message });
|
|
setIsPaymentOpen(false);
|
|
},
|
|
});
|
|
|
|
// ── Field updaters ───────────────────────────────────────────────────────
|
|
|
|
const setTopic = useCallback((topic: string) => {
|
|
setForm((prev) => ({ ...prev, title: topic }));
|
|
setErrors((prev) => ({ ...prev, title: undefined }));
|
|
}, []);
|
|
|
|
const setFile = useCallback((file: File | null) => {
|
|
setForm((prev) => ({ ...prev, file }));
|
|
setErrors((prev) => ({ ...prev, file: undefined }));
|
|
}, []);
|
|
|
|
const setOption = useCallback((option: number) => {
|
|
setForm((prev) => ({ ...prev, type: option }));
|
|
setErrors((prev) => ({ ...prev, type: undefined }));
|
|
}, []);
|
|
|
|
const toggleCertificate = useCallback(() => {
|
|
setForm((prev) => ({ ...prev, certificate: !prev.certificate }));
|
|
}, []);
|
|
|
|
// ── Submission ───────────────────────────────────────────────────────────
|
|
|
|
// 1. Wrap the form's onSubmit to intercept the event properly
|
|
const handleSubmitWithModal = useCallback(
|
|
async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
|
|
console.log('Form submitted user:', user); // Debugging log
|
|
if (localUser === null) {
|
|
toast.error('Iltimos, avval tizimga kiring!');
|
|
return;
|
|
}
|
|
// Run validation first
|
|
const validationErrors = validatePlagiarismForm(form);
|
|
if (!isFormValid(validationErrors)) {
|
|
setErrors(validationErrors);
|
|
return; // Don't open modal if invalid
|
|
}
|
|
|
|
console.log('new');
|
|
const fd = new FormData();
|
|
fd.append('title', form.title.trim());
|
|
fd.append('text', form.text || '');
|
|
fd.append('file', form.file!);
|
|
fd.append('certificate', String(form.certificate));
|
|
fd.append('type', String(form.type));
|
|
console.log('sended data: ', fd);
|
|
checkdocumentRequest.mutate(fd);
|
|
},
|
|
[form, localUser],
|
|
);
|
|
|
|
const handleSubmit = useCallback(async () => {
|
|
setSubmission({ status: 'loading', error: null });
|
|
|
|
payment.mutate({ order_id });
|
|
}, [form, user]);
|
|
|
|
const resetSubmission = useCallback(() => {
|
|
setSubmission(INITIAL_SUBMISSION);
|
|
}, []);
|
|
|
|
// ── Derived state ────────────────────────────────────────────────────────
|
|
|
|
const isLoading = submission.status === 'loading';
|
|
|
|
return {
|
|
form,
|
|
errors,
|
|
submission,
|
|
senderFullName: localUser
|
|
? `${localUser?.name} ${localUser?.surname}`
|
|
: null,
|
|
isLoading,
|
|
setTopic,
|
|
setFile,
|
|
toggleCertificate,
|
|
handleSubmit,
|
|
resetSubmission,
|
|
handleSubmitWithModal,
|
|
setIsPaymentOpen,
|
|
isPaymentOpen,
|
|
setOption,
|
|
prices,
|
|
};
|
|
}
|