0
1
Fork 0
This commit is contained in:
William Buezas 2024-08-28 16:12:34 -03:00
parent facbe9b990
commit cb2c9871cc
12 changed files with 260 additions and 112 deletions

View File

@ -97,6 +97,7 @@ const url = computed(() => {
spinner-color="primary"
:width="props.width"
:height="props.height"
draggable
>
<template #error>
<div
@ -115,6 +116,7 @@ const url = computed(() => {
class="img_zoom"
v-bind="$attrs"
spinner-color="primary"
draggable
/>
</QDialog>
<QDialog v-if="props.editable" v-model="showEditForm">

View File

@ -61,6 +61,8 @@ export default {
adminNewsDetails: 'Afegir o editar notícia',
//
orderLoadedIntoBasket: 'Comanda carregada a la cistella!',
loadAnOrder:
'Si us plau carrega una comanda pendent a la cistella o en comença una de nova',
at: 'a les',
back: 'Tornar',
remove: 'Esborrar',

View File

@ -74,6 +74,7 @@ export default {
adminNewsDetails: 'Add or edit new',
//
orderLoadedIntoBasket: 'Order loaded into basket!',
loadAnOrder: 'Please load a pending order to the cart or start a new one',
at: 'at',
back: 'Back',
remove: 'Remove',

View File

@ -80,6 +80,8 @@ export default {
adminNewsDetails: 'Añadir o editar noticia',
//
orderLoadedIntoBasket: '¡Pedido cargado en la cesta!',
loadAnOrder:
'Por favor carga un pedido pendiente en la cesta o empieza uno nuevo',
at: 'a las',
back: 'Volver',
remove: 'Borrar',

View File

@ -61,6 +61,8 @@ export default {
adminNewsDetails: 'Ajouter ou editer nouvelles',
//
orderLoadedIntoBasket: 'Commande chargée dans le panier!',
loadAnOrder:
'Veuillez télécharger une commande en attente dans le panier ou en démarrer une nouvelle',
at: 'à',
back: 'Retour',
remove: 'Effacer',

View File

@ -62,6 +62,7 @@ export default {
adminNewsDetails: 'Ajouter ou editer nouvelles',
//
orderLoadedIntoBasket: 'Pedido carregado na cesta!',
loadAnOrder: 'Carregue um pedido pendente no carrinho ou inicie um novo',
at: 'às',
back: 'Voltar',
remove: 'Eliminar',

View File

@ -130,7 +130,6 @@ export class Connection extends JsonConnection {
async getValue(query, params) {
const res = await this.execQuery(query, params);
console.log('RESSSS: ', res);
return res.fetchValue();
}

View File

@ -96,7 +96,6 @@ export class ResultSet {
*/
fetchValue() {
const row = this.fetchRow();
console.log('row', row);
if (row instanceof Array && row.length > 0) {
return row[0];
}
@ -111,7 +110,6 @@ export class ResultSet {
*/
fetchRow() {
const result = this.fetch();
console.log('test result', result);
if (
result !== null &&
result.data instanceof Array &&

View File

@ -1 +1,14 @@
<template>Basket view</template>
<script setup>
import { onBeforeMount } from 'vue';
import { useAppStore } from 'stores/app';
const appStore = useAppStore();
onBeforeMount(() => {
appStore.check();
});
</script>
<template>
<div>basket view</div>
</template>

View File

@ -37,7 +37,16 @@
{{ $t('warehouse') }}
{{ 'Algemesi' }}
</p>
<QBtn flat rounded no-caps>
<QBtn
flat
rounded
no-caps
:to="{
name: 'checkout',
params: { id: appStore.basketOrderId },
query: { continue: 'catalog' }
}"
>
{{ $t('modify') }}
</QBtn>
</div>
@ -355,7 +364,7 @@ export default {
setup() {
const appStore = useAppStore();
const { isHeaderMounted } = storeToRefs(appStore);
return { isHeaderMounted };
return { isHeaderMounted, appStore };
},
data() {
return {
@ -417,6 +426,12 @@ export default {
created() {
this.$app.useRightDrawer = true;
},
async beforeMount() {
const isGuest = false; // TODO: Integrate isGuest logic
if (!isGuest) {
this.appStore.check('catalog');
}
},
async mounted() {
this.categories = await this.$jApi.query(
`SELECT c.id, l.name, c.color, c.code

View File

@ -5,7 +5,7 @@ import { useRoute, useRouter } from 'vue-router';
import VnSelect from 'src/components/common/VnSelect.vue';
import { formatDateTitle } from 'src/lib/filters.js';
import { formatDateTitle, formatDate } from 'src/lib/filters.js';
import useNotify from 'src/composables/useNotify.js';
import { useAppStore } from 'stores/app';
@ -22,14 +22,13 @@ const loading = ref(false);
const today = ref(null);
const addresses = ref([]);
const agencies = ref([]);
const warehouses = ref([]);
const currentStep = ref('method');
// const lastStep = 'confirm';
const id = route.params.id;
const orderForm = ref({
method: '',
method: 'AGENCY',
date: '',
address: '',
agency: ''
address: ''
});
const steps = {
@ -37,50 +36,26 @@ const steps = {
{
name: 'method',
stepDone: false,
validateStep: () => {
const validation = !!orderForm.value.method;
console.log('validation:', validation);
if (!validation) {
notify(t('pleaseSelectADate'), 'negative');
}
return validation;
}
validateStep: () =>
validateStep('method', t('pleaseSelectAnOption'))
},
{
name: 'date',
stepDone: false,
validateStep: () => {
const validation = !!orderForm.value.date;
console.log('validation:', validation);
if (!validation) {
notify(t('pleaseSelectAnOption'), 'negative');
}
return validation;
}
validateStep: () => validateStep('date', t('pleaseSelectADate'))
},
{
name: 'address',
validateStep: () => {
const validation = !!orderForm.value.address;
if (!validation) {
notify(t('pleaseSelectAnAddress'), 'negative');
}
return validation;
}
validateStep: () =>
validateStep('address', t('pleaseSelectAnAddress'))
},
{
name: 'agency',
onStepMounted: async () => {
await getAgencies();
},
validateStep: () => {
const validation = !!orderForm.value.agency;
if (!validation) {
notify(t('pleaseSelectAnAgency'), 'negative');
}
return validation;
}
validateStep: () =>
validateStep('agency', t('pleaseSelectAnAgency'))
},
{
name: 'confirm',
@ -91,25 +66,41 @@ const steps = {
],
PICKUP: [
{
name: 'method'
// validateStep: () => {
// const validation = orderForm.value.method !== '';
// if (!validation) {
// notify('Please select a method', 'negative');
// }
// return validation;
// }
name: 'method',
validateStep: () =>
validateStep('method', t('pleaseSelectAnOption'))
},
{
name: 'date',
validateStep: () => validateStep('date', t('pleaseSelectADate'))
},
{ name: 'date' },
{ name: 'address' },
{ name: 'pickup' },
{ name: 'confirm' }
{
name: 'pickup',
validateStep: () =>
validateStep('agency', t('pleaseSelectAWarehouse')),
onStepMounted: async () => {
await getWarehouses();
}
},
{
name: 'confirm',
onBeforeNextStep: async () => {
await submit();
}
}
]
};
const confirmArrivalText = computed(() => {
if (!orderForm.value.agency) return '';
return `${t('arrival')} ${formatDateTitle(orderForm.value.date)}`;
const { method, agency, date } = orderForm.value;
if (!agency) {
return '';
}
const arrivalType = method === 'AGENCY' ? t('arrival') : t('pickup');
return `${arrivalType} ${formatDateTitle(date)}`;
});
const confirmAddressText = computed(() => {
@ -120,14 +111,33 @@ const confirmAddressText = computed(() => {
return address.street;
});
const confirmAgencyText = computed(() => {
if (!orderForm.value.agency) return '';
const agency = agencies.value.find(
agency => agency.id === orderForm.value.agency
);
return `${t('agency')} ${agency.description}`;
const confirmPlaceText = computed(() => {
const { agency, method } = orderForm.value;
if (!agency) return '';
if (method === 'AGENCY') {
const agencyItem = agencies.value.find(a => a.id === agency);
return agencyItem ? `${t('agency')} ${agencyItem.description}` : '';
}
if (method === 'PICKUP') {
const warehouseItem = warehouses.value.find(w => w.id === agency);
return warehouseItem
? `${t('warehouse')} ${warehouseItem.description}`
: '';
}
return '';
});
const validateStep = (formField, errorMessage) => {
const validation = !!orderForm.value[formField];
if (!validation) {
notify(errorMessage, 'negative');
}
return validation;
};
const getAddresses = async () => {
try {
addresses.value = await jApi.query(
@ -137,7 +147,6 @@ const getAddresses = async () => {
JOIN vn.country c ON c.id = p.countryFk
WHERE a.isActive`
);
console.log('addresses:', addresses.value);
} catch (error) {
console.error('Error getting addresses:', error);
}
@ -157,20 +166,44 @@ const getAgencies = async () => {
DROP TEMPORARY TABLE tmp.zoneGetAgency`,
{
address: orderForm.value.address,
date: orderForm.value.date
date: new Date(orderForm.value.date)
}
);
agencies.value = results[1].data;
console.log('AGENCIES:', agencies.value);
} catch (error) {
console.error('Error getting agencies:', error);
}
};
const getWarehouses = async () => {
try {
const { results } = await jApi.execQuery(
`CALL vn.zone_getAgency(#address, #date);
SELECT DISTINCT a.agencyModeFk id, a.description
FROM tmp.zoneGetAgency a
JOIN vn.deliveryMethod d
ON d.id = a.deliveryMethodFk
WHERE d.code IN ('PICKUP')
AND a.isVisible
ORDER BY a.description;
DROP TEMPORARY TABLE tmp.zoneGetAgency;`,
{
address: orderForm.value.address,
date: new Date(orderForm.value.date)
}
);
warehouses.value = results[1].data;
if (!warehouses.value || !warehouses.value.length) {
notify(t('noWarehousesAvailableForDate'), 'negative');
}
} catch (error) {
console.error('Error getting agencies:', error);
}
};
const onNextStep = async stepIndex => {
console.log('on next step');
const currentStep = steps[orderForm.value.method][stepIndex];
console.log('currentStep:', currentStep);
if (currentStep.onBeforeNextStep) {
await currentStep.onBeforeNextStep();
}
@ -183,17 +216,12 @@ const onNextStep = async stepIndex => {
await stepperRef.value.next();
const nextStep = steps[orderForm.value.method][stepIndex + 1];
console.log('nextStep:', nextStep);
if (nextStep && nextStep.onStepMounted) {
await nextStep.onStepMounted();
}
};
const onPreviousStep = async stepIndex => {
console.log('on previous step');
const currentStep = steps[orderForm.value.method][stepIndex];
console.log('step:', currentStep);
await stepperRef.value.previous();
const previousStep = steps[orderForm.value.method][stepIndex - 1];
@ -220,24 +248,20 @@ const submit = async () => {
'CALL myOrder_configure(#id, #date, #method, #agency, #address)';
}
console.log('id:', id);
let resultSet;
try {
resultSet = await jApi.execQuery(query, orderForm.value);
console.log('resultSet:', resultSet);
const { date, ...restOfForm } = orderForm.value;
const _date = new Date(date);
resultSet = await jApi.execQuery(query, { ...restOfForm, date: _date });
if (id) {
notify(t('orderUpdated'), 'positive');
if (route.query.continue === 'catalog') {
router.push({ name: 'catalog' });
} else {
router.push({ name: 'basket', params: { id } });
}
} else {
console.log('pre resultSet log: ', resultSet);
// const orderId = resultSet.fetchValue(); por alguna razon no funciona
const orderId = resultSet.results[1].data[0]['@orderId'];
console.log('orderId:', orderId);
appStore.loadIntoBasket(orderId);
router.push({ name: 'catalog' });
}
@ -246,37 +270,34 @@ const submit = async () => {
} finally {
loading.value = false;
}
// const basket = new Hedera.Basket(this.app);
// if (id) {
// Htk.Toast.showMessage(_('OrderUpdated'));
// switch (this.hash.$.continue) {
// case 'catalog':
// redirect = { form: 'ecomerce/catalog' };
// break;
// default:
// redirect = { form: 'ecomerce/basket' };
// if (id !== basket.orderId) redirect.id = id;
// }
// } else {
// basket.loadIntoBasket(resultSet.fetchValue());
// redirect = { form: 'ecomerce/catalog' };
// }
// this.hash.setAll(redirect);
};
onMounted(async () => {
today.value = Date.vnNew();
today.value.setHours(0, 0, 0, 0);
const [defaultValues] = await getDefaultValues();
console.log('defaultValues:', defaultValues);
if (defaultValues) {
orderForm.value.method = defaultValues.deliveryMethod;
if (route.params.id) {
const [order] = await jApi.query(
`SELECT m.code deliveryMethod, o.sent, o.agencyModeFk, o.addressFk
FROM myOrder o
JOIN vn.deliveryMethod m ON m.id = o.deliveryMethodFk
WHERE o.id = #id`,
{ id: route.params.id }
);
if (order) {
orderForm.value.method = order.deliveryMethod;
orderForm.value.date = formatDate(order.sent, 'YYYY/MM/DD');
orderForm.value.agency = order.agencyModeFk;
orderForm.value.address = order.addressFk;
}
} else {
const [defaultValues] = await getDefaultValues();
if (defaultValues) {
orderForm.value.method = defaultValues.deliveryMethod;
}
}
getAddresses();
});
</script>
@ -298,6 +319,7 @@ onMounted(async () => {
:done="step.stepDone"
done-color="accent"
>
<!-- Method step -->
<div
v-if="step.name === 'method'"
class="column justify-center items-center"
@ -318,6 +340,7 @@ onMounted(async () => {
/>
</div>
</div>
<!-- Date step -->
<div
v-if="step.name === 'date'"
class="flex justify-center items-center"
@ -331,6 +354,7 @@ onMounted(async () => {
color="accent"
/>
</div>
<!-- Address step -->
<QList
v-if="step.name === 'address'"
class="vn-w-xs q-gutter-y-sm"
@ -355,6 +379,7 @@ onMounted(async () => {
</QItemSection>
</QItem>
</QList>
<!-- Agency step (AGENCY) -->
<div
v-if="step.name === 'agency'"
class="flex justify-center items-center"
@ -369,6 +394,21 @@ onMounted(async () => {
:options="agencies"
/>
</div>
<div
v-if="step.name === 'pickup'"
class="flex justify-center items-center"
>
<span class="text-h6 text-bold tex q-mb-md text-center">
{{ t('pickupWarehouse') }}
</span>
<VnSelect
v-model="orderForm.agency"
option-label="description"
option-value="id"
:options="warehouses"
/>
</div>
<!-- Confirm step -->
<div
v-if="step.name === 'confirm'"
class="flex column justify-center items-center"
@ -378,8 +418,10 @@ onMounted(async () => {
</span>
<div class="column vn-w-xs full-width">
<span>{{ confirmArrivalText }}</span>
<span>{{ confirmAddressText }}</span>
<span>{{ confirmAgencyText }}</span>
<span v-if="orderForm.method === 'AGENCY'">
{{ confirmAddressText }}
</span>
<span>{{ confirmPlaceText }}</span>
</div>
</div>
<QStepperNavigation class="flex justify-between">
@ -389,7 +431,7 @@ onMounted(async () => {
@click="onPreviousStep(stepIndex)"
label="Back"
class="q-ml-sm"
:class="{ invisible: currentStep === 1 }"
:class="{ invisible: currentStep === 'method' }"
/>
<QBtn
@click="onNextStep(stepIndex)"
@ -419,6 +461,12 @@ en-US:
pleaseSelectADate: Please select a date
pleaseSelectAnAddress: Please select an address
pleaseSelectAnAgency: Please select an agency
pickupWarehouse: What store you want to pickup your order?
noWarehousesAvailableForDate: There are no stores available for the selected date, check the date of order pickup and that selected address contains a correct province and zip code
noAgeciesAvailableForDate: There are no agencies available for the selected date and consignee, check the date of the order and that selected address contains a correct province and zip code
pleaseSelectAWarehouse: Please select a store
warehouse: Warehouse
pickup: Pickup
es-ES:
receiveOrPickOrder: ¿Quieres recibir o recoger el pedido?
receiveOrder: Recibir en mi tienda
@ -432,6 +480,12 @@ es-ES:
pleaseSelectADate: Por favor, selecciona una fecha
pleaseSelectAnAddress: Por favor, selecciona una dirección
pleaseSelectAnAgency: Por favor, selecciona una agencia
pickupWarehouse: ¿En qué almacén quieres recoger tu pedido?
noWarehousesAvailableForDate: No hay almacenes disponibles para la fecha seleccionada, comprueba la fecha de recogida del pedido y que consignatario seleccionado contiene una provincia y código postal correctos
noAgeciesAvailableForDate: No hay almacenes disponibles para la fecha seleccionada, comprueba la fecha de recogida del pedido y que consignatario seleccionado contiene una provincia y código postal correctos
pleaseSelectAWarehouse: Por favor elige un almacén
warehouse: Almacén
pickup: Recogida
ca-ES:
receiveOrPickOrder: Vols rebre o recollir la comanda?
receiveOrder: Rebre en mi tenda
@ -445,6 +499,12 @@ ca-ES:
pleaseSelectADate: Si us plau tria una data
pleaseSelectAnAddress: Si us plau tria una adreça
pleaseSelectAnAgency: Si us plau tria una agència
pickupWarehouse: En quin magatzem vols recollir la comanda?
noWarehousesAvailableForDate: No hi ha magatzems disponibles per a la data seleccionada, comprova la data de recollida de la comanda i que consignatari seleccionat conté una província i codi postal correctes
noAgeciesAvailableForDate: No hi ha agències disponibles per a la data i el consignatari seleccionats, comprova la data de la comanda i que consignatari seleccionat conté una província i codi postal correctes
pleaseSelectAWarehouse: Si us plau tria un magatzem
warehouse: Magatzem
pickup: Recollida
fr-FR:
receiveOrPickOrder: Voulez-vous recevoir ou récuperer l'ordre?
receiveOrder: Livraison à la boutique
@ -458,6 +518,12 @@ fr-FR:
pleaseSelectADate: Veuillez choisir une date
pleaseSelectAnAddress: Veuillez choisir une adresse
pleaseSelectAnAgency: Veuillez choisir une agence
pickupWarehouse: Dans quel magasin vuoulez-vous retirer votre commande?
noWarehousesAvailableForDate: Pas de magasins disponibles à la date sélectionnée, changer la date de retrait et vérifier quel destinataire a été sélectionné contient une province et un code postal correct
noAgeciesAvailableForDate: Aucune agence disponibles pour la date et le destinataire sélectionné, changer la date d'envoi de la commande et vérifier quel destinataire a été sélectionné contient une province et un code postal correct
pleaseSelectAWarehouse: Veuillez choisir un entrepôt
warehouse: Entrepôt
pickup: Retrait
pt-PT:
receiveOrPickOrder: Queres receber ou levantar a encomenda?
receiveOrder: Receber na minha loja
@ -470,4 +536,10 @@ pt-PT:
pleaseSelectADate: Por favor, escolha uma data
pleaseSelectAnAddress: Por favor, escolha um endereço
pleaseSelectAnAgency: Por favor, escolha uma agência
pickupWarehouse: Em qual armazém queres levantar a encomenda?
noWarehousesAvailableForDate: Não armazéns disponíveis para a data seleccionada, modifique a data para levantar a encomenda e verifique qual destinatário selecionou contém uma província e código postal corretos
noAgeciesAvailableForDate: Não agências disponíveis para a data e o consignatario escolhido, modifique a data de envío do pedido e verifique qual destinatário selecionou contém uma província e código postal corretos
pleaseSelectAWarehouse: Por favor, escolha um armazém
warehouse: Armazém
pickup: Recolhida
</i18n>

View File

@ -57,21 +57,62 @@ export const useAppStore = defineStore('hedera', {
},
async checkOrder(orderId) {
const resultSet = await jApi.execQuery(
'CALL myOrder_checkConfig(#id)',
{ id: orderId }
);
resultSet.fetchValue();
},
async check(checkoutContinue) {
if (this.basketOrderId) {
return await this.checkRedirect(checkoutContinue);
} else {
this.redirect();
return false;
}
},
async checkRedirect(checkoutContinue) {
try {
const resultSet = await jApi.execQuery(
'CALL myOrder_checkConfig(#id)',
{ id: orderId }
);
resultSet.fetchValue();
await this.checkOrder(this.basketOrderId);
return true;
} catch (err) {
console.error('Error checking order', err);
if (err.exception === 'Vn.Lib.UserError') {
switch (err.code) {
case 'orderConfirmed':
case 'orderNotOwnedByUser':
await this.redirect();
break;
default:
this.router.push({
name: 'checkout',
params: { id: this.basketOrderId },
query: { continue: checkoutContinue }
});
notify(err.message, 'negative');
}
return false;
} else throw err;
}
},
async redirect() {
const resultSet = await jApi.execQuery(
'SELECT COUNT(*) > 0 FROM myOrder'
);
if (resultSet.fetchValue()) {
this.router.push({ name: 'pendingOrders' });
notify('loadAnOrder', 'warning');
} else {
this.router.push({ name: 'checkout' });
}
},
loadIntoBasket(orderId) {
if (this.basketOrderId !== orderId) {
localStorage.setItem('hederaBasket', orderId);
this.basketOrderId = orderId;
localStorage.setItem('hederaBasket', orderId);
notify('orderLoadedIntoBasket', 'positive');
}
}