mirror of
https://git.imnavajas.es/jjimenez/erp-imprimelibros.git
synced 2026-01-24 09:40:21 +00:00
direccion unica añadida
This commit is contained in:
@ -1,27 +1,214 @@
|
||||
$(() => {
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
|
||||
const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');
|
||||
if (window.$ && csrfToken && csrfHeader) {
|
||||
$.ajaxSetup({
|
||||
beforeSend: function (xhr) {
|
||||
xhr.setRequestHeader(csrfHeader, csrfToken);
|
||||
}
|
||||
});
|
||||
}
|
||||
$("#onlyOneShipping").on('change', function () {
|
||||
if ($(this).is(':checked')) {
|
||||
$('.nav-product').hide();
|
||||
document.querySelectorAll('.card.product').forEach(card => {
|
||||
const detailsBtn = card.querySelector('.nav-link[id^="pills-details-"][id$="-tab"]');
|
||||
if (detailsBtn) new bootstrap.Tab(detailsBtn).show();
|
||||
});
|
||||
$('#shippingAddressesContainer').empty().show();
|
||||
$('.div-shipping-product').show();
|
||||
$('#addOrderAddress').show();
|
||||
} else {
|
||||
$('.nav-product').show();
|
||||
$('#shippingAddressesContainer').hide();
|
||||
$('.div-shipping-product').empty().hide();
|
||||
$('#addOrderAddress').hide();
|
||||
}
|
||||
});
|
||||
|
||||
$('#shippingAddressesContainer').on('click', '.btn-delete-direccion', function (e) {
|
||||
e.preventDefault();
|
||||
const $card = $(this).closest('.direccion-card');
|
||||
$card.remove();
|
||||
$('#addOrderAddress').show();
|
||||
});
|
||||
|
||||
const language = document.documentElement.lang || 'es-ES';
|
||||
const modalEl = document.getElementById('direccionFormModal');
|
||||
const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
|
||||
|
||||
|
||||
$("#onlyOneShipping").on('change', function () {
|
||||
if ($(this).is(':checked')) {
|
||||
$('#shippingAddressesContainer').empty().show();
|
||||
$('#shippingMultipleAddressesContainer').show();
|
||||
$(document).on("change", ".direccionFacturacion", function () {
|
||||
const isChecked = $(this).is(':checked');
|
||||
if (isChecked) {
|
||||
$('.direccionFacturacionItems').removeClass('d-none');
|
||||
} else {
|
||||
$('#shippingAddressesContainer').hide();
|
||||
$('#shippingMultipleAddressesContainer').empty().hide();
|
||||
$('.direccionFacturacionItems').addClass('d-none');
|
||||
$('#razonSocial').val('');
|
||||
$('#tipoIdentificacionFiscal').val('DNI');
|
||||
$('#identificacionFiscal').val('');
|
||||
}
|
||||
});
|
||||
|
||||
$('#addOrderAddress').on('click', () => {
|
||||
if ($('#onlyOneShipping').is(':checked')) {
|
||||
if(seleccionarDireccionEnvio()){
|
||||
$('#addOrderAddress').hide();
|
||||
}
|
||||
} else {
|
||||
// Add address to multiple shipping addresses container
|
||||
}
|
||||
});
|
||||
|
||||
async function seleccionarDireccionEnvio() {
|
||||
|
||||
const { value: direccionId, isDenied } = await Swal.fire({
|
||||
title: window.languageBundle['cart.shipping.add.title'] || 'Seleccione una dirección',
|
||||
html: `
|
||||
<select id="direccionSelect" class="form-select" style="width: 100%"></select>
|
||||
`,
|
||||
showCancelButton: true,
|
||||
showDenyButton: true,
|
||||
buttonsStyling: false,
|
||||
confirmButtonText: window.languageBundle['app.seleccionar'] || 'Seleccionar',
|
||||
cancelButtonText: window.languageBundle['app.cancelar'] || 'Cancelar',
|
||||
denyButtonText: window.languageBundle['cart.shipping.new-address'] || 'Nueva dirección',
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-secondary me-2',
|
||||
cancelButton: 'btn btn-light',
|
||||
denyButton: 'btn btn-secondary me-2'
|
||||
},
|
||||
focusConfirm: false,
|
||||
|
||||
// Inicializa cuando el DOM del modal ya existe
|
||||
didOpen: () => {
|
||||
const $select = $('#direccionSelect');
|
||||
$select.empty(); // limpia placeholder estático
|
||||
|
||||
$select.select2({
|
||||
width: '100%',
|
||||
dropdownParent: $('.swal2-container'),
|
||||
ajax: {
|
||||
url: '/direcciones/select2',
|
||||
dataType: 'json',
|
||||
delay: 250,
|
||||
data: params => ({ q: params.term || '' }),
|
||||
processResults: (data) => {
|
||||
const items = Array.isArray(data) ? data : (data.results || []);
|
||||
return {
|
||||
results: items.map(item => ({
|
||||
id: item.id,
|
||||
text: item.text, // ← Select2 necesita 'id' y 'text'
|
||||
alias: item.alias || 'Sin alias',
|
||||
att: item.att || '',
|
||||
direccion: item.direccion || '',
|
||||
cp: item.cp || '',
|
||||
ciudad: item.ciudad || '',
|
||||
html: `
|
||||
<div>
|
||||
<strong>${item.alias || 'Sin alias'}</strong><br>
|
||||
${item.att ? `<small>${item.att}</small><br>` : ''}
|
||||
<small>${item.direccion || ''}${item.cp ? ', ' + item.cp : ''}${item.ciudad ? ', ' + item.ciudad : ''}</small>
|
||||
</div>
|
||||
`
|
||||
})),
|
||||
pagination: { more: false } // opcional, evita que espere más páginas
|
||||
};
|
||||
}
|
||||
|
||||
},
|
||||
placeholder: window.languageBundle['cart.shipping.select-placeholder'] || 'Buscar en direcciones...',
|
||||
language: language,
|
||||
|
||||
templateResult: data => {
|
||||
if (data.loading) return data.text;
|
||||
return $(data.html || data.text);
|
||||
},
|
||||
// Selección más compacta (solo alias + ciudad)
|
||||
templateSelection: data => {
|
||||
if (!data.id) return data.text;
|
||||
const alias = data.alias || data.text;
|
||||
const ciudad = data.ciudad ? ` — ${data.ciudad}` : '';
|
||||
return $(`<span>${alias}${ciudad}</span>`);
|
||||
},
|
||||
escapeMarkup: m => m
|
||||
});
|
||||
|
||||
// (Opcional) Prefijar valor si ya tienes una dirección elegida:
|
||||
// const preselected = { id: '123', text: 'Oficina Central — Madrid' };
|
||||
// const option = new Option(preselected.text, preselected.id, true, true);
|
||||
// $select.append(option).trigger('change');
|
||||
},
|
||||
|
||||
preConfirm: () => {
|
||||
const $select = $('#direccionSelect');
|
||||
const val = $select.val();
|
||||
if (!val) {
|
||||
Swal.showValidationMessage(
|
||||
window.languageBundle['cart.shipping.errors.noAddressSelected'] || 'Por favor, seleccione una dirección.'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return val;
|
||||
},
|
||||
|
||||
didClose: () => {
|
||||
// Limpieza: destruir select2 para evitar fugas
|
||||
const $select = $('#direccionSelect');
|
||||
if ($select.data('select2')) {
|
||||
$select.select2('destroy');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (isDenied) {
|
||||
$.get('/direcciones/direction-form', function (html) {
|
||||
$('#direccionFormModalBody').html(html);
|
||||
const title = $('#direccionFormModalBody #direccionForm').data('add');
|
||||
$('#direccionFormModal .modal-title').text(title);
|
||||
modal.show();
|
||||
});
|
||||
}
|
||||
|
||||
if (direccionId) {
|
||||
// Obtén el objeto completo seleccionado
|
||||
const response = await fetch(`/cart/get-address/${direccionId}`);
|
||||
if (response.ok) {
|
||||
const html = await response.text();
|
||||
$('#shippingAddressesContainer').append(html);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
$(document).on('submit', '#direccionForm', function (e) {
|
||||
e.preventDefault();
|
||||
const $form = $(this);
|
||||
|
||||
$.ajax({
|
||||
url: $form.attr('action'),
|
||||
type: 'POST', // PUT simulado via _method
|
||||
data: $form.serialize(),
|
||||
dataType: 'html',
|
||||
success: function (html) {
|
||||
// Si por cualquier motivo llega 200 con fragmento, lo insertamos igual
|
||||
if (typeof html === 'string' && html.indexOf('id="direccionForm"') !== -1 && html.indexOf('<html') === -1) {
|
||||
$('#direccionFormModalBody').html(html);
|
||||
const isEdit = $('#direccionFormModalBody #direccionForm input[name="_method"][value="PUT"]').length > 0;
|
||||
const title = $('#direccionFormModalBody #direccionForm').data(isEdit ? 'edit' : 'add');
|
||||
$('#direccionModal .modal-title').text(title);
|
||||
return;
|
||||
}
|
||||
// Éxito real: cerrar y recargar tabla
|
||||
modal.hide();
|
||||
seleccionarDireccionEnvio();
|
||||
},
|
||||
error: function (xhr) {
|
||||
// Con 422 devolvemos el fragmento con errores aquí
|
||||
if (xhr.status === 422 && xhr.responseText) {
|
||||
$('#direccionFormModalBody').html(xhr.responseText);
|
||||
const isEdit = $('#direccionFormModalBody #direccionForm input[name="_method"][value="PUT"]').length > 0;
|
||||
const title = $('#direccionFormModalBody #direccionForm').data(isEdit ? 'edit' : 'add');
|
||||
$('#direccionModal .modal-title').text(title);
|
||||
initSelect2Cliente(true);
|
||||
return;
|
||||
}
|
||||
// Fallback
|
||||
$('#direccionFormModalBody').html('<div class="p-3 text-danger">Error inesperado.</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -15,179 +15,7 @@ $(() => {
|
||||
const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
|
||||
|
||||
|
||||
$("#onlyOneShipping").on('change', function () {
|
||||
if ($(this).is(':checked')) {
|
||||
$('#shippingAddressesContainer').empty().show();
|
||||
$('#shippingMultipleAddressesContainer').show();
|
||||
} else {
|
||||
$('#shippingAddressesContainer').hide();
|
||||
$('#shippingMultipleAddressesContainer').empty().hide();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
$('#addOrderAddress').on('click', () => {
|
||||
if ($('#onlyOneShipping').is(':checked')) {
|
||||
seleccionarDireccionEnvio();
|
||||
} else {
|
||||
// Add address to multiple shipping addresses container
|
||||
}
|
||||
});
|
||||
|
||||
async function seleccionarDireccionEnvio() {
|
||||
|
||||
const { value: direccionId, isDenied } = await Swal.fire({
|
||||
title: window.languageBundle['checkout.shipping.add.title'] || 'Seleccione una dirección',
|
||||
html: `
|
||||
<select id="direccionSelect" class="form-select" style="width: 100%"></select>
|
||||
`,
|
||||
showCancelButton: true,
|
||||
showDenyButton: true,
|
||||
buttonsStyling: false,
|
||||
confirmButtonText: window.languageBundle['app.seleccionar'] || 'Seleccionar',
|
||||
cancelButtonText: window.languageBundle['app.cancelar'] || 'Cancelar',
|
||||
denyButtonText: window.languageBundle['checkout.shipping.new-address'] || 'Nueva dirección',
|
||||
customClass: {
|
||||
confirmButton: 'btn btn-secondary me-2',
|
||||
cancelButton: 'btn btn-light',
|
||||
denyButton: 'btn btn-secondary me-2'
|
||||
},
|
||||
focusConfirm: false,
|
||||
|
||||
// Inicializa cuando el DOM del modal ya existe
|
||||
didOpen: () => {
|
||||
const $select = $('#direccionSelect');
|
||||
$select.empty(); // limpia placeholder estático
|
||||
|
||||
$select.select2({
|
||||
width: '100%',
|
||||
dropdownParent: $('.swal2-container'),
|
||||
ajax: {
|
||||
url: '/direcciones/select2',
|
||||
dataType: 'json',
|
||||
delay: 250,
|
||||
data: params => ({ q: params.term || '' }),
|
||||
processResults: (data) => {
|
||||
const items = Array.isArray(data) ? data : (data.results || []);
|
||||
return {
|
||||
results: items.map(item => ({
|
||||
id: item.id,
|
||||
text: item.text, // ← Select2 necesita 'id' y 'text'
|
||||
alias: item.alias || 'Sin alias',
|
||||
att: item.att || '',
|
||||
direccion: item.direccion || '',
|
||||
cp: item.cp || '',
|
||||
ciudad: item.ciudad || '',
|
||||
html: `
|
||||
<div>
|
||||
<strong>${item.alias || 'Sin alias'}</strong><br>
|
||||
${item.att ? `<small>${item.att}</small><br>` : ''}
|
||||
<small>${item.direccion || ''}${item.cp ? ', ' + item.cp : ''}${item.ciudad ? ', ' + item.ciudad : ''}</small>
|
||||
</div>
|
||||
`
|
||||
})),
|
||||
pagination: { more: false } // opcional, evita que espere más páginas
|
||||
};
|
||||
}
|
||||
|
||||
},
|
||||
placeholder: window.languageBundle['checkout.shipping.select-placeholder'] || 'Buscar en direcciones...',
|
||||
language: language,
|
||||
|
||||
templateResult: data => {
|
||||
if (data.loading) return data.text;
|
||||
return $(data.html || data.text);
|
||||
},
|
||||
// Selección más compacta (solo alias + ciudad)
|
||||
templateSelection: data => {
|
||||
if (!data.id) return data.text;
|
||||
const alias = data.alias || data.text;
|
||||
const ciudad = data.ciudad ? ` — ${data.ciudad}` : '';
|
||||
return $(`<span>${alias}${ciudad}</span>`);
|
||||
},
|
||||
escapeMarkup: m => m
|
||||
});
|
||||
|
||||
// (Opcional) Prefijar valor si ya tienes una dirección elegida:
|
||||
// const preselected = { id: '123', text: 'Oficina Central — Madrid' };
|
||||
// const option = new Option(preselected.text, preselected.id, true, true);
|
||||
// $select.append(option).trigger('change');
|
||||
},
|
||||
|
||||
preConfirm: () => {
|
||||
const $select = $('#direccionSelect');
|
||||
const val = $select.val();
|
||||
if (!val) {
|
||||
Swal.showValidationMessage(
|
||||
lang.startsWith('es') ? 'Debes seleccionar una dirección' : 'You must select an address'
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return val;
|
||||
},
|
||||
|
||||
didClose: () => {
|
||||
// Limpieza: destruir select2 para evitar fugas
|
||||
const $select = $('#direccionSelect');
|
||||
if ($select.data('select2')) {
|
||||
$select.select2('destroy');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (isDenied) {
|
||||
$.get('/direcciones/direction-form', function (html) {
|
||||
$('#direccionFormModalBody').html(html);
|
||||
const title = $('#direccionFormModalBody #direccionForm').data('add');
|
||||
$('#direccionFormModal .modal-title').text(title);
|
||||
modal.show();
|
||||
});
|
||||
}
|
||||
|
||||
if (direccionId) {
|
||||
// Obtén el objeto completo seleccionado
|
||||
const response = await fetch(`/checkout/get-address/${direccionId}`);
|
||||
if (response.ok) {
|
||||
const html = await response.text();
|
||||
$('#shippingAddressesContainer').html(html);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$(document).on('submit', '#direccionForm', function (e) {
|
||||
e.preventDefault();
|
||||
const $form = $(this);
|
||||
|
||||
$.ajax({
|
||||
url: $form.attr('action'),
|
||||
type: 'POST', // PUT simulado via _method
|
||||
data: $form.serialize(),
|
||||
dataType: 'html',
|
||||
success: function (html) {
|
||||
// Si por cualquier motivo llega 200 con fragmento, lo insertamos igual
|
||||
if (typeof html === 'string' && html.indexOf('id="direccionForm"') !== -1 && html.indexOf('<html') === -1) {
|
||||
$('#direccionFormModalBody').html(html);
|
||||
const isEdit = $('#direccionFormModalBody #direccionForm input[name="_method"][value="PUT"]').length > 0;
|
||||
const title = $('#direccionFormModalBody #direccionForm').data(isEdit ? 'edit' : 'add');
|
||||
$('#direccionModal .modal-title').text(title);
|
||||
return;
|
||||
}
|
||||
// Éxito real: cerrar y recargar tabla
|
||||
modal.hide();
|
||||
seleccionarDireccionEnvio();
|
||||
},
|
||||
error: function (xhr) {
|
||||
// Con 422 devolvemos el fragmento con errores aquí
|
||||
if (xhr.status === 422 && xhr.responseText) {
|
||||
$('#direccionFormModalBody').html(xhr.responseText);
|
||||
const isEdit = $('#direccionFormModalBody #direccionForm input[name="_method"][value="PUT"]').length > 0;
|
||||
const title = $('#direccionFormModalBody #direccionForm').data(isEdit ? 'edit' : 'add');
|
||||
$('#direccionModal .modal-title').text(title);
|
||||
initSelect2Cliente(true);
|
||||
return;
|
||||
}
|
||||
// Fallback
|
||||
$('#direccionFormModalBody').html('<div class="p-3 text-danger">Error inesperado.</div>');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user