Confirm view

This commit is contained in:
William Buezas 2024-09-09 08:50:21 -03:00
parent c52fe7a870
commit 265ff5c47f
9 changed files with 379 additions and 63 deletions

View File

@ -214,7 +214,6 @@ en-US:
newPassword: New password
oldPassword: Old password
repeatPassword: Repeat password
modify: Modify
requirements: Requirements
passwordRequirements: Password requirements
charactersLong: '{length} characters long'
@ -229,7 +228,6 @@ es-ES:
newPassword: Nueva contraseña
oldPassword: Contraseña antigua
repeatPassword: Repetir contraseña
modify: Modificar
requirements: Requisitos
passwordRequirements: Requisitos de contraseña
charactersLong: '{length} caracteres de longitud'
@ -244,7 +242,6 @@ ca-ES:
newPassword: Nova contrasenya
oldPassword: Contrasenya antiga
repeatPassword: Repetir contrasenya
modify: Modificar
requirements: Requisits
passwordRequirements: Requisits de contrasenya
charactersLong: '{length} caràcters de longitud'
@ -259,7 +256,6 @@ fr-FR:
newPassword: Nouveau mot de passe
oldPassword: Ancien mot de passe
repeatPassword: Répéter le mot de passe
modify: Modifier
requirements: Exigences
passwordRequirements: Mot de passe exigences
charactersLong: '{length} caractères de longueur'
@ -274,7 +270,6 @@ pt-PT:
newPassword: Nova palavra-passe
oldPassword: Palavra-passe antiga
repeatPassword: Repetir palavra-passe
modify: Modificar
requirements: Requisitos
passwordRequirements: Requisitos de palavra-passe
charactersLong: '{length} caracteres de comprimento'

View File

@ -71,5 +71,7 @@ export default {
noData: 'Sense dades',
confirm: 'Confirmar',
delete: 'Esborrar',
reallyDelete: 'Estàs segur que vols esborrar la línia?'
reallyDelete: 'Estàs segur que vols esborrar la línia?',
emptyList: 'Llista buida',
modify: 'Modificar'
};

View File

@ -106,5 +106,7 @@ export default {
dataSaved: 'Data saved',
save: 'Save',
cancel: 'Cancel',
of: 'of'
of: 'of',
emptyList: 'Empty list',
modify: 'Modify'
};

View File

@ -122,5 +122,7 @@ export default {
dataSaved: 'Datos guardados',
save: 'Guardar',
cancel: 'Cancelar',
of: 'de'
of: 'de',
emptyList: 'Lista vacía',
modify: 'Modificar'
};

View File

@ -71,5 +71,7 @@ export default {
noData: 'Aucune donnée',
confirm: 'Confirmer',
delete: 'Effacer',
reallyDelete: 'Voulez-vous vraiment supprimer la ligne?'
reallyDelete: 'Voulez-vous vraiment supprimer la ligne?',
emptyList: 'Vider la liste',
modify: 'Modifier'
};

View File

@ -71,5 +71,7 @@ export default {
noData: 'Sem dados',
confirm: 'Confirme',
delete: 'Eliminar',
reallyDelete: 'Tens certeza que queres eliminar esta linha?'
reallyDelete: 'Tens certeza que queres eliminar esta linha?',
emptyList: 'Lista vazia',
modify: 'Modificar'
};

View File

@ -1,24 +1,79 @@
<script setup>
import { onBeforeMount, ref, inject, onMounted } from 'vue';
import { onBeforeMount, ref, inject, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAppStore } from 'stores/app';
import TicketDetails from 'src/pages/Ecomerce/TicketDetails.vue';
import { storeToRefs } from 'pinia';
import { useRoute } from 'vue-router';
import { useRoute, useRouter } from 'vue-router';
import useNotify from 'src/composables/useNotify.js';
import { currency } from 'src/lib/filters.js';
import { tpvStore } from 'stores/tpv';
import { useQuasar } from 'quasar';
const $q = useQuasar();
const jApi = inject('jApi');
const { notify } = useNotify();
const { t } = useI18n();
const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const tpv = tpvStore();
const { basketOrderId, isHeaderMounted } = storeToRefs(appStore);
const rows = ref([]);
const order = ref({});
const orderId = ref(null);
const transferAccounts = ref([]);
const paymentMethod = ref(null);
const loading = ref(false);
const paymentOptionsMap = ref({
balance: {
value: 'BALANCE',
label: t('useMyBalance'),
caption: t('favorableBalance'),
disable: true,
size: 'sm'
},
credit: {
value: 'CREDIT',
label: t('useMyCredit'),
caption: t('favorableCredit'),
disable: true,
size: 'sm'
},
card: {
value: 'CARD',
label: t('creditCard'),
caption: t('youWillBeRedirectedToPayment'),
disable: true,
size: 'sm'
},
transfer: {
value: 'TRANSFER',
label: t('bankTransfer'),
caption: t('makeTransfer'),
disable: true,
size: 'sm'
},
later: {
value: 'LATER',
label: t('payLater'),
disable: true,
size: 'sm'
}
});
const payAmount = ref(null);
const excessAmount = ref(null);
const totalAmount = ref(null);
const exceededCredit = ref(null);
const paymentOptionsArray = computed(() => {
return Object.values(paymentOptionsMap.value).filter(
option => !option.disable
);
});
const getOrder = async () => {
try {
@ -50,10 +105,15 @@ const getOrder = async () => {
const { sent, ...restOfData } = orderData;
const total = orderData.taxableBase + orderData.tax || 0;
const exceededCredit = orderData.debt + total;
const creditExceededCond = exceededCredit > 0;
const totalDebt = orderData.debt + total;
exceededCredit.value = totalDebt - orderData.credit;
const creditExceededCond = exceededCredit.value > 0;
payAmount.value = 'ALL';
excessAmount.value = exceededCredit;
totalAmount.value = totalDebt;
if (creditExceededCond) {
payAmount.value = 'EXCEEDED';
notify(t('creditExceeded'), 'warning');
}
@ -65,7 +125,34 @@ const getOrder = async () => {
};
order.value = formattedData;
console.log('orderData', order.value);
let methods = [];
if (totalDebt <= 0) {
methods = ['balance'];
paymentMethod.value = 'BALANCE';
} else {
methods = ['card', 'transfer', 'later'];
if (!creditExceededCond) {
methods.push('credit');
paymentMethod.value = 'CREDIT';
} else {
paymentMethod.value = 'CARD';
}
}
methods.forEach(
method => (paymentOptionsMap.value[method].disable = false)
);
} catch (error) {
console.error(error);
}
};
const getTransferAccounts = async () => {
try {
const data = await jApi.query(`SELECT name, iban FROM mainAccountBank`);
transferAccounts.value = data;
} catch (error) {
console.error(error);
}
@ -73,6 +160,44 @@ const getOrder = async () => {
const fetchData = async () => {
await getOrder();
await getTransferAccounts();
};
const modifyOrder = () => {
router.push({ name: 'basket', params: { id: orderId.value } });
};
const confirmOrder = async () => {
try {
loading.value = true;
await jApi.execQuery('CALL myOrder_confirm(#id)', {
id: orderId.value
});
appStore.unloadOrder();
$q.dialog({
message: t('orderConfirmed'),
persistent: true
}).onDismiss(() => {
onOrderConfirmed();
});
} finally {
loading.value = false;
}
};
const onOrderConfirmed = async () => {
let _payAmount;
if (paymentMethod.value === 'CARD') {
if (payAmount.value === 'EXCEEDED') {
_payAmount = excessAmount.value;
} else {
_payAmount = totalAmount.value;
}
await tpv.pay(_payAmount, order.value.companyFk);
} else {
router.push({ name: 'confirmedOrders' });
}
};
onBeforeMount(() => {
@ -119,7 +244,7 @@ onMounted(async () => {
can-delete-items
class="q-mb-md"
/>
<QCard style="padding: 32px">
<QCard class="column q-gutter-y-xs" style="padding: 32px">
<div class="row justify-between">
<span>{{ t('previousBalance') }}</span>
<span>{{ currency(order.debt) }}</span>
@ -132,14 +257,121 @@ onMounted(async () => {
<span>{{ t('orderVat') }}</span>
<span>{{ currency(order.tax) }}</span>
</div>
<div class="row justify-between">
<QSeparator inset />
<div class="row justify-between text-bold">
<span>{{ t('totalDebt') }}</span>
<span>{{ currency() }}</span>
<span>{{ currency(order.total) }}</span>
</div>
<div class="row justify-between">
<span>{{ t('credit') }}</span>
<span>{{ currency(order.credit) }}</span>
</div>
<div v-if="exceededCredit > 0" class="column">
<QSeparator inset />
<div class="row justify-between text-negative text-bold">
<span>{{ t('exceededCredit') }}</span>
<span>{{ currency(exceededCredit) }}</span>
</div>
<span class="text-subtitle1 text-bold q-mt-md">
{{ t('amountToPay') }}
</span>
<QRadio
v-model="payAmount"
val="ALL"
:label="`${t('totalDebt')}, ${currency(order.total)}`"
/>
<QRadio
v-model="payAmount"
val="EXCEEDED"
:label="`${t('exceededCredit')}, ${currency(exceededCredit)}`"
/>
</div>
<span class="text-subtitle1 text-bold q-mt-md">
{{ t('paymentMethod') }}
</span>
<QOptionGroup
v-model="paymentMethod"
:options="paymentOptionsArray"
class="radio-modifications"
>
<template #label="opt">
<div
class="column"
:class="{ 'q-mb-md': paymentMethod === opt.value }"
>
<span>{{ opt.label }}</span>
<span v-if="opt.caption && paymentMethod === opt.value">
{{ opt.caption }}
</span>
<div
v-if="
paymentMethod === 'TRANSFER' &&
opt.value === 'TRANSFER'
"
>
<div
v-if="!transferAccounts.length"
class="row items-center justify-center q-pa-md bg-red"
>
<QIcon class="q-mr-md" name="block" size="sm" />
<span>{{ t('emptyList') }}</span>
</div>
<QList>
<QItem
v-for="(account, index) in transferAccounts"
:key="index"
>
<QItemSection>
<div>{{ account.name }}</div>
<div>{{ account.iban }}</div>
</QItemSection>
</QItem>
</QList>
</div>
</div>
</template>
</QOptionGroup>
<div class="full-width flex justify-end q-gutter-x-sm">
<QBtn
:label="t('modify')"
rounded
no-caps
flat
@click="modifyOrder()"
/>
<QBtn
:label="t('confirm')"
rounded
unelevated
color="accent"
@click="confirmOrder()"
/>
</div>
</QCard>
</QPage>
</template>
<style lang="scss">
.radio-modifications {
.q-radio {
align-items: start;
width: 100% !important;
.q-radio__bg {
top: 0;
}
.q-radio__label {
width: 100%;
}
.q-radio__inner:before {
display: none;
}
}
}
</style>
<i18n lang="yaml">
en-US:
previousBalance: Previous balance
@ -147,28 +379,98 @@ en-US:
orderVat: Order VAT
totalDebt: Total debt
creditExceeded: You have exceeded your credit, in order to prepare your order please pay your debt.
credit: Credit
paymentMethod: Payment method
useMyBalance: Use my balance
favorableBalance: You do not need to perform any payment, you have a favorable balance.
useMyCredit: Use my credit
favorableCredit: You do not need to pay now, you have a favorable credit.
creditCard: Credit card
youWillBeRedirectedToPayment: By confirming the order you will be redirected to the payment platform.
bankTransfer: Bank Transfer
makeTransfer: Make a transfer to one of the following accounts and send the receipt to your salesperson.
payLater: Pay later
orderConfirmed: Your order has been confirmed successfully
exceededCredit: Exceeded credit
amountToPay: Amount to pay
es-ES:
previousBalance: Saldo anterior
orderTotal: Total pedido
orderVat: IVA pedido
totalDebt: Deuda total
totalDebt: Total deuda
creditExceeded: Has excedido tu crédito, por favor realiza el pago para que podamos preparar tu pedido.
credit: Crédito
paymentMethod: Método de pago
useMyBalance: Usar mi saldo
favorableBalance: No necesitas pagar nada, tienes un saldo favorable.
useMyCredit: Usar mi crédito
favorableCredit: No necesitas pagar nada, tienes crédito favorable.
creditCard: Tarjeta de crédito
youWillBeRedirectedToPayment: Al confirmar el pedido serás redirigido a la plataforma de pago.
bankTransfer: Transferencia bancaria
makeTransfer: Haz una transferecia a una de las siguientes cuentas y envía el justificante a tu comercial.
payLater: Pagar más tarde
orderConfirmed: Tu pedido ha sido realizado con éxito
exceededCredit: Crédito excedido
amountToPay: Valor a pagar
ca-ES:
previousBalance: Saldo anterior
orderTotal: Total comanda
orderVat: IVA comanda
totalDebt: Total deute
creditExceeded: Has excedit el teu crèdit, si us plau realitza el pagament perquè puguem preparar la teva comanda.
credit: Crèdit
paymentMethod: Mètode de pagament
useMyBalance: Utilitzar el meu saldo
favorableBalance: No necessites pagar res, tens un saldo favorable.
useMyCredit: Utilitzar el meu crèdit
favorableCredit: No necessites pagar res, tens crèdit favorable.
creditCard: Targeta de crèdit
youWillBeRedirectedToPayment: En confirmar la comanda seràs redirigit a la plataforma de pagament.
bankTransfer: Transferència bancària
makeTransfer: Fer una transferecia a una de les següents comptes i envia el justificant al teu comercial.
payLater: Pagar més tard
orderConfirmed: La teva comanda ha estat realitzat amb èxit
exceededCredit: Crèdit excedit
amountToPay: Quantitat a pagar
fr-FR:
previousBalance: Solde précédent
orderTotal: Total de la commande
orderVat: TVA de la commande
totalDebt: Total de la dette
creditExceeded: Vous avez dépassé votre crédit, s'il vous plaît effectuer le paiement afin que nous puissions préparer votre commande.
credit: Crédit
paymentMethod: Mode de paiement
useMyBalance: Utiliser mon équilibre
favorableBalance: Pas besoin de payer quoi que ce soit, vous avez un solde favorable.
useMyCredit: Utiliser mon crédit
favorableCredit: Pas besoin de payer quoi que ce soit, vous favorable crédit.
creditCard: Carte de crédit
youWillBeRedirectedToPayment: En confirmant la commande, vous serez redirigé vers la plateforme de paiement.
bankTransfer: Virement bancaire
makeTransfer: Faire Transféré à l'un des comptes suivants et envoyer le coupon à votre entreprise.
payLater: Payer plus tard
orderConfirmed: Votre commande a été complété avec succès
exceededCredit: Crédit dépassée
amountToPay: Montant à payer
pt-PT:
previousBalance: Saldo anterior
orderTotal: Total pedido
orderVat: IVA
totalDebt: Total dívida
creditExceeded: Ultrapassastes seu crédito, por favor, faça o pagamento para que possamos preparar sua encomenda.
credit: Crédito
paymentMethod: Método de pagamento
useMyBalance: Usar meu saldo
favorableBalance: Não necessidade de pagar, tens um crédito a seu favor.
useMyCredit: Usar meu crédito
favorableCredit: Não necessidade de pagar, tens um crédito à favor.
creditCard: Cartão de crédito
youWillBeRedirectedToPayment: Ao confirmar a encomenda, serás re-direcionado à plataforma de pagamento.
bankTransfer: Transferência bancária
makeTransfer: Faça a transferencia para uma das seguintes contas e envie o comprovativo para seu comercial.
payLater: Pagar mais tarde
orderConfirmed: Seu pedido foi realizado com êxito
exceededCredit: Crédito excedido
amountToPay: Valor a pagar
</i18n>

View File

@ -134,6 +134,11 @@ export const useAppStore = defineStore('hedera', {
localStorage.setItem('hederaBasket', orderId);
notify('orderLoadedIntoBasket', 'positive');
}
},
unloadOrder() {
localStorage.removeItem('hederaBasket');
this.basketOrderId = null;
}
},
getters: {

View File

@ -1,46 +1,50 @@
import { defineStore } from 'pinia'
import { jApi } from 'boot/axios'
import { defineStore } from 'pinia';
import { jApi } from 'boot/axios';
export const tpvStore = defineStore('tpv', {
actions: {
async check (route) {
const order = route.query.tpvOrder
const status = route.query.tpvStatus
if (!(order && status)) return null
async check(route) {
const order = route.query.tpvOrder;
const status = route.query.tpvStatus;
if (!(order && status)) return null;
await jApi.execQuery('CALL myTpvTransaction_end(#order, #status)', {
order,
status
})
});
if (status === 'ko') {
const retry = confirm('retryPayQuestion')
const retry = confirm('retryPayQuestion');
if (retry) {
this.retryPay(order)
this.retryPay(order);
}
}
return status
return status;
},
async pay (amount, company) {
await this.realPay(amount * 100, company)
async pay(amount, company) {
console.log('pay amount', amount);
console.log('pay company', company);
await this.realPay(amount * 100, company);
},
async retryPay (order) {
async retryPay(order) {
const payment = await jApi.getObject(
`SELECT t.amount, m.companyFk
FROM myTpvTransaction t
JOIN tpvMerchant m ON m.id = t.merchantFk
WHERE t.id = #order`,
{ order }
)
await this.realPay(payment.amount, payment.companyFk)
);
await this.realPay(payment.amount, payment.companyFk);
},
async realPay (amount, company) {
async realPay(amount, company) {
console.log('realPay amount', amount);
console.log('realPay company', company);
if (!isNumeric(amount) || amount <= 0) {
throw new Error('payAmountError')
throw new Error('payAmountError');
}
const json = await jApi.send('tpv/transaction', {
@ -48,46 +52,46 @@ export const tpvStore = defineStore('tpv', {
urlOk: this.makeUrl('ok'),
urlKo: this.makeUrl('ko'),
company
})
});
const postValues = json.postValues
const postValues = json.postValues;
const form = document.createElement('form')
form.method = 'POST'
form.action = json.url
document.body.appendChild(form)
const form = document.createElement('form');
form.method = 'POST';
form.action = json.url;
document.body.appendChild(form);
for (const field in postValues) {
const input = document.createElement('input')
input.type = 'hidden'
input.name = field
form.appendChild(input)
const input = document.createElement('input');
input.type = 'hidden';
input.name = field;
form.appendChild(input);
if (postValues[field]) {
input.value = postValues[field]
input.value = postValues[field];
}
}
form.submit()
form.submit();
},
makeUrl (status) {
let path = location.protocol + '//' + location.hostname
path += location.port ? ':' + location.port : ''
path += location.pathname
path += location.search ? location.search : ''
path += '#/ecomerce/orders'
makeUrl(status) {
let path = location.protocol + '//' + location.hostname;
path += location.port ? ':' + location.port : '';
path += location.pathname;
path += location.search ? location.search : '';
path += '#/ecomerce/orders';
path +=
'?' +
new URLSearchParams({
tpvStatus: status,
tpvOrder: '_transactionId_'
}).toString()
return path
'?' +
new URLSearchParams({
tpvStatus: status,
tpvOrder: '_transactionId_'
}).toString();
return path;
}
}
})
});
function isNumeric (n) {
return !isNaN(parseFloat(n)) && isFinite(n)
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}