Resolve conflicts
gitea/hedera-web/pipeline/pr-4922-vueMigration This commit looks good Details

This commit is contained in:
William Buezas 2024-09-13 21:48:49 -03:00
commit 21b6e96148
14 changed files with 580 additions and 106 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

@ -74,7 +74,7 @@ export default {
Shelves: 'Prestatgeries',
Account: 'Compte',
Addresses: 'Adreces',
Confirm: 'Confirmar',
OrderSummary: 'Resum de la comanda',
Checkout: `Configurar l'encarrec`,
'Address details': 'Configuració',
'Admin news details': `Afegir o editar notícia`,
@ -101,5 +101,6 @@ export default {
loginMail: "{'info'}{'@'}{'verdnatura.es'}",
remindMe: "Recorda'm",
user: 'Usuari',
password: 'Contrasenya'
password: 'Contrasenya',
modify: 'Modificar'
};

View File

@ -86,7 +86,7 @@ export default {
Shelves: 'Shelves',
Account: 'Account',
Addresses: 'Addresses',
Confirm: 'Confirm',
OrderSummary: 'Order summary',
Checkout: 'Configure order',
'Address details': 'Configuration',
'Admin news details': 'Add or edit new',
@ -133,5 +133,6 @@ export default {
loginPhone: '+34 963 242 100',
loginMail: "{'info'}{'@'}{'verdnatura.es'}",
remindMe: 'Remember me',
password: 'Password'
password: 'Password',
modify: 'Modify'
};

View File

@ -83,7 +83,7 @@ export default {
Shelves: 'Estanterías',
Account: 'Cuenta',
Addresses: 'Direcciones',
Confirm: 'Confirmar',
OrderSummary: 'Resumen del pedido',
Checkout: 'Configurar pedido',
'Address details': 'Configuración',
'Admin news details': 'Añadir o editar noticia',
@ -132,5 +132,6 @@ export default {
dataSaved: 'Datos guardados',
save: 'Guardar',
cancel: 'Cancelar',
of: 'de'
of: 'de',
modify: 'Modificar'
};

View File

@ -74,7 +74,7 @@ export default {
Shelves: 'Étagères',
Account: 'Compte',
Addresses: 'Adresses',
Confirm: 'Confirmer',
OrderSummary: 'Résumé de la commande',
Checkout: 'Configurer la commande',
'Address details': 'Configuration',
'Admin news details': 'Ajouter ou éditer une nouvelle',
@ -101,5 +101,6 @@ export default {
loginMail: "{'info'}{'@'}{'verdnatura.es'}",
remindMe: `Rappelle-moi`,
user: 'Utilisateur',
password: 'Mot de passe'
password: 'Mot de passe',
modify: 'Modifier'
};

View File

@ -73,7 +73,7 @@ export default {
Shelves: 'Estantes',
Account: 'Conta',
Addresses: 'Moradas',
Confirm: 'Confirme',
OrderSummary: 'Resumo da encomenda',
Checkout: 'Configurar encomenda',
'Address details': 'Configuração',
'Admin news details': 'Adicionar ou editar notícia',
@ -99,5 +99,6 @@ export default {
loginMail: "{'info'}{'@'}{'verdnatura.es'}",
remindMe: 'Lembrar-me',
user: 'Utilizador',
password: 'Senha'
password: 'Senha',
modify: 'Modificar'
};

View File

@ -1,5 +1,5 @@
<script setup>
import { onBeforeMount, ref, inject, onMounted } from 'vue';
import { onBeforeMount, ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAppStore } from 'stores/app';
@ -17,14 +17,12 @@ const rows = ref([]);
const ticket = ref({});
const orderId = ref(null);
onBeforeMount(() => {
appStore.check();
});
onMounted(async () => {
onBeforeMount(async () => {
await appStore.check();
orderId.value = route.params.id || basketOrderId.value;
if (orderId.value) await fetchData();
});
const getOrder = async () => {
try {
const [data] = await jApi.query(
@ -126,7 +124,6 @@ const fetchData = async () => {
<TicketDetails
:rows="rows"
:ticket="ticket"
is-basket
:show-tax="false"
can-delete-items
@on-row-deleted="fetchData"

View File

@ -1 +1,454 @@
<template>Confirm view</template>
<script setup>
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, 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 } = 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 {
const { results } = await jApi.execQuery(
`CALL myOrder_getTax(#id);
SELECT o.id, o.sent, o.notes, o.companyFk,
ag.description agency, v.code method,
ad.nickname, ad.postalCode, ad.city, ad.street,
t.*, c.credit, myClient_getDebt(NULL) debt
FROM myOrder o
JOIN vn.agencyMode ag ON ag.id = o.agencyModeFk
LEFT JOIN myAddress ad ON ad.id = o.addressFk
JOIN vn.deliveryMethod v ON v.id = o.deliveryMethodFk
JOIN myClient c
JOIN (
SELECT
IFNULL(SUM(taxableBase), 0) taxableBase,
IFNULL(SUM(tax), 0) tax
FROM tmp.orderAmount
) t
WHERE o.id = #id;
DROP TEMPORARY TABLE
tmp.orderAmount,
tmp.orderTax;`,
{ id: orderId.value }
);
const orderData = results[1]?.data[0];
const { sent, ...restOfData } = orderData;
const total = orderData.taxableBase + orderData.tax || 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');
}
const formattedData = {
landed: new Date(sent),
total,
debt: orderData.debt || 0,
...restOfData
};
order.value = formattedData;
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);
}
};
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(() => {
appStore.check();
});
onMounted(async () => {
orderId.value = route.params.id || basketOrderId.value;
await fetchData();
});
</script>
<template>
<QPage class="vn-w-sm">
<TicketDetails
:rows="rows"
:ticket="order"
:show-tax="false"
:show-items="false"
:show-total="false"
can-delete-items
class="q-mb-md"
/>
<QCard class="column q-gutter-y-xs" style="padding: 32px">
<div class="row justify-between">
<span>{{ t('previousBalance') }}</span>
<span>{{ currency(order.debt) }}</span>
</div>
<div class="row justify-between">
<span>{{ t('orderTotal') }}</span>
<span>{{ currency(order.taxableBase) }}</span>
</div>
<div class="row justify-between">
<span>{{ t('orderVat') }}</span>
<span>{{ currency(order.tax) }}</span>
</div>
<QSeparator inset />
<div class="row justify-between text-bold">
<span>{{ t('totalDebt') }}</span>
<span>{{ currency(totalAmount) }}</span>
</div>
<div v-if="order.credit > 0" class="row justify-between">
<span>{{ t('credit') }}</span>
<span>{{ currency(order.credit) }}</span>
</div>
<div v-if="exceededCredit > 0 && order.credit > 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(totalAmount)}`"
/>
<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
outline
@click="modifyOrder()"
/>
<QBtn
:label="t('confirm')"
rounded
unelevated
no-caps
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
orderTotal: Order total
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: 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: Cantidad 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

@ -90,7 +90,11 @@ onMounted(async () => {
<VnTable
:columns="columns"
:rows="invoices"
:hide-header="!invoices?.length"
hide-header
:hide-bottom="!!invoices.length"
:pagination="{ rowsPerPage: 0 }"
hide-pagination
class="invoices-table"
>
<template #body-cell-hasPdf="{ row }">
<QTd
@ -127,6 +131,14 @@ onMounted(async () => {
</div>
</template>
<style lang="scss">
.invoices-table {
.scroll {
overflow: hidden !important;
}
}
</style>
<i18n lang="yaml">
en-US:
noInvoicesFound: No invoices found

View File

@ -16,10 +16,18 @@ defineProps({
type: Array,
default: () => []
},
showTotal: {
type: Boolean,
default: true
},
showTax: {
type: Boolean,
default: true
},
showItems: {
type: Boolean,
default: true
},
canDeleteItems: {
type: Boolean,
default: false
@ -77,7 +85,7 @@ const deleteRow = id => {
{{ ticket.agency }}
</div>
</QCardSection>
<QCardSection class="no-padding q-mb-md q-gutter-y-xs">
<QCardSection class="no-padding q-gutter-y-xs">
<div class="text-subtitle1 text-bold">
{{ t('deliveryAddress') }}
</div>
@ -91,7 +99,8 @@ const deleteRow = id => {
</div>
</QCardSection>
<QCardSection
class="no-padding q-mb-md text-subtitle1 text-bold column"
v-if="showTotal"
class="no-padding q-my-md text-subtitle1 text-bold column"
>
<span class="text-right">
{{ t('total') }} {{ currency(ticket.taxBase) }}
@ -100,16 +109,8 @@ const deleteRow = id => {
{{ t('totalTax') }} {{ currency(ticket.total) }}
</span>
</QCardSection>
<QSeparator inset />
<div
v-if="!rows.length"
class="row items-center justify-center q-pa-md"
style="margin-top: 32px"
>
<QIcon class="q-mr-md" name="block" size="sm" />
<span>{{ t('emptyList') }}</span>
</div>
<QList v-else v-for="(row, index) in rows" :key="index">
<QSeparator v-if="showItems" inset />
<QList v-for="(row, index) in rows" :key="index">
<QItem v-if="row">
<QItemSection v-if="canDeleteItems" avatar>
<QBtn
@ -166,6 +167,14 @@ const deleteRow = id => {
</QItemSection>
</QItem>
</QList>
<div
v-if="!rows.length && showItems"
class="row items-center justify-center q-pa-md"
style="margin-top: 32px"
>
<QIcon class="q-mr-md" name="block" size="sm" />
<span>{{ t('emptyList') }}</span>
</div>
</QCard>
</template>

View File

@ -15,6 +15,7 @@ const route = useRoute();
const userStore = useUserStore();
const appStore = useAppStore();
const { isHeaderMounted } = storeToRefs(appStore);
const { user, token } = storeToRefs(userStore);
const ticket = ref({});
const rows = ref([]);
@ -39,8 +40,8 @@ onMounted(async () => {
const onPrintClick = () => {
const params = new URLSearchParams({
access_token: userStore.token,
recipientId: userStore.id,
access_token: token.value,
recipientId: user.value.id,
type: 'deliveryNote'
});
window.open(
@ -60,10 +61,7 @@ const onPrintClick = () => {
/>
</Teleport>
<QPage>
<TicketDetails
:rows="rows"
:ticket="ticket"
/>
<TicketDetails :rows="rows" :ticket="ticket" />
</QPage>
</template>

View File

@ -89,7 +89,7 @@ const routes = [
name: 'confirm',
path: '/ecomerce/confirm/:id?',
meta: {
title: 'Confirm'
title: 'OrderSummary'
},
component: () => import('pages/Ecomerce/ConfirmView.vue')
},

View File

@ -5,6 +5,7 @@ import { i18n } from 'src/boot/i18n';
import { useQuasar } from 'quasar';
const { notify } = useNotify();
const storageOrderName = 'hederaBasket';
export const useAppStore = defineStore('hedera', {
state: () => ({
@ -72,7 +73,7 @@ export const useAppStore = defineStore('hedera', {
},
getBasketOrderId() {
this.basketOrderId = localStorage.getItem('hederaBasket');
this.basketOrderId = localStorage.getItem(storageOrderName);
},
async checkOrder(orderId) {
@ -87,7 +88,7 @@ export const useAppStore = defineStore('hedera', {
if (this.basketOrderId) {
return await this.checkRedirect(checkoutContinue);
} else {
this.redirect();
await this.redirect();
return false;
}
},
@ -97,22 +98,21 @@ export const useAppStore = defineStore('hedera', {
await this.checkOrder(this.basketOrderId);
return true;
} catch (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;
switch (err.code) {
case 'orderConfirmed':
case 'orderNotOwnedByUser':
this.unloadOrder();
await this.redirect();
break;
default:
this.router.push({
name: 'checkout',
params: { id: this.basketOrderId },
query: { continue: checkoutContinue }
});
notify(err.message, 'negative');
}
return false;
}
},
@ -131,9 +131,14 @@ export const useAppStore = defineStore('hedera', {
loadIntoBasket(orderId) {
if (this.basketOrderId !== orderId) {
this.basketOrderId = orderId;
localStorage.setItem('hederaBasket', orderId);
localStorage.setItem(storageOrderName, orderId);
notify('orderLoadedIntoBasket', 'positive');
}
},
unloadOrder() {
localStorage.removeItem(storageOrderName);
this.basketOrderId = null;
}
},
getters: {

View File

@ -1,46 +1,46 @@
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) {
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) {
if (!isNumeric(amount) || amount <= 0) {
throw new Error('payAmountError')
throw new Error('payAmountError');
}
const json = await jApi.send('tpv/transaction', {
@ -48,46 +48,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);
}