diff --git a/src/components/modals/CompanyModal.vue b/src/components/modals/CompanyModal.vue index 0e39dbd..3103daf 100644 --- a/src/components/modals/CompanyModal.vue +++ b/src/components/modals/CompanyModal.vue @@ -1,109 +1,124 @@ - + + - {{ isEditMode ? 'Editar Usuário' : 'Adicionar Novo Empresa' }} + {{ isEditMode ? 'Editar Empresa' : 'Adicionar Nova Empresa' }} - Dados básicos + Dados básicos - + - + - + - + Contato - + - - + - - + - - + - Endereço - + - + - + - + - + - + - + - + Cancelar - + Salvar - - - - - \ No newline at end of file +}); +watch(isOpen, (newVal) => { + if (!newVal) { + emit('update:isModalOpen', false); + } +}); +const closeModal = () => { + isOpen.value = false; +}; +const handleSave = async (e) => { + e.preventDefault(); // Isso é um seguro extra + try { + const companyData = { ...localCompany.value }; + if (!props.isEditMode) { + delete companyData.id; + await companyStore.createCompany(companyData); + } else { + await companyStore.updateCompany(companyData.id, companyData); + } + emit('company-updated'); + closeModal(); + } catch (error) { + console.error('Erro ao salvar empresa:', error); + } +}; + + \ No newline at end of file diff --git a/src/components/modals/CompanyModalCreate.vue b/src/components/modals/CompanyModalCreate.vue new file mode 100644 index 0000000..af0cc47 --- /dev/null +++ b/src/components/modals/CompanyModalCreate.vue @@ -0,0 +1,167 @@ + + + + + + Adicionar Nova Empresa + + + + + Dados básicos + + + + + + + + + + + + + Contato + + + + + + + + + + + + + Endereço + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cancelar + + Salvar + + + + + + + + + \ No newline at end of file diff --git a/src/components/modals/EditShiftModal.vue b/src/components/modals/EditShiftModal.vue index 611add8..fa2b2df 100644 --- a/src/components/modals/EditShiftModal.vue +++ b/src/components/modals/EditShiftModal.vue @@ -1,10 +1,10 @@ - - Editar Escala + + Editar Escala - + --> + + + Cancelar + + Salvar + + - - - Cancelar - - Salvar - + \ No newline at end of file diff --git a/src/components/modals/HolidayModal.vue b/src/components/modals/HolidayModal.vue index 288f1d4..810586d 100644 --- a/src/components/modals/HolidayModal.vue +++ b/src/components/modals/HolidayModal.vue @@ -1,23 +1,21 @@ - + - {{ isEditMode ? 'Editar Feriado' : 'Adicionar Novo Feriado' }} + Editar Feriado - + - + + :rules="[v => !!v || 'Data é obrigatória']" required /> @@ -31,30 +29,33 @@ Cancelar - + Salvar - + \ No newline at end of file diff --git a/src/components/modals/UserModal.vue b/src/components/modals/UserModal.vue index bec65ac..3ed27f0 100644 --- a/src/components/modals/UserModal.vue +++ b/src/components/modals/UserModal.vue @@ -104,6 +104,7 @@ watch(isOpen, (newValue) => { }); const loadUserData = async () => { try { + console.log('Carregando dados do usuário:', props.modalUser); const fullUserData = await userStore.fetchUserById(props.modalUser.id); if (fullUserData) { localUser.value = { diff --git a/src/stores/company.js b/src/stores/company.js index 1cadd16..da0a1e3 100644 --- a/src/stores/company.js +++ b/src/stores/company.js @@ -30,18 +30,25 @@ export const useCompanyStore = defineStore('company', { this.loading = true; const authStore = useAuthStore(); const token = authStore.token; + const userId = authStore.userId; + console.log('userId: ', userId); // Exibe o userId no console const response = await api.get('/company/', { headers: { 'Authorization': `Bearer ${token}` } }); + console.log('requisicao company.js: ',response.data); - // Filtra para manter apenas usuários não deletados - //const filteredCompanys = response.data.filter(company => !company.deleted); - //this.userData = filteredUsers; - + const filteredCompanys = response.data.filter(company => { + console.log('Verificando company: ', company); // Exibe o objeto completo da empresa + console.log('parent_id da empresa: ', company.parent_id); // Exibe apenas o valor do parent_id + return String(company.parent_id) === String(userId); + }); + console.log('filteredCompanys', filteredCompanys); // Retorna apenas os usuários não deletados - return response.data; + this.companies = filteredCompanys; + + return filteredCompanys; } catch (error) { console.error('Erro ao buscar lista de empresas', error); throw error; @@ -61,7 +68,8 @@ export const useCompanyStore = defineStore('company', { 'Content-Type': 'application/json' } }); - + print('response.data', response.data); + print('compony', companyData); this.companys.push(response.data); return response.data; } catch (error) { @@ -75,8 +83,8 @@ export const useCompanyStore = defineStore('company', { }, // Na função updateUser - async updateCompany(companyId, companyData) { - const url = `/company/${id}`; + async updateCompany(companyId, company) { + const url = `/company/${companyId}`; this.loading = true; this.error = null; @@ -132,7 +140,7 @@ export const useCompanyStore = defineStore('company', { } }, - async fetchUserById(userId) { + /*async fetchUserById(userId) { try { this.loading = true; const authStore = useAuthStore(); @@ -150,7 +158,7 @@ export const useCompanyStore = defineStore('company', { } finally { this.loading = false; } - }, + },*/ async fetchCompanyById(company_id) { const url = `/company/${company_id}`; diff --git a/src/stores/users.js b/src/stores/users.js index 361194e..b6c11a3 100644 --- a/src/stores/users.js +++ b/src/stores/users.js @@ -160,7 +160,8 @@ export const useUserStore = defineStore('users', { ? new Date(userData.birth_date).toISOString().split('T')[0] : null, ...(userData.password ? { password: userData.password } : {}), - ...(userData.status_at !== undefined ? { status_at: userData.status_at } : {}) + ...(userData.status_at !== undefined ? { status_at: userData.status_at } : {}), + status: userData.status, }; console.log("📤 Enviando dados para API:", formattedData); @@ -191,7 +192,7 @@ export const useUserStore = defineStore('users', { const token = authStore.token; // Realiza o soft delete definindo o campo deleted como true - const response = await api.put(`/users/${userId}`, { deleted: true }, { + const response = await api.delete(`/users/${userId}`, { deleted: true }, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` diff --git a/src/views/Company.vue b/src/views/Company.vue index 968058e..a81d579 100644 --- a/src/views/Company.vue +++ b/src/views/Company.vue @@ -41,7 +41,7 @@ class="ml-2" prepend-icon="mdi-plus" variant="elevated" - @click="openDialog('company', 'create')" + @click="openCreateModal" > Adicionar Empresa @@ -82,6 +82,10 @@ :modalCompany="forms.company" @save="submitForm" /> + @@ -139,17 +143,20 @@ import { ref, computed, onMounted } from 'vue'; import { useRouter } from 'vue-router'; import CompanyModal from '../components/modals/CompanyModal.vue'; + import CompanyModayCreate from '../components/modals/CompanyModalCreate.vue'; import { useCompanyStore } from '../stores/company'; export default { name: 'CompanyManagement', components: { - CompanyModal + CompanyModal, + CompanyModayCreate }, setup() { const router = useRouter(); // Estados + const isCreateModalOpen = ref(false); const isEditing = ref(false); const itemToEdit = ref(null); const itemToDelete = ref(null); @@ -168,6 +175,7 @@ // Diálogos const dialogs = ref({ company: false, + createCompany: false, delete: false }); @@ -213,8 +221,8 @@ { title: 'ID', key: 'id' }, { title: 'Nome empresa', key: 'name' }, { title: 'Tipo', key: 'type' }, - { title: 'Endereço', key: 'endereco' }, - //{ title: 'Grupo', key: 'grupo' }, + { title: 'Bairro', key: 'bairro' }, + { title: 'Rua', key: 'rua' }, //{ title: 'Permissão', key: 'permissao' }, { title: 'Ações', key: 'actions', sortable: false, align: 'end' } ] @@ -351,13 +359,17 @@ } dialogs.value[type] = true; }; + const openCreateModal = () => { + isCreateModalOpen.value = true; + dialogs.value.createCompany = true + }; const openEditPage = (type, item) => { console.log('Usuário que será editado:', item); // Log para depuração // Criar uma cópia do item para evitar problemas de mutação const companyData = { ...item }; - + console.log('CompanyData que será editado:', companyData); // Garantir que todos os campos necessários estejam presentes forms.value[type] = { id: companyData.id, @@ -385,7 +397,7 @@ }; const handleCompanyUpdated = (updatedCompany) => { - const index = companys.value.findIndex(companys => company.id === updatedCompany.id); + const index = companys.value.findIndex(company => company.id === updatedCompany.id); if (index !== -1) { companys.value[index] = updatedCompany; } @@ -451,7 +463,21 @@ const filterCompanys = () => { // O filtro já é realizado automaticamente por meio do computed property filteredUsers }; - + + const SubmitFormCreate = async (companyData) => { + loading.value.submit = true; + try { + //const newItem = await companyStore.createCompany(companyData); + companys.value.push(newItem); + showNotification('Empresa cadastrado com sucesso!'); + } catch (error) { + console.error('Error submitting form:', error); + } finally { + loading.value.submit = false; + dialogs.value.createCompany = false; + } + }; + const submitForm = async (companyData) => { loading.value.submit = true; try { @@ -462,11 +488,8 @@ if (index !== -1) { Companys.value[index] = companyData; } - } else { - // Criar novo item - const newItem = await companyStore.createCompany(companyData); - companys.value.push(newItem); } + showNotification(`Empresa ${isEditing.value ? 'atualizado' : 'cadastrado'} com sucesso!`); dialogs.value.company = false; } catch (error) { @@ -521,6 +544,8 @@ deleteItem, openEditPage, filterCompanys, + openCreateModal, + SubmitFormCreate, //exportToCSV, handleCompanyUpdated }; diff --git a/src/views/Holiday.vue b/src/views/Holiday.vue index a0bb0b3..c50ec80 100644 --- a/src/views/Holiday.vue +++ b/src/views/Holiday.vue @@ -40,7 +40,7 @@ class="ml-2" prepend-icon="mdi-plus" variant="elevated" - @click="openDialog('holiday', 'create')" + @click="openCreateModal" > Adicionar Feriado @@ -80,7 +80,10 @@ :holiday="forms.holiday" @save="submitForm" /> - + @@ -138,12 +141,13 @@ import { useRouter } from 'vue-router'; import holidayModal from '../components/modals/HolidayModal.vue'; import {useHolidayStore} from '../stores/holiday'; - + import CreateHolidayModal from '../components/modals/HolidayModalCreate.vue'; export default { name: 'holidayManagement', components: { - holidayModal + holidayModal, + CreateHolidayModal }, setup() { const router = useRouter(); @@ -151,6 +155,7 @@ const holidayStore = useHolidayStore(); // Estados + const isCreateModalOpen = ref(false); const isEditing = ref(false); const itemToEdit = ref(null); const itemToDelete = ref(null); @@ -169,6 +174,7 @@ // Diálogos const dialogs = ref({ holiday: false, + createholiday: false, delete: false }); const editMode = ref(false) @@ -212,17 +218,17 @@ }); // Computed properties - const filteredholidays = computed(() => { + const filteredholidays = computed(() => { const filtered = holidays.value.filter(holiday => !holiday.deleted); - console.log("Feriado após filtro 'deleted':", filtered); - return filtered.filter(holiday => { - return holiday.name.toLowerCase().includes(filters.value.holiday.toLowerCase()) + const holidayName = holiday.name || ''; // Garantir que seja uma string vazia se undefined + return holidayName.toLowerCase().includes(filters.value.holiday.toLowerCase()) }).map(holiday => ({ ...holiday, created_at: holiday.created_at ? new Date(holiday.created_at).toLocaleString() : '-' })); }); + /* // Função para exportar para CSV const exportToCSV = () => { @@ -300,14 +306,7 @@ editMode.value = action === 'edit' if (type === 'holiday') { - if (action === 'create') { - forms.value.holiday = { - id: '', - name: '', - date: '', - loading: false - } - } else if (action === 'edit') { + if (action === 'edit') { forms.value.holiday = { ...item, loading: false @@ -318,8 +317,13 @@ dialogs.value.holiday = true } } - - + // Abrir modal de criação + const openCreateModal = () => { + isCreateModalOpen.value = true; + dialogs.value.createholiday = true + }; + + const openEditPage = (type, item) => { console.log('Feriado que será editado:', item); // Log para depuração @@ -419,11 +423,7 @@ if (index !== -1) { holidays.value[index] = holidayData; } - } else { - // Criar novo item - const newItem = await holidayStore.createHoliday(holidayData); - holidays.value.push(newItem); - } + } showNotification(`Feriado ${isEditing.value ? 'atualizado' : 'cadastrado'} com sucesso!`); } catch (error) { @@ -434,7 +434,19 @@ } }; - + const SubmitFormCreate = async (holidayData) => { + loading.value.submit = true; + try { + //const newItem = await holidayStore.createHoliday(holidayData); + holidays.value.push(newItem); + showNotification('Feriado cadastrado com sucesso!'); + } catch (error) { + console.error('Error submitting form:', error); + } finally { + loading.value.submit = false; + dialogs.value.createholiday = false; + } + }; // Lifecycle hooks onMounted(async () => { @@ -479,8 +491,10 @@ openDialog, confirmDelete, submitForm, + SubmitFormCreate, deleteItem, openEditPage, + openCreateModal, // filtercameras, //exportToCSV, handleholidayUpdated diff --git a/src/views/Users.vue b/src/views/Users.vue index 76f2153..3210a69 100644 --- a/src/views/Users.vue +++ b/src/views/Users.vue @@ -22,7 +22,19 @@ @update:model-value="filterUsers" clearable /> - + + + + + + + + {{ item.status ? 'mdi-account-cancel' : 'mdi-account-check' }} + + + + + + + + + {{ statusToChange ? 'Desativar Usuário' : 'Ativar Usuário' }} + + + + + Tem certeza que deseja {{ statusToChange ? 'desativar' : 'ativar' }} o usuário + {{ itemToChangeStatus.username }}? + + + Erro: Nenhum usuário selecionado. + + + + + + Cancelar + + {{ statusToChange ? 'Desativar' : 'Ativar' }} + + + + + { - return user.username.toLowerCase().includes(filters.value.user.toLowerCase()) || - user.email.toLowerCase().includes(filters.value.user.toLowerCase()); + // Filtro por texto (username ou email) + const textMatch = user.username.toLowerCase().includes(filters.value.user.toLowerCase()) || + user.email.toLowerCase().includes(filters.value.user.toLowerCase()); + + // Filtro por status (se selecionado) + const statusMatch = filters.value.status === null || user.status === filters.value.status; + + return textMatch && statusMatch; }).map(user => ({ ...user, created_at: user.created_at ? new Date(user.created_at).toLocaleString() : '-' })); }); + // Função para alternar status do usuário + const toggleUserStatus = (item) => { + itemToChangeStatus.value = {...item}; + statusToChange.value = item.status; // Se true, vai desativar; se false, vai ativar + dialogs.value.status = true; + }; + + // Função para confirmar a alteração de status + const changeUserStatus = async () => { + if (!itemToChangeStatus.value || itemToChangeStatus.value.id === undefined) { + showNotification('Erro ao alterar status do usuário', 'error'); + + return; + } + console.log("Alterando status do usuário:", itemToChangeStatus.value); + loading.value.status = true; + try { + const userId = itemToChangeStatus.value.id; + const newStatusAt = statusToChange.value ? 'inativo' : 'ativo'; + const updatedUser = { + ...itemToChangeStatus.value, + status: newStatusAt + }; + + await userStore.updateUser(userId, updatedUser); + + const index = users.value.findIndex(user => user.id === userId); + if (index !== -1) { + users.value[index].status = newStatusAt === 'ativo'; + users.value[index].status = newStatusAt; + } + + showNotification(`Usuário ${newStatusAt === 'ativo' ? 'ativado' : 'desativado'} com sucesso!`); + dialogs.value.status = false; + } catch (error) { + showNotification('Erro ao alterar status do usuário', 'error'); + console.error('Error updating user status:', error); + } finally { + loading.value.status = false; + itemToChangeStatus.value = null; + } + }; + // Função para exportar para CSV const exportToCSV = () => { if (filteredUsers.value.length === 0) { @@ -298,6 +427,7 @@ export default { birth_date: item.birth_date, phone: item.phone, profile_image: item.profile_image, + status: item.status, //contrato: item.contrato, //grupo: item.grupo, //permissao: item.permissao @@ -311,6 +441,7 @@ export default { birth_date: '', phone: '', profile_image: '', + status: true, //contrato: '', //grupo: '', //permissao: '' @@ -332,7 +463,8 @@ export default { email: userData.email || '', birth_date: userData.birth_date || '', phone: userData.phone || '', - profile_image: userData.profile_image || '' + profile_image: userData.profile_image || '', + status: userData.status || true, }; // Definir modo de edição e abrir o diálogo @@ -444,7 +576,12 @@ export default { console.log("Dados recebidos da API:", usersData); // Garanta que os dados já estão filtrados (usuários deletados removidos) - users.value = usersData.filter(user => !user.deleted); + users.value = usersData + .filter(user => !user.deleted) + .map(user => ({ + ...user, + status: user.status !== 'inativo' + })); } catch (error) { showNotification('Erro ao carregar dados da API', 'error'); console.error('Error fetching users:', error); @@ -467,7 +604,9 @@ export default { itemsPerPage, itemToDelete, selectedUser, - + statusOptions, + itemToChangeStatus, + statusToChange, // Computed filteredUsers, @@ -479,7 +618,9 @@ export default { openEditPage, filterUsers, exportToCSV, - handleUserUpdated + handleUserUpdated, + toggleUserStatus, + changeUserStatus }; } };
+ Tem certeza que deseja {{ statusToChange ? 'desativar' : 'ativar' }} o usuário + {{ itemToChangeStatus.username }}? +
+ Erro: Nenhum usuário selecionado. +