Compare commits

..

No commits in common. "dev" and "6739-invoiceOut" have entirely different histories.

693 changed files with 32191 additions and 42422 deletions

View File

@ -1,33 +0,0 @@
const fs = require('fs');
const path = require('path');
function getCurrentBranchName(p = process.cwd()) {
if (!fs.existsSync(p)) return false;
const gitHeadPath = path.join(p, '.git', 'HEAD');
if (!fs.existsSync(gitHeadPath))
return getCurrentBranchName(path.resolve(p, '..'));
const headContent = fs.readFileSync(gitHeadPath, 'utf-8');
return headContent.trim().split('/')[2];
}
const branchName = getCurrentBranchName();
if (branchName) {
const msgPath = `.git/COMMIT_EDITMSG`;
const msg = fs.readFileSync(msgPath, 'utf-8');
const reference = branchName.match(/^\d+/);
const referenceTag = `refs #${reference}`;
if (!msg.includes(referenceTag) && reference) {
const splitedMsg = msg.split(':');
if (splitedMsg.length > 1) {
const finalMsg = splitedMsg[0] + ': ' + referenceTag + splitedMsg.slice(1).join(':');
fs.writeFileSync(msgPath, finalMsg);
}
}
}

View File

@ -1,8 +0,0 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
echo "Running husky commit-msg hook"
npx --no-install commitlint --edit
echo "Adding reference tag to commit message"
node .husky/addReferenceTag.js

View File

@ -14,5 +14,5 @@
"[vue]": { "[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode" "editor.defaultFormatter": "esbenp.prettier-vscode"
}, },
"cSpell.words": ["axios", "composables"] "cSpell.words": ["axios"]
} }

File diff suppressed because it is too large Load Diff

6
Jenkinsfile vendored
View File

@ -4,8 +4,7 @@ def PROTECTED_BRANCH
def BRANCH_ENV = [ def BRANCH_ENV = [
test: 'test', test: 'test',
master: 'production', master: 'production'
beta: 'production'
] ]
node { node {
@ -16,8 +15,7 @@ node {
PROTECTED_BRANCH = [ PROTECTED_BRANCH = [
'dev', 'dev',
'test', 'test',
'master', 'master'
'beta'
].contains(env.BRANCH_NAME) ].contains(env.BRANCH_NAME)
// https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables // https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables

View File

@ -1 +0,0 @@
module.exports = { extends: ['@commitlint/config-conventional'] };

View File

@ -1,7 +1,4 @@
const { defineConfig } = require('cypress'); const { defineConfig } = require('cypress');
// https://docs.cypress.io/app/tooling/reporters
// https://docs.cypress.io/app/references/configuration
// https://www.npmjs.com/package/cypress-mochawesome-reporter
module.exports = defineConfig({ module.exports = defineConfig({
e2e: { e2e: {
@ -14,23 +11,12 @@ module.exports = defineConfig({
video: false, video: false,
specPattern: 'test/cypress/integration/**/*.spec.js', specPattern: 'test/cypress/integration/**/*.spec.js',
experimentalRunAllSpecs: true, experimentalRunAllSpecs: true,
watchForFileChanges: true,
reporter: 'cypress-mochawesome-reporter',
reporterOptions: {
charts: true,
reportPageTitle: 'Cypress Inline Reporter',
reportFilename: '[status]_[datetime]-report',
embeddedScreenshots: true,
reportDir: 'test/cypress/reports',
inlineAssets: true,
},
component: { component: {
componentFolder: 'src', componentFolder: 'src',
testFiles: '**/*.spec.js', testFiles: '**/*.spec.js',
supportFile: 'test/cypress/support/unit.js', supportFile: 'test/cypress/support/unit.js',
}, },
setupNodeEvents(on, config) { setupNodeEvents(on, config) {
require('cypress-mochawesome-reporter/plugin')(on);
// implement node event listeners here // implement node event listeners here
}, },
}, },

View File

@ -1,23 +1,19 @@
{ {
"name": "salix-front", "name": "salix-front",
"version": "24.52.0", "version": "24.28.1",
"description": "Salix frontend", "description": "Salix frontend",
"productName": "Salix", "productName": "Salix",
"author": "Verdnatura", "author": "Verdnatura",
"private": true, "private": true,
"packageManager": "pnpm@8.15.1", "packageManager": "pnpm@8.15.1",
"scripts": { "scripts": {
"resetDatabase": "cd ../salix && gulp docker",
"lint": "eslint --ext .js,.vue ./", "lint": "eslint --ext .js,.vue ./",
"format": "prettier --write \"**/*.{js,vue,scss,html,md,json}\" --ignore-path .gitignore", "format": "prettier --write \"**/*.{js,vue,scss,html,md,json}\" --ignore-path .gitignore",
"test:e2e": "cypress open", "test:e2e": "cypress open",
"test:e2e:ci": "npm run resetDatabase && cd ../salix-front && cypress run", "test:e2e:ci": "cd ../salix && gulp docker && cd ../salix-front && cypress run",
"test": "echo \"See package.json => scripts for available tests.\" && exit 0", "test": "echo \"See package.json => scripts for available tests.\" && exit 0",
"test:unit": "vitest", "test:unit": "vitest",
"test:unit:ci": "vitest run", "test:unit:ci": "vitest run"
"commitlint": "commitlint --edit",
"prepare": "npx husky install",
"addReferenceTag": "node .husky/addReferenceTag.js"
}, },
"dependencies": { "dependencies": {
"@quasar/cli": "^2.3.0", "@quasar/cli": "^2.3.0",
@ -33,8 +29,6 @@
"vue-router": "^4.2.1" "vue-router": "^4.2.1"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "^19.2.1",
"@commitlint/config-conventional": "^19.1.0",
"@intlify/unplugin-vue-i18n": "^0.8.1", "@intlify/unplugin-vue-i18n": "^0.8.1",
"@pinia/testing": "^0.1.2", "@pinia/testing": "^0.1.2",
"@quasar/app-vite": "^1.7.3", "@quasar/app-vite": "^1.7.3",
@ -43,12 +37,10 @@
"@vue/test-utils": "^2.4.4", "@vue/test-utils": "^2.4.4",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"cypress": "^13.6.6", "cypress": "^13.6.6",
"cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^8.41.0", "eslint": "^8.41.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-cypress": "^2.13.3", "eslint-plugin-cypress": "^2.13.3",
"eslint-plugin-vue": "^9.14.1", "eslint-plugin-vue": "^9.14.1",
"husky": "^8.0.0",
"postcss": "^8.4.23", "postcss": "^8.4.23",
"prettier": "^2.8.8", "prettier": "^2.8.8",
"vitest": "^0.31.1" "vitest": "^0.31.1"

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

View File

@ -2,22 +2,18 @@ import axios from 'axios';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
import { Router } from 'src/router'; import { Router } from 'src/router';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
import { useStateQueryStore } from 'src/stores/useStateQueryStore';
const session = useSession(); const session = useSession();
const { notify } = useNotify(); const { notify } = useNotify();
const stateQuery = useStateQueryStore();
const baseUrl = '/api/';
axios.defaults.baseURL = baseUrl; axios.defaults.baseURL = '/api/';
const axiosNoError = axios.create({ baseURL: baseUrl });
const onRequest = (config) => { const onRequest = (config) => {
const token = session.getToken(); const token = session.getToken();
if (token.length && !config.headers.Authorization) { if (token.length && !config.headers.Authorization) {
config.headers.Authorization = token; config.headers.Authorization = token;
} }
stateQuery.add(config);
return config; return config;
}; };
@ -26,10 +22,10 @@ const onRequestError = (error) => {
}; };
const onResponse = (response) => { const onResponse = (response) => {
const config = response.config; const { method } = response.config;
stateQuery.remove(config);
if (config.method === 'patch') { const isSaveRequest = method === 'patch';
if (isSaveRequest) {
notify('globals.dataSaved', 'positive'); notify('globals.dataSaved', 'positive');
} }
@ -37,23 +33,42 @@ const onResponse = (response) => {
}; };
const onResponseError = (error) => { const onResponseError = (error) => {
stateQuery.remove(error.config); let message = '';
if (session.isLoggedIn() && error.response?.status === 401) { const response = error.response;
session.destroy(false); const responseData = response && response.data;
const responseError = responseData && response.data.error;
if (responseError) {
message = responseError.message;
}
switch (response?.status) {
case 500:
message = 'errors.statusInternalServerError';
break;
case 502:
message = 'errors.statusBadGateway';
break;
case 504:
message = 'errors.statusGatewayTimeout';
break;
}
if (session.isLoggedIn() && response?.status === 401) {
session.destroy();
const hash = window.location.hash; const hash = window.location.hash;
const url = hash.slice(1); const url = hash.slice(1);
Router.push(`/login?redirect=${url}`); Router.push({ path: url });
} else if (!session.isLoggedIn()) { } else if (!session.isLoggedIn()) {
return Promise.reject(error); return Promise.reject(error);
} }
notify(message, 'negative');
return Promise.reject(error); return Promise.reject(error);
}; };
axios.interceptors.request.use(onRequest, onRequestError); axios.interceptors.request.use(onRequest, onRequestError);
axios.interceptors.response.use(onResponse, onResponseError); axios.interceptors.response.use(onResponse, onResponseError);
axiosNoError.interceptors.request.use(onRequest);
axiosNoError.interceptors.response.use(onResponse);
export { onRequest, onResponseError, axiosNoError }; export { onRequest, onResponseError };

View File

@ -1,4 +0,0 @@
import { QInput } from 'quasar';
import setDefault from './setDefault';
setDefault(QInput, 'dense', true);

View File

@ -1,4 +0,0 @@
import { QSelect } from 'quasar';
import setDefault from './setDefault';
setDefault(QSelect, 'dense', true);

View File

@ -1,34 +0,0 @@
export default {
mounted: function (el, binding) {
const shortcut = binding.value ?? '+';
const { key, ctrl, alt, callback } =
typeof shortcut === 'string'
? {
key: shortcut,
ctrl: true,
alt: true,
callback: () =>
document
.querySelector(`button[shortcut="${shortcut}"]`)
?.click(),
}
: binding.value;
const handleKeydown = (event) => {
if (event.key === key && (!ctrl || event.ctrlKey) && (!alt || event.altKey)) {
callback();
}
};
// Attach the event listener to the window
window.addEventListener('keydown', handleKeydown);
el._handleKeydown = handleKeydown;
},
unmounted: function (el) {
if (el._handleKeydown) {
window.removeEventListener('keydown', el._handleKeydown);
}
},
};

View File

@ -1,36 +0,0 @@
import routes from 'src/router/modules';
import { useRouter } from 'vue-router';
let isNotified = false;
export default {
created: function () {
const router = useRouter();
const keyBindingMap = routes
.filter((route) => route.meta.keyBinding)
.reduce((map, route) => {
map['Key' + route.meta.keyBinding.toUpperCase()] = route.path;
return map;
}, {});
const handleKeyDown = (event) => {
const { ctrlKey, altKey, code } = event;
if (ctrlKey && altKey && keyBindingMap[code] && !isNotified) {
event.preventDefault();
router.push(keyBindingMap[code]);
isNotified = true;
}
};
const handleKeyUp = (event) => {
const { ctrlKey, altKey } = event;
if (!ctrlKey || !altKey) {
isNotified = false;
}
};
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
},
};

View File

@ -1,52 +1,47 @@
function focusFirstInput(input) { import { getCurrentInstance } from 'vue';
input.focus();
return; const filterAvailableInput = (element) => {
} return element.classList.contains('q-field__native') && !element.disabled;
};
const filterAvailableText = (element) => {
return (
element.__vueParentComponent.type.name === 'QInput' &&
element.__vueParentComponent?.attrs?.class !== 'vn-input-date'
);
};
export default { export default {
mounted: function () { mounted: function () {
const that = this; const vm = getCurrentInstance();
if (vm.type.name === 'QForm') {
if (!['searchbarForm', 'filterPanelForm'].includes(this.$el?.id)) {
// AUTOFOCUS
const elementsArray = Array.from(this.$el.elements);
const availableInputs = elementsArray.filter(filterAvailableInput);
const firstInputElement = availableInputs.find(filterAvailableText);
const form = document.querySelector('.q-form#formModel'); if (firstInputElement) {
if (!form) return; firstInputElement.focus();
try {
const inputsFormCard = form.querySelectorAll(
`input:not([disabled]):not([type="checkbox"])`
);
if (inputsFormCard.length) {
focusFirstInput(inputsFormCard[0]);
}
const textareas = document.querySelectorAll(
'textarea:not([disabled]), [contenteditable]:not([disabled])'
);
if (textareas.length) {
focusFirstInput(textareas[textareas.length - 1]);
}
const inputs = document.querySelectorAll(
'form#formModel input:not([disabled]):not([type="checkbox"])'
);
const input = inputs[0];
if (!input) return;
focusFirstInput(input);
} catch (error) {
console.error(error);
}
form.addEventListener('keyup', function (evt) {
if (evt.key === 'Enter') {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
evt.preventDefault();
let { selectionStart, selectionEnd } = input;
input.value =
input.value.substring(0, selectionStart) +
'\n' +
input.value.substring(selectionEnd);
selectionStart = selectionEnd = selectionStart + 1;
return;
} }
evt.preventDefault(); const that = this;
that.onSubmit(); this.$el.addEventListener('keyup', function (evt) {
if (evt.key === 'Enter') {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
evt.preventDefault();
let { selectionStart, selectionEnd } = input;
input.value =
input.value.substring(0, selectionStart) +
'\n' +
input.value.substring(selectionEnd);
selectionStart = selectionEnd = selectionStart + 1;
return;
}
evt.preventDefault();
that.onSubmit();
}
});
} }
}); }
}, },
}; };

View File

@ -1,3 +1 @@
export * from './defaults/qTable'; export * from './defaults/qTable';
export * from './defaults/qInput';
export * from './defaults/qSelect';

View File

@ -1,54 +1,6 @@
import axios from 'axios';
import { boot } from 'quasar/wrappers'; import { boot } from 'quasar/wrappers';
import qFormMixin from './qformMixin'; import qFormMixin from './qformMixin';
import keyShortcut from './keyShortcut';
import { QForm } from 'quasar';
import { QLayout } from 'quasar';
import mainShortcutMixin from './mainShortcutMixin';
import { useCau } from 'src/composables/useCau';
export default boot(({ app }) => { export default boot(({ app }) => {
QForm.mixins = [qFormMixin]; app.mixin(qFormMixin);
QLayout.mixins = [mainShortcutMixin];
app.directive('shortcut', keyShortcut);
app.config.errorHandler = async (error) => {
let message;
const response = error.response;
const responseData = response?.data;
const responseError = responseData && response.data.error;
if (responseError) {
message = responseError.message;
}
switch (response?.status) {
case 422:
if (error.name == 'ValidationError')
message +=
' "' +
responseError.details.context +
'.' +
Object.keys(responseError.details.codes).join(',') +
'"';
break;
case 500:
message = 'errors.statusInternalServerError';
break;
case 502:
message = 'errors.statusBadGateway';
break;
case 504:
message = 'errors.statusGatewayTimeout';
break;
}
console.error(error);
if (error instanceof axios.CanceledError) {
const env = process.env.NODE_ENV;
if (env && env !== 'development') return;
message = 'Duplicate request';
}
await useCau(response, message);
};
}); });

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { reactive, ref, onMounted, nextTick, computed } from 'vue'; import { reactive, ref, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
@ -7,29 +7,27 @@ import VnSelect from 'src/components/common/VnSelect.vue';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import FormModelPopup from './FormModelPopup.vue'; import FormModelPopup from './FormModelPopup.vue';
import { useState } from 'src/composables/useState';
defineProps({ showEntityField: { type: Boolean, default: true } });
const emit = defineEmits(['onDataSaved']); const emit = defineEmits(['onDataSaved']);
const { t } = useI18n(); const { t } = useI18n();
const bicInputRef = ref(null); const bicInputRef = ref(null);
const state = useState(); const bankEntityFormData = reactive({
name: null,
const customer = computed(() => state.get('customer')); bic: null,
countryFk: null,
id: null,
});
const countriesFilter = { const countriesFilter = {
fields: ['id', 'name', 'code'], fields: ['id', 'name', 'code'],
}; };
const bankEntityFormData = reactive({
name: null,
bic: null,
countryFk: customer.value?.countryFk,
});
const countriesOptions = ref([]); const countriesOptions = ref([]);
const onDataSaved = (...args) => { const onDataSaved = (formData, requestResponse) => {
emit('onDataSaved', ...args); emit('onDataSaved', formData, requestResponse);
}; };
onMounted(async () => { onMounted(async () => {
@ -41,6 +39,7 @@ onMounted(async () => {
<template> <template>
<FetchData <FetchData
url="Countries" url="Countries"
:filter="countriesFilter"
auto-load auto-load
@on-fetch="(data) => (countriesOptions = data)" @on-fetch="(data) => (countriesOptions = data)"
/> />
@ -50,11 +49,10 @@ onMounted(async () => {
:title="t('title')" :title="t('title')"
:subtitle="t('subtitle')" :subtitle="t('subtitle')"
:form-initial-data="bankEntityFormData" :form-initial-data="bankEntityFormData"
:filter="countriesFilter"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved"
> >
<template #form-inputs="{ data, validate }"> <template #form-inputs="{ data, validate }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput <VnInput
:label="t('name')" :label="t('name')"
v-model="data.name" v-model="data.name"
@ -69,7 +67,7 @@ onMounted(async () => {
:rules="validate('bankEntity.bic')" :rules="validate('bankEntity.bic')"
/> />
</VnRow> </VnRow>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<div class="col"> <div class="col">
<VnSelect <VnSelect
:label="t('country')" :label="t('country')"
@ -82,13 +80,7 @@ onMounted(async () => {
:rules="validate('bankEntity.countryFk')" :rules="validate('bankEntity.countryFk')"
/> />
</div> </div>
<div <div v-if="showEntityField" class="col">
v-if="
countriesOptions.find((c) => c.id === data.countryFk)?.code ==
'ES'
"
class="col"
>
<VnInput <VnInput
:label="t('id')" :label="t('id')"
v-model="data.id" v-model="data.id"

View File

@ -0,0 +1,166 @@
<script setup>
import { reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModelPopup from './FormModelPopup.vue';
import VnInputDate from './common/VnInputDate.vue';
const emit = defineEmits(['onDataSaved']);
const { t } = useI18n();
const router = useRouter();
const manualInvoiceFormData = reactive({
maxShipped: Date.vnNew(),
});
const formModelPopupRef = ref();
const invoiceOutSerialsOptions = ref([]);
const taxAreasOptions = ref([]);
const ticketsOptions = ref([]);
const clientsOptions = ref([]);
const isLoading = computed(() => formModelPopupRef.value?.isLoading);
const onDataSaved = async (formData, requestResponse) => {
emit('onDataSaved', formData, requestResponse);
if (requestResponse && requestResponse.id)
router.push({ name: 'InvoiceOutSummary', params: { id: requestResponse.id } });
};
</script>
<template>
<FetchData
url="InvoiceOutSerials"
:filter="{ where: { code: { neq: 'R' } }, order: ['code'] }"
@on-fetch="(data) => (invoiceOutSerialsOptions = data)"
auto-load
/>
<FetchData
url="TaxAreas"
:filter="{ order: ['code'] }"
@on-fetch="(data) => (taxAreasOptions = data)"
auto-load
/>
<FetchData
url="Tickets"
:filter="{
fields: ['id', 'nickname'],
where: { refFk: null },
order: 'shipped DESC',
}"
@on-fetch="(data) => (ticketsOptions = data)"
auto-load
/>
<FetchData
url="Clients"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
@on-fetch="(data) => (clientsOptions = data)"
auto-load
/>
<FormModelPopup
ref="formModelPopupRef"
:title="t('Create manual invoice')"
url-create="InvoiceOuts/createManualInvoice"
model="invoiceOut"
:form-initial-data="manualInvoiceFormData"
@on-data-saved="onDataSaved"
>
<template #form-inputs="{ data }">
<span v-if="isLoading" class="text-primary invoicing-text">
<QIcon name="warning" class="fill-icon q-mr-sm" size="md" />
{{ t('Invoicing in progress...') }}
</span>
<VnRow class="row q-gutter-md q-mb-md">
<VnSelect
:label="t('Ticket')"
:options="ticketsOptions"
hide-selected
option-label="id"
option-value="id"
v-model="data.ticketFk"
@update:model-value="data.clientFk = null"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel> #{{ scope.opt?.id }} </QItemLabel>
<QItemLabel caption>{{ scope.opt?.nickname }}</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
<span class="row items-center" style="max-width: max-content">{{
t('Or')
}}</span>
<VnSelect
:label="t('Client')"
:options="clientsOptions"
hide-selected
option-label="name"
option-value="id"
v-model="data.clientFk"
@update:model-value="data.ticketFk = null"
/>
<VnInputDate :label="t('Max date')" v-model="data.maxShipped" />
</VnRow>
<VnRow class="row q-gutter-md q-mb-md">
<VnSelect
:label="t('Serial')"
:options="invoiceOutSerialsOptions"
hide-selected
option-label="description"
option-value="code"
v-model="data.serial"
:required="true"
/>
<VnSelect
:label="t('Area')"
:options="taxAreasOptions"
hide-selected
option-label="code"
option-value="code"
v-model="data.taxArea"
:required="true"
/>
</VnRow>
<VnRow class="row q-gutter-md q-mb-md">
<VnInput
:label="t('Reference')"
type="textarea"
v-model="data.reference"
fill-input
autogrow
/>
</VnRow>
</template>
</FormModelPopup>
</template>
<style lang="scss" scoped>
.invoicing-text {
display: flex;
justify-content: center;
align-items: center;
color: $primary;
font-size: 24px;
margin-bottom: 8px;
}
</style>
<i18n>
es:
Create manual invoice: Crear factura manual
Ticket: Ticket
Client: Cliente
Max date: Fecha límite
Serial: Serie
Area: Area
Reference: Referencia
Or: O
Invoicing in progress...: Facturación en progreso...
</i18n>

View File

@ -1,62 +1,58 @@
<script setup> <script setup>
import { onMounted, ref } from 'vue'; import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import VnSelectProvince from 'components/VnSelectProvince.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import FormModelPopup from './FormModelPopup.vue'; import FormModelPopup from './FormModelPopup.vue';
const emit = defineEmits(['onDataSaved']); const emit = defineEmits(['onDataSaved']);
const $props = defineProps({
countryFk: {
type: Number,
default: null,
},
provinceSelected: {
type: Number,
default: null,
},
});
const { t } = useI18n(); const { t } = useI18n();
const cityFormData = ref({ const cityFormData = reactive({
name: null, name: null,
provinceFk: null, provinceFk: null,
}); });
onMounted(() => {
cityFormData.value.provinceFk = $props.provinceSelected; const provincesOptions = ref([]);
});
const onDataSaved = (...args) => { const onDataSaved = (dataSaved) => {
emit('onDataSaved', ...args); emit('onDataSaved', dataSaved);
}; };
</script> </script>
<template> <template>
<FetchData
@on-fetch="(data) => (provincesOptions = data)"
auto-load
url="Provinces"
/>
<FormModelPopup <FormModelPopup
:title="t('New city')" :title="t('New city')"
:subtitle="t('Please, ensure you put the correct data!')" :subtitle="t('Please, ensure you put the correct data!')"
:form-initial-data="cityFormData" :form-initial-data="cityFormData"
url-create="towns" url-create="towns"
model="city" model="city"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved($event)"
data-cy="newCityForm"
> >
<template #form-inputs="{ data, validate }"> <template #form-inputs="{ data, validate }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput <VnInput
:label="t('Name')" :label="t('Name')"
v-model="data.name" v-model="data.name"
:rules="validate('city.name')" :rules="validate('city.name')"
required
data-cy="cityName"
/> />
<VnSelectProvince <VnSelect
:province-selected="$props.provinceSelected" :label="t('Province')"
:country-fk="$props.countryFk" :options="provincesOptions"
hide-selected
option-label="name"
option-value="id"
v-model="data.provinceFk" v-model="data.provinceFk"
required :rules="validate('city.provinceFk')"
data-cy="provinceCity"
/> />
</VnRow> </VnRow>
</template> </template>

View File

@ -1,50 +0,0 @@
<script setup>
import { useI18n } from 'vue-i18n';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import FormModelPopup from './FormModelPopup.vue';
const emit = defineEmits(['onDataSaved']);
const { t } = useI18n();
</script>
<template>
<FormModelPopup
url-create="Expenses"
model="Expense"
:title="t('New expense')"
:form-initial-data="{ id: null, isWithheld: false, name: null }"
@on-data-saved="emit('onDataSaved', $event)"
>
<template #form-inputs="{ data, validate }">
<VnRow>
<VnInput
:label="`${t('globals.code')}`"
v-model="data.id"
:required="true"
:rules="validate('expense.code')"
/>
<QCheckbox
dense
size="sm"
:label="`${t('It\'s a withholding')}`"
v-model="data.isWithheld"
:rules="validate('expense.isWithheld')"
/>
</VnRow>
<VnRow>
<VnInput
:label="`${t('globals.description')}`"
v-model="data.name"
:required="true"
:rules="validate('expense.description')"
/>
</VnRow>
</template>
</FormModelPopup>
</template>
<i18n>
es:
New expense: Nuevo gasto
It's a withholding: Es una retención
</i18n>

View File

@ -5,9 +5,9 @@ import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectProvince from 'src/components/VnSelectProvince.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import CreateNewCityForm from './CreateNewCityForm.vue'; import CreateNewCityForm from './CreateNewCityForm.vue';
import CreateNewProvinceForm from './CreateNewProvinceForm.vue';
import VnSelectDialog from 'components/common/VnSelectDialog.vue'; import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import FormModelPopup from './FormModelPopup.vue'; import FormModelPopup from './FormModelPopup.vue';
@ -21,202 +21,123 @@ const postcodeFormData = reactive({
provinceFk: null, provinceFk: null,
townFk: null, townFk: null,
}); });
const townsFetchDataRef = ref(false);
const townFilter = ref({});
const countriesRef = ref(false); const townsFetchDataRef = ref(null);
const provincesFetchDataRef = ref(null);
const countriesOptions = ref([]);
const provincesOptions = ref([]); const provincesOptions = ref([]);
const townsOptions = ref([]); const townsLocationOptions = ref([]);
const town = ref({});
const countryFilter = ref({});
function onDataSaved(formData) { const onDataSaved = (formData) => {
const newPostcode = { const newPostcode = {
...formData, ...formData,
}; };
newPostcode.town = town.value.name; const townObject = townsLocationOptions.value.find(
newPostcode.townFk = town.value.id; ({ id }) => id === formData.townFk
);
newPostcode.town = townObject?.name;
const provinceObject = provincesOptions.value.find( const provinceObject = provincesOptions.value.find(
({ id }) => id === formData.provinceFk ({ id }) => id === formData.provinceFk
); );
newPostcode.province = provinceObject?.name; newPostcode.province = provinceObject?.name;
const countryObject = countriesRef.value.opts.find( const countryObject = countriesOptions.value.find(
({ id }) => id === formData.countryFk ({ id }) => id === formData.countryFk
); );
newPostcode.country = countryObject?.name; newPostcode.country = countryObject?.country;
emit('onDataSaved', newPostcode); emit('onDataSaved', newPostcode);
} };
async function setCountry(countryFk, data) { const onCityCreated = async ({ name, provinceFk }, formData) => {
data.townFk = null; await townsFetchDataRef.value.fetch();
data.provinceFk = null; formData.townFk = townsLocationOptions.value.find((town) => town.name === name).id;
data.countryFk = countryFk; formData.provinceFk = provinceFk;
await fetchTowns(); formData.countryFk = provincesOptions.value.find(
} (province) => province.id === provinceFk
).countryFk;
};
// Province const onProvinceCreated = async ({ name }, formData) => {
await provincesFetchDataRef.value.fetch();
async function handleProvinces(data) { formData.provinceFk = provincesOptions.value.find(
provincesOptions.value = data; (province) => province.name === name
if (postcodeFormData.countryFk) { ).id;
await fetchTowns(); };
}
}
async function setProvince(id, data) {
if (data.provinceFk === id) return;
const newProvince = provincesOptions.value.find((province) => province.id == id);
if (newProvince) data.countryFk = newProvince.countryFk;
postcodeFormData.provinceFk = id;
await fetchTowns();
}
async function onProvinceCreated(data) {
postcodeFormData.provinceFk = data.id;
}
function provinceByCountry(countryFk = postcodeFormData.countryFk) {
return provincesOptions.value
.filter((province) => province.countryFk === countryFk)
.map(({ id }) => id);
}
// Town
async function handleTowns(data) {
townsOptions.value = data;
}
function setTown(newTown, data) {
town.value = newTown;
data.provinceFk = newTown?.provinceFk ?? newTown;
data.countryFk = newTown?.province?.countryFk ?? newTown;
}
async function onCityCreated(newTown, formData) {
newTown.province = provincesOptions.value.find(
(province) => province.id === newTown.provinceFk
);
formData.townFk = newTown;
setTown(newTown, formData);
}
async function fetchTowns(countryFk = postcodeFormData.countryFk) {
if (!countryFk) return;
const provinces = postcodeFormData.provinceFk
? [postcodeFormData.provinceFk]
: provinceByCountry();
townFilter.value.where = {
provinceFk: {
inq: provinces,
},
};
await townsFetchDataRef.value?.fetch();
}
async function filterTowns(name) {
if (name !== '') {
townFilter.value.where = {
name: {
like: `%${name}%`,
},
};
await townsFetchDataRef.value?.fetch();
}
}
</script> </script>
<template> <template>
<FetchData <FetchData
ref="townsFetchDataRef" ref="townsFetchDataRef"
:sort-by="['name ASC']" @on-fetch="(data) => (townsLocationOptions = data)"
:limit="30"
:filter="townFilter"
@on-fetch="handleTowns"
auto-load auto-load
url="Towns/location" url="Towns/location"
/> />
<FetchData
ref="provincesFetchDataRef"
@on-fetch="(data) => (provincesOptions = data)"
auto-load
url="Provinces"
/>
<FetchData
@on-fetch="(data) => (countriesOptions = data)"
auto-load
url="Countries"
/>
<FormModelPopup <FormModelPopup
url-create="postcodes" url-create="postcodes"
model="postcode" model="postcode"
:title="t('New postcode')" :title="t('New postcode')"
:subtitle="t('Please, ensure you put the correct data!')" :subtitle="t('Please, ensure you put the correct data!')"
:form-initial-data="postcodeFormData" :form-initial-data="postcodeFormData"
:mapper="(data) => (data.townFk = data.townFk.id) && data"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved"
> >
<template #form-inputs="{ data, validate }"> <template #form-inputs="{ data, validate }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput <VnInput
:label="t('Postcode')" :label="t('Postcode')"
v-model="data.code" v-model="data.code"
:rules="validate('postcode.code')" :rules="validate('postcode.code')"
clearable
required
data-cy="locationPostcode"
/> />
<VnSelectDialog <VnSelectDialog
:label="t('City')" :label="t('City')"
@update:model-value="(value) => setTown(value, data)" :options="townsLocationOptions"
@filter="filterTowns"
:tooltip="t('Create city')"
v-model="data.townFk" v-model="data.townFk"
:options="townsOptions" hide-selected
option-label="name" option-label="name"
option-value="id" option-value="id"
:rules="validate('postcode.city')" :rules="validate('postcode.city')"
:acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]" :roles-allowed-to-create="['deliveryAssistant']"
:emit-value="false"
required
data-cy="locationTown"
> >
<template #option="{ itemProps, opt }">
<QItem v-bind="itemProps">
<QItemSection>
<QItemLabel>{{ opt.name }}</QItemLabel>
<QItemLabel caption>
{{ opt.province.name }},
{{ opt.province.country.name }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
<template #form> <template #form>
<CreateNewCityForm <CreateNewCityForm @on-data-saved="onCityCreated($event, data)" />
:country-fk="data.countryFk"
:province-selected="data.provinceFk"
@on-data-saved="
(_, requestResponse) =>
onCityCreated(requestResponse, data)
"
/>
</template> </template>
</VnSelectDialog> </VnSelectDialog>
</VnRow> </VnRow>
<VnRow> <VnRow class="row q-gutter-md q-mb-xl">
<VnSelectProvince <VnSelectDialog
:country-fk="data.countryFk" :label="t('Province')"
:province-selected="data.provinceFk" :options="provincesOptions"
@update:model-value="(value) => setProvince(value, data)" hide-selected
@update:options=" option-label="name"
(data) => { option-value="id"
provincesOptions = data;
}
"
v-model="data.provinceFk" v-model="data.provinceFk"
@on-province-created="onProvinceCreated" :rules="validate('postcode.provinceFk')"
required :roles-allowed-to-create="['deliveryAssistant']"
/> >
<VnSelect <template #form>
ref="countriesRef" <CreateNewProvinceForm
:limit="30" @on-data-saved="onProvinceCreated($event, data)"
:filter="countryFilter" />
:sort-by="['name ASC']" </template> </VnSelectDialog
auto-load ></VnRow>
url="Countries" <VnRow class="row q-gutter-md q-mb-xl"
required ><VnSelect
:label="t('Country')" :label="t('Country')"
:options="countriesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
option-value="id" option-value="id"
v-model="data.countryFk" v-model="data.countryFk"
:rules="validate('postcode.countryFk')" :rules="validate('postcode.countryFk')"
@update:model-value="(value) => setCountry(value, data)"
data-cy="locationCountry"
/> />
</VnRow> </VnRow>
</template> </template>
@ -226,7 +147,6 @@ async function filterTowns(name) {
<i18n> <i18n>
es: es:
New postcode: Nuevo código postal New postcode: Nuevo código postal
Create city: Crear población
Please, ensure you put the correct data!: ¡Por favor, asegúrese de poner los datos correctos! Please, ensure you put the correct data!: ¡Por favor, asegúrese de poner los datos correctos!
City: Población City: Población
Province: Provincia Province: Provincia

View File

@ -1,7 +1,8 @@
<script setup> <script setup>
import { computed, reactive, ref } from 'vue'; import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
@ -15,71 +16,44 @@ const provinceFormData = reactive({
name: null, name: null,
autonomyFk: null, autonomyFk: null,
}); });
const $props = defineProps({
countryFk: {
type: Number,
default: null,
},
});
const autonomiesRef = ref([]);
const onDataSaved = (dataSaved, requestResponse) => { const autonomiesOptions = ref([]);
requestResponse.autonomy = autonomiesRef.value.opts.find(
(autonomy) => autonomy.id == requestResponse.autonomyFk const onDataSaved = (dataSaved) => {
); emit('onDataSaved', dataSaved);
emit('onDataSaved', dataSaved, requestResponse);
}; };
const where = computed(() => {
if (!$props.countryFk) {
return {};
}
return { countryFk: $props.countryFk };
});
</script> </script>
<template> <template>
<FetchData
@on-fetch="(data) => (autonomiesOptions = data)"
auto-load
url="Autonomies"
/>
<FormModelPopup <FormModelPopup
:title="t('New province')" :title="t('New province')"
:subtitle="t('Please, ensure you put the correct data!')" :subtitle="t('Please, ensure you put the correct data!')"
url-create="provinces" url-create="provinces"
model="province" model="province"
:form-initial-data="provinceFormData" :form-initial-data="provinceFormData"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved($event)"
> >
<template #form-inputs="{ data, validate }"> <template #form-inputs="{ data, validate }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput <VnInput
:label="t('Name')" :label="t('Name')"
v-model="data.name" v-model="data.name"
:rules="validate('province.name')" :rules="validate('province.name')"
required
data-cy="provinceName"
/> />
<VnSelect <VnSelect
data-cy="autonomyProvince"
required
ref="autonomiesRef"
auto-load
:where="where"
url="Autonomies/location"
:sort-by="['name ASC']"
:limit="30"
:label="t('Autonomy')" :label="t('Autonomy')"
:options="autonomiesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
option-value="id" option-value="id"
v-model="data.autonomyFk" v-model="data.autonomyFk"
:rules="validate('province.autonomyFk')" :rules="validate('province.autonomyFk')"
> />
<template #option="{ itemProps, opt }">
<QItem v-bind="itemProps">
<QItemSection>
<QItemLabel>{{ opt.name }}</QItemLabel>
<QItemLabel caption> {{ opt.country.name }} </QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</VnRow> </VnRow>
</template> </template>
</FormModelPopup> </FormModelPopup>

View File

@ -38,7 +38,7 @@ const onDataSaved = (dataSaved) => {
@on-fetch="(data) => (warehousesOptions = data)" @on-fetch="(data) => (warehousesOptions = data)"
auto-load auto-load
url="Warehouses" url="Warehouses"
:filter="{ fields: ['id', 'name'], order: 'name ASC' }" :filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
/> />
<FetchData <FetchData
@on-fetch="(data) => (temperaturesOptions = data)" @on-fetch="(data) => (temperaturesOptions = data)"
@ -50,10 +50,10 @@ const onDataSaved = (dataSaved) => {
model="thermograph" model="thermograph"
:title="t('New thermograph')" :title="t('New thermograph')"
:form-initial-data="thermographFormData" :form-initial-data="thermographFormData"
@on-data-saved="(_, response) => onDataSaved(response)" @on-data-saved="onDataSaved($event)"
> >
<template #form-inputs="{ data, validate }"> <template #form-inputs="{ data, validate }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput <VnInput
:label="t('Identifier')" :label="t('Identifier')"
v-model="data.thermographId" v-model="data.thermographId"

View File

@ -1,7 +1,7 @@
<script setup> <script setup>
import axios from 'axios'; import axios from 'axios';
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router'; import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import { useValidator } from 'src/composables/useValidator'; import { useValidator } from 'src/composables/useValidator';
@ -10,7 +10,6 @@ import VnPaginate from 'components/ui/VnPaginate.vue';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnConfirm from 'components/ui/VnConfirm.vue';
import SkeletonTable from 'components/ui/SkeletonTable.vue'; import SkeletonTable from 'components/ui/SkeletonTable.vue';
import { tMobile } from 'src/composables/tMobile'; import { tMobile } from 'src/composables/tMobile';
import getDifferences from 'src/filters/getDifferences';
const { push } = useRouter(); const { push } = useRouter();
const quasar = useQuasar(); const quasar = useQuasar();
@ -68,7 +67,7 @@ const $props = defineProps({
default: '', default: '',
description: 'It is used for redirect on click "save and continue"', description: 'It is used for redirect on click "save and continue"',
}, },
hasSubToolbar: { hasSubtoolbar: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
@ -78,7 +77,7 @@ const isLoading = ref(false);
const hasChanges = ref(false); const hasChanges = ref(false);
const originalData = ref(); const originalData = ref();
const vnPaginateRef = ref(); const vnPaginateRef = ref();
const formData = ref([]); const formData = ref();
const saveButtonRef = ref(null); const saveButtonRef = ref(null);
const watchChanges = ref(); const watchChanges = ref();
const formUrl = computed(() => $props.url); const formUrl = computed(() => $props.url);
@ -95,35 +94,23 @@ defineExpose({
saveChanges, saveChanges,
getChanges, getChanges,
formData, formData,
originalData,
vnPaginateRef, vnPaginateRef,
}); });
onBeforeRouteLeave((to, from, next) => {
if (hasChanges.value)
quasar.dialog({
component: VnConfirm,
componentProps: {
title: t('globals.unsavedPopup.title'),
message: t('globals.unsavedPopup.subtitle'),
promise: () => next(),
},
});
else next();
});
async function fetch(data) { async function fetch(data) {
if (data && Array.isArray(data)) {
let $index = 0;
data.map((d) => (d.$index = $index++));
}
resetData(data); resetData(data);
emit('onFetch', data); emit('onFetch', data);
return data; return data;
} }
function resetData(data) { function resetData(data) {
if (!data) return; if (!data) return;
if (data && Array.isArray(data)) {
let $index = 0;
data.map((d) => (d.$index = $index++));
}
originalData.value = JSON.parse(JSON.stringify(data)); originalData.value = JSON.parse(JSON.stringify(data));
formData.value = JSON.parse(JSON.stringify(data)); formData.value = JSON.parse(JSON.stringify(data));
@ -176,13 +163,14 @@ async function saveChanges(data) {
const changes = data || getChanges(); const changes = data || getChanges();
try { try {
await axios.post($props.saveUrl || $props.url + '/crud', changes); await axios.post($props.saveUrl || $props.url + '/crud', changes);
} finally { } catch (e) {
isLoading.value = false; return (isLoading.value = false);
} }
originalData.value = JSON.parse(JSON.stringify(formData.value)); originalData.value = JSON.parse(JSON.stringify(formData.value));
if (changes.creates?.length) await vnPaginateRef.value.fetch(); if (changes.creates?.length) await vnPaginateRef.value.fetch();
hasChanges.value = false; hasChanges.value = false;
isLoading.value = false;
emit('saveChanges', data); emit('saveChanges', data);
quasar.notify({ quasar.notify({
type: 'positive', type: 'positive',
@ -190,11 +178,11 @@ async function saveChanges(data) {
}); });
} }
async function insert(pushData = $props.dataRequired) { async function insert() {
const $index = formData.value.length const $index = formData.value.length
? formData.value[formData.value.length - 1].$index + 1 ? formData.value[formData.value.length - 1].$index + 1
: 0; : 0;
formData.value.push(Object.assign({ $index }, pushData)); formData.value.push(Object.assign({ $index }, $props.dataRequired));
hasChanges.value = true; hasChanges.value = true;
} }
@ -235,8 +223,6 @@ async function remove(data) {
newData = newData.filter((form) => !ids.some((id) => id == form[pk])); newData = newData.filter((form) => !ids.some((id) => id == form[pk]));
fetch(newData); fetch(newData);
}); });
} else {
reset();
} }
emit('update:selected', []); emit('update:selected', []);
} }
@ -249,7 +235,7 @@ function getChanges() {
for (const [i, row] of formData.value.entries()) { for (const [i, row] of formData.value.entries()) {
if (!row[pk]) { if (!row[pk]) {
creates.push(row); creates.push(row);
} else if (originalData.value[i]) { } else if (originalData.value) {
const data = getDifferences(originalData.value[i], row); const data = getDifferences(originalData.value[i], row);
if (!isEmpty(data)) { if (!isEmpty(data)) {
updates.push({ updates.push({
@ -268,6 +254,28 @@ function getChanges() {
return changes; return changes;
} }
function getDifferences(obj1, obj2) {
let diff = {};
delete obj1.$index;
delete obj2.$index;
for (let key in obj1) {
if (obj2[key] && JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])) {
diff[key] = obj2[key];
}
}
for (let key in obj2) {
if (
obj1[key] === undefined ||
JSON.stringify(obj1[key]) !== JSON.stringify(obj2[key])
) {
diff[key] = obj2[key];
}
}
return diff;
}
function isEmpty(obj) { function isEmpty(obj) {
if (obj == null) return true; if (obj == null) return true;
if (obj === undefined) return true; if (obj === undefined) return true;
@ -291,7 +299,7 @@ watch(formUrl, async () => {
:url="url" :url="url"
:limit="limit" :limit="limit"
@on-fetch="fetch" @on-fetch="fetch"
@on-change="fetch" @on-change="resetData"
:skeleton="false" :skeleton="false"
ref="vnPaginateRef" ref="vnPaginateRef"
v-bind="$attrs" v-bind="$attrs"
@ -305,11 +313,8 @@ watch(formUrl, async () => {
></slot> ></slot>
</template> </template>
</VnPaginate> </VnPaginate>
<SkeletonTable <SkeletonTable v-if="!formData" :columns="$attrs.columns?.length" />
v-if="!formData && $attrs.autoLoad" <Teleport to="#st-actions" v-if="stateStore?.isSubToolbarShown() && hasSubtoolbar">
:columns="$attrs.columns?.length"
/>
<Teleport to="#st-actions" v-if="stateStore?.isSubToolbarShown() && hasSubToolbar">
<QBtnGroup push style="column-gap: 10px"> <QBtnGroup push style="column-gap: 10px">
<slot name="moreBeforeActions" /> <slot name="moreBeforeActions" />
<QBtn <QBtn
@ -373,7 +378,6 @@ watch(formUrl, async () => {
@click="onSubmit" @click="onSubmit"
:disable="!hasChanges" :disable="!hasChanges"
:title="t('globals.save')" :title="t('globals.save')"
data-cy="crudModelDefaultSaveBtn"
/> />
<slot name="moreAfterActions" /> <slot name="moreAfterActions" />
</QBtnGroup> </QBtnGroup>

View File

@ -156,22 +156,26 @@ const rotateRight = () => {
}; };
const onSubmit = () => { const onSubmit = () => {
if (!newPhoto.files && !newPhoto.url) { try {
notify(t('Select an image'), 'negative'); if (!newPhoto.files && !newPhoto.url) {
return; notify(t('Select an image'), 'negative');
return;
}
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
} catch (err) {
console.error('Error uploading image');
} }
const options = {
type: 'blob',
};
editor.value
.result(options)
.then((result) => {
const file = new File([result], newPhoto.files?.name || '');
newPhoto.blob = file;
})
.then(() => makeRequest());
}; };
const makeRequest = async () => { const makeRequest = async () => {
@ -241,14 +245,14 @@ const makeRequest = async () => {
</div> </div>
<div class="column"> <div class="column">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<QOptionGroup <QOptionGroup
:options="uploadMethodsOptions" :options="uploadMethodsOptions"
type="radio" type="radio"
v-model="uploadMethodSelected" v-model="uploadMethodSelected"
/> />
</VnRow> </VnRow>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<QFile <QFile
v-if="uploadMethodSelected === 'computer'" v-if="uploadMethodSelected === 'computer'"
ref="inputFileRef" ref="inputFileRef"
@ -283,7 +287,7 @@ const makeRequest = async () => {
placeholder="https://" placeholder="https://"
/> />
</VnRow> </VnRow>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnSelect <VnSelect
:label="t('Orientation')" :label="t('Orientation')"
:options="viewportTypes" :options="viewportTypes"

View File

@ -51,17 +51,21 @@ const onDataSaved = () => {
}; };
const onSubmit = async () => { const onSubmit = async () => {
isLoading.value = true; try {
const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk })); isLoading.value = true;
const payload = { const rowsToEdit = $props.rows.map((row) => ({ id: row.id, itemFk: row.itemFk }));
field: selectedField.value.field, const payload = {
newValue: newValue.value, field: selectedField.value.field,
lines: rowsToEdit, newValue: newValue.value,
}; lines: rowsToEdit,
};
await axios.post($props.editUrl, payload); await axios.post($props.editUrl, payload);
onDataSaved(); onDataSaved();
isLoading.value = false; isLoading.value = false;
} catch (err) {
console.error('Error submitting table cell edit');
}
}; };
const closeForm = () => { const closeForm = () => {
@ -78,21 +82,19 @@ const closeForm = () => {
<span class="title">{{ t('Edit') }}</span> <span class="title">{{ t('Edit') }}</span>
<span class="countLines">{{ ` ${rows.length} ` }}</span> <span class="countLines">{{ ` ${rows.length} ` }}</span>
<span class="title">{{ t('buy(s)') }}</span> <span class="title">{{ t('buy(s)') }}</span>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnSelect <VnSelect
:label="t('Field to edit')" :label="t('Field to edit')"
:options="fieldsOptions" :options="fieldsOptions"
hide-selected hide-selected
option-label="label" option-label="label"
v-model="selectedField" v-model="selectedField"
data-cy="field-to-edit"
/> />
<component <component
:is="inputs[selectedField?.component || 'input']" :is="inputs[selectedField?.component || 'input']"
v-bind="selectedField?.attrs || {}" v-bind="selectedField?.attrs || {}"
v-model="newValue" v-model="newValue"
:label="t('Value')" :label="t('Value')"
data-cy="value-to-edit"
style="width: 200px" style="width: 200px"
/> />
</VnRow> </VnRow>

View File

@ -44,7 +44,7 @@ onMounted(async () => {
async function fetch(fetchFilter = {}) { async function fetch(fetchFilter = {}) {
try { try {
const filter = { ...fetchFilter, ...$props.filter }; // eslint-disable-line vue/no-dupe-keys const filter = Object.assign(fetchFilter, $props.filter); // eslint-disable-line vue/no-dupe-keys
if ($props.where && !fetchFilter.where) filter.where = $props.where; if ($props.where && !fetchFilter.where) filter.where = $props.where;
if ($props.sortBy) filter.order = $props.sortBy; if ($props.sortBy) filter.order = $props.sortBy;
if ($props.limit) filter.limit = $props.limit; if ($props.limit) filter.limit = $props.limit;

View File

@ -50,25 +50,25 @@ const loading = ref(false);
const tableColumns = computed(() => [ const tableColumns = computed(() => [
{ {
label: t('globals.id'), label: t('entry.buys.id'),
name: 'id', name: 'id',
field: 'id', field: 'id',
align: 'left', align: 'left',
}, },
{ {
label: t('globals.name'), label: t('entry.buys.name'),
name: 'name', name: 'name',
field: 'name', field: 'name',
align: 'left', align: 'left',
}, },
{ {
label: t('globals.size'), label: t('entry.buys.size'),
name: 'size', name: 'size',
field: 'size', field: 'size',
align: 'left', align: 'left',
}, },
{ {
label: t('globals.producer'), label: t('entry.buys.producer'),
name: 'producerName', name: 'producerName',
field: 'producer', field: 'producer',
align: 'left', align: 'left',
@ -84,30 +84,34 @@ const tableColumns = computed(() => [
]); ]);
const onSubmit = async () => { const onSubmit = async () => {
let filter = itemFilter; try {
const params = itemFilterParams; let filter = itemFilter;
const where = {}; const params = itemFilterParams;
for (let key in params) { const where = {};
const value = params[key]; for (let key in params) {
if (!value) continue; const value = params[key];
if (!value) continue;
switch (key) { switch (key) {
case 'name': case 'name':
where[key] = { like: `%${value}%` }; where[key] = { like: `%${value}%` };
break; break;
case 'producerFk': case 'producerFk':
case 'typeFk': case 'typeFk':
case 'size': case 'size':
case 'inkFk': case 'inkFk':
where[key] = value; where[key] = value;
}
} }
} filter.where = where;
filter.where = where;
const { data } = await axios.get(props.url, { const { data } = await axios.get(props.url, {
params: { filter: JSON.stringify(filter) }, params: { filter: JSON.stringify(filter) },
}); });
tableRows.value = data; tableRows.value = data;
} catch (err) {
console.error('Error fetching entries items');
}
}; };
const closeForm = () => { const closeForm = () => {
@ -147,11 +151,11 @@ const selectItem = ({ id }) => {
<QIcon name="close" size="sm" /> <QIcon name="close" size="sm" />
</span> </span>
<h1 class="title">{{ t('Filter item') }}</h1> <h1 class="title">{{ t('Filter item') }}</h1>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnInput :label="t('globals.name')" v-model="itemFilterParams.name" /> <VnInput :label="t('entry.buys.name')" v-model="itemFilterParams.name" />
<VnInput :label="t('entry.buys.size')" v-model="itemFilterParams.size" /> <VnInput :label="t('entry.buys.size')" v-model="itemFilterParams.size" />
<VnSelect <VnSelect
:label="t('globals.producer')" :label="t('entry.buys.producer')"
:options="producersOptions" :options="producersOptions"
hide-selected hide-selected
option-label="name" option-label="name"
@ -159,7 +163,7 @@ const selectItem = ({ id }) => {
v-model="itemFilterParams.producerFk" v-model="itemFilterParams.producerFk"
/> />
<VnSelect <VnSelect
:label="t('globals.type')" :label="t('entry.buys.type')"
:options="ItemTypesOptions" :options="ItemTypesOptions"
hide-selected hide-selected
option-label="name" option-label="name"

View File

@ -48,13 +48,13 @@ const loading = ref(false);
const tableColumns = computed(() => [ const tableColumns = computed(() => [
{ {
label: t('globals.id'), label: t('entry.basicData.id'),
name: 'id', name: 'id',
field: 'id', field: 'id',
align: 'left', align: 'left',
}, },
{ {
label: t('globals.warehouseOut'), label: t('entry.basicData.warehouseOut'),
name: 'warehouseOutFk', name: 'warehouseOutFk',
field: 'warehouseOutFk', field: 'warehouseOutFk',
align: 'left', align: 'left',
@ -62,7 +62,7 @@ const tableColumns = computed(() => [
warehousesOptions.value.find((warehouse) => warehouse.id === val).name, warehousesOptions.value.find((warehouse) => warehouse.id === val).name,
}, },
{ {
label: t('globals.warehouseIn'), label: t('entry.basicData.warehouseIn'),
name: 'warehouseInFk', name: 'warehouseInFk',
field: 'warehouseInFk', field: 'warehouseInFk',
align: 'left', align: 'left',
@ -70,14 +70,14 @@ const tableColumns = computed(() => [
warehousesOptions.value.find((warehouse) => warehouse.id === val).name, warehousesOptions.value.find((warehouse) => warehouse.id === val).name,
}, },
{ {
label: t('globals.shipped'), label: t('entry.basicData.shipped'),
name: 'shipped', name: 'shipped',
field: 'shipped', field: 'shipped',
align: 'left', align: 'left',
format: (val) => toDate(val), format: (val) => toDate(val),
}, },
{ {
label: t('globals.landed'), label: t('entry.basicData.landed'),
name: 'landed', name: 'landed',
field: 'landed', field: 'landed',
align: 'left', align: 'left',
@ -86,28 +86,32 @@ const tableColumns = computed(() => [
]); ]);
const onSubmit = async () => { const onSubmit = async () => {
let filter = travelFilter; try {
const params = travelFilterParams; let filter = travelFilter;
const where = {}; const params = travelFilterParams;
for (let key in params) { const where = {};
const value = params[key]; for (let key in params) {
if (!value) continue; const value = params[key];
if (!value) continue;
switch (key) { switch (key) {
case 'agencyModeFk': case 'agencyModeFk':
case 'warehouseInFk': case 'warehouseInFk':
case 'warehouseOutFk': case 'warehouseOutFk':
case 'shipped': case 'shipped':
case 'landed': case 'landed':
where[key] = value; where[key] = value;
}
} }
}
filter.where = where; filter.where = where;
const { data } = await axios.get('Travels', { const { data } = await axios.get('Travels', {
params: { filter: JSON.stringify(filter) }, params: { filter: JSON.stringify(filter) },
}); });
tableRows.value = data; tableRows.value = data;
} catch (err) {
console.error('Error fetching travels');
}
}; };
const closeForm = () => { const closeForm = () => {
@ -140,9 +144,9 @@ const selectTravel = ({ id }) => {
<QIcon name="close" size="sm" /> <QIcon name="close" size="sm" />
</span> </span>
<h1 class="title">{{ t('Filter travels') }}</h1> <h1 class="title">{{ t('Filter travels') }}</h1>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnSelect <VnSelect
:label="t('globals.agency')" :label="t('entry.basicData.agency')"
:options="agenciesOptions" :options="agenciesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
@ -150,7 +154,7 @@ const selectTravel = ({ id }) => {
v-model="travelFilterParams.agencyModeFk" v-model="travelFilterParams.agencyModeFk"
/> />
<VnSelect <VnSelect
:label="t('globals.warehouseOut')" :label="t('entry.basicData.warehouseOut')"
:options="warehousesOptions" :options="warehousesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
@ -158,7 +162,7 @@ const selectTravel = ({ id }) => {
v-model="travelFilterParams.warehouseOutFk" v-model="travelFilterParams.warehouseOutFk"
/> />
<VnSelect <VnSelect
:label="t('globals.warehouseIn')" :label="t('entry.basicData.warehouseIn')"
:options="warehousesOptions" :options="warehousesOptions"
hide-selected hide-selected
option-label="name" option-label="name"
@ -166,11 +170,11 @@ const selectTravel = ({ id }) => {
v-model="travelFilterParams.warehouseInFk" v-model="travelFilterParams.warehouseInFk"
/> />
<VnInputDate <VnInputDate
:label="t('globals.shipped')" :label="t('entry.basicData.shipped')"
v-model="travelFilterParams.shipped" v-model="travelFilterParams.shipped"
/> />
<VnInputDate <VnInputDate
:label="t('globals.landed')" :label="t('entry.basicData.landed')"
v-model="travelFilterParams.landed" v-model="travelFilterParams.landed"
/> />
</VnRow> </VnRow>

View File

@ -22,7 +22,7 @@ const { t } = useI18n();
const { validate } = useValidator(); const { validate } = useValidator();
const { notify } = useNotify(); const { notify } = useNotify();
const route = useRoute(); const route = useRoute();
const myForm = ref(null);
const $props = defineProps({ const $props = defineProps({
url: { url: {
type: String, type: String,
@ -87,14 +87,6 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
defaultTrim: {
type: Boolean,
default: true,
},
maxWidth: {
type: [String, Boolean],
default: '800px',
},
}); });
const emit = defineEmits(['onFetch', 'onDataSaved']); const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed( const modelValue = computed(
@ -108,21 +100,17 @@ const isResetting = ref(false);
const hasChanges = ref(!$props.observeFormChanges); const hasChanges = ref(!$props.observeFormChanges);
const originalData = ref({}); const originalData = ref({});
const formData = computed(() => state.get(modelValue)); const formData = computed(() => state.get(modelValue));
const formUrl = computed(() => $props.url);
const defaultButtons = computed(() => ({ const defaultButtons = computed(() => ({
save: { save: {
dataCy: 'saveDefaultBtn',
color: 'primary', color: 'primary',
icon: 'save', icon: 'save',
label: 'globals.save', label: 'globals.save',
click: () => myForm.value.submit(),
type: 'submit',
}, },
reset: { reset: {
dataCy: 'resetDefaultBtn',
color: 'primary', color: 'primary',
icon: 'restart_alt', icon: 'restart_alt',
label: 'globals.reset', label: 'globals.reset',
click: () => reset(),
}, },
...$props.defaultButtons, ...$props.defaultButtons,
})); }));
@ -160,22 +148,19 @@ if (!$props.url)
(val) => updateAndEmit('onFetch', val) (val) => updateAndEmit('onFetch', val)
); );
watch( watch(formUrl, async () => {
() => [$props.url, $props.filter], originalData.value = null;
async () => { reset();
originalData.value = null; await fetch();
reset(); });
await fetch();
}
);
onBeforeRouteLeave((to, from, next) => { onBeforeRouteLeave((to, from, next) => {
if (hasChanges.value && $props.observeFormChanges) if (hasChanges.value && $props.observeFormChanges)
quasar.dialog({ quasar.dialog({
component: VnConfirm, component: VnConfirm,
componentProps: { componentProps: {
title: t('globals.unsavedPopup.title'), title: t('Unsaved changes will be lost'),
message: t('globals.unsavedPopup.subtitle'), message: t('Are you sure exit without saving?'),
promise: () => next(), promise: () => next(),
}, },
}); });
@ -208,10 +193,7 @@ async function save() {
isLoading.value = true; isLoading.value = true;
try { try {
formData.value = trimData(formData.value); const body = $props.mapper ? $props.mapper(formData.value) : formData.value;
const body = $props.mapper
? $props.mapper(formData.value, originalData.value)
: formData.value;
const method = $props.urlCreate ? 'post' : 'patch'; const method = $props.urlCreate ? 'post' : 'patch';
const url = const url =
$props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url; $props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url;
@ -224,8 +206,11 @@ async function save() {
updateAndEmit('onDataSaved', formData.value, response?.data); updateAndEmit('onDataSaved', formData.value, response?.data);
if ($props.reload) await arrayData.fetch({}); if ($props.reload) await arrayData.fetch({});
hasChanges.value = false; } catch (err) {
console.error(err);
notify('errors.writeRequest', 'negative');
} finally { } finally {
hasChanges.value = false;
isLoading.value = false; isLoading.value = false;
} }
} }
@ -266,109 +251,93 @@ function updateAndEmit(evt, val, res) {
emit(evt, state.get(modelValue), res); emit(evt, state.get(modelValue), res);
} }
function trimData(data) {
if (!$props.defaultTrim) return data;
for (const key in data) {
if (typeof data[key] == 'string') data[key] = data[key].trim();
}
return data;
}
defineExpose({ defineExpose({
save, save,
isLoading, isLoading,
hasChanges, hasChanges,
reset, reset,
fetch, fetch,
formData,
}); });
</script> </script>
<template> <template>
<div class="column items-center full-width"> <div class="column items-center full-width">
<QForm <QForm
ref="myForm"
v-if="formData" v-if="formData"
@submit="save" @submit="save"
@reset="reset" @reset="reset"
class="q-pa-md" class="q-pa-md"
:style="maxWidth ? 'max-width: ' + maxWidth : ''"
id="formModel" id="formModel"
> >
<QCard> <QCard>
<slot <slot
v-if="formData"
name="form" name="form"
:data="formData" :data="formData"
:validate="validate" :validate="validate"
:filter="filter" :filter="filter"
/> />
<SkeletonForm v-else />
</QCard> </QCard>
</QForm> </QForm>
</div> </div>
<Teleport <Teleport
to="#st-actions" to="#st-actions"
v-if=" v-if="stateStore?.isSubToolbarShown() && componentIsRendered"
$props.defaultActions &&
stateStore?.isSubToolbarShown() &&
componentIsRendered
"
> >
<QBtnGroup push class="q-gutter-x-sm"> <div v-if="$props.defaultActions">
<slot name="moreActions" /> <QBtnGroup push class="q-gutter-x-sm">
<QBtn <slot name="moreActions" />
:label="tMobile(defaultButtons.reset.label)" <QBtn
:color="defaultButtons.reset.color" :label="tMobile(defaultButtons.reset.label)"
:icon="defaultButtons.reset.icon" :color="defaultButtons.reset.color"
flat :icon="defaultButtons.reset.icon"
@click="defaultButtons.reset.click" flat
:disable="!hasChanges" @click="reset"
:title="t(defaultButtons.reset.label)" :disable="!hasChanges"
/> :title="t(defaultButtons.reset.label)"
<QBtnDropdown />
data-cy="saveAndContinueDefaultBtn" <QBtnDropdown
v-if="$props.goTo" v-if="$props.goTo"
@click="saveAndGo" @click="saveAndGo"
:label="tMobile('globals.saveAndContinue')" :label="tMobile('globals.saveAndContinue')"
:title="t('globals.saveAndContinue')" :title="t('globals.saveAndContinue')"
:disable="!hasChanges" :disable="!hasChanges"
color="primary" color="primary"
icon="save" icon="save"
split split
> >
<QList> <QList>
<QItem <QItem
clickable clickable
v-close-popup v-close-popup
@click="save" @click="save"
:title="t('globals.save')" :title="t('globals.save')"
> >
<QItemSection> <QItemSection>
<QItemLabel> <QItemLabel>
<QIcon <QIcon
name="save" name="save"
color="white" color="white"
class="q-mr-sm" class="q-mr-sm"
size="sm" size="sm"
/> />
{{ t('globals.save').toUpperCase() }} {{ t('globals.save').toUpperCase() }}
</QItemLabel> </QItemLabel>
</QItemSection> </QItemSection>
</QItem> </QItem>
</QList> </QList>
</QBtnDropdown> </QBtnDropdown>
<QBtn <QBtn
v-else v-else
:label="tMobile('globals.save')" :label="tMobile('globals.save')"
color="primary" color="primary"
icon="save" icon="save"
@click="defaultButtons.save.click" @click="save"
:disable="!hasChanges" :disable="!hasChanges"
:title="t(defaultButtons.save.label)" :title="t(defaultButtons.save.label)"
/> />
</QBtnGroup> </QBtnGroup>
</div>
</Teleport> </Teleport>
<SkeletonForm v-if="!formData" />
<QInnerLoading <QInnerLoading
:showing="isLoading" :showing="isLoading"
:label="t('globals.pleaseWait')" :label="t('globals.pleaseWait')"
@ -381,6 +350,7 @@ defineExpose({
color: black; color: black;
} }
#formModel { #formModel {
max-width: 800px;
width: 100%; width: 100%;
} }
@ -388,3 +358,8 @@ defineExpose({
padding: 32px; padding: 32px;
} }
</style> </style>
<i18n>
es:
Unsaved changes will be lost: Los cambios que no haya guardado se perderán
Are you sure exit without saving?: ¿Seguro que quiere salir sin guardar?
</i18n>

View File

@ -23,15 +23,18 @@ const formModelRef = ref(null);
const closeButton = ref(null); const closeButton = ref(null);
const onDataSaved = (formData, requestResponse) => { const onDataSaved = (formData, requestResponse) => {
if (closeButton.value) closeButton.value.click(); closeForm();
emit('onDataSaved', formData, requestResponse); emit('onDataSaved', formData, requestResponse);
}; };
const isLoading = computed(() => formModelRef.value?.isLoading); const isLoading = computed(() => formModelRef.value?.isLoading);
const closeForm = async () => {
if (closeButton.value) closeButton.value.click();
};
defineExpose({ defineExpose({
isLoading, isLoading,
onDataSaved,
}); });
</script> </script>
@ -61,8 +64,6 @@ defineExpose({
:loading="isLoading" :loading="isLoading"
@click="emit('onDataCanceled')" @click="emit('onDataCanceled')"
v-close-popup v-close-popup
data-cy="FormModelPopup_cancel"
z-max
/> />
<QBtn <QBtn
:label="t('globals.save')" :label="t('globals.save')"
@ -72,8 +73,6 @@ defineExpose({
class="q-ml-sm" class="q-ml-sm"
:disabled="isLoading" :disabled="isLoading"
:loading="isLoading" :loading="isLoading"
data-cy="FormModelPopup_save"
z-max
/> />
</div> </div>
</template> </template>

View File

@ -4,7 +4,7 @@ import { useI18n } from 'vue-i18n';
const emit = defineEmits(['onSubmit']); const emit = defineEmits(['onSubmit']);
const $props = defineProps({ defineProps({
title: { title: {
type: String, type: String,
default: '', default: '',
@ -25,21 +25,16 @@ const $props = defineProps({
type: String, type: String,
default: '', default: '',
}, },
submitOnEnter: {
type: Boolean,
default: true,
},
}); });
const { t } = useI18n(); const { t } = useI18n();
const closeButton = ref(null); const closeButton = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const onSubmit = () => { const onSubmit = () => {
if ($props.submitOnEnter) { emit('onSubmit');
emit('onSubmit'); closeForm();
closeForm();
}
}; };
const closeForm = () => { const closeForm = () => {

View File

@ -9,8 +9,6 @@ import VnSelect from 'components/common/VnSelect.vue';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue'; import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
import axios from 'axios'; import axios from 'axios';
import { getParamWhere } from 'src/filters';
import { useRoute } from 'vue-router';
const { t } = useI18n(); const { t } = useI18n();
const props = defineProps({ const props = defineProps({
@ -28,22 +26,29 @@ const props = defineProps({
}, },
}); });
const route = useRoute(); const itemCategories = ref([]);
const selectedCategoryFk = ref(null);
const selectedTypeFk = ref(null);
const itemTypesOptions = ref([]); const itemTypesOptions = ref([]);
const suppliersOptions = ref([]); const suppliersOptions = ref([]);
const tagOptions = ref([]); const tagOptions = ref([]);
const tagValues = ref([]); const tagValues = ref([]);
const categoryList = ref(null);
const selectedCategoryFk = ref(getParamWhere(route.query.table, 'categoryFk', false));
const selectedTypeFk = ref(getParamWhere(route.query.table, 'typeFk', false));
const selectedCategory = computed(() => { const categoryList = computed(() => {
return (categoryList.value || []).find( return (itemCategories.value || [])
(category) => category?.id === selectedCategoryFk.value .filter((category) => category.display)
); .map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
}); });
const selectedCategory = computed(() =>
(itemCategories.value || []).find(
(category) => category?.id === selectedCategoryFk.value
)
);
const selectedType = computed(() => { const selectedType = computed(() => {
return (itemTypesOptions.value || []).find( return (itemTypesOptions.value || []).find(
(type) => type?.id === selectedTypeFk.value (type) => type?.id === selectedTypeFk.value
@ -82,17 +87,21 @@ const applyTags = (params, search) => {
search(); search();
}; };
const fetchItemTypes = async (id = selectedCategoryFk.value) => { const fetchItemTypes = async (id) => {
const filter = { try {
fields: ['id', 'name', 'categoryFk'], const filter = {
where: { categoryFk: id }, fields: ['id', 'name', 'categoryFk'],
include: 'category', where: { categoryFk: id },
order: 'name ASC', include: 'category',
}; order: 'name ASC',
const { data } = await axios.get('ItemTypes', { };
params: { filter: JSON.stringify(filter) }, const { data } = await axios.get('ItemTypes', {
}); params: { filter: JSON.stringify(filter) },
itemTypesOptions.value = data; });
itemTypesOptions.value = data;
} catch (err) {
console.error('Error fetching item types', err);
}
}; };
const getCategoryClass = (category, params) => { const getCategoryClass = (category, params) => {
@ -102,38 +111,37 @@ const getCategoryClass = (category, params) => {
}; };
const getSelectedTagValues = async (tag) => { const getSelectedTagValues = async (tag) => {
if (!tag?.selectedTag?.id) return; try {
tag.value = null; tag.value = null;
const filter = { const filter = {
fields: ['value'], fields: ['value'],
order: 'value ASC', order: 'value ASC',
limit: 30, limit: 30,
}; };
const params = { filter: JSON.stringify(filter) }; const params = { filter: JSON.stringify(filter) };
const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, { const { data } = await axios.get(`Tags/${tag.selectedTag.id}/filterValue`, {
params, params,
}); });
tag.valueOptions = data; tag.valueOptions = data;
} catch (err) {
console.error('Error getting selected tag values');
}
}; };
const removeTag = (index, params, search) => { const removeTag = (index, params, search) => {
(tagValues.value || []).splice(index, 1); (tagValues.value || []).splice(index, 1);
applyTags(params, search); applyTags(params, search);
}; };
const setCategoryList = (data) => {
categoryList.value = (data || [])
.filter((category) => category.display)
.map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
fetchItemTypes();
};
</script> </script>
<template> <template>
<FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" /> <FetchData
url="ItemCategories"
limit="30"
auto-load
@on-fetch="(data) => (itemCategories = data)"
/>
<FetchData <FetchData
url="Suppliers" url="Suppliers"
limit="30" limit="30"
@ -150,8 +158,8 @@ const setCategoryList = (data) => {
/> />
<VnFilterPanel <VnFilterPanel
:data-key="props.dataKey" :data-key="props.dataKey"
:expr-builder="props.exprBuilder" :expr-builder="exprBuilder"
:custom-tags="props.customTags" :custom-tags="customTags"
> >
<template #tags="{ tag, formatFn }"> <template #tags="{ tag, formatFn }">
<strong v-if="tag.label === 'categoryFk'"> <strong v-if="tag.label === 'categoryFk'">
@ -239,7 +247,7 @@ const setCategoryList = (data) => {
> >
<QItemSection class="col"> <QItemSection class="col">
<VnSelect <VnSelect
:label="t('globals.tag')" :label="t('components.itemsFilterPanel.tag')"
v-model="value.selectedTag" v-model="value.selectedTag"
:options="tagOptions" :options="tagOptions"
option-label="name" option-label="name"
@ -288,12 +296,11 @@ const setCategoryList = (data) => {
/> />
</QItem> </QItem>
<QItem class="q-mt-lg"> <QItem class="q-mt-lg">
<QBtn <QIcon
icon="add_circle" name="add_circle"
shortcut="+"
flat
class="fill-icon-on-hover q-px-xs" class="fill-icon-on-hover q-px-xs"
color="primary" color="primary"
size="sm"
@click="tagValues.push({})" @click="tagValues.push({})"
/> />
</QItem> </QItem>

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import axios from 'axios'; import axios from 'axios';
import { onMounted, watch, ref, reactive, computed } from 'vue'; import { onMounted, ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { QSeparator, useQuasar } from 'quasar'; import { QSeparator, useQuasar } from 'quasar';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
@ -9,7 +9,6 @@ import { toLowerCamel } from 'src/filters';
import routes from 'src/router/modules'; import routes from 'src/router/modules';
import LeftMenuItem from './LeftMenuItem.vue'; import LeftMenuItem from './LeftMenuItem.vue';
import LeftMenuItemGroup from './LeftMenuItemGroup.vue'; import LeftMenuItemGroup from './LeftMenuItemGroup.vue';
import VnInput from './common/VnInput.vue';
const { t } = useI18n(); const { t } = useI18n();
const route = useRoute(); const route = useRoute();
@ -22,58 +21,14 @@ const props = defineProps({
default: 'main', default: 'main',
}, },
}); });
const initialized = ref(false);
const items = ref([]);
const expansionItemElements = reactive({}); const expansionItemElements = reactive({});
const pinnedModules = computed(() => {
const map = new Map();
items.value.forEach((item) => item.isPinned && map.set(item.name, item));
return map;
});
const search = ref(null);
const filteredItems = computed(() => {
if (!search.value) return items.value;
const normalizedSearch = normalize(search.value);
return items.value.filter((item) => {
const locale = normalize(t(item.title));
return locale.includes(normalizedSearch);
});
});
const filteredPinnedModules = computed(() => {
if (!search.value) return pinnedModules.value;
const normalizedSearch = search.value
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
const map = new Map();
for (const [key, pinnedModule] of pinnedModules.value) {
const locale = t(pinnedModule.title)
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
if (locale.includes(normalizedSearch)) map.set(key, pinnedModule);
}
return map;
});
onMounted(async () => { onMounted(async () => {
await navigation.fetchPinned(); await navigation.fetchPinned();
getRoutes(); getRoutes();
initialized.value = true;
}); });
watch(
() => route.matched,
() => {
if (!initialized.value) return;
items.value = [];
getRoutes();
},
{ deep: true }
);
function findMatches(search, item) { function findMatches(search, item) {
const matches = []; const matches = [];
function findRoute(search, item) { function findRoute(search, item) {
@ -102,6 +57,7 @@ function addChildren(module, route, parent) {
} }
} }
const items = ref([]);
function getRoutes() { function getRoutes() {
if (props.source === 'main') { if (props.source === 'main') {
const modules = Object.assign([], navigation.getModules().value); const modules = Object.assign([], navigation.getModules().value);
@ -110,9 +66,10 @@ function getRoutes() {
const moduleDef = routes.find( const moduleDef = routes.find(
(route) => toLowerCamel(route.name) === item.module (route) => toLowerCamel(route.name) === item.module
); );
if (!moduleDef) continue;
item.children = []; item.children = [];
if (!moduleDef) continue;
addChildren(item.module, moduleDef, item.children); addChildren(item.module, moduleDef, item.children);
} }
@ -157,58 +114,21 @@ async function togglePinned(item, event) {
const handleItemExpansion = (itemName) => { const handleItemExpansion = (itemName) => {
expansionItemElements[itemName].scrollToLastElement(); expansionItemElements[itemName].scrollToLastElement();
}; };
function normalize(text) {
return text
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase();
}
</script> </script>
<template> <template>
<QList padding class="column-max-width"> <QList padding class="column-max-width">
<template v-if="$props.source === 'main'"> <template v-if="$props.source === 'main'">
<template v-if="$route?.matched[1]?.name === 'Dashboard'"> <template v-if="$route?.matched[1]?.name === 'Dashboard'">
<QItem class="q-pb-md"> <QItem class="header">
<VnInput <QItemSection avatar>
v-model="search" <QIcon name="view_module" />
:label="t('Search modules')" </QItemSection>
class="full-width" <QItemSection> {{ t('globals.modules') }}</QItemSection>
filled
dense
autofocus
/>
</QItem> </QItem>
<QSeparator /> <QSeparator />
<template v-if="filteredPinnedModules.size"> <template v-for="item in items" :key="item.name">
<LeftMenuItem <template v-if="item.children">
v-for="[key, pinnedModule] of filteredPinnedModules"
:key="key"
:item="pinnedModule"
group="modules"
>
<template #side>
<QBtn
v-if="pinnedModule.isPinned === true"
@click="togglePinned(pinnedModule, $event)"
icon="remove_circle"
size="xs"
flat
round
>
<QTooltip>
{{ t('components.leftMenu.removeFromPinned') }}
</QTooltip>
</QBtn>
</template>
</LeftMenuItem>
<QSeparator />
</template>
<template v-for="item in filteredItems" :key="item.name">
<template
v-if="item.children && !filteredPinnedModules.has(item.name)"
>
<LeftMenuItem :item="item" group="modules"> <LeftMenuItem :item="item" group="modules">
<template #side> <template #side>
<QBtn <QBtn
@ -327,7 +247,3 @@ function normalize(text) {
color: var(--vn-label-color); color: var(--vn-label-color);
} }
</style> </style>
<i18n>
es:
Search modules: Buscar módulos
</i18n>

View File

@ -21,7 +21,7 @@ const itemComputed = computed(() => {
</script> </script>
<template> <template>
<QItem <QItem
active-class="bg-vn-hover" active-class="bg-hover"
class="min-height" class="min-height"
:to="{ name: itemComputed.name }" :to="{ name: itemComputed.name }"
clickable clickable
@ -33,17 +33,13 @@ const itemComputed = computed(() => {
<QItemSection avatar v-if="!itemComputed.icon"> <QItemSection avatar v-if="!itemComputed.icon">
<QIcon name="disabled_by_default" /> <QIcon name="disabled_by_default" />
</QItemSection> </QItemSection>
<QItemSection> <QItemSection>{{ t(itemComputed.title) }}</QItemSection>
{{ t(itemComputed.title) }}
<QTooltip v-if="item.keyBinding">
{{ 'Ctrl + Alt + ' + item?.keyBinding?.toUpperCase() }}
</QTooltip>
</QItemSection>
<QItemSection side> <QItemSection side>
<slot name="side" :item="itemComputed" /> <slot name="side" :item="itemComputed" />
</QItemSection> </QItemSection>
</QItem> </QItem>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.q-item { .q-item {
min-height: 5vh; min-height: 5vh;

View File

@ -1,21 +1,21 @@
<script setup> <script setup>
import { onMounted, ref } from 'vue'; import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useSession } from 'src/composables/useSession';
import { useState } from 'src/composables/useState'; import { useState } from 'src/composables/useState';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useStateQueryStore } from 'src/stores/useStateQueryStore';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import PinnedModules from './PinnedModules.vue'; import PinnedModules from './PinnedModules.vue';
import UserPanel from 'components/UserPanel.vue'; import UserPanel from 'components/UserPanel.vue';
import VnBreadcrumbs from './common/VnBreadcrumbs.vue'; import VnBreadcrumbs from './common/VnBreadcrumbs.vue';
import VnAvatar from './ui/VnAvatar.vue';
const { t } = useI18n(); const { t } = useI18n();
const stateStore = useStateStore(); const stateStore = useStateStore();
const quasar = useQuasar(); const quasar = useQuasar();
const stateQuery = useStateQueryStore();
const state = useState(); const state = useState();
const user = state.getUser(); const user = state.getUser();
const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia();
const appName = 'Lilium'; const appName = 'Lilium';
onMounted(() => stateStore.setMounted()); onMounted(() => stateStore.setMounted());
@ -26,13 +26,7 @@ const pinnedModulesRef = ref();
<template> <template>
<QHeader color="white" elevated> <QHeader color="white" elevated>
<QToolbar class="q-py-sm q-px-md"> <QToolbar class="q-py-sm q-px-md">
<QBtn <QBtn @click="stateStore.toggleLeftDrawer()" icon="menu" round dense flat>
@click="stateStore.toggleLeftDrawer()"
icon="dock_to_right"
round
dense
flat
>
<QTooltip bottom anchor="bottom right"> <QTooltip bottom anchor="bottom right">
{{ t('globals.collapseMenu') }} {{ t('globals.collapseMenu') }}
</QTooltip> </QTooltip>
@ -52,14 +46,6 @@ const pinnedModulesRef = ref();
</QBtn> </QBtn>
</RouterLink> </RouterLink>
<VnBreadcrumbs v-if="$q.screen.gt.sm" /> <VnBreadcrumbs v-if="$q.screen.gt.sm" />
<QSpinner
color="primary"
class="q-ml-md"
:class="{
'no-visible': !stateQuery.isLoading().value,
}"
size="xs"
/>
<QSpace /> <QSpace />
<div id="searchbar" class="searchbar"></div> <div id="searchbar" class="searchbar"></div>
<QSpace /> <QSpace />
@ -88,13 +74,21 @@ const pinnedModulesRef = ref();
</QTooltip> </QTooltip>
<PinnedModules ref="pinnedModulesRef" /> <PinnedModules ref="pinnedModulesRef" />
</QBtn> </QBtn>
<QBtn class="q-pa-none" rounded dense flat no-wrap id="user"> <QBtn
<VnAvatar :class="{ 'q-pa-none': quasar.platform.is.mobile }"
:worker-id="user.id" rounded
:title="user.name" dense
size="lg" flat
color="transparent" no-wrap
/> id="user"
>
<QAvatar size="lg">
<QImg
:src="`/api/Images/user/160x160/${user.id}/download?access_token=${token}`"
spinner-color="primary"
>
</QImg>
</QAvatar>
<QTooltip bottom> <QTooltip bottom>
{{ t('globals.userPanel') }} {{ t('globals.userPanel') }}
</QTooltip> </QTooltip>

View File

@ -1,170 +0,0 @@
<script setup>
import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useDialogPluginComponent } from 'quasar';
import VnRow from 'components/ui/VnRow.vue';
import FetchData from 'components/FetchData.vue';
import VnSelect from 'components/common/VnSelect.vue';
import FormPopup from './FormPopup.vue';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
const $props = defineProps({
invoiceOutData: {
type: Object,
default: () => {},
},
});
const { dialogRef } = useDialogPluginComponent();
const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();
const rectificativeTypeOptions = ref([]);
const siiTypeInvoiceOutsOptions = ref([]);
const invoiceParams = reactive({
id: $props.invoiceOutData?.id,
inheritWarehouse: true,
});
const invoiceCorrectionTypesOptions = ref([]);
const refund = async () => {
const params = {
id: invoiceParams.id,
withWarehouse: invoiceParams.inheritWarehouse,
cplusRectificationTypeFk: invoiceParams.cplusRectificationTypeFk,
siiTypeInvoiceOutFk: invoiceParams.siiTypeInvoiceOutFk,
invoiceCorrectionTypeFk: invoiceParams.invoiceCorrectionTypeFk,
};
const { data } = await axios.post('InvoiceOuts/refundAndInvoice', params);
notify(t('Refunded invoice'), 'positive');
const [id] = data?.refundId || [];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
};
</script>
<template>
<FetchData
url="CplusRectificationTypes"
:filter="{ order: 'description' }"
@on-fetch="
(data) => (
(rectificativeTypeOptions = data),
(invoiceParams.cplusRectificationTypeFk = data.filter(
(type) => type.description == 'I Por diferencias'
)[0].id)
)
"
auto-load
/>
<FetchData
url="SiiTypeInvoiceOuts"
:filter="{ where: { code: { like: 'R%' } } }"
@on-fetch="
(data) => (
(siiTypeInvoiceOutsOptions = data),
(invoiceParams.siiTypeInvoiceOutFk = data.filter(
(type) => type.code == 'R4'
)[0].id)
)
"
auto-load
/>
<FetchData
url="InvoiceCorrectionTypes"
@on-fetch="(data) => (invoiceCorrectionTypesOptions = data)"
auto-load
/>
<QDialog ref="dialogRef">
<FormPopup
@on-submit="refund()"
:custom-submit-button-label="t('Accept')"
:default-cancel-button="false"
>
<template #form-inputs>
<VnRow>
<VnSelect
:label="t('Rectificative type')"
:options="rectificativeTypeOptions"
hide-selected
option-label="description"
option-value="id"
v-model="invoiceParams.cplusRectificationTypeFk"
:required="true"
/>
</VnRow>
<VnRow>
<VnSelect
:label="t('Class')"
:options="siiTypeInvoiceOutsOptions"
hide-selected
option-label="description"
option-value="id"
v-model="invoiceParams.siiTypeInvoiceOutFk"
:required="true"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt?.code }} -
{{ scope.opt?.description }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</VnRow>
<VnRow>
<VnSelect
:label="t('Type')"
:options="invoiceCorrectionTypesOptions"
hide-selected
option-label="description"
option-value="id"
v-model="invoiceParams.invoiceCorrectionTypeFk"
:required="true"
/> </VnRow
><VnRow>
<div>
<QCheckbox
:label="t('Inherit warehouse')"
v-model="invoiceParams.inheritWarehouse"
/>
<QIcon name="info" class="cursor-info q-ml-sm" size="sm">
<QTooltip>{{ t('Inherit warehouse tooltip') }}</QTooltip>
</QIcon>
</div>
</VnRow>
</template>
</FormPopup>
</QDialog>
</template>
<i18n>
en:
Refund invoice: Refund invoice
Rectificative type: Rectificative type
Class: Class
Type: Type
Refunded invoice: Refunded invoice
Inherit warehouse: Inherit the warehouse
Inherit warehouse tooltip: Select this option to inherit the warehouse when refunding the invoice
Accept: Accept
Error refunding invoice: Error refunding invoice
es:
Refund invoice: Abonar factura
Rectificative type: Tipo rectificativa
Class: Clase
Type: Tipo
Refunded invoice: Factura abonada
Inherit warehouse: Heredar el almacén
Inherit warehouse tooltip: Seleccione esta opción para heredar el almacén al abonar la factura.
Accept: Aceptar
Error refunding invoice: Error abonando factura
</i18n>

View File

@ -15,7 +15,7 @@ const props = defineProps({
default: null, default: null,
}, },
warehouseFk: { warehouseFk: {
type: Number, type: Boolean,
default: null, default: null,
}, },
}); });
@ -23,7 +23,7 @@ const props = defineProps({
const { t } = useI18n(); const { t } = useI18n();
const regularizeFormData = reactive({ const regularizeFormData = reactive({
itemFk: Number(props.itemFk), itemFk: props.itemFk,
warehouseFk: props.warehouseFk, warehouseFk: props.warehouseFk,
quantity: null, quantity: null,
}); });
@ -49,19 +49,18 @@ const onDataSaved = (data) => {
@on-data-saved="onDataSaved($event)" @on-data-saved="onDataSaved($event)"
> >
<template #form-inputs="{ data }"> <template #form-inputs="{ data }">
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<QInput <QInput
:label="t('Type the visible quantity')" :label="t('Type the visible quantity')"
v-model.number="data.quantity" v-model.number="data.quantity"
type="number"
autofocus autofocus
/> />
</VnRow> </VnRow>
<VnRow> <VnRow class="row q-gutter-md q-mb-md">
<div class="col"> <div class="col">
<VnSelect <VnSelect
:label="t('Warehouse')" :label="t('Warehouse')"
v-model.number="data.warehouseFk" v-model="data.warehouseFk"
:options="warehousesOptions" :options="warehousesOptions"
option-value="id" option-value="id"
option-label="name" option-label="name"

View File

@ -1,40 +0,0 @@
<script setup>
defineProps({ row: { type: Object, required: true } });
</script>
<template>
<span>
<QIcon
v-if="row.isTaxDataChecked === 0"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon>
<QIcon v-if="row.hasTicketRequest" name="vn:buyrequest" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon>
<QIcon v-if="row.itemShortage" name="vn:unavailable" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.notVisible') }}</QTooltip>
</QIcon>
<QIcon v-if="row.isFreezed" name="vn:frozen" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.clientFrozen') }}</QTooltip>
</QIcon>
<QIcon
v-if="row.risk"
name="vn:risk"
:color="row.hasHighRisk ? 'negative' : 'primary'"
size="xs"
>
<QTooltip>
{{ $t('salesTicketsTable.risk') }}: {{ row.risk - row.credit }}
</QTooltip>
</QIcon>
<QIcon v-if="row.hasComponentLack" name="vn:components" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.componentLack') }}</QTooltip>
</QIcon>
<QIcon v-if="row.isTooLittle" name="vn:isTooLittle" color="primary" size="xs">
<QTooltip>{{ $t('salesTicketsTable.tooLittle') }}</QTooltip>
</QIcon>
</span>
</template>

View File

@ -2,12 +2,13 @@
import { ref, reactive } from 'vue'; import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useQuasar, useDialogPluginComponent } from 'quasar'; import { useQuasar } from 'quasar';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnConfirm from 'components/ui/VnConfirm.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import FormPopup from './FormPopup.vue'; import FormPopup from './FormPopup.vue';
import axios from 'axios'; import axios from 'axios';
import useNotify from 'src/composables/useNotify.js'; import useNotify from 'src/composables/useNotify.js';
@ -18,18 +19,18 @@ const $props = defineProps({
}, },
}); });
const { dialogRef } = useDialogPluginComponent();
const quasar = useQuasar(); const quasar = useQuasar();
const { t } = useI18n(); const { t } = useI18n();
const router = useRouter(); const router = useRouter();
const { notify } = useNotify(); const { notify } = useNotify();
const rectificativeTypeOptions = ref([]);
const siiTypeInvoiceOutsOptions = ref([]);
const checked = ref(true); const checked = ref(true);
const transferInvoiceParams = reactive({ const transferInvoiceParams = reactive({
id: $props.invoiceOutData?.id, id: $props.invoiceOutData?.id,
refFk: $props.invoiceOutData?.ref,
}); });
const rectificativeTypeOptions = ref([]);
const siiTypeInvoiceOutsOptions = ref([]);
const invoiceCorrectionTypesOptions = ref([]); const invoiceCorrectionTypesOptions = ref([]);
const selectedClient = (client) => { const selectedClient = (client) => {
@ -43,38 +44,46 @@ const makeInvoice = async () => {
const params = { const params = {
id: transferInvoiceParams.id, id: transferInvoiceParams.id,
cplusRectificationTypeFk: transferInvoiceParams.cplusRectificationTypeFk, cplusRectificationTypeFk: transferInvoiceParams.cplusRectificationTypeFk,
siiTypeInvoiceOutFk: transferInvoiceParams.siiTypeInvoiceOutFk,
invoiceCorrectionTypeFk: transferInvoiceParams.invoiceCorrectionTypeFk, invoiceCorrectionTypeFk: transferInvoiceParams.invoiceCorrectionTypeFk,
newClientFk: transferInvoiceParams.newClientFk, newClientFk: transferInvoiceParams.newClientFk,
refFk: transferInvoiceParams.refFk,
siiTypeInvoiceOutFk: transferInvoiceParams.siiTypeInvoiceOutFk,
makeInvoice: checked.value, makeInvoice: checked.value,
}; };
if (checked.value && hasToInvoiceByAddress) { try {
const response = await new Promise((resolve) => { if (checked.value && hasToInvoiceByAddress) {
quasar const response = await new Promise((resolve) => {
.dialog({ quasar
component: VnConfirm, .dialog({
componentProps: { component: VnConfirm,
title: t('Bill destination client'), componentProps: {
message: t('transferInvoiceInfo'), title: t('Bill destination client'),
}, message: t('transferInvoiceInfo'),
}) },
.onOk(() => { })
resolve(true); .onOk(() => {
}) resolve(true);
.onCancel(() => { })
resolve(false); .onCancel(() => {
}); resolve(false);
}); });
if (!response) { });
return; if (!response) {
console.log('entra cuando no checkbox');
return;
}
} }
}
const { data } = await axios.post('InvoiceOuts/transfer', params); console.log('params: ', params);
notify(t('Transferred invoice'), 'positive'); const { data } = await axios.post('InvoiceOuts/transferInvoice', params);
const id = data?.[0]; console.log('data: ', data);
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } }); notify(t('Transferred invoice'), 'positive');
const id = data?.[0];
if (id) router.push({ name: 'InvoiceOutSummary', params: { id } });
} catch (err) {
console.error('Error transfering invoice', err);
}
}; };
</script> </script>
@ -110,95 +119,90 @@ const makeInvoice = async () => {
@on-fetch="(data) => (invoiceCorrectionTypesOptions = data)" @on-fetch="(data) => (invoiceCorrectionTypesOptions = data)"
auto-load auto-load
/> />
<QDialog ref="dialogRef"> <FormPopup
<FormPopup @on-submit="makeInvoice()"
@on-submit="makeInvoice()" :title="t('Transfer invoice')"
:title="t('Transfer invoice')" :custom-submit-button-label="t('Transfer client')"
:custom-submit-button-label="t('Transfer client')" :default-cancel-button="false"
:default-cancel-button="false" >
> <template #form-inputs>
<template #form-inputs> <VnRow class="row q-gutter-md q-mb-md">
<VnRow> <VnSelect
<VnSelect :label="t('Client')"
:label="t('Client')" :options="clientsOptions"
:options="clientsOptions" hide-selected
hide-selected option-label="name"
option-label="name" option-value="id"
option-value="id" v-model="transferInvoiceParams.newClientFk"
v-model="transferInvoiceParams.newClientFk" :required="true"
:required="true" url="Clients"
url="Clients" :fields="['id', 'name', 'hasToInvoiceByAddress']"
:fields="['id', 'name', 'hasToInvoiceByAddress']" auto-load
auto-load >
> <template #option="scope">
<template #option="scope"> <QItem
<QItem v-bind="scope.itemProps"
v-bind="scope.itemProps" @click="selectedClient(scope.opt)"
@click="selectedClient(scope.opt)" >
> <QItemSection>
<QItemSection> <QItemLabel>
<QItemLabel> #{{ scope.opt?.id }} - {{ scope.opt?.name }}
#{{ scope.opt?.id }} - {{ scope.opt?.name }} </QItemLabel>
</QItemLabel> </QItemSection>
</QItemSection> </QItem>
</QItem> </template>
</template> </VnSelect>
</VnSelect> <VnSelect
<VnSelect :label="t('Rectificative type')"
:label="t('Rectificative type')" :options="rectificativeTypeOptions"
:options="rectificativeTypeOptions" hide-selected
hide-selected option-label="description"
option-label="description" option-value="id"
option-value="id" v-model="transferInvoiceParams.cplusRectificationTypeFk"
v-model="transferInvoiceParams.cplusRectificationTypeFk" :required="true"
:required="true" />
/> </VnRow>
</VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnRow> <VnSelect
<VnSelect :label="t('Class')"
:label="t('Class')" :options="siiTypeInvoiceOutsOptions"
:options="siiTypeInvoiceOutsOptions" hide-selected
hide-selected option-label="description"
option-label="description" option-value="id"
option-value="id" v-model="transferInvoiceParams.siiTypeInvoiceOutFk"
v-model="transferInvoiceParams.siiTypeInvoiceOutFk" :required="true"
:required="true" >
> <template #option="scope">
<template #option="scope"> <QItem v-bind="scope.itemProps">
<QItem v-bind="scope.itemProps"> <QItemSection>
<QItemSection> <QItemLabel>
<QItemLabel> {{ scope.opt?.code }} -
{{ scope.opt?.code }} - {{ scope.opt?.description }}
{{ scope.opt?.description }} </QItemLabel>
</QItemLabel> </QItemSection>
</QItemSection> </QItem>
</QItem> </template>
</template> </VnSelect>
</VnSelect> <VnSelect
<VnSelect :label="t('Type')"
:label="t('Type')" :options="invoiceCorrectionTypesOptions"
:options="invoiceCorrectionTypesOptions" hide-selected
hide-selected option-label="description"
option-label="description" option-value="id"
option-value="id" v-model="transferInvoiceParams.invoiceCorrectionTypeFk"
v-model="transferInvoiceParams.invoiceCorrectionTypeFk" :required="true"
:required="true" />
/> </VnRow>
</VnRow> <VnRow class="row q-gutter-md q-mb-md">
<VnRow> <div>
<div> <QCheckbox :label="t('Bill destination client')" v-model="checked" />
<QCheckbox <QIcon name="info" class="cursor-info q-ml-sm" size="sm">
:label="t('Bill destination client')" <QTooltip>{{ t('transferInvoiceInfo') }}</QTooltip>
v-model="checked" </QIcon>
/> </div>
<QIcon name="info" class="cursor-info q-ml-sm" size="sm"> </VnRow>
<QTooltip>{{ t('transferInvoiceInfo') }}</QTooltip> </template>
</QIcon> </FormPopup>
</div>
</VnRow>
</template>
</FormPopup>
</QDialog>
</template> </template>
<i18n> <i18n>

View File

@ -11,17 +11,13 @@ import VnSelect from 'src/components/common/VnSelect.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import FetchData from 'components/FetchData.vue'; import FetchData from 'components/FetchData.vue';
import { useClipboard } from 'src/composables/useClipboard'; import { useClipboard } from 'src/composables/useClipboard';
import { useRole } from 'src/composables/useRole'; import VnImg from 'src/components/ui/VnImg.vue';
import VnAvatar from './ui/VnAvatar.vue';
import useNotify from 'src/composables/useNotify';
const state = useState(); const state = useState();
const session = useSession(); const session = useSession();
const router = useRouter(); const router = useRouter();
const { t, locale } = useI18n(); const { t, locale } = useI18n();
const { copyText } = useClipboard(); const { copyText } = useClipboard();
const { notify } = useNotify();
const userLocale = computed({ const userLocale = computed({
get() { get() {
return locale.value; return locale.value;
@ -55,7 +51,6 @@ const user = state.getUser();
const warehousesData = ref(); const warehousesData = ref();
const companiesData = ref(); const companiesData = ref();
const accountBankData = ref(); const accountBankData = ref();
const isEmployee = computed(() => useRole().isEmployee());
onMounted(async () => { onMounted(async () => {
updatePreferences(); updatePreferences();
@ -73,28 +68,18 @@ function updatePreferences() {
async function saveDarkMode(value) { async function saveDarkMode(value) {
const query = `/UserConfigs/${user.value.id}`; const query = `/UserConfigs/${user.value.id}`;
try { await axios.patch(query, {
await axios.patch(query, { darkMode: value,
darkMode: value, });
}); user.value.darkMode = value;
user.value.darkMode = value;
onDataSaved();
} catch (error) {
onDataError();
}
} }
async function saveLanguage(value) { async function saveLanguage(value) {
const query = `/VnUsers/${user.value.id}`; const query = `/VnUsers/${user.value.id}`;
try { await axios.patch(query, {
await axios.patch(query, { lang: value,
lang: value, });
}); user.value.lang = value;
user.value.lang = value;
onDataSaved();
} catch (error) {
onDataError();
}
} }
function logout() { function logout() {
@ -110,23 +95,10 @@ function localUserData() {
state.setUser(user.value); state.setUser(user.value);
} }
async function saveUserData(param, value) { function saveUserData(param, value) {
try { axios.post('UserConfigs/setUserConfig', { [param]: value });
await axios.post('UserConfigs/setUserConfig', { [param]: value }); localUserData();
localUserData();
onDataSaved();
} catch (error) {
onDataError();
}
} }
const onDataSaved = () => {
notify('globals.dataSaved', 'positive');
};
const onDataError = () => {
notify('errors.updateUserConfig', 'negative');
};
</script> </script>
<template> <template>
@ -137,14 +109,12 @@ const onDataError = () => {
auto-load auto-load
/> />
<FetchData <FetchData
v-if="isEmployee"
url="Companies" url="Companies"
order="name" order="name"
@on-fetch="(data) => (companiesData = data)" @on-fetch="(data) => (companiesData = data)"
auto-load auto-load
/> />
<FetchData <FetchData
v-if="isEmployee"
url="Accountings" url="Accountings"
order="name" order="name"
@on-fetch="(data) => (accountBankData = data)" @on-fetch="(data) => (accountBankData = data)"
@ -161,7 +131,7 @@ const onDataError = () => {
@update:model-value="saveLanguage" @update:model-value="saveLanguage"
:label="t(`globals.lang['${userLocale}']`)" :label="t(`globals.lang['${userLocale}']`)"
icon="public" icon="public"
color="primary" color="orange"
false-value="es" false-value="es"
true-value="en" true-value="en"
/> />
@ -170,7 +140,7 @@ const onDataError = () => {
@update:model-value="saveDarkMode" @update:model-value="saveDarkMode"
:label="t(`globals.darkMode`)" :label="t(`globals.darkMode`)"
checked-icon="dark_mode" checked-icon="dark_mode"
color="primary" color="orange"
unchecked-icon="light_mode" unchecked-icon="light_mode"
/> />
</div> </div>
@ -178,20 +148,10 @@ const onDataError = () => {
<QSeparator vertical inset class="q-mx-lg" /> <QSeparator vertical inset class="q-mx-lg" />
<div class="col column items-center q-mb-sm"> <div class="col column items-center q-mb-sm">
<VnAvatar <QAvatar size="80px">
:worker-id="user.id" <VnImg :id="user.id" collection="user" size="160x160" />
:title="user.name" </QAvatar>
size="xxl"
color="transparent"
/>
<QBtn
v-if="isEmployee"
class="q-mt-sm q-px-md"
:to="`/worker/${user.id}`"
color="primary"
:label="t('globals.myAccount')"
dense
/>
<div class="text-subtitle1 q-mt-md"> <div class="text-subtitle1 q-mt-md">
<strong>{{ user.nickname }}</strong> <strong>{{ user.nickname }}</strong>
</div> </div>
@ -203,7 +163,7 @@ const onDataError = () => {
</div> </div>
<QBtn <QBtn
id="logout" id="logout"
color="primary" color="orange"
flat flat
:label="t('globals.logOut')" :label="t('globals.logOut')"
size="sm" size="sm"

View File

@ -1,97 +0,0 @@
<script setup>
import { ref, watch } from 'vue';
import { useValidator } from 'src/composables/useValidator';
import { useI18n } from 'vue-i18n';
import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import FetchData from 'components/FetchData.vue';
import CreateNewProvinceForm from './CreateNewProvinceForm.vue';
const emit = defineEmits(['onProvinceCreated', 'onProvinceFetched', 'update:options']);
const $props = defineProps({
countryFk: {
type: Number,
default: null,
},
provinceSelected: {
type: Number,
default: null,
},
});
const provinceFk = defineModel({ type: Number, default: null });
const { validate } = useValidator();
const { t } = useI18n();
const filter = ref({
include: { relation: 'country' },
where: {
countryFk: $props.countryFk,
},
});
const provincesOptions = ref($props.provinces);
const provincesFetchDataRef = ref();
provinceFk.value = $props.provinceSelected;
if (!$props.countryFk) {
filter.value.where = {};
}
async function onProvinceCreated(_, data) {
await provincesFetchDataRef.value.fetch({ where: { countryFk: $props.countryFk } });
provinceFk.value = data.id;
emit('onProvinceCreated', data);
}
async function handleProvinces(data) {
provincesOptions.value = data;
emit('update:options', data);
}
watch(
() => $props.countryFk,
async () => {
if ($props.countryFk) {
filter.value.where.countryFk = $props.countryFk;
} else filter.value.where = {};
await provincesFetchDataRef.value.fetch({});
emit('onProvinceFetched', provincesOptions.value);
}
);
</script>
<template>
<FetchData
ref="provincesFetchDataRef"
:filter="filter"
@on-fetch="handleProvinces"
url="Provinces"
auto-load
/>
<VnSelectDialog
data-cy="locationProvince"
:label="t('Province')"
:options="provincesOptions"
:tooltip="t('Create province')"
hide-selected
v-model="provinceFk"
:rules="validate && validate('postcode.provinceFk')"
:acls="[{ model: 'Province', props: '*', accessType: 'WRITE' }]"
>
<template #option="{ itemProps, opt }">
<QItem v-bind="itemProps">
<QItemSection>
<QItemLabel>{{ opt.name }}</QItemLabel>
<QItemLabel caption> {{ opt.country.name }} </QItemLabel>
</QItemSection>
</QItem>
</template>
<template #form>
<CreateNewProvinceForm
:country-fk="$props.countryFk"
@on-data-saved="onProvinceCreated"
/>
</template>
</VnSelectDialog>
</template>
<i18n>
es:
Province: Provincia
Create province: Crear provincia
</i18n>

View File

@ -35,9 +35,7 @@ function stopEventPropagation(event) {
dense dense
square square
> >
<span v-if="!col.chip.icon"> <span v-if="!col.chip.icon">{{ row[col.name] }}</span>
{{ col.format ? col.format(row) : row[col.name] }}
</span>
<QIcon v-else :name="col.chip.icon" color="primary-light" /> <QIcon v-else :name="col.chip.icon" color="primary-light" />
</QChip> </QChip>
</span> </span>

View File

@ -1,17 +1,13 @@
<script setup> <script setup>
import { markRaw, computed } from 'vue'; import { markRaw, computed, defineModel } from 'vue';
import { QIcon, QCheckbox } from 'quasar'; import { QIcon, QCheckbox } from 'quasar';
import { dashIfEmpty } from 'src/filters'; import { dashIfEmpty } from 'src/filters';
/* basic input */ /* basic input */
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import VnSelectCache from 'components/common/VnSelectCache.vue';
import VnInput from 'components/common/VnInput.vue'; import VnInput from 'components/common/VnInput.vue';
import VnInputNumber from 'components/common/VnInputNumber.vue';
import VnInputDate from 'components/common/VnInputDate.vue'; import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnComponent from 'components/common/VnComponent.vue'; import VnComponent from 'components/common/VnComponent.vue';
import VnUserLink from 'components/ui/VnUserLink.vue';
const model = defineModel(undefined, { required: true }); const model = defineModel(undefined, { required: true });
const $props = defineProps({ const $props = defineProps({
@ -45,33 +41,20 @@ const $props = defineProps({
}, },
}); });
const defaultSelect = {
attrs: {
row: $props.row,
disable: !$props.isEditable,
class: 'fit',
},
forceAttrs: {
label: $props.showLabel && $props.column.label,
},
};
const defaultComponents = { const defaultComponents = {
input: { input: {
component: markRaw(VnInput), component: markRaw(VnInput),
attrs: { attrs: {
disable: !$props.isEditable, disable: !$props.isEditable,
class: 'fit',
}, },
forceAttrs: { forceAttrs: {
label: $props.showLabel && $props.column.label, label: $props.showLabel && $props.column.label,
}, },
}, },
number: { number: {
component: markRaw(VnInputNumber), component: markRaw(VnInput),
attrs: { attrs: {
disable: !$props.isEditable, disable: !$props.isEditable,
class: 'fit',
}, },
forceAttrs: { forceAttrs: {
label: $props.showLabel && $props.column.label, label: $props.showLabel && $props.column.label,
@ -80,19 +63,9 @@ const defaultComponents = {
date: { date: {
component: markRaw(VnInputDate), component: markRaw(VnInputDate),
attrs: { attrs: {
readonly: !$props.isEditable, readonly: true,
disable: !$props.isEditable, disable: !$props.isEditable,
style: 'min-width: 125px', style: 'min-width: 125px',
class: 'fit',
},
forceAttrs: {
label: $props.showLabel && $props.column.label,
},
},
time: {
component: markRaw(VnInputTime),
attrs: {
disable: !$props.isEditable,
}, },
forceAttrs: { forceAttrs: {
label: $props.showLabel && $props.column.label, label: $props.showLabel && $props.column.label,
@ -100,14 +73,14 @@ const defaultComponents = {
}, },
checkbox: { checkbox: {
component: markRaw(QCheckbox), component: markRaw(QCheckbox),
attrs: ({ model }) => { attrs: (prop) => {
const defaultAttrs = { const defaultAttrs = {
disable: !$props.isEditable, disable: !$props.isEditable,
'model-value': Boolean(model), 'model-value': Boolean(prop),
class: 'no-padding fit', class: 'no-padding',
}; };
if (typeof model == 'number') { if (typeof prop == 'number') {
defaultAttrs['true-value'] = 1; defaultAttrs['true-value'] = 1;
defaultAttrs['false-value'] = 0; defaultAttrs['false-value'] = 0;
} }
@ -118,19 +91,17 @@ const defaultComponents = {
}, },
}, },
select: { select: {
component: markRaw(VnSelectCache),
...defaultSelect,
},
rawSelect: {
component: markRaw(VnSelect), component: markRaw(VnSelect),
...defaultSelect, attrs: {
disable: !$props.isEditable,
},
forceAttrs: {
label: $props.showLabel && $props.column.label,
},
}, },
icon: { icon: {
component: markRaw(QIcon), component: markRaw(QIcon),
}, },
userLink: {
component: markRaw(VnUserLink),
},
}; };
const value = computed(() => { const value = computed(() => {
@ -151,8 +122,8 @@ const col = computed(() => {
}; };
} }
if ( if (
(/^is[A-Z]/.test(newColumn.name) || /^has[A-Z]/.test(newColumn.name)) && (newColumn.name.startsWith('is') || newColumn.name.startsWith('has')) &&
newColumn.component == null !newColumn.component
) )
newColumn.component = 'checkbox'; newColumn.component = 'checkbox';
if ($props.default && !newColumn.component) newColumn.component = $props.default; if ($props.default && !newColumn.component) newColumn.component = $props.default;
@ -163,19 +134,19 @@ const col = computed(() => {
const components = computed(() => $props.components ?? defaultComponents); const components = computed(() => $props.components ?? defaultComponents);
</script> </script>
<template> <template>
<div class="row no-wrap"> <div class="row no-wrap fit">
<VnComponent <VnComponent
v-if="col.before" v-if="col.before"
:prop="col.before" :prop="col.before"
:components="components" :components="components"
:value="{ row, model }" :value="model"
v-model="model" v-model="model"
/> />
<VnComponent <VnComponent
v-if="col.component" v-if="col.component"
:prop="col" :prop="col"
:components="components" :components="components"
:value="{ row, model }" :value="model"
v-model="model" v-model="model"
/> />
<span :title="value" v-else>{{ value }}</span> <span :title="value" v-else>{{ value }}</span>
@ -183,7 +154,7 @@ const components = computed(() => $props.components ?? defaultComponents);
v-if="col.after" v-if="col.after"
:prop="col.after" :prop="col.after"
:components="components" :components="components"
:value="{ row, model }" :value="model"
v-model="model" v-model="model"
/> />
</div> </div>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { markRaw, computed } from 'vue'; import { markRaw, computed, defineModel } from 'vue';
import { QCheckbox } from 'quasar'; import { QCheckbox } from 'quasar';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
@ -7,7 +7,6 @@ import { useArrayData } from 'composables/useArrayData';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import VnInput from 'components/common/VnInput.vue'; import VnInput from 'components/common/VnInput.vue';
import VnInputDate from 'components/common/VnInputDate.vue'; import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnTableColumn from 'components/VnTable/VnColumn.vue'; import VnTableColumn from 'components/VnTable/VnColumn.vue';
const $props = defineProps({ const $props = defineProps({
@ -25,12 +24,9 @@ const $props = defineProps({
}, },
searchUrl: { searchUrl: {
type: String, type: String,
default: 'table', default: 'params',
}, },
}); });
defineExpose({ addFilter, props: $props });
const model = defineModel(undefined, { required: true }); const model = defineModel(undefined, { required: true });
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl }); const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl });
const columnFilter = computed(() => $props.column?.columnFilter); const columnFilter = computed(() => $props.column?.columnFilter);
@ -43,23 +39,12 @@ const enterEvent = {
const defaultAttrs = { const defaultAttrs = {
filled: !$props.showTitle, filled: !$props.showTitle,
class: 'q-px-xs q-pb-xs q-pt-none fit', class: 'q-px-sm q-pb-xs q-pt-none',
dense: true, dense: true,
}; };
const forceAttrs = { const forceAttrs = {
label: $props.showTitle ? '' : columnFilter.value?.label ?? $props.column.label, label: $props.showTitle ? '' : $props.column.label,
};
const selectComponent = {
component: markRaw(VnSelect),
event: updateEvent,
attrs: {
class: 'q-px-sm q-pb-xs q-pt-none fit',
dense: true,
filled: !$props.showTitle,
},
forceAttrs,
}; };
const components = { const components = {
@ -78,7 +63,6 @@ const components = {
attrs: { attrs: {
...defaultAttrs, ...defaultAttrs,
clearable: true, clearable: true,
type: 'number',
}, },
forceAttrs, forceAttrs,
}, },
@ -91,36 +75,33 @@ const components = {
}, },
forceAttrs, forceAttrs,
}, },
time: {
component: markRaw(VnInputTime),
event: updateEvent,
attrs: {
...defaultAttrs,
disable: !$props.isEditable,
},
forceAttrs: {
label: $props.showLabel && $props.column.label,
},
},
checkbox: { checkbox: {
component: markRaw(QCheckbox), component: markRaw(QCheckbox),
event: updateEvent, event: updateEvent,
attrs: { attrs: {
dense: true, dense: true,
class: $props.showTitle ? 'q-py-sm q-mt-md' : 'q-px-md q-py-xs fit', class: $props.showTitle ? 'q-py-sm q-mt-md' : 'q-px-md q-py-xs',
'toggle-indeterminate': true, 'toggle-indeterminate': true,
}, },
forceAttrs, forceAttrs,
}, },
select: selectComponent, select: {
rawSelect: selectComponent, component: markRaw(VnSelect),
event: updateEvent,
attrs: {
class: 'q-px-md q-pb-xs q-pt-none',
dense: true,
filled: !$props.showTitle,
},
forceAttrs,
},
}; };
async function addFilter(value, name) { async function addFilter(value) {
value ??= undefined; value ??= undefined;
if (value && typeof value === 'object') value = model.value; if (value && typeof value === 'object') value = model.value;
value = value === '' ? undefined : value; value = value === '' ? undefined : value;
let field = columnFilter.value?.name ?? $props.column.name ?? name; let field = columnFilter.value?.name ?? $props.column.name;
if (columnFilter.value?.inWhere) { if (columnFilter.value?.inWhere) {
if (columnFilter.value.alias) field = columnFilter.value.alias + '.' + field; if (columnFilter.value.alias) field = columnFilter.value.alias + '.' + field;
@ -143,25 +124,23 @@ function alignRow() {
const showFilter = computed( const showFilter = computed(
() => $props.column?.columnFilter !== false && $props.column.name != 'tableActions' () => $props.column?.columnFilter !== false && $props.column.name != 'tableActions'
); );
const onTabPressed = async () => {
if (model.value) enterEvent['keyup.enter']();
};
</script> </script>
<template> <template>
<div <div
v-if="showFilter" v-if="showTitle"
class="full-width" class="q-pt-sm q-px-sm ellipsis"
:class="alignRow()" :class="`text-${column?.align ?? 'left'}`"
style="max-height: 45px; overflow: hidden" :style="!showFilter ? { 'min-height': 72 + 'px' } : ''"
> >
{{ column?.label }}
</div>
<div v-if="showFilter" class="full-width" :class="alignRow()">
<VnTableColumn <VnTableColumn
:column="$props.column" :column="$props.column"
default="input" default="input"
v-model="model" v-model="model"
:components="components" :components="components"
component-prop="columnFilter" component-prop="columnFilter"
@keydown.tab="onTabPressed"
/> />
</div> </div>
</template> </template>

View File

@ -1,95 +0,0 @@
<script setup>
import { ref } from 'vue';
import { useArrayData } from 'composables/useArrayData';
const model = defineModel({ type: Object });
const $props = defineProps({
name: {
type: [String, Boolean],
default: '',
},
label: {
type: String,
default: undefined,
},
dataKey: {
type: String,
required: true,
},
searchUrl: {
type: String,
default: 'table',
},
vertical: {
type: Boolean,
default: false,
},
});
const hover = ref();
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl });
async function orderBy(name, direction) {
if (!name) return;
switch (direction) {
case 'DESC':
direction = undefined;
break;
case undefined:
direction = 'ASC';
break;
case 'ASC':
direction = 'DESC';
break;
}
if (!direction) return await arrayData.deleteOrder(name);
await arrayData.addOrder(name, direction);
}
defineExpose({ orderBy });
</script>
<template>
<div
@mouseenter="hover = true"
@mouseleave="hover = false"
@click="orderBy(name, model?.direction)"
class="row items-center no-wrap cursor-pointer"
>
<span :title="label">{{ label }}</span>
<QChip
v-if="name"
:label="!vertical ? model?.index : ''"
:icon="
(model?.index || hover) && !vertical
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: undefined
"
:size="vertical ? '' : 'sm'"
:class="[
model?.index ? 'color-vn-text' : 'bg-transparent',
vertical ? 'q-px-none' : '',
]"
class="no-box-shadow"
:clickable="true"
style="min-width: 40px"
>
<div
class="column flex-center"
v-if="vertical"
:style="!model?.index && 'color: #5d5d5d'"
>
{{ model?.index }}
<QIcon
:name="
model?.index
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: 'swap_vert'
"
size="xs"
/>
</div>
</QChip>
</div>
</template>

File diff suppressed because it is too large Load Diff

View File

@ -1,189 +0,0 @@
<script setup>
import { useI18n } from 'vue-i18n';
import { ref, computed, onMounted } from 'vue';
import { useState } from 'src/composables/useState';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
const columns = defineModel({ type: Object, default: [] });
const $props = defineProps({
tableCode: {
type: String,
default: '',
},
skip: {
type: Array,
default: () => [],
},
});
const { notify } = useNotify();
const { t } = useI18n();
const state = useState();
const user = state.getUser();
const popupProxyRef = ref();
const initialUserConfigViewData = ref();
const localColumns = ref([]);
const areAllChecksMarked = computed(() => {
return localColumns.value.every((col) => col.visible);
});
function setUserConfigViewData(data, isLocal) {
if (!data) return;
// Importante: El name de las columnas de la tabla debe conincidir con el name de las variables que devuelve la view config
if (!isLocal) localColumns.value = [];
// Array to Object
const skippeds = $props.skip.reduce((a, v) => ({ ...a, [v]: v }), {});
for (let column of columns.value) {
const { label, name } = column;
if (skippeds[name]) continue;
column.visible = data[name] ?? true;
if (!isLocal) localColumns.value.push({ name, label, visible: column.visible });
}
}
function toggleMarkAll(val) {
localColumns.value.forEach((col) => (col.visible = val));
}
async function getConfig(url, filter) {
const response = await axios.get(url, {
params: { filter: filter },
});
return response.data && response.data.length > 0 ? response.data[0] : null;
}
async function fetchViewConfigData() {
try {
const defaultFilter = {
where: { tableCode: $props.tableCode },
};
const userConfig = await getConfig('UserConfigViews', {
where: {
...defaultFilter.where,
...{ userFk: user.value.id },
},
});
if (userConfig) {
initialUserConfigViewData.value = userConfig;
setUserConfigViewData(userConfig.configuration);
return;
}
const defaultConfig = await getConfig('DefaultViewConfigs', defaultFilter);
if (defaultConfig) {
setUserConfigViewData(defaultConfig.columns);
return;
}
} catch (err) {
console.error('Error fetching config view data', err);
}
}
async function saveConfig() {
const configuration = {};
for (const { name, visible } of localColumns.value)
configuration[name] = visible ?? true;
setUserConfigViewData(configuration, true);
if (!$props.tableCode) return popupProxyRef.value.hide();
try {
const params = {};
// Si existe una view config del usuario hacemos un update si no la creamos
if (initialUserConfigViewData.value) {
params.updates = [
{
data: {
configuration,
},
where: {
id: initialUserConfigViewData.value.id,
},
},
];
} else {
params.creates = [
{
userFk: user.value.id,
tableCode: $props.tableCode,
tableConfig: $props.tableCode,
configuration,
},
];
}
const response = await axios.post('UserConfigViews/crud', params);
if (response.data && response.data[0]) {
initialUserConfigViewData.value = response.data[0];
}
notify('globals.dataSaved', 'positive');
popupProxyRef.value.hide();
} catch (err) {
console.error('Error saving user view config', err);
notify('errors.writeRequest', 'negative');
}
}
onMounted(async () => {
setUserConfigViewData({});
await fetchViewConfigData();
});
</script>
<template>
<QBtn icon="vn:visible_columns" class="bg-vn-section-color q-mr-sm q-px-sm" dense>
<QPopupProxy ref="popupProxyRef">
<QCard class="column q-pa-md">
<QIcon name="info" size="sm" class="info-icon">
<QTooltip>{{ t('Check the columns you want to see') }}</QTooltip>
</QIcon>
<span class="text-body1 q-mb-sm">{{ t('Visible columns') }}</span>
<QCheckbox
:label="t('Tick all')"
:model-value="areAllChecksMarked"
@update:model-value="toggleMarkAll($event)"
class="q-mb-sm"
/>
<div v-if="columns.length > 0" class="checks-layout">
<QCheckbox
v-for="col in localColumns"
:key="col.name"
:label="col.label"
v-model="col.visible"
/>
</div>
<QBtn
class="full-width q-mt-md"
color="primary"
@click="saveConfig()"
:label="t('globals.save')"
/>
</QCard>
</QPopupProxy>
<QTooltip>{{ t('Visible columns') }}</QTooltip>
</QBtn>
</template>
<style lang="scss" scoped>
.info-icon {
position: absolute;
top: 20px;
right: 20px;
}
.checks-layout {
display: grid;
grid-template-columns: repeat(3, 200px);
}
</style>
<i18n>
es:
Check the columns you want to see: Marca las columnas que quieres ver
Visible columns: Columnas visibles
Tick all: Marcar todas
</i18n>

View File

@ -37,7 +37,7 @@ const stateStore = useStateStore();
@click="stateStore.toggleRightDrawer()" @click="stateStore.toggleRightDrawer()"
round round
dense dense
icon="dock_to_left" icon="menu"
> >
<QTooltip bottom anchor="bottom right"> <QTooltip bottom anchor="bottom right">
{{ t('globals.collapseMenu') }} {{ t('globals.collapseMenu') }}
@ -46,7 +46,7 @@ const stateStore = useStateStore();
</div> </div>
</Teleport> </Teleport>
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above> <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
<QScrollArea class="fit"> <QScrollArea class="fit text-grey-8">
<div id="right-panel"></div> <div id="right-panel"></div>
<slot v-if="!hasContent" name="right-panel" /> <slot v-if="!hasContent" name="right-panel" />
</QScrollArea> </QScrollArea>

View File

@ -52,77 +52,79 @@ const toggleMarkAll = (val) => {
const getConfig = async (url, filter) => { const getConfig = async (url, filter) => {
const response = await axios.get(url, { const response = await axios.get(url, {
params: { filter: JSON.stringify(filter) }, params: { filter: filter },
}); });
return response.data && response.data.length > 0 ? response.data[0] : null; return response.data && response.data.length > 0 ? response.data[0] : null;
}; };
const fetchViewConfigData = async () => { const fetchViewConfigData = async () => {
const userConfigFilter = { try {
where: { tableCode: $props.tableCode, userFk: user.value.id }, const userConfigFilter = {
}; where: { tableCode: $props.tableCode, userFk: user.id },
const userConfig = await getConfig('UserConfigViews', userConfigFilter); };
const userConfig = await getConfig('UserConfigViews', userConfigFilter);
if (userConfig) { if (userConfig) {
initialUserConfigViewData.value = userConfig; initialUserConfigViewData.value = userConfig;
setUserConfigViewData(userConfig.configuration); setUserConfigViewData(userConfig.configuration);
return; return;
} }
const defaultConfigFilter = { where: { tableCode: $props.tableCode } }; const defaultConfigFilter = { where: { tableCode: $props.tableCode } };
const defaultConfig = await getConfig('DefaultViewConfigs', defaultConfigFilter); const defaultConfig = await getConfig('DefaultViewConfigs', defaultConfigFilter);
if (defaultConfig) { if (defaultConfig) {
// Si el backend devuelve una configuración por defecto la usamos setUserConfigViewData(defaultConfig.columns);
setUserConfigViewData(defaultConfig.columns); return;
return; }
} else { } catch (err) {
// Si no hay configuración por defecto mostramos todas las columnas console.err('Error fetching config view data', err);
const defaultColumns = {};
$props.allColumns.forEach((col) => (defaultColumns[col] = true));
setUserConfigViewData(defaultColumns);
} }
}; };
const saveConfig = async () => { const saveConfig = async () => {
const params = {}; try {
const configuration = {}; const params = {};
const configuration = {};
formattedCols.value.forEach((col) => { formattedCols.value.forEach((col) => {
const { name, active } = col; const { name, active } = col;
configuration[name] = active; configuration[name] = active;
}); });
// Si existe una view config del usuario hacemos un update si no la creamos // Si existe una view config del usuario hacemos un update si no la creamos
if (initialUserConfigViewData.value) { if (initialUserConfigViewData.value) {
params.updates = [ params.updates = [
{ {
data: { data: {
configuration: configuration,
},
where: {
id: initialUserConfigViewData.value.id,
},
},
];
} else {
params.creates = [
{
userFk: user.value.id,
tableCode: $props.tableCode,
tableConfig: $props.tableCode,
configuration: configuration, configuration: configuration,
}, },
where: { ];
id: initialUserConfigViewData.value.id, }
},
},
];
} else {
params.creates = [
{
userFk: user.value.id,
tableCode: $props.tableCode,
tableConfig: $props.tableCode,
configuration: configuration,
},
];
}
const response = await axios.post('UserConfigViews/crud', params); const response = await axios.post('UserConfigViews/crud', params);
if (response.data && response.data[0]) { if (response.data && response.data[0]) {
initialUserConfigViewData.value = response.data[0]; initialUserConfigViewData.value = response.data[0];
}
emitSavedConfig();
notify('globals.dataSaved', 'positive');
popupProxyRef.value.hide();
} catch (err) {
console.error('Error saving user view config', err);
} }
emitSavedConfig();
notify('globals.dataSaved', 'positive');
popupProxyRef.value.hide();
}; };
const emitSavedConfig = () => { const emitSavedConfig = () => {

View File

@ -1,24 +1,20 @@
<script setup> <script setup>
import { nextTick, ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { QInput } from 'quasar'; import { QInput } from 'quasar';
const $props = defineProps({ const props = defineProps({
modelValue: { modelValue: {
type: String, type: String,
default: '', default: '',
}, },
insertable: {
type: Boolean,
default: false,
},
}); });
const emit = defineEmits(['update:modelValue', 'accountShortToStandard']); const emit = defineEmits(['update:modelValue', 'accountShortToStandard']);
let internalValue = ref($props.modelValue); let internalValue = ref(props.modelValue);
watch( watch(
() => $props.modelValue, () => props.modelValue,
(newVal) => { (newVal) => {
internalValue.value = newVal; internalValue.value = newVal;
} }
@ -32,46 +28,8 @@ watch(
} }
); );
const handleKeydown = (e) => {
if (e.key === 'Backspace') return;
if (e.key === '.') {
accountShortToStandard();
// TODO: Fix this setTimeout, with nextTick doesn't work
setTimeout(() => {
setCursorPosition(0, e.target);
}, 1);
return;
}
if ($props.insertable && e.key.match(/[0-9]/)) {
handleInsertMode(e);
}
};
function setCursorPosition(pos, el = vnInputRef.value) {
el.focus();
el.setSelectionRange(pos, pos);
}
const vnInputRef = ref(false);
const handleInsertMode = (e) => {
e.preventDefault();
const input = e.target;
const cursorPos = input.selectionStart;
const { maxlength } = vnInputRef.value;
let currentValue = internalValue.value;
if (!currentValue) currentValue = e.key;
const newValue = e.key;
if (newValue && !isNaN(newValue) && cursorPos < maxlength) {
internalValue.value =
currentValue.substring(0, cursorPos) +
newValue +
currentValue.substring(cursorPos + 1);
}
nextTick(() => {
input.setSelectionRange(cursorPos + 1, cursorPos + 1);
});
};
function accountShortToStandard() { function accountShortToStandard() {
internalValue.value = internalValue.value?.replace( internalValue.value = internalValue.value.replace(
'.', '.',
'0'.repeat(11 - internalValue.value.length) '0'.repeat(11 - internalValue.value.length)
); );
@ -79,5 +37,5 @@ function accountShortToStandard() {
</script> </script>
<template> <template>
<QInput @keydown="handleKeydown" ref="vnInputRef" v-model="internalValue" /> <q-input v-model="internalValue" />
</template> </template>

View File

@ -18,7 +18,7 @@ watchEffect(() => {
(matched) => Object.keys(matched.meta).length (matched) => Object.keys(matched.meta).length
); );
breadcrumbs.value.length = 0; breadcrumbs.value.length = 0;
if (!matched.value[0]) return;
if (matched.value[0].name != 'Dashboard') { if (matched.value[0].name != 'Dashboard') {
root.value = useCamelCase(matched.value[0].path.substring(1).toLowerCase()); root.value = useCamelCase(matched.value[0].path.substring(1).toLowerCase());

View File

@ -1,19 +0,0 @@
<script setup>
import VnSelect from './VnSelect.vue';
defineProps({
selectProps: { type: Object, required: true },
promise: { type: Function, default: () => {} },
});
</script>
<template>
<QBtnDropdown v-bind="$attrs" color="primary">
<VnSelect
v-bind="selectProps"
hide-selected
hide-dropdown-icon
focus-on-mount
@update:model-value="promise"
/>
</QBtnDropdown>
</template>

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { onBeforeMount, computed } from 'vue'; import { onBeforeMount, computed } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'; import { useRoute } from 'vue-router';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import useCardSize from 'src/composables/useCardSize'; import useCardSize from 'src/composables/useCardSize';
@ -8,6 +8,7 @@ import VnSubToolbar from '../ui/VnSubToolbar.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue'; import VnSearchbar from 'components/ui/VnSearchbar.vue';
import LeftMenu from 'components/LeftMenu.vue'; import LeftMenu from 'components/LeftMenu.vue';
import RightMenu from 'components/common/RightMenu.vue'; import RightMenu from 'components/common/RightMenu.vue';
const props = defineProps({ const props = defineProps({
dataKey: { type: String, required: true }, dataKey: { type: String, required: true },
baseUrl: { type: String, default: undefined }, baseUrl: { type: String, default: undefined },
@ -16,47 +17,30 @@ const props = defineProps({
descriptor: { type: Object, required: true }, descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined }, filterPanel: { type: Object, default: undefined },
searchDataKey: { type: String, default: undefined }, searchDataKey: { type: String, default: undefined },
searchbarProps: { type: Object, default: undefined }, searchUrl: { type: String, default: undefined },
redirectOnError: { type: Boolean, default: false }, searchbarLabel: { type: String, default: '' },
searchbarInfo: { type: String, default: '' },
searchCustomRouteRedirect: { type: String, default: undefined },
searchRedirect: { type: Boolean, default: true },
searchMakeFetch: { type: Boolean, default: true },
}); });
const stateStore = useStateStore(); const stateStore = useStateStore();
const route = useRoute(); const route = useRoute();
const router = useRouter();
const url = computed(() => { const url = computed(() => {
if (props.baseUrl) { if (props.baseUrl) return `${props.baseUrl}/${route.params.id}`;
return `${props.baseUrl}/${route.params.id}`;
}
return props.customUrl; return props.customUrl;
}); });
const searchRightDataKey = computed(() => {
if (!props.searchDataKey) return route.name;
return props.searchDataKey;
});
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: url.value, url: url.value,
filter: props.filter, filter: props.filter,
}); });
onBeforeMount(async () => { onBeforeMount(async () => {
try { if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id };
if (!props.baseUrl) arrayData.store.filter.where = { id: route.params.id }; await arrayData.fetch({ append: false });
await arrayData.fetch({ append: false, updateRouter: false });
} catch {
const { matched: matches } = router.currentRoute.value;
const { path } = matches.at(-1);
router.push({ path: path.replace(/:id.*/, '') });
}
}); });
if (props.baseUrl) {
onBeforeRouteUpdate(async (to, from) => {
if (to.params.id !== from.params.id) {
arrayData.store.url = `${props.baseUrl}/${to.params.id}`;
await arrayData.fetch({ append: false, updateRouter: false });
}
});
}
</script> </script>
<template> <template>
<QDrawer <QDrawer
@ -72,18 +56,26 @@ if (props.baseUrl) {
</QScrollArea> </QScrollArea>
</QDrawer> </QDrawer>
<slot name="searchbar" v-if="props.searchDataKey"> <slot name="searchbar" v-if="props.searchDataKey">
<VnSearchbar :data-key="props.searchDataKey" v-bind="props.searchbarProps" /> <VnSearchbar
:data-key="props.searchDataKey"
:url="props.searchUrl"
:label="props.searchbarLabel"
:info="props.searchbarInfo"
:custom-route-redirect-name="searchCustomRouteRedirect"
:redirect="searchRedirect"
/>
</slot> </slot>
<slot v-else name="searchbar" />
<RightMenu> <RightMenu>
<template #right-panel v-if="props.filterPanel"> <template #right-panel v-if="props.filterPanel">
<component :is="props.filterPanel" :data-key="searchRightDataKey" /> <component :is="props.filterPanel" :data-key="props.searchDataKey" />
</template> </template>
</RightMenu> </RightMenu>
<QPageContainer> <QPageContainer>
<QPage> <QPage>
<VnSubToolbar /> <VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]"> <div :class="[useCardSize(), $attrs.class]">
<RouterView :key="route.path" /> <RouterView />
</div> </div>
</QPage> </QPage>
</QPageContainer> </QPageContainer>

View File

@ -1,136 +0,0 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import VnRow from '../ui/VnRow.vue';
import VnInput from './VnInput.vue';
import FetchData from '../FetchData.vue';
import useNotify from 'src/composables/useNotify';
const props = defineProps({
submitFn: { type: Function, default: () => {} },
askOldPass: { type: Boolean, default: false },
});
const emit = defineEmits(['onSubmit']);
const { t } = useI18n();
const { notify } = useNotify();
const form = ref();
const changePassDialog = ref();
const passwords = ref({ newPassword: null, repeatPassword: null });
const requirements = ref([]);
const isLoading = ref(false);
const validate = async () => {
const { newPassword, repeatPassword, oldPassword } = passwords.value;
if (!newPassword) {
notify(t('You must enter a new password'), 'negative');
return;
}
if (newPassword !== repeatPassword) {
notify(t("Passwords don't match"), 'negative');
return;
}
try {
isLoading.value = true;
await props.submitFn(newPassword, oldPassword);
emit('onSubmit');
} catch (e) {
notify('errors.writeRequest', 'negative');
} finally {
changePassDialog.value.hide();
isLoading.value = false;
}
};
defineExpose({ show: () => changePassDialog.value.show() });
</script>
<template>
<FetchData
url="UserPasswords/findOne"
auto-load
@on-fetch="(data) => (requirements = data)"
/>
<QDialog ref="changePassDialog">
<QCard style="width: 350px">
<QCardSection>
<slot name="header">
<VnRow class="items-center" style="flex-direction: row">
<span class="text-h6" v-text="t('globals.changePass')" />
<QIcon
class="cursor-pointer"
name="close"
size="xs"
style="flex: 0"
v-close-popup
/>
</VnRow>
</slot>
</QCardSection>
<QForm ref="form">
<QCardSection>
<VnInput
v-if="props.askOldPass"
:label="t('Old password')"
v-model="passwords.oldPassword"
type="password"
:required="true"
autofocus
/>
<VnInput
:label="t('New password')"
v-model="passwords.newPassword"
type="password"
:required="true"
:info="
t('passwordRequirements', {
length: requirements.length,
nAlpha: requirements.nAlpha,
nUpper: requirements.nUpper,
nDigits: requirements.nDigits,
nPunct: requirements.nPunct,
})
"
autofocus
/>
<VnInput
:label="t('Repeat password')"
v-model="passwords.repeatPassword"
type="password"
/>
</QCardSection>
</QForm>
<QCardActions>
<slot name="actions">
<QBtn
:disabled="isLoading"
:loading="isLoading"
:label="t('globals.cancel')"
class="q-ml-sm"
color="primary"
flat
type="reset"
v-close-popup
/>
<QBtn
:disabled="isLoading"
:loading="isLoading"
:label="t('globals.confirm')"
color="primary"
@click="validate"
/>
</slot>
</QCardActions>
</QCard>
</QDialog>
</template>
<i18n>
es:
New password: Nueva contraseña
Repeat password: Repetir contraseña
You must enter a new password: Debes introducir la nueva contraseña
Passwords don't match: Las contraseñas no coinciden
</i18n>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed } from 'vue'; import { computed, defineModel } from 'vue';
const model = defineModel(undefined, { required: true }); const model = defineModel(undefined, { required: true });
const $props = defineProps({ const $props = defineProps({
@ -12,7 +12,7 @@ const $props = defineProps({
default: () => {}, default: () => {},
}, },
value: { value: {
type: [Object, Number, String, Boolean], type: [Object, Number, String],
default: () => {}, default: () => {},
}, },
}); });
@ -33,7 +33,7 @@ function mix(toComponent) {
...toComponent, ...toComponent,
...toValueAttrs(customComponent?.forceAttrs), ...toValueAttrs(customComponent?.forceAttrs),
}, },
event: { ...customComponent?.event, ...event }, event: event ?? customComponent?.event,
}; };
} }
@ -54,6 +54,7 @@ function toValueAttrs(attrs) {
v-bind="mix(toComponent).attrs" v-bind="mix(toComponent).attrs"
v-on="mix(toComponent).event ?? {}" v-on="mix(toComponent).event ?? {}"
v-model="model" v-model="model"
class="fit"
/> />
</span> </span>
</template> </template>

View File

@ -0,0 +1,34 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useCapitalize } from 'src/composables/useCapitalize';
import VnInput from 'src/components/common/VnInput.vue';
const props = defineProps({
modelValue: { type: [String, Number], default: '' },
});
const { t } = useI18n();
const emit = defineEmits(['update:modelValue']);
const amount = computed({
get() {
return props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
</script>
<template>
<VnInput
v-model="amount"
type="number"
step="any"
:label="useCapitalize(t('amount'))"
/>
</template>
<i18n>
es:
amount: importe
</i18n>

View File

@ -1,29 +0,0 @@
<script setup>
const model = defineModel({ type: [String, Number], required: true });
</script>
<template>
<QDate v-model="model" :today-btn="true" :options="$attrs.options" />
</template>
<style lang="scss" scoped>
.q-date {
width: 245px;
min-width: unset;
:deep(.q-date__calendar) {
padding-bottom: 0;
}
:deep(.q-date__view) {
min-height: 245px;
padding: 8px;
}
:deep(.q-date__calendar-days-container) {
min-height: 160px;
height: unset;
}
:deep(.q-date__header) {
padding: 2px 2px 5px 12px;
height: 60px;
}
}
</style>

View File

@ -1,31 +0,0 @@
<script setup>
import { toDateFormat } from 'src/filters/date.js';
defineProps({ date: { type: [Date, String], required: true } });
function getBadgeAttrs(date) {
let today = Date.vnNew();
today.setHours(0, 0, 0, 0);
let timeTicket = new Date(date);
timeTicket.setHours(0, 0, 0, 0);
let timeDiff = today - timeTicket;
if (timeDiff == 0) return { color: 'warning', 'text-color': 'black' };
if (timeDiff < 0) return { color: 'success', 'text-color': 'black' };
return { color: 'transparent', 'text-color': 'white' };
}
function formatShippedDate(date) {
if (!date) return '-';
const dateSplit = date.split('T');
const [year, month, day] = dateSplit[0].split('-');
const newDate = new Date(year, month - 1, day);
return toDateFormat(newDate);
}
</script>
<template>
<QBadge v-bind="getBadgeAttrs(date)" class="q-pa-sm" style="font-size: 14px">
{{ formatShippedDate(date) }}
</QBadge>
</template>

View File

@ -31,10 +31,6 @@ const $props = defineProps({
type: String, type: String,
default: null, default: null,
}, },
description: {
type: String,
default: null,
},
}); });
const warehouses = ref(); const warehouses = ref();
@ -47,8 +43,7 @@ const dms = ref({});
onMounted(() => { onMounted(() => {
defaultData(); defaultData();
if (!$props.formInitialData) if (!$props.formInitialData)
dms.value.description = dms.value.description = t($props.model + 'Description', dms.value);
$props.description ?? t($props.model + 'Description', dms.value);
}); });
function onFileChange(files) { function onFileChange(files) {
dms.value.hasFileAttached = !!files; dms.value.hasFileAttached = !!files;
@ -59,6 +54,7 @@ function mapperDms(data) {
const formData = new FormData(); const formData = new FormData();
const { files } = data; const { files } = data;
if (files) formData.append(files?.name, files); if (files) formData.append(files?.name, files);
delete data.files;
const dms = { const dms = {
hasFile: !!data.hasFile, hasFile: !!data.hasFile,
@ -82,7 +78,6 @@ async function save() {
const body = mapperDms(dms.value); const body = mapperDms(dms.value);
const response = await axios.post(getUrl(), body[0], body[1]); const response = await axios.post(getUrl(), body[0], body[1]);
emit('onDataSaved', body[1].params, response); emit('onDataSaved', body[1].params, response);
delete dms.value.files;
return response; return response;
} }
@ -163,14 +158,13 @@ function addDefaultData(data) {
/> />
<QFile <QFile
ref="inputFileRef" ref="inputFileRef"
:label="t('globals.file')" :label="t('entry.buys.file')"
v-model="dms.files" v-model="dms.files"
:multiple="false" :multiple="false"
:accept="allowedContentTypes" :accept="allowedContentTypes"
@update:model-value="onFileChange(dms.files)" @update:model-value="onFileChange(dms.files)"
class="required" class="required"
:display-value="dms.file" :display-value="dms.file"
data-cy="VnDms_inputFile"
> >
<template #append> <template #append>
<QIcon <QIcon

View File

@ -5,14 +5,12 @@ import { useRoute } from 'vue-router';
import { useQuasar, QCheckbox, QBtn, QInput } from 'quasar'; import { useQuasar, QCheckbox, QBtn, QInput } from 'quasar';
import axios from 'axios'; import axios from 'axios';
import VnUserLink from '../ui/VnUserLink.vue';
import { downloadFile } from 'src/composables/downloadFile';
import VnImg from 'components/ui/VnImg.vue';
import VnPaginate from 'components/ui/VnPaginate.vue'; import VnPaginate from 'components/ui/VnPaginate.vue';
import VnDms from 'src/components/common/VnDms.vue'; import VnDms from 'src/components/common/VnDms.vue';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnConfirm from 'components/ui/VnConfirm.vue';
import VnInputDate from 'components/common/VnInputDate.vue'; import VnInputDate from 'components/common/VnInputDate.vue';
import { useSession } from 'src/composables/useSession'; import VnUserLink from '../ui/VnUserLink.vue';
import { downloadFile } from 'src/composables/downloadFile';
const route = useRoute(); const route = useRoute();
const quasar = useQuasar(); const quasar = useQuasar();
@ -20,7 +18,6 @@ const { t } = useI18n();
const rows = ref(); const rows = ref();
const dmsRef = ref(); const dmsRef = ref();
const formDialog = ref({}); const formDialog = ref({});
const token = useSession().getTokenMultimedia();
const $props = defineProps({ const $props = defineProps({
model: { model: {
@ -92,23 +89,6 @@ const dmsFilter = {
}; };
const columns = computed(() => [ const columns = computed(() => [
{
label: '',
name: 'file',
align: 'left',
component: VnImg,
props: (prop) => {
return {
storage: 'dms',
collection: null,
resolution: null,
id: prop.row.file.split('.')[0],
token: token,
class: 'rounded',
ratio: 1,
};
},
},
{ {
align: 'left', align: 'left',
field: 'id', field: 'id',
@ -155,13 +135,19 @@ const columns = computed(() => [
field: 'hasFile', field: 'hasFile',
label: t('globals.original'), label: t('globals.original'),
name: 'hasFile', name: 'hasFile',
toolTip: t('The documentation is available in paper form'),
component: QCheckbox, component: QCheckbox,
props: (prop) => ({ props: (prop) => ({
disable: true, disable: true,
'model-value': Boolean(prop.value), 'model-value': Boolean(prop.value),
}), }),
}, },
{
align: 'left',
field: 'file',
label: t('globals.file'),
name: 'file',
component: 'span',
},
{ {
align: 'left', align: 'left',
field: 'worker', field: 'worker',
@ -287,10 +273,6 @@ function shouldRenderButton(button, isExternal = false) {
if (button.name == 'download') return true; if (button.name == 'download') return true;
return button.external === isExternal; return button.external === isExternal;
} }
defineExpose({
dmsRef,
});
</script> </script>
<template> <template>
<VnPaginate <VnPaginate
@ -311,14 +293,6 @@ defineExpose({
row-key="clientFk" row-key="clientFk"
:grid="$q.screen.lt.sm" :grid="$q.screen.lt.sm"
> >
<template #header="props">
<QTr :props="props" class="bg">
<QTh v-for="col in props.cols" :key="col.name" :props="props">
<QTooltip v-if="col.toolTip">{{ col.toolTip }}</QTooltip
>{{ col.label }}
</QTh>
</QTr>
</template>
<template #body-cell="props"> <template #body-cell="props">
<QTd :props="props"> <QTd :props="props">
<QTr :props="props"> <QTr :props="props">
@ -400,21 +374,14 @@ defineExpose({
/> />
</QDialog> </QDialog>
<QPageSticky position="bottom-right" :offset="[25, 25]"> <QPageSticky position="bottom-right" :offset="[25, 25]">
<QBtn <QBtn fab color="primary" icon="add" @click="showFormDialog()" />
fab
color="primary"
icon="add"
shortcut="+"
@click="showFormDialog()"
class="fill-icon"
>
<QTooltip>
{{ t('Upload file') }}
</QTooltip>
</QBtn>
</QPageSticky> </QPageSticky>
</template> </template>
<style scoped> <style scoped>
.q-gutter-y-ms {
display: grid;
row-gap: 20px;
}
.labelColor { .labelColor {
color: var(--vn-label-color); color: var(--vn-label-color);
} }
@ -422,10 +389,7 @@ defineExpose({
<i18n> <i18n>
en: en:
contentTypesInfo: Allowed file types {allowedContentTypes} contentTypesInfo: Allowed file types {allowedContentTypes}
The documentation is available in paper form: The documentation is available in paper form
es: es:
contentTypesInfo: Tipos de archivo permitidos {allowedContentTypes} contentTypesInfo: Tipos de archivo permitidos {allowedContentTypes}
Generate identifier for original file: Generar identificador para archivo original Generate identifier for original file: Generar identificador para archivo original
Upload file: Subir fichero
the documentation is available in paper form: Se tiene la documentación en papel
</i18n> </i18n>

View File

@ -1,11 +1,7 @@
<script setup> <script setup>
import { computed, ref, useAttrs, nextTick } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRequired } from 'src/composables/useRequired';
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const { t } = useI18n();
const emit = defineEmits([ const emit = defineEmits([
'update:modelValue', 'update:modelValue',
'update:options', 'update:options',
@ -30,27 +26,16 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: true, default: true,
}, },
emptyToNull: {
type: Boolean,
default: true,
},
insertable: {
type: Boolean,
default: false,
},
maxlength: {
type: Number,
default: null,
},
}); });
const { t } = useI18n();
const requiredFieldRule = (val) => !!val || t('globals.fieldRequired');
const vnInputRef = ref(null); const vnInputRef = ref(null);
const value = computed({ const value = computed({
get() { get() {
return $props.modelValue; return $props.modelValue;
}, },
set(value) { set(value) {
if ($props.emptyToNull && value === '') value = null;
emit('update:modelValue', value); emit('update:modelValue', value);
}, },
}); });
@ -73,90 +58,43 @@ defineExpose({
focus, focus,
}); });
const mixinRules = [ const inputRules = [
requiredFieldRule,
...($attrs.rules ?? []),
(val) => { (val) => {
const { maxlength } = vnInputRef.value; const { min } = vnInputRef.value.$attrs;
if (maxlength && +val.length > maxlength)
return t(`maxLength`, { value: maxlength });
const { min, max } = vnInputRef.value.$attrs;
if (!min) return null;
if (min >= 0) if (Math.floor(val) < min) return t('inputMin', { value: min }); if (min >= 0) if (Math.floor(val) < min) return t('inputMin', { value: min });
if (!max) return null;
if (max > 0) {
if (Math.floor(val) > max) return t('inputMax', { value: max });
}
}, },
]; ];
const handleKeydown = (e) => {
if (e.key === 'Backspace') return;
if ($props.insertable && e.key.match(/[0-9]/)) {
handleInsertMode(e);
}
};
const handleInsertMode = (e) => {
e.preventDefault();
const input = e.target;
const cursorPos = input.selectionStart;
const { maxlength } = vnInputRef.value;
let currentValue = value.value;
if (!currentValue) currentValue = e.key;
const newValue = e.key;
if (newValue && !isNaN(newValue) && cursorPos < maxlength) {
value.value =
currentValue.substring(0, cursorPos) +
newValue +
currentValue.substring(cursorPos + 1);
}
nextTick(() => {
input.setSelectionRange(cursorPos + 1, cursorPos + 1);
});
};
</script> </script>
<template> <template>
<div @mouseover="hover = true" @mouseleave="hover = false"> <div
@mouseover="hover = true"
@mouseleave="hover = false"
:rules="$attrs.required ? [requiredFieldRule] : null"
>
<QInput <QInput
ref="vnInputRef" ref="vnInputRef"
v-model="value" v-model="value"
v-bind="{ ...$attrs, ...styleAttrs }" v-bind="{ ...$attrs, ...styleAttrs }"
:type="$attrs.type" :type="$attrs.type"
:class="{ required: isRequired }" :class="{ required: $attrs.required }"
@keyup.enter="emit('keyup.enter')" @keyup.enter="emit('keyup.enter')"
@keydown="handleKeydown"
:clearable="false" :clearable="false"
:rules="mixinRules" :rules="inputRules"
:lazy-rules="true" :lazy-rules="true"
hide-bottom-space hide-bottom-space
:data-cy="$attrs.dataCy ?? $attrs.label + '_input'"
> >
<template v-if="$slots.prepend" #prepend> <template v-if="$slots.prepend" #prepend>
<slot name="prepend" /> <slot name="prepend" />
</template> </template>
<template #append> <template #append>
<slot name="append" v-if="$slots.append && !$attrs.disabled" />
<QIcon <QIcon
name="close" name="close"
size="xs" size="xs"
v-if=" v-if="hover && value && !$attrs.disabled && $props.clearable"
hover && @click="value = null"
value &&
!$attrs.disabled &&
!$attrs.readonly &&
$props.clearable
"
@click="
() => {
value = null;
vnInputRef.focus();
emit('remove');
}
"
></QIcon> ></QIcon>
<slot name="append" v-if="$slots.append && !$attrs.disabled" />
<QIcon v-if="info" name="info"> <QIcon v-if="info" name="info">
<QTooltip max-width="350px"> <QTooltip max-width="350px">
{{ info }} {{ info }}
@ -169,15 +107,6 @@ const handleInsertMode = (e) => {
<i18n> <i18n>
en: en:
inputMin: Must be more than {value} inputMin: Must be more than {value}
maxLength: The value exceeds {value} characters
inputMax: Must be less than {value}
es: es:
inputMin: Debe ser mayor a {value} inputMin: Debe ser mayor a {value}
maxLength: El valor excede los {value} carácteres
inputMax: Debe ser menor a {value}
</i18n> </i18n>
<style lang="scss">
.q-field__append {
padding-inline: 0;
}
</style>

View File

@ -1,85 +1,80 @@
<script setup> <script setup>
import { onMounted, watch, computed, ref, useAttrs } from 'vue'; import { computed, ref } from 'vue';
import { date } from 'quasar'; import isValidDate from 'filters/isValidDate';
import { useI18n } from 'vue-i18n';
import VnDate from './VnDate.vue';
import { useRequired } from 'src/composables/useRequired';
const $attrs = useAttrs(); const props = defineProps({
const { isRequired, requiredFieldRule } = useRequired($attrs); modelValue: {
const model = defineModel({ type: [String, Date] }); type: String,
const { t } = useI18n(); default: null,
},
const $props = defineProps({ readonly: {
type: Boolean,
default: false,
},
isOutlined: { isOutlined: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
showEvent: { emitDateFormat: {
type: Boolean, type: Boolean,
default: true, default: false,
}, },
}); });
const hover = ref(false);
const vnInputDateRef = ref(null); const emit = defineEmits(['update:modelValue']);
const dateFormat = 'DD/MM/YYYY'; const joinDateAndTime = (date, time) => {
const isPopupOpen = ref(); if (!date) {
const hover = ref(); return null;
const mask = ref(); }
if (!time) {
return new Date(date).toISOString();
}
const [year, month, day] = date.split('/');
return new Date(`${year}-${month}-${day}T${time}`).toISOString();
};
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])]; const time = computed(() => (props.modelValue ? props.modelValue.split('T')?.[1] : null));
const value = computed({
const formattedDate = computed({
get() { get() {
if (!model.value) return model.value; return props.modelValue;
return date.formatDate(new Date(model.value), dateFormat);
}, },
set(value) { set(value) {
if (value == model.value) return; emit(
let newDate; 'update:modelValue',
if (value) { props.emitDateFormat ? new Date(value) : joinDateAndTime(value, time.value)
// parse input );
if (value.includes('/') && value.length >= 10) {
if (value.at(2) == '/') value = value.split('/').reverse().join('/');
value = date.formatDate(
new Date(value).toISOString(),
'YYYY-MM-DDTHH:mm:ss.SSSZ'
);
}
const [year, month, day] = value.split('-').map((e) => parseInt(e));
newDate = new Date(year, month - 1, day);
if (model.value) {
const orgDate =
model.value instanceof Date ? model.value : new Date(model.value);
newDate.setHours(
orgDate.getHours(),
orgDate.getMinutes(),
orgDate.getSeconds(),
orgDate.getMilliseconds()
);
}
}
if (!isNaN(newDate)) model.value = newDate.toISOString();
}, },
}); });
const popupDate = computed(() => const isPopupOpen = ref(false);
model.value ? date.formatDate(new Date(model.value), 'YYYY/MM/DD') : model.value
); const onDateUpdate = (date) => {
onMounted(() => { value.value = date;
// fix quasar bug isPopupOpen.value = false;
mask.value = '##/##/####'; };
});
watch( const padDate = (value) => value.toString().padStart(2, '0');
() => model.value, const formatDate = (dateString) => {
(val) => (formattedDate.value = val), const date = new Date(dateString || '');
{ immediate: true } return `${date.getFullYear()}/${padDate(date.getMonth() + 1)}/${padDate(
); date.getDate()
)}`;
};
const displayDate = (dateString) => {
if (!dateString || !isValidDate(dateString)) {
return '';
}
return new Date(dateString).toLocaleDateString([], {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
};
const styleAttrs = computed(() => { const styleAttrs = computed(() => {
return $props.isOutlined return props.isOutlined
? { ? {
dense: true, dense: true,
outlined: true, outlined: true,
@ -87,70 +82,44 @@ const styleAttrs = computed(() => {
} }
: {}; : {};
}); });
const manageDate = (date) => {
formattedDate.value = date;
isPopupOpen.value = false;
};
</script> </script>
<template> <template>
<div @mouseover="hover = true" @mouseleave="hover = false"> <div @mouseover="hover = true" @mouseleave="hover = false">
<QInput <QInput
ref="vnInputDateRef"
v-model="formattedDate"
class="vn-input-date" class="vn-input-date"
:mask="mask" readonly
placeholder="dd/mm/aaaa" :model-value="displayDate(value)"
v-bind="{ ...$attrs, ...styleAttrs }" v-bind="{ ...$attrs, ...styleAttrs }"
:class="{ required: isRequired }"
:rules="mixinRules"
:clearable="false"
@click="isPopupOpen = true" @click="isPopupOpen = true"
hide-bottom-space
> >
<template #append> <template #append>
<QIcon <QIcon
name="close" name="close"
size="xs" size="xs"
v-if=" v-if="hover && value && !readonly"
($attrs.clearable == undefined || $attrs.clearable) && @click="onDateUpdate(null)"
hover && ></QIcon>
model && <QIcon name="event" class="cursor-pointer">
!$attrs.disable <QPopupProxy
" v-model="isPopupOpen"
@click=" cover
vnInputDateRef.focus(); transition-show="scale"
model = null; transition-hide="scale"
isPopupOpen = false; :no-parent-event="props.readonly"
" >
/> <QDate
<QIcon :today-btn="true"
v-if="showEvent" :model-value="formatDate(value)"
name="event" @update:model-value="onDateUpdate"
class="cursor-pointer" />
@click="isPopupOpen = !isPopupOpen" </QPopupProxy>
:title="t('Open date')" </QIcon>
/>
</template> </template>
<QMenu
v-if="$q.screen.gt.xs"
transition-show="scale"
transition-hide="scale"
v-model="isPopupOpen"
anchor="bottom left"
self="top start"
:no-focus="true"
:no-parent-event="true"
>
<VnDate v-model="popupDate" @update:model-value="manageDate" />
</QMenu>
<QDialog v-else v-model="isPopupOpen">
<VnDate v-model="popupDate" @update:model-value="manageDate" />
</QDialog>
</QInput> </QInput>
</div> </div>
</template> </template>
<style lang="scss"> <style lang="scss">
.vn-input-date.q-field--standard.q-field--readonly .q-field__control:before { .vn-input-date.q-field--standard.q-field--readonly .q-field__control:before {
border-bottom-style: solid; border-bottom-style: solid;
@ -160,7 +129,3 @@ const manageDate = (date) => {
border-style: solid; border-style: solid;
} }
</style> </style>
<i18n>
es:
Open date: Abrir fecha
</i18n>

View File

@ -1,13 +0,0 @@
<script setup>
import VnInput from 'src/components/common/VnInput.vue';
import { ref } from 'vue';
import { useAttrs } from 'vue';
const model = defineModel({ type: [Number, String] });
const $attrs = useAttrs();
const step = ref($attrs.step || 0.01);
</script>
<template>
<VnInput v-bind="$attrs" v-model.number="model" type="number" :step="step" />
</template>

View File

@ -1,16 +1,14 @@
<script setup> <script setup>
import { computed, ref, useAttrs } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { date } from 'quasar'; import isValidDate from 'filters/isValidDate';
import VnTime from './VnTime.vue';
import { useRequired } from 'src/composables/useRequired';
const $attrs = useAttrs();
const { isRequired, requiredFieldRule } = useRequired($attrs);
const { t } = useI18n();
const model = defineModel({ type: String });
const props = defineProps({ const props = defineProps({
timeOnly: { modelValue: {
type: String,
default: null,
},
readonly: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
@ -19,12 +17,42 @@ const props = defineProps({
default: false, default: false,
}, },
}); });
const vnInputTimeRef = ref(null); const { t } = useI18n();
const initialDate = ref(model.value ?? Date.vnNew()); const emit = defineEmits(['update:modelValue']);
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])];
const dateFormat = 'HH:mm'; const value = computed({
const isPopupOpen = ref(); get() {
const hover = ref(); return props.modelValue;
},
set(value) {
const [hours, minutes] = value.split(':');
const date = new Date(props.modelValue);
date.setHours(Number.parseInt(hours) || 0, Number.parseInt(minutes) || 0, 0, 0);
emit('update:modelValue', value ? date.toISOString() : null);
},
});
const isPopupOpen = ref(false);
const onDateUpdate = (date) => {
internalValue.value = date;
};
const save = () => {
value.value = internalValue.value;
};
const formatTime = (dateString) => {
if (!dateString || !isValidDate(dateString)) {
return '';
}
const date = new Date(dateString || '');
return date.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
});
};
const internalValue = ref(formatTime(value));
const styleAttrs = computed(() => { const styleAttrs = computed(() => {
return props.isOutlined return props.isOutlined
@ -35,96 +63,52 @@ const styleAttrs = computed(() => {
} }
: {}; : {};
}); });
const formattedTime = computed({
get() {
if (!model.value || model.value?.length <= 5) return model.value;
return dateToTime(model.value);
},
set(value) {
if (value == model.value) return;
let time = value;
if (time) {
if (time?.length > 5) time = dateToTime(time);
else {
if (time.length == 1 && parseInt(time) > 2) time = time.padStart(2, '0');
time = time.padEnd(5, '0');
if (!time.includes(':'))
time = time.substring(0, 2) + ':' + time.substring(3, 5);
}
if (!props.timeOnly) {
const [hh, mm] = time.split(':');
const date = new Date(model.value ? model.value : initialDate.value);
date.setHours(hh, mm, 0);
time = date?.toISOString();
}
}
model.value = time;
},
});
function dateToTime(newDate) {
return date.formatDate(new Date(newDate), dateFormat);
}
</script> </script>
<template> <template>
<div @mouseover="hover = true" @mouseleave="hover = false"> <QInput
<QInput class="vn-input-time"
ref="vnInputTimeRef" readonly
class="vn-input-time" :model-value="formatTime(value)"
mask="##:##" v-bind="{ ...$attrs, ...styleAttrs }"
placeholder="--:--" @click="isPopupOpen = true"
v-model="formattedTime" >
v-bind="{ ...$attrs, ...styleAttrs }" <template #append>
:class="{ required: isRequired }" <QIcon name="Schedule" class="cursor-pointer">
style="min-width: 100px" <QPopupProxy
:rules="mixinRules" v-model="isPopupOpen"
@click="isPopupOpen = false" cover
type="time" transition-show="scale"
hide-bottom-space transition-hide="scale"
> :no-parent-event="props.readonly"
<template #append> >
<QIcon <QTime
name="close" :format24h="false"
size="xs" :model-value="formatTime(value)"
v-if=" @update:model-value="onDateUpdate"
($attrs.clearable == undefined || $attrs.clearable) && >
hover && <div class="row items-center justify-end q-gutter-sm">
model && <QBtn
!$attrs.disable :label="t('Cancel')"
" color="primary"
@click=" flat
vnInputTimeRef.focus(); v-close-popup
model = null; />
isPopupOpen = false; <QBtn
" label="Ok"
/> color="primary"
<QIcon flat
name="Schedule" @click="save"
class="cursor-pointer" v-close-popup
@click="isPopupOpen = !isPopupOpen" />
:title="t('Open time')" </div>
/> </QTime>
</template> </QPopupProxy>
<QMenu </QIcon>
v-if="$q.screen.gt.xs" </template>
transition-show="scale" </QInput>
transition-hide="scale"
v-model="isPopupOpen"
anchor="bottom left"
self="top start"
:no-focus="true"
:no-parent-event="true"
>
<VnTime v-model="formattedTime" />
</QMenu>
<QDialog v-else v-model="isPopupOpen">
<VnTime v-model="formattedTime" />
</QDialog>
</QInput>
</div>
</template> </template>
<style lang="scss"> <style lang="scss">
.vn-input-time.q-field--standard.q-field--readonly .q-field__control:before { .vn-input-time.q-field--standard.q-field--readonly .q-field__control:before {
border-bottom-style: solid; border-bottom-style: solid;
@ -134,12 +118,8 @@ function dateToTime(newDate) {
border-style: solid; border-style: solid;
} }
</style> </style>
<style lang="scss" scoped>
:deep(input[type='time']::-webkit-calendar-picker-indicator) {
display: none;
}
</style>
<i18n> <i18n>
es: es:
Open time: Abrir tiempo Cancel: Cancelar
</i18n> </i18n>

View File

@ -1,93 +1,122 @@
<script setup> <script setup>
import { ref, toRefs, computed, watch, onMounted } from 'vue';
import CreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue'; import CreateNewPostcode from 'src/components/CreateNewPostcodeForm.vue';
import VnSelectDialog from 'components/common/VnSelectDialog.vue'; import VnSelectDialog from 'components/common/VnSelectDialog.vue';
import FetchData from 'components/FetchData.vue';
const emit = defineEmits(['update:modelValue', 'update:options']);
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { computed } from 'vue';
import { useAttrs } from 'vue';
import { useRequired } from 'src/composables/useRequired';
const { t } = useI18n(); const { t } = useI18n();
const emit = defineEmits(['update:model-value', 'update:options']); const postcodesOptions = ref([]);
const $attrs = useAttrs(); const postcodesRef = ref(null);
const { isRequired, requiredFieldRule } = useRequired($attrs);
const props = defineProps({ const $props = defineProps({
location: { modelValue: {
type: Object, type: [String, Number, Object],
default: null, default: null,
}, },
options: {
type: Array,
default: () => [],
},
optionLabel: {
type: String,
default: '',
},
optionValue: {
type: String,
default: '',
},
filterOptions: {
type: Array,
default: () => [],
},
isClearable: {
type: Boolean,
default: true,
},
defaultFilter: {
type: Boolean,
default: true,
},
}); });
const mixinRules = [requiredFieldRule]; const { options } = toRefs($props);
const locationProperties = [ const myOptions = ref([]);
'postcode', const myOptionsOriginal = ref([]);
(obj) =>
obj.city
? `${obj.city}${obj.province?.name ? `(${obj.province.name})` : ''}`
: null,
(obj) => obj.country?.name,
];
const formatLocation = (obj, properties) => { const value = computed({
const parts = properties.map((prop) => { get() {
if (typeof prop === 'string') { return $props.modelValue;
return obj[prop]; },
} else if (typeof prop === 'function') { set(value) {
return prop(obj); emit(
} 'update:modelValue',
return null; postcodesOptions.value.find((p) => p.code === value)
}); );
},
});
const filteredParts = parts.filter( onMounted(() => {
(part) => part !== null && part !== undefined && part !== '' locationFilter($props.modelValue);
); });
return filteredParts.join(', '); function setOptions(data) {
}; myOptions.value = JSON.parse(JSON.stringify(data));
myOptionsOriginal.value = JSON.parse(JSON.stringify(data));
}
setOptions(options.value);
const modelValue = computed(() => watch(options, (newValue) => {
props.location ? formatLocation(props.location, locationProperties) : null setOptions(newValue);
); });
function showLabel(data) { function showLabel(data) {
const dataProperties = [ return `${data.code} - ${data.town}(${data.province}), ${data.country}`;
'code',
(obj) => (obj.town ? `${obj.town}(${obj.province})` : null),
'country',
];
return formatLocation(data, dataProperties);
} }
const handleModelValue = (data) => { function locationFilter(search = '') {
emit('update:model-value', data); if (
}; search &&
(search.includes('undefined') || search.startsWith(`${$props.modelValue} - `))
)
return;
let where = { search };
postcodesRef.value.fetch({ filter: { where }, limit: 30 });
}
function handleFetch(data) {
postcodesOptions.value = data;
}
function onDataSaved(newPostcode) {
postcodesOptions.value.push(newPostcode);
value.value = newPostcode.code;
}
</script> </script>
<template> <template>
<VnSelectDialog <FetchData
v-model="modelValue" ref="postcodesRef"
option-filter-value="search"
:option-label="
(opt) => (typeof modelValue === 'string' ? modelValue : showLabel(opt))
"
url="Postcodes/filter" url="Postcodes/filter"
@update:model-value="handleModelValue" @on-fetch="(data) => handleFetch(data)"
:use-like="false" />
<VnSelectDialog
v-if="postcodesRef"
:option-label="(opt) => showLabel(opt) ?? 'code'"
:option-value="(opt) => opt.code"
v-model="value"
:options="postcodesOptions"
:label="t('Location')" :label="t('Location')"
:placeholder="t('search_by_postalcode')" :placeholder="t('search_by_postalcode')"
@input-value="locationFilter"
:default-filter="false"
:input-debounce="300" :input-debounce="300"
:class="{ required: isRequired }" :class="{ required: $attrs.required }"
v-bind="$attrs" v-bind="$attrs"
:emit-value="false" clearable
:tooltip="t('Create new location')"
:rules="mixinRules"
:lazy-rules="true"
> >
<template #form> <template #form>
<CreateNewPostcode <CreateNewPostcode
@on-data-saved=" @on-data-saved="onDataSaved"
(newValue) => {
modelValue = newValue;
emit('update:model-value', newValue);
}
"
/> />
</template> </template>
<template #option="{ itemProps, opt }"> <template #option="{ itemProps, opt }">
@ -111,9 +140,7 @@ const handleModelValue = (data) => {
<i18n> <i18n>
en: en:
search_by_postalcode: Search by postalcode, town, province or country search_by_postalcode: Search by postalcode, town, province or country
Create new location: Create new location
es: es:
Location: Ubicación Location: Ubicación
Create new location: Crear nueva ubicación
search_by_postalcode: Buscar por código postal, ciudad o país search_by_postalcode: Buscar por código postal, ciudad o país
</i18n> </i18n>

View File

@ -1,7 +1,7 @@
<script setup> <script setup>
import { ref, onUnmounted, watch } from 'vue'; import { ref, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router'; import { useRoute } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
import { date } from 'quasar'; import { date } from 'quasar';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
@ -14,13 +14,11 @@ import VnJsonValue from '../common/VnJsonValue.vue';
import FetchData from '../FetchData.vue'; import FetchData from '../FetchData.vue';
import VnSelect from './VnSelect.vue'; import VnSelect from './VnSelect.vue';
import VnUserLink from '../ui/VnUserLink.vue'; import VnUserLink from '../ui/VnUserLink.vue';
import VnPaginate from '../ui/VnPaginate.vue';
const stateStore = useStateStore(); const stateStore = useStateStore();
const validationsStore = useValidator(); const validationsStore = useValidator();
const { models } = validationsStore; const { models } = validationsStore;
const route = useRoute(); const route = useRoute();
const router = useRouter();
const { t } = useI18n(); const { t } = useI18n();
const props = defineProps({ const props = defineProps({
model: { model: {
@ -51,7 +49,6 @@ const filter = {
'changedModelId', 'changedModelId',
'changedModelValue', 'changedModelValue',
'description', 'description',
'summaryId',
], ],
include: [ include: [
{ {
@ -67,10 +64,9 @@ const filter = {
}, },
}, },
], ],
where: { and: [{ originFk: route.params.id }] },
}; };
const paginate = ref(); const workers = ref();
const actions = ref(); const actions = ref();
const changeInput = ref(); const changeInput = ref();
const searchInput = ref(); const searchInput = ref();
@ -216,7 +212,7 @@ function getLogTree(data) {
} }
nLogs++; nLogs++;
modelLog.logs.push(log); modelLog.logs.push(log);
modelLog.summaryId = modelLog.logs[0].summaryId;
// Changes // Changes
const notDelete = log.action != 'delete'; const notDelete = log.action != 'delete';
const olds = (notDelete ? log.oldInstance : null) || {}; const olds = (notDelete ? log.oldInstance : null) || {};
@ -237,8 +233,9 @@ async function openPointRecord(id, modelLog) {
const locale = validations[modelLog.model]?.locale || {}; const locale = validations[modelLog.model]?.locale || {};
pointRecord.value = parseProps(propNames, locale, data); pointRecord.value = parseProps(propNames, locale, data);
} }
async function setLogTree(data) { async function setLogTree() {
if (!data) return; filter.where = { and: [{ originFk: route.params.id }] };
const { data } = await getLogs(filter);
logTree.value = getLogTree(data); logTree.value = getLogTree(data);
} }
@ -267,7 +264,15 @@ async function applyFilter() {
filter.where.and.push(selectedFilters.value); filter.where.and.push(selectedFilters.value);
} }
paginate.value.fetch(filter); const { data } = await getLogs(filter);
logTree.value = getLogTree(data);
}
async function getLogs(filter) {
return axios.get(props.url ?? `${props.model}Logs`, {
params: { filter: JSON.stringify(filter) },
});
} }
function setDate(type) { function setDate(type) {
@ -370,313 +375,257 @@ async function clearFilter() {
await applyFilter(); await applyFilter();
} }
setLogTree();
onUnmounted(() => { onUnmounted(() => {
stateStore.rightDrawer = false; stateStore.rightDrawer = false;
}); });
watch(
() => router.currentRoute.value.params.id,
() => {
applyFilter();
}
);
</script> </script>
<template> <template>
<FetchData
:url="`${props.model}Logs/${route.params.id}/editors`"
:filter="{
fields: ['id', 'nickname', 'name', 'image'],
order: 'nickname',
limit: 30,
}"
@on-fetch="(data) => (workers = data)"
auto-load
/>
<FetchData <FetchData
:url="`${props.model}Logs/${route.params.id}/models`" :url="`${props.model}Logs/${route.params.id}/models`"
:filter="{ order: ['changedModel'] }" :filter="{ order: ['changedModel'] }"
@on-fetch=" @on-fetch="
(data) => (data) =>
(actions = data.map((item) => { (actions = data.map((item) => {
const changedModel = item.changedModel;
return { return {
locale: useCapitalize( locale: useCapitalize(validations[item.changedModel].locale.name),
validations[changedModel]?.locale?.name ?? changedModel value: item.changedModel,
),
value: changedModel,
}; };
})) }))
" "
auto-load auto-load
/> />
<VnPaginate <div
ref="paginate" class="column items-center logs origin-log q-mt-md"
:data-key="`${model}Log`" v-for="(originLog, originLogIndex) in logTree"
:url="`${model}Logs`" :key="originLogIndex"
:filter="filter"
:skeleton="false"
auto-load
@on-fetch="setLogTree"
search-url="logs"
> >
<template #body> <QItem class="origin-info items-center q-my-md" v-if="logTree.length > 1">
<div <h6 class="origin-id text-grey">
class="column items-center logs origin-log q-mt-md" {{ useCapitalize(validations[props.model].locale.name) }}
v-for="(originLog, originLogIndex) in logTree" #{{ originLog.originFk }}
:key="originLogIndex" </h6>
> <div class="line bg-grey"></div>
<QItem class="origin-info items-center q-my-md" v-if="logTree.length > 1"> </QItem>
<h6 class="origin-id text-grey"> <div
{{ useCapitalize(validations[props.model].locale.name) }} class="user-log q-mb-sm"
#{{ originLog.originFk }} v-for="(userLog, userIndex) in originLog.logs"
</h6> :key="userIndex"
<div class="line bg-grey"></div> >
</QItem> <div class="timeline">
<div <div class="user-avatar">
class="user-log q-mb-sm" <VnUserLink :worker-id="userLog?.user?.id">
v-for="(userLog, userIndex) in originLog.logs" <template #link>
:key="userIndex" <VnAvatar
:class="{ 'cursor-pointer': userLog?.user?.id }"
:worker-id="userLog?.user?.id"
:title="userLog?.user?.nickname"
:show-letter="!userLog?.user"
size="lg"
/>
</template>
</VnUserLink>
</div>
<div class="arrow bg-panel" v-if="byRecord"></div>
<div class="line"></div>
</div>
<QList class="user-changes" v-if="userLog">
<QItem
class="model-log column q-px-none q-py-xs"
v-for="(modelLog, modelLogIndex) in userLog.logs"
:key="modelLogIndex"
> >
<div class="timeline"> <QItemSection>
<div class="user-avatar"> <QItemLabel class="model-info q-mb-xs" v-if="!byRecord">
<VnUserLink :worker-id="userLog?.user?.id"> <QChip
<template #link> dense
<VnAvatar size="md"
:class="{ 'cursor-pointer': userLog?.user?.id }" class="model-name q-mr-xs text-white"
:worker-id="userLog?.user?.id" v-if="
:title="userLog?.user?.nickname" !(modelLog.changedModel && modelLog.changedModelId) &&
:show-letter="!userLog?.user" modelLog.model
size="lg" "
/> :style="{
</template> backgroundColor: useColor(modelLog.model),
</VnUserLink> }"
</div> :title="modelLog.model"
<div class="arrow bg-panel" v-if="byRecord"></div> >
<div class="line"></div> {{ t(modelLog.modelI18n) }}
</div> </QChip>
<QList class="user-changes" v-if="userLog"> <span class="model-id" v-if="modelLog.id"
<QItem >#{{ modelLog.id }}</span
class="model-log column q-px-none q-py-xs" >
v-for="(modelLog, modelLogIndex) in userLog.logs" <span class="model-value" :title="modelLog.showValue">
:key="modelLogIndex" {{ modelLog.showValue }}
</span>
<QBtn
flat
round
color="grey"
class="q-mr-xs q-ml-auto"
size="sm"
icon="filter_alt"
:title="t('recordChanges')"
@click.stop="filterByRecord(modelLog)"
/>
</QItemLabel>
</QItemSection>
<QItemSection>
<QCard
class="changes-log q-py-none q-mb-xs"
v-for="(log, logIndex) in modelLog.logs"
:key="logIndex"
> >
<QItemSection> <QCardSection class="change-info q-pa-none">
<QItemLabel class="model-info q-mb-xs" v-if="!byRecord"> <QItem
<QChip class="q-px-sm q-py-xs justify-between items-center"
dense
size="md"
class="model-name q-mr-xs text-white"
v-if="
!(
modelLog.changedModel &&
modelLog.changedModelId
) && modelLog.model
"
:style="{
backgroundColor: useColor(modelLog.model),
}"
:title="`${modelLog.model} #${modelLog.id}`"
>
{{ t(modelLog.modelI18n) }}
</QChip>
<span
class="model-id q-mr-xs"
v-if="modelLog.summaryId"
v-text="`#${modelLog.summaryId}`"
/>
<span
class="model-value"
:title="modelLog.showValue"
v-text="modelLog.showValue"
/>
<QBtn
flat
round
color="grey"
class="q-mr-xs q-ml-auto"
size="sm"
icon="filter_alt"
:title="t('recordChanges')"
@click.stop="filterByRecord(modelLog)"
/>
</QItemLabel>
</QItemSection>
<QItemSection>
<QCard
class="changes-log q-py-none q-mb-xs"
v-for="(log, logIndex) in modelLog.logs"
:key="logIndex"
> >
<QCardSection class="change-info q-pa-none"> <div
<QItem class="date text-grey text-caption q-mr-sm"
class="q-px-sm q-py-xs justify-between items-center" :title="
> date.formatDate(
<div log.creationDate,
class="date text-grey text-caption q-mr-sm" 'DD/MM/YYYY hh:mm:ss'
:title=" ) ?? `date:'dd/MM/yyyy HH:mm:ss'`
date.formatDate( "
log.creationDate,
'DD/MM/YYYY hh:mm:ss'
) ?? `date:'dd/MM/yyyy HH:mm:ss'`
"
>
{{ toRelativeDate(log.creationDate) }}
</div>
<div>
<QBtn
color="grey"
class="pit"
icon="preview"
flat
round
:title="t('pointRecord')"
padding="none"
v-if="log.action != 'insert'"
@click.stop="
openPointRecord(log.id, modelLog)
"
>
<QPopupProxy>
<QCard v-if="pointRecord">
<div
class="header q-px-sm q-py-xs q-ma-none text-white text-bold bg-primary"
>
{{ modelLog.modelI18n }}
<span v-if="modelLog.id"
>#{{
modelLog.id
}}</span
>
</div>
<QCardSection
class="change-detail q-pa-sm"
>
<QItem
v-for="(
value, index
) in pointRecord"
:key="index"
class="q-pa-none"
>
<span
class="json-field q-mr-xs text-grey"
:title="
value.name
"
>
{{
value.nameI18n
}}:
</span>
<VnJsonValue
:value="
value.val.val
"
/>
</QItem>
</QCardSection>
</QCard>
</QPopupProxy>
</QBtn>
<QIcon
class="action q-ml-xs"
:class="actionsClass[log.action]"
:name="actionsIcon[log.action]"
:title="
t(
`actions.${
actionsText[log.action]
}`
)
"
/>
</div>
</QItem>
</QCardSection>
<QCardSection
class="change-detail q-px-sm q-py-xs"
:class="{ expanded: log.expand }"
v-if="log.props.length || log.description"
> >
<QIcon {{ toRelativeDate(log.creationDate) }}
class="cursor-pointer q-mr-md" </div>
<div>
<QBtn
color="grey" color="grey"
name="expand_more" class="pit"
:title="t('globals.details')" icon="preview"
size="sm" flat
@click="log.expand = !log.expand" round
/> :title="t('pointRecord')"
<span v-if="log.props.length" class="attributes"> padding="none"
<span v-if="log.action != 'insert'"
v-if="!log.expand" @click.stop="
class="q-pa-none text-grey" openPointRecord(log.id, modelLog)
> "
<span >
v-for="(prop, propIndex) in log.props" <QPopupProxy>
:key="propIndex" <QCard v-if="pointRecord">
class="basic-json" <div
> class="header q-px-sm q-py-xs q-ma-none text-white text-bold bg-primary"
<span
class="json-field"
:title="prop.name"
> >
{{ prop.nameI18n }}: {{ modelLog.modelI18n }}
</span> <span v-if="modelLog.id"
<VnJsonValue :value="prop.val.val" /> >#{{ modelLog.id }}</span
<span >
v-if=" </div>
propIndex < <QCardSection
log.props.length - 1 class="change-detail q-pa-sm"
" >
>,&nbsp; <QItem
</span> v-for="(
value, index
) in pointRecord"
:key="index"
class="q-pa-none"
>
<span
class="json-field q-mr-xs text-grey"
:title="value.name"
>
{{ value.nameI18n }}:
</span>
<VnJsonValue
:value="value.val.val"
/>
</QItem>
</QCardSection>
</QCard>
</QPopupProxy>
</QBtn>
<QIcon
class="action q-ml-xs"
:class="actionsClass[log.action]"
:name="actionsIcon[log.action]"
:title="
t(`actions.${actionsText[log.action]}`)
"
/>
</div>
</QItem>
</QCardSection>
<QCardSection
class="change-detail q-px-sm q-py-xs"
:class="{ expanded: log.expand }"
v-if="log.props.length || log.description"
>
<QIcon
class="cursor-pointer q-mr-md"
color="grey"
name="expand_more"
:title="t('globals.details')"
size="sm"
@click="log.expand = !log.expand"
/>
<span v-if="log.props.length" class="attributes">
<span v-if="!log.expand" class="q-pa-none text-grey">
<span
v-for="(prop, propIndex) in log.props"
:key="propIndex"
class="basic-json"
>
<span class="json-field" :title="prop.name">
{{ prop.nameI18n }}:
</span>
<VnJsonValue :value="prop.val.val" />
<span v-if="propIndex < log.props.length - 1"
>,&nbsp;
</span>
</span>
</span>
<span
v-if="log.expand"
class="expanded-json column q-pa-none"
>
<div
v-for="(prop, prop2Index) in log.props"
:key="prop2Index"
class="q-pa-none text-grey"
>
<span class="json-field" :title="prop.name">
{{ prop.nameI18n }}:
</span>
<VnJsonValue :value="prop.val.val" />
<span v-if="prop.val.id" class="id-value">
#{{ prop.val.id }}
</span>
<span v-if="log.action == 'update'">
<VnJsonValue :value="prop.old.val" />
<span v-if="prop.old.id" class="id-value">
#{{ prop.old.id }}
</span> </span>
</span> </span>
<span </div>
v-if="log.expand" </span>
class="expanded-json column q-pa-none" </span>
> <span v-if="!log.props.length" class="description">
<div {{ log.description }}
v-for="( </span>
prop, prop2Index </QCardSection>
) in log.props" </QCard>
:key="prop2Index" </QItemSection>
class="q-pa-none text-grey" </QItem>
> </QList>
<span </div>
class="json-field" </div>
:title="prop.name"
>
{{ prop.nameI18n }}:
</span>
<VnJsonValue :value="prop.val.val" />
<span
v-if="prop.val.id"
class="id-value"
>
#{{ prop.val.id }}
</span>
<span v-if="log.action == 'update'">
<VnJsonValue
:value="prop.old.val"
/>
<span
v-if="prop.old.id"
class="id-value"
>
#{{ prop.old.id }}
</span>
</span>
</div>
</span>
</span>
<span
v-if="!log.props.length"
class="description"
>
{{ log.description }}
</span>
</QCardSection>
</QCard>
</QItemSection>
</QItem>
</QList>
</div>
</div>
</template>
</VnPaginate>
<Teleport to="#right-panel" v-if="stateStore.isHeaderMounted()"> <Teleport to="#right-panel" v-if="stateStore.isHeaderMounted()">
<QList dense> <QList dense>
<QSeparator /> <QSeparator />
@ -725,16 +674,17 @@ watch(
</QOptionGroup> </QOptionGroup>
</QItem> </QItem>
<QItem class="q-mt-sm"> <QItem class="q-mt-sm">
<QItemSection v-if="userRadio !== null"> <QItemSection v-if="!workers">
<QSkeleton type="QInput" class="full-width" />
</QItemSection>
<QItemSection v-if="workers && userRadio !== null">
<VnSelect <VnSelect
class="full-width" class="full-width"
:label="t('globals.user')" :label="t('globals.user')"
v-model="userSelect" v-model="userSelect"
option-label="name" option-label="name"
option-value="id" option-value="id"
:url="`${model}Logs/${$route.params.id}/editors`" :options="workers"
:fields="['id', 'nickname', 'name', 'image']"
sort-by="nickname"
@update:model-value="selectFilter('userSelect')" @update:model-value="selectFilter('userSelect')"
hide-selected hide-selected
> >

View File

@ -9,6 +9,10 @@ const $props = defineProps({
type: Number, //Progress value (1.0 > x > 0.0) type: Number, //Progress value (1.0 > x > 0.0)
required: true, required: true,
}, },
showDialog: {
type: Boolean,
required: true,
},
cancelled: { cancelled: {
type: Boolean, type: Boolean,
required: false, required: false,
@ -20,22 +24,30 @@ const emit = defineEmits(['cancel', 'close']);
const dialogRef = ref(null); const dialogRef = ref(null);
const showDialog = defineModel('showDialog', { const _showDialog = computed({
type: Boolean, get: () => $props.showDialog,
default: false, set: (value) => {
if (value) dialogRef.value.show();
},
}); });
const _progress = computed(() => $props.progress); const _progress = computed(() => $props.progress);
const progressLabel = computed(() => `${Math.round($props.progress * 100)}%`); const progressLabel = computed(() => `${Math.round($props.progress * 100)}%`);
const cancel = () => {
dialogRef.value.hide();
emit('cancel');
};
</script> </script>
<template> <template>
<QDialog ref="dialogRef" v-model="showDialog" @hide="emit('close')"> <QDialog ref="dialogRef" v-model="_showDialog" @hide="onDialogHide">
<QCard class="full-width dialog"> <QCard class="full-width dialog">
<QCardSection class="row"> <QCardSection class="row">
<span class="text-h6">{{ t('Progress') }}</span> <span class="text-h6">{{ t('Progress') }}</span>
<QSpace /> <QSpace />
<QBtn icon="close" flat round dense v-close-popup /> <QBtn icon="close" flat round dense @click="emit('close')" />
</QCardSection> </QCardSection>
<QCardSection> <QCardSection>
<div class="column"> <div class="column">
@ -68,7 +80,7 @@ const progressLabel = computed(() => `${Math.round($props.progress * 100)}%`);
type="button" type="button"
flat flat
class="text-primary" class="text-primary"
v-close-popup @click="cancel()"
> >
{{ t('globals.cancel') }} {{ t('globals.cancel') }}
</QBtn> </QBtn>

View File

@ -2,12 +2,5 @@
const model = defineModel({ type: Boolean, required: true }); const model = defineModel({ type: Boolean, required: true });
</script> </script>
<template> <template>
<QRadio <QRadio v-model="model" v-bind="$attrs" dense :dark="true" class="q-mr-sm" />
v-model="model"
v-bind="$attrs"
dense
:dark="true"
class="q-mr-sm"
size="xs"
/>
</template> </template>

View File

@ -1,20 +1,8 @@
<script setup> <script setup>
import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue'; import { ref, toRefs, computed, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useArrayData } from 'src/composables/useArrayData'; import FetchData from 'src/components/FetchData.vue';
import { useRequired } from 'src/composables/useRequired'; const emit = defineEmits(['update:modelValue', 'update:options']);
import dataByOrder from 'src/utils/dataByOrder';
const emit = defineEmits(['update:modelValue', 'update:options', 'remove']);
const $attrs = useAttrs();
const { t } = useI18n();
const isRequired = computed(() => {
return useRequired($attrs).isRequired;
});
const requiredFieldRule = computed(() => {
return useRequired($attrs).requiredFieldRule;
});
const $props = defineProps({ const $props = defineProps({
modelValue: { modelValue: {
@ -37,22 +25,14 @@ const $props = defineProps({
type: String, type: String,
default: null, default: null,
}, },
optionFilterValue: {
type: String,
default: null,
},
url: { url: {
type: String, type: String,
default: null, default: '',
}, },
filterOptions: { filterOptions: {
type: [Array], type: [Array],
default: () => [], default: () => [],
}, },
exprBuilder: {
type: Function,
default: null,
},
isClearable: { isClearable: {
type: Boolean, type: Boolean,
default: true, default: true,
@ -65,10 +45,6 @@ const $props = defineProps({
type: Array, type: Array,
default: null, default: null,
}, },
include: {
type: [Object, Array],
default: null,
},
where: { where: {
type: Object, type: Object,
default: null, default: null,
@ -85,85 +61,37 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
useLike: {
type: Boolean,
default: true,
},
params: {
type: Object,
default: null,
},
noOne: {
type: Boolean,
default: false,
},
dataKey: {
type: String,
default: null,
},
}); });
const mixinRules = [requiredFieldRule, ...($attrs.rules ?? [])]; const { t } = useI18n();
const { optionLabel, optionValue, optionFilter, optionFilterValue, options, modelValue } = const requiredFieldRule = (val) => val ?? t('globals.fieldRequired');
toRefs($props);
const { optionLabel, optionValue, optionFilter, options, modelValue } = toRefs($props);
const myOptions = ref([]); const myOptions = ref([]);
const myOptionsOriginal = ref([]); const myOptionsOriginal = ref([]);
const vnSelectRef = ref(); const vnSelectRef = ref();
const lastVal = ref(); const dataRef = ref();
const noOneText = t('globals.noOne');
const noOneOpt = ref({
[optionValue.value]: false,
[optionLabel.value]: noOneText,
});
const isLoading = ref(false);
const useURL = computed(() => $props.url);
const value = computed({ const value = computed({
get() { get() {
return $props.modelValue; return $props.modelValue;
}, },
set(value) { set(value) {
setOptions(myOptionsOriginal.value);
emit('update:modelValue', value); emit('update:modelValue', value);
}, },
}); });
watch(options, (newValue) => {
setOptions(newValue);
});
watch(modelValue, async (newValue) => {
if (!myOptions?.value?.some((option) => option[optionValue.value] == newValue))
await fetchFilter(newValue);
if ($props.noOne) myOptions.value.unshift(noOneOpt.value);
});
onMounted(() => {
setOptions(options.value);
if (useURL.value && $props.modelValue && !findKeyInOptions())
fetchFilter($props.modelValue);
if ($props.focusOnMount) setTimeout(() => vnSelectRef.value.showPopup(), 300);
});
const arrayDataKey =
$props.dataKey ?? ($props.url?.length > 0 ? $props.url : $attrs.name ?? $attrs.label);
const arrayData = useArrayData(arrayDataKey, { url: $props.url, searchUrl: false });
function findKeyInOptions() {
if (!$props.options) return;
return filter($props.modelValue, $props.options)?.length;
}
function setOptions(data) { function setOptions(data) {
data = dataByOrder(data, $props.sortBy);
myOptions.value = JSON.parse(JSON.stringify(data)); myOptions.value = JSON.parse(JSON.stringify(data));
myOptionsOriginal.value = JSON.parse(JSON.stringify(data)); myOptionsOriginal.value = JSON.parse(JSON.stringify(data));
emit('update:options', data);
} }
onMounted(() => {
setOptions(options.value);
if ($props.url && $props.modelValue) fetchFilter($props.modelValue);
});
function filter(val, options) { function filter(val, options) {
const search = val?.toString()?.toLowerCase(); const search = val.toString().toLowerCase();
if (!search) return options; if (!search) return options;
@ -175,8 +103,7 @@ function filter(val, options) {
}); });
} }
if (!row) return; const id = row.id;
const id = row[$props.optionValue];
const optionLabel = String(row[$props.optionLabel]).toLowerCase(); const optionLabel = String(row[$props.optionLabel]).toLowerCase();
return id == search || optionLabel.includes(search); return id == search || optionLabel.includes(search);
@ -184,55 +111,27 @@ function filter(val, options) {
} }
async function fetchFilter(val) { async function fetchFilter(val) {
if (!$props.url) return; if (!$props.url || !dataRef.value) return;
const { fields, include, sortBy, limit } = $props; const { fields, sortBy, limit } = $props;
const key = let key = optionLabel.value;
optionFilterValue.value ??
(new RegExp(/\d/g).test(val)
? optionValue.value
: optionFilter.value ?? optionLabel.value);
let defaultWhere = {}; if (new RegExp(/\d/g).test(val)) key = optionFilter.value ?? optionValue.value;
if ($props.filterOptions.length) {
defaultWhere = $props.filterOptions.reduce((obj, prop) => { const where = { ...{ [key]: { like: `%${val}%` } }, ...$props.where };
if (!obj.or) obj.or = []; const fetchOptions = { where, order: sortBy, limit };
obj.or.push({ [prop]: getVal(val) });
return obj;
}, {});
} else defaultWhere = { [key]: getVal(val) };
const where = { ...(val ? defaultWhere : {}), ...$props.where };
$props.exprBuilder && Object.assign(where, $props.exprBuilder(key, val));
const fetchOptions = { where, include, limit };
if (fields) fetchOptions.fields = fields; if (fields) fetchOptions.fields = fields;
if (sortBy) fetchOptions.order = sortBy; return dataRef.value.fetch(fetchOptions);
arrayData.reset(['skip', 'filter.skip', 'page']);
const { data } = await arrayData.applyFilter({ filter: fetchOptions });
setOptions(data);
return data;
} }
async function filterHandler(val, update) { async function filterHandler(val, update) {
if (!val && lastVal.value === val) {
lastVal.value = val;
return update();
}
lastVal.value = val;
let newOptions;
if (!$props.defaultFilter) return update(); if (!$props.defaultFilter) return update();
if ( let newOptions;
$props.url && if ($props.url) {
($props.limit || (!$props.limit && Object.keys(myOptions.value).length === 0))
) {
newOptions = await fetchFilter(val); newOptions = await fetchFilter(val);
} else newOptions = filter(val, myOptionsOriginal.value); } else newOptions = filter(val, myOptionsOriginal.value);
update( update(
() => { () => {
if ($props.noOne && noOneText.toLowerCase().includes(val.toLowerCase()))
newOptions.unshift(noOneOpt.value);
myOptions.value = newOptions; myOptions.value = newOptions;
}, },
(ref) => { (ref) => {
@ -244,119 +143,59 @@ async function filterHandler(val, update) {
); );
} }
function nullishToTrue(value) { watch(options, (newValue) => {
return value ?? true; setOptions(newValue);
} });
const getVal = (val) => ($props.useLike ? { like: `%${val}%` } : val); watch(modelValue, (newValue) => {
if (!myOptions.value.some((option) => option[optionValue.value] == newValue))
fetchFilter(newValue);
});
async function onScroll({ to, direction, from, index }) { onMounted(async () => {
const lastIndex = myOptions.value.length - 1; if ($props.focusOnMount) setTimeout(() => vnSelectRef.value.showPopup(), 300);
});
if (from === 0 && index === 0) return;
if (!useURL.value && !$props.fetchRef) return;
if (direction === 'decrease') return;
if (to === lastIndex && arrayData.store.hasMoreData && !isLoading.value) {
isLoading.value = true;
await arrayData.loadMore();
setOptions(arrayData.store.data);
vnSelectRef.value.scrollTo(lastIndex);
isLoading.value = false;
}
}
defineExpose({ opts: myOptions });
function handleKeyDown(event) {
if (event.key === 'Tab' && !event.shiftKey) {
event.preventDefault();
const inputValue = vnSelectRef.value?.inputValue;
if (inputValue) {
const matchingOption = myOptions.value.find(
(option) =>
option[optionLabel.value].toLowerCase() === inputValue.toLowerCase()
);
if (matchingOption) {
emit('update:modelValue', matchingOption[optionValue.value]);
} else {
emit('update:modelValue', inputValue);
}
vnSelectRef.value?.hidePopup();
}
const focusableElements = document.querySelectorAll(
'a, button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])'
);
const currentIndex = Array.prototype.indexOf.call(
focusableElements,
event.target
);
if (currentIndex >= 0 && currentIndex < focusableElements.length - 1) {
focusableElements[currentIndex + 1].focus();
}
}
}
</script> </script>
<template> <template>
<FetchData
ref="dataRef"
:url="$props.url"
@on-fetch="(data) => setOptions(data)"
:where="where || { [optionValue]: value }"
:limit="limit"
:sort-by="sortBy"
:fields="fields"
/>
<QSelect <QSelect
v-model="value" v-model="value"
:options="myOptions" :options="myOptions"
:option-label="optionLabel" :option-label="optionLabel"
:option-value="optionValue" :option-value="optionValue"
v-bind="$attrs" v-bind="$attrs"
emit-value
map-options
use-input
@filter="filterHandler" @filter="filterHandler"
@keydown="handleKeyDown" hide-selected
:emit-value="nullishToTrue($attrs['emit-value'])" fill-input
:map-options="nullishToTrue($attrs['map-options'])"
:use-input="nullishToTrue($attrs['use-input'])"
:hide-selected="nullishToTrue($attrs['hide-selected'])"
:fill-input="nullishToTrue($attrs['fill-input'])"
ref="vnSelectRef" ref="vnSelectRef"
lazy-rules lazy-rules
:class="{ required: isRequired }" :class="{ required: $attrs.required }"
:rules="mixinRules" :rules="$attrs.required ? [requiredFieldRule] : null"
virtual-scroll-slice-size="options.length" virtual-scroll-slice-size="options.length"
hide-bottom-space
:input-debounce="useURL ? '300' : '0'"
:loading="isLoading"
@virtual-scroll="onScroll"
:data-cy="$attrs.dataCy ?? $attrs.label + '_select'"
> >
<template #append> <template v-if="isClearable" #append>
<QIcon <QIcon
v-show="isClearable && value" v-show="value"
name="close" name="close"
@click.stop=" @click.stop="value = null"
() => {
value = null;
emit('remove');
}
"
class="cursor-pointer" class="cursor-pointer"
size="xs" size="xs"
/> />
</template> </template>
<template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName"> <template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName">
<div v-if="slotName == 'append'"> <slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
<QIcon
v-show="isClearable && value"
name="close"
@click.stop="
() => {
value = null;
emit('remove');
}
"
class="cursor-pointer"
size="xs"
/>
<slot name="append" v-if="$slots.append" v-bind="slotData ?? {}" />
</div>
<slot v-else :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template> </template>
</QSelect> </QSelect>
</template> </template>

View File

@ -1,39 +0,0 @@
<script setup>
import { ref, onBeforeMount, useAttrs } from 'vue';
import VnSelect from 'src/components/common/VnSelect.vue';
const $props = defineProps({
row: {
type: [Object],
default: null,
},
find: {
type: [String, Object],
default: null,
description: 'search in row to add default options',
},
});
const options = ref([]);
onBeforeMount(async () => {
const { url, optionValue, optionLabel } = useAttrs();
const findBy = $props.find ?? url?.charAt(0)?.toLocaleLowerCase() + url?.slice(1, -1);
if (!findBy || !$props.row) return;
// is object
if (typeof findBy == 'object') {
const { value, label } = findBy;
if (!$props.row[value] || !$props.row[label]) return;
return (options.value = [
{
[optionValue ?? 'id']: $props.row[value],
[optionLabel ?? 'name']: $props.row[label],
},
]);
}
// is string
if ($props.row[findBy]) options.value = [$props.row[findBy]];
});
</script>
<template>
<VnSelect v-bind="$attrs" :options="$attrs.options ?? options" />
</template>

View File

@ -1,21 +1,25 @@
<script setup> <script setup>
import { computed } from 'vue'; import { ref, computed } from 'vue';
import { useRole } from 'src/composables/useRole';
import { useAcl } from 'src/composables/useAcl';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import { useRole } from 'src/composables/useRole';
const emit = defineEmits(['update:modelValue']); const emit = defineEmits(['update:modelValue']);
const value = defineModel({ type: [String, Number, Object] });
const $props = defineProps({ const $props = defineProps({
modelValue: {
type: [String, Number, Object],
default: null,
},
options: {
type: Array,
default: () => [],
},
rolesAllowedToCreate: { rolesAllowedToCreate: {
type: Array, type: Array,
default: () => ['developer'], default: () => ['developer'],
}, },
acls: {
type: Array,
default: () => [],
},
actionIcon: { actionIcon: {
type: String, type: String,
default: 'add', default: 'add',
@ -27,24 +31,31 @@ const $props = defineProps({
}); });
const role = useRole(); const role = useRole();
const acl = useAcl(); const showForm = ref(false);
const value = computed({
get() {
return $props.modelValue;
},
set(value) {
emit('update:modelValue', value);
},
});
const isAllowedToCreate = computed(() => { const isAllowedToCreate = computed(() => {
if ($props.acls.length) return acl.hasAny($props.acls);
return role.hasAny($props.rolesAllowedToCreate); return role.hasAny($props.rolesAllowedToCreate);
}); });
const toggleForm = () => {
showForm.value = !showForm.value;
};
</script> </script>
<template> <template>
<VnSelect <VnSelect v-model="value" :options="options" v-bind="$attrs">
v-model="value"
v-bind="$attrs"
@update:model-value="(...args) => emit('update:modelValue', ...args)"
>
<template v-if="isAllowedToCreate" #append> <template v-if="isAllowedToCreate" #append>
<QIcon <QIcon
:data-cy="$attrs.dataCy ?? $attrs.label + '_icon'" @click.stop.prevent="toggleForm()"
@click.stop.prevent="$refs.dialog.show()"
:name="actionIcon" :name="actionIcon"
:size="actionIcon === 'add' ? 'xs' : 'sm'" :size="actionIcon === 'add' ? 'xs' : 'sm'"
:class="['default-icon', { '--add-icon': actionIcon === 'add' }]" :class="['default-icon', { '--add-icon': actionIcon === 'add' }]"
@ -54,7 +65,7 @@ const isAllowedToCreate = computed(() => {
> >
<QTooltip v-if="tooltip">{{ tooltip }}</QTooltip> <QTooltip v-if="tooltip">{{ tooltip }}</QTooltip>
</QIcon> </QIcon>
<QDialog ref="dialog" transition-show="scale" transition-hide="scale"> <QDialog v-model="showForm" transition-show="scale" transition-hide="scale">
<slot name="form" /> <slot name="form" />
</QDialog> </QDialog>
</template> </template>

View File

@ -1,52 +0,0 @@
<script setup>
import { onBeforeMount, ref, useAttrs } from 'vue';
import axios from 'axios';
import VnSelect from 'components/common/VnSelect.vue';
const { schema, table, column, translation, defaultOptions } = defineProps({
schema: {
type: String,
default: 'vn',
},
table: {
type: String,
required: true,
},
column: {
type: String,
required: true,
},
translation: {
type: Function,
default: null,
},
defaultOptions: {
type: Array,
default: () => [],
},
});
const $attrs = useAttrs();
const options = ref([]);
onBeforeMount(async () => {
options.value = [].concat(defaultOptions);
const { data } = await axios.get(`Applications/get-enum-values`, {
params: { schema, table, column },
});
for (const value of data)
options.value.push({
[$attrs['option-value'] ?? 'id']: value,
[$attrs['option-label'] ?? 'name']: translation ? translation(value) : value,
});
});
</script>
<template>
<VnSelect
v-bind="$attrs"
:options="options"
:key="options.length"
:input-debounce="0"
/>
</template>

View File

@ -1,85 +0,0 @@
<script setup>
import { computed, useAttrs } from 'vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnAvatar from 'src/components/ui/VnAvatar.vue';
const emit = defineEmits(['update:modelValue']);
const $props = defineProps({
hasAvatar: {
type: Boolean,
default: false,
},
hasInfo: {
type: Boolean,
default: false,
},
modelValue: {
type: [String, Number, Object],
default: null,
},
});
const $attrs = useAttrs();
const value = computed({
get() {
return $props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
const url = computed(() => {
let url = 'Workers/search';
const { departmentCodes } = $attrs.params ?? {};
if (!departmentCodes) return url;
const params = new URLSearchParams({
departmentCodes: JSON.stringify(departmentCodes),
});
return url.concat(`?${params.toString()}`);
});
</script>
<template>
<VnSelect
:label="$t('globals.worker')"
v-bind="$attrs"
v-model="value"
:url="url"
option-value="id"
option-label="nickname"
:fields="['id', 'name', 'nickname', 'code']"
sort-by="nickname ASC"
>
<template #prepend v-if="$props.hasAvatar">
<VnAvatar :worker-id="value" color="primary" :title="title" />
</template>
<template #append v-if="$props.hasInfo">
<QIcon name="info" class="cursor-pointer">
<QTooltip>{{ $t($props.hasInfo) }}</QTooltip>
</QIcon>
</template>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt.name }}
</QItemLabel>
<QItemLabel v-if="!scope.opt.id">
{{ scope.opt.nickname }}
</QItemLabel>
<QItemLabel caption v-else>
{{ scope.opt.nickname }}, {{ scope.opt.code }}
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
</template>
<i18n>
es:
Responsible for approving invoices: Responsable de aprobar las facturas
</i18n>

View File

@ -86,7 +86,7 @@ async function send() {
</script> </script>
<template> <template>
<QDialog ref="dialogRef" data-cy="vnSmsDialog"> <QDialog ref="dialogRef">
<QCard class="q-pa-sm"> <QCard class="q-pa-sm">
<QCardSection class="row items-center q-pb-none"> <QCardSection class="row items-center q-pb-none">
<span class="text-h6 text-grey"> <span class="text-h6 text-grey">
@ -161,7 +161,6 @@ async function send() {
:loading="isLoading" :loading="isLoading"
color="primary" color="primary"
unelevated unelevated
data-cy="sendSmsBtn"
/> />
</QCardActions> </QCardActions>
</QCard> </QCard>

View File

@ -1,16 +0,0 @@
<script setup>
const model = defineModel({ type: [String, Number], required: true });
</script>
<template>
<QTime v-model="model" now-btn mask="HH:mm" />
</template>
<style lang="scss" scoped>
.q-time {
width: 230px;
min-width: unset;
:deep(.q-time__header) {
min-height: unset;
height: 50px;
}
}
</style>

View File

@ -7,8 +7,8 @@ defineProps({
</script> </script>
<template> <template>
<div :class="$q.screen.gt.md ? 'q-pb-lg' : 'q-pb-md'"> <div :class="$q.screen.gt.md ? 'q-pb-lg' : 'q-pb-md'">
<div class="header-link" :style="{ cursor: url ? 'pointer' : 'default' }"> <div class="header-link">
<a :href="url" :class="url ? 'link' : 'color-vn-text'" v-bind="$attrs"> <a :href="url" :class="url ? 'link' : 'color-vn-text'">
{{ text }} {{ text }}
<QIcon v-if="url" :name="icon" /> <QIcon v-if="url" :name="icon" />
</a> </a>

View File

@ -46,8 +46,7 @@ let arrayData;
let store; let store;
let entity; let entity;
const isLoading = ref(false); const isLoading = ref(false);
const isSameDataKey = computed(() => $props.dataKey === route.meta.moduleName);
const menuRef = ref();
defineExpose({ getData }); defineExpose({ getData });
onBeforeMount(async () => { onBeforeMount(async () => {
@ -57,19 +56,12 @@ onBeforeMount(async () => {
skip: 0, skip: 0,
}); });
store = arrayData.store; store = arrayData.store;
entity = computed(() => { entity = computed(() => (Array.isArray(store.data) ? store.data[0] : store.data));
const data = (Array.isArray(store.data) ? store.data[0] : store.data) ?? {};
if (data) emit('onFetch', data);
return data;
});
// It enables to load data only once if the module is the same as the dataKey // It enables to load data only once if the module is the same as the dataKey
if (!isSameDataKey.value || !route.params.id) await getData(); if ($props.dataKey !== route.meta.moduleName || !route.params.id) await getData();
watch( watch(
() => [$props.url, $props.filter], () => [$props.url, $props.filter],
async () => { async () => await getData()
if (!isSameDataKey.value) await getData();
}
); );
}); });
@ -85,50 +77,14 @@ async function getData() {
isLoading.value = false; isLoading.value = false;
} }
} }
function getValueFromPath(path) {
if (!path) return;
const keys = path.toString().split('.');
let current = entity.value;
for (const key of keys) {
if (current[key] === undefined) return undefined;
else current = current[key];
}
return current;
}
const emit = defineEmits(['onFetch']); const emit = defineEmits(['onFetch']);
const iconModule = computed(() => route.matched[1].meta.icon);
const toModule = computed(() =>
route.matched[1].path.split('/').length > 2
? route.matched[1].redirect
: route.matched[1].children[0].redirect
);
</script> </script>
<template> <template>
<div class="descriptor"> <div class="descriptor">
<template v-if="entity && !isLoading"> <template v-if="entity && !isLoading">
<div class="header bg-primary q-pa-sm justify-between"> <div class="header bg-primary q-pa-sm justify-between">
<slot name="header-extra-action" <slot name="header-extra-action" />
><QBtn
round
flat
dense
size="md"
:icon="iconModule"
color="white"
class="link"
:to="$attrs['to-module'] ?? toModule"
>
<QTooltip>
{{ t('globals.goToModuleIndex') }}
</QTooltip>
</QBtn></slot
>
<QBtn <QBtn
@click.stop="viewSummary(entity.id, $props.summary)" @click.stop="viewSummary(entity.id, $props.summary)"
round round
@ -167,14 +123,13 @@ const toModule = computed(() =>
icon="more_vert" icon="more_vert"
round round
size="md" size="md"
data-cy="descriptor-more-opts"
> >
<QTooltip> <QTooltip>
{{ t('components.cardDescriptor.moreOptions') }} {{ t('components.cardDescriptor.moreOptions') }}
</QTooltip> </QTooltip>
<QMenu :ref="menuRef"> <QMenu>
<QList> <QList>
<slot name="menu" :entity="entity" :menu-ref="menuRef" /> <slot name="menu" :entity="entity" />
</QList> </QList>
</QMenu> </QMenu>
</QBtn> </QBtn>
@ -184,8 +139,8 @@ const toModule = computed(() =>
<QList dense> <QList dense>
<QItemLabel header class="ellipsis text-h5" :lines="1"> <QItemLabel header class="ellipsis text-h5" :lines="1">
<div class="title"> <div class="title">
<span v-if="$props.title" :title="getValueFromPath(title)"> <span v-if="$props.title" :title="$props.title">
{{ getValueFromPath(title) ?? $props.title }} {{ entity[title] ?? $props.title }}
</span> </span>
<slot v-else name="description" :entity="entity"> <slot v-else name="description" :entity="entity">
<span :title="entity.name"> <span :title="entity.name">
@ -196,7 +151,7 @@ const toModule = computed(() =>
</QItemLabel> </QItemLabel>
<QItem dense> <QItem dense>
<QItemLabel class="subtitle" caption> <QItemLabel class="subtitle" caption>
#{{ getValueFromPath(subtitle) ?? entity.id }} #{{ $props.subtitle ?? entity.id }}
</QItemLabel> </QItemLabel>
</QItem> </QItem>
</QList> </QList>
@ -222,8 +177,8 @@ const toModule = computed(() =>
/> />
</template> </template>
<style lang="scss" scoped> <style lang="scss">
:deep(.body) { .body {
background-color: var(--vn-section-color); background-color: var(--vn-section-color);
.text-h5 { .text-h5 {
font-size: 20px; font-size: 20px;
@ -262,7 +217,9 @@ const toModule = computed(() =>
} }
} }
} }
</style>
<style lang="scss" scoped>
.title { .title {
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;

View File

@ -4,7 +4,6 @@ import { useRoute } from 'vue-router';
import SkeletonSummary from 'components/ui/SkeletonSummary.vue'; import SkeletonSummary from 'components/ui/SkeletonSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { isDialogOpened } from 'src/filters';
const props = defineProps({ const props = defineProps({
url: { url: {
@ -59,6 +58,22 @@ async function fetch() {
emit('onFetch', Array.isArray(data) ? data[0] : data); emit('onFetch', Array.isArray(data) ? data[0] : data);
isLoading.value = false; isLoading.value = false;
} }
const showRedirectToSummaryIcon = computed(() => {
const exist = existSummary(route.matched);
return !isSummary.value && route.meta.moduleName && exist;
});
function existSummary(routes) {
const hasSummary = routes.some((r) => r.name === `${route.meta.moduleName}Summary`);
if (hasSummary) return hasSummary;
for (const current of routes) {
if (current.path != '/' && current.children) {
const exist = existSummary(current.children);
if (exist) return exist;
}
}
}
</script> </script>
<template> <template>
@ -69,7 +84,7 @@ async function fetch() {
<div class="summaryHeader bg-primary q-pa-sm text-weight-bolder"> <div class="summaryHeader bg-primary q-pa-sm text-weight-bolder">
<slot name="header-left"> <slot name="header-left">
<router-link <router-link
v-if="isDialogOpened()" v-if="showRedirectToSummaryIcon"
class="header link" class="header link"
:to="{ :to="{
name: `${moduleName ?? route.meta.moduleName}Summary`, name: `${moduleName ?? route.meta.moduleName}Summary`,
@ -83,7 +98,7 @@ async function fetch() {
<slot name="header" :entity="entity" dense> <slot name="header" :entity="entity" dense>
<VnLv :label="`${entity.id} -`" :value="entity.name" /> <VnLv :label="`${entity.id} -`" :value="entity.name" />
</slot> </slot>
<slot name="header-right" :entity="entity"> <slot name="header-right">
<span></span> <span></span>
</slot> </slot>
</div> </div>
@ -103,7 +118,6 @@ async function fetch() {
.cardSummary { .cardSummary {
width: 100%; width: 100%;
max-height: 70vh;
.summaryHeader { .summaryHeader {
text-align: center; text-align: center;
font-size: 20px; font-size: 20px;
@ -173,10 +187,15 @@ async function fetch() {
color: lighten($primary, 20%); color: lighten($primary, 20%);
} }
.q-checkbox { .q-checkbox {
display: flex;
margin-bottom: 9px;
& .q-checkbox__label { & .q-checkbox__label {
margin-left: 31px;
color: var(--vn-text-color); color: var(--vn-text-color);
} }
& .q-checkbox__inner { & .q-checkbox__inner {
position: absolute;
left: 0;
color: var(--vn-label-color); color: var(--vn-label-color);
} }
} }

View File

@ -2,6 +2,10 @@
import { computed } from 'vue'; import { computed } from 'vue';
const $props = defineProps({ const $props = defineProps({
maxLength: {
type: Number,
required: true,
},
item: { item: {
type: Object, type: Object,
required: true, required: true,

View File

@ -52,8 +52,8 @@ const containerClasses = computed(() => {
--calendar-border-current: #84d0e2 2px solid; --calendar-border-current: #84d0e2 2px solid;
--calendar-current-color-dark: #84d0e2; --calendar-current-color-dark: #84d0e2;
// Colores de fondo del calendario en dark mode // Colores de fondo del calendario en dark mode
--calendar-outside-background-dark: var(--vn-section-color); --calendar-outside-background-dark: #222;
--calendar-background-dark: var(--vn-section-color); --calendar-background-dark: #222;
} }
// Clases para modificar el color de fecha seleccionada en componente QCalendarMonth // Clases para modificar el color de fecha seleccionada en componente QCalendarMonth
@ -70,26 +70,8 @@ const containerClasses = computed(() => {
text-transform: capitalize; text-transform: capitalize;
} }
.q-calendar-month__head--workweek,
.q-calendar-month__head--weekday,
// .q-calendar-month__workweek.q-past-day,
.q-calendar-month__week :nth-child(n+6):nth-child(-n+7) {
color: var(--vn-label-color);
}
.q-calendar-month__head--weekdays > div[aria-label='miércoles'] > span {
/* color: transparent; */
visibility: hidden;
// position: absolute;
}
.q-calendar-month__head--weekdays > div[aria-label='miércoles'] > span:after {
content: 'X';
visibility: visible;
left: 33%;
position: absolute;
}
.transparent-background { .transparent-background {
// --calendar-background-dark: transparent; --calendar-background-dark: transparent;
--calendar-background: transparent; --calendar-background: transparent;
--calendar-outside-background-dark: transparent; --calendar-outside-background-dark: transparent;
} }
@ -128,6 +110,11 @@ const containerClasses = computed(() => {
cursor: pointer; cursor: pointer;
} }
} }
.q-calendar-month__week--days > div:nth-child(6),
.q-calendar-month__week--days > div:nth-child(7) {
// Cambia el color de los días sábado y domingo
color: #777777;
}
.q-calendar-month__week--wrapper { .q-calendar-month__week--wrapper {
margin-bottom: 4px; margin-bottom: 4px;
@ -137,7 +124,6 @@ const containerClasses = computed(() => {
height: 32px; height: 32px;
display: flex; display: flex;
justify-content: center; justify-content: center;
color: var(--vn-label-color);
} }
.q-calendar__button--bordered { .q-calendar__button--bordered {
@ -161,7 +147,7 @@ const containerClasses = computed(() => {
.q-calendar-month__head--workweek, .q-calendar-month__head--workweek,
.q-calendar-month__head--weekday.q-calendar__center.q-calendar__ellipsis { .q-calendar-month__head--weekday.q-calendar__center.q-calendar__ellipsis {
text-transform: capitalize; text-transform: capitalize;
color: var(--vn-label-color); color: $color-font-secondary;
font-weight: bold; font-weight: bold;
font-size: 0.8rem; font-size: 0.8rem;
text-align: center; text-align: center;

View File

@ -1,14 +1,20 @@
<template> <template>
<div class="row q-gutter-md q-mb-md"> <div class="q-pa-md">
<QSkeleton type="QInput" class="col" square /> <div class="row q-gutter-md q-mb-md">
<QSkeleton type="QInput" class="col" square /> <QSkeleton type="QInput" square />
<QSkeleton type="QInput" square />
</div>
<div class="row q-gutter-md q-mb-md">
<QSkeleton type="QInput" square />
<QSkeleton type="QInput" square />
</div>
<div class="row q-gutter-md q-mb-md">
<QSkeleton type="QInput" square />
<QSkeleton type="QInput" square />
</div>
<div class="row q-gutter-md">
<QSkeleton type="QBtn" />
<QSkeleton type="QBtn" />
</div>
</div> </div>
<div class="row q-gutter-md q-mb-md"> </template>
<QSkeleton type="QInput" class="col" square />
<QSkeleton type="QInput" class="col" square />
</div>
<div class="row q-gutter-md q-mb-md">
<QSkeleton type="QInput" class="col" square />
<QSkeleton type="QInput" class="col" square />
</div>
</template>

View File

@ -1,68 +1,45 @@
<script setup> <script setup>
import { computed, ref, watch } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
import { useColor } from 'src/composables/useColor'; import { useColor } from 'src/composables/useColor';
import { getCssVar } from 'quasar';
const $props = defineProps({ const $props = defineProps({
workerId: { type: [Number, undefined], default: null }, workerId: { type: Number, required: true },
description: { type: String, default: null }, description: { type: String, default: null },
size: { type: String, default: null },
title: { type: String, default: null }, title: { type: String, default: null },
color: { type: String, default: null },
}); });
const { getTokenMultimedia } = useSession(); const { getTokenMultimedia } = useSession();
const token = getTokenMultimedia(); const token = getTokenMultimedia();
const { t } = useI18n(); const { t } = useI18n();
const src = computed( const title = computed(() => $props.title ?? t('globals.system'));
() => `/api/Images/user/160x160/${$props.workerId}/download?access_token=${token}`
);
const title = computed(() => $props.title?.toUpperCase() || t('globals.system'));
const showLetter = ref(false); const showLetter = ref(false);
const backgroundColor = computed(() => {
const color = $props.color || useColor(title.value);
return getCssVar(color) || color;
});
watch(src, () => (showLetter.value = false));
</script> </script>
<template> <template>
<div class="column items-center"> <div class="avatar-picture column items-center">
<QAvatar <QAvatar
:style="{ backgroundColor }" :style="{
v-bind="$attrs" backgroundColor: useColor(title),
:title="title || t('globals.system')" }"
:size="$props.size"
:title="title"
> >
<template v-if="showLetter"> <template v-if="showLetter">{{ title.charAt(0) }}</template>
{{ title.charAt(0) }}
</template>
<QImg <QImg
v-else-if="workerId" v-else
:src="src" :src="`/api/Images/user/160x160/${$props.workerId}/download?access_token=${token}`"
spinner-color="white" spinner-color="white"
@error="showLetter = true" @error="showLetter = true"
/> />
<QIcon v-else name="mood" size="xs" />
</QAvatar> </QAvatar>
<div class="description"> <div class="description">
<slot name="description" v-if="description"> <slot name="description" v-if="$props.description">
<p v-text="description" /> <p>
{{ $props.description }}
</p>
</slot> </slot>
</div> </div>
</div> </div>
</template> </template>
<style lang="scss" scoped>
[size='xxl'] {
.q-avatar,
.q-img {
width: 80px;
height: 80px;
}
.q-img {
object-fit: cover;
}
}
</style>

View File

@ -15,7 +15,7 @@ const props = defineProps({
default: null, default: null,
}, },
message: { message: {
type: [String, Boolean], type: String,
default: null, default: null,
}, },
data: { data: {
@ -30,17 +30,12 @@ const props = defineProps({
}, },
}); });
const emit = defineEmits(['confirm', 'cancel', ...useDialogPluginComponent.emits]); defineEmits(['confirm', ...useDialogPluginComponent.emits]);
defineExpose({ show: () => dialogRef.value.show(), hide: () => dialogRef.value.hide() });
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = const { dialogRef, onDialogOK } = useDialogPluginComponent();
useDialogPluginComponent();
const title = props.title || t('Confirm'); const title = props.title || t('Confirm');
const message = const message = props.message || t('Are you sure you want to continue?');
props.message ||
(props.message !== false ? t('Are you sure you want to continue?') : false);
const isLoading = ref(false); const isLoading = ref(false);
async function confirm() { async function confirm() {
@ -54,14 +49,9 @@ async function confirm() {
} }
onDialogOK(props.data); onDialogOK(props.data);
} }
function cancel() {
emit('cancel');
onDialogCancel();
}
</script> </script>
<template> <template>
<QDialog ref="dialogRef" @hide="onDialogHide"> <QDialog ref="dialogRef">
<QCard class="q-pa-sm"> <QCard class="q-pa-sm">
<QCardSection class="row items-center q-pb-none"> <QCardSection class="row items-center q-pb-none">
<QAvatar <QAvatar
@ -71,21 +61,12 @@ function cancel() {
size="xl" size="xl"
v-if="icon" v-if="icon"
/> />
<span class="text-h6">{{ title }}</span> <span class="text-h6 text-grey">{{ title }}</span>
<QSpace /> <QSpace />
<QBtn <QBtn icon="close" :disable="isLoading" flat round dense v-close-popup />
icon="close"
:disable="isLoading"
flat
round
dense
@click="cancel()"
/>
</QCardSection> </QCardSection>
<QCardSection class="q-pb-none"> <QCardSection class="row items-center">
<span v-if="message !== false" v-html="message" /> <span v-html="message"></span>
</QCardSection>
<QCardSection class="row items-center q-pt-none">
<slot name="customHTML"></slot> <slot name="customHTML"></slot>
</QCardSection> </QCardSection>
<QCardActions align="right"> <QCardActions align="right">
@ -94,7 +75,7 @@ function cancel() {
color="primary" color="primary"
:disable="isLoading" :disable="isLoading"
flat flat
@click="cancel()" v-close-popup
/> />
<QBtn <QBtn
:label="t('globals.confirm')" :label="t('globals.confirm')"
@ -103,7 +84,6 @@ function cancel() {
@click="confirm()" @click="confirm()"
unelevated unelevated
autofocus autofocus
data-cy="VnConfirm_confirm"
/> />
</QCardActions> </QCardActions>
</QCard> </QCard>

View File

@ -7,17 +7,15 @@ import toDate from 'filters/toDate';
import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue'; import VnFilterPanelChip from 'components/ui/VnFilterPanelChip.vue';
const { t } = useI18n(); const { t } = useI18n();
const params = defineModel({ default: {}, required: true, type: Object });
const $props = defineProps({ const $props = defineProps({
modelValue: {
type: Object,
default: () => {},
},
dataKey: { dataKey: {
type: String, type: String,
required: true, required: true,
}, },
searchButton: { searchButton: {
type: Boolean, type: Boolean,
required: false,
default: false, default: false,
}, },
showAll: { showAll: {
@ -28,8 +26,8 @@ const $props = defineProps({
type: Array, type: Array,
required: false, required: false,
default: () => [], default: () => [],
description: `Some filters come with default search parameters and require a value. description:
This prop helps us determine which filters can be removed and which cannot.`, 'Algunos filtros vienen con parametros de búsqueda por default y necesitan tener si o si un valor, por eso de ser necesario, esta prop nos sirve para saber que filtros podemos remover y cuales no',
}, },
exprBuilder: { exprBuilder: {
type: Function, type: Function,
@ -37,7 +35,7 @@ const $props = defineProps({
}, },
hiddenTags: { hiddenTags: {
type: Array, type: Array,
default: () => ['filter', 'or', 'and'], default: () => ['filter'],
}, },
customTags: { customTags: {
type: Array, type: Array,
@ -49,7 +47,7 @@ const $props = defineProps({
}, },
searchUrl: { searchUrl: {
type: String, type: String,
default: 'table', default: 'params',
}, },
redirect: { redirect: {
type: Boolean, type: Boolean,
@ -57,154 +55,115 @@ const $props = defineProps({
}, },
}); });
const emit = defineEmits([ const emit = defineEmits(['refresh', 'clear', 'search', 'init', 'remove']);
'update:modelValue',
'refresh',
'clear',
'search',
'init',
'remove',
'setUserParams',
]);
const arrayData = useArrayData($props.dataKey, { const arrayData = useArrayData($props.dataKey, {
exprBuilder: $props.exprBuilder, exprBuilder: $props.exprBuilder,
searchUrl: $props.searchUrl, searchUrl: $props.searchUrl,
navigate: $props.redirect ? {} : null, navigate: {},
}); });
const route = useRoute(); const route = useRoute();
const store = arrayData.store; const store = arrayData.store;
const userParams = ref({});
defineExpose({ search, sanitizer, params: userParams });
onMounted(() => { onMounted(() => {
if (!userParams.value) userParams.value = $props.modelValue ?? {}; emit('init', { params: params.value });
emit('init', { params: userParams.value });
}); });
function setUserParams(watchedParams) { function setUserParams(watchedParams) {
if (!watchedParams || Object.keys(watchedParams).length == 0) return; if (!watchedParams) return;
if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams); if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
if (typeof watchedParams?.filter == 'string')
watchedParams.filter = JSON.parse(watchedParams.filter);
watchedParams = { ...watchedParams, ...watchedParams.filter?.where }; watchedParams = { ...watchedParams, ...watchedParams.filter?.where };
const order = watchedParams.filter?.order;
delete watchedParams.filter; delete watchedParams.filter;
userParams.value = sanitizer(watchedParams); params.value = { ...params.value, ...watchedParams };
emit('setUserParams', userParams.value, order);
} }
watch( watch(
() => route.query[$props.searchUrl], () => route.query[$props.searchUrl],
(val, oldValue) => (val || oldValue) && setUserParams(val) (val) => setUserParams(val)
); );
watch( watch(
() => arrayData.store.userParams, () => arrayData.store.userParams,
(val, oldValue) => (val || oldValue) && setUserParams(val), (val) => setUserParams(val)
{ immediate: true }
);
watch(
() => $props.modelValue,
(val) => (userParams.value = val ?? {})
); );
const isLoading = ref(false); const isLoading = ref(false);
async function search(evt) { async function search(evt) {
try { if (evt && $props.disableSubmitEvent) return;
if (evt && $props.disableSubmitEvent) return;
store.filter.where = {}; store.filter.where = {};
isLoading.value = true; isLoading.value = true;
const filter = { ...userParams.value, ...$props.modelValue }; const filter = { ...params.value };
store.userParamsChanged = true; store.userParamsChanged = true;
const { params: newParams } = await arrayData.addFilter({ store.filter.skip = 0;
params: filter, store.skip = 0;
}); const { params: newParams } = await arrayData.addFilter({ params: params.value });
userParams.value = newParams; params.value = newParams;
if (!$props.showAll && !Object.values(filter).length) store.data = []; if (!$props.showAll && !Object.values(filter).length) store.data = [];
emit('search');
} finally { isLoading.value = false;
isLoading.value = false; emit('search');
} }
async function reload() {
isLoading.value = true;
const params = Object.values(params.value).filter((param) => param);
await arrayData.fetch({ append: false });
if (!$props.showAll && !params.length) store.data = [];
isLoading.value = false;
emit('refresh');
} }
async function clearFilters() { async function clearFilters() {
try { isLoading.value = true;
isLoading.value = true; store.userParamsChanged = true;
store.userParamsChanged = true; store.filter.skip = 0;
arrayData.reset(['skip', 'filter.skip', 'page']); store.skip = 0;
// Filtrar los params no removibles // Filtrar los params no removibles
const removableFilters = Object.keys(userParams.value).filter((param) => const removableFilters = Object.keys(params.value).filter((param) =>
$props.unremovableParams.includes(param) $props.unremovableParams.includes(param)
); );
const newParams = {}; const newParams = {};
// Conservar solo los params que no son removibles // Conservar solo los params que no son removibles
for (const key of removableFilters) { for (const key of removableFilters) {
newParams[key] = userParams.value[key]; newParams[key] = params.value[key];
}
userParams.value = {};
userParams.value = { ...newParams }; // Actualizar los params con los removibles
await arrayData.applyFilter({ params: userParams.value });
if (!$props.showAll) {
store.data = [];
}
emit('clear');
emit('update:modelValue', userParams.value);
} finally {
isLoading.value = false;
} }
params.value = {};
params.value = { ...newParams }; // Actualizar los params con los removibles
await arrayData.applyFilter({ params: params.value });
if (!$props.showAll) {
store.data = [];
}
isLoading.value = false;
emit('clear');
} }
const tagsList = computed(() => { const tagsList = computed(() => {
const tagList = []; const tagList = [];
for (const key of Object.keys(userParams.value)) { for (const key of Object.keys(params.value)) {
const value = userParams.value[key]; const value = params.value[key];
if (value == null || ($props.hiddenTags || []).includes(key)) continue; if (value == null || ($props.hiddenTags || []).includes(key)) continue;
tagList.push({ label: key, value }); tagList.push({ label: key, value });
} }
return tagList; return tagList;
}); });
const formatTags = (tags) => {
const formattedTags = [];
tags.forEach((tag) => {
if (tag.label === 'and') {
tag.value.forEach((item) => {
for (const key in item) {
formattedTags.push({ label: key, value: item[key] });
}
});
} else {
formattedTags.push(tag);
}
});
return formattedTags;
};
const tags = computed(() => { const tags = computed(() => {
const filteredTags = tagsList.value.filter( return tagsList.value.filter((tag) => !($props.customTags || []).includes(tag.key));
(tag) => !($props.customTags || []).includes(tag.label)
);
return formatTags(filteredTags);
}); });
const customTags = computed(() => const customTags = computed(() =>
tagsList.value.filter((tag) => ($props.customTags || []).includes(tag.label)) tagsList.value.filter((tag) => ($props.customTags || []).includes(tag.key))
); );
async function remove(key) { async function remove(key) {
userParams.value[key] = undefined; params.value[key] = undefined;
await search(); search();
emit('remove', key); emit('remove', key);
emit('update:modelValue', userParams.value);
} }
function formatValue(value) { function formatValue(value) {
@ -213,33 +172,10 @@ function formatValue(value) {
return `"${value}"`; return `"${value}"`;
} }
function sanitizer(params) {
for (const [key, value] of Object.entries(params)) {
if (key === 'and' && Array.isArray(value)) {
value.forEach((item) => {
Object.assign(params, item);
});
delete params[key];
} else if (value && typeof value === 'object') {
const param = Object.values(value)[0];
if (typeof param == 'string') params[key] = param.replaceAll('%', '');
}
}
return params;
}
</script> </script>
<template> <template>
<QBtn <QForm @submit="search" id="filterPanelForm">
class="q-mt-lg q-mr-xs q-mb-lg"
round
color="primary"
style="position: fixed; z-index: 1; right: 0; bottom: 0"
icon="search"
@click="search()"
></QBtn>
<QForm @submit="search" id="filterPanelForm" @keyup.enter="search()">
<QList dense> <QList dense>
<QItem class="q-mt-xs"> <QItem class="q-mt-xs">
<QItemSection top> <QItemSection top>
@ -248,18 +184,32 @@ function sanitizer(params) {
</QItemLabel> </QItemLabel>
</QItemSection> </QItemSection>
<QItemSection top side> <QItemSection top side>
<QBtn <div class="q-gutter-xs">
@click="clearFilters" <QBtn
color="primary" @click="clearFilters"
dense color="primary"
flat dense
icon="filter_list_off" flat
padding="none" icon="filter_list_off"
round padding="none"
size="sm" round
> size="sm"
<QTooltip>{{ t('Remove filters') }}</QTooltip> >
</QBtn> <QTooltip>{{ t('Remove filters') }}</QTooltip>
</QBtn>
<QBtn
@click="reload"
color="primary"
dense
flat
icon="refresh"
padding="none"
round
size="sm"
>
<QTooltip>{{ t('Refresh') }}</QTooltip>
</QBtn>
</div>
</QItemSection> </QItemSection>
</QItem> </QItem>
<QItem class="q-mb-sm"> <QItem class="q-mb-sm">
@ -273,9 +223,8 @@ function sanitizer(params) {
<VnFilterPanelChip <VnFilterPanelChip
v-for="chip of tags" v-for="chip of tags"
:key="chip.label" :key="chip.label"
:removable="!unremovableParams?.includes(chip.label)" :removable="!unremovableParams.includes(chip.label)"
@remove="remove(chip.label)" @remove="remove(chip.label)"
data-cy="vnFilterPanelChip"
> >
<slot name="tags" :tag="chip" :format-fn="formatValue"> <slot name="tags" :tag="chip" :format-fn="formatValue">
<div class="q-gutter-x-xs"> <div class="q-gutter-x-xs">
@ -287,7 +236,7 @@ function sanitizer(params) {
<slot <slot
v-if="$slots.customTags" v-if="$slots.customTags"
name="customTags" name="customTags"
:params="userParams" :params="params"
:tags="customTags" :tags="customTags"
:format-fn="formatValue" :format-fn="formatValue"
:search-fn="search" :search-fn="search"
@ -297,8 +246,25 @@ function sanitizer(params) {
<QSeparator /> <QSeparator />
</QList> </QList>
<QList dense class="list q-gutter-y-sm q-mt-sm"> <QList dense class="list q-gutter-y-sm q-mt-sm">
<slot name="body" :params="sanitizer(userParams)" :search-fn="search"></slot> <slot name="body" :params="params" :search-fn="search"></slot>
</QList> </QList>
<template v-if="$props.searchButton">
<QItem>
<QItemSection class="q-py-sm">
<QBtn
:label="t('Search')"
class="full-width"
color="primary"
dense
icon="search"
rounded
:type="disableSubmitEvent ? 'button' : 'submit'"
unelevated
/>
</QItemSection>
</QItem>
<QSeparator />
</template>
</QForm> </QForm>
<QInnerLoading <QInnerLoading
:label="t('globals.pleaseWait')" :label="t('globals.pleaseWait')"

View File

@ -1,8 +1,6 @@
<script setup> <script setup>
import { ref } from 'vue'; import { ref, computed, onMounted } from 'vue';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
import noImage from '/no-user.png';
import { useRole } from 'src/composables/useRole';
const $props = defineProps({ const $props = defineProps({
storage: { storage: {
@ -13,17 +11,14 @@ const $props = defineProps({
type: String, type: String,
default: 'catalog', default: 'catalog',
}, },
resolution: { size: {
type: String, type: String,
default: '200x200', default: '200x200',
}, },
zoomResolution: { zoomSize: {
type: String, type: String,
default: null, required: false,
}, default: 'lg',
zoom: {
type: Boolean,
default: true,
}, },
id: { id: {
type: Number, type: Number,
@ -33,50 +28,35 @@ const $props = defineProps({
const show = ref(false); const show = ref(false);
const token = useSession().getTokenMultimedia(); const token = useSession().getTokenMultimedia();
const timeStamp = ref(`timestamp=${Date.now()}`); const timeStamp = ref(`timestamp=${Date.now()}`);
const isEmployee = useRole().isEmployee(); const url = computed(
() =>
const getUrl = (zoom = false) => { `/api/${$props.storage}/${$props.collection}/${$props.size}/${$props.id}/download?access_token=${token}&${timeStamp.value}`
const curResolution = zoom );
? $props.zoomResolution || $props.resolution const reload = (emit = false) => {
: $props.resolution;
if ($props.storage === 'dms')
return `/api/${$props.storage}/${$props.id}/downloadFile?access_token=${token}`;
return isEmployee
? `/api/${$props.storage}/${$props.collection}/${curResolution}/${$props.id}/download?access_token=${token}&${timeStamp.value}`
: noImage;
};
const reload = () => {
timeStamp.value = `timestamp=${Date.now()}`; timeStamp.value = `timestamp=${Date.now()}`;
}; };
defineExpose({ defineExpose({
reload, reload,
}); });
onMounted(() => {});
</script> </script>
<template> <template>
<QImg <QImg :src="url" v-bind="$attrs" @click="show = !show" spinner-color="primary" />
:draggable="true" <QDialog v-model="show" v-if="$props.zoomSize">
:class="{ zoomIn: zoom }"
:src="getUrl()"
v-bind="$attrs"
@click.stop="show = $props.zoom"
spinner-color="primary"
/>
<QDialog v-if="$props.zoom" v-model="show">
<QImg <QImg
:draggable="true" :src="url"
:src="getUrl(true)" size="full"
class="img_zoom"
v-bind="$attrs" v-bind="$attrs"
spinner-color="primary" spinner-color="primary"
class="img_zoom"
:ratio="0"
/> />
</QDialog> </QDialog>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.q-img { .q-img {
&.zoomIn { cursor: zoom-in;
cursor: zoom-in;
}
min-width: 50px; min-width: 50px;
} }
.rounded { .rounded {

View File

@ -1,16 +0,0 @@
<script setup>
defineProps({ email: { type: [String], default: null } });
</script>
<template>
<QBtn
v-if="email"
flat
round
icon="email"
size="sm"
color="primary"
padding="none"
:href="`mailto:${email}`"
@click.stop
/>
</template>

View File

@ -1,60 +1,16 @@
<script setup> <script setup>
import { ref, reactive, useAttrs, onBeforeMount, capitalize } from 'vue'; defineProps({ phoneNumber: { type: [String, Number], default: null } });
import axios from 'axios';
import { parsePhone } from 'src/filters';
import useOpenURL from 'src/composables/useOpenURL';
const props = defineProps({
phoneNumber: { type: [String, Number], default: null },
channel: { type: Number, default: null },
country: { type: String, default: null },
});
const phone = ref(props.phoneNumber);
const config = reactive({
sip: { icon: 'phone', href: `sip:${props.phoneNumber}` },
'say-simple': {
icon: 'vn:saysimple',
url: null,
channel: props.channel,
},
});
const type = Object.keys(config).find((key) => key in useAttrs()) || 'sip';
onBeforeMount(async () => {
if (!phone.value) return;
let { channel } = config[type];
if (type === 'say-simple') {
const { url, defaultChannel } = (await axios.get('SaySimpleConfigs/findOne'))
.data;
if (!channel) channel = defaultChannel;
phone.value = await parsePhone(props.phoneNumber, props.country.toLowerCase());
config[
type
].url = `${url}?customerIdentity=%2B${phone.value}&channelId=${channel}`;
}
});
function handleClick() {
if (config[type].url) useOpenURL(config[type].url);
else if (config[type].href) window.location.href = config[type].href;
}
</script> </script>
<template> <template>
<QBtn <QBtn
v-if="phone" v-if="phoneNumber"
flat flat
round round
:icon="config[type].icon" icon="phone"
size="sm" size="sm"
color="primary" color="primary"
padding="none" padding="none"
@click.stop="handleClick" :href="`sip:${phoneNumber}`"
> @click.stop
<QTooltip> />
{{ capitalize(type).replace('-', '') }}
</QTooltip>
</QBtn>
</template> </template>

View File

@ -2,7 +2,6 @@
import { dashIfEmpty } from 'src/filters'; import { dashIfEmpty } from 'src/filters';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useClipboard } from 'src/composables/useClipboard'; import { useClipboard } from 'src/composables/useClipboard';
import { computed } from 'vue';
const $props = defineProps({ const $props = defineProps({
label: { type: String, default: null }, label: { type: String, default: null },
@ -25,67 +24,52 @@ function copyValueText() {
}, },
}); });
} }
const val = computed(() => $props.value);
</script> </script>
<template> <style scoped>
<div class="vn-label-value"> .label,
<QCheckbox .value {
v-if="typeof value === 'boolean'" white-space: pre-line;
v-model="val" word-wrap: break-word;
:label="label" }
disable </style>
dense <template>
/> <div class="vn-label-value">
<template v-else> <div v-if="$props.label || $slots.label" class="label">
<div v-if="label || $slots.label" class="label"> <slot name="label">
<slot name="label"> <span>{{ $props.label }}</span>
<span>{{ label }}</span> </slot>
</slot> </div>
</div> <div class="value">
<div class="value"> <slot name="value">
<slot name="value"> <span :title="$props.value">
<span :title="value"> {{ $props.dash ? dashIfEmpty($props.value) : $props.value }}
{{ dash ? dashIfEmpty(value) : value }} </span>
</span> </slot>
</slot> </div>
</div> <div class="info" v-if="$props.info">
<div class="info" v-if="info"> <QIcon name="info" class="cursor-pointer" size="xs" color="grey">
<QIcon name="info" class="cursor-pointer" size="xs" color="grey"> <QTooltip class="bg-dark text-white shadow-4" :offset="[10, 10]">
<QTooltip class="bg-dark text-white shadow-4" :offset="[10, 10]"> {{ $props.info }}
{{ info }} </QTooltip>
</QTooltip> </QIcon>
</QIcon> </div>
</div> <div class="copy" v-if="$props.copy && $props.value" @click="copyValueText()">
<div class="copy" v-if="copy && value" @click="copyValueText()"> <QIcon name="Content_Copy" color="primary">
<QIcon name="Content_Copy" color="primary"> <QTooltip>{{ t('globals.copyClipboard') }}</QTooltip>
<QTooltip>{{ t('globals.copyClipboard') }}</QTooltip> </QIcon>
</QIcon> </div>
</div> </div>
</template> </template>
</div>
</template> <style lang="scss" scoped>
<style lang="scss" scoped> .vn-label-value:hover .copy {
.vn-label-value { visibility: visible;
&:hover .copy { cursor: pointer;
visibility: visible; }
cursor: pointer; .copy {
} visibility: hidden;
}
.label, .info {
.value { margin-left: 5px;
white-space: pre-line;
word-wrap: break-word;
}
.copy {
visibility: hidden;
}
.info {
margin-left: 5px;
}
}
:deep(.q-checkbox.disabled) {
opacity: 1 !important;
} }
</style> </style>

View File

@ -1,108 +1,71 @@
<script setup> <script setup>
import axios from 'axios'; import VnAvatar from 'src/components/ui/VnAvatar.vue';
import { ref, reactive } from 'vue';
import { onBeforeRouteLeave } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { toDateHourMin } from 'src/filters'; import { toDateHourMin } from 'src/filters';
import { ref } from 'vue';
import VnPaginate from 'components/ui/VnPaginate.vue'; import axios from 'axios';
import VnUserLink from 'components/ui/VnUserLink.vue'; import { useI18n } from 'vue-i18n';
import VnConfirm from 'components/ui/VnConfirm.vue'; import VnPaginate from './VnPaginate.vue';
import VnAvatar from 'components/ui/VnAvatar.vue'; import VnUserLink from '../ui/VnUserLink.vue';
import VnRow from 'components/ui/VnRow.vue'; import { useState } from 'src/composables/useState';
import VnSelect from 'components/common/VnSelect.vue';
import FetchData from 'components/FetchData.vue';
import VnInput from 'components/common/VnInput.vue';
const $props = defineProps({ const $props = defineProps({
url: { type: String, default: null }, url: { type: String, default: null },
filter: { type: Object, default: () => {} }, filter: { type: Object, default: () => {} },
body: { type: Object, default: () => {} }, body: { type: Object, default: () => {} },
addNote: { type: Boolean, default: false }, addNote: { type: Boolean, default: false },
selectType: { type: Boolean, default: false },
}); });
const { t } = useI18n(); const { t } = useI18n();
const quasar = useQuasar(); const state = useState();
const newNote = reactive({ text: null, observationTypeFk: null }); const currentUser = ref(state.getUser());
const observationTypes = ref([]); const newNote = ref('');
const vnPaginateRef = ref(); const vnPaginateRef = ref();
function handleKeyUp(event) {
async function insert() { if (event.key === 'Enter') {
if (!newNote.text || ($props.selectType && !newNote.observationTypeFk)) return; event.preventDefault();
if (!event.shiftKey) insert();
const body = $props.body; }
const newBody = { }
...body, async function insert() {
...{ text: newNote.text, observationTypeFk: newNote.observationTypeFk }, const body = $props.body;
}; Object.assign(body, { text: newNote.value });
await axios.post($props.url, newBody); await axios.post($props.url, body);
await vnPaginateRef.value.fetch(); await vnPaginateRef.value.fetch();
newNote.value = '';
} }
onBeforeRouteLeave((to, from, next) => {
if (newNote.text)
quasar.dialog({
component: VnConfirm,
componentProps: {
title: t('globals.unsavedPopup.title'),
message: t('globals.unsavedPopup.subtitle'),
promise: () => next(),
},
});
else next();
});
</script> </script>
<template> <template>
<FetchData <QCard class="q-pa-xs q-mb-xl full-width" v-if="$props.addNote">
v-if="selectType"
url="ObservationTypes"
:filter="{ fields: ['id', 'description'] }"
auto-load
@on-fetch="(data) => (observationTypes = data)"
/>
<QCard class="q-pa-xs q-mb-lg full-width" v-if="$props.addNote">
<QCardSection horizontal> <QCardSection horizontal>
{{ t('New note') }} <VnAvatar :worker-id="currentUser.id" size="md" />
<div class="full-width row justify-between q-pa-xs">
<VnUserLink :name="t('New note')" :worker-id="currentUser.id" />
{{ t('globals.now') }}
</div>
</QCardSection> </QCardSection>
<QCardSection class="q-px-xs q-my-none q-py-none"> <QCardSection class="q-pa-xs q-my-none q-py-none" horizontal>
<VnRow class="full-width"> <QInput
<VnSelect v-model="newNote"
:label="t('Observation type')" class="full-width"
v-if="selectType" type="textarea"
url="ObservationTypes" :label="t('Add note here...')"
v-model="newNote.observationTypeFk" filled
option-label="description" size="lg"
style="flex: 0.15" autogrow
:required="true" autofocus
@keyup.enter.stop="insert" @keyup="handleKeyUp"
/> clearable
<VnInput >
v-model.trim="newNote.text" <template #append>
type="textarea" <QBtn
:label="t('Add note here...')" :title="t('Save (Enter)')"
filled icon="save"
size="lg" color="primary"
autogrow flat
@keyup.enter.stop="insert" @click="insert"
clearable />
:required="true" </template>
> </QInput>
<template #append>
<QBtn
:title="t('Save (Enter)')"
icon="save"
color="primary"
flat
@click="insert"
class="q-mb-xs"
dense
data-cy="saveNote"
/>
</template>
</VnInput>
</VnRow>
</QCardSection> </QCardSection>
</QCard> </QCard>
<VnPaginate <VnPaginate
@ -115,11 +78,6 @@ onBeforeRouteLeave((to, from, next) => {
ref="vnPaginateRef" ref="vnPaginateRef"
class="show" class="show"
v-bind="$attrs" v-bind="$attrs"
search-url="notes"
@on-fetch="
newNote.text = '';
newNote.observationTypeFk = null;
"
> >
<template #body="{ rows }"> <template #body="{ rows }">
<TransitionGroup name="list" tag="div" class="column items-center full-width"> <TransitionGroup name="list" tag="div" class="column items-center full-width">
@ -133,28 +91,13 @@ onBeforeRouteLeave((to, from, next) => {
:descriptor="false" :descriptor="false"
:worker-id="note.workerFk" :worker-id="note.workerFk"
size="md" size="md"
:title="note.worker?.user.nickname"
/> />
<div class="full-width row justify-between q-pa-xs"> <div class="full-width row justify-between q-pa-xs">
<div> <VnUserLink
<VnUserLink :name="`${note.worker.user.nickname}`"
:name="`${note.worker.user.name}`" :worker-id="note.worker.id"
:worker-id="note.worker.id" />
/> {{ toDateHourMin(note.created) }}
<QBadge
class="q-ml-xs"
outline
color="grey"
v-if="selectType && note.observationTypeFk"
>
{{
observationTypes.find(
(ot) => ot.id === note.observationTypeFk
)?.description
}}
</QBadge>
</div>
<span v-text="toDateHourMin(note.created)" />
</div> </div>
</QCardSection> </QCardSection>
<QCardSection class="q-pa-xs q-my-none q-py-none"> <QCardSection class="q-pa-xs q-my-none q-py-none">
@ -168,6 +111,12 @@ onBeforeRouteLeave((to, from, next) => {
<style lang="scss" scoped> <style lang="scss" scoped>
.q-card { .q-card {
width: 90%; width: 90%;
@media (max-width: $breakpoint-sm) {
width: 100%;
}
&__section {
word-wrap: break-word;
}
} }
.q-dialog .q-card { .q-dialog .q-card {
width: 400px; width: 400px;
@ -181,28 +130,11 @@ onBeforeRouteLeave((to, from, next) => {
opacity: 0; opacity: 0;
background-color: $primary; background-color: $primary;
} }
.vn-row > :nth-child(2) {
margin-left: 0;
}
@media (max-width: $breakpoint-xs) {
.vn-row > :deep(*) {
margin-left: 0;
}
.q-card {
width: 100%;
&__section {
padding: 0;
}
}
}
</style> </style>
<i18n> <i18n>
es: es:
Add note here...: Añadir nota aquí... Add note here...: Añadir nota aquí...
New note: Nueva nota New note: Nueva nota
Save (Enter): Guardar (Intro) Save (Enter): Guardar (Intro)
Observation type: Tipo de observación
</i18n> </i18n>

View File

@ -1,32 +0,0 @@
<script setup>
const emit = defineEmits(['submit']);
defineProps({
icon: { type: String, required: false, default: 'phonelink_lock' },
title: { type: String, required: true },
});
</script>
<template>
<QForm @submit="emit('submit')" class="q-gutter-y-md q-pa-lg formCard">
<div class="column items-center">
<QIcon v-if="icon != false" :name="icon" size="xl" color="primary" />
<h5 class="text-center q-my-md">
{{ title }}
</h5>
</div>
<slot></slot>
<div class="q-mt-lg">
<slot name="buttons"></slot>
</div>
</QForm>
</template>
<style lang="scss" scoped>
.formCard {
max-width: 350px;
min-width: 300px;
}
@media (max-width: $breakpoint-xs-max) {
.formCard {
min-width: 100%;
}
}
</style>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'; import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
@ -10,10 +10,6 @@ const props = defineProps({
type: String, type: String,
required: true, required: true,
}, },
class: {
type: String,
default: '',
},
autoLoad: { autoLoad: {
type: Boolean, type: Boolean,
default: false, default: false,
@ -30,10 +26,6 @@ const props = defineProps({
type: Object, type: Object,
default: null, default: null,
}, },
userFilter: {
type: Object,
default: null,
},
where: { where: {
type: Object, type: Object,
default: null, default: null,
@ -44,7 +36,7 @@ const props = defineProps({
}, },
limit: { limit: {
type: Number, type: Number,
default: 20, default: 10,
}, },
userParams: { userParams: {
type: Object, type: Object,
@ -56,7 +48,7 @@ const props = defineProps({
}, },
offset: { offset: {
type: Number, type: Number,
default: undefined, default: 0,
}, },
skeleton: { skeleton: {
type: Boolean, type: Boolean,
@ -88,7 +80,6 @@ const pagination = ref({
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: props.url, url: props.url,
filter: props.filter, filter: props.filter,
userFilter: props.userFilter,
where: props.where, where: props.where,
limit: props.limit, limit: props.limit,
order: props.order, order: props.order,
@ -100,12 +91,10 @@ const arrayData = useArrayData(props.dataKey, {
const store = arrayData.store; const store = arrayData.store;
onMounted(async () => { onMounted(async () => {
if (props.autoLoad && !store.data?.length) await fetch(); if (props.autoLoad) await fetch();
mounted.value = true; mounted.value = true;
}); });
onBeforeUnmount(() => arrayData.reset());
watch( watch(
() => props.data, () => props.data,
() => { () => {
@ -115,41 +104,26 @@ watch(
watch( watch(
() => store.data, () => store.data,
(data) => { (data) => emit('onChange', data)
if (!mounted.value) return;
emit('onChange', data);
},
{ immediate: true }
); );
watch( watch(
() => [props.url, props.filter], () => props.url,
([url, filter]) => mounted.value && fetch({ url, filter }) (url) => fetch({ url })
); );
const addFilter = async (filter, params) => { const addFilter = async (filter, params) => {
await arrayData.addFilter({ filter, params }); await arrayData.addFilter({ filter, params });
}; };
async function fetch(params) { async function fetch(params) {
useArrayData(props.dataKey, params); useArrayData(props.dataKey, params);
arrayData.reset(['filter.skip', 'skip', 'page']); store.filter.skip = 0;
await arrayData.fetch({ append: false, updateRouter: mounted.value });
return emitStoreData();
}
async function update(params) {
useArrayData(props.dataKey, params);
const { limit, skip } = store;
store.limit = limit + skip;
store.skip = 0; store.skip = 0;
await arrayData.fetch({ append: false }); await arrayData.fetch({ append: false });
store.limit = limit; if (!store.hasMoreData) {
store.skip = skip; isLoading.value = false;
return emitStoreData(); }
}
function emitStoreData() {
if (!store.hasMoreData) isLoading.value = false;
emit('onFetch', store.data); emit('onFetch', store.data);
return store.data; return store.data;
} }
@ -195,7 +169,7 @@ async function onLoad(index, done) {
done(isDone); done(isDone);
} }
defineExpose({ fetch, update, addFilter, paginate }); defineExpose({ fetch, addFilter, paginate });
</script> </script>
<template> <template>
@ -235,25 +209,18 @@ defineExpose({ fetch, update, addFilter, paginate });
v-if="store.data" v-if="store.data"
@load="onLoad" @load="onLoad"
:offset="offset" :offset="offset"
:class="['full-width', props.class]" class="full-width"
:disable="disableInfiniteScroll || !store.hasMoreData" :disable="disableInfiniteScroll || !store.hasMoreData"
v-bind="$attrs" v-bind="$attrs"
> >
<slot name="body" :rows="store.data"></slot> <slot name="body" :rows="store.data"></slot>
<div v-if="isLoading" class="spinner info-row q-pa-md text-center"> <div v-if="isLoading" class="info-row q-pa-md text-center">
<QSpinner color="primary" size="md" /> <QSpinner color="orange" size="md" />
</div> </div>
</QInfiniteScroll> </QInfiniteScroll>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.spinner {
z-index: 1;
align-content: end;
position: absolute;
bottom: 0;
left: 0;
}
.info-row { .info-row {
width: 100%; width: 100%;

View File

@ -1,26 +1,18 @@
<template> <template>
<div class="vn-row q-gutter-md"> <div class="vn-row q-gutter-md q-mb-md">
<slot /> <slot></slot>
</div> </div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scopped>
.vn-row { .vn-row {
display: flex; display: flex;
> :deep(*) { > * {
flex: 1; flex: 1;
} }
&[wrap] {
flex-wrap: wrap;
}
} }
@media screen and (max-width: 800px) { @media screen and (max-width: 800px) {
.vn-row { .vn-row {
&:not(.wrap) { flex-direction: column;
flex-direction: column;
}
&[fixed] {
flex-direction: row;
}
} }
} }
</style> </style>

View File

@ -45,7 +45,7 @@ const props = defineProps({
}, },
limit: { limit: {
type: Number, type: Number,
default: 20, default: 10,
}, },
userParams: { userParams: {
type: Object, type: Object,
@ -63,13 +63,13 @@ const props = defineProps({
type: String, type: String,
default: '', default: '',
}, },
whereFilter: { makeFetch: {
type: Function, type: Boolean,
default: undefined, default: true,
}, },
}); });
const searchText = ref(); const searchText = ref('');
let arrayDataProps = { ...props }; let arrayDataProps = { ...props };
if (props.redirect) if (props.redirect)
arrayDataProps = { arrayDataProps = {
@ -100,24 +100,18 @@ onMounted(() => {
}); });
async function search() { async function search() {
const staticParams = Object.entries(store.userParams); const staticParams = Object.entries(store.userParams).filter(
arrayData.reset(['skip', 'page']); ([key, value]) => value && (props.staticParams || []).includes(key)
);
store.skip = 0;
const filter = { if (props.makeFetch)
params: { await arrayData.applyFilter({
...Object.fromEntries(staticParams), params: {
search: searchText.value, ...Object.fromEntries(staticParams),
}, search: searchText.value,
...{ filter: props.filter }, },
}; });
if (props.whereFilter) {
filter.filter = {
where: props.whereFilter(searchText.value),
};
delete filter.params.search;
}
await arrayData.applyFilter(filter);
} }
</script> </script>
<template> <template>
@ -125,12 +119,11 @@ async function search() {
<QForm @submit="search" id="searchbarForm"> <QForm @submit="search" id="searchbarForm">
<VnInput <VnInput
id="searchbar" id="searchbar"
v-model.trim="searchText" v-model="searchText"
:placeholder="t(props.label)" :placeholder="t(props.label)"
dense dense
standout standout
autofocus autofocus
data-cy="vnSearchBar"
> >
<template #prepend> <template #prepend>
<QIcon <QIcon

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed } from 'vue'; import { onBeforeMount } from 'vue';
import { date } from 'quasar'; import { date } from 'quasar';
import VnPaginate from 'src/components/ui/VnPaginate.vue'; import VnPaginate from 'src/components/ui/VnPaginate.vue';
import VnAvatar from '../ui/VnAvatar.vue'; import VnAvatar from '../ui/VnAvatar.vue';
@ -10,32 +10,31 @@ const $props = defineProps({
where: { type: Object, default: () => {} }, where: { type: Object, default: () => {} },
}); });
const filter = computed(() => { const filter = {
return { fields: ['smsFk'],
fields: ['smsFk'], include: {
include: { relation: 'sms',
relation: 'sms', scope: {
scope: { fields: [
fields: [ 'senderFk',
'senderFk', 'sender',
'sender', 'destination',
'destination', 'message',
'message', 'statusCode',
'statusCode', 'status',
'status', 'created',
'created', ],
], include: {
include: { relation: 'sender',
relation: 'sender', scope: {
scope: { fields: ['name'],
fields: ['name'],
},
}, },
}, },
}, },
...{ where: $props.where }, },
}; };
});
onBeforeMount(() => (filter.where = $props.where));
function formatNumber(number) { function formatNumber(number) {
if (number.length <= 10) return number; if (number.length <= 10) return number;

Some files were not shown because too many files have changed in this diff Show More