Skip to content

Commit

Permalink
update activity children
Browse files Browse the repository at this point in the history
  • Loading branch information
ousamazemzami committed Dec 13, 2024
1 parent 1f05d06 commit cf844f5
Show file tree
Hide file tree
Showing 8 changed files with 76 additions and 31 deletions.
21 changes: 21 additions & 0 deletions server/controllers/activity.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import type { JSONSchemaType } from 'ajv';
import type { NextFunction, Request, Response } from 'express';
import { IsNull } from 'typeorm';
Expand Down Expand Up @@ -450,6 +451,11 @@ activityController.put({ path: '/:id', userType: UserType.TEACHER }, async (req:
activity.data = data.data ?? activity.data;
activity.content = data.content ?? activity.content;

// update activity children
if (!activity.parentActivityId && activity.status === ActivityStatus.PUBLISHED) {
await updateActivityChildren(activity, data as UpdateActivity);
}

// logic to create a activity game
if (activity.type === ActivityType.GAME && activity.status === ActivityStatus.PUBLISHED && activity.data) {
const gamesData = activity.data as GamesData;
Expand Down Expand Up @@ -486,6 +492,21 @@ activityController.put({ path: '/:id', userType: UserType.TEACHER }, async (req:
res.sendJSON(activity);
});

// --- update activity children ---
async function updateActivityChildren(activity: Activity, data: UpdateActivity): Promise<void> {
const children = await AppDataSource.getRepository(Activity).find({ where: { parentActivityId: activity.id } });

for (const child of children) {
child.responseActivityId = data.responseActivityId ?? child.responseActivityId ?? null;
child.responseType = data.responseType ?? child.responseType ?? null;
child.isPinned = data.isPinned ?? child.isPinned;
child.displayAsUser = data.displayAsUser ?? child.displayAsUser;
child.data = data.data ?? child.data;
child.content = data.content ?? child.content;
await AppDataSource.getRepository(Activity).save(child);
}
}

// --- create a game ---
const createGame = async (data: GameData, activity: Activity): Promise<Game> => {
const id = data.gameId;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
import Link from 'next/link';
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';
Expand All @@ -16,24 +17,19 @@ import { htmlToText } from 'src/utils';
export default function ActivityCard({
activity,
modifiedDisabled,
actions = ['configure', 'update', 'delete'],
}: {
activity: Pick<Activity, 'images' | 'content' | 'phase' | 'data' | 'id' | 'status'>;
activity: Pick<Activity, 'images' | 'content' | 'phase' | 'data' | 'id' | 'status' | 'type'>;
modifiedDisabled?: boolean;
actions?: ('configure' | 'update' | 'delete')[];
}) {
const publishActivity = usePublishActivity({ activityId: activity.id });
const howManyChildren = useGetChildrenActivitiesById({ id: Number(activity.id) });
// eslint-disable-next-line
// @ts-ignore
const publishDate = new Date(activity.publishDate);
const formattedDate = new Intl.DateTimeFormat('fr-FR', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).format(publishDate);

const subtitle = `Publié le ${formattedDate} dans ${howManyChildren.data?.length} Village-Monde`;
const queryClient = useQueryClient();
const router = useRouter();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);

const title: string = activity?.data?.title ? (activity.data.title as string) : '';
const isImageUrl = activity.content.find((e) => e.type === 'image')?.value;
const imageUrl: string = isImageUrl ? isImageUrl : 'https://placehold.co/600x400?text=No Picture';
Expand All @@ -44,8 +40,16 @@ export default function ActivityCard({
return acc;
}, '');

const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
// eslint-disable-next-line
// @ts-ignore
const publishDate = new Date(activity.publishDate);
const formattedDate = new Intl.DateTimeFormat('fr-FR', {
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).format(publishDate);
const subtitle = `Publié le ${formattedDate} dans ${howManyChildren.data?.length} Village-Monde`;

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
Expand All @@ -55,14 +59,17 @@ export default function ActivityCard({
router.reload();
setAnchorEl(null);
};
const handleModified = () => {
if (activity.status === 0) {
router.push(`/admin/newportal/publier/prepublish/edit/${activity.id}`);
} else {
const handleUpdate = () => {
console.log(activity);
if (activity.type === 5) {
router.push(`/admin/newportal/contenulibre/edit/1/${activity.id}`);
}
setAnchorEl(null);
};

const handleConfigure = () => {
router.push(`/admin/newportal/publier/prepublish/edit/${activity.id}`);
};
const handleClose = () => {
setAnchorEl(null);
};
Expand Down Expand Up @@ -112,10 +119,13 @@ export default function ActivityCard({
'aria-labelledby': 'basic-button',
}}
>
<MenuItem onClick={handleModified} disabled={modifiedDisabled}>
Configurer
</MenuItem>
<MenuItem onClick={handleDelete}>Supprimer</MenuItem>
{actions.includes('configure') && (
<MenuItem onClick={handleConfigure} disabled={modifiedDisabled}>
Configurer
</MenuItem>
)}
{actions.includes('delete') && <MenuItem onClick={handleUpdate}>Modifier</MenuItem>}
{actions.includes('delete') && <MenuItem onClick={handleDelete}>Supprimer</MenuItem>}
</Menu>
</>
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ type Props = {
noDataText: string;
buttonAction: () => void;
modifiedDisabled?: boolean;
actions?: ('configure' | 'update' | 'delete')[];
};

export default function ActivityCardAdminList({ title, activities, svgNoData, noDataText, buttonAction, modifiedDisabled }: Props) {
export default function ActivityCardAdminList({ title, activities, svgNoData, noDataText, buttonAction, modifiedDisabled, actions }: Props) {
const isMobile = useMediaQuery('(max-width: 768px)');

return (
Expand Down Expand Up @@ -48,7 +49,7 @@ export default function ActivityCardAdminList({ title, activities, svgNoData, no
<div key={activity.id} style={{ width: isMobile ? '100%' : '50%' }}>
{/* eslint-disable-next-line */}
{/* @ts-ignore */}
<ActivityCardAdmin activity={activity} modifiedDisabled={modifiedDisabled} />
<ActivityCardAdmin actions={actions} activity={activity} modifiedDisabled={modifiedDisabled} />
</div>
))}
</div>
Expand Down
5 changes: 0 additions & 5 deletions src/contexts/activityContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -354,11 +354,6 @@ export const ActivityContextProvider = ({ children }: React.PropsWithChildren<Re
}

const queryKey = ['activityById', activityRef.current.id];
if (activityRef.current.status !== ActivityStatus.DRAFT && !publish) {
return {
success: false,
}; // don't save draft for already published activities.
}
if (!publish) {
clearTimeout(draftStepTimeout.current);
setDraftStep(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const ContenuLibre = () => {

const onModified = async () => {
setIsLoading(true);
const { success } = await save(false);
const { success } = await save(activity?.status === 0 ? true : false);
if (success) {
setDraft(null);
router.push('/admin/newportal/contenulibre/success');
Expand Down
1 change: 1 addition & 0 deletions src/pages/admin/newportal/publier/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const Publier = () => {
svgNoData={<PelicoStar style={{ height: '6rem', width: '6rem' }} />}
buttonAction={() => router.push('/admin/newportal/publier/draft')}
modifiedDisabled={false}
actions={['update', 'delete']}
/>
</div>
<div style={{ margin: 10 }}>
Expand Down
20 changes: 19 additions & 1 deletion src/pages/admin/newportal/publier/prepublish/edit/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,24 @@ const ModifPrepublish = () => {
}
};

const isModificationDisabled = () => {
if (isLoading) return true;

const publishedVillageIds = childrenActivities.map((activity: Activity) => activity.villageId).filter((id: number) => id !== undefined); // Exclude undefined IDs

const hasPublishedVillages = publishedVillageIds.length > 0;
const hasSelectedVillages = selectedVillages.length > 0;

// Check if published and selected have the same numbers
const areVillagesTheSame =
hasPublishedVillages &&
hasSelectedVillages &&
publishedVillageIds.length === selectedVillages.length &&
publishedVillageIds.every((id: number) => selectedVillages.includes(id));

return (selectedVillages.length < 1 && publishedVillageIds.length === 0) || areVillagesTheSame;
};

return (
<div style={{ display: 'flex', flexDirection: 'column', maxWidth: '80vw' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', paddingBottom: '10px' }}>
Expand All @@ -208,7 +226,7 @@ const ModifPrepublish = () => {
<h1>{activityParent?.data?.title}</h1>
</div>
<div>
<Button variant="contained" color="primary" onClick={handlePublish} disabled={isLoading || selectedVillages.length < 1}>
<Button variant="contained" color="primary" onClick={handlePublish} disabled={isModificationDisabled()}>
Modifier
{isLoading && (
<Box sx={{ display: 'flex', paddingLeft: '1rem' }}>
Expand Down
1 change: 0 additions & 1 deletion src/pages/contenu-libre/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-console */
import { useRouter } from 'next/router';
import React from 'react';

Expand Down

0 comments on commit cf844f5

Please sign in to comment.