salix-front/src/pages/Item/ItemFixedPrice.vue

716 lines
23 KiB
Vue

<script setup>
import { onMounted, ref, reactive, onUnmounted, nextTick, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import VnSubToolbar from 'src/components/ui/VnSubToolbar.vue';
import FetchedTags from 'components/ui/FetchedTags.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInputDate from 'src/components/common/VnInputDate.vue';
import EditTableCellValueForm from 'src/components/EditTableCellValueForm.vue';
import ItemFixedPriceFilter from './ItemFixedPriceFilter.vue';
import ItemDescriptorProxy from './Card/ItemDescriptorProxy.vue';
import { useStateStore } from 'stores/useStateStore';
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 { 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);
const stateStore = useStateStore();
const { t } = useI18n();
const { openConfirmationModal } = useVnConfirm();
const state = useState();
const { notify } = useNotify();
const editTableCellDialogRef = ref(null);
const user = state.getUser();
const fixedPrices = ref([]);
const fixedPricesOriginalData = ref([]);
const warehousesOptions = ref([]);
const rowsSelected = ref([]);
const exprBuilder = (param, value) => {
switch (param) {
case 'name':
return { 'i.name': { like: `%${value}%` } };
case 'itemFk':
case 'warehouseFk':
case 'rate2':
case 'rate3':
param = `fp.${param}`;
return { [param]: value };
case 'minPrice':
param = `i.${param}`;
return { [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 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));
// };
// 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 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 defaultColumnAttrs = {
align: 'left',
sortable: true,
};
const columns = computed(() => [
{
sortable: true,
align: 'left',
label: t('item.fixedPrice.itemId'),
name: 'itemId',
...defaultColumnAttrs,
isId: true,
cardVisible: true,
columnField: {
component: 'input',
type: 'number',
},
},
{
label: t('globals.name'),
field: 'name',
name: 'description',
...defaultColumnAttrs,
create: true,
cardVisible: true,
},
{
label: t('item.fixedPrice.groupingPrice'),
field: 'rate2',
name: 'rate2',
...defaultColumnAttrs,
cardVisible: true,
class: 'expand',
style: 'max-width: 80px',
},
{
label: t('item.fixedPrice.packingPrice'),
field: 'rate3',
name: 'rate3',
...defaultColumnAttrs,
cardVisible: true,
class: 'expand',
style: 'max-width: 80px',
},
{
label: t('item.fixedPrice.minPrice'),
field: 'minPrice',
name: 'minPrice',
...defaultColumnAttrs,
cardVisible: true,
columnField: {
class: 'expand',
component: 'input',
type: 'number',
},
},
{
label: t('item.fixedPrice.started'),
field: 'started',
name: 'started',
...defaultColumnAttrs,
cardVisible: true,
component: 'date',
format: (row) => toDate(row.started),
},
{
label: t('item.fixedPrice.ended'),
field: 'ended',
name: 'ended',
...defaultColumnAttrs,
cardVisible: true,
component: 'date',
format: (row) => toDate(row.ended),
},
{
label: t('item.fixedPrice.warehouse'),
field: 'warehouseFk',
name: 'warehouseFk',
...defaultColumnAttrs,
component: 'select',
attrs: {
options: warehousesOptions,
},
},
{
align: 'right',
name: 'tableActions',
actions: [
{
title: t('delete'),
icon: 'delete',
action: (row) => confirmRemove(row),
isPrimary: true,
},
],
},
]);
const getRowUpdateInputEvents = (props, resetMinPrice, inputType = 'text') => {
return inputType === 'text'
? {
'keyup.enter': () => upsertPrice(props, resetMinPrice),
blur: () => upsertPrice(props, resetMinPrice),
}
: { 'update:modelValue': () => upsertPrice(props, resetMinPrice) };
};
const validations = (row, rowIndex, col) => {
const isNew = !row.id;
// 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;
const requiredFields = ['itemFk', 'started', 'ended', 'rate2', 'rate3'];
return requiredFields.every(
(field) => row[field] !== null && row[field] !== undefined
);
};
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,
});
};
const upsertPrice = async ({ row, col, rowIndex }, resetMinPrice = false) => {
// if (!validations(row, rowIndex, col)) return;
try {
if (resetMinPrice) row.hasMinPrice = 0;
row = await upsertFixedPrice(row);
// fixedPricesOriginalData.value[rowIndex][col.field] = row[col.field];
} catch (err) {
console.error('Error editing price', err);
}
};
async function upsertFixedPrice(row) {
try {
const { data } = await axios.patch('FixedPrices/upsertFixedPrice', row);
return data;
} catch (err) {
console.error('Error editing price', err);
}
}
async function saveOnRowChange(row) {
if (rowsSelected.value.length > 1) return;
if (rowsSelected.value[0]?.id === row.id) return;
else if (rowsSelected.value.length === 1)
await upsertFixedPrice(rowsSelected.value[0]);
rowsSelected.value = [row];
// if (rowsSelected.value.length > 0) {
// disableUnselectedRows();
// } else {
// resetRowStates();
// }
// if (lastRow.value && lastRow.value !== row.id) {
// console.log('update');
// // await upsertPrice(row);
// }
// lastRow.value = row.id;
}
// function disableUnselectedRows() {
// fixedPrices.value.forEach((row) => {
// row.disabled = !rowsSelected.value.includes(row.id);
// });
// }
// function resetRowStates() {
// fixedPrices.value.forEach((row) => {
// row.disable = false;
// });
// // Aquí puedes guardar los cambios si es necesario
// console.log('Guardando cambios...');
// }
const tableRef = ref();
function checkLastVisibleRow() {
const rows = document
.getElementsByClassName('q-table')[0]
.querySelectorAll('tr.cursor-pointer');
let lastVisibleRow = null;
rows.forEach((row, index) => {
const rect = row.getBoundingClientRect();
if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
lastVisibleRow = index;
}
});
if (lastVisibleRow) {
console.log('Última fila visible:', lastVisibleRow);
return lastVisibleRow;
}
}
const addRow = (fixedPrice = null) => {
const lastvisible = checkLastVisibleRow();
// if (!fixedPrices.value || fixedPrices.value.length === 0) {
// fixedPrices.value = [];
// const today = Date.vnNew();
// const millisecsInDay = 86400000;
// const daysInWeek = 7;
// const nextWeek = new Date(today.getTime() + daysInWeek * millisecsInDay);
// const newPrice = {
// started: today,
// ended: nextWeek,
// hasMinPrice: 0,
// };
// fixedPricesOriginalData.value.push({ ...newPrice });
// 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);
nextTick(() => {
highlightNewRow(lastvisible);
});
};
const lastItem = ref(null);
function highlightNewRow(index) {
const row = document
.getElementsByClassName('q-table')[0]
.querySelectorAll('tr.cursor-pointer')[index];
if (row) {
row.classList.add('highlight');
setTimeout(() => {
row.classList.remove('highlight');
}, 3000); // Duración de la animación en milisegundos
}
}
const openEditTableCellDialog = () => {
editTableCellDialogRef.value.show();
};
const onEditCellDataSaved = async () => {
rowsSelected.value = [];
};
/*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 }) => {
const rowIndex = fixedPrices.value.findIndex((r) => r.id === id);
removePrice(id, rowIndex);
});
} catch (err) {
console.error('Error removing price', err);
}
};
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}`);
notify(t('globals.dataSaved'), 'positive');
tableRef.value.reload({});
} catch (err) {
console.error('Error removing price', err);
}
};
onMounted(async () => {
stateStore.rightDrawer = true;
params.warehouseFk = user.value.warehouseFk;
});
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
@on-fetch="(data) => (warehousesOptions = data)"
auto-load
url="Warehouses"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
/>
<RightMenu>
<template #right-panel>
<ItemFixedPriceFilter
data-key="ItemFixedPrices"
:warehouses-options="warehousesOptions"
/>
</template>
</RightMenu>
<VnSubToolbar>
<template #st-data>
<QBtn
v-if="rowsSelected.length"
@click="openEditTableCellDialog()"
color="primary"
icon="edit"
>
<QTooltip>
{{ t('Edit fixed price(s)') }}
</QTooltip>
</QBtn>
</template>
</VnSubToolbar>
<QPage>
{{ lastRow }}
{{ rowsSelected }}
<VnTable
data-key="ItemFixedPrices"
url="FixedPrices/filter"
:filter="{ where: exprBuilder }"
:order="['name ASC', 'itemFk DESC']"
ref="tableRef"
dense
:columns="columns"
default-mode="table"
auto-load
:is-editable="true"
:right-search="false"
:table="{
'row-key': 'id',
selection: 'multiple',
}"
v-model:selected="rowsSelected"
:row-click="saveOnRowChange"
:create-as-dialog="false"
:create="{
onDataSaved: handleOnDataSave,
}"
:use-model="true"
:disable-option="{ card: true }"
>
<template #header-selection="scope">
<QCheckbox v-model="scope.selected" />
</template>
<template #body-selection="scope">
{{ scope }}
<QCheckbox
flat
style="width: 10px; margin-left: -20px"
v-model="scope.selected"
/>
<!--:disable="
rowsSelected.length > 0 && rowsSelected[0].id !== scope.row.id
"-->
</template>
<template #column-itemId="props">
<QTd>
<VnSelect
style="max-width: 125px"
url="Items/withName"
hide-selected
option-label="id"
option-value="id"
v-model="props.row.itemFk"
v-on="getRowUpdateInputEvents(props, true, 'select')"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel> #{{ scope.opt?.id }} </QItemLabel>
<QItemLabel caption>{{ scope.opt?.name }}</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</QTd>
</template>
<template #column-description="{ row }">
<QTd class="col">
<span class="link">
{{ row.name }}
</span>
<ItemDescriptorProxy :id="row.itemFk" />
<FetchedTags style="max-width: 220px" :item="row" :max-length="6" />
</QTd>
</template>
<template #column-rate2="props">
<QTd class="col">
<VnInput
style="max-width: 80px"
mask="###.##"
v-model.number="props.row.rate2"
v-on="getRowUpdateInputEvents(props)"
>
<template #append>€</template>
</VnInput>
</QTd>
</template>
<template #column-rate3="props">
<QTd class="col">
<VnInput
style="width: 80px"
mask="###.##"
v-model.number="props.row.rate3"
v-on="getRowUpdateInputEvents(props)"
>
<template #append>€</template>
</VnInput>
</QTd>
</template>
<template #column-minPrice="props">
<QTd class="col">
<div class="row" style="width: 130px">
<QCheckbox
:model-value="props.row.hasMinPrice"
@update:model-value="updateMinPrice($event, props)"
:false-value="0"
:true-value="1"
/>
<VnInput
class="col"
mask="###.##"
style="width: 80px"
:disable="props.row.hasMinPrice === 1"
v-model.number="props.row.minPrice"
v-on="getRowUpdateInputEvents(props)"
>
<template #append>€{{ props.row.hasMinPrice }}</template>
</VnInput>
</div>
</QTd>
</template>
<template #column-started="props">
<QTd class="col">
<VnInputDate
:show-event="true"
v-model="props.row.started"
v-on="getRowUpdateInputEvents(props, false, 'date')"
v-bind="
isBigger(props.row.started)
? {
'bg-color': 'warning',
'is-outlined': true,
}
: {}
"
/>
</QTd>
</template>
<template #column-ended="props">
<QTd class="col">
<VnInputDate
:show-event="true"
v-model="props.row.ended"
v-on="getRowUpdateInputEvents(props, false, 'date')"
v-bind="
isLower(props.row.started)
? {
'bg-color': 'warning',
'is-outlined': true,
}
: {}
"
/>
</QTd>
</template>
<template #column-warehouseFk="props">
<QTd class="col" style="max-width: 180px">
<VnSelect
:options="warehousesOptions"
hide-selected
option-label="name"
option-value="id"
v-model="props.row.warehouseFk"
v-on="getRowUpdateInputEvents(props, false, 'select')"
/>
</QTd>
</template>
<template #column-deleteAction="{ row, rowIndex }">
<QTd class="col">
<QIcon
name="delete"
size="sm"
class="cursor-pointer fill-icon-on-hover"
color="primary"
@click.stop="
openConfirmationModal(
t('This row will be removed'),
t('Do you want to clone this item?'),
() => removePrice(row.id, rowIndex)
)
"
>
<QTooltip class="text-no-wrap">
{{ t('Delete') }}
</QTooltip>
</QIcon>
</QTd>
</template>
</VnTable>
<QDialog ref="editTableCellDialogRef">
<EditTableCellValueForm
edit-url="FixedPrices/editFixedPrice"
:rows="rowsSelected"
:fields-options="editTableFieldsOptions"
@on-data-saved="onEditCellDataSaved()"
/>
</QDialog>
</QPage>
</template>
<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-checkbox__inner--truthy {
color: var(--q-primary);
}
}
}
}
}
}
.q-field__after,
.q-field__append {
padding: 0;
}
/* height or max-height is important */
tbody tr.highlight .q-td {
animation: highlight-animation 4s ease-in-out;
}
@keyframes highlight-animation {
0% {
background-color: $primary-light;
}
100% {
background-color: transparent;
}
}
</style>
<i18n>
es:
Add fixed price: Añadir precio fijado
Edit fixed price(s): Editar precio(s) fijado(s)
This row will be removed: Esta linea se eliminará
Are you sure you want to continue?: ¿Seguro que quieres continuar?
Delete: Eliminar
</i18n>