0
0
Fork 0

feat: with VnTable

This commit is contained in:
Javier Segarra 2024-07-17 12:07:50 +02:00
parent 9fe09bcffc
commit 0e5e7c3fda
2 changed files with 220 additions and 248 deletions

View File

@ -158,7 +158,7 @@ const col = computed(() => {
const components = computed(() => $props.components ?? defaultComponents);
</script>
<template>
<div class="row no-wrap">
<div class="row no-wrap" :style="$props.column.style">
<VnComponent
v-if="col.before"
:prop="col.before"

View File

@ -1,9 +1,8 @@
<script setup>
import { onMounted, ref, reactive, onUnmounted, watch, nextTick } from 'vue';
import { onMounted, ref, reactive, onUnmounted, nextTick, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import FetchData from 'components/FetchData.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
@ -13,15 +12,15 @@ import ItemFixedPriceFilter from './ItemFixedPriceFilter.vue';
import ItemDescriptorProxy from './Card/ItemDescriptorProxy.vue';
import { useStateStore } from 'stores/useStateStore';
import { dashIfEmpty } from 'src/filters';
import { dashIfEmpty, toDate } from 'src/filters';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useState } from 'src/composables/useState';
import { toCurrency } from 'filters/index';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';
import { useArrayData } from 'composables/useArrayData';
import { isLower, isBigger } from 'src/filters/date.js';
import RightMenu from 'src/components/common/RightMenu.vue';
import VnTable from 'src/components/VnTable/VnTable.vue';
import { QCheckbox } from 'quasar';
const checked = ref(false);
@ -55,106 +54,106 @@ const exprBuilder = (param, value) => {
};
const params = reactive({});
const arrayData = useArrayData('ItemFixedPrices', {
url: 'FixedPrices/filter',
userParams: params,
order: ['name ASC', 'itemFk'],
exprBuilder: exprBuilder,
});
const store = arrayData.store;
// const arrayData = useArrayData('ItemFixedPrices', {
// url: 'FixedPrices/filter',
// userParams: params,
// order: ['name ASC', 'itemFk'],
// exprBuilder: exprBuilder,
// });
// const store = arrayData.store;
const fetchFixedPrices = async () => {
await arrayData.fetch({ append: false });
};
// const fetchFixedPrices = async () => {
// await arrayData.fetch({ append: false });
// };
const onFixedPricesFetched = (data) => {
data.forEach((item) => {
console.log(item.hasMinPrice);
item.hasMinPrice = `${item.hasMinPrice !== 0}`;
});
fixedPrices.value = data;
// el objetivo de guardar una copia de las rows es evitar guardar cambios si la data no cambió al disparar los eventos
fixedPricesOriginalData.value = JSON.parse(JSON.stringify(data));
};
// const onFixedPricesFetched = (data) => {
// data.forEach((item) => {
// console.log(item.hasMinPrice);
// item.hasMinPrice = `${item.hasMinPrice !== 0}`;
// });
// fixedPrices.value = data;
// // el objetivo de guardar una copia de las rows es evitar guardar cambios si la data no cambió al disparar los eventos
// fixedPricesOriginalData.value = JSON.parse(JSON.stringify(data));
// };
watch(
() => store.data,
(data) => onFixedPricesFetched(data)
);
// watch(
// () => store.data,
// (data) => onFixedPricesFetched(data)
// );
const applyColumnFilter = async (col) => {
try {
const paramKey = col.columnFilter?.filterParamKey || col.field;
params[paramKey] = col.columnFilter.filterValue;
await arrayData.addFilter({ params });
} catch (err) {
console.error('Error applying column filter', err);
}
};
// const applyColumnFilter = async (col) => {
// try {
// const paramKey = col.columnFilter?.filterParamKey || col.field;
// params[paramKey] = col.columnFilter.filterValue;
// await arrayData.addFilter({ params });
// } catch (err) {
// console.error('Error applying column filter', err);
// }
// };
const getColumnInputEvents = (col) => {
return col.columnFilter.type === 'select'
? { 'update:modelValue': () => applyColumnFilter(col) }
: {
'keyup.enter': () => applyColumnFilter(col),
};
};
// const getColumnInputEvents = (col) => {
// return col.columnFilter.type === 'select'
// ? { 'update:modelValue': () => applyColumnFilter(col) }
// : {
// 'keyup.enter': () => applyColumnFilter(col),
// };
// };
const defaultColumnFilter = {
component: VnInput,
type: 'text',
filterValue: null,
event: getColumnInputEvents,
attrs: {
dense: true,
},
};
// const defaultColumnFilter = {
// component: VnInput,
// type: 'text',
// filterValue: null,
// event: getColumnInputEvents,
// attrs: {
// dense: true,
// },
// };
const defaultColumnAttrs = {
align: 'left',
sortable: true,
};
const columns = ref([
const columns = computed(() => [
{
sortable: true,
align: 'left',
label: t('item.fixedPrice.itemId'),
name: 'itemId',
field: 'itemFk',
...defaultColumnAttrs,
columnFilter: {
...defaultColumnFilter,
isId: true,
cardVisible: true,
columnField: {
component: 'input',
type: 'number',
},
},
{
label: t('globals.description'),
label: t('globals.name'),
field: 'name',
name: 'description',
...defaultColumnAttrs,
columnFilter: {
...defaultColumnFilter,
},
create: true,
cardVisible: true,
},
{
label: t('item.fixedPrice.groupingPrice'),
field: 'rate2',
name: 'groupingPrice',
name: 'rate2',
...defaultColumnAttrs,
columnFilter: {
...defaultColumnFilter,
},
format: (val) => toCurrency(val),
cardVisible: true,
class: 'expand',
style: 'max-width: 80px',
},
{
label: t('item.fixedPrice.packingPrice'),
field: 'rate3',
name: 'packingPrice',
name: 'rate3',
...defaultColumnAttrs,
columnFilter: {
...defaultColumnFilter,
},
format: (val) => dashIfEmpty(val),
cardVisible: true,
class: 'expand',
style: 'max-width: 80px',
},
{
@ -162,8 +161,11 @@ const columns = ref([
field: 'minPrice',
name: 'minPrice',
...defaultColumnAttrs,
columnFilter: {
...defaultColumnFilter,
cardVisible: true,
columnField: {
class: 'expand',
component: 'input',
type: 'number',
},
},
{
@ -171,93 +173,40 @@ const columns = ref([
field: 'started',
name: 'started',
...defaultColumnAttrs,
columnFilter: null,
cardVisible: true,
component: 'date',
format: (row) => toDate(row.started),
},
{
label: t('item.fixedPrice.ended'),
field: 'ended',
name: 'ended',
...defaultColumnAttrs,
columnFilter: null,
cardVisible: true,
component: 'date',
format: (row) => toDate(row.ended),
},
{
label: t('item.fixedPrice.warehouse'),
field: 'warehouseFk',
name: 'warehouse',
name: 'warehouseFk',
...defaultColumnAttrs,
columnFilter: {
component: VnSelect,
type: 'select',
filterValue: null,
event: getColumnInputEvents,
attrs: {
options: warehousesOptions.value,
'option-value': 'id',
'option-label': 'name',
dense: true,
},
{
align: 'right',
name: 'tableActions',
actions: [
{
title: t('delete'),
icon: 'delete',
action: (row) => confirmRemove(row),
isPrimary: true,
},
},
],
},
{ name: 'deleteAction', align: 'center' },
]);
const editTableFieldsOptions = [
{
field: 'rate2',
label: t('item.fixedPrice.groupingPrice'),
component: 'input',
attrs: {
type: 'number',
},
},
{
field: 'rate3',
label: t('item.fixedPrice.packingPrice'),
component: 'input',
attrs: {
type: 'number',
},
},
{
field: 'minPrice',
label: t('item.fixedPrice.minPrice'),
component: 'input',
attrs: {
type: 'number',
},
},
{
field: 'hasMinPrice',
label: t('item.fixedPrice.hasMinPrice'),
component: 'checkbox',
attrs: {
'false-value': 0,
'true-value': 1,
},
},
{
field: 'started',
label: t('item.fixedPrice.started'),
component: 'date',
},
{
field: 'ended',
label: t('item.fixedPrice.ended'),
component: 'date',
},
{
field: 'warehouseFk',
label: t('item.fixedPrice.warehouse'),
component: 'select',
attrs: {
options: [],
'option-label': 'name',
'option-value': 'id',
},
},
];
const getRowUpdateInputEvents = (props, resetMinPrice, inputType = 'text') => {
return inputType === 'text'
? {
@ -272,8 +221,8 @@ const validations = (row, rowIndex, col) => {
// Si la row no tiene id significa que fue agregada con addRow y no se ha guardado en la base de datos
// Si isNew es falso no se checkea si el valor es igual a la original
if (!isNew)
if (fixedPricesOriginalData.value[rowIndex][col.field] == row[col.field])
return false;
// if (fixedPricesOriginalData.value[rowIndex][col.field] == row[col.field])
return false;
const requiredFields = ['itemFk', 'started', 'ended', 'rate2', 'rate3'];
return requiredFields.every(
@ -295,12 +244,12 @@ const upsertPrice = async ({ row, col, rowIndex }, resetMinPrice = false) => {
try {
if (resetMinPrice) row.hasMinPrice = 0;
row = await upsertFixedPrice(row);
fixedPricesOriginalData.value[rowIndex][col.field] = row[col.field];
// fixedPricesOriginalData.value[rowIndex][col.field] = row[col.field];
} catch (err) {
console.error('Error editing price', err);
}
};
async function saveOnRowChange(_, row) {
async function saveOnRowChange(row) {
if (rowsSelected.value.length > 1) return;
if (rowsSelected.value[0]?.id === row.id) return;
else if (rowsSelected.value.length === 1)
@ -331,9 +280,9 @@ async function saveOnRowChange(_, row) {
// }
const tableRef = ref();
function checkLastVisibleRow() {
const tableBody = tableRef.value.$el.querySelector('tbody');
if (!tableBody) return;
const rows = tableBody.querySelectorAll('tr');
const rows = document
.getElementsByClassName('q-table')[0]
.querySelectorAll('tr.cursor-pointer');
let lastVisibleRow = null;
rows.forEach((row, index) => {
@ -348,7 +297,7 @@ function checkLastVisibleRow() {
return lastVisibleRow;
}
}
const addRow = () => {
const addRow = (fixedPrice = null) => {
const lastvisible = checkLastVisibleRow();
if (!fixedPrices.value || fixedPrices.value.length === 0) {
fixedPrices.value = [];
@ -368,10 +317,16 @@ const addRow = () => {
fixedPrices.value.push({ ...newPrice });
return;
}
if (fixedPrice) {
lastItem.value = fixedPrice;
return;
}
const lastItemCopy = JSON.parse(
JSON.stringify(fixedPrices.value[fixedPrices.value.length - 1])
);
lastItem.value = lastItemCopy;
// tableRef.value.create.formInitialData = lastItem;
delete lastItemCopy.id;
fixedPricesOriginalData.value.splice(lastvisible, 0, lastItemCopy);
fixedPrices.value.unshift(lastItemCopy);
@ -379,9 +334,11 @@ const addRow = () => {
highlightNewRow(lastvisible);
});
};
const lastItem = ref(null);
function highlightNewRow(index) {
const tableBody = tableRef.value.$el.querySelector('tbody');
const row = tableBody.querySelectorAll('tr')[index];
const row = document
.getElementsByClassName('q-table')[0]
.querySelectorAll('tr.cursor-pointer')[index];
if (row) {
row.classList.add('highlight');
setTimeout(() => {
@ -394,18 +351,26 @@ const openEditTableCellDialog = () => {
};
const onEditCellDataSaved = async () => {
rowsSelected.value = [];
await fetchFixedPrices();
};
const onWarehousesFetched = (data) => {
warehousesOptions.value = data;
// Actualiza las 'options' del elemento con field 'warehouseFk' en 'editTableFieldsOptions'.
const warehouseField = editTableFieldsOptions.find(
(field) => field.field === 'warehouseFk'
);
warehouseField.attrs.options = data;
};
/*const lastRow = ref(null);
async function saveOnRowChange(row) {
if (lastRow.value && lastRow.value !== row.id) {
console.log('update');
await upsertPrice(row);
return;
}
lastRow.value = row.id;
}*/
// const onWarehousesFetched = (data) => {
// warehousesOptions.value = data;
// // Actualiza las 'options' del elemento con field 'warehouseFk' en 'editTableFieldsOptions'.
// const warehouseField = editTableFieldsOptions.find(
// (field) => field.field === 'warehouseFk'
// );
// warehouseField.attrs.options = data;
// };
import { useQuasar } from 'quasar';
const removeFuturePrice = async () => {
try {
rowsSelected.value.forEach(({ id }) => {
@ -416,43 +381,54 @@ const removeFuturePrice = async () => {
console.error('Error removing price', err);
}
};
const removePrice = async (id, rowIndex) => {
const quasar = useQuasar();
import VnConfirm from 'components/ui/VnConfirm.vue';
import FetchData from 'src/components/FetchData.vue';
function confirmRemove(item) {
quasar.dialog({
component: VnConfirm,
componentProps: {
title: t('This row will be removed'),
message: t('Do you want to clone this item?'),
promise: async () => removePrice(item.id),
},
});
}
const removePrice = async (id) => {
try {
await axios.delete(`FixedPrices/${id}`);
fixedPrices.value.splice(rowIndex, 1);
fixedPricesOriginalData.value.splice(rowIndex, 1);
notify(t('globals.dataSaved'), 'positive');
tableRef.value.reload({});
} catch (err) {
console.error('Error removing price', err);
}
};
const updateMinPrice = async (value, props) => {
// El checkbox hasMinPrice se encuentra en la misma columna que el input hasMinPrice
// Por lo tanto le mandamos otro objeto con las mismas propiedades pero con el campo 'field' cambiado
props.row.hasMinPrice = value;
await upsertPrice({
row: props.row,
col: { field: 'hasMinPrice' },
rowIndex: props.rowIndex,
});
};
onMounted(async () => {
stateStore.rightDrawer = true;
params.warehouseFk = user.value.warehouseFk;
await fetchFixedPrices();
});
function handleOnDataSave(CrudModelRef) {
addRow(
CrudModelRef.CrudModelRef.formData[CrudModelRef.CrudModelRef.formData.length - 1]
);
CrudModelRef.CrudModelRef.formData.unshift(lastItem);
nextTick(() => {
highlightNewRow(checkLastVisibleRow());
});
// CrudModelRef.value.insert(lastItem);
}
onUnmounted(() => (stateStore.rightDrawer = false));
</script>
<template>
<FetchData
url="Warehouses"
:filter="{ where: { isDestiny: true }, order: ['name'] }"
@on-fetch="(data) => (warehousesOptions = data)"
auto-load
@on-fetch="(data) => onWarehousesFetched(data)"
url="Warehouses"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
/>
<RightMenu>
<template #right-panel>
@ -476,53 +452,39 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</QBtn>
</template>
</VnSubToolbar>
<QPage class="column items-center q-pa-md">
<QTable
<QPage>
{{ lastRow }}
{{ rowsSelected }}
<VnTable
data-key="ItemFixedPrices"
url="FixedPrices/filter"
:filter="{ where: exprBuilder }"
:order="['name ASC', 'itemFk DESC']"
ref="tableRef"
dense
:rows="fixedPrices"
:columns="columns"
row-key="id"
selection="multiple"
default-mode="table"
auto-load
:is-editable="true"
:right-search="false"
:table="{
'row-key': 'id',
selection: 'multiple',
}"
v-model:selected="rowsSelected"
:pagination="{ rowsPerPage: 0 }"
class="full-width q-mt-md"
:no-data-label="t('globals.noResults')"
@row-click="saveOnRowChange"
:row-click="saveOnRowChange"
:create-as-dialog="false"
:create="{
onDataSaved: handleOnDataSave,
}"
:use-model="true"
:disable-option="{ card: true }"
>
<template #top-row="{ cols }">
<QTr>
<QTd />
<QTd
v-for="(col, index) in cols"
:key="index"
style="max-width: 100px"
>
<component
:is="col.columnFilter.component"
v-if="col.columnFilter"
v-model="col.columnFilter.filterValue"
v-bind="col.columnFilter.attrs"
v-on="col.columnFilter.event(col)"
dense
/>
</QTd>
</QTr>
</template>
<template #header="props">
<QTr :props="props" class="bg">
<QTh />
<QTh
v-for="col in props.cols"
:key="col.name"
:props="props"
style="text-wrap: balance"
>
{{ col.label }}
</QTh>
</QTr>
<template #header-selection="scope">
<QCheckbox v-model="scope.selected" />
</template>
<template #body-selection="scope">
{{ scope }}
<QCheckbox
flat
style="width: 10px; margin-left: -20px"
@ -532,13 +494,11 @@ onUnmounted(() => (stateStore.rightDrawer = false));
rowsSelected.length > 0 && rowsSelected[0].id !== scope.row.id
"-->
</template>
<template #header-selection="scope">
<QCheckbox style="margin-left: -15px" v-model="scope.selected" />
</template>
<template #body-cell-itemId="props">
<template #column-itemId="props">
<QTd>
<VnSelect
style="width: 115px"
style="max-width: 125px"
url="Items/withName"
hide-selected
option-label="id"
@ -557,7 +517,7 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</VnSelect>
</QTd>
</template>
<template #body-cell-description="{ row }">
<template #column-description="{ row }">
<QTd class="col">
<span class="link">
{{ row.name }}
@ -566,10 +526,10 @@ onUnmounted(() => (stateStore.rightDrawer = false));
<FetchedTags style="width: 200px" :item="row" :max-length="6" />
</QTd>
</template>
<template #body-cell-groupingPrice="props">
<template #column-rate2="props">
<QTd class="col">
<VnInput
style="width: 80px"
style="max-width: 80px"
mask="###.##"
v-model.number="props.row.rate2"
v-on="getRowUpdateInputEvents(props)"
@ -578,11 +538,11 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</VnInput>
</QTd>
</template>
<template #body-cell-packingPrice="props">
<template #column-rate3="props">
<QTd class="col">
<VnInput
mask="###.##"
style="width: 80px"
mask="###.##"
v-model.number="props.row.rate3"
v-on="getRowUpdateInputEvents(props)"
>
@ -590,31 +550,31 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</VnInput>
</QTd>
</template>
<template #body-cell-minPrice="props">
<template #column-minPrice="props">
<QTd class="col">
<div class="row">
<div class="row" style="width: 130px">
<QCheckbox
:model-value="props.row.hasMinPrice"
@update:model-value="updateMinPrice($event, props)"
:true-value="'true'"
:false-value="'false'"
:toggle-indeterminate="false"
/>
<VnInput
style="padding-left: -20px; width: 80px"
class="col"
:disable="props.row.hasMinPrice === 'false'"
mask="###.##"
style="width: 80px"
:disable="props.row.hasMinPrice === 1"
v-model.number="props.row.minPrice"
v-on="getRowUpdateInputEvents(props)"
type="number"
/>
>
<template #append>{{ props.row.hasMinPrice }}</template>
</VnInput>
</div>
</QTd>
</template>
<template #body-cell-started="props">
<template #column-started="props">
<QTd class="col">
<VnInputDate
style="max-width: 125px"
:show-event="true"
v-model="props.row.started"
v-on="getRowUpdateInputEvents(props, false, 'date')"
@ -629,10 +589,9 @@ onUnmounted(() => (stateStore.rightDrawer = false));
/>
</QTd>
</template>
<template #body-cell-ended="props">
<template #column-ended="props">
<QTd class="col">
<VnInputDate
style="max-width: 125px"
:show-event="true"
v-model="props.row.ended"
v-on="getRowUpdateInputEvents(props, false, 'date')"
@ -647,7 +606,7 @@ onUnmounted(() => (stateStore.rightDrawer = false));
/>
</QTd>
</template>
<template #body-cell-warehouse="props">
<template #column-warehouseFk="props">
<QTd class="col" style="max-width: 180px">
<VnSelect
:options="warehousesOptions"
@ -659,7 +618,7 @@ onUnmounted(() => (stateStore.rightDrawer = false));
/>
</QTd>
</template>
<template #body-cell-deleteAction="{ row, rowIndex }">
<template #column-deleteAction="{ row, rowIndex }">
<QTd class="col">
<QIcon
name="delete"
@ -680,7 +639,7 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</QIcon>
</QTd>
</template>
</QTable>
</VnTable>
<QPageSticky :offset="[20, 0]">
<QBtn @click="addRow()" color="primary" fab icon="add" />
<QTooltip>
@ -698,11 +657,24 @@ onUnmounted(() => (stateStore.rightDrawer = false));
</QDialog>
</QPage>
</template>
<style lang="scss" scoped>
<style lang="scss">
.q-table th,
.q-table td {
padding-inline: 5px !important;
}
.q-table tbody td {
max-width: none;
.q-td.col {
& div.row {
& .q-checkbox {
& .q-checkbox__inner {
position: relative !important;
}
}
}
}
}
.q-field__after,
.q-field__append {
padding: 0;