0% found this document useful (0 votes)
10 views10 pages

X Access Token Bearer

The document contains code snippets related to a lottery theme management system, focusing on image uploads and theme initialization. It includes functionality for handling different device types (desktop and mobile) and ensures that themes have valid structures to avoid errors. Additionally, it discusses the validation of JSON inputs for themes and the management of lottery IDs within the application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

X Access Token Bearer

The document contains code snippets related to a lottery theme management system, focusing on image uploads and theme initialization. It includes functionality for handling different device types (desktop and mobile) and ensures that themes have valid structures to avoid errors. Additionally, it discusses the validation of JSON inputs for themes and the management of lottery IDs within the application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

x-access-token: Bearer

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlRzWEo0MFFXZHlwSG9mUnNVLUpFWiJ9.eyJodH
RwczovL2FwaS1sb3RvYm9sYS1wZS1kZXZlbG9wbWVudC9jbGFpbXMvYXBwX21ldGFkYXRhLyI6e30sImh0d
HBzOi8vYXBpLWxvdG9ib2xhLXBlLWRldmVsb3BtZW50L2NsYWltcy91c2VyX25hbWUvIjoiYWxlamFuZHJv
QGVsb3Rncm91cC5jb20iLCJpc3MiOiJodHRwczovL2xvdG9ib2xhLXBlLWRldmVsb3BtZW50LmV1LmF1dGg
wLmNvbS8iLCJzdWIiOiJhdXRoMHw2NzY1YmE2OWRlMTk2ZmZjNjE0ODFiMzgiLCJhdWQiOlsiaHR0cHM6Ly
9hcGktbG90b2JvbGEtcGUtZGV2ZWxvcG1lbnQiLCJodHRwczovL2xvdG9ib2xhLXBlLWRldmVsb3BtZW50L
mV1LmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE3MzY5NTU3NjgsImV4cCI6MTczNzA0MjE2OCwic2Nv
cGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCIsImF6cCI6IlFSbWxSZ0tuMHdFTU5GdVpCS1NXZVJNakJweTI
5WGFwIn0.p0GZfv0zM7vQvImBVzi7ddoXs-yPWSXP6e5TyGIUP-IwIPhAG6aS5uXtMF-
jCF0sMku5t2GYUb0wi3kU807G745Lq-05OIaQgkDydsb-f7_ziq44EZeZ5L-
o60ZXlHqMb92kfz4TEGmg3VyKonISRavwVO_boSutdK4Sb0o4MXiUB9OmpKgKwbl0ZoS-
yXhBDPLExAv8QGuJYWI6cTMkjZY3EiwSAvY3FUaBEbu2gfGAtfNYNpA0yXq0pVpUEI9yEkvTj6JtmpoWZB1
JOxvpwNoZtjDYYWUsicjCVLm-FE0cENHfWrmjoQYzffQEFej2mt12H8CAulSmL2mYpqXVpg

<input
name="imageHeroBanner"
accept="image/*"
className="hidden"
id="button-file"
type="file"
onChange={async (e) => {
const file =
e.target.files?.[0];
if (file) {
const uploadedImageUrl
= await readFileAsync(file);
if
(methods.getValues('deviceType') === 'desktop') {

setUploadedImageUrlHeroDesktop(uploadedImageUrl);
} else {

setUploadedImageUrlHeroMobile(uploadedImageUrl);
}
}
}}
/>

// if (!currentTheme) {
// currentTheme = {
// lotteryId,
// desktop: {
// heroBanner: {
// src: '',
// title: '',
// },
// detailsImage: {
// src: '',
// title: '',
// },
// },
// mobile: {
// heroBanner: {
// src: '',
// title: '',
// },
// detailsImage: {
// src: '',
// title: '',
// },
// },
// };

// // Structure added for new theme


// lotteriesThemesList.push(currentTheme);
// }

Este bloque de código está verificando si la variable currentTheme es


falsy (lo que incluye valores como null, undefined, false, etc.). Si currentTheme
es falsy (es decir, no tiene un valor válido o está vacío), entonces se inicializa
con un objeto con ciertas propiedades predeterminadas.

La razón por la que se hace esto es asegurarse de que currentTheme siempre tenga un
valor válido, especialmente cuando más adelante se espera manipularlo o utilizarlo
dentro de un array (lotteriesThemesList). Si currentTheme no está inicializado
correctamente, se pueden generar errores al intentar acceder a sus propiedades más
adelante.

En resumen:

Si currentTheme no tiene un valor asignado (es null, undefined, etc.), se le


asigna un objeto con una estructura predeterminada.
Este objeto predeterminado tiene valores por defecto para las propiedades
lotteryId, desktop, y mobile.
Luego, este objeto se agrega al array lotteriesThemesList con
push(currentTheme).

Esto garantiza que la lista lotteriesThemesList tenga una estructura consistente,


sin elementos null o undefined, evitando errores posteriores.

<Button
variant="outlined"
component="label"
sx={{
mt: 2,
borderRadius: '5px',
border: 'none',
backgroundColor: '#f5f5f5',
pt: (

methods.getValues('deviceType') === 'desktop'


?
uploadedImageUrlDetailsDesktop
:
uploadedImageUrlDetailsMobile
)
? '90px'
: '30px',
pb: (

methods.getValues('deviceType') === 'desktop'


?
uploadedImageUrlDetailsDesktop
:
uploadedImageUrlDetailsMobile
)
? '90px'
: '30px',
width: '300px',
height: '150px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
overflow: 'hidden',
...
(methods.getValues('deviceType') === 'desktop' &&

uploadedImageUrlDetailsDesktop && {
width: '100%',
height: '100%',
}),
...
(methods.getValues('deviceType') === 'mobile' &&

uploadedImageUrlDetailsMobile && {
width: '100%',
height: '100%',
}),
}}
>
{(
methods.getValues('deviceType')
=== 'desktop'
?
uploadedImageUrlDetailsDesktop
:
uploadedImageUrlDetailsMobile
) ? (
<img
src={

methods.getValues('deviceType') === 'desktop'


?
uploadedImageUrlDetailsDesktop.url
:
uploadedImageUrlDetailsMobile.url
}
alt="Uploaded preview"
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
borderRadius: '8px',
minWidth: '150px',
minHeight: '150px',
}}
/>
) : (
t('uploadPicture')
)}
<input
name="imageDetails"
accept="image/*"
className="hidden"
id="button-file"
type="file"
onChange={async (e) => {
const file =
e.target.files?.[0];
if (file) {
const uploadedImageUrl
= await readFileAsync(file);
if
(methods.getValues('deviceType') === 'desktop') {

setUploadedImageUrlDetailsDesktop(uploadedImageUrl);
} else {

setUploadedImageUrlDetailsMobile(uploadedImageUrl);
}
}
}}
/>
</Button>

polos bobos (fucsia, camel, melon)


s/12 3x s/30
polos bobos manga s/12
3x s/30
polo boton s/12
3x s/30
bvd s/14 3x s/33
short harem s/14
3x s/33
bikers s/11 3x s/29
faldas s/28 2x s/49
body bobitos print s/10
body bobitos pima (antiguo)
s/10
body bvd (antiguo) s/10
calzones tripack s/14
2x s/25
calzoncillo
tripack s/14 2x s/25
useEffect(() => {
const theme = lotteryThemes?.find((t) => t.lotteryId === lotteryId);
if (!theme) return;

const normalizeImage = (image?: {src?: string; title?: string}) => ({


src: image?.src ?? null,
title: image?.title ?? 'filename',
});

setCurrentTheme({
...theme,
desktop: {
heroBanner: normalizeImage(theme.desktop?.heroBanner),
detailsImage: normalizeImage(theme.desktop?.detailsImage),
},
mobile: {
heroBanner: normalizeImage(theme.mobile?.heroBanner),
detailsImage: normalizeImage(theme.mobile?.detailsImage),
},
});

const deviceType = methods.watch('deviceType');

// Obtener imágenes desde `lotteryThemes`


const heroBannerSrc = theme[deviceType]?.heroBanner?.src || null;
const detailsImageSrc = theme[deviceType]?.detailsImage?.src || null;

// Obtener imágenes desde `getValues`


const heroBannerFormValue = methods.getValues('imageHeroBanner') || null;
const detailsImageFormValue = methods.getValues('imageDetails') || null;

const updateImageState = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
setImage: React.Dispatch<React.SetStateAction<any>>,
src: string | null,
formValue: string | null
) => {
const finalSrc = formValue || src; // Priorizar el valor del formulario
si está definido
setImage(finalSrc ? {url: finalSrc, base64: '', fileName: 'filename',
data: '', mimeType: ''} : null);
};

if (deviceType === 'desktop') {


updateImageState(setUploadedImageUrlHeroDesktop, heroBannerSrc,
heroBannerFormValue);
updateImageState(setUploadedImageUrlDetailsDesktop, detailsImageSrc,
detailsImageFormValue);
} else {
updateImageState(setUploadedImageUrlHeroMobile, heroBannerSrc,
heroBannerFormValue);
updateImageState(setUploadedImageUrlDetailsMobile, detailsImageSrc,
detailsImageFormValue);
}
}, [lotteryId, lotteryThemes]);
COMPONENTE SELECT PARA CREATE JSON CON ID

import FuseLoading from '@fuse/core/FuseLoading';


import {useFormContext, Controller} from 'react-hook-form';
import {Select, MenuItem} from '@mui/material';
import {useTranslation} from 'react-i18next';
import {TUpdateConfigurationForm} from '../lottery-theme-create-schema';
import {useEffect, useMemo} from 'react';
import {fetchLotteries} from '@lottob/graphql/queries/lotteries-id';
import {useQuery} from '@tanstack/react-query';
import {fetchLotteryThemeByName} from '@lottob/graphql/queries/lottery-value-theme-
by-name';

type LotteryIdSelectProps = {
lotteryId?: string;
setToastMessage?: (message: string) => void;
onLotteryIdChange: (lotteryId: string) => void;
};

export function LotteryIdSelect({lotteryId, setToastMessage, onLotteryIdChange}:


LotteryIdSelectProps) {
const {t} = useTranslation('lotteryThemePage');

const {control, setValue} = useFormContext<TUpdateConfigurationForm>();

useEffect(() => {
if (lotteryId) {
setValue('lotteryId', lotteryId);
}
}, [lotteryId, setValue]);

return (
<Controller
control={control}
name="lotteryId"
render={({field}) => (
<>
<Select {...field} labelId="lottery-select-label" displayEmpty
className="w-[400px] mb-[54px]">
{lotteryId && <MenuItem
value={lotteryId}>{lotteryId}</MenuItem>}
</Select>
</>
)}
/>
);
}

<LotteryIdSelect
lotteryId={lotteryId}
onLotteryIdChange={(selectedLotteryId) => {
console.log('LotteryId seleccionado:',
selectedLotteryId);
methods.setValue('lotteryId',
selectedLotteryId);
setLotteryId(selectedLotteryId);
}}
/>

useEffect(() => {
const newLotteryId = uuid();
console.log('Nuevo lotteryId generado:', newLotteryId);
setLotteryId(newLotteryId);
setTimeout(() => {
methods.setValue('lotteryId', newLotteryId);
}, 0);

const copiedTheme = sessionStorage.getItem('copiedLotteryTheme');


if (copiedTheme) {
console.log('Copiando themeJSON desde sessionStorage:', copiedTheme);
setTimeout(() => {
methods.setValue('themeJSON', copiedTheme);
}, 0);
}
return () => {
console.log('Limpiando sessionStorage');
sessionStorage.removeItem('copiedLotteryTheme');
};
}, [methods]);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++
onsuccess:
queryClient.setQueryData(['lotteryTheme'], (oldData: any) => {
if (!oldData) return oldData;
const updatedValue = JSON.parse(data.configuration.value) as
ILotteryThemeDatum[];
return { ...oldData, configuration: { ...oldData.configuration, value:
JSON.stringify(updatedValue) } };
});

const handleUpdateTheme = async (data: TUpdateConfigurationForm) => {


const payload: UpdateConfigurationDto = {
configurationName: 'lottery_themes',
payload: {
value: data.themeJSON,
},
};

try {
await createThemeMutation(payload);

setToastMessage(t('updatedSuccessfully'));

setIsSaved(true);
} catch (error) {
setToastMessage(t('failedTheme'));
}
};

// Validar el JSON pegado


const validationError =
validateJSONInput(copiedTheme);
setIsJSONValid(!validationError);
if (validationError) {
methods.setError('themeJSON', {
type: 'manual',
message: validationError,
});
} else {

methods.clearErrors('themeJSON');
}
// Validar el JSON
inicial
const validationError = validateJSONInput(jsonString);
setIsJSONValid(!validationError);

if (validationError) {
methods.setError('themeJSON', {
type: 'manual',
message: validationError,
});
} else {
methods.clearErrors('themeJSON');
}

// Revalidar formulario
methods.trigger('themeJSON');

useEffect(() => {
if (lotteryThemes && lotteryId) {
const theme = lotteryThemes.find((t) => t.lotteryId === lotteryId);

if (theme) {
const {name, lotteryId, configurationName, ...filteredTheme} =
theme;
//const jsonString = JSON.stringify(filteredTheme, null, 2);

// Validar el JSON inicial


const validationError =
validateJSONInput(JSON.stringify(filteredTheme));

methods.setValue('themeJSON', filteredTheme);
methods.setValue('lotteryId', lotteryId);
setIsJSONValid(!validationError);

if (validationError) {
methods.setError('themeJSON', {
type: 'manual',
message: validationError,
});
} else {
methods.clearErrors('themeJSON');
}
// Revalidar formulario
methods.trigger('themeJSON');
}
}
}, [lotteryId, lotteryThemes, methods]);

You might also like