diff --git a/src/components/ImmediateCreditsStages/PhoneAccept.js b/src/components/ImmediateCreditsStages/PhoneAccept.js index ac71361..118fb8e 100644 --- a/src/components/ImmediateCreditsStages/PhoneAccept.js +++ b/src/components/ImmediateCreditsStages/PhoneAccept.js @@ -1,13 +1,13 @@ // IMPORT MODULES -import React, { useState, useContext } from "react"; -import { LanguageContext } from "../../backend/LanguageContext"; -import { useForm } from "react-hook-form"; -import { z } from "zod"; -import { zodResolver } from "@hookform/resolvers/zod"; +import React, { useState, useContext } from 'react'; +import { LanguageContext } from '../../backend/LanguageContext'; +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; +import { zodResolver } from '@hookform/resolvers/zod'; // IMPORT IMAGES -import next from "../../icons/next.svg"; -import next_reverse from "../../icons/next-reverse.svg"; -import { UserContext } from "../../backend/UserContext"; +import next from '../../icons/next.svg'; +import next_reverse from '../../icons/next-reverse.svg'; +import { UserContext } from '../../backend/UserContext'; // import arrow from "../../icons/arrow.svg"; const schema = z.object({ @@ -33,7 +33,7 @@ const PhoneAccept = ({ }) => { const { locale } = useContext(LanguageContext); const { user } = useContext(UserContext); - const userToken = localStorage.getItem("userToken"); + const userToken = localStorage.getItem('userToken'); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(false); @@ -41,10 +41,13 @@ const PhoneAccept = ({ const [invalidData, setInvalidData] = useState(false); const [tryAgain, setTryAgain] = useState(false); - const [codeValue, setPhoneValue] = useState(""); + const [codeValue, setPhoneValue] = useState(''); const [errMessage, setErrMessage] = useState(); + const [messageSend, setMessageSend] = useState(false); + const [timeLeft, setTimeLeft] = useState(0); + const handleCodeChange = (e) => { setPhoneValue(e.target.value); }; @@ -58,26 +61,23 @@ const PhoneAccept = ({ const confirmPayment = async () => { try { const headers = { - "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", + 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }; const formData = new URLSearchParams(); - formData.append("app", "sanlykarz"); - formData.append("id", borrowerData.idNo); - formData.append("md-order", paymentDetails["md-order"]); - formData.append("acs-req-id", submitCardDetails["acs-request-id"]); - formData.append("acs-session-url", submitCardDetails["acs-session-url"]); - formData.append("otp", codeValue); - formData.append("term-url", submitCardDetails["terminate-url"]); + formData.append('app', 'sanlykarz'); + formData.append('id', borrowerData.idNo); + formData.append('md-order', paymentDetails['md-order']); + formData.append('acs-req-id', submitCardDetails['acs-request-id']); + formData.append('acs-session-url', submitCardDetails['acs-session-url']); + formData.append('otp', codeValue); + formData.append('term-url', submitCardDetails['terminate-url']); - const response = await fetch( - "https://shahsyotag.halkbank.gov.tm/api/v1/confirm-payment", - { - method: "POST", - headers: headers, - body: formData.toString(), - } - ); + const response = await fetch('https://shahsyotag.halkbank.gov.tm/api/v1/confirm-payment', { + method: 'POST', + headers: headers, + body: formData.toString(), + }); const jsonedResponse = await response.json(); @@ -85,16 +85,13 @@ const PhoneAccept = ({ throw new Error(`HTTP error! Status: ${response.status}`); } - if ( - jsonedResponse.status === "ok" && - jsonedResponse["final-url"].includes("status=1") - ) { - console.log(jsonedResponse["final-url"]); + if (jsonedResponse.status === 'ok' && jsonedResponse['final-url'].includes('status=1')) { + console.log(jsonedResponse['final-url']); setInvalidData(false); checkPayment(); } else if ( - jsonedResponse.status === "wrong-otp" || - !jsonedResponse["final-url"].includes("status=1") + jsonedResponse.status === 'wrong-otp' || + !jsonedResponse['final-url'].includes('status=1') ) { setTryAgain(true); } else { @@ -106,7 +103,7 @@ const PhoneAccept = ({ const checkPayment = async () => { try { const response = await fetch( - `https://shahsyotag.halkbank.gov.tm/app/api/check-payment-credit-card?paymentId=${paymentLink.id}&orderId=${paymentDetails["md-order"]}&status=1` + `https://shahsyotag.halkbank.gov.tm/app/api/check-payment-credit-card?paymentId=${paymentLink.id}&orderId=${paymentDetails['md-order']}&status=1`, ); if (!response.ok) { @@ -115,8 +112,8 @@ const PhoneAccept = ({ const jsonedResponse = await response.json(); - if (jsonedResponse.status.ErrorCode === "0") { - console.log("success"); + if (jsonedResponse.status.ErrorCode === '0') { + console.log('success'); loanCreateCheck(); } } catch (error) { @@ -127,12 +124,12 @@ const PhoneAccept = ({ const loanCreateCheck = async () => { try { const response = await fetch( - "https://shahsyotag.halkbank.gov.tm/onlineloancre-services/api/loancre/check", + 'https://shahsyotag.halkbank.gov.tm/onlineloancre-services/api/loancre/check', { - method: "POST", + method: 'POST', headers: { - Accept: "application/json, text/plain", - "Content-Type": "application/json;charset=UTF-8", + Accept: 'application/json, text/plain', + 'Content-Type': 'application/json;charset=UTF-8', }, body: JSON.stringify({ clientRecipient: { @@ -142,7 +139,7 @@ const PhoneAccept = ({ name: borrowerData.name, surname: borrowerData.surname, availableAmount: borrowerData.availableAmount, - clientType: "recipient", + clientType: 'recipient', signRecipient: borrowerData.signRecipient, }, clientGuarantor: isGuranter @@ -153,7 +150,7 @@ const PhoneAccept = ({ name: guaranterData.name, surname: guaranterData.surname, availableAmount: guaranterData.availableAmount, - clientType: "guarantor", + clientType: 'guarantor', signGuarantor: guaranterData.signGuarantor, } : null, @@ -162,7 +159,7 @@ const PhoneAccept = ({ mrtIsInsuarance: isGuranter ? 0 : 1, termInYears: creditDuration, }), - } + }, ); if (!response.ok) { @@ -181,16 +178,13 @@ const PhoneAccept = ({ const sendCode = async () => { try { - const response = await fetch( - "https://shahsyotag.halkbank.gov.tm/sendOTP", - { - method: "POST", - headers: { "Content-Type": "aplication/json" }, - body: JSON.stringify({ - phone_number: user.mobile_phone, - }), - } - ); + const response = await fetch('https://shahsyotag.halkbank.gov.tm/sendOTP', { + method: 'POST', + headers: { 'Content-Type': 'aplication/json' }, + body: JSON.stringify({ + phone_number: user.mobile_phone, + }), + }); if (!response.ok) { setErrMessage(response.status); @@ -209,22 +203,19 @@ const PhoneAccept = ({ const confirmCode = async () => { try { setIsLoading(true); - const response = await fetch( - "https://shahsyotag.halkbank.gov.tm/validateOTP", - { - headers: { "Content-Type": "aplication/json" }, - method: "POST", + const response = await fetch('https://shahsyotag.halkbank.gov.tm/validateOTP', { + headers: { 'Content-Type': 'aplication/json' }, + method: 'POST', - body: JSON.stringify({ - phone_number: user.mobile_phone, - otp: codeValue, - }), - } - ); + body: JSON.stringify({ + phone_number: user.mobile_phone, + otp: codeValue, + }), + }); const jsonedResponse = await response.json(); - if (jsonedResponse === "OTP validated successfully") { + if (jsonedResponse === 'OTP validated successfully') { loanCreate(); } else { setErrMessage(true); @@ -237,9 +228,9 @@ const PhoneAccept = ({ const response = await fetch( `https://shahsyotag.halkbank.gov.tm/onlineloancre-services/api/loancre`, { - method: "POST", + method: 'POST', headers: { - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, body: JSON.stringify({ clientRecipient: { @@ -249,7 +240,7 @@ const PhoneAccept = ({ name: borrowerData.name, surname: borrowerData.surname, availableAmount: borrowerData.availableAmount, - clientType: "recipient", + clientType: 'recipient', signRecipient: borrowerData.signRecipient, }, clientGuarantor: isGuranter @@ -260,7 +251,7 @@ const PhoneAccept = ({ name: guaranterData.name, surname: guaranterData.surname, availableAmount: guaranterData.availableAmount, - clientType: "guarantor", + clientType: 'guarantor', signGuarantor: guaranterData.signGuarantor, } : null, @@ -269,7 +260,7 @@ const PhoneAccept = ({ mrtIsInsuarance: isGuranter ? 0 : 1, termInYears: creditDuration, }), - } + }, ); if (!response.ok) { @@ -294,25 +285,22 @@ const PhoneAccept = ({ const sendData = async (requestBody) => { try { const headers = { - Accept: "application/json", - "Content-Type": "application/json", + Accept: 'application/json', + 'Content-Type': 'application/json', Authorization: `Bearer ${userToken}`, }; - const response = await fetch( - "https://shahsyotag.halkbank.gov.tm/app/api/quick_loans", - { - method: "POST", - headers: headers, - body: JSON.stringify({ - sign: requestBody.sign, - where_works: recipientWorkPlace, - position: recipientWorkPosition, - mobile_phone: user.mobile_phone, - name: borrowerData.name, - surname: borrowerData.surname, - }), - } - ); + const response = await fetch('https://shahsyotag.halkbank.gov.tm/app/api/quick_loans', { + method: 'POST', + headers: headers, + body: JSON.stringify({ + sign: requestBody.sign, + where_works: recipientWorkPlace, + position: recipientWorkPosition, + mobile_phone: user.mobile_phone, + name: borrowerData.name, + surname: borrowerData.surname, + }), + }); const jsonedResponse = await response.json(); if (!cardDetails) { @@ -328,6 +316,49 @@ const PhoneAccept = ({ } }; + const codeResend = async () => { + try { + const response = await fetch('https://shahsyotag.halkbank.gov.tm/sendOTP', { + method: 'POST', + headers: { 'Content-Type': 'aplication/json' }, + body: JSON.stringify({ + phone_number: user.mobile_phone, + }), + }); + + if (!response.ok) { + setError(true); + throw new Error(`HTTP error! Status: ${response.status}`); + } + + if (response.status !== 200 || response.status !== 201) { + setMessageSend(true); + } + } catch (error) { + console.error(error); + } + }; + + const startTimer = () => { + setTimeLeft(30); // Set initial time + const intervalId = setInterval(() => { + setTimeLeft((prevTimeLeft) => { + if (prevTimeLeft === 1) { + clearInterval(intervalId); + setMessageSend(false); // Reset messageSend state after timer finishes + setResendDisabled(false); // Enable the button again + } + return prevTimeLeft - 1; + }); + }, 1000); + }; + + useEffect(() => { + if (messageSend) { + startTimer(); + } + }, [messageSend]); + const onSubmit = (data) => { if (cardDetails) { confirmCode(); @@ -340,13 +371,13 @@ const PhoneAccept = ({ return (

- {locale === "TKM" - ? "Garaşmagyňyzy haýyş edýäris ..." - : locale === "РУС" - ? "Пожалуйста, подождите..." - : locale === "ENG" - ? "Please wait..." - : "Garaşmagyňyzy haýyş edýäris ..."} + {locale === 'TKM' + ? 'Garaşmagyňyzy haýyş edýäris ...' + : locale === 'РУС' + ? 'Пожалуйста, подождите...' + : locale === 'ENG' + ? 'Please wait...' + : 'Garaşmagyňyzy haýyş edýäris ...'}

); @@ -357,32 +388,28 @@ const PhoneAccept = ({

{errMessage} - {locale === "TKM" - ? "Bir zat ýalňyş ..." - : locale === "РУС" - ? " Ошибка..." - : locale === "ENG" - ? " Error..." - : " Bir zat ýalňyş ..."} + {locale === 'TKM' + ? 'Bir zat ýalňyş ...' + : locale === 'РУС' + ? ' Ошибка...' + : locale === 'ENG' + ? ' Error...' + : ' Bir zat ýalňyş ...'}


- @@ -394,77 +421,69 @@ const PhoneAccept = ({

- {locale === "TKM" + {locale === 'TKM' ? `${ - cardDetails - ? user.mobile_phone - : submitCardDetails["three-d-secure-number"] + cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number'] } Karz ýüzlenmäni tassyklamak üçin belgä iberilen SMS duýduryş koduny giriziň` - : locale === "РУС" + : locale === 'РУС' ? `Для подтверждения кредитной заявки, введите код с СМС оповещения, отправленный на номер ${ - cardDetails - ? user.mobile_phone - : submitCardDetails["three-d-secure-number"] + cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number'] }` - : locale === "ENG" + : locale === 'ENG' ? `To confirm the loan application enter the SMS alert code sent to the number ${ - cardDetails - ? user.mobile_phone - : submitCardDetails["three-d-secure-number"] + cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number'] }` : `${ - cardDetails - ? user.mobile_phone - : submitCardDetails["three-d-secure-number"] + cardDetails ? user.mobile_phone : submitCardDetails['three-d-secure-number'] } Karz ýüzlenmäni tassyklamak üçin belgä iberilen SMS duýduryş koduny giriziň`}

- - {/* + + + {messageSend &&

Time left: {timeLeft} seconds

} {/* {errors.code && {errors.code.message}} */}
{invalidData && (

- {locale === "TKM" - ? "Ýalňyş, maglumatlary barlaň" - : locale === "РУС" - ? "Ошибка, проверьте данные" - : locale === "ENG" - ? "Error, check data" - : "Ýalňyş, maglumatlary barlaň"} + {locale === 'TKM' + ? 'Ýalňyş, maglumatlary barlaň' + : locale === 'РУС' + ? 'Ошибка, проверьте данные' + : locale === 'ENG' + ? 'Error, check data' + : 'Ýalňyş, maglumatlary barlaň'}

)} {tryAgain && (

- {" "} - {locale === "TKM" - ? "Gaýtadan iberip görüň" - : locale === "РУС" - ? "Попробуйте отправить снова" - : locale === "ENG" - ? "Try sending again" - : "Gaýtadan iberip görüň"} + {' '} + {locale === 'TKM' + ? 'Gaýtadan iberip görüň' + : locale === 'РУС' + ? 'Попробуйте отправить снова' + : locale === 'ENG' + ? 'Try sending again' + : 'Gaýtadan iberip görüň'}

)} @@ -472,20 +491,19 @@ const PhoneAccept = ({ @@ -501,17 +519,16 @@ const PhoneAccept = ({ } type="submit" onClick={onSubmit} - className="sign-btn cu-btn" - > + className="sign-btn cu-btn">

- {locale === "TKM" - ? "Dowam et" - : locale === "РУС" - ? "Подтвердить " - : locale === "ENG" - ? "Proceed" - : "Dowam et"} + {locale === 'TKM' + ? 'Dowam et' + : locale === 'РУС' + ? 'Подтвердить ' + : locale === 'ENG' + ? 'Proceed' + : 'Dowam et'}

logout