versao todos os cruds funcionais
This commit is contained in:
parent
0f45adb7b6
commit
1d05933646
@ -1,109 +1,124 @@
|
||||
<template>
|
||||
<v-dialog v-model="isOpen" max-width="500px" @close="closeModal">
|
||||
<v-dialog v-model="isOpen" max-width="500px" @close="closeModal">
|
||||
<v-form @submit="handleSave">
|
||||
<v-card class="pa-6 rounded-xl elevation-2 card-modal">
|
||||
<v-card-title class="text-h5 font-weight-bold pb-0">
|
||||
<span class="text-h5">{{ isEditMode ? 'Editar Usuário' : 'Adicionar Novo Empresa' }}</span>
|
||||
<span class="text-h5">{{ isEditMode ? 'Editar Empresa' : 'Adicionar Nova Empresa' }}</span>
|
||||
</v-card-title>
|
||||
<v-card-text>
|
||||
<v-container>
|
||||
<v-row>
|
||||
<v-text class="text-h7">Dados básicos</v-text>
|
||||
<v-text class="text-h7">Dados básicos</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.name" label="Nome empresa *" clearable required />
|
||||
<v-text-field v-model="localCompany.name" label="Nome da Empresa *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.fantasyname" label="Nome fantasia" clearable />
|
||||
<v-text-field v-model="localCompany.fantasy_name" label="Nome Fantasia" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cnpj" label="CNPJ *" type="cnpj" clearable required />
|
||||
<v-text-field v-model="localCompany.cnpj" label="CNPJ *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.tipo" label="Tipo" clearable />
|
||||
<v-text-field v-model="localCompany.type" label="Tipo" clearable />
|
||||
</v-col>
|
||||
<v-text class="text-h7">Contato</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.email" label="Email *" type="email" clearable
|
||||
:rules="[v => !!v || 'Email é obrigatório', v => /.+@.+\..+/.test(v) || 'Email inválido']" required />
|
||||
<v-text-field v-model="localCompany.email" label="Email *" clearable required />
|
||||
</v-col>
|
||||
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.email_sec" label="Email Secundario*" type="email_sec" clearable
|
||||
:rules="[v => !!v || 'Email é obrigatório', v => /.+@.+\..+/.test(v) || 'Email inválido']" />
|
||||
<v-text-field v-model="localCompany.email_sec" label="Email Secundário" clearable />
|
||||
</v-col>
|
||||
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.phone" label="Telefone *" type="tel" clearable
|
||||
:rules="[v => !!v || 'Telefone é obrigatório', v => /^[0-9]+$/.test(v) || 'Apenas números permitidos']" />
|
||||
<v-text-field v-model="localCompany.phone" label="Telefone *" clearable required />
|
||||
</v-col>
|
||||
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.phone_sec" label="Telefone Secundario *" type="tel_sec" clearable
|
||||
:rules="[v => !!v || 'Telefone é obrigatório', v => /^[0-9]+$/.test(v) || 'Apenas números permitidos']" />
|
||||
<v-text-field v-model="localCompany.phone_sec" label="Telefone Secundário" clearable />
|
||||
</v-col>
|
||||
|
||||
<v-text class="text-h7">Endereço</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cep" label="CEP *" type="cep" clearable />
|
||||
<v-text-field v-model="localCompany.cep" label="CEP *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.rua" label="Rua *" type="rua" clearable />
|
||||
<v-text-field v-model="localCompany.rua" label="Rua *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.numero" label="Numero *" type="numero" clearable />
|
||||
<v-text-field v-model="localCompany.numero" label="Número *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.bairro" label="Bairro *" type="bairro" clearable />
|
||||
<v-text-field v-model="localCompany.bairro" label="Bairro *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.complemento" label="Complemento" type="complemento" clearable />
|
||||
<v-text-field v-model="localCompany.complemento" label="Complemento" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.estado" label="Estado" type="estado" clearable />
|
||||
<v-text-field v-model="localCompany.estado" label="Estado" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cidade" label="Cidade" type="cidade" clearable />
|
||||
<v-text-field v-model="localCompany.cidade" label="Cidade" clearable />
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-container>
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer></v-spacer>
|
||||
<v-spacer />
|
||||
<v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="companyStore.loading">
|
||||
<v-btn
|
||||
type="submit"
|
||||
text
|
||||
class="text-white salvar-btn"
|
||||
:loading="companyStore.loading"
|
||||
>
|
||||
Salvar
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref, watch, computed } from 'vue';
|
||||
import { useCompanyStore } from '../../stores/company';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
|
||||
const props = defineProps({
|
||||
isModalOpen: Boolean,
|
||||
isEditMode: Boolean,
|
||||
modalCompany: Object
|
||||
});
|
||||
const emit = defineEmits(['update:isModalOpen', 'save', 'company-updated']);
|
||||
const companyStore = useCompanyStore();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
console.log('service intance id',authStore.service_instance_id);
|
||||
const isOpen = ref(false);
|
||||
const localCompany = ref({
|
||||
</v-form>
|
||||
</v-dialog>
|
||||
</template>
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { useCompanyStore } from '../../stores/company';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
const props = defineProps({
|
||||
isModalOpen: Boolean,
|
||||
isEditMode: Boolean,
|
||||
modalCompany: Object,
|
||||
});
|
||||
const emit = defineEmits(['update:isModalOpen', 'company-updated']);
|
||||
const companyStore = useCompanyStore();
|
||||
const authStore = useAuthStore();
|
||||
const isOpen = ref(false);
|
||||
const localCompany = ref({
|
||||
id: null,
|
||||
name: '',
|
||||
fantasy_name: '',
|
||||
type: '',
|
||||
cnpj: '',
|
||||
email: '',
|
||||
email_sec: '',
|
||||
phone: '',
|
||||
phone_sec: '',
|
||||
estado: '',
|
||||
cidade: '',
|
||||
bairro: '',
|
||||
rua: '',
|
||||
numero: '',
|
||||
complemento: '',
|
||||
cep: '',
|
||||
service_instance_id: authStore.service_instance_id || 2,
|
||||
parent_id: authStore.userId,
|
||||
});
|
||||
const resetLocalCompany = () => {
|
||||
localCompany.value = {
|
||||
id: null,
|
||||
name: '',
|
||||
fantasy_name: '',
|
||||
type: '',
|
||||
cnpj: '',
|
||||
|
||||
email: '',
|
||||
email_sec: '',
|
||||
phone: '',
|
||||
phone_sec: '',
|
||||
|
||||
estado: '',
|
||||
cidade: '',
|
||||
bairro: '',
|
||||
@ -111,133 +126,64 @@
|
||||
numero: '',
|
||||
complemento: '',
|
||||
cep: '',
|
||||
//parent_id: authStore.companyId,
|
||||
service_instance_id: authStore.service_instance_id || 2,
|
||||
});
|
||||
// Resetar dados ao abrir para novo usuário
|
||||
const resetlocalCompany = () => {
|
||||
localCompany.value = {
|
||||
id: null,
|
||||
name: '',
|
||||
fantasy_name: '',
|
||||
type: '',
|
||||
cnpj: '',
|
||||
|
||||
email: '',
|
||||
email_sec: '',
|
||||
phone: '',
|
||||
phone_sec: '',
|
||||
|
||||
estado: '',
|
||||
cidade: '',
|
||||
bairro: '',
|
||||
rua: '',
|
||||
numero: '',
|
||||
complemento: '',
|
||||
cep: '',
|
||||
//parent_id: authStore.companyId,
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
|
||||
};
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
parent_id: authStore.userId,
|
||||
};
|
||||
// Sincroniza `isOpen` com `props.isModalOpen`
|
||||
watch(() => props.isModalOpen, (newValue) => {
|
||||
isOpen.value = newValue;
|
||||
if (newValue) {
|
||||
if (props.isEditMode && props.modalCompany) {
|
||||
loadCompanyData();
|
||||
} else {
|
||||
resetlocalCompany(); // <- limpa os dados para novo usuário
|
||||
}
|
||||
};
|
||||
const loadCompanyData = async () => {
|
||||
try {
|
||||
const data = await companyStore.fetchCompanyById(props.modalCompany.id);
|
||||
if (data) {
|
||||
Object.assign(localCompany.value, data);
|
||||
}
|
||||
});
|
||||
// Atualiza `props.isModalOpen` quando o modal é fechado
|
||||
watch(isOpen, (newValue) => {
|
||||
if (!newValue) {
|
||||
emit('update:isModalOpen', false);
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
const loadCompanyData = async () => {
|
||||
try {
|
||||
const fullCompanyData = await companyStore.fetchCompanyById(props.modalCompany.id);
|
||||
if (fullCompanyData) {
|
||||
localCompany.value = {
|
||||
id: fullCompanyData.company.id || null,
|
||||
name: fullCompanyData.company.name || '',
|
||||
fantasy_name: fullCompanyData.company.fantasy_name || '',
|
||||
type: fullCompanyData.company.type || '',
|
||||
cnpj: fullCompanyData.company.cnpj || '',
|
||||
email: fullCompanyData.company.email || '',
|
||||
email_sec: fullCompanyData.company.email_sec || '',
|
||||
phone: fullCompanyData.company.phone || '',
|
||||
phone_sec: fullCompanyData.company.phone_sec || '',
|
||||
estado: fullCompanyData.company.estado || '',
|
||||
cidade: fullCompanyData.company.cidade || '',
|
||||
bairro: fullCompanyData.company.bairro || '',
|
||||
rua: fullCompanyData.company.rua || '',
|
||||
numero: fullCompanyData.company.numero || '',
|
||||
complemento: fullCompanyData.company.complemento || '',
|
||||
cep: fullCompanyData.company.cep || '',
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
};
|
||||
}
|
||||
console.log('Enviando companyData:', fullCompanyData);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados do usuário:', error);
|
||||
}
|
||||
};
|
||||
console.log('company', props.modalCompany);
|
||||
/*const isFormValid = computed(() => {
|
||||
const { name, email, password, birth_date, phone } = localCompany.value;
|
||||
const isEmailValid = /.+@.+\..+/.test(email);
|
||||
const isPhoneValid = /^[0-9]+$/.test(phone);
|
||||
return name &&
|
||||
email &&
|
||||
isEmailValid &&
|
||||
birth_date &&
|
||||
phone &&
|
||||
isPhoneValid &&
|
||||
(props.isEditMode || password);
|
||||
});*/
|
||||
const closeModal = () => {
|
||||
isOpen.value = false;
|
||||
};
|
||||
const handleSave = async () => {
|
||||
// if (!isFormValid.value) return;
|
||||
try {
|
||||
const companyData = {
|
||||
...localCompany.value, // não localHoliday
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
parent_id: authStore.userId,
|
||||
};
|
||||
if (!props.isEditMode) {
|
||||
delete companyData.id;
|
||||
}
|
||||
if (props.isEditMode) {
|
||||
await companyStore.updateCompany(companyData.id, companyData);
|
||||
} else {
|
||||
await companyStore.createCompany(companyData);
|
||||
}
|
||||
emit('company-updated');
|
||||
closeModal();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar empresa:', error);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-modal {
|
||||
background-color: #ffffff;
|
||||
border-radius: 16px;
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
}
|
||||
|
||||
.salvar-btn {
|
||||
background: linear-gradient(to right, #6b4eff, #2eb6ff);
|
||||
border-radius: 999px;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
};
|
||||
watch(() => props.isModalOpen, (newVal) => {
|
||||
isOpen.value = newVal;
|
||||
if (newVal) {
|
||||
if (props.isEditMode) {
|
||||
loadCompanyData();
|
||||
} else {
|
||||
resetLocalCompany();
|
||||
}
|
||||
}
|
||||
</style>
|
||||
});
|
||||
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);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<style scoped>
|
||||
.card-modal {
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 16px;
|
||||
}
|
||||
.salvar-btn {
|
||||
background: linear-gradient(to right, #6B4EFF, #2EB6FF);
|
||||
border-radius: 999px;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
167
src/components/modals/CompanyModalCreate.vue
Normal file
167
src/components/modals/CompanyModalCreate.vue
Normal file
@ -0,0 +1,167 @@
|
||||
<template>
|
||||
<v-dialog v-model="isOpen" max-width="500px" @close="closeModal">
|
||||
<v-form>
|
||||
<v-card class="pa-6 rounded-xl elevation-2 card-modal">
|
||||
<v-card-title class="text-h5 font-weight-bold pb-0">
|
||||
<span class="text-h5">Adicionar Nova Empresa</span>
|
||||
</v-card-title>
|
||||
<v-card-text>
|
||||
<v-container>
|
||||
<v-row>
|
||||
<v-text class="text-h7">Dados básicos</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.name" label="Nome da Empresa *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.fantasy_name" label="Nome Fantasia" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cnpj" label="CNPJ *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.type" label="Tipo" clearable />
|
||||
</v-col>
|
||||
<v-text class="text-h7">Contato</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.email" label="Email *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.email_sec" label="Email Secundário" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.phone" label="Telefone *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.phone_sec" label="Telefone Secundário" clearable />
|
||||
</v-col>
|
||||
<v-text class="text-h7">Endereço</v-text>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cep" label="CEP *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.rua" label="Rua *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.numero" label="Número *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.bairro" label="Bairro *" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.complemento" label="Complemento" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.estado" label="Estado" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localCompany.cidade" label="Cidade" clearable />
|
||||
</v-col>
|
||||
</v-row>
|
||||
<!--<FormFields :company="localCompany" />-->
|
||||
</v-container>
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="companyStore.loading">
|
||||
Salvar
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-form>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue';
|
||||
import { useCompanyStore } from '../../stores/company';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
//import FormFields from './FormFields.vue'; // Campos de formulário extraídos (opcional)
|
||||
|
||||
const props = defineProps({
|
||||
isModalOpen: Boolean
|
||||
});
|
||||
const emit = defineEmits(['update:isModalOpen', 'company-created']);
|
||||
|
||||
const isOpen = ref(false);
|
||||
const companyStore = useCompanyStore();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const localCompany = ref({
|
||||
name: '',
|
||||
fantasy_name: '',
|
||||
type: '',
|
||||
cnpj: '',
|
||||
email: '',
|
||||
email_sec: '',
|
||||
phone: '',
|
||||
phone_sec: '',
|
||||
estado: '',
|
||||
cidade: '',
|
||||
bairro: '',
|
||||
rua: '',
|
||||
numero: '',
|
||||
complemento: '',
|
||||
cep: '',
|
||||
service_instance_id: authStore.service_instance_id || 2,
|
||||
parent_id: authStore.userId,
|
||||
});
|
||||
|
||||
watch(() => props.isModalOpen, (newVal) => {
|
||||
isOpen.value = newVal;
|
||||
if (newVal) {
|
||||
Object.assign(localCompany.value, {
|
||||
name: '',
|
||||
fantasy_name: '',
|
||||
type: '',
|
||||
cnpj: '',
|
||||
email: '',
|
||||
email_sec: '',
|
||||
phone: '',
|
||||
phone_sec: '',
|
||||
estado: '',
|
||||
cidade: '',
|
||||
bairro: '',
|
||||
rua: '',
|
||||
numero: '',
|
||||
complemento: '',
|
||||
cep: '',
|
||||
service_instance_id: authStore.service_instance_id || 2,
|
||||
parent_id: authStore.userId,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
watch(isOpen, (newVal) => {
|
||||
if (!newVal){
|
||||
emit('update:isModalOpen', false);
|
||||
}
|
||||
});
|
||||
|
||||
const closeModal = () => {
|
||||
isOpen.value = false;
|
||||
};
|
||||
|
||||
const handleSave = async (e) => {
|
||||
e.preventDefault(); // Impede o comportamento padrão do botão
|
||||
try {
|
||||
await companyStore.createCompany(localCompany.value);
|
||||
emit('company-created');
|
||||
closeModal();
|
||||
} catch (error) {
|
||||
console.error('Erro ao criar empresa:', error);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<style scoped>
|
||||
.card-modal {
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 16px;
|
||||
}
|
||||
.salvar-btn {
|
||||
background: linear-gradient(to right, #6B4EFF, #2EB6FF);
|
||||
border-radius: 999px;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@ -1,10 +1,10 @@
|
||||
<template>
|
||||
<v-dialog v-model="isOpen" max-width="600">
|
||||
<v-card>
|
||||
<v-card-title>Editar Escala</v-card-title>
|
||||
<v-card class="pa-6 rounded-xl elevation-2 card-modal">
|
||||
<v-card-title e class="text-h5 font-weight-bold pb-0">Editar Escala</v-card-title>
|
||||
|
||||
<v-card-text>
|
||||
<v-form @submit.prevent="submit">
|
||||
<v-form @submit.prevent>
|
||||
|
||||
<v-text-field
|
||||
label="Nome da escala"
|
||||
@ -44,20 +44,22 @@
|
||||
label="Marcar intervalo automaticamente?"
|
||||
v-model="form.autoBreak"
|
||||
/>-->
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="companyStore.loading">
|
||||
Salvar
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-form>
|
||||
</v-card-text>
|
||||
|
||||
<v-card-actions>
|
||||
<v-btn @click="close">Cancelar</v-btn>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn color="primary" @click="submit">Salvar</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch } from 'vue'
|
||||
import {useShiftStore} from '../../stores/shift';
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: Boolean,
|
||||
@ -86,6 +88,7 @@ watch(() => props.shiftData, (newData) => {
|
||||
if (!newData) return
|
||||
console.log('📥 shiftData recebido no modal:', newData)
|
||||
form.value = {
|
||||
id: newData.id || null,
|
||||
name: newData.name ||'',
|
||||
day: newData.day || '',
|
||||
start_time: newData.start_time || '',
|
||||
@ -101,9 +104,33 @@ watch(() => props.shiftData, (newData) => {
|
||||
function close() {
|
||||
isOpen.value = false
|
||||
}
|
||||
|
||||
const shiftStore = useShiftStore();
|
||||
function submit() {
|
||||
shiftStore.updateShift(form.value.id,form.value);
|
||||
console.log('📤 Dados enviados para o store:', form.value)
|
||||
emit('save', form.value)
|
||||
close()
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
await companyStore.createCompany(localCompany.value);
|
||||
emit('company-created');
|
||||
closeModal();
|
||||
} catch (error) {
|
||||
console.error('Erro ao criar empresa:', error);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<style scoped>
|
||||
.card-modal {
|
||||
background-color: #FFFFFF;
|
||||
border-radius: 16px;
|
||||
}
|
||||
.salvar-btn {
|
||||
background: linear-gradient(to right, #6B4EFF, #2EB6FF);
|
||||
border-radius: 999px;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@ -1,23 +1,21 @@
|
||||
<template>
|
||||
<v-dialog :model-value="isOpen" max-width="500px" >
|
||||
<v-dialog v-model="dialogVisible" max-width="500px">
|
||||
<v-card class="pa-6 rounded-xl elevation-2 card-modal">
|
||||
<v-card-title class="text-h5 font-weight-bold pb-0">
|
||||
<span class="text-h5">{{ isEditMode ? 'Editar Feriado' : 'Adicionar Novo Feriado' }}</span>
|
||||
<span class="text-h5">Editar Feriado</span>
|
||||
</v-card-title>
|
||||
<v-card-text>
|
||||
<v-container>
|
||||
<v-row>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.name" label="Feriado *" clearable
|
||||
required />
|
||||
<v-text-field v-model="localHoliday.name" label="Feriado *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.type" label="Tipo do Feriado *" clearable
|
||||
required />
|
||||
<v-text-field v-model="localHoliday.type" label="Tipo do Feriado *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.date" label="Data do feriado *" type="date" clearable
|
||||
:rules="[v => !!v || 'Data de nascimento é obrigatória']" required />
|
||||
:rules="[v => !!v || 'Data é obrigatória']" required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.municipio" label="Municipio" type="municipio" clearable />
|
||||
@ -31,30 +29,33 @@
|
||||
<v-card-actions>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="holidayStore.loading" >
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="holidayStore.loading">
|
||||
Salvar
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, computed } from 'vue';
|
||||
import { ref, watch, onMounted } from 'vue';
|
||||
import { useHolidayStore } from '../../stores/holiday';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
|
||||
const props = defineProps({
|
||||
modalValue: Boolean,
|
||||
isEditMode: Boolean,
|
||||
holiday: Object
|
||||
});
|
||||
const emit = defineEmits(['update:isModalOpen', 'save', 'user-updated']);
|
||||
|
||||
const emit = defineEmits(['update:modalValue', 'save']);
|
||||
|
||||
const holidayStore = useHolidayStore();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
console.log('service intance id',authStore.service_instance_id);
|
||||
const isOpen = ref(false);
|
||||
// Controle local da visibilidade do diálogo
|
||||
const dialogVisible = ref(false);
|
||||
|
||||
// Estado local do feriado
|
||||
const localHoliday = ref({
|
||||
id: null,
|
||||
name: '',
|
||||
@ -63,137 +64,136 @@ const localHoliday = ref({
|
||||
estado: '',
|
||||
municipio: '',
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id || 2,
|
||||
service_instance_id: authStore.service_instance_id || 2
|
||||
});
|
||||
// Resetar dados ao abrir para novo usuário
|
||||
const resetLocalHoliday = () => {
|
||||
localHoliday.value = {
|
||||
id: null,
|
||||
name: '',
|
||||
type: '',
|
||||
date: '',
|
||||
estado: '',
|
||||
municipio: '',
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
|
||||
};
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.holiday,
|
||||
async (newVal) => {
|
||||
if (props.isEditMode && newVal && newVal.id) {
|
||||
await loadHolidayData(); // busca os dados completos pela API
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
console.log('holiday no modal', props.holiday);
|
||||
|
||||
|
||||
// Carregar dados do feriado para edição
|
||||
const loadHolidayData = async () => {
|
||||
console.log('Carregando dados do feriado ID:', props.holiday?.id);
|
||||
|
||||
try {
|
||||
// Verifique se holiday foi passado corretamente
|
||||
if (!props.holiday || !props.holiday.id) {
|
||||
console.error('Feriado não encontrado, props.holiday está vazio ou sem id');
|
||||
return; // Se não encontrar, retorna sem fazer a requisição
|
||||
console.error('Feriado não encontrado ou sem ID');
|
||||
return;
|
||||
}
|
||||
|
||||
const fullHolidayData = await holidayStore.fetchHolidayById(props.holiday.id);
|
||||
console.log('fullHolidayData', fullHolidayData);
|
||||
if (fullHolidayData) {
|
||||
// Carregar dados completos do feriado
|
||||
const holidayData = await holidayStore.fetchHolidayById(props.holiday.id);
|
||||
|
||||
if (holidayData) {
|
||||
console.log('Dados carregados com sucesso:', holidayData);
|
||||
// Preencher dados do formulário
|
||||
localHoliday.value = {
|
||||
id: fullHolidayData.id || null,
|
||||
name: fullHolidayData.name || '',
|
||||
type: fullHolidayData.type || '',
|
||||
date: fullHolidayData.date
|
||||
? new Date(fullHolidayData.date).toISOString().split('T')[0]
|
||||
id: holidayData.id,
|
||||
name: holidayData.name || '',
|
||||
type: holidayData.type || '',
|
||||
date: holidayData.date
|
||||
? new Date(holidayData.date).toISOString().split('T')[0]
|
||||
: '',
|
||||
estado: fullHolidayData.estado || '',
|
||||
municipio: fullHolidayData.municipio || ''
|
||||
estado: holidayData.estado || '',
|
||||
municipio: holidayData.municipio || '',
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id || 2
|
||||
};
|
||||
} else if (props.holiday) {
|
||||
// Fallback para os dados recebidos via props
|
||||
console.log('Usando dados de holiday props como fallback');
|
||||
localHoliday.value = {
|
||||
...props.holiday,
|
||||
date: props.holiday.date
|
||||
? new Date(props.holiday.date).toISOString().split('T')[0]
|
||||
: ''
|
||||
};
|
||||
console.log('localHoliday.value', localHoliday.value);
|
||||
} else {
|
||||
console.error('Dados do feriado não encontrados');
|
||||
console.error('Não foi possível carregar dados do feriado');
|
||||
}
|
||||
|
||||
console.log('Feriado carregado:', localHoliday.value);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados do feriado:', error);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
const loadHolidayData = () => {
|
||||
localHoliday.value = {
|
||||
id: props.holiday.id || null,
|
||||
name: props.holiday.name || '',
|
||||
type: props.holiday.type || '',
|
||||
date: props.holiday.date || '',
|
||||
estado: props.holiday.estado || '',
|
||||
municipio: props.holiday.municipio || '',
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
};
|
||||
};*/
|
||||
// Sincroniza `isOpen` com `props.isModalOpen`
|
||||
watch(() => props.modalValue, (newValue) => {
|
||||
isOpen.value = newValue;
|
||||
if (newValue) {
|
||||
if (props.isEditMode && props.holiday) {
|
||||
loadHolidayData();
|
||||
} else {
|
||||
resetLocalHoliday(); // <- limpa os dados para novo usuário
|
||||
// Tenta usar os dados do props como fallback
|
||||
if (props.holiday) {
|
||||
localHoliday.value = {
|
||||
...props.holiday,
|
||||
date: props.holiday.date
|
||||
? new Date(props.holiday.date).toISOString().split('T')[0]
|
||||
: ''
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
// Atualiza `props.isModalOpen` quando o modal é fechado
|
||||
watch(isOpen, (newValue) => {
|
||||
if (!newValue) {
|
||||
emit('update:modalValue', false);
|
||||
};
|
||||
|
||||
// Observar mudanças no modalValue
|
||||
watch(() => props.modalValue, async (newVal) => {
|
||||
console.log('EditModal - modalValue mudou para:', newVal);
|
||||
dialogVisible.value = newVal;
|
||||
|
||||
if (newVal) {
|
||||
// Espera até o holiday ter ID antes de tentar carregar
|
||||
const waitForHoliday = async () => {
|
||||
const maxTries = 10;
|
||||
let tries = 0;
|
||||
while (!props.holiday?.id && tries < maxTries) {
|
||||
await new Promise(resolve => setTimeout(resolve, 100)); // espera 100ms
|
||||
tries++;
|
||||
}
|
||||
if (props.holiday?.id) {
|
||||
console.log('Feriado encontrado após espera:', props.holiday.id);
|
||||
loadHolidayData();
|
||||
} else {
|
||||
console.warn('Holiday não disponível após espera.');
|
||||
}
|
||||
};
|
||||
|
||||
waitForHoliday();
|
||||
}
|
||||
});
|
||||
console.log('holiday', props.holiday);
|
||||
|
||||
/*
|
||||
const isFormValid = computed(() => {
|
||||
const { username, email, password, birth_date, phone } = localHoliday.value;
|
||||
const isEmailValid = /.+@.+\..+/.test(email);
|
||||
const isPhoneValid = /^[0-9]+$/.test(phone);
|
||||
return username &&
|
||||
email &&
|
||||
isEmailValid &&
|
||||
birth_date &&
|
||||
phone &&
|
||||
isPhoneValid &&
|
||||
(props.isEditMode || password);
|
||||
});*/
|
||||
|
||||
// Observar mudanças no objeto holiday
|
||||
watch(() => props.holiday, (newVal) => {
|
||||
console.log('Props holiday mudou:', newVal);
|
||||
if (newVal && newVal.id) {
|
||||
loadHolidayData();
|
||||
}
|
||||
}, { deep: true });
|
||||
|
||||
// Atualizar o prop quando o diálogo local mudar
|
||||
watch(dialogVisible, (newVal) => {
|
||||
if (props.modalValue !== newVal) {
|
||||
emit('update:modalValue', newVal);
|
||||
}
|
||||
});
|
||||
|
||||
// Fechar o modal
|
||||
const closeModal = () => {
|
||||
isOpen.value = false;
|
||||
console.log('Fechando modal de edição');
|
||||
dialogVisible.value = false;
|
||||
emit('update:modalValue', false);
|
||||
};
|
||||
|
||||
// Salvar as alterações no feriado
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
const holidayData = {
|
||||
...localHoliday.value, // não localHoliday
|
||||
service_instance_id: authStore.service_instance_id,
|
||||
parent_id: authStore.userId,
|
||||
};
|
||||
if (!props.isEditMode) {
|
||||
delete holidayData.id;
|
||||
}
|
||||
if (props.isEditMode) {
|
||||
await holidayStore.updateHoliday(holidayData.id, holidayData);
|
||||
} else {
|
||||
await holidayStore.createHoliday(holidayData);
|
||||
}
|
||||
emit('save', holidayData); // avisa o pai que salvou
|
||||
const holidayData = { ...localHoliday.value };
|
||||
console.log('Atualizando feriado:', holidayData);
|
||||
|
||||
await holidayStore.updateHoliday(holidayData.id, holidayData);
|
||||
|
||||
emit('save', holidayData);
|
||||
closeModal();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar feriado:', error);
|
||||
console.error('Erro ao atualizar feriado:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Inicialização do componente
|
||||
onMounted(() => {
|
||||
console.log('Modal de edição montado - holiday:', props.holiday);
|
||||
dialogVisible.value = props.modalValue;
|
||||
|
||||
if (props.modalValue && props.holiday && props.holiday.id) {
|
||||
loadHolidayData();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
151
src/components/modals/HolidayModalCreate.vue
Normal file
151
src/components/modals/HolidayModalCreate.vue
Normal file
@ -0,0 +1,151 @@
|
||||
<template>
|
||||
<v-dialog :model-value="modalValue" @update:model-value="updateModalValue" max-width="500px">
|
||||
<v-card class="pa-6 rounded-xl elevation-2 card-modal">
|
||||
<v-card-title class="text-h5 font-weight-bold pb-0">
|
||||
<span class="text-h5">Adicionar Novo Feriado</span>
|
||||
</v-card-title>
|
||||
<v-card-text>
|
||||
<v-container>
|
||||
<v-row>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.name" label="Feriado *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.type" label="Tipo do Feriado *" clearable required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.date" label="Data do feriado *" type="date" clearable
|
||||
:rules="[v => !!v || 'Data é obrigatória']" required />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.municipio" label="Municipio" type="municipio" clearable />
|
||||
</v-col>
|
||||
<v-col cols="12">
|
||||
<v-text-field v-model="localHoliday.estado" label="Estado" type="estado" clearable />
|
||||
</v-col>
|
||||
</v-row>
|
||||
</v-container>
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn text color="blue-darken-1" @click.prevent.stop="closeModal">Cancelar</v-btn>
|
||||
<v-btn text class="text-white salvar-btn" @click="handleSave" :loading="holidayStore.loading">
|
||||
Salvar
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, onMounted } from 'vue';
|
||||
import { useHolidayStore } from '../../stores/holiday';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
|
||||
const props = defineProps({
|
||||
modalValue: {
|
||||
type: Boolean,
|
||||
required: true
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['update:modalValue', 'save']);
|
||||
|
||||
const holidayStore = useHolidayStore();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Objeto de feriado padrão
|
||||
const defaultHoliday = {
|
||||
name: '',
|
||||
type: '',
|
||||
date: '',
|
||||
estado: '',
|
||||
municipio: '',
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id || 2
|
||||
};
|
||||
|
||||
// Estado local do feriado
|
||||
const localHoliday = ref({...defaultHoliday});
|
||||
|
||||
// Função para atualizar o estado do modal
|
||||
const updateModalValue = (value) => {
|
||||
console.log('Dialog emitindo update:model-value:', value);
|
||||
emit('update:modalValue', value);
|
||||
|
||||
if (!value) {
|
||||
resetLocalHoliday();
|
||||
}
|
||||
};
|
||||
|
||||
// Resetar o feriado para o estado inicial
|
||||
const resetLocalHoliday = () => {
|
||||
console.log('Resetando formulário de criação para valores padrão');
|
||||
for (const key in defaultHoliday) {
|
||||
localHoliday.value[key] = defaultHoliday[key];
|
||||
}
|
||||
};
|
||||
|
||||
// Observar mudanças no modalValue
|
||||
watch(() => props.modalValue, (newVal, oldVal) => {
|
||||
console.log(`CreateModal - modalValue mudou de ${oldVal} para ${newVal}`);
|
||||
|
||||
if (newVal) {
|
||||
// Modal está sendo aberto - resetar formulário
|
||||
resetLocalHoliday();
|
||||
}
|
||||
});
|
||||
|
||||
// Fechar o modal e limpar os dados
|
||||
const closeModal = () => {
|
||||
console.log('Botão cancelar clicado - fechando modal de criação');
|
||||
// Emitir evento para fechar o modal
|
||||
emit('update:modalValue', false);
|
||||
// Resetar dados
|
||||
resetLocalHoliday();
|
||||
};
|
||||
|
||||
// Salvar o novo feriado
|
||||
const handleSave = async (event) => {
|
||||
event.preventDefault(); // Impede o comportamento padrão do botão
|
||||
try {
|
||||
const holidayData = {
|
||||
...localHoliday.value,
|
||||
parent_id: authStore.userId,
|
||||
service_instance_id: authStore.service_instance_id || 2
|
||||
};
|
||||
|
||||
console.log('Criando novo feriado:', holidayData);
|
||||
|
||||
await holidayStore.createHoliday(holidayData);
|
||||
|
||||
emit('save', holidayData);
|
||||
emit('update:modalValue', false);
|
||||
resetLocalHoliday();
|
||||
} catch (error) {
|
||||
console.error('Erro ao criar feriado:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Inicialização do componente
|
||||
onMounted(() => {
|
||||
console.log('Modal de criação montado - modalValue:', props.modalValue);
|
||||
if (props.modalValue) {
|
||||
resetLocalHoliday();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.card-modal {
|
||||
background-color: #ffffff;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.salvar-btn {
|
||||
background: linear-gradient(to right, #6b4eff, #2eb6ff);
|
||||
border-radius: 999px;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@ -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 = {
|
||||
|
||||
@ -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}`;
|
||||
|
||||
@ -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}`
|
||||
|
||||
@ -41,7 +41,7 @@
|
||||
class="ml-2"
|
||||
prepend-icon="mdi-plus"
|
||||
variant="elevated"
|
||||
@click="openDialog('company', 'create')"
|
||||
@click="openCreateModal"
|
||||
>
|
||||
Adicionar Empresa
|
||||
</v-btn>
|
||||
@ -82,6 +82,10 @@
|
||||
:modalCompany="forms.company"
|
||||
@save="submitForm"
|
||||
/>
|
||||
<CompanyModayCreate
|
||||
v-model:isModalOpen="dialogs.createCompany"
|
||||
@save="SubmitFormCreate"
|
||||
/>
|
||||
|
||||
<!-- Diálogo de Confirmação de Exclusão -->
|
||||
<v-dialog v-model="dialogs.delete" max-width="400px">
|
||||
@ -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
|
||||
};
|
||||
|
||||
@ -40,7 +40,7 @@
|
||||
class="ml-2"
|
||||
prepend-icon="mdi-plus"
|
||||
variant="elevated"
|
||||
@click="openDialog('holiday', 'create')"
|
||||
@click="openCreateModal"
|
||||
>
|
||||
Adicionar Feriado
|
||||
</v-btn>
|
||||
@ -80,7 +80,10 @@
|
||||
:holiday="forms.holiday"
|
||||
@save="submitForm"
|
||||
/>
|
||||
|
||||
<CreateHolidayModal
|
||||
v-model="dialogs.createholiday"
|
||||
@save="SubmitFormCreate"
|
||||
/>
|
||||
<!-- Diálogo de Confirmação de Exclusão -->
|
||||
<v-dialog v-model="dialogs.delete" max-width="400px">
|
||||
<v-card>
|
||||
@ -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
|
||||
|
||||
@ -22,7 +22,19 @@
|
||||
@update:model-value="filterUsers"
|
||||
clearable
|
||||
/>
|
||||
|
||||
<!-- Filtro de Status -->
|
||||
<v-select
|
||||
v-model="filters.status"
|
||||
:items="statusOptions"
|
||||
label="Status"
|
||||
density="compact"
|
||||
variant="outlined"
|
||||
hide-details
|
||||
class="mx-2"
|
||||
style="max-width: 150px;"
|
||||
@update:model-value="filterUsers"
|
||||
clearable
|
||||
/>
|
||||
<!-- Botão para exportar CSV -->
|
||||
<v-btn
|
||||
color="primary"
|
||||
@ -57,6 +69,29 @@
|
||||
:items-per-page="itemsPerPage"
|
||||
:page.sync="page"
|
||||
>
|
||||
<!-- Coluna de Status -->
|
||||
<template v-slot:item.status="{ item }">
|
||||
<!-- Botão para alternar status -->
|
||||
|
||||
<v-icon
|
||||
size="small"
|
||||
class="mr-2"
|
||||
:color="item.status ? 'error' : 'success'"
|
||||
@click="toggleUserStatus(item)"
|
||||
:title="item.status ? 'Desativar usuário' : 'Ativar usuário'"
|
||||
>
|
||||
{{ item.status ? 'mdi-account-cancel' : 'mdi-account-check' }}
|
||||
</v-icon>
|
||||
<!--
|
||||
<v-chip
|
||||
:color="item.status ? 'success' : 'error'"
|
||||
text-color="white"
|
||||
size="small"
|
||||
>
|
||||
{{ item.status ? 'Ativo' : 'Inativo' }}
|
||||
</v-chip>-->
|
||||
</template>
|
||||
|
||||
<template v-slot:item.actions="{ item }">
|
||||
<v-icon
|
||||
size="small"
|
||||
@ -115,6 +150,38 @@
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
|
||||
<!-- Diálogo de Confirmação de Alteração de Status -->
|
||||
<v-dialog v-model="dialogs.status" max-width="400px">
|
||||
<v-card>
|
||||
<v-card-title class="text-h5" :class="statusToChange ? 'bg-error' : 'bg-success'" style="color: white;">
|
||||
{{ statusToChange ? 'Desativar Usuário' : 'Ativar Usuário' }}
|
||||
</v-card-title>
|
||||
|
||||
<v-card-text class="pt-4">
|
||||
<p v-if="itemToChangeStatus && itemToChangeStatus.username">
|
||||
Tem certeza que deseja {{ statusToChange ? 'desativar' : 'ativar' }} o usuário
|
||||
<strong>{{ itemToChangeStatus.username }}</strong>?
|
||||
</p>
|
||||
<p v-else>
|
||||
Erro: Nenhum usuário selecionado.
|
||||
</p>
|
||||
</v-card-text>
|
||||
|
||||
<v-card-actions>
|
||||
<v-spacer></v-spacer>
|
||||
<v-btn color="grey" @click="dialogs.status = false">Cancelar</v-btn>
|
||||
<v-btn
|
||||
:color="statusToChange ? 'error' : 'success'"
|
||||
:loading="loading.status"
|
||||
:disabled="!itemToChangeStatus || !itemToChangeStatus.id"
|
||||
@click="changeUserStatus"
|
||||
>
|
||||
{{ statusToChange ? 'Desativar' : 'Ativar' }}
|
||||
</v-btn>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
</v-dialog>
|
||||
|
||||
<!-- Snackbar para Feedback -->
|
||||
<v-snackbar
|
||||
v-model="snackbar.show"
|
||||
@ -156,24 +223,35 @@ export default {
|
||||
const page = ref(1);
|
||||
const itemsPerPage = ref(10);
|
||||
const selectedUser = ref(null);
|
||||
const itemToChangeStatus = ref(null);
|
||||
const statusToChange = ref(null);
|
||||
|
||||
// Status options para filtro
|
||||
const statusOptions = [
|
||||
{ title: 'Ativo', value: true },
|
||||
{ title: 'Inativo', value: false }
|
||||
];
|
||||
|
||||
// Loading states
|
||||
const loading = ref({
|
||||
users: false,
|
||||
submit: false,
|
||||
delete: false,
|
||||
export: false
|
||||
export: false,
|
||||
status: false
|
||||
});
|
||||
|
||||
// Diálogos
|
||||
const dialogs = ref({
|
||||
user: false,
|
||||
delete: false
|
||||
delete: false,
|
||||
status: false
|
||||
});
|
||||
|
||||
// Filtros
|
||||
const filters = ref({
|
||||
user: ''
|
||||
user: '',
|
||||
status: null
|
||||
});
|
||||
|
||||
// Dados - array vazio que será preenchido via API ou entrada do usuário
|
||||
@ -188,7 +266,8 @@ export default {
|
||||
email: '',
|
||||
birth_date: '',
|
||||
phone: '',
|
||||
profile_image: ''
|
||||
profile_image: '',
|
||||
status: true,
|
||||
//contrato: '',
|
||||
// grupo: '',
|
||||
//permissao: ''
|
||||
@ -201,6 +280,7 @@ export default {
|
||||
{ title: 'ID', key: 'id' },
|
||||
{ title: 'Usuário', key: 'username' },
|
||||
{ title: 'Email', key: 'email' },
|
||||
{ title: 'Status', key: 'status', align: 'center' },
|
||||
//{ title: 'Contrato', key: 'contrato' },
|
||||
//{ title: 'Grupo', key: 'grupo' },
|
||||
//{ title: 'Permissão', key: 'permissao' },
|
||||
@ -221,14 +301,63 @@ export default {
|
||||
console.log("Usuários após filtro 'deleted':", filtered);
|
||||
|
||||
return filtered.filter(user => {
|
||||
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
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
Loading…
Reference in New Issue
Block a user