Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 user get consumables if having ♻️ refactor of mentorshipService #1587

Merged
Merged
5 changes: 5 additions & 0 deletions public/locales/en/workshops.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"in-person-confirm": "This is an in-person event that will take place in {{address}}. Do you still want to confirm your attendance?",
"confirm-attendance": "Yes, I will be there",
"deny-attendance" : "No, I will not attend",
"denny-access":{
"description": "This is a private event, only students with access to",
"button": "You don't have access to this event",
"can-join": "can join"
},
"form": {
"title": "Join this event",
"description": "Sign in to join other coders live solving technical or career challenges.",
Expand Down
5 changes: 5 additions & 0 deletions public/locales/es/workshops.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"in-person-confirm": "Este es un evento presencial que se llevará a cabo en {{address}}. ¿Aún quieres confirmar tu asistencia?",
"confirm-attendance": "Si, si asistiré",
"deny-attendance" : "No, no asistiré",
"denny-access":{
"description": "",
lumi-tip marked this conversation as resolved.
Show resolved Hide resolved
"button": "No tienes acceso a este evento.",
"can-join": "pueden entrar"
},
"form": {
"title": "Únete a este evento",
"description": "Inicia sesión para unirte a otros programadores en vivo resolviendo desafíos técnicos o profesionales.",
Expand Down
25 changes: 20 additions & 5 deletions src/common/components/SupportSidebar/Mentoring.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@ function Mentoring({
return [];
};

const sortByConsumptionAvailability = (allConsumables) => allConsumables.sort((a, b) => {
lumi-tip marked this conversation as resolved.
Show resolved Hide resolved
const balanceA = a?.balance?.unit;
const balanceB = b?.balance?.unit;

if (balanceA === -1 && balanceB !== -1) return -1;
if (balanceA !== -1 && balanceB === -1) return 1;

if (balanceA > 0 && balanceB <= 0) return -1;
if (balanceA <= 0 && balanceB > 0) return 1;

return 0;
});

const getMentorsAndConsumables = async () => {
const mentors = await getAllMentorsAvailable();
const reqConsumables = await bc.payment().service().consumable()
Expand All @@ -141,7 +154,8 @@ function Mentoring({
}))));

const allConsumables = await Promise.all(reqConsumables);
setConsumables(allConsumables);
const sortedConsumables = sortByConsumptionAvailability(allConsumables);
setConsumables(sortedConsumables);
setAllMentorsAvailable(mentors);
};

Expand All @@ -153,7 +167,6 @@ function Mentoring({

useEffect(() => {
const existsCohortSession = typeof cohortSession?.available_as_saas === 'boolean';

if (existsCohortSession) {
setIsAvailableForConsumables(cohortSession?.available_as_saas);
}
Expand All @@ -164,9 +177,11 @@ function Mentoring({
}
}, [allCohorts]);

const mentorshipService = consumables?.mentorship_service_sets?.find(
(c) => c?.slug.toLowerCase() === subscriptionData?.selected_mentorship_service_set?.slug.toLowerCase(),
);
const mentorshipService = consumables?.length > 0 ? consumables?.find(
(c) => subscriptions.some(
(s) => c?.slug.toLowerCase() === s?.selected_mentorship_service_set?.slug.toLowerCase(),
),
) : {};

return !isLoading && user?.id && (
<Box>
Expand Down
19 changes: 16 additions & 3 deletions src/common/components/SupportSidebar/MentoringConsumables.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ function MentoringConsumables({
}
}, [allMentorsAvailable]);

const checkForConsumableAvailable = (consumableList, serviceSelected) => {
const filteredConsumables = consumableList.filter((consumable) => consumable?.mentorship_services?.some((service) => serviceSelected?.slug === service.slug));
lumi-tip marked this conversation as resolved.
Show resolved Hide resolved

const validConsumable = filteredConsumables.find((consumable) => consumable?.balance?.unit === -1 || consumable?.balance?.unit > 0);

if (validConsumable) {
return validConsumable;
}
const balanceZeroConsumable = filteredConsumables.find((consumable) => consumable?.balance?.unit === 0);
return balanceZeroConsumable;
};

const manageMentorsData = (service, data) => {
reportDatalayer({
dataLayer: {
Expand All @@ -153,12 +165,13 @@ function MentoringConsumables({
mentorship_service: service?.slug,
},
});
const relatedConsumables = consumables.find((consumable) => consumable?.mentorship_services?.some((c) => c?.slug === service?.slug));
const relatedConsumable = checkForConsumableAvailable(consumables, service);

setProgramMentors(data);
setConsumableOfService({
...relatedConsumables,
...relatedConsumable,
balance: {
unit: service?.academy?.available_as_saas === false ? -1 : relatedConsumables?.balance?.unit,
unit: service?.academy?.available_as_saas === false ? -1 : relatedConsumable?.balance?.unit,
},
available_as_saas: service?.academy?.available_as_saas,
});
Expand Down
58 changes: 50 additions & 8 deletions src/pages/workshops/[event_slug].jsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ function Page({ eventData, asset }) {
const [dataToGetAccessModal, setDataToGetAccessModal] = useState({});
const [isFetchingDataForModal, setIsFetchingDataForModal] = useState(false);
const [noConsumablesFound, setNoConsumablesFound] = useState(false);
const [denyAccessToEvent, setDenyAccessToEvent] = useState(false);

const router = useRouter();
const { locale } = router;
Expand Down Expand Up @@ -350,9 +351,36 @@ function Page({ eventData, asset }) {
});
};

const sortByConsumptionAvailability = (consum) => consum.sort((a, b) => {
const balanceA = a?.balance?.unit;
const balanceB = b?.balance?.unit;

if (balanceA === -1 && balanceB !== -1) return -1;
if (balanceA !== -1 && balanceB === -1) return 1;

if (balanceA > 0 && balanceB <= 0) return -1;
if (balanceA <= 0 && balanceB > 0) return 1;

return 0;
});

const getSubscriptionForCurrentEvent = () => {
if (!subscriptions || !event?.event_type?.slug) return [];
const currentEventSlug = event.event_type.slug;

const filteredSubscriptions = subscriptions.filter((subscription) => {
const eventTypes = subscription.selected_event_type_set?.event_types || [];
return eventTypes.some((eventType) => eventType.slug === currentEventSlug);
});

return filteredSubscriptions;
};

const consumableEventList = consumables?.data?.event_type_sets || [];
const currentConsumable = consumableEventList?.length > 0 ? consumableEventList?.find(
(c) => subscriptions.some(
const availableConsumables = sortByConsumptionAvailability(consumableEventList);
const subscriptionsForCurrentEvent = getSubscriptionForCurrentEvent();
const currentConsumable = availableConsumables?.length > 0 ? availableConsumables?.find(
(c) => subscriptionsForCurrentEvent.some(
(s) => c?.slug.toLowerCase() === s?.selected_event_type_set?.slug.toLowerCase(),
),
) : {};
Expand All @@ -362,6 +390,18 @@ function Page({ eventData, asset }) {
const existsNoAvailableAsSaas = myCohorts.some((c) => c?.cohort?.available_as_saas === false);
const isFreeForConsumables = event?.free_for_all || finishedEvent || (event?.free_for_bootcamps === true && existsNoAvailableAsSaas);

console.log('AAAAAAAAAA', availableConsumables);
console.log('CURRENT CONSUMABLE', currentConsumable);
console.log('suscription for current event', subscriptionsForCurrentEvent);
console.log('SUSCRIPCIONT', subscriptions);

useEffect(() => {
if (subscriptionsForCurrentEvent.length === 0) setDenyAccessToEvent(true);
else {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else setDenyAccessToEvent(false);

setDenyAccessToEvent(false);
}
}, [subscriptionsForCurrentEvent]);

const dynamicFormInfo = () => {
if (finishedEvent) {
return ({
Expand All @@ -374,7 +414,7 @@ function Page({ eventData, asset }) {
title: '',
childrenDescription: (
<Text size="14px" fontWeight={700} lineHeight="18px">
{t('no-consumables.description')}
{!denyAccessToEvent ? t('no-consumables.description') : `${t('denny-access.description')} '${event?.event_type?.name}' ${t('denny-access.can-join')}`}
</Text>
),
});
Expand Down Expand Up @@ -876,7 +916,7 @@ function Page({ eventData, asset }) {
<Box display="flex" flexDirection="column" alignItems="center">
{hasFetchedAndNoConsumablesToUse && (
<Text marginBottom="10px" size="14px" fontWeight={700} lineHeight="18px">
{t('no-consumables.description')}
{!denyAccessToEvent ? t('no-consumables.description') : `${t('denny-access.description')} '${event?.event_type?.name}' ${t('denny-access.can-join')}`}
</Text>
)}
<Button
Expand All @@ -889,10 +929,11 @@ function Page({ eventData, asset }) {
alignItems="center"
gridGap="10px"
width="100%"
isDisabled={denyAccessToEvent}
background={hexColor.greenLight}
>
{t('no-consumables.get-more-workshops')}
<Icon icon="longArrowRight" width="24px" height="10px" color="currentColor" />
{denyAccessToEvent ? t('no-consumables.get-more-workshops') : t('denny-access.button')}
{!denyAccessToEvent && <Icon icon="longArrowRight" width="24px" height="10px" color="currentColor" />}
</Button>
</Box>
)}
Expand Down Expand Up @@ -1028,10 +1069,11 @@ function Page({ eventData, asset }) {
alignItems="center"
gridGap="10px"
width="100%"
isDisabled={denyAccessToEvent}
background={hexColor.greenLight}
>
{t('no-consumables.get-more-workshops')}
<Icon icon="longArrowRight" width="24px" height="10px" color="currentColor" />
{!denyAccessToEvent ? t('no-consumables.get-more-workshops') : t('denny-access.button')}
{!denyAccessToEvent && <Icon icon="longArrowRight" width="24px" height="10px" color="currentColor" />}
</Button>
</Box>
) : (
Expand Down
74 changes: 37 additions & 37 deletions src/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,24 @@ const slugify = (str) => (typeof str === 'string' ? str
.replace(/^-+|-+$/g, '')
: '');

const unSlugify = (str, capitalize = false) => (typeof str === 'string'
? str
.replace(/-/g, ' ')
.replace(
/\w\S*/g,
(txt) => {
const firstLetter = capitalize ? txt.charAt(0).toUpperCase() : txt.charAt(0);
return firstLetter + txt.substring(1).toLowerCase();
},
)
: '');
const unSlugify = (str, capitalize = false) => (typeof str === 'string'
? str
.replace(/-/g, ' ')
.replace(
/\w\S*/g,
(txt) => {
const firstLetter = capitalize ? txt.charAt(0).toUpperCase() : txt.charAt(0);
return firstLetter + txt.substring(1).toLowerCase();
},
)
: '');

const unSlugifyCapitalize = (str) => (typeof str === 'string' ? str
.replace(/-/g, ' ')
.replace(
/\w\S*/g,
(txt) => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase(),
)
/\w\S*/g,
(txt) => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase(),
)
: '');

function slugToTitle(slug) {
Expand All @@ -60,7 +60,7 @@ function slugToTitle(slug) {
return word.charAt(0) + word.slice(1);
},
).join(' ').replace(/([A-Z])/g, ' $1')
.trim();
.trim();
}

const cleanQueryStrings = (url) => url.split('?')[0];
Expand Down Expand Up @@ -116,8 +116,8 @@ const devLog = (msg, ...params) => { // Relevant logs only in dev mode
const devLogTable = (msg, array) => { // Relevant table logs with title only in dev mode
if (isDevMode) {
console.group();
console.log(`%c🛠️${msg}`, 'font-size: 14px');
console.table(array);
console.log(`%c🛠️${msg}`, 'font-size: 14px');
console.table(array);
console.groupEnd();
}
};
Expand All @@ -127,19 +127,19 @@ const objectAreNotEqual = (t1, t2) => Object.keys(t1).map((l) => t1[l] === t2[l]
function removeURLParameter(url, parameter) {
const urlparts = url.split('?');
if (urlparts.length >= 2) {
const prefix = `${encodeURIComponent(parameter)}=`;
const pars = urlparts[1].split(/[&;]/g);

// reverse iteration as may be destructive
// eslint-disable-next-line no-plusplus
for (let i = pars.length; i-- > 0;) {
// idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
const prefix = `${encodeURIComponent(parameter)}=`;
const pars = urlparts[1].split(/[&;]/g);

// reverse iteration as may be destructive
// eslint-disable-next-line no-plusplus
for (let i = pars.length; i-- > 0;) {
// idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}

return urlparts[0] + (pars.length > 0 ? `?${pars.join('&')}` : '');
return urlparts[0] + (pars.length > 0 ? `?${pars.join('&')}` : '');
}
return url;
}
Expand Down Expand Up @@ -297,7 +297,7 @@ const getQueryString = (key, def) => {
const createArray = (length) => Array.from({ length }, (_, i) => i);
const lengthOfString = (string) => (typeof string === 'string' ? string?.replaceAll(/\s/g, '').length : 0);

const syncInterval = (callback = () => {}) => {
const syncInterval = (callback = () => { }) => {
const now = new Date();
const secondsToNextMinute = 60 - now.getSeconds();

Expand Down Expand Up @@ -348,7 +348,7 @@ function adjustNumberBeetwenMinMax({ number = 1, min = 1, max = 10 }) {

function getDiscountedPrice({ numItems, maxItems, discountRatio, bundleSize, pricePerUnit, startDiscountFrom = 0 }) {
if (numItems > maxItems) {
console.log('numItems cannot be greater than maxItems');
console.log('numItems cannot be greater than maxItems');
}

let totalDiscountRatio = 0;
Expand All @@ -357,12 +357,12 @@ function getDiscountedPrice({ numItems, maxItems, discountRatio, bundleSize, pri
const maxDiscount = 0.2;

for (let i = startDiscountFrom; i < Math.floor(numItems / bundleSize); i += 1) {
totalDiscountRatio += currentDiscountRatio;
currentDiscountRatio -= currentDiscountRatio * discountNerf;
totalDiscountRatio += currentDiscountRatio;
currentDiscountRatio -= currentDiscountRatio * discountNerf;
}

if (totalDiscountRatio > maxDiscount) {
totalDiscountRatio = maxDiscount;
totalDiscountRatio = maxDiscount;
}

const amount = pricePerUnit * numItems;
Expand Down Expand Up @@ -402,11 +402,11 @@ function cleanObject(obj) {

function decodeBase64(encoded) {
// Decode from base64 and convert to UTF-8 and remove � characters if they exist
const decoded = new TextDecoder('utf-8')
.decode(Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0)))
.replace(/�/g, '');
const decoded = new TextDecoder('utf-8')
.decode(Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0)))
.replace(/�/g, '');

return decoded;
return decoded;
}

export {
Expand Down