Skip to content

Commit

Permalink
🐛 fix: bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrogomes18 committed Jul 16, 2024
1 parent 1d9fcfa commit d1d2496
Show file tree
Hide file tree
Showing 7 changed files with 234 additions and 62 deletions.
166 changes: 141 additions & 25 deletions src/components/QuestionSection/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import InputRange from '@components/InputRage';

import VisitService from '@services/VisitService';
import useAuth from '@hooks/useAuth';
import { useToast } from 'react-native-toast-notifications';

interface Props {
category: ICategories;
Expand All @@ -26,6 +27,7 @@ interface Props {
sellerId: string;
onUpdateAnswers: (answers: any[]) => void;
onCategoryUpdate?: (updatedCategory: ICategories) => void;
onDeleteCategory?: (categoryId: string) => void; // Novo prop para deletar categoria
loading?: boolean;
}

Expand All @@ -36,36 +38,42 @@ const QuestionSection: React.FC<Props> = ({
sellerId,
onUpdateAnswers,
onCategoryUpdate,
onDeleteCategory,
loading,
}) => {
const [categoryQuestions, setCategoryQuestions] = useState<IQuestions[]>([]);
const [answers, setAnswers] = useState<any[]>([]);
const [isEditing, setIsEditing] = useState(false);
const [editedCategory, setEditedCategory] = useState<ICategories>(category);
const [editedQuestions, setEditedQuestions] = useState<IQuestions[]>([]);
const [newQuestionText, setNewQuestionText] = useState('');
const [showAddQuestionInput, setShowAddQuestionInput] = useState(false);
const { user } = useAuth();
const toast = useToast();

useEffect(() => {
const fetchQuestions = async () => {
try {
const questions = await VisitService.getQuestionsByIdCategory(
category.id
);
setCategoryQuestions(questions);
setEditedQuestions(questions);
} catch (error) {
console.log(error);
}
};
fetchQuestions();
}, [category.id]);

const fetchQuestions = async () => {
try {
const questions = await VisitService.getQuestionsByIdCategory(category.id);
setCategoryQuestions(questions);
setEditedQuestions(questions);
} catch (error) {
console.log(error);
}
};

const handleInputChange = (
questionId: string,
value: number,
question: string
) => {
const existingAnswerIndex = answers.findIndex(
(answer) => answer.questionId === questionId && answer.sellerId === sellerId
(answer) =>
answer.questionId === questionId && answer.sellerId === sellerId
);

if (existingAnswerIndex !== -1) {
Expand Down Expand Up @@ -110,8 +118,12 @@ const QuestionSection: React.FC<Props> = ({
}

setIsEditing(false);
onCategoryUpdate?.(editedCategory); // Update the parent component with the new category data
await fetchQuestions();
onCategoryUpdate?.(editedCategory);
const updatedQuestions = await VisitService.getQuestionsByIdCategory(
editedCategory.id
);
setCategoryQuestions(updatedQuestions);
setEditedQuestions(updatedQuestions);
} catch (error) {
console.log(error);
}
Expand All @@ -128,26 +140,68 @@ const QuestionSection: React.FC<Props> = ({
setEditedQuestions(updatedQuestions);
};

const handleDeleteQuestion = (questionId: string) => {
const updatedQuestions = editedQuestions.filter((q) => q.id !== questionId);
setEditedQuestions(updatedQuestions);
const showToast = (message: string, type: string) => {
toast.show(message, {
type: type,
placement: 'bottom',
duration: 3500,
animationType: 'zoom-in',
});
};

const handleDeleteQuestion = async (questionId: string) => {
try {
await VisitService.deleteQuestion(questionId);
const updatedQuestions = editedQuestions.filter(
(q) => q.id !== questionId
);
setEditedQuestions(updatedQuestions);
showToast('Pergunta deletada com sucesso', 'success');
} catch (error) {
showToast('Não foi possível deletar a pergunta', 'danger');
console.log(error);
}
};

const handleDeleteCategory = async () => {
try {
await VisitService.deleteCategories(category.id);
onDeleteCategory?.(category.id);
showToast('Categoria deletada com sucesso', 'success');
} catch (error) {
showToast('Não foi possível deletar a categoria', 'danger');
console.log(error);
}
};

const handleAddQuestion = async () => {
setNewQuestionText('');
setShowAddQuestionInput(true);
};

const handleConfirmAddQuestion = async () => {
try {
const newQuestion = await VisitService.createQuestions({
categoriesId: editedCategory.id,
question: 'Nova Pergunta',
question: newQuestionText,
number: 0,
});
showToast('Pergunta adicionada', 'success');
setEditedQuestions([...editedQuestions, newQuestion]);
setCategoryQuestions([...categoryQuestions, newQuestion]);
setShowAddQuestionInput(false);
} catch (error) {
showToast('Não foi possível adicionar a pergunta', 'danger');
console.log(error);
}
};

const handleCancelAddQuestion = () => {
setNewQuestionText('');
setShowAddQuestionInput(false);
};

const handleAddCategory = async () => {
// Implement your logic to add a new category here
console.log('Adicionar Nova Categoria');
};

Expand All @@ -156,9 +210,19 @@ const QuestionSection: React.FC<Props> = ({
}

return selectedIndex === index ? (
<ScrollView style={{ minWidth: '95%', height: user.job === 'Gerente' ? 700 : 400, marginVertical: 16, marginHorizontal: 16 }}>
<ScrollView
style={{
minWidth: '95%',
height: user.job === 'Gerente' ? 600 : 400,
marginVertical: 16,
marginHorizontal: 16,
}}
>
{user.job === 'Gerente' && (
<TouchableOpacity onPress={handleEditQuestion} style={styles.editButton}>
<TouchableOpacity
onPress={handleEditQuestion}
style={styles.editButton}
>
<FontAwesome
name="pencil"
size={24}
Expand All @@ -184,7 +248,9 @@ const QuestionSection: React.FC<Props> = ({
placeholder="Edit Question"
placeholderTextColor="#666"
/>
<TouchableOpacity onPress={() => handleDeleteQuestion(question.id)}>
<TouchableOpacity
onPress={() => handleDeleteQuestion(question.id)}
>
<FontAwesome
name="trash"
size={24}
Expand All @@ -194,12 +260,49 @@ const QuestionSection: React.FC<Props> = ({
</TouchableOpacity>
</View>
))}
<TouchableOpacity onPress={handleAddQuestion} style={styles.addButton}>
<Text style={styles.addButtonText}>Adicionar Pergunta</Text>
</TouchableOpacity>
{showAddQuestionInput ? (
<View style={styles.questionContainer}>
<TextInput
style={styles.questionInput}
value={newQuestionText} // Mostra o texto digitado
onChangeText={(text) => setNewQuestionText(text)} // Atualiza o texto da nova pergunta
placeholder="Nova Pergunta"
placeholderTextColor="#666"
/>
<TouchableOpacity onPress={handleConfirmAddQuestion}>
<FontAwesome
name="check"
size={24}
color="#3E63DD"
style={styles.trashIcon}
/>
</TouchableOpacity>
<TouchableOpacity onPress={handleCancelAddQuestion}>
<FontAwesome
name="times"
size={24}
color="#FF6347"
style={styles.trashIcon}
/>
</TouchableOpacity>
</View>
) : (
<TouchableOpacity
onPress={handleAddQuestion}
style={styles.addButton}
>
<Text style={styles.addButtonText}>Adicionar Pergunta</Text>
</TouchableOpacity>
)}
<S.ButtonFirst onPress={handleSaveChanges}>
<S.TextBtn>Salvar Alterações</S.TextBtn>
</S.ButtonFirst>
<TouchableOpacity
onPress={handleDeleteCategory} // Adicionando a função para deletar a categoria
style={styles.deleteButton}
>
<Text style={styles.deleteButtonText}>Deletar Categoria</Text>
</TouchableOpacity>
</View>
) : (
<>
Expand Down Expand Up @@ -263,7 +366,7 @@ const styles = StyleSheet.create({
backgroundColor: '#fff',
},
trashIcon: {
marginLeft: 10,
marginHorizontal: 10,
},
addButton: {
backgroundColor: '#3E63DD',
Expand All @@ -278,6 +381,19 @@ const styles = StyleSheet.create({
fontSize: 16,
fontWeight: 'bold',
},
deleteButton: {
backgroundColor: '#FF6347',
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 5,
marginTop: 10,
alignItems: 'center',
},
deleteButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
});

export default QuestionSection;
1 change: 1 addition & 0 deletions src/interfaces/Visit/QuestionGrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export default interface QuestionsGrade {
grade: number;
sellerId: string;
questionsId: string;
visitId: string;
}
2 changes: 1 addition & 1 deletion src/interfaces/Visit/Questions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ export default interface Questions {
value?: number;
id?: string;
question: string;
number?: number;
number: number;
categoriesId: string;
}
69 changes: 45 additions & 24 deletions src/routes/TabNav/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Visit from '@screens/SalesInspector/TabScreens/Visit';
import Card from '@components/Cards';
import SellerServices from '@services/SellerServices';
import ISeller from '@interfaces/Seller';
import Action from '@screens/SalesInspector/TabScreens/Action';

const Tab = createMaterialTopTabNavigator();

Expand All @@ -22,7 +23,8 @@ const TabNav: React.FC = ({ route }) => {
if (cargo === 'Supervisor') {
setLoading(true);
try {
const sellers = await SellerServices.getAllSellerFromSupervisor(idEmployee);
const sellers =
await SellerServices.getAllSellerFromSupervisor(idEmployee);
setSellers(sellers);
} catch (error) {
console.error('Error fetching sellers:', error);
Expand All @@ -33,7 +35,7 @@ const TabNav: React.FC = ({ route }) => {
};

fetchData();
}, [route.params]);
}, [cargo, idEmployee, route.params]);

const getScreenOptions = (screenName) => ({
tabBarActiveTintColor: 'white',
Expand Down Expand Up @@ -70,28 +72,47 @@ const TabNav: React.FC = ({ route }) => {
options={getScreenOptions('Visita')}
/>
)}
<Tab.Screen
name="Vendedores"
options={getScreenOptions('Vendedores')}
>
{() => (
<>
{loading ? (
<LoadingIndicator />
) : sellers.length > 0 ? (
<ScrollView contentContainerStyle={{ flexGrow: 1, backgroundColor: theme.colors.primary.main }}>
{sellers.map((seller, index) => (
<View key={index} style={{ width: '100%', marginBottom: 16 }}>
<CardItem seller={seller} />
</View>
))}
</ScrollView>
) : (
<NoDataMessage />
)}
</>
)}
</Tab.Screen>
{cargo === 'Vendedor' && (
<Tab.Screen
name="Planos de Ação"
component={Action}
initialParams={{ idEmployee, cargo, companyId }}
options={getScreenOptions('Planos de Ação')}
/>
)}

{cargo === 'Supervisor' && (
<Tab.Screen
name="Vendedores"
options={getScreenOptions('Vendedores')}
>
{() => (
<>
{loading ? (
<LoadingIndicator />
) : sellers.length > 0 ? (
<ScrollView
contentContainerStyle={{
flexGrow: 1,
backgroundColor: theme.colors.primary.main,
}}
>
{sellers.map((seller, index) => (
<View
key={index}
style={{ width: '100%', marginBottom: 16 }}
>
<CardItem seller={seller} />
</View>
))}
</ScrollView>
) : (
<NoDataMessage />
)}
</>
)}
</Tab.Screen>
)}
</Tab.Navigator>
</S.Container>
</View>
Expand Down
Loading

0 comments on commit d1d2496

Please sign in to comment.