Files
WebETA/src/views/loads/modals/FormLoadModal.vue
2025-06-21 14:28:38 -06:00

694 lines
28 KiB
Vue

<script setup>
import { reactive, ref, onMounted, watch } from 'vue';
import { useLoadsStore } from '../../../stores/loads';
import Custominput from '../../../components/ui/CustomInput.vue';
import Segments from '../../../components/ui/Segments.vue';
import TruckTypes from '../../../components/ui/TruckTypes.vue';
import Spiner from '../../../components/ui/Spiner.vue';
import Products from '../../../components/ui/Products.vue';
import { GoogleMap, Marker, Polyline } from "vue3-google-map";
import useDirectionsRender from '../../../composables/useDirectionRender';
import { useAuthStore } from '../../../stores/auth';
import Swal from 'sweetalert2';
import { useNotificationsStore } from '../../../stores/notifications';
import { useCompanyStore } from '../../../stores/company';
import { useI18n } from 'vue-i18n';
import { computed } from 'vue';
import {getDateTime } from '../../../helpers/date_formats';
import { validateEmail } from '../../../helpers/validations';
import AddressPreview from '../../../components/AddressPreview.vue';
const loadStore = useLoadsStore();
const notyStore = useNotificationsStore();
const auth = useAuthStore();
const companyStore = useCompanyStore()
const windowWidth = ref(window.innerWidth);
const zoom = ref(6);
const heightMap = ref(768);
const originCoords = ref(null);
const destinationCoords = ref(null);
const polylines = ref([]);
const startLocation = ref(null);
const endLocation = ref(null);
const isLoading = ref(false);
const loadingLocations = ref(false);
const submited = ref(false);
const { geocodeAddress, getDirections } = useDirectionsRender();
const formRef = ref(null);
const locationLoadSelected = ref(null)
const locationDownloadSelected = ref(null)
const originRef = ref('')
const destinationRef = ref('')
const emails = ref([]);
const emailInput = ref('');
const errors = ref({
segment: null,
truckType: null,
locationOrigin: null,
locationDestination: null,
});
const mapKey = import.meta.env.VITE_MAP_KEY;
const { t } = useI18n()
const clearLoad = () => {
loadStore.currentLoad = null;
loadStore.openModalEdit = false;
}
const handleResize = () => {
windowWidth.value = window.innerWidth
if(windowWidth.value <= 1024){
zoom.value = 4
heightMap.value = 420;
} else {
zoom.value = 6;
heightMap.value = 768;
}
}
onMounted(() => {
window.addEventListener('resize', handleResize);
if(window.innerWidth <= 1024) {
zoom.value = 4;
heightMap.value = 420;
}
getLocations('unloading');
getLocations('loading');
formLoad.owner = auth.user?.first_name + ' ' + auth.user?.last_name;
if(loadStore.currentLoad){
const dateStart = getDateTime(loadStore.currentLoad.est_loading_date, 0);
const dateEnd = getDateTime(loadStore.currentLoad.est_unloading_date, 0);
formLoad.price = loadStore.currentLoad.actual_cost;
formLoad.segment = loadStore.currentLoad.categories?.length <= 0 ? [] : loadStore.currentLoad.categories.map(m =>{
return m;
});
startLocation.value = loadStore.currentLoad.origin_formatted_address;
endLocation.value = loadStore.currentLoad.destination_formatted_address;
formLoad.terms = loadStore.currentLoad.product;
formLoad.owner = loadStore.currentLoad.posted_by_name;
formLoad.notes = loadStore.currentLoad.notes;
formLoad.weight = loadStore.currentLoad.weight;
formLoad.dateLoad = dateStart.substring(0, 10);
formLoad.dateDownload = dateEnd.substring(0, 10);
formLoad.truckType = loadStore.currentLoad.truck_type ? {meta_value: loadStore.currentLoad.truck_type} : null;
emails.value = loadStore.currentLoad?.alert_list || [];
getCoordsMap();
}
watch(origin, async() => {
if(origin.city && origin.state) {
startLocation.value = origin.address + ', ' + origin.city.city_name + ', ' + origin.state.state_name + ', ' + origin.country + ', ' +origin.postalCode;
originCoords.value = await geocodeAddress(startLocation.value);
}
})
watch(destination, async() => {
if(destination.city && destination.state) {
endLocation.value = destination.address + ', ' + destination.city.city_name + ', ' + destination.state.state_name + ', ' + destination.country + ', ' +destination.postalCode;
destinationCoords.value = await geocodeAddress(endLocation.value);
}
})
watch([originCoords, destinationCoords], async() => {
if(originCoords.value && destinationCoords.value) {
polylines.value = await getDirections(originCoords.value, destinationCoords.value);
}
})
})
watch(locationLoadSelected, () => {
origin.locationName = locationLoadSelected.value?.branch_name;
origin.address = locationLoadSelected.value?.address;
origin.state = { state_name: locationLoadSelected.value?.state };
origin.city = { city_name: locationLoadSelected.value?.city };
originRef.value = locationLoadSelected.value?.description;
});
watch(locationDownloadSelected, () => {
destination.locationName = locationDownloadSelected.value?.branch_name;
destination.address = locationDownloadSelected.value?.address;
destination.state = { state_name: locationDownloadSelected.value?.state };
destination.city = { city_name: locationDownloadSelected.value?.city };
destinationRef.value = locationDownloadSelected.value?.description;
});
const getLocations = async(type) => {
loadingLocations.value = true;
await companyStore.getLocationsLoads(type)
setLocations(type);
loadingLocations.value = false;
}
const setLocations = (type) => {
if(loadStore.currentLoad) {
if(type === 'loading') {
locationLoadSelected.value = companyStore.locationsLoad.find( (l) => l._id === loadStore.currentLoad?.origin_warehouse?._id);
origin.locationName = loadStore.currentLoad.origin.company_name;
origin.address = loadStore.currentLoad.origin.street_address1;
origin.state = loadStore.currentLoad.origin?.state ? { state_name: loadStore.currentLoad.origin.state } : null;
origin.city = loadStore.currentLoad.origin?.city ? { city_name: loadStore.currentLoad.origin.city } : null;
origin.country = loadStore.currentLoad.origin.country;
origin.postalCode = loadStore.currentLoad.origin.zipcode;
originRef.value = loadStore.currentLoad.origin.landmark;
} else {
locationDownloadSelected.value = companyStore.locationsDowload.find( (l) => l._id === loadStore.currentLoad?.destination_warehouse?._id)
destination.locationName = loadStore.currentLoad.destination.company_name;
destination.address = loadStore.currentLoad.destination.street_address1;
destination.state = loadStore.currentLoad.destination?.state ? { state_name: loadStore.currentLoad.destination.state } : null;
destination.city = loadStore.currentLoad.destination?.city ? { city_name: loadStore.currentLoad.destination.city } : null;
destination.country = loadStore.currentLoad.destination.country;
destination.postalCode = loadStore.currentLoad.destination.zipcode;
destinationRef.value = loadStore.currentLoad.destination.landmark;
}
}
}
const getCoordsMap = async() => {
const destinationLat = loadStore.currentLoad.destination?.lat;
const destinationLng = loadStore.currentLoad.destination?.lng;
const originLat = loadStore.currentLoad.origin?.lat;
const originLng = loadStore.currentLoad.origin?.lng;
if(destinationLat && destinationLng) {
destinationCoords.value = {lat: Number.parseFloat(destinationLat), lng: Number.parseFloat(destinationLng)}
}
if(originLat && originLng) {
originCoords.value = {lat: Number.parseFloat(originLat), lng: Number.parseFloat(originLng)}
}
if(originCoords.value && destinationCoords.value) {
polylines.value = await getDirections(originCoords.value, destinationCoords.value);
}
}
const formLoad = reactive({
dateLoad: '',
dateDownload: '',
segment: [],
truckType: '',
terms: '',
price: 0,
weight: 0,
notes: '',
owner: '',
});
const origin = reactive({
id: null,
locationName: '',
address: '',
state: '',
city: '',
country: '',
postalCode: '',
});
const destination = reactive({
locationName: '',
address: '',
state: '',
city: '',
country: '',
postalCode: '',
});
const setLoadData = () => {
const currentDate = new Date();
const hours = currentDate.getHours().toString().padStart(2, '0');
const minutes = currentDate.getMinutes().toString().padStart(2, '0');
const seconds = currentDate.getSeconds().toString().padStart(2, '0');
const startDate = formLoad.dateLoad === "" ? "" : new Date(`${formLoad.dateLoad}T${hours}:${minutes}:${seconds}`).toISOString();
const endDate = formLoad.dateDownload === "" ? "" : new Date(`${formLoad.dateDownload}T${hours}:${minutes}:${seconds}`).toISOString();
let loadData = {
actual_cost: formLoad.price,
truck_type: formLoad.truckType?.meta_value || null,
est_loading_date : startDate,
est_unloading_date : endDate,
notes : formLoad.notes,
weight : formLoad.weight,
product: formLoad.terms?.length <= 0 ? null : formLoad.terms,
categories: formLoad.segment || null,
origin:{
company_name : origin?.locationName,
street_address1 : origin?.address,
state : origin.state?.state_name,
city : origin.city?.city_name,
country : origin?.country,
landmark : originRef.value,
zipcode : origin?.postalCode,
lat : originCoords.value?.lat,
lng : originCoords.value?.lng
},
destination:{
company_name : destination?.locationName,
street_address1 : destination?.address,
state : destination.state?.state_name,
city : destination.city?.city_name,
country : destination?.country,
landmark : destinationRef.value,
zipcode : destination?.postalCode,
lat : destinationCoords.value?.lat,
lng : destinationCoords.value?.lng
},
company: auth.user.company,
posted_by: auth.user._id,
posted_by_name: formLoad.owner,
origin_warehouse: locationLoadSelected.value?._id || null,
destination_warehouse: locationDownloadSelected.value?._id || null,
alert_list: emails.value.length > 0 ? emails.value : null
};
return loadData;
}
const updateLoad = async(loadData) => {
isLoading.value = true;
if(loadStore.currentLoad){
const resp = await loadStore.updateLoad(loadStore.currentLoad._id, loadData);
isLoading.value = false;
const dataLocal = {
company: auth.user.company,
categories: formLoad.segment || null,
product: formLoad.terms?.length <= 0 ? null : formLoad.terms,
origin_warehouse: locationLoadSelected.value,
destination_warehouse: locationDownloadSelected.value,
};
if(resp) {
const index = loadStore.loads.findIndex((load) => load._id === resp._id);
loadStore.loads[index] = {
...loadStore.loads[index],
...resp,
...dataLocal,
};
return 'success';
} else {
return 'error';
}
} else{
const resp = await loadStore.saveLoad(loadData);
isLoading.value = false;
if(resp) {
const load = {
...resp,
...loadData,
categories: [loadData.categories],
origin_warehouse: locationLoadSelected.value,
destination_warehouse: locationDownloadSelected.value,
}
loadStore.loads.unshift(load);
return 'success';
} else {
return 'error';
}
}
}
const handleSave = async() => {
submited.value = false;
const loadData = setLoadData();
const resp = await updateLoad(loadData);
if(resp === 'success') {
notyStore.show = 'true';
notyStore.text = t('loads.msgSave');
document.getElementById('btnCloseFormLoadModal').click();
} else {
Swal.fire({
title: "Error!",
text: t('loads.msgNotSave'),
icon: "error"
});
}
}
const validations = () => {
errors.value = {
segment: (!formLoad.segment || formLoad.segment?.length <= 0) ? t('errors.segment') : null,
truckType: formLoad.truckType ? null : t('errors.truck'),
locationOrigin: locationLoadSelected.value ? null : 'Seleccione una ubicación de origen',
locationDestination: locationDownloadSelected.value ? null : 'Seleccione una ubicación de destino',
};
}
const handlePostLoad = async() => {
submited.value = true;
setTimeout(async() => {
const formValid = formRef.value.checkValidity();
validations()
if(formValid){
const hasError = Object.values(errors.value).some(val => val != null);
if(!hasError) {
let loadData = setLoadData();
loadData = {
...loadData,
status: "Published",
load_status: "Published"
}
const resp = await updateLoad(loadData);
if(resp === 'success') {
notyStore.show = 'true';
notyStore.text = t('loads.msgPost')
document.getElementById('btnCloseFormLoadModal').click();
} else {
Swal.fire({
title: "Error!",
text: t('loads.msgNotPost'),
icon: "error"
});
}
}
}
}, 200)
}
const title = computed(() => loadStore.currentLoad == null
? t('loads.create')
: t('loads.edit')
)
const addObserver = () => {
const trimmedEmail = emailInput.value.trim()
if (trimmedEmail && validateEmail(trimmedEmail)) {
if(emails.value.includes(trimmedEmail)) {
Swal.fire({
title: t('errors.emailExist'),
icon: 'error'
})
return
}
emails.value.push(trimmedEmail)
emailInput.value = ''
} else if (trimmedEmail) {
Swal.fire({
title: t('errors.email'),
icon: 'error'
})
}
}
const removeObserver = (email) => {
emails.value = emails.value.filter((e) => e !== email)
}
</script>
<template>
<div class="modal fade" id="formLoadModal" tabindex="-1" role="dialog" aria-labelledby="formLoadModal" aria-hidden="true">
<div class="modal-dialog modal-fullscreen modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="title mt-2 mb-3">{{ title }}</h2>
<button
id="btnCloseFormLoadModal"
type="button"
class="close bg-white"
data-dismiss="modal"
@click="clearLoad"
aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form class="form-content" ref="formRef">
<div class="form-box">
<div class="form-section">
<div class="mb-4 mt-3">
<label class="custom-label required">{{ t('global.segment') }}*</label>
<Segments
v-model="formLoad.segment"
/>
<span class="error-msg" v-if="submited && errors.segment">{{ errors.segment }}</span>
</div>
<div class="mb-4 mt-3">
<label class="custom-label required">{{ t('directory.typeTruck') }}*</label>
<TruckTypes
v-model="formLoad.truckType"
/>
<span class="error-msg" v-if="submited && errors.truckType">{{ errors.truckType }}</span>
</div>
<Custominput
:label="t('loads.dateLoad') + '*'"
type="date"
:filled="false"
name="date-load"
:required="submited ? true : false"
:error="(submited && !formLoad.dateLoad) ? t('errors.date') : null"
v-model:field="formLoad.dateLoad"
/>
<Custominput
:label="t('loads.dateDownload') + '*'"
type="date"
:filled="false"
name="date-download"
:required="submited ? true : false"
:error="(submited && !formLoad.dateDownload) ? t('errors.date') : null"
v-model:field="formLoad.dateDownload"
/>
<Custominput
:label="t('loads.labelWeight') + '*'"
type="number"
:filled="false"
name="weight"
:required="submited ? true : false"
:error="(submited && !formLoad.weight) ? t('errors.weight') : null"
v-model:field="formLoad.weight"
/>
<div class="mb-4 mt-3">
<label class="custom-label">{{ t('loads.product') }}</label>
<Products
v-model="formLoad.terms"
/>
</div>
</div>
<div class="form-section">
<Custominput
:label="t('loads.labelPrice')"
type="Number"
:filled="false"
name="price"
v-model:field="formLoad.price"
/>
<Custominput
:label="t('loads.notes')"
type="text"
:filled="false"
name="notes"
v-model:field="formLoad.notes"
/>
<Custominput
:label="t('loads.postBy')"
type="text"
:filled="false"
:readonly="true"
name="owner"
v-model:field="formLoad.owner"
/>
<div class="box-observers mt-4">
<div class="box-input">
<div class="input-observer">
<Custominput
label="Agregar correo del cliente"
name="email"
type="email"
v-model:field="emailInput"
:filled="false"
:tooltip="t('messages.observerClient')"
/>
</div>
<button
type="button"
@click="addObserver"
class="btn-leading-input mb-4"
>
Agregar
</button>
</div>
<h5 v-if="emails.length > 0">Lista de correos de clientes:</h5>
<div class="box-emails" v-if="emails.length > 0">
<div
v-for="(email, index) in emails"
:key="email"
class="observer-email"
>
<span>{{ email }}</span>
<i
@click="removeObserver(email)"
class="fa-solid fa-xmark icon-delete">
</i>
</div>
</div>
</div>
</div>
</div>
<div class="form-box">
<div class="form-section">
<Spiner v-if="loadingLocations"/>
<div class="d-flex flex-column mb-4" v-if="!loadingLocations">
<label class="custom-label mb-2" for="locationLoad">{{ t('loads.addressOrigin') }}:</label>
<select
class="custom-input-light"
name="locationLoad"
id="locationLoad"
v-model="locationLoadSelected"
>
<option disabled value="">-- {{ t('loads.selectedLocation') }} --</option>
<option v-for="loc in companyStore.locationsLoad" :value="loc">{{ loc.branch_name }}</option>
</select>
<span class="error-msg" v-if="submited && errors.locationOrigin">{{ errors.locationOrigin }}</span>
</div>
<AddressPreview
v-if="origin.locationName"
:address="origin"
/>
</div>
<div class="form-section">
<Spiner v-if="loadingLocations"/>
<div class="d-flex flex-column mb-4" v-if="!loadingLocations">
<label class="custom-label mb-2" for="locationDownload">{{ t('loads.addressDestination') }}:</label>
<select
class="custom-input-light"
name="locationDownload"
id="locationDownload"
v-model="locationDownloadSelected"
>
<option disabled value="">-- {{ t('loads.selectedLocation') }} --</option>
<option v-for="loc in companyStore.locationsDowload" :value="loc">{{ loc.branch_name }}</option>
</select>
<span class="error-msg" v-if="submited && errors.locationDestination">{{ errors.locationDestination }}</span>
</div>
<AddressPreview
v-if="destination.locationName"
:address="destination"
/>
</div>
</div>
</form>
<GoogleMap
:api-key="mapKey"
:center="{lat:19.432600, lng:-99.133209}"
:zoom="zoom"
:min-zoom="2"
:max-zoom="12"
:style="{width: 100 + '%', height: heightMap + 'px'}"
:options="{
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: true,
rotateControl: true,
fullscreenControl: true
}"
>
<Marker v-if="originCoords" :options="{position: originCoords, label: 'O', title: 'Destino'}" />
<Marker v-if="destinationCoords" :options="{position: destinationCoords, label: 'D', title: 'Origen'}" />
<Polyline
v-if="polylines"
:options="{
path: polylines,
// geodesic: true,
strokeColor: '#2D90BB',
strokeOpacity: 0.7,
strokeWeight: 5,
clickable: true,
fillColor: '#75ad3e',
}"
/>
</GoogleMap>
</div>
<div class="modal-footer custom-footer">
<Spiner v-if="isLoading"/>
<div v-else class="btns-footer">
<button
type="button"
class="btn btn-dark"
@click="clearLoad"
data-dismiss="modal">{{ t('buttons.close') }}</button>
<button
type="button"
class="btn btn-dark"
@click="handleSave"
>{{ t('buttons.save') }}</button>
<button
type="submit"
@click.prevent="handlePostLoad"
class="btn-primary-sm radius-sm"
>{{ t('buttons.post') }}</button>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.form-content {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-content: center;
align-items: center;
margin: 0 auto;
}
.form-box {
width: 80%;
display: flex;
flex-direction: row;
justify-content: space-between;
gap: 4rem;
}
.form-section {
width: 100%;
}
.custom-footer {
display: flex;
justify-content: center;
}
.error-msg {
color: red;
font-size: 12px;
font-weight: 300;
}
.btns-footer {
display: flex;
gap: 1rem;
}
.chekmark {
height: 25px;
width: 25px;
margin-right: 10px;
}
.radius-sm{
border-radius: 5px;
}
@media (max-width: 1024px) {
.form-box {
width: 95%;
gap: 2rem;
}
}
@media (max-width: 568px) {
.form-box {
width: 100%;
flex-direction: column;
gap: 2rem;
}
}
</style>