Skip to content

Commit

Permalink
Merge pull request #41 from fga-eps-mds/fix#144/ordenacao-pontos-de-p…
Browse files Browse the repository at this point in the history
…artida

fix(#144):Arrumando Ordenação dos pontos de partidas
  • Loading branch information
DaviMatheus authored Sep 5, 2024
2 parents 3bea937 + 81f7063 commit 146d811
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 76 deletions.
46 changes: 29 additions & 17 deletions src/app/starting-points/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,29 @@ import { UpdateStartPointForm } from '@/components/forms/editStartPoint.form';

const StartPointPage: React.FC = () => {
const { data: session } = useSession();
const [listStartPoints, setListStartPoints] = useState<StartPoint[]>([]);
const [filteredStartPoints, setFilteredStartPoints] = useState<StartPoint[]>([]);
const [searchQuery, setSearchQuery] = useState<string>('');

const [selectedStartPoint, setSelectedStartPoint] =
useState<StartPoint | null>(null);
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const [exclusionDialogOpen, setExclusionDialogOpen] =
useState<boolean>(false);
const [editionDialogOpen, setEditionDialogOpen] = useState<boolean>(false);
const [createDialogOpen, setCreateDialogOpen] = useState(false);

const fetchStartPoints = async (): Promise<StartPoint[]> => {
const startPoints = await getStartPointsByUser(session?.user.id!);
let startPoints: StartPoint[] = [];

if (session?.user.role === UserRole.ADMIN) {
startPoints = await getStartPoints();
} else {
startPoints = await getStartPointsByUser(session?.user.id!);
}

startPoints.sort((a, b) => a.order - b.order);

setListStartPoints(startPoints);
setFilteredStartPoints(startPoints);
return startPoints;
Expand All @@ -39,27 +60,12 @@ const StartPointPage: React.FC = () => {
const {
data = [],
isLoading,

error,
} = useQuery<StartPoint[], Error>({
queryKey: ['startpoints', session?.user.id],
queryFn: fetchStartPoints,
});

const [listStartPoints, setListStartPoints] = useState<StartPoint[]>([]);
const [filteredStartPoints, setFilteredStartPoints] = useState<StartPoint[]>(
[],
);
const [searchQuery, setSearchQuery] = useState<string>('');

const [selectedStartPoint, setSelectedStartPoint] =
useState<StartPoint | null>(null);
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const [exclusionDialogOpen, setExclusionDialogOpen] =
useState<boolean>(false);
const [editionDialogOpen, setEditionDialogOpen] = useState<boolean>(false);
const [createDialogOpen, setCreateDialogOpen] = useState(false);

useEffect(() => {
if (searchQuery === '') {
setFilteredStartPoints(listStartPoints);
Expand All @@ -72,7 +78,7 @@ const StartPointPage: React.FC = () => {
);
setFilteredStartPoints(filtered);
}
}, [searchQuery, listStartPoints]);
}, [searchQuery, listStartPoints, setFilteredStartPoints]);

const handleMenuOpen = (
event: React.MouseEvent<HTMLButtonElement>,
Expand Down Expand Up @@ -131,6 +137,11 @@ const StartPointPage: React.FC = () => {
);
}

const updateStartPoints = (updatedStartPoints: StartPoint[]) => {
setListStartPoints(updatedStartPoints);
setFilteredStartPoints(updatedStartPoints);
};

return (
<Box
sx={{
Expand All @@ -151,6 +162,7 @@ const StartPointPage: React.FC = () => {
onMenuClick={handleMenuOpen}
onMenuClose={handleMenuClose}
onStartPointAction={handleStartPointAction}
onUpdateStartPoints={updateStartPoints}
/>

<ButtonRed onClick={() => setCreateDialogOpen(true)}>
Expand Down
1 change: 1 addition & 0 deletions src/components/home/homePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const HomePrincipalPage = () => {
const { fetchPoints } = JourneyService();
const allPoints = await fetchPoints();

allPoints.sort((a, b) => a.order - b.order);
setAllPoints(allPoints);
};
loadPoints();
Expand Down
151 changes: 92 additions & 59 deletions src/components/tables/startingpoints.table.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import React from 'react';
import React, { useMemo } from 'react';
import {
useMaterialReactTable,
type MRT_ColumnDef,
MRT_TableContainer,
MRT_Row,
} from 'material-react-table';
import {
Box,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Paper,
IconButton,
Menu,
MenuItem,
} from '@mui/material';
import { useRouter } from 'next/navigation';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import { StartPoint } from '@/lib/interfaces/startPoint.interface';
import { updatePointOrder } from '@/services/studioMaker.service';
import { toast } from 'sonner';

interface StartpointTableProps {
startPoints: StartPoint[];
Expand All @@ -25,6 +25,7 @@ interface StartpointTableProps {
) => void;
onMenuClose: () => void;
onStartPointAction: (action: string) => void;
onUpdateStartPoints: OnUpdateStartPoints;
}

const StartpointTable: React.FC<StartpointTableProps> = ({
Expand All @@ -33,9 +34,9 @@ const StartpointTable: React.FC<StartpointTableProps> = ({
onMenuClick,
onMenuClose,
onStartPointAction,
onUpdateStartPoints,
}) => {
const open = Boolean(anchorEl);
const router = useRouter();
const [selectedStartPoint, setSelectedStartPoint] =
React.useState<StartPoint | null>(null);

Expand All @@ -49,57 +50,89 @@ const StartpointTable: React.FC<StartpointTableProps> = ({
setSelectedStartPoint(startPoint);
};

const columns = useMemo<MRT_ColumnDef<StartPoint>[]>(
() => [
{
accessorKey: 'name',
header: 'Nome',
},
{
accessorKey: 'actions',
header: '',
enableColumnFilter: false,
Cell: ({ row }: { row: { original: StartPoint } }) => (
<>
<IconButton
onClick={(e) => {
onMenuClick(e, row.original);
setSelectedStartPoint(row.original);
}}
color="primary"
>
<MoreVertIcon />
</IconButton>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={onMenuClose}
>
<MenuItem onClick={() => handleMenuItemClick('editar')}>
Editar Trilha
</MenuItem>
<MenuItem onClick={() => handleMenuItemClick('gerenciar')}>
Gerenciar Trilha
</MenuItem>
<MenuItem onClick={() => handleMenuItemClick('excluir')}>
Excluir
</MenuItem>
</Menu>
</>
),
},
],
[anchorEl, onMenuClick, onMenuClose, handleMenuItemClick],
);

const table = useMaterialReactTable({
columns,
data: startPoints,
enableRowOrdering: true,
enablePagination: false,
muiRowDragHandleProps: ({ table }) => ({
onDragEnd: async () => {
const { draggingRow, hoveredRow } = table.getState();
if (hoveredRow && draggingRow) {
const newData = [...startPoints];
newData.splice(
(hoveredRow as MRT_Row<StartPoint>).index,
0,
newData.splice(draggingRow.index, 1)[0],
);

await updateTrailOrder(newData);
onUpdateStartPoints(newData);
}
},
}),
});

const updateTrailOrder = async (updatedTrails: StartPoint[]) => {
updatedTrails.forEach((trail, index) => {
trail.order = index;
});

const response = await updatePointOrder(updatedTrails);

if (response.error) {
toast.error('Erro ao atualizar ordem da trilha');
return;
}
toast.success('Ordem da trilha atualizada com sucesso');
};

return (
<Box sx={{ width: '100%', maxWidth: 800 }}>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell sx={{ fontWeight: 'bold' }}>Nome</TableCell>
<TableCell sx={{ fontWeight: 'bold' }}>Descrição</TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
{startPoints.map((startPoint) => (
<TableRow key={startPoint._id}>
<TableCell align="left">{startPoint.name}</TableCell>
<TableCell align="left">{startPoint.description}</TableCell>
<TableCell align="right">
<IconButton
onClick={(e) => handleItem(e, startPoint)}
color="primary"
>
<MoreVertIcon />
</IconButton>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={onMenuClose}
>
<MenuItem onClick={() => handleMenuItemClick('editar')}>
Editar Ponto de partida
</MenuItem>
<MenuItem
onClick={() =>
router.push(`/journey/${selectedStartPoint?._id}`)
}
>
Gerenciar Jornadas
</MenuItem>
<MenuItem
onClick={() => handleMenuItemClick('excluir')}
sx={{ color: 'crimson' }}
>
Excluir
</MenuItem>
</Menu>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
<MRT_TableContainer table={table} />
</Box>
);
};
Expand Down
1 change: 1 addition & 0 deletions src/lib/interfaces/startPoint.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export interface StartPoint {
user: string;
createdAt: string;
updatedAt: string;
order: number;
}
19 changes: 19 additions & 0 deletions src/services/studioMaker.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,25 @@ export const updateTrailsOrder = async (
}
};


export const updatePointOrder = async (
updatedPoints: StartPoint[],
): Promise<any> => {
try {
const response = await studioMakerApi.patch('/points/update-point-order', {
points: updatedPoints,
});
console.log('Points updated:', response.data);
return {
data: response.data,
};
} catch (error) {
console.error('Failed to update points', error);
return { error: error };
}
};


export const updateJourneysOrder = async (
updatedTrails: Journey[],
): Promise<any> => {
Expand Down

0 comments on commit 146d811

Please sign in to comment.