WIP: #7134 SupplierBalance #905

Draft
jsegarra wants to merge 10 commits from 7134-supplierBalance into dev
9 changed files with 906 additions and 2 deletions

View File

@ -0,0 +1,12 @@
export default function (initialFooter, data) {
const footer = data.reduce(
(acc, row) => {
Object.entries(initialFooter).forEach(([key, initialValue]) => {
acc[key] += row?.[key] !== undefined ? row[key] : initialValue;
});
return acc;
},
{ ...initialFooter }
);
return footer;
}

View File

@ -0,0 +1,22 @@
import axios from 'axios';
export async function getClientRisk(_filter) {
const filter = {
..._filter,
include: { relation: 'company', scope: { fields: ['code'] } },
};
return await axios(`ClientRisks`, {
params: { filter: JSON.stringify(filter) },
});
}
export async function getSupplierRisk(_filter) {
const filter = {
..._filter,
include: { relation: 'company', scope: { fields: ['code'] } },
};
return await axios(`ClientRisks`, {
params: { filter: JSON.stringify(filter) },
});
}

View File

@ -5,7 +5,7 @@ import { useRoute } from 'vue-router';
import { useAcl } from 'src/composables/useAcl';
import axios from 'axios';
import { useQuasar } from 'quasar';
import { getClientRisk } from '../composables/getClientRisk';
import { getClientRisk } from 'src/composables/getRisk';
import { toCurrency, toDate, toDateHourMin } from 'src/filters';
import { useState } from 'composables/useState';

View File

@ -3,7 +3,7 @@ import { onBeforeMount, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { getClientRisk } from '../composables/getClientRisk';
import { getClientRisk } from 'src/composables/getRisk';
import { useDialogPluginComponent } from 'quasar';
import { usePrintService } from 'composables/usePrintService';

View File

@ -0,0 +1,348 @@
<script setup>
import { computed, onBeforeMount, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { useAcl } from 'src/composables/useAcl';
import axios from 'axios';
import { useQuasar } from 'quasar';
import { getSupplierRisk } from 'src/composables/getRisk';
import tableFooter from 'src/components/VnTable/filters/tableFooter';
import { dashIfEmpty, toCurrency, toDate, toDateHourMin } from 'src/filters';
import { useState } from 'composables/useState';
import { useStateStore } from 'stores/useStateStore';
import { usePrintService } from 'composables/usePrintService';
import { useVnConfirm } from 'composables/useVnConfirm';
import VnTable from 'components/VnTable/VnTable.vue';
import VnInput from 'components/common/VnInput.vue';
import VnSubToolbar from 'components/ui/VnSubToolbar.vue';
import VnFilter from 'components/VnTable/VnFilter.vue';
import SupplierNewPayment from 'src/pages/Supplier/Card/SupplierNewPayment.vue';
import InvoiceOutDescriptorProxy from 'src/pages/InvoiceOut/Card/InvoiceOutDescriptorProxy.vue';
import SupplierBalanceFilter from './SupplierBalanceFilter.vue';
const { openConfirmationModal } = useVnConfirm();
const { sendEmail, openReport } = usePrintService();
const { t } = useI18n();
const { hasAny } = useAcl();
const quasar = useQuasar();
const route = useRoute();
const state = useState();
const stateStore = useStateStore();
const user = state.getUser();
const supplierRisk = ref([]);
const tableRef = ref();
const companyId = ref();
const companyUser = ref(user.value.companyFk);
const bankUser = ref(user.value.localBankFk);
const balances = ref([]);
const vnFilterRef = ref({});
const filter = computed(() => {
return {
supplierId: route.params.id,
companyId: companyId.value ?? companyUser.value,
};
});
const companyFilterColumn = {
align: 'left',
name: 'companyId',
label: t('Company'),
component: 'select',
attrs: {
url: 'Companies',
optionLabel: 'code',
optionValue: 'id',
sortBy: 'code',
},
columnFilter: {
event: {
remove: () => (companyId.value = null),
'update:modelValue': (newCompanyFk) => {
if (!newCompanyFk) return;
vnFilterRef.value.addFilter(newCompanyFk);
companyUser.value = newCompanyFk;
},
blur: () => !companyId.value && (companyId.value = companyUser.value),
},
},
visible: false,
};
const columns = computed(() => [
// {
// align: 'left',
// name: 'payed',
// label: t('Date'),
// format: ({ payed }) => toDate(payed),
// cardVisible: true,
// },
{
align: 'left',
name: 'dated',
label: t('Creation date'),
format: ({ dated }) => toDateHourMin(dated),
cardVisible: true,
},
// {
// align: 'left',
// label: t('Employee'),
// columnField: {
// component: 'userLink',
// attrs: ({ row }) => {
// return {
// workerId: row.workerFk,
// name: row.userName,
// };
// },
// },
// cardVisible: true,
// },
{
align: 'left',
name: 'sref',
label: t('Reference'),
isTitle: true,
class: 'extend',
format: ({ sref }) => dashIfEmpty(sref),
},
{
align: 'left',
name: 'bankFk',
label: t('Bank'),
cardVisible: true,
},
{
align: 'left',
name: 'invoiceEuros',
label: t('Debit'),
format: ({ invoiceEuros }) => invoiceEuros && toCurrency(invoiceEuros),
isId: true,
},
{
align: 'left',
name: 'paymentEuros',
label: t('Havings'),
format: ({ paymentEuros }) => paymentEuros && toCurrency(paymentEuros),
cardVisible: true,
},
{
align: 'left',
name: 'euroBalance',
label: t('Balance'),
format: ({ euroBalance }) => toCurrency(euroBalance),
cardVisible: true,
},
{
align: 'left',
name: 'isConciliate',
label: t('Conciliated'),
cardVisible: true,
},
{
align: 'left',
name: 'tableActions',
actions: [
// {
// title: t('globals.downloadPdf'),
// icon: 'cloud_download',
// show: (row) => row.isInvoice,
// action: (row) => showBalancePdf(row),
// },
// {
// title: t('Send compensation'),
// icon: 'outgoing_mail',
// show: (row) => !!row.isCompensation,
// action: ({ id }) =>
// openConfirmationModal(
// t('Send compensation'),
// t('Do you want to report compensation to the supplier by mail?'),
// () => sendEmail(`Receipts/${id}/balance-compensation-email`)
// ),
// },
],
},
]);
onBeforeMount(() => {
stateStore.rightDrawer = true;
companyId.value = companyUser.value;
});
async function getSupplierRisks() {
const filter = {
where: { supplierFk: route.params.id, companyFk: companyUser.value },
};
const { data } = await getSupplierRisk(filter);
supplierRisk.value = data;
return supplierRisk.value;
}
async function getCurrentBalance() {
const currentBalance = (await getSupplierRisks()).find((balance) => {
return balance.companyFk === companyId.value;
});
return currentBalance && currentBalance.amount;
}
function setFooter(data) {
const initialFooter = {
invoiceEuros: 0,
paymentEuros: 0,
euroBalance: 0,
};
tableRef.value.footer = tableFooter(initialFooter, data);
}
async function onFetch(data) {
return;
// balances.value = [];
// for (const [index, balance] of data.entries()) {
// if (index === 0) {
// balance.balance = await getCurrentBalance();
// continue;
// }
// const previousBalance = data[index - 1];
// balance.balance =
// previousBalance?.balance - (previousBalance?.debit - previousBalance?.credit);
// }
// balances.value = data;
}
const showNewPaymentDialog = () => {
quasar.dialog({
component: SupplierNewPayment,
componentProps: {
companyId: companyId.value,
bankId: bankUser.value,
totalCredit: supplierRisk.value[0]?.amount,
extraFields: ['currencyFk', 'orderBy'],
promise: () => tableRef.value.reload(),
},
});
};
const showBalancePdf = ({ id }) => {
openReport(`InvoiceOuts/${id}/download`, {}, '_blank');
};
</script>
<template>
<VnSubToolbar class="q-mb-md">
<template #st-data>
<div class="column justify-center q-px-md q-py-sm">
<span class="text-bold">{{ t('Total by company') }}</span>
<div class="row justify-center" v-if="supplierRisk?.length">
{{ supplierRisk[0].company.code }}:
{{ toCurrency(supplierRisk[0].amount) }}
</div>
</div>
</template>
<template #st-actions>
<div>
<VnFilter
ref="vnFilterRef"
v-model="companyId"
data-key="CustomerBalance"
:column="companyFilterColumn"
search-url="balance"
/>
</div>
</template>
</VnSubToolbar>
<QDrawer side="right" :width="265" v-model="stateStore.rightDrawer">
<SupplierBalanceFilter data-key="SupplierBalance" />
</QDrawer>
<VnTable
ref="tableRef"
data-key="SupplierBalance"
url="Suppliers/receipts"
search-url="balance"
:user-params="filter"
:columns="columns"
:right-search="false"
:is-editable="false"
:column-search="false"
@on-fetch="onFetch"
:disable-option="{ card: true }"
auto-load
>
<template #column-balance="{ rowIndex }">
{{ toCurrency(balances[rowIndex]?.balance) }}
</template>
<template #column-description="{ row }">
<div class="link" v-if="row.isInvoice">
{{ t('bill', { ref: row.description }) }}
<InvoiceOutDescriptorProxy :id="row.description" />
</div>
<span v-else class="q-pa-xs dotted rounded-borders" :title="row.description">
{{ row.description }}
</span>
<QPopupEdit
v-model="row.description"
v-slot="scope"
@save="
(value) =>
value != row.description &&
axios.patch(`Receipts/${row.id}`, { description: value })
"
auto-save
>
<VnInput
v-model="scope.value"
:disable="
!hasAny([{ model: 'Receipt', props: '*', accessType: 'WRITE' }])
"
@keypress.enter="scope.set"
autofocus
/>
</QPopupEdit>
</template>
</VnTable>
<QPageSticky :offset="[18, 18]" style="z-index: 2">
<QBtn
@click.stop="showNewPaymentDialog()"
color="primary"
fab
icon="add"
shortcut="+"
/>
<QTooltip>
{{ t('New payment') }}
</QTooltip>
</QPageSticky>
</template>
<i18n>
en:
bill: 'N/INV {ref}'
es:
Company: Empresa
Total by company: Total por empresa
New payment: Añadir pago
supplierNewpayment: Añadir pago de proveedor
clientNewpayment: Añadir pago de cliente
Date: Fecha
Creation date: Fecha de creación
Employee: Empleado
Reference: Referencia
bill: 'N/FRA {ref}'
Bank: Caja
Debit: Debe
Havings: Haber
Balance: Balance
Conciliated: Conciliado
Send compensation: Enviar compensación
Do you want to report compensation to the supplier by mail?: ¿Desea informar de la compensación al cliente por correo?
</i18n>
<style lang="scss" scoped>
.dotted {
border: 1px dotted var(--vn-header-color);
}
.dotted:hover {
border: 1px dotted $primary;
}
</style>

View File

@ -0,0 +1,124 @@
<script setup>
import { useI18n } from 'vue-i18n';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
const { t } = useI18n();
defineProps({
dataKey: {
type: String,
required: true,
},
});
</script>
<template>
<VnFilterPanel :data-key="dataKey" :search-button="true" :redirect="false">
<template #tags="{ tag, formatFn }">
<div class="q-gutter-x-xs">
<strong>{{ t(`params.${tag.label}`) }}: </strong>
<span>{{ formatFn(tag.value) }}</span>
</div>
</template>
<template #body="{ params, searchFn }">
{{ params }}
<QItem>
<QItemSection>
<VnInputDate
:label="t('params.from')"
v-model="params.from"
@update:model-value="searchFn()"
is-outlined
/>
</QItemSection>
</QItem>
<QItem>
<QItemSection>
<VnSelect
:label="t('params.bank')"
v-model="params.bankFk"
url="Accountings"
option-label="bank"
:include="{ relation: 'accountingType' }"
sort-by="id"
:limit="0"
dense
outlined
rounded
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt.id }}:&ensp;{{ scope.opt.bank }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</QItemSection>
</QItem>
<QItem>
<QItemSection>
<VnSelect
:label="t('params.currencyFk')"
url="Currencies"
:filter="{ fields: ['id', 'name'] }"
order="code"
v-model="params.currencyFk"
option-value="id"
option-label="name"
hide-selected
dense
outlined
rounded
/>
</QItemSection>
</QItem>
<QItem>
<QItemSection>
<QCheckbox
v-model="params.isConciliated"
:label="t('params.isConciliated')"
@update:model-value="searchFn()"
toggle-indeterminate
/></QItemSection>
</QItem>
<QItem>
<QItemSection>
<VnInput
v-model="params.itemId"
:label="t('params.itemId')"
is-outlined
/>
</QItemSection>
</QItem>
</template>
</VnFilterPanel>
</template>
<i18n>
en:
params:
search: General search
itemId: Item id
buyerId: Buyer
typeId: Type
categoryId: Category
from: From
to: To
es:
params:
isConciliated: Conciliado
currencyFk: Moneda
New payment: Añadir pago
Date: Fecha
Company: Empresa
bank: Caja
Amount: Importe
Reference: Referencia
Cash: Efectivo
</i18n>

View File

@ -0,0 +1,375 @@
<script setup>
import { onBeforeMount, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { getSupplierRisk } from 'src/composables/getRisk';
import { useDialogPluginComponent } from 'quasar';
import { usePrintService } from 'composables/usePrintService';
import useNotify from 'src/composables/useNotify.js';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputNumber from 'components/common/VnInputNumber.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnAccountNumber from 'src/components/common/VnAccountNumber.vue';
const { t } = useI18n();
const route = useRoute();
const { notify } = useNotify();
const { sendEmail, openReport } = usePrintService();
const { dialogRef } = useDialogPluginComponent();
const $props = defineProps({
companyId: {
type: Number,
required: true,
},
bankId: {
type: Number,
required: true,
},
totalCredit: {
type: Number,
required: true,
},
promise: {
type: Function,
default: null,
},
extraFields: {
type: [String],
default: '',
},
});
const currenciesOptions = ref([]);
const closeButton = ref(null);
const urlCreate = ref([]);
const companyOptions = ref([]);
const bankOptions = ref([]);
const recordFindOne = ref([]);
const viewReceipt = ref();
const shouldSendEmail = ref(false);
const maxAmount = ref();
const accountingType = ref({});
const isCash = ref(false);
const formModelRef = ref(false);
const filterBanks = {
fields: ['id', 'bank', 'accountingTypeFk'],
include: { relation: 'accountingType' },
order: 'id',
limit: 30,
};
const filterRecordFindOne = {
fields: [],
where: {
id: route.params.id,
},
};
const initialData = reactive({
amountPaid: $props.totalCredit,
supplierFk: route.params.id,
companyFk: $props.companyId,
bankFk: $props.bankId,
email: recordFindOne.value.email,
currencyFk: 1,
});
onBeforeMount(() => {
urlCreate.value = `Suppliers/${route.params.id}/createReceipt`;
});
function setPaymentType(accounting) {
if (!accounting) return;
accountingType.value = accounting.accountingType;
initialData.description = [];
initialData.payed = Date.vnNew();
isCash.value = accountingType.value.code == 'cash';
viewReceipt.value = isCash.value;
if (accountingType.value.daysInFuture)
initialData.payed.setDate(
initialData.payed.getDate() + accountingType.value.daysInFuture
);
maxAmount.value = accountingType.value && accountingType.value.maxAmount;
if (accountingType.value.code == 'compensation')
return (initialData.description = '');
if (accountingType.value.receiptDescription)
initialData.description.push(accountingType.value.receiptDescription);
if (initialData.description) initialData.description.push(initialData.description);
initialData.description = initialData.description.join(', ');
}
const calculateFromAmount = (event) => {
initialData.amountToReturn =
parseFloat(initialData.deliveredAmount) + parseFloat(event) * -1;
};
const calculateFromDeliveredAmount = (event) => {
initialData.amountToReturn = parseFloat(event) - initialData.amountPaid;
};
function onBeforeSave(data) {
const exceededAmount = data.amountPaid > maxAmount.value;
if (isCash.value && exceededAmount)
return notify(t('Amount exceeded', { maxAmount: maxAmount.value }), 'negative');
if (isCash.value && shouldSendEmail.value && !data.email)
return notify(t(`There is no assigned email for this supplier`), 'negative');
data.bankFk = data.bankFk.id;
return data;
}
async function onDataSaved(formData, { id }) {
try {
if (shouldSendEmail.value && isCash.value)
await sendEmail(`Receipts/${id}/receipt-email`, {
recipient: formData.email,
});
if (viewReceipt.value) openReport(`Receipts/${id}/receipt-pdf`);
} finally {
if ($props.promise) $props.promise();
if (closeButton.value) closeButton.value.click();
}
}
async function accountShortToStandard({ target: { value } }) {
if (!value) return (initialData.description = '');
initialData.compensationAccount = value.replace('.', '0'.repeat(11 - value.length));
const params = { bankAccount: initialData.compensationAccount };
const { data } = await axios(`Clients/getClientOrSupplierReference`, { params });
if (!data.clientId) {
initialData.description = t('Supplier Compensation Reference', {
supplierId: data.supplierId,
supplierName: data.supplierName,
});
return;
}
initialData.description = t('Client Compensation Reference', {
clientId: data.clientId,
clientName: data.clientName,
});
}
async function getAmountPaid() {
const filter = {
where: {
supplierFk: route.params.id,
companyFk: initialData.companyFk,
},
};
const { data } = await getSupplierRisk(filter);
initialData.amountPaid = (data?.length && data[0].amount) || undefined;
}
</script>
<template>
<QDialog ref="dialogRef" persistent>
<FetchData
@on-fetch="(data) => (companyOptions = data)"
auto-load
url="Companies"
/>
<FetchData
:filter="filterRecordFindOne"
url="Suppliers/findOne"
auto-load
@on-fetch="({ email }) => (initialData.email = email)"
/>
<FetchData
url="Currencies"
:filter="{ fields: ['id', 'name'] }"
order="code"
@on-fetch="(data) => (currenciesOptions = data)"
auto-load
/>
<FormModel
ref="formModelRef"
:form-initial-data="initialData"
:observe-form-changes="false"
:url-create="urlCreate"
:mapper="onBeforeSave"
@on-data-saved="onDataSaved"
>
<template #form="{ data, validate }">
<span ref="closeButton" class="row justify-end close-icon" v-close-popup>
<QIcon name="close" size="sm" />
</span>
{{ data }}
<h5 class="q-mt-none">{{ t('New payment') }}</h5>
<VnRow>
<VnInputDate
:label="t('Date')"
:required="true"
v-model="data.payed"
/>
<VnSelect
:label="t('Company')"
:options="companyOptions"
:required="true"
:rules="validate('entry.companyFk')"
hide-selected
option-label="code"
option-value="id"
v-model="data.companyFk"
@update:model-value="getAmountPaid()"
/>
</VnRow>
<VnRow>
<VnSelect
:label="t('Bank')"
v-model="data.bankFk"
url="Accountings"
option-label="bank"
:include="{ relation: 'accountingType' }"
sort-by="id"
:limit="0"
@update:model-value="
(value, options) => setPaymentType(value, options)
"
:emit-value="false"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt.id }}:&ensp;{{ scope.opt.bank }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
<VnInputNumber
:label="t('Amount')"
:required="true"
@update:model-value="calculateFromAmount($event)"
clearable
v-model.number="data.amountPaid"
/>
</VnRow>
<div v-if="data.bankFk?.accountingType?.code == 'compensation'">
<div class="text-h6">
{{ t('Compensation') }}
</div>
<VnRow>
<VnAccountNumber
:label="t('Compensation account')"
clearable
required
v-model="data.compensationAccount"
@blur="accountShortToStandard"
/>
</VnRow>
</div>
<VnInput
:label="t('Reference')"
:required="true"
clearable
v-model="data.description"
/>
<div v-if="data.bankFk?.accountingType?.code == 'cash'">
<div class="text-h6">{{ t('Cash') }}</div>
<VnRow>
<VnInputNumber
:label="t('Delivered amount')"
@update:model-value="calculateFromDeliveredAmount($event)"
clearable
v-model="data.deliveredAmount"
/>
<VnInputNumber
:label="t('Amount to return')"
disable
v-model="data.amountToReturn"
/>
</VnRow>
<VnRow>
<QCheckbox v-model="viewReceipt" :label="t('View recipt')" />
<QCheckbox v-model="shouldSendEmail" :label="t('Send email')" />
</VnRow>
</div>
<VnRow>
<VnSelect
v-if="$props.extraFields.includes('orderBy')"
:label="t('Type')"
v-model="data.orderBy"
:options="['issued', ' bookEntried', ' booked', ' dueDate']"
option-value="id"
option-label="name"
hide-selected
/>
</VnRow>
<VnRow class="row">
<VnSelect
v-if="$props.extraFields.includes('currencyFk')"
:label="t('currencyFk')"
v-model="data.currencyFk"
:options="currenciesOptions"
option-value="id"
option-label="name"
hide-selected
/>
<VnInputNumber
v-if="data.currencyFk !== 1"
:label="t('Divisa')"
v-model="data.divisa"
/>
</VnRow>
<div class="q-mt-lg row justify-end">
<QBtn
:disabled="formModelRef.isLoading"
:label="t('globals.cancel')"
:loading="formModelRef.isLoading"
class="q-ml-sm"
color="primary"
flat
type="reset"
v-close-popup
/>
<QBtn
:disabled="formModelRef.isLoading"
:label="t('globals.save')"
:loading="formModelRef.isLoading"
color="primary"
type="submit"
/>
</div>
</template>
</FormModel>
</QDialog>
</template>
<i18n>
es:
New payment: Añadir pago
Date: Fecha
Company: Empresa
Bank: Caja
Amount: Importe
Reference: Referencia
Cash: Efectivo
currencyFk: Moneda
Type: Tipo
Delivered amount: Cantidad entregada
Amount to return: Cantidad a devolver
View recipt: Ver recibido
Send email: Enviar correo
Compensation: Compensación
Compensation account: Cuenta para compensar
Supplier Compensation Reference: ({supplierId}) Ntro Proveedor {supplierName}
Client Compensation Reference: ({clientId}) Ntro Cliente {clientName}
There is no assigned email for this client: No hay correo asignado para este cliente
Amount exceeded: Según ley contra el fraude no se puede recibir cobros por importe igual o superior a {maxAmount}
</i18n>

View File

@ -0,0 +1,12 @@
import axios from 'axios';
export async function getClientRisk(_filter) {
const filter = {
..._filter,
include: { relation: 'company', scope: { fields: ['code'] } },
};
return await axios(`ClientRisks`, {
params: { filter: JSON.stringify(filter) },
});
}

View File

@ -21,6 +21,7 @@ export default {
'SupplierAccounts',
'SupplierContacts',
'SupplierAddresses',
'SupplierBalance',
'SupplierConsumption',
'SupplierAgencyTerm',
'SupplierDms',
@ -144,6 +145,16 @@ export default {
component: () =>
import('src/pages/Supplier/Card/SupplierAddressesCreate.vue'),
},
{
path: 'balance',
name: 'SupplierBalance',
meta: {
title: 'balance',
icon: 'balance',
},
component: () =>
import('src/pages/Supplier/Card/SupplierBalance.vue'),
},
{
path: 'consumption',
name: 'SupplierConsumption',