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

front(UI): Adiciona pop-up ao tentar salvar grades na nuvem #200

Merged
merged 12 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions api/api/tests/test_schedule_save.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

from ..views.save_schedule import SCHEDULES_LIMIT, SCHEDULES_LIMIT_ERROR_MSG
from ..views.save_schedule import SCHEDULES_LIMIT, SCHEDULES_LIMIT_ERROR_MSG, SCHEDULES_INVALID_SCHEDULES_MSG

from utils import db_handler as dbh

Expand Down Expand Up @@ -251,7 +251,7 @@ def test_save_incorrect_schedule_with_compatible_classes(self):

response = self.make_post_request(schedule=schedule)

error_msg = 'error while saving schedule, you may have chosen classes that are not compatible'
error_msg = SCHEDULES_INVALID_SCHEDULES_MSG
self.assertEqual(response.data.get('errors'), error_msg)
self.assertEqual(response.status_code, 400)

Expand Down
8 changes: 5 additions & 3 deletions api/api/views/save_schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
from api import serializers

SCHEDULES_LIMIT = 10
SCHEDULES_LIMIT_ERROR_MSG = f"you have reached the limit of {SCHEDULES_LIMIT} schedules"
SCHEDULES_LIMIT_ERROR_MSG = f"Você atingiu o limite de {SCHEDULES_LIMIT} grades na nuvem."
SCHEDULES_INVALID_SCHEDULES_MSG = "Erro ao salvar a grade horária. Você pode ter escolhido matérias com horários incompatíveis."
SCHEDULES_SAVE_ERROR_MSG = "Ocorreu um erro no servidor ao salvar a grade horária. Tente novamente."


class SaveSchedule():
Expand Down Expand Up @@ -51,13 +53,13 @@ def post(self, request: request.Request, *args, **kwargs) -> response.Response:
try:
valid_schedule = validate_received_schedule(current_db_classes_ids)
except:
error_msg = "error while saving schedule, you may have chosen classes that are not compatible"
error_msg = SCHEDULES_INVALID_SCHEDULES_MSG
return handle_400_error(error_msg)

user = request.user
answer = save_schedule(user, valid_schedule)

return response.Response(status=status.HTTP_201_CREATED) if answer else handle_400_error("error while saving schedule")
return response.Response(status=status.HTTP_201_CREATED) if answer else handle_400_error(SCHEDULES_SAVE_ERROR_MSG)
mateusvrs marked this conversation as resolved.
Show resolved Hide resolved


def check_discipline_key_existence(key: str, discipline_key: str, **kwargs):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ChangeEvent, Dispatch, SetStateAction, useEffect, useState } from 'reac
import useYearPeriod from '@/app/hooks/useYearPeriod';
import useSelectedClasses from '@/app/hooks/useSelectedClasses';

import { errorToast } from '@/app/utils/errorToast';
import { errorToast } from '@/app/utils/toast';

import { DisciplineOptionFormPropsType, FormType, defaultFormData } from '../types/types';
import { DisciplineType } from '@/app/utils/api/searchDiscipline';
Expand Down
68 changes: 46 additions & 22 deletions web/app/components/SchedulePreview/SchedulePreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ import saveSchedule from '@/app/utils/api/saveSchedule';
import getSchedules from '@/app/utils/api/getSchedules';
import { days, months } from '@/app/utils/dates';
import deleteSchedule from '@/app/utils/api/deleteSchedule';
import { errorToast } from '@/app/utils/errorToast';
import { errorToast, successToast } from '@/app/utils/toast';

import jsPDF from 'jspdf';
import { AxiosError } from 'axios';

const commonError = () => errorToast('Houve um erro na atualização das grades!');

Expand Down Expand Up @@ -92,21 +93,9 @@ function BottomPart(props: {
}
}) {
const { user } = useUser();
const { setCloudSchedules } = useSchedules();

const [changeDate, setChangeDate] = useState('');

async function handleUploadToCloud() {
const saveResponse = await saveSchedule(props.schedules.localSchedule, user.access);

if (saveResponse.status == 201) {
getSchedules(user.access).then(response => {
props.handleDelete();
setCloudSchedules(response.data);
}).catch(() => commonError());
} else errorToast('Não foi possível salvar a grade na nuvem!');
}

useEffect(() => {
if (props.isCloud && props.schedules.cloudSchedule?.created_at) {
setChangeDate(handleDate(props.schedules.cloudSchedule.created_at));
Expand All @@ -115,18 +104,12 @@ function BottomPart(props: {

return (
<div className={`flex justify-between items-center w-full ${props.isCloud ? '-bottom-14' : '-bottom-7'}`}>
<div
className='text-[#000000] opacity-40 text-lg font-bold'
>
<div className='text-[#000000] opacity-40 text-lg font-bold' >
Grade {props.position} <br />
{props.isCloud && changeDate && <span className='text-sm font-normal'>{changeDate}</span>}
</div>
<div className='flex gap-4 h-[25px] opacity-50'>
{!props.isCloud && !user.is_anonymous &&
<button onClick={() => handleUploadToCloud()}>
<Image width={25} src={uploadIcon} alt="ícone de upload" />
</button>
}
{!props.isCloud && !user.is_anonymous && <UploadToCloudButton schedules={props.schedules} handleDelete={props.handleDelete} />}
<button onClick={() => {
props.setters.setActiveScheduleModal(true);
props.setters.setToDownload(true);
Expand All @@ -139,6 +122,47 @@ function BottomPart(props: {
);
}

function UploadToCloudButton({ ...props }: {
schedules: {
localSchedule?: Array<ScheduleClassType>;
};
handleDelete: () => void;
}) {
const { user } = useUser();
const { setCloudSchedules } = useSchedules();

function handleSuccessToSave() {
getSchedules(user.access).then(response => {
props.handleDelete();
setCloudSchedules(response.data);
}).catch(() => commonError());
successToast('Grade salva com sucesso!');
}

function handleErrorToSave(axiosError: AxiosError) {
if (axiosError.response) {
const data = axiosError.response.data as { errors: string };
errorToast(data.errors);
}
}

/**
* Tenta salvar a grade na nuvem, se der certo, atualiza as grades locais.
* Caso contrário, exibe errorToast com mensagem retornada pela API.
*/
async function handleUploadToCloud() {
saveSchedule(props.schedules.localSchedule, user.access).then(response => {
if (response.status == 201) handleSuccessToSave();
}).catch((error: any) => handleErrorToSave(error));
}

return (
<button onClick={() => handleUploadToCloud()}>
<Image width={25} src={uploadIcon} alt="ícone de upload" />
</button>
);
}

function handleDownloadPDF(isCloud: boolean, index: number) {
const doc = document.getElementById('download-content')!;

Expand Down Expand Up @@ -220,4 +244,4 @@ export default function SchedulePreview({ localSchedule, cloudSchedule, index, p
/>
</>
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { createContext, useState } from 'react';

import { errorToast } from '../../utils/errorToast';
import { errorToast } from '../../utils/toast';

import { ProviderJSXPropsType, SelectedClassesContextProviderPropsType, SelectedClassesContextType, SelectedClassesType } from './types';

Expand Down
2 changes: 1 addition & 1 deletion web/app/contexts/UserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { UserData } from '../components/SignInSection';
import { settings } from '../utils/settings';
import request from '../utils/request';
import getSchedules from '../utils/api/getSchedules';
import { errorToast } from '../utils/errorToast';
import { errorToast } from '../utils/toast';
import useSchedules from '../hooks/useSchedules';

export interface User {
Expand Down
4 changes: 2 additions & 2 deletions web/app/schedules/home/components/GenerateScheduleButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Modal from '@/app/components/Modal/Modal';
import { ScheduleAPIType, ScheduleClassType } from '@/app/contexts/SchedulesContext';

import generateSchedule, { EachFieldNumber } from '@/app/utils/api/generateSchedule';
import { errorToast } from '@/app/utils/errorToast';
import { errorToast } from '@/app/utils/toast';

function PreferenceOrder({ setPreference }: {
setPreference: (preference: EachFieldNumber) => void
Expand Down Expand Up @@ -58,7 +58,7 @@ export default function GenerateScheduleButton() {
const schedules = data.schedules as Array<ScheduleClassType>;

if (!schedules.length) {
errorToast(data.message, data.message.split('\n').length == 1);
errorToast(data.message, {centered: data.message.split('\n').length == 1});
setLoading(false);
} else {
setLocalSchedules(schedules);
Expand Down
11 changes: 0 additions & 11 deletions web/app/utils/errorToast.ts

This file was deleted.

23 changes: 23 additions & 0 deletions web/app/utils/toast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import toast from 'react-hot-toast';

interface ToastOptions {
duration?: number;
centered?: boolean;
style?: React.CSSProperties;
}

const createToast = (message: string, type: 'success' | 'error', options?: ToastOptions) => {
const { duration = 5000, centered = true, style } = options || {};

toast[type](message, {
duration,
style: {
textAlign: centered ? 'center' : 'justify',
...style,
},
});
};

export const successToast = (message: string, options?: ToastOptions) => createToast(message, 'success', options);

export const errorToast = (message: string, options?: ToastOptions) => createToast(message, 'error', options);
Loading