From 1d059336466e75cae1f81ce83c57741b41cad622 Mon Sep 17 00:00:00 2001 From: ka-lucas Date: Wed, 23 Apr 2025 16:14:06 -0300 Subject: [PATCH] versao todos os cruds funcionais --- src/components/modals/CompanyModal.vue | 296 ++++++++----------- src/components/modals/CompanyModalCreate.vue | 167 +++++++++++ src/components/modals/EditShiftModal.vue | 47 ++- src/components/modals/HolidayModal.vue | 236 +++++++-------- src/components/modals/HolidayModalCreate.vue | 151 ++++++++++ src/components/modals/UserModal.vue | 1 + src/stores/company.js | 28 +- src/stores/users.js | 5 +- src/views/Company.vue | 47 ++- src/views/Holiday.vue | 62 ++-- src/views/Users.vue | 163 +++++++++- 11 files changed, 842 insertions(+), 361 deletions(-) create mode 100644 src/components/modals/CompanyModalCreate.vue create mode 100644 src/components/modals/HolidayModalCreate.vue 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 @@ - - - \ 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 @@ + + + + \ 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 @@ + \ 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 @@ + \ 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 /> - + + + + +