Merge branch 'main' into NCFRONT-72

This commit is contained in:
smanylov
2026-02-17 18:20:50 +07:00
107 changed files with 7351 additions and 1431 deletions
+104 -11
View File
@@ -1,15 +1,14 @@
'use server'
import { getSessionData, deleteSession } from '@/app/actions/session';
import { testUserData, API_BASE_URL } from '@/app/actions/definitions';
import { tokenLifeExtension } from '@/app/actions/auth';
import { redirect } from 'next/navigation';
export async function getUserData() {
const userEmail = await getSessionData('email');
const token = await getSessionData('token');
/* для теста */
if (userEmail === "test" && token === "1111") {
if (userEmail === 'test' && token === '1111') {
return testUserData;
}
/* для теста */
@@ -18,17 +17,19 @@ export async function getUserData() {
const response = await fetch(`${API_BASE_URL}/v1/api/user?email=${userEmail}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
}
});
if (response.ok) {
return await response.json();
} else {
return null
}
} catch (error) {
console.error('error');
return null
}
}
@@ -42,13 +43,13 @@ export async function getUserFilesInfo() {
version: 1,
msg_id: 20005,
message_body: {
action: "user_files_info",
action: 'user_files_info',
token: token
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -61,8 +62,100 @@ export async function getUserFilesInfo() {
} else {
throw parsed.message_code;
}
} else {
return null
}
} catch (error) {
console.error(`error: ${error}`);
return null
}
}
export async function fetchTariffs() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30001,
message_body: {
action: 'get',
user_token: token
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
const parsed = await response.json()
if (parsed?.message_code === 0) {
return parsed.message_body?.tariffs;
} else {
return []
}
} else {
return null
}
} catch (error) {
return null
}
}
export async function getBuildData() {
try {
const response = await fetch(`${API_BASE_URL}/check/api/build`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
if (response.ok) {
return await response.json();
} else {
return null
}
} catch (error) {
return null;
}
}
export async function fetchINN(inn: string) {
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30004,
message_body: {
inn: inn,
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
const parsed = await response.json()
if (parsed?.message_code === 0) {
return parsed.message_body
} else {
return null
}
} else {
return null
}
} catch (error) {
return null
}
}
+132 -59
View File
@@ -3,6 +3,7 @@
import { loginFormSchema, API_BASE_URL, getSignupFormSchema } from '@/app/actions/definitions';
import { createSession, deleteSession, getSessionData, updateSession } from '@/app/actions/session';
import { redirect } from 'next/navigation';
import { fetchINN } from '@/app/actions/action';
export async function logout() {
const token = await getSessionData('token');
@@ -11,9 +12,9 @@ export async function logout() {
await fetch(`${API_BASE_URL}/v1/api/auth/logout`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
}
});
} catch (error) {
@@ -36,8 +37,8 @@ export async function authorization(
const password = formData.get('password');
/* для теста */
if (email === "test" && password === "test") {
await createSession("1111", "test");
if (email === 'test' && password === 'test') {
await createSession('1111', 'test');
redirect('/pages/dashboard');
}
/* для теста */
@@ -81,13 +82,13 @@ export async function authorization(
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_desc === 'Operation successful') {
if (parsed.message_code === 0) {
await createSession(parsed.message_body.token, email);
} else {
throw (`${parsed.message_code}`);
@@ -130,14 +131,16 @@ export async function authorization(
export type FormState = {
previousState: {
fullName: string;
email: string;
password: string;
confirm_password: string;
phone: string;
companyName: string;
agree: string;
},
fullName?: string | undefined;
email?: string | undefined;
password?: string | undefined;
confirm_password?: string | undefined;
phone?: string | undefined;
companyName?: string | undefined;
agree?: string | undefined;
referralCode?: string | undefined;
inn?: string | undefined;
} | undefined,
mailConfirm?: boolean,
userId?: number,
error: Record<string, string> | null
@@ -147,6 +150,8 @@ export async function registration(
state: FormState | undefined,
formData: FormData,
): Promise<FormState> {
const accountType = formData.get('accountType') as 'b2b' | 'b2c';
const fullName = formData.get('fullName') as string || '';
const email = formData.get('email') as string || '';
const password = formData.get('password') as string || '';
@@ -154,8 +159,10 @@ export async function registration(
const phone = formData.get('phone') as string || '';
const companyName = formData.get('companyName') as string || '';
const agree = formData.get('agree') as string || '';
const referralCode = formData.get('referralCode');
const inn = formData.get('inn') as string || '';
const SignupFormSchema = await getSignupFormSchema();
const SignupFormSchema = await getSignupFormSchema(accountType);
const dataToValidate = {
fullName,
@@ -164,23 +171,41 @@ export async function registration(
password,
confirm_password,
agree,
companyName
...(accountType === 'b2b' && { companyName, inn })
};
const validatedFields = SignupFormSchema.safeParse(dataToValidate);
const validatedFields = await SignupFormSchema.safeParse(dataToValidate);
if (!validatedFields.success) {
console.log(`try to register ${accountType}`);
let confirmedCompanyName: boolean = true;
if (accountType === 'b2b') {
try {
const response = await fetchINN(inn);
confirmedCompanyName = response?.companyName ? true : false;
} catch (error) {
confirmedCompanyName = false;
}
}
if (!validatedFields.success || !confirmedCompanyName) {
const errors: Record<string, string> = {}
JSON.parse(validatedFields.error.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]}&${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
if (validatedFields?.error?.message) {
JSON?.parse(validatedFields?.error?.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]}&${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
}
if (!confirmedCompanyName) {
errors.inn = 'inn-invalid'
}
return {
previousState: {
@@ -189,8 +214,8 @@ export async function registration(
password,
confirm_password,
phone,
companyName,
agree
agree,
...(accountType === 'b2b' && { companyName, inn })
},
error: errors
};
@@ -208,25 +233,47 @@ export async function registration(
email,
phone: phone,
password,
companyName: companyName,
accountType,
...(accountType === 'b2b' && { companyName: companyName, inn: inn }),
...(referralCode !== '' && { referralLink: referralCode })
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
console.log({
fullName: fullName,
email,
phone: phone,
password,
accountType,
...(accountType === 'b2b' && { companyName: companyName, inn: inn }),
...(referralCode !== '' && { referralLink: referralCode })
})
if (response.ok) {
let parsed = await response.json() as {
message_desc: string,
message_body: { token: string, userId: number },
message_code: string
message_code: number
};
console.log(parsed);
if (parsed.message_desc === 'Operation successful') {
if (parsed.message_code === 0) {
console.log(`registration - ${accountType}`);
console.log({
fullName: fullName,
email,
phone: phone,
password,
accountType,
...(referralCode !== '' && { referralLink: referralCode }),
...(accountType === 'b2b' && { companyName: companyName, inn: inn })
});
/* await createSession(parsed.message_body.token, email as string); */
return {
previousState: {
fullName,
@@ -234,14 +281,17 @@ export async function registration(
password,
confirm_password,
phone,
companyName,
agree
agree,
...(referralCode !== '' && { referralLink: referralCode }),
...(accountType === 'b2b' && { companyName: companyName, inn: inn })
},
mailConfirm: true,
userId: parsed.message_body.userId,
error: null
};
} else {
console.log(parsed);
throw parsed;
}
} else {
@@ -249,26 +299,35 @@ export async function registration(
}
} catch (error: unknown) {
const errors: Record<string, string> = {};
if (error) {
const typedError = error as any;
const errors: Record<string, string> = {};
switch (typedError.message_code) {
case 1:
errors['server'] = 'email-or-already-registered'
break;
if (typedError.message_desc === 'Refferal link is not exist') {
errors['server'] = 'referral-link-is-not-exist'
break;
} else {
errors['server'] = 'email-or-already-registered'
break;
}
case 2:
typedError.message_body.fieldErrors.forEach((obj: {
code: string,
field: string
}) => {
if (errors[obj.field]) {
errors[obj.field] = `${errors[obj.field]}&${obj.code.replaceAll('.', '-')}`;
} else {
errors[obj.field] = obj.code.replaceAll('.', '-');
}
});
if (typedError.message_body?.fieldErrors) {
typedError.message_body?.fieldErrors?.forEach((obj: {
code: string,
field: string
}) => {
if (errors[obj.field]) {
errors[obj.field] = `${errors[obj.field]}&${obj.code.replaceAll('.', '-')}`;
} else {
errors[obj.field] = obj.code.replaceAll('.', '-');
}
});
} else {
errors['server'] = 'unknown-error'
}
break;
default:
@@ -284,14 +343,27 @@ export async function registration(
confirm_password,
phone,
companyName,
agree
agree,
inn
},
mailConfirm: false,
error: errors
};
}
throw error;
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone,
companyName,
agree,
inn
},
error: errors
};
}
redirect('/pages/dashboard');
@@ -306,8 +378,8 @@ export async function tokenLifeExtension() {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
version: 1,
@@ -331,11 +403,12 @@ export async function tokenLifeExtension() {
}
export async function confirmEmail(
state: {error: string} | undefined,
state: { error: string } | undefined,
formData: FormData
) {
console.log('confirmEmail');
const emailConfirm = formData.get('emailConfirm') as string || '';
console.log(emailConfirm);
const userId = formData.get('userId') as string || '';
try {
+199
View File
@@ -0,0 +1,199 @@
'use server'
import { API_BASE_URL, getSignupFormSchema } from '@/app/actions/definitions';
import { getSessionData } from '@/app/actions/session';
export type CompanyUserRegistrationFormState = {
previousState: {
fullName: string;
email: string;
password: string;
confirm_password: string;
phone: string;
},
createdUser: string | null
error: Record<string, string> | null
} | undefined;
export async function companyUserRegistration(
state: CompanyUserRegistrationFormState | undefined,
formData: FormData,
): Promise<CompanyUserRegistrationFormState> {
const token = await getSessionData('token');
if (!token) {
return;
}
const fullName = formData.get('fullName') as string || '';
const email = formData.get('email') as string || '';
const password = formData.get('password') as string || '';
const confirm_password = formData.get('confirm_password') as string || '';
const phone = formData.get('phone') as string || '';
const SignupFormSchema = await getSignupFormSchema('b2c');
const dataToValidate = {
fullName,
email,
phone: phone.replace(/[-\(\)\s]/g, ''),
password,
confirm_password,
agree: 'on'
};
const validatedFields = SignupFormSchema.safeParse(dataToValidate);
console.log(`try to register company users ${email}`);
if (!validatedFields.success) {
const errors: Record<string, string> = {}
JSON.parse(validatedFields.error.message).forEach((obj: {
message: string,
path: string
}) => {
if (errors[obj.path[0]]) {
errors[obj.path[0]] = `${errors[obj.path[0]]}&${obj.message}`;
} else {
errors[obj.path[0]] = obj.message;
}
});
console.log('registration error');
console.log(errors);
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone
},
createdUser: null,
error: errors
};
}
try {
const { fullName, email, password, phone } = validatedFields.data;
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 20002,
message_body: {
fullName: fullName,
email,
phone: phone,
password,
accountType: 'b2b',
authToken: token
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json() as {
message_desc: string,
message_body: { token: string },
message_code: number
};
console.log({
fullName: fullName,
email,
phone: phone,
password,
accountType: 'b2b',
authToken: token
});
if (parsed.message_code === 0) {
console.log(`registration - ${email}`);
console.log({
fullName: fullName,
email,
phone: phone,
password
});
return {
previousState: {
fullName: '',
email: '',
password: '',
confirm_password: '',
phone: ''
},
createdUser: fullName,
error: null
}
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error: unknown) {
const errors: Record<string, string> = {};
if (error) {
const typedError = error as any;
switch (typedError.message_code) {
case 1:
errors['server'] = 'email-or-already-registered'
break;
case 2:
if (typedError.message_body?.fieldErrors) {
typedError.message_body?.fieldErrors?.forEach((obj: {
code: string,
field: string
}) => {
if (errors[obj.field]) {
errors[obj.field] = `${errors[obj.field]}&${obj.code.replaceAll('.', '-')}`;
} else {
errors[obj.field] = obj.code.replaceAll('.', '-');
}
});
} else {
errors['server'] = 'unknown-error'
}
break;
default:
errors['server'] = 'request-ended-with-an-error'
break;
}
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone
},
createdUser: null,
error: errors
};
}
return {
previousState: {
fullName,
email,
password,
confirm_password,
phone
},
createdUser: null,
error: errors
};
}
}
+14 -12
View File
@@ -1,5 +1,5 @@
import * as z from 'zod'
import { createValidationSchema } from "@/app/lib/validation-config-parser";
import {createValidationSchema, createValidationSchemaForPassword} from '@/app/lib/validation-config-parser';
import validationConfig from '@/app/lib/validation-config.json';
export type FormState =
@@ -35,30 +35,31 @@ interface ValidationConfig {
const defaultConfig = validationConfig as ValidationConfig;
let cachedSignupSchema: any = null;
let schemaPromise: Promise<any> | null = null;
async function loadConfigFromBackend(): Promise<any> {
async function loadConfigFromBackend(accountType?: 'b2b' | 'b2c'): Promise<any> {
try {
const response = await fetch('/api/validation-config');
if (!response.ok) throw new Error('Failed to load config');
return await response.json();
} catch (error) {
console.error('Using default validation config:', error);
//сейчас выполняем это пока бека нету
/* console.error('Using default validation config:', error); */
return defaultConfig;
}
}
export async function getSignupFormSchema() {
console.log('get scheme');
if (cachedSignupSchema) {
return cachedSignupSchema;
}
export async function getSignupFormSchema(schemaType?: 'b2b' | 'b2c' | 'resetPassword') {
let schemaPromise: Promise<any> | null = null;
let cachedSignupSchema: any = null;
if (!schemaPromise) {
schemaPromise = (async () => {
const config = await loadConfigFromBackend();
cachedSignupSchema = createValidationSchema(config);
if (schemaType === 'resetPassword') {
cachedSignupSchema = createValidationSchemaForPassword(config);
} else {
cachedSignupSchema = createValidationSchema(config, schemaType);
}
return cachedSignupSchema;
})();
}
@@ -66,6 +67,7 @@ export async function getSignupFormSchema() {
return await schemaPromise;
}
// для валидации в реально времени на клиентской странице
export const SignupFormSchema = createValidationSchema(defaultConfig);
+44 -5
View File
@@ -21,8 +21,8 @@ export async function getUserFilesData(page: number, pageSize: number) {
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -42,7 +42,7 @@ export async function getUserFilesData(page: number, pageSize: number) {
}
}
export async function removeUserFile(fileId: string) {
export async function removeUserFile(fileId: string, fullDelete: number) {
const token = await getSessionData('token');
try {
@@ -54,12 +54,13 @@ export async function removeUserFile(fileId: string) {
message_body: {
action: 'delete_file',
file_id: fileId,
full_delete: fullDelete,
token: token
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -75,6 +76,44 @@ export async function removeUserFile(fileId: string) {
throw (`${response.status}`);
}
} catch (error) {
return error
}
}
export async function viewFileInfo(fileId: string) {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 20005,
message_body: {
action: 'file_info',
file_id: fileId,
token: token
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return error
}
+45 -18
View File
@@ -2,6 +2,8 @@
import { API_BASE_URL } from '@/app/actions/definitions';
import { getSessionData } from '@/app/actions/session';
import { FormState } from '@/app/actions/auth';
import { unknown } from 'zod';
interface initMessageBody {
file_name: string,
@@ -12,15 +14,18 @@ interface initMessageBody {
token?: string
}
export async function fileUpload(messageBody: initMessageBody) {
export async function fileUpload(messageBody: initMessageBody, convertTo: string | null | undefined) {
const token = await getSessionData('token');
if (!token) {
return;
}
const message = messageBody;
message.action = "init";
message.action = 'init';
message.token = token;
// нужно будет добавить свойство convertTo в тело запроса он может прийти со значением reject тогда конвертировать не нужно.
// console.log(convertTo);
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
@@ -30,8 +35,8 @@ export async function fileUpload(messageBody: initMessageBody) {
message_body: message
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -68,13 +73,13 @@ export async function cancelUpload(udloadId: string) {
version: 1,
msg_id: 20004,
message_body: {
action: "cancel",
action: 'cancel',
upload_id: udloadId,
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -101,7 +106,12 @@ export async function cancelUpload(udloadId: string) {
}
}
export async function chunkUpload(formData: FormData) {
export type ChunkResponse = {
errorMesage: string | null
fileId?: string
};
export async function chunkUpload(formData: FormData): Promise<ChunkResponse> {
try {
const response = await fetch(`${API_BASE_URL}/api/v1/files/chunk`, {
method: 'POST',
@@ -111,17 +121,34 @@ export async function chunkUpload(formData: FormData) {
if (response.ok) {
let parsed = await response.json();
if (parsed.message_desc === 'Upload cancelled successfully') {
return parsed.message_body;
if (parsed.message_code === 0) {
return {
errorMesage: null,
fileId: parsed.message_body.file_id
}
} else if (parsed.message_desc === 'Duplicate file upload') {
throw 'duplicate-file'
} else if (parsed.message_desc === 'Failed to upload chunk: Failed to upload chunk: User not have tokens for protect') {
throw 'user-not-have-tokens-for-protect'
} else {
throw parsed;
throw 'error'
}
} else {
throw (`${response.status}`);
throw 'error'
}
} catch (error: unknown) {
if (error) {
const typedError = error as any;
return {
errorMesage: typedError
};
} else {
return {
errorMesage: 'error'
};
}
} catch (error) {
return error
}
}
@@ -138,8 +165,8 @@ export async function checkChunkStatus(upload_id: string) {
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
@@ -173,8 +200,8 @@ export async function getAllowedFilesExtensions(type: string) {
}
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
+181
View File
@@ -0,0 +1,181 @@
'use server'
import { getSessionData } from '@/app/actions/session';
import { API_BASE_URL } from '@/app/actions/definitions';
export async function fetchReferralsLevels() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30003,
message_body: {
action: 'levels',
token: token,
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_code === 0) {
return {
referrals: parsed.message_body,
error: null
}
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return {
referrals: [],
error: error
}
}
}
export async function fetchReferralUserStats() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30003,
message_body: {
action: 'userStats',
token: token,
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return {
error: error
}
}
}
export async function fetchReferralInvitees() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30003,
message_body: {
action: 'invitees',
token: token,
pageSize: 100,
pageNumber: 0
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
console.log({
action: 'invitees',
token: token,
pageSize: 10,
pageNumber: 0
})
console.log(parsed);
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return {
error: error
}
}
}
export async function referralRefill() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 30003,
message_body: {
action: 'refill',
token: token,
amount: 1,
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
console.log('referralRefill');
console.log({
action: 'refill',
token: token,
amount: 1,
})
let parsed = await response.json();
console.log(parsed);
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return {
error: error
}
}
}
+126
View File
@@ -0,0 +1,126 @@
'use server'
import { getSessionData } from '@/app/actions/session';
import { API_BASE_URL } from '@/app/actions/definitions';
export async function searchUserFiles(fileId: string) {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/v1/files/${fileId}/similar?similarityLevels=DUPLICATE,SIMILARITY&auth_token=${token}`, {
method: 'GET'
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return error
}
}
export async function searchGlobalFiles(fileId: string, currentPage: number) {
const token = await getSessionData('token');
console.log('searchGlobalFiles');
console.log(currentPage);
//удалить когда поиск будет нормально работать
/* return {
images: [
{
url: 'string1',
pageTitle: `string1 from page ${currentPage}`,
height: 100,
width: 100,
host: 'string1',
pageUrl: 'string1'
},
{
url: 'string1',
pageTitle: `string2 from page ${currentPage}`,
height: 100,
width: 100,
host: 'string1',
pageUrl: 'string1'
},
{
url: 'string1',
pageTitle: `string3 from page ${currentPage}`,
height: 100,
width: 100,
host: 'string1',
pageUrl: 'string1'
}
],
page: 0,
pageSize: 0,
totalPages: 11,
totalResults: 100,
} */
try {
const response = await fetch(`${API_BASE_URL}/api/v1/data`, {
method: 'POST',
body: JSON.stringify({
version: 1,
msg_id: 20007,
message_body: {
file_id: fileId,
page: currentPage,
}
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
let parsed = await response.json();
if (parsed.message_code === 0) {
return parsed.message_body;
} else {
throw parsed;
}
} else {
throw (`${response.status}`);
}
} catch (error) {
return error
}
}
export async function getSearchStats() {
const token = await getSessionData('token');
try {
const response = await fetch(`${API_BASE_URL}/api/check/file_stats`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
}
});
if (response.ok) {
let parsed = await response.json();
return parsed;
} else {
return null;
}
} catch (error) {
return null;
}
}
+8 -3
View File
@@ -97,7 +97,12 @@ export async function getSessionData(type: 'token' | 'email'): Promise<string |
export async function deleteSession() {
console.log('delete session')
const cookieStore = await cookies()
cookieStore.delete('session');
redirect('/login');
try {
const cookieStore = await cookies()
cookieStore.delete('session');
} catch (error) {
} finally {
redirect('/login');
}
}
+2 -2
View File
@@ -15,8 +15,8 @@ export async function vkAuthorization(data : any, codeVerifier: string) {
const response = await fetch(`${API_BASE_URL}/api/v1/vk/authorization/${code}/${state}/${codeVerifier}/${device_id}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
+2 -2
View File
@@ -15,8 +15,8 @@ export async function YandexAuthorization(data: any, codeVerifier: string) {
const response = await fetch(`${API_BASE_URL}/api/v1/yandex/authorization/${code}/${state}/${codeVerifier}/${device_id}`, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (response.ok) {
+43
View File
@@ -0,0 +1,43 @@
'use server'
import { YooCheckout, ICreatePayment } from '@a2seven/yoo-checkout';
import { getSessionData } from '@/app/actions/session';
const checkout = new YooCheckout({ shopId: '1276731', secretKey: 'test_0Yns_0NHV5GJf6ypJ5HC4NSfnLO8SJkw-1PwrVWsDl4' });
const idempotenceKey = '02347fc4-a1f0-49db-807e-f0d67c2ed5a5';
export async function yooKasaCreatePayment(amount: number, tariff: string) {
console.log(amount);
console.log(tariff);
/* return true; */
const userEmail = await getSessionData('email');
const createPayload: ICreatePayment = {
amount: {
value: amount.toLocaleString(),
currency: 'RUB'
},
payment_method_data: {
type: 'bank_card'
},
confirmation: {
type: 'redirect',
return_url: 'test'
},
metadata: {
userId: userEmail,
tariff: tariff
}
};
try {
const payment = await checkout.createPayment(createPayload, Date.now().toLocaleString());
console.log(payment);
return payment?.confirmation.confirmation_url;
/* return payment; */
} catch (error) {
console.error(error);
}
}