Merge branch 'dev' of https: refs #6564//gitea.verdnatura.es/verdnatura/salix-front into 6564-enhanceTicketAdvance

This commit is contained in:
Jorge Penadés 2025-03-21 15:53:53 +01:00
commit 90d556c892
447 changed files with 11726 additions and 7766 deletions

1
.dockerignore Normal file
View File

@ -0,0 +1 @@
node_modules

1
.gitignore vendored
View File

@ -31,6 +31,7 @@ yarn-error.log*
# Cypress directories and files # Cypress directories and files
/test/cypress/videos /test/cypress/videos
/test/cypress/screenshots /test/cypress/screenshots
/junit
# VitePress directories and files # VitePress directories and files
/docs/.vitepress/cache /docs/.vitepress/cache

File diff suppressed because it is too large Load Diff

116
Jenkinsfile vendored
View File

@ -1,6 +1,7 @@
#!/usr/bin/env groovy #!/usr/bin/env groovy
def PROTECTED_BRANCH def PROTECTED_BRANCH
def IS_LATEST
def BRANCH_ENV = [ def BRANCH_ENV = [
test: 'test', test: 'test',
@ -10,19 +11,22 @@ def BRANCH_ENV = [
node { node {
stage('Setup') { stage('Setup') {
env.FRONT_REPLICAS = 1
env.NODE_ENV = BRANCH_ENV[env.BRANCH_NAME] ?: 'dev' env.NODE_ENV = BRANCH_ENV[env.BRANCH_NAME] ?: 'dev'
PROTECTED_BRANCH = [ PROTECTED_BRANCH = [
'dev', 'dev',
'test', 'test',
'master', 'master',
'main',
'beta' 'beta'
].contains(env.BRANCH_NAME) ]
// https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables IS_PROTECTED_BRANCH = PROTECTED_BRANCH.contains(env.BRANCH_NAME)
IS_LATEST = ['master', 'main'].contains(env.BRANCH_NAME)
// https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
echo "NODE_NAME: ${env.NODE_NAME}" echo "NODE_NAME: ${env.NODE_NAME}"
echo "WORKSPACE: ${env.WORKSPACE}" echo "WORKSPACE: ${env.WORKSPACE}"
echo "CHANGE_TARGET: ${env.CHANGE_TARGET}"
configFileProvider([ configFileProvider([
configFile(fileId: 'salix-front.properties', configFile(fileId: 'salix-front.properties',
@ -33,7 +37,7 @@ node {
props.each {key, value -> echo "${key}: ${value}" } props.each {key, value -> echo "${key}: ${value}" }
} }
if (PROTECTED_BRANCH) { if (IS_PROTECTED_BRANCH) {
configFileProvider([ configFileProvider([
configFile(fileId: "salix-front.branch.${env.BRANCH_NAME}", configFile(fileId: "salix-front.branch.${env.BRANCH_NAME}",
variable: 'BRANCH_PROPS_FILE') variable: 'BRANCH_PROPS_FILE')
@ -58,6 +62,19 @@ pipeline {
PROJECT_NAME = 'lilium' PROJECT_NAME = 'lilium'
} }
stages { stages {
stage('Version') {
when {
expression { IS_PROTECTED_BRANCH }
}
steps {
script {
def packageJson = readJSON file: 'package.json'
def version = "${packageJson.version}-build${env.BUILD_ID}"
writeFile(file: 'VERSION.txt', text: version)
echo "VERSION: ${version}"
}
}
}
stage('Install') { stage('Install') {
environment { environment {
NODE_ENV = "" NODE_ENV = ""
@ -68,48 +85,93 @@ pipeline {
} }
stage('Test') { stage('Test') {
when { when {
expression { !PROTECTED_BRANCH } expression { !IS_PROTECTED_BRANCH }
} }
environment { environment {
NODE_ENV = "" NODE_ENV = ''
CI = 'true'
TZ = 'Europe/Madrid'
} }
steps { parallel {
sh 'pnpm run test:unit:ci' stage('Unit') {
} steps {
post { sh 'pnpm run test:front:ci'
always { }
junit( post {
testResults: 'junitresults.xml', always {
allowEmptyResults: true junit(
) testResults: 'junit/vitest.xml',
allowEmptyResults: true
)
}
}
}
stage('E2E') {
environment {
CREDS = credentials('docker-registry')
COMPOSE_PROJECT = "${PROJECT_NAME}-${env.BUILD_ID}"
COMPOSE_PARAMS = "-p ${env.COMPOSE_PROJECT} -f test/cypress/docker-compose.yml --project-directory ."
}
steps {
script {
sh 'rm -f junit/e2e-*.xml'
sh 'rm -rf test/cypress/screenshots'
env.COMPOSE_TAG = PROTECTED_BRANCH.contains(env.CHANGE_TARGET) ? env.CHANGE_TARGET : 'dev'
def image = docker.build('lilium-dev', '-f docs/Dockerfile.dev docs')
sh 'docker login --username $CREDS_USR --password $CREDS_PSW $REGISTRY'
sh "docker-compose ${env.COMPOSE_PARAMS} pull back"
sh "docker-compose ${env.COMPOSE_PARAMS} pull db"
sh "docker-compose ${env.COMPOSE_PARAMS} up -d"
image.inside("--network ${env.COMPOSE_PROJECT}_default -e CI -e TZ --init") {
sh 'sh test/cypress/cypressParallel.sh 1'
}
}
}
post {
always {
sh "docker-compose ${env.COMPOSE_PARAMS} down -v"
archiveArtifacts artifacts: 'test/cypress/screenshots/**/*', allowEmptyArchive: true
junit(
testResults: 'junit/e2e-*.xml',
allowEmptyResults: true
)
}
}
} }
} }
} }
stage('Build') { stage('Build') {
when { when {
expression { PROTECTED_BRANCH } expression { IS_PROTECTED_BRANCH }
} }
environment { environment {
CREDENTIALS = credentials('docker-registry') VERSION = readFile 'VERSION.txt'
} }
steps { steps {
sh 'quasar build'
script { script {
def packageJson = readJSON file: 'package.json' sh 'quasar build'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
def baseImage = "salix-frontend:${env.VERSION}"
def image = docker.build(baseImage, ".")
docker.withRegistry("https://${env.REGISTRY}", 'docker-registry') {
image.push()
image.push(env.BRANCH_NAME)
if (IS_LATEST) image.push('latest')
}
} }
dockerBuild()
} }
} }
stage('Deploy') { stage('Deploy') {
when { when {
expression { PROTECTED_BRANCH } expression { IS_PROTECTED_BRANCH }
}
environment {
VERSION = readFile 'VERSION.txt'
} }
steps { steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
}
withKubeConfig([ withKubeConfig([
serverUrl: "$KUBERNETES_API", serverUrl: "$KUBERNETES_API",
credentialsId: 'kubernetes', credentialsId: 'kubernetes',

View File

@ -23,7 +23,7 @@ quasar dev
### Run unit tests ### Run unit tests
```bash ```bash
pnpm run test:unit pnpm run test:front
``` ```
### Run e2e tests ### Run e2e tests
@ -32,6 +32,18 @@ pnpm run test:unit
pnpm run test:e2e pnpm run test:e2e
``` ```
### Run e2e parallel
```bash
pnpm run test:e2e:parallel
```
### View e2e parallel report
```bash
pnpm run test:e2e:summary
```
### Build the app for production ### Build the app for production
```bash ```bash

View File

@ -1,12 +1,44 @@
import { defineConfig } from 'cypress'; import { defineConfig } from 'cypress';
// https://docs.cypress.io/app/tooling/reporters
// https://docs.cypress.io/app/references/configuration let urlHost, reporter, reporterOptions, timeouts;
// https://www.npmjs.com/package/cypress-mochawesome-reporter
if (process.env.CI) {
urlHost = 'front';
reporter = 'junit';
reporterOptions = {
mochaFile: 'junit/e2e-[hash].xml',
};
timeouts = {
defaultCommandTimeout: 30000,
requestTimeout: 30000,
responseTimeout: 60000,
pageLoadTimeout: 60000,
};
} else {
urlHost = 'localhost';
reporter = 'cypress-mochawesome-reporter';
reporterOptions = {
charts: true,
reportPageTitle: 'Cypress Inline Reporter',
reportFilename: '[status]_[datetime]-report',
embeddedScreenshots: true,
reportDir: 'test/cypress/reports',
inlineAssets: true,
};
timeouts = {
defaultCommandTimeout: 10000,
requestTimeout: 10000,
responseTimeout: 30000,
pageLoadTimeout: 60000,
};
}
export default defineConfig({ export default defineConfig({
e2e: { e2e: {
baseUrl: 'http://localhost:9000/', baseUrl: `http://${urlHost}:9000`,
experimentalStudio: true, experimentalStudio: false,
trashAssetsBeforeRuns: false,
defaultBrowser: 'chromium',
fixturesFolder: 'test/cypress/fixtures', fixturesFolder: 'test/cypress/fixtures',
screenshotsFolder: 'test/cypress/screenshots', screenshotsFolder: 'test/cypress/screenshots',
supportFile: 'test/cypress/support/index.js', supportFile: 'test/cypress/support/index.js',
@ -14,29 +46,19 @@ export default defineConfig({
downloadsFolder: 'test/cypress/downloads', downloadsFolder: 'test/cypress/downloads',
video: false, video: false,
specPattern: 'test/cypress/integration/**/*.spec.js', specPattern: 'test/cypress/integration/**/*.spec.js',
experimentalRunAllSpecs: false, experimentalRunAllSpecs: true,
watchForFileChanges: false, watchForFileChanges: true,
reporter: 'cypress-mochawesome-reporter', reporter,
reporterOptions: { 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: async (on, config) => {
const plugin = await import('cypress-mochawesome-reporter/plugin');
plugin.default(on);
return config;
},
viewportWidth: 1280, viewportWidth: 1280,
viewportHeight: 720, viewportHeight: 720,
...timeouts,
includeShadowDom: true,
waitForAnimations: true,
}, },
}); });

View File

@ -1,7 +0,0 @@
version: '3.7'
services:
main:
image: registry.verdnatura.es/salix-frontend:${VERSION:?}
build:
context: .
dockerfile: ./Dockerfile

47
docs/Dockerfile.dev Normal file
View File

@ -0,0 +1,47 @@
FROM debian:12.9-slim
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
gnupg2 \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& npm install -g corepack@0.31.0 \
&& corepack enable pnpm \
&& rm -rf /var/lib/apt/lists/*
RUN apt-get update \
&& apt-get -y --no-install-recommends install \
apt-utils \
chromium \
libasound2 \
libgbm-dev \
libgtk-3-0 \
libgtk2.0-0 \
libnotify-dev \
libnss3 \
libxss1 \
libxtst6 \
mesa-vulkan-drivers \
vulkan-tools \
xauth \
xvfb \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
RUN groupadd -r -g 1000 app \
&& useradd -r -u 1000 -g app -m -d /home/app app
USER app
ENV SHELL=bash
ENV PNPM_HOME="/home/app/.local/share/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN pnpm setup \
&& pnpm install --global cypress@14.1.0 \
&& cypress install
WORKDIR /app

View File

@ -1,6 +1,6 @@
{ {
"name": "salix-front", "name": "salix-front",
"version": "25.08.0", "version": "25.14.0",
"description": "Salix frontend", "description": "Salix frontend",
"productName": "Salix", "productName": "Salix",
"author": "Verdnatura", "author": "Verdnatura",
@ -13,9 +13,11 @@
"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": "npm run resetDatabase && cd ../salix-front && cypress run",
"test:e2e:parallel": "bash ./test/cypress/run.sh",
"test:e2e:summary": "bash ./test/cypress/summary.sh",
"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:front": "vitest",
"test:unit:ci": "vitest run", "test:front:ci": "vitest run",
"commitlint": "commitlint --edit", "commitlint": "commitlint --edit",
"prepare": "npx husky install", "prepare": "npx husky install",
"addReferenceTag": "node .husky/addReferenceTag.js", "addReferenceTag": "node .husky/addReferenceTag.js",
@ -47,18 +49,21 @@
"@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0", "@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0",
"@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": "^14.1.0",
"cypress-mochawesome-reporter": "^3.8.2", "cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1", "eslint-config-prettier": "^10.0.1",
"eslint-plugin-cypress": "^4.1.0", "eslint-plugin-cypress": "^4.1.0",
"eslint-plugin-vue": "^9.32.0", "eslint-plugin-vue": "^9.32.0",
"husky": "^8.0.0", "husky": "^8.0.0",
"junit-merge": "^2.0.0",
"mocha": "^11.1.0",
"postcss": "^8.4.23", "postcss": "^8.4.23",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"sass": "^1.83.4", "sass": "^1.83.4",
"vitepress": "^1.6.3", "vitepress": "^1.6.3",
"vitest": "^0.34.0" "vitest": "^0.34.0",
"xunit-viewer": "^10.6.1"
}, },
"engines": { "engines": {
"node": "^20 || ^18 || ^16", "node": "^20 || ^18 || ^16",

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
export default [ export default [
{ {
path: '/api', path: '/api',
rule: { target: 'http://0.0.0.0:3000' }, rule: { target: 'http://127.0.0.1:3000' },
}, },
]; ];

View File

@ -11,6 +11,7 @@
import { configure } from 'quasar/wrappers'; import { configure } from 'quasar/wrappers';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite'; import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import path from 'path'; import path from 'path';
const target = `http://${process.env.CI ? 'back' : 'localhost'}:3000`;
export default configure(function (/* ctx */) { export default configure(function (/* ctx */) {
return { return {
@ -108,13 +109,17 @@ export default configure(function (/* ctx */) {
}, },
proxy: { proxy: {
'/api': { '/api': {
target: 'http://0.0.0.0:3000', target: target,
logLevel: 'debug', logLevel: 'debug',
changeOrigin: true, changeOrigin: true,
secure: false, secure: false,
}, },
}, },
open: false, open: false,
allowedHosts: [
'front', // Agrega este nombre de host
'localhost', // Opcional, para pruebas locales
],
}, },
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework // https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#framework

View File

@ -30,22 +30,5 @@ export default {
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
form.addEventListener('keyup', function (evt) {
if (evt.key === 'Enter' && !that.$attrs['prevent-submit']) {
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

@ -2,7 +2,6 @@
import { 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 VnSelectProvince from 'src/components/VnSelectProvince.vue'; import VnSelectProvince from 'src/components/VnSelectProvince.vue';
@ -21,14 +20,11 @@ const postcodeFormData = reactive({
provinceFk: null, provinceFk: null,
townFk: null, townFk: null,
}); });
const townsFetchDataRef = ref(false);
const townFilter = ref({}); const townFilter = ref({});
const countriesRef = ref(false); const countriesRef = ref(false);
const provincesOptions = ref([]); const provincesOptions = ref([]);
const townsOptions = ref([]);
const town = ref({}); const town = ref({});
const countryFilter = ref({});
function onDataSaved(formData) { function onDataSaved(formData) {
const newPostcode = { const newPostcode = {
@ -51,7 +47,6 @@ async function setCountry(countryFk, data) {
data.townFk = null; data.townFk = null;
data.provinceFk = null; data.provinceFk = null;
data.countryFk = countryFk; data.countryFk = countryFk;
await fetchTowns();
} }
// Province // Province
@ -60,22 +55,11 @@ async function setProvince(id, data) {
const newProvince = provincesOptions.value.find((province) => province.id == id); const newProvince = provincesOptions.value.find((province) => province.id == id);
if (newProvince) data.countryFk = newProvince.countryFk; if (newProvince) data.countryFk = newProvince.countryFk;
postcodeFormData.provinceFk = id; postcodeFormData.provinceFk = id;
await fetchTowns();
} }
async function onProvinceCreated(data) { async function onProvinceCreated(data) {
postcodeFormData.provinceFk = data.id; 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) { function setTown(newTown, data) {
town.value = newTown; town.value = newTown;
data.provinceFk = newTown?.provinceFk ?? newTown; data.provinceFk = newTown?.provinceFk ?? newTown;
@ -88,18 +72,6 @@ async function onCityCreated(newTown, formData) {
formData.townFk = newTown; formData.townFk = newTown;
setTown(newTown, formData); 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) { async function filterTowns(name) {
if (name !== '') { if (name !== '') {
@ -108,22 +80,11 @@ async function filterTowns(name) {
like: `%${name}%`, like: `%${name}%`,
}, },
}; };
await townsFetchDataRef.value?.fetch();
} }
} }
</script> </script>
<template> <template>
<FetchData
ref="townsFetchDataRef"
:sort-by="['name ASC']"
:limit="30"
:filter="townFilter"
@on-fetch="handleTowns"
auto-load
url="Towns/location"
/>
<FormModelPopup <FormModelPopup
url-create="postcodes" url-create="postcodes"
model="postcode" model="postcode"
@ -149,14 +110,13 @@ async function filterTowns(name) {
@filter="filterTowns" @filter="filterTowns"
:tooltip="t('Create city')" :tooltip="t('Create city')"
v-model="data.townFk" v-model="data.townFk"
:options="townsOptions" url="Towns/location"
option-label="name"
option-value="id"
:rules="validate('postcode.city')" :rules="validate('postcode.city')"
:acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]" :acls="[{ model: 'Town', props: '*', accessType: 'WRITE' }]"
:emit-value="false" :emit-value="false"
required required
data-cy="locationTown" data-cy="locationTown"
sort-by="name ASC"
> >
<template #option="{ itemProps, opt }"> <template #option="{ itemProps, opt }">
<QItem v-bind="itemProps"> <QItem v-bind="itemProps">
@ -197,16 +157,12 @@ async function filterTowns(name) {
/> />
<VnSelect <VnSelect
ref="countriesRef" ref="countriesRef"
:limit="30"
:filter="countryFilter"
:sort-by="['name ASC']" :sort-by="['name ASC']"
auto-load auto-load
url="Countries" url="Countries"
required required
:label="t('Country')" :label="t('Country')"
hide-selected hide-selected
option-label="name"
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)" @update:model-value="(value) => setCountry(value, data)"

View File

@ -62,12 +62,9 @@ const where = computed(() => {
auto-load auto-load
:where="where" :where="where"
url="Autonomies/location" url="Autonomies/location"
:sort-by="['name ASC']" sort-by="name ASC"
:limit="30"
:label="t('Autonomy')" :label="t('Autonomy')"
hide-selected hide-selected
option-label="name"
option-value="id"
v-model="data.autonomyFk" v-model="data.autonomyFk"
:rules="validate('province.autonomyFk')" :rules="validate('province.autonomyFk')"
> >

View File

@ -181,17 +181,19 @@ async function saveChanges(data) {
return; return;
} }
let changes = data || getChanges(); let changes = data || getChanges();
if ($props.beforeSaveFn) { if ($props.beforeSaveFn) changes = await $props.beforeSaveFn(changes, getChanges);
changes = await $props.beforeSaveFn(changes, getChanges);
}
try { try {
if (changes?.creates?.length === 0 && changes?.updates?.length === 0) {
return;
}
await axios.post($props.saveUrl || $props.url + '/crud', changes); await axios.post($props.saveUrl || $props.url + '/crud', changes);
} finally { } finally {
isLoading.value = false; 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;
emit('saveChanges', data); emit('saveChanges', data);

View File

@ -42,7 +42,6 @@ const itemFilter = {
const itemFilterParams = reactive({}); const itemFilterParams = reactive({});
const closeButton = ref(null); const closeButton = ref(null);
const isLoading = ref(false); const isLoading = ref(false);
const producersOptions = ref([]);
const ItemTypesOptions = ref([]); const ItemTypesOptions = ref([]);
const InksOptions = ref([]); const InksOptions = ref([]);
const tableRows = ref([]); const tableRows = ref([]);
@ -121,23 +120,17 @@ const selectItem = ({ id }) => {
</script> </script>
<template> <template>
<FetchData
url="Producers"
@on-fetch="(data) => (producersOptions = data)"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
auto-load
/>
<FetchData <FetchData
url="ItemTypes" url="ItemTypes"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }" :filter="{ fields: ['id', 'name'], order: 'name ASC' }"
order="name" order="name ASC"
@on-fetch="(data) => (ItemTypesOptions = data)" @on-fetch="(data) => (ItemTypesOptions = data)"
auto-load auto-load
/> />
<FetchData <FetchData
url="Inks" url="Inks"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }" :filter="{ fields: ['id', 'name'], order: 'name ASC' }"
order="name" order="name ASC"
@on-fetch="(data) => (InksOptions = data)" @on-fetch="(data) => (InksOptions = data)"
auto-load auto-load
/> />
@ -152,11 +145,11 @@ const selectItem = ({ id }) => {
<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('globals.producer')"
:options="producersOptions"
hide-selected hide-selected
option-label="name"
option-value="id"
v-model="itemFilterParams.producerFk" v-model="itemFilterParams.producerFk"
url="Producers"
:fields="['id', 'name']"
sort-by="name ASC"
/> />
<VnSelect <VnSelect
:label="t('globals.type')" :label="t('globals.type')"
@ -195,7 +188,7 @@ const selectItem = ({ id }) => {
> >
<template #body-cell-id="{ row }"> <template #body-cell-id="{ row }">
<QTd auto-width @click.stop> <QTd auto-width @click.stop>
<QBtn flat color="blue">{{ row.id }}</QBtn> <QBtn flat class="link">{{ row.id }}</QBtn>
<ItemDescriptorProxy :id="row.id" /> <ItemDescriptorProxy :id="row.id" />
</QTd> </QTd>
</template> </template>

View File

@ -124,7 +124,7 @@ const selectTravel = ({ id }) => {
<FetchData <FetchData
url="AgencyModes" url="AgencyModes"
@on-fetch="(data) => (agenciesOptions = data)" @on-fetch="(data) => (agenciesOptions = data)"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }" :filter="{ fields: ['id', 'name'], order: ['name ASC'] }"
auto-load auto-load
/> />
<FetchData <FetchData
@ -196,7 +196,7 @@ const selectTravel = ({ id }) => {
> >
<template #body-cell-id="{ row }"> <template #body-cell-id="{ row }">
<QTd auto-width @click.stop data-cy="travelFk-travel-form"> <QTd auto-width @click.stop data-cy="travelFk-travel-form">
<QBtn flat color="blue">{{ row.id }}</QBtn> <QBtn flat class="link">{{ row.id }}</QBtn>
<TravelDescriptorProxy :id="row.id" /> <TravelDescriptorProxy :id="row.id" />
</QTd> </QTd>
</template> </template>

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import axios from 'axios'; import axios from 'axios';
import { onMounted, onUnmounted, computed, ref, watch, nextTick } from 'vue'; import { onMounted, onUnmounted, computed, ref, watch, nextTick, useAttrs } from 'vue';
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router'; import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
@ -12,6 +12,7 @@ import SkeletonForm from 'components/ui/SkeletonForm.vue';
import VnConfirm from './ui/VnConfirm.vue'; import VnConfirm from './ui/VnConfirm.vue';
import { tMobile } from 'src/composables/tMobile'; import { tMobile } from 'src/composables/tMobile';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { getDifferences, getUpdatedValues } from 'src/filters';
const { push } = useRouter(); const { push } = useRouter();
const quasar = useQuasar(); const quasar = useQuasar();
@ -22,6 +23,7 @@ const { validate } = useValidator();
const { notify } = useNotify(); const { notify } = useNotify();
const route = useRoute(); const route = useRoute();
const myForm = ref(null); const myForm = ref(null);
const attrs = useAttrs();
const $props = defineProps({ const $props = defineProps({
url: { url: {
type: String, type: String,
@ -94,6 +96,10 @@ const $props = defineProps({
type: [String, Boolean], type: [String, Boolean],
default: '800px', default: '800px',
}, },
onDataSaved: {
type: Function,
default: () => {},
},
}); });
const emit = defineEmits(['onFetch', 'onDataSaved']); const emit = defineEmits(['onFetch', 'onDataSaved']);
const modelValue = computed( const modelValue = computed(
@ -106,14 +112,14 @@ const isLoading = ref(false);
const isResetting = ref(false); const isResetting = ref(false);
const hasChanges = ref(!$props.observeFormChanges); const hasChanges = ref(!$props.observeFormChanges);
const originalData = computed(() => state.get(modelValue)); const originalData = computed(() => state.get(modelValue));
const formData = ref({}); const formData = ref();
const defaultButtons = computed(() => ({ const defaultButtons = computed(() => ({
save: { save: {
dataCy: 'saveDefaultBtn', dataCy: 'saveDefaultBtn',
color: 'primary', color: 'primary',
icon: 'save', icon: 'save',
label: 'globals.save', label: 'globals.save',
click: () => myForm.value.onSubmit(false), click: async () => await save(),
type: 'submit', type: 'submit',
}, },
reset: { reset: {
@ -134,7 +140,8 @@ onMounted(async () => {
if (!$props.formInitialData) { if (!$props.formInitialData) {
if ($props.autoLoad && $props.url) await fetch(); if ($props.autoLoad && $props.url) await fetch();
else if (arrayData.store.data) updateAndEmit('onFetch', arrayData.store.data); else if (arrayData.store.data)
updateAndEmit('onFetch', { val: arrayData.store.data });
} }
if ($props.observeFormChanges) { if ($props.observeFormChanges) {
watch( watch(
@ -154,7 +161,7 @@ onMounted(async () => {
if (!$props.url) if (!$props.url)
watch( watch(
() => arrayData.store.data, () => arrayData.store.data,
(val) => updateAndEmit('onFetch', val), (val) => updateAndEmit('onFetch', { val }),
); );
watch( watch(
@ -200,15 +207,14 @@ async function fetch() {
}); });
if (Array.isArray(data)) data = data[0] ?? {}; if (Array.isArray(data)) data = data[0] ?? {};
updateAndEmit('onFetch', data); updateAndEmit('onFetch', { val: data });
} catch (e) { } catch (e) {
state.set(modelValue, {}); state.set(modelValue, {});
throw e; throw e;
} }
} }
async function save(prevent = false) { async function save() {
if (prevent) return;
if ($props.observeFormChanges && !hasChanges.value) if ($props.observeFormChanges && !hasChanges.value)
return notify('globals.noChanges', 'negative'); return notify('globals.noChanges', 'negative');
@ -228,7 +234,11 @@ async function save(prevent = false) {
if ($props.urlCreate) notify('globals.dataCreated', 'positive'); if ($props.urlCreate) notify('globals.dataCreated', 'positive');
updateAndEmit('onDataSaved', formData.value, response?.data); updateAndEmit('onDataSaved', {
val: formData.value,
res: response?.data,
old: originalData.value,
});
if ($props.reload) await arrayData.fetch({}); if ($props.reload) await arrayData.fetch({});
hasChanges.value = false; hasChanges.value = false;
} finally { } finally {
@ -243,7 +253,7 @@ async function saveAndGo() {
function reset() { function reset() {
formData.value = JSON.parse(JSON.stringify(originalData.value)); formData.value = JSON.parse(JSON.stringify(originalData.value));
updateAndEmit('onFetch', originalData.value); updateAndEmit('onFetch', { val: originalData.value });
if ($props.observeFormChanges) { if ($props.observeFormChanges) {
hasChanges.value = false; hasChanges.value = false;
isResetting.value = true; isResetting.value = true;
@ -265,11 +275,11 @@ function filter(value, update, filterOptions) {
); );
} }
function updateAndEmit(evt, val, res) { function updateAndEmit(evt, { val, res, old } = { val: null, res: null, old: null }) {
state.set(modelValue, val); state.set(modelValue, val);
if (!$props.url) arrayData.store.data = val; if (!$props.url) arrayData.store.data = val;
emit(evt, state.get(modelValue), res); emit(evt, state.get(modelValue), res, old);
} }
function trimData(data) { function trimData(data) {
@ -279,6 +289,27 @@ function trimData(data) {
} }
return data; return data;
} }
function onBeforeSave(formData, originalData) {
return getUpdatedValues(
Object.keys(getDifferences(formData, originalData)),
formData,
);
}
async function onKeyup(evt) {
if (evt.key === 'Enter' && !('prevent-submit' in attrs)) {
const input = evt.target;
if (input.type == 'textarea' && evt.shiftKey) {
let { selectionStart, selectionEnd } = input;
input.value =
input.value.substring(0, selectionStart) +
'\n' +
input.value.substring(selectionEnd);
selectionStart = selectionEnd = selectionStart + 1;
return;
}
await save();
}
}
defineExpose({ defineExpose({
save, save,
@ -294,12 +325,13 @@ defineExpose({
<QForm <QForm
ref="myForm" ref="myForm"
v-if="formData" v-if="formData"
@submit="save(!!$event)" @submit.prevent
@keyup.prevent="onKeyup"
@reset="reset" @reset="reset"
class="q-pa-md" class="q-pa-md"
:style="maxWidth ? 'max-width: ' + maxWidth : ''" :style="maxWidth ? 'max-width: ' + maxWidth : ''"
id="formModel" id="formModel"
:prevent-submit="$attrs['prevent-submit']" :mapper="onBeforeSave"
> >
<QCard> <QCard>
<slot <slot

View File

@ -1,12 +1,13 @@
<script setup> <script setup>
import { ref, computed } from 'vue'; import { ref, computed, useAttrs, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useState } from 'src/composables/useState';
import FormModel from 'components/FormModel.vue'; import FormModel from 'components/FormModel.vue';
const emit = defineEmits(['onDataSaved', 'onDataCanceled']); const emit = defineEmits(['onDataSaved', 'onDataCanceled']);
defineProps({ const props = defineProps({
title: { title: {
type: String, type: String,
default: '', default: '',
@ -22,17 +23,28 @@ defineProps({
}); });
const { t } = useI18n(); const { t } = useI18n();
const attrs = useAttrs();
const state = useState();
const formModelRef = ref(null); const formModelRef = ref(null);
const closeButton = ref(null); const closeButton = ref(null);
const isSaveAndContinue = ref(false); const isSaveAndContinue = ref(props.showSaveAndContinueBtn);
const onDataSaved = (formData, requestResponse) => { const isLoading = computed(() => formModelRef.value?.isLoading);
if (closeButton.value && isSaveAndContinue) closeButton.value.click(); const reset = computed(() => formModelRef.value?.reset);
const onDataSaved = async (formData, requestResponse) => {
if (!isSaveAndContinue.value) closeButton.value?.click();
if (isSaveAndContinue.value) {
await nextTick();
state.set(attrs.model, attrs.formInitialData);
}
isSaveAndContinue.value = props.showSaveAndContinueBtn;
emit('onDataSaved', formData, requestResponse); emit('onDataSaved', formData, requestResponse);
}; };
const isLoading = computed(() => formModelRef.value?.isLoading); const onClick = async (saveAndContinue) => {
const reset = computed(() => formModelRef.value?.reset); isSaveAndContinue.value = saveAndContinue;
await formModelRef.value.save();
};
defineExpose({ defineExpose({
isLoading, isLoading,
@ -69,19 +81,13 @@ defineExpose({
data-cy="FormModelPopup_cancel" data-cy="FormModelPopup_cancel"
v-close-popup v-close-popup
z-max z-max
@click=" @click="emit('onDataCanceled')"
isSaveAndContinue = false;
emit('onDataCanceled');
"
/> />
<QBtn <QBtn
:flat="showSaveAndContinueBtn" :flat="showSaveAndContinueBtn"
:label="t('globals.save')" :label="t('globals.save')"
:title="t('globals.save')" :title="t('globals.save')"
@click=" @click="onClick(false)"
formModelRef.save();
isSaveAndContinue = false;
"
color="primary" color="primary"
class="q-ml-sm" class="q-ml-sm"
:disabled="isLoading" :disabled="isLoading"
@ -99,10 +105,7 @@ defineExpose({
:loading="isLoading" :loading="isLoading"
data-cy="FormModelPopup_isSaveAndContinue" data-cy="FormModelPopup_isSaveAndContinue"
z-max z-max
@click=" @click="onClick(true)"
isSaveAndContinue = true;
formModelRef.save();
"
/> />
</div> </div>
</template> </template>

View File

@ -121,23 +121,25 @@ const removeTag = (index, params, search) => {
applyTags(params, search); applyTags(params, search);
}; };
const setCategoryList = (data) => { const setCategoryList = (data) => {
categoryList.value = (data || []) categoryList.value = (data || []).map((category) => ({
.filter((category) => category.display) ...category,
.map((category) => ({ icon: `vn:${(category.icon || '').split('-')[1]}`,
...category, }));
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
fetchItemTypes(); fetchItemTypes();
}; };
</script> </script>
<template> <template>
<FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" /> <FetchData
url="ItemCategories"
auto-load
@on-fetch="setCategoryList"
:where="{ display: { neq: 0 } }"
/>
<FetchData <FetchData
url="Tags" url="Tags"
:filter="{ fields: ['id', 'name', 'isFree'] }" :filter="{ fields: ['id', 'name', 'isFree'] }"
auto-load auto-load
limit="30"
@on-fetch="(data) => (tagOptions = data)" @on-fetch="(data) => (tagOptions = data)"
/> />
<VnFilterPanel <VnFilterPanel
@ -195,8 +197,6 @@ const setCategoryList = (data) => {
:label="t('components.itemsFilterPanel.typeFk')" :label="t('components.itemsFilterPanel.typeFk')"
v-model="params.typeFk" v-model="params.typeFk"
:options="itemTypesOptions" :options="itemTypesOptions"
option-value="id"
option-label="name"
dense dense
outlined outlined
rounded rounded
@ -234,7 +234,6 @@ const setCategoryList = (data) => {
:label="t('globals.tag')" :label="t('globals.tag')"
v-model="value.selectedTag" v-model="value.selectedTag"
:options="tagOptions" :options="tagOptions"
option-label="name"
dense dense
outlined outlined
rounded rounded

View File

@ -77,6 +77,7 @@ watch(
function findMatches(search, item) { function findMatches(search, item) {
const matches = []; const matches = [];
function findRoute(search, item) { function findRoute(search, item) {
if (!item?.children) return;
for (const child of item.children) { for (const child of item.children) {
if (search?.indexOf(child.name) > -1) { if (search?.indexOf(child.name) > -1) {
matches.push(child); matches.push(child);
@ -92,7 +93,7 @@ function findMatches(search, item) {
} }
function addChildren(module, route, parent) { function addChildren(module, route, parent) {
const menus = route?.meta?.menu ?? route?.menus?.[props.source]; //backwards compatible const menus = route?.meta?.menu;
if (!menus) return; if (!menus) return;
const matches = findMatches(menus, route); const matches = findMatches(menus, route);
@ -107,11 +108,7 @@ function getRoutes() {
main: getMainRoutes, main: getMainRoutes,
card: getCardRoutes, card: getCardRoutes,
}; };
try { handleRoutes[props.source]();
handleRoutes[props.source]();
} catch (error) {
throw new Error(`Method is not defined`);
}
} }
function getMainRoutes() { function getMainRoutes() {
const modules = Object.assign([], navigation.getModules().value); const modules = Object.assign([], navigation.getModules().value);
@ -122,7 +119,6 @@ function getMainRoutes() {
); );
if (!moduleDef) continue; if (!moduleDef) continue;
item.children = []; item.children = [];
addChildren(item.module, moduleDef, item.children); addChildren(item.module, moduleDef, item.children);
} }
@ -132,21 +128,16 @@ function getMainRoutes() {
function getCardRoutes() { function getCardRoutes() {
const currentRoute = route.matched[1]; const currentRoute = route.matched[1];
const currentModule = toLowerCamel(currentRoute.name); const currentModule = toLowerCamel(currentRoute.name);
let moduleDef = routes.find((route) => toLowerCamel(route.name) === currentModule); let moduleDef;
if (!moduleDef) return;
if (!moduleDef?.menus) moduleDef = betaGetRoutes();
addChildren(currentModule, moduleDef, items.value);
}
function betaGetRoutes() {
let menuRoute;
let index = route.matched.length - 1; let index = route.matched.length - 1;
while (!menuRoute && index > 0) { while (!moduleDef && index > 0) {
if (route.matched[index]?.meta?.menu) menuRoute = route.matched[index]; if (route.matched[index]?.meta?.menu) moduleDef = route.matched[index];
index--; index--;
} }
return menuRoute;
if (!moduleDef) return;
addChildren(currentModule, moduleDef, items.value);
} }
async function togglePinned(item, event) { async function togglePinned(item, event) {

View File

@ -57,7 +57,7 @@ const refresh = () => window.location.reload();
:class="{ :class="{
'no-visible': !stateQuery.isLoading().value, 'no-visible': !stateQuery.isLoading().value,
}" }"
size="xs" size="sm"
data-cy="loading-spinner" data-cy="loading-spinner"
/> />
<QSpace /> <QSpace />
@ -85,7 +85,15 @@ const refresh = () => window.location.reload();
</QTooltip> </QTooltip>
<PinnedModules ref="pinnedModulesRef" /> <PinnedModules ref="pinnedModulesRef" />
</QBtn> </QBtn>
<QBtn class="q-pa-none" rounded dense flat no-wrap id="user"> <QBtn
class="q-pa-none"
rounded
dense
flat
no-wrap
id="user"
data-cy="userPanel_btn"
>
<VnAvatar <VnAvatar
:worker-id="user.id" :worker-id="user.id"
:title="user.name" :title="user.name"

View File

@ -1,16 +1,53 @@
<script setup> <script setup>
import { toCurrency } from 'src/filters';
defineProps({ row: { type: Object, required: true } }); defineProps({ row: { type: Object, required: true } });
</script> </script>
<template> <template>
<span class="q-gutter-x-xs"> <span class="q-gutter-x-xs">
<router-link
v-if="row.claim?.claimFk"
:to="{ name: 'ClaimBasicData', params: { id: row.claim?.claimFk } }"
class="link"
>
<QIcon name="vn:claims" size="xs">
<QTooltip>
{{ $t('ticketSale.claim') }}:
{{ row.claim?.claimFk }}
</QTooltip>
</QIcon>
</router-link>
<QIcon <QIcon
v-if="row?.risk" v-if="row?.reserved"
color="primary"
name="vn:reserva"
size="xs"
data-cy="ticketSaleReservedIcon"
>
<QTooltip>
{{ t('ticketSale.reserved') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.isDeleted"
color="primary"
name="vn:deletedTicket"
size="xs"
data-cy="ticketDeletedIcon"
>
<QTooltip>
{{ t('Ticket deleted') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasRisk"
name="vn:risk" name="vn:risk"
:color="row.hasHighRisk ? 'negative' : 'primary'" :color="row.hasHighRisk ? 'negative' : 'primary'"
size="xs" size="xs"
> >
<QTooltip> <QTooltip>
{{ $t('salesTicketsTable.risk') }}: {{ row.risk - row.credit }} {{ $t('salesTicketsTable.risk') }}:
{{ toCurrency(row.risk - (row.credit ?? 0)) }}
</QTooltip> </QTooltip>
</QIcon> </QIcon>
<QIcon <QIcon
@ -52,12 +89,7 @@ defineProps({ row: { type: Object, required: true } });
> >
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip> <QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon> </QIcon>
<QIcon <QIcon v-if="row?.isTaxDataChecked" name="vn:no036" color="primary" size="xs">
v-if="!row?.isTaxDataChecked === 0"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip> <QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon> </QIcon>
<QIcon v-if="row?.isFreezed" name="vn:frozen" color="primary" size="xs"> <QIcon v-if="row?.isFreezed" name="vn:frozen" color="primary" size="xs">

View File

@ -87,7 +87,7 @@ const makeInvoice = async () => {
(data) => ( (data) => (
(rectificativeTypeOptions = data), (rectificativeTypeOptions = data),
(transferInvoiceParams.cplusRectificationTypeFk = data.filter( (transferInvoiceParams.cplusRectificationTypeFk = data.filter(
(type) => type.description == 'I Por diferencias' (type) => type.description == 'I Por diferencias',
)[0].id) )[0].id)
) )
" "
@ -100,7 +100,7 @@ const makeInvoice = async () => {
(data) => ( (data) => (
(siiTypeInvoiceOutsOptions = data), (siiTypeInvoiceOutsOptions = data),
(transferInvoiceParams.siiTypeInvoiceOutFk = data.filter( (transferInvoiceParams.siiTypeInvoiceOutFk = data.filter(
(type) => type.code == 'R4' (type) => type.code == 'R4',
)[0].id) )[0].id)
) )
" "
@ -122,7 +122,6 @@ const makeInvoice = async () => {
<VnRow> <VnRow>
<VnSelect <VnSelect
:label="t('Client')" :label="t('Client')"
:options="clientsOptions"
hide-selected hide-selected
option-label="name" option-label="name"
option-value="id" option-value="id"

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { markRaw, computed } from 'vue'; import { markRaw, computed } from 'vue';
import { QIcon, QCheckbox, QToggle } from 'quasar'; import { QIcon, QToggle } from 'quasar';
import { dashIfEmpty } from 'src/filters'; import { dashIfEmpty } from 'src/filters';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';

View File

@ -6,6 +6,7 @@ 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 VnInputTime from 'components/common/VnInputTime.vue';
import VnCheckbox from 'components/common/VnCheckbox.vue';
import VnColumn from 'components/VnTable/VnColumn.vue'; import VnColumn from 'components/VnTable/VnColumn.vue';
const $props = defineProps({ const $props = defineProps({
@ -91,7 +92,6 @@ const components = {
event: updateEvent, event: updateEvent,
attrs: { attrs: {
...defaultAttrs, ...defaultAttrs,
style: 'min-width: 150px',
}, },
forceAttrs, forceAttrs,
}, },
@ -107,7 +107,7 @@ const components = {
}, },
}, },
checkbox: { checkbox: {
component: markRaw(QCheckbox), component: markRaw(VnCheckbox),
event: updateEvent, event: updateEvent,
attrs: { attrs: {
class: $props.showTitle ? 'q-py-sm' : 'q-px-md q-py-xs fit', class: $props.showTitle ? 'q-py-sm' : 'q-px-md q-py-xs fit',
@ -152,7 +152,7 @@ const onTabPressed = async () => {
}; };
</script> </script>
<template> <template>
<div v-if="showFilter" class="full-width flex-center" style="overflow: hidden"> <div v-if="showFilter" class="full-width" style="overflow: hidden">
<VnColumn <VnColumn
:column="$props.column" :column="$props.column"
default="input" default="input"

View File

@ -23,6 +23,10 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
align: {
type: String,
default: 'end',
},
}); });
const hover = ref(); const hover = ref();
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl }); const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl });
@ -46,16 +50,27 @@ async function orderBy(name, direction) {
} }
defineExpose({ orderBy }); defineExpose({ orderBy });
function textAlignToFlex(textAlign) {
return `justify-content: ${
{
'text-center': 'center',
'text-left': 'start',
'text-right': 'end',
}[textAlign] || 'start'
};`;
}
</script> </script>
<template> <template>
<div <div
@mouseenter="hover = true" @mouseenter="hover = true"
@mouseleave="hover = false" @mouseleave="hover = false"
@click="orderBy(name, model?.direction)" @click="orderBy(name, model?.direction)"
class="row items-center no-wrap cursor-pointer title" class="items-center no-wrap cursor-pointer title"
:style="textAlignToFlex(align)"
> >
<span :title="label">{{ label }}</span> <span :title="label">{{ label }}</span>
<sup v-if="name && model?.index"> <div v-if="name && model?.index">
<QChip <QChip
:label="!vertical ? model?.index : ''" :label="!vertical ? model?.index : ''"
:icon=" :icon="
@ -92,20 +107,16 @@ defineExpose({ orderBy });
/> />
</div> </div>
</QChip> </QChip>
</sup> </div>
</div> </div>
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
.title { .title {
display: flex; display: flex;
justify-content: center;
align-items: center; align-items: center;
height: 30px; height: 30px;
width: 100%; width: 100%;
color: var(--vn-label-color); color: var(--vn-label-color);
} white-space: nowrap;
sup {
vertical-align: super; /* Valor predeterminado */
/* También puedes usar otros valores como "baseline", "top", "text-top", etc. */
} }
</style> </style>

View File

@ -10,14 +10,15 @@ import {
render, render,
inject, inject,
useAttrs, useAttrs,
nextTick,
} from 'vue'; } from 'vue';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { useQuasar } from 'quasar'; import { useQuasar, date } from 'quasar';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useFilterParams } from 'src/composables/useFilterParams'; import { useFilterParams } from 'src/composables/useFilterParams';
import { dashIfEmpty } from 'src/filters'; import { dashIfEmpty, toDate } from 'src/filters';
import CrudModel from 'src/components/CrudModel.vue'; import CrudModel from 'src/components/CrudModel.vue';
import FormModelPopup from 'components/FormModelPopup.vue'; import FormModelPopup from 'components/FormModelPopup.vue';
@ -30,6 +31,7 @@ import VnLv from 'components/ui/VnLv.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue'; import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
import VnTableFilter from './VnTableFilter.vue'; import VnTableFilter from './VnTableFilter.vue';
import { getColAlign } from 'src/composables/getColAlign'; import { getColAlign } from 'src/composables/getColAlign';
import RightMenu from '../common/RightMenu.vue';
const arrayData = useArrayData(useAttrs()['data-key']); const arrayData = useArrayData(useAttrs()['data-key']);
const $props = defineProps({ const $props = defineProps({
@ -49,14 +51,14 @@ const $props = defineProps({
type: Boolean, type: Boolean,
default: true, default: true,
}, },
rightSearchIcon: {
type: Boolean,
default: true,
},
rowClick: { rowClick: {
type: [Function, Boolean], type: [Function, Boolean],
default: null, default: null,
}, },
rowCtrlClick: {
type: [Function, Boolean],
default: null,
},
redirect: { redirect: {
type: String, type: String,
default: null, default: null,
@ -136,6 +138,10 @@ const $props = defineProps({
createComplement: { createComplement: {
type: Object, type: Object,
}, },
dataCy: {
type: String,
default: 'vnTable',
},
}); });
const { t } = useI18n(); const { t } = useI18n();
@ -164,7 +170,6 @@ const app = inject('app');
const editingRow = ref(null); const editingRow = ref(null);
const editingField = ref(null); const editingField = ref(null);
const isTableMode = computed(() => mode.value == TABLE_MODE); const isTableMode = computed(() => mode.value == TABLE_MODE);
const showRightIcon = computed(() => $props.rightSearch || $props.rightSearchIcon);
const selectRegex = /select/; const selectRegex = /select/;
const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']); const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']);
const tableModes = [ const tableModes = [
@ -252,7 +257,9 @@ function splitColumns(columns) {
col.columnFilter = { inWhere: true, ...col.columnFilter }; col.columnFilter = { inWhere: true, ...col.columnFilter };
splittedColumns.value.columns.push(col); splittedColumns.value.columns.push(col);
} }
// Status column
splittedColumns.value.create = createOrderSort(splittedColumns.value.create);
if (splittedColumns.value.chips.length) { if (splittedColumns.value.chips.length) {
splittedColumns.value.columnChips = splittedColumns.value.chips.filter( splittedColumns.value.columnChips = splittedColumns.value.chips.filter(
(c) => !c.isId, (c) => !c.isId,
@ -268,6 +275,24 @@ function splitColumns(columns) {
} }
} }
function createOrderSort(columns) {
const orderedColumn = columns
.map((column, index) =>
column.createOrder !== undefined ? { ...column, originalIndex: index } : null,
)
.filter((item) => item !== null);
orderedColumn.sort((a, b) => a.createOrder - b.createOrder);
const filteredColumns = columns.filter((col) => col.createOrder === undefined);
orderedColumn.forEach((col) => {
filteredColumns.splice(col.createOrder, 0, col);
});
return filteredColumns;
}
const rowClickFunction = computed(() => { const rowClickFunction = computed(() => {
if ($props.rowClick != undefined) return $props.rowClick; if ($props.rowClick != undefined) return $props.rowClick;
if ($props.redirect) return ({ id }) => redirectFn(id); if ($props.redirect) return ({ id }) => redirectFn(id);
@ -313,8 +338,14 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
if (evt?.shiftKey && added) { if (evt?.shiftKey && added) {
const rowIndex = selectedRows[0].$index; const rowIndex = selectedRows[0].$index;
const selectedIndexes = new Set(selected.value.map((row) => row.$index)); const selectedIndexes = new Set(selected.value.map((row) => row.$index));
for (const row of rows) { const minIndex = selectedIndexes.size
if (row.$index == rowIndex) break; ? Math.min(...selectedIndexes, rowIndex)
: 0;
const maxIndex = Math.max(...selectedIndexes, rowIndex);
for (let i = minIndex; i <= maxIndex; i++) {
const row = rows[i];
if (row.$index == rowIndex) continue;
if (!selectedIndexes.has(row.$index)) { if (!selectedIndexes.has(row.$index)) {
selected.value.push(row); selected.value.push(row);
selectedIndexes.add(row.$index); selectedIndexes.add(row.$index);
@ -337,15 +368,14 @@ function hasEditableFormat(column) {
const clickHandler = async (event) => { const clickHandler = async (event) => {
const clickedElement = event.target.closest('td'); const clickedElement = event.target.closest('td');
const isDateElement = event.target.closest('.q-date'); const isDateElement = event.target.closest('.q-date');
const isTimeElement = event.target.closest('.q-time'); const isTimeElement = event.target.closest('.q-time');
const isQselectDropDown = event.target.closest('.q-select__dropdown-icon'); const isQSelectDropDown = event.target.closest('.q-select__dropdown-icon');
if (isDateElement || isTimeElement || isQselectDropDown) return; if (isDateElement || isTimeElement || isQSelectDropDown) return;
if (clickedElement === null) { if (clickedElement === null) {
destroyInput(editingRow.value, editingField.value); await destroyInput(editingRow.value, editingField.value);
return; return;
} }
const rowIndex = clickedElement.getAttribute('data-row-index'); const rowIndex = clickedElement.getAttribute('data-row-index');
@ -353,19 +383,19 @@ const clickHandler = async (event) => {
const column = $props.columns.find((col) => col.name === colField); const column = $props.columns.find((col) => col.name === colField);
if (editingRow.value !== null && editingField.value !== null) { if (editingRow.value !== null && editingField.value !== null) {
if (editingRow.value === rowIndex && editingField.value === colField) { if (editingRow.value == rowIndex && editingField.value == colField) return;
return;
}
destroyInput(editingRow.value, editingField.value); await destroyInput(editingRow.value, editingField.value);
} }
if (isEditableColumn(column))
if (isEditableColumn(column)) {
await renderInput(Number(rowIndex), colField, clickedElement); await renderInput(Number(rowIndex), colField, clickedElement);
}
}; };
async function handleTabKey(event, rowIndex, colField) { async function handleTabKey(event, rowIndex, colField) {
if (editingRow.value == rowIndex && editingField.value == colField) if (editingRow.value == rowIndex && editingField.value == colField)
destroyInput(editingRow.value, editingField.value); await destroyInput(editingRow.value, editingField.value);
const direction = event.shiftKey ? -1 : 1; const direction = event.shiftKey ? -1 : 1;
const { nextRowIndex, nextColumnName } = await handleTabNavigation( const { nextRowIndex, nextColumnName } = await handleTabNavigation(
@ -413,19 +443,13 @@ async function renderInput(rowId, field, clickedElement) {
eventHandlers: { eventHandlers: {
'update:modelValue': async (value) => { 'update:modelValue': async (value) => {
if (isSelect && value) { if (isSelect && value) {
row[column.name] = value[column.attrs?.optionValue ?? 'id']; await updateSelectValue(value, column, row, oldValue);
row[column?.name + 'TextValue'] =
value[column.attrs?.optionLabel ?? 'name'];
await column?.cellEvent?.['update:modelValue']?.(
value,
oldValue,
row,
);
} else row[column.name] = value; } else row[column.name] = value;
await column?.cellEvent?.['update:modelValue']?.(value, oldValue, row); await column?.cellEvent?.['update:modelValue']?.(value, oldValue, row);
}, },
keyup: async (event) => { keyup: async (event) => {
if (event.key === 'Enter') handleBlur(rowId, field, clickedElement); if (event.key === 'Enter')
await destroyInput(rowId, field, clickedElement);
}, },
keydown: async (event) => { keydown: async (event) => {
switch (event.key) { switch (event.key) {
@ -434,7 +458,7 @@ async function renderInput(rowId, field, clickedElement) {
event.stopPropagation(); event.stopPropagation();
break; break;
case 'Escape': case 'Escape':
destroyInput(rowId, field, clickedElement); await destroyInput(rowId, field, clickedElement);
break; break;
default: default:
break; break;
@ -449,16 +473,31 @@ async function renderInput(rowId, field, clickedElement) {
node.appContext = app._context; node.appContext = app._context;
render(node, clickedElement); render(node, clickedElement);
if (['checkbox', 'toggle', undefined].includes(column?.component)) if (['toggle'].includes(column?.component))
node.el?.querySelector('span > div').focus(); node.el?.querySelector('span > div').focus();
if (['checkbox', undefined].includes(column?.component))
node.el?.querySelector('span > div > div').focus();
} }
function destroyInput(rowIndex, field, clickedElement) { async function updateSelectValue(value, column, row, oldValue) {
row[column.name] = value[column.attrs?.optionValue ?? 'id'];
row[column?.name + 'VnTableTextValue'] = value[column.attrs?.optionLabel ?? 'name'];
if (column?.attrs?.find?.label)
row[column?.attrs?.find?.label] = value[column.attrs?.optionLabel ?? 'name'];
await column?.cellEvent?.['update:modelValue']?.(value, oldValue, row);
}
async function destroyInput(rowIndex, field, clickedElement) {
if (!clickedElement) if (!clickedElement)
clickedElement = document.querySelector( clickedElement = document.querySelector(
`[data-row-index="${rowIndex}"][data-col-field="${field}"]`, `[data-row-index="${rowIndex}"][data-col-field="${field}"]`,
); );
if (clickedElement) { if (clickedElement) {
await nextTick();
render(null, clickedElement); render(null, clickedElement);
Array.from(clickedElement.childNodes).forEach((child) => { Array.from(clickedElement.childNodes).forEach((child) => {
child.style.visibility = 'visible'; child.style.visibility = 'visible';
@ -470,10 +509,6 @@ function destroyInput(rowIndex, field, clickedElement) {
editingField.value = null; editingField.value = null;
} }
function handleBlur(rowIndex, field, clickedElement) {
destroyInput(rowIndex, field, clickedElement);
}
async function handleTabNavigation(rowIndex, colName, direction) { async function handleTabNavigation(rowIndex, colName, direction) {
const columns = $props.columns; const columns = $props.columns;
const totalColumns = columns.length; const totalColumns = columns.length;
@ -489,9 +524,7 @@ async function handleTabNavigation(rowIndex, colName, direction) {
if (isEditableColumn(columns[newColumnIndex])) break; if (isEditableColumn(columns[newColumnIndex])) break;
} while (iterations < totalColumns); } while (iterations < totalColumns);
if (iterations >= totalColumns) { if (iterations >= totalColumns + 1) return;
return;
}
if (direction === 1 && newColumnIndex <= currentColumnIndex) { if (direction === 1 && newColumnIndex <= currentColumnIndex) {
rowIndex++; rowIndex++;
@ -520,27 +553,82 @@ function getToggleIcon(value) {
} }
function formatColumnValue(col, row, dashIfEmpty) { function formatColumnValue(col, row, dashIfEmpty) {
if (col?.format) { if (col?.format || row[col?.name + 'VnTableTextValue']) {
if (selectRegex.test(col?.component) && row[col?.name + 'TextValue']) { if (selectRegex.test(col?.component) && row[col?.name + 'VnTableTextValue']) {
return dashIfEmpty(row[col?.name + 'TextValue']); return dashIfEmpty(row[col?.name + 'VnTableTextValue']);
} else { } else {
return col.format(row, dashIfEmpty); return col.format(row, dashIfEmpty);
} }
} else {
return dashIfEmpty(row[col?.name]);
} }
if (col?.component === 'date') return dashIfEmpty(toDate(row[col?.name]));
if (col?.component === 'time')
return row[col?.name] >= 5
? dashIfEmpty(date.formatDate(new Date(row[col?.name]), 'HH:mm'))
: row[col?.name];
if (selectRegex.test(col?.component) && $props.isEditable) {
const { find, url } = col.attrs;
const urlRelation = url?.charAt(0)?.toLocaleLowerCase() + url?.slice(1, -1);
if (col?.attrs.options) {
const find = col?.attrs.options.find((option) => option.id === row[col.name]);
if (!col.attrs?.optionLabel || !find) return dashIfEmpty(row[col?.name]);
return dashIfEmpty(find[col.attrs?.optionLabel ?? 'name']);
}
if (typeof row[urlRelation] == 'object') {
if (typeof find == 'object')
return dashIfEmpty(row[urlRelation][find?.label ?? 'name']);
return dashIfEmpty(row[urlRelation][col?.attrs.optionLabel ?? 'name']);
}
if (typeof row[urlRelation] == 'string') return dashIfEmpty(row[urlRelation]);
}
return dashIfEmpty(row[col?.name]);
} }
const checkbox = ref(null);
function cardClick(_, row) {
if ($props.redirect) router.push({ path: `/${$props.redirect}/${row.id}` });
}
function removeTextValue(data, getChanges) {
let changes = data.updates;
if (changes) {
for (const change of changes) {
for (const key in change.data) {
if (key.endsWith('VnTableTextValue')) {
delete change.data[key];
}
}
}
data.updates = changes.filter((change) => Object.keys(change.data).length > 0);
}
if ($attrs?.beforeSaveFn) data = $attrs.beforeSaveFn(data, getChanges);
return data;
}
function handleRowClick(event, row) {
if (event.ctrlKey) return rowCtrlClickFunction.value(event, row);
if (rowClickFunction.value) rowClickFunction.value(row);
}
const rowCtrlClickFunction = computed(() => {
if ($props.rowCtrlClick != undefined) return $props.rowCtrlClick;
if ($props.redirect)
return (evt, { id }) => {
stopEventPropagation(evt);
window.open(`/#/${$props.redirect}/${id}`, '_blank');
};
return () => {};
});
</script> </script>
<template> <template>
<QDrawer <RightMenu v-if="$props.rightSearch" :overlay="overlay">
v-if="$props.rightSearch" <template #right-panel>
v-model="stateStore.rightDrawer"
side="right"
:width="256"
:overlay="$props.overlay"
>
<QScrollArea class="fit">
<VnTableFilter <VnTableFilter
:data-key="$attrs['data-key']" :data-key="$attrs['data-key']"
:columns="columns" :columns="columns"
@ -554,8 +642,8 @@ const checkbox = ref(null);
<slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" /> <slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template> </template>
</VnTableFilter> </VnTableFilter>
</QScrollArea> </template>
</QDrawer> </RightMenu>
<CrudModel <CrudModel
v-bind="$attrs" v-bind="$attrs"
:class="$attrs['class'] ?? 'q-px-md'" :class="$attrs['class'] ?? 'q-px-md'"
@ -564,6 +652,7 @@ const checkbox = ref(null);
@on-fetch="(...args) => emit('onFetch', ...args)" @on-fetch="(...args) => emit('onFetch', ...args)"
:search-url="searchUrl" :search-url="searchUrl"
:disable-infinite-scroll="isTableMode" :disable-infinite-scroll="isTableMode"
:before-save-fn="removeTextValue"
@save-changes="reload" @save-changes="reload"
:has-sub-toolbar="$props.hasSubToolbar ?? isEditable" :has-sub-toolbar="$props.hasSubToolbar ?? isEditable"
:auto-load="hasParams || $attrs['auto-load']" :auto-load="hasParams || $attrs['auto-load']"
@ -591,10 +680,11 @@ const checkbox = ref(null);
:style="isTableMode && `max-height: ${tableHeight}`" :style="isTableMode && `max-height: ${tableHeight}`"
:virtual-scroll="isTableMode" :virtual-scroll="isTableMode"
@virtual-scroll="handleScroll" @virtual-scroll="handleScroll"
@row-click="(_, row) => rowClickFunction && rowClickFunction(row)" @row-click="(event, row) => handleRowClick(event, row)"
@update:selected="emit('update:selected', $event)" @update:selected="emit('update:selected', $event)"
@selection="(details) => handleSelection(details, rows)" @selection="(details) => handleSelection(details, rows)"
:hide-selected-banner="true" :hide-selected-banner="true"
:data-cy
> >
<template #top-left v-if="!$props.withoutHeader"> <template #top-left v-if="!$props.withoutHeader">
<slot name="top-left"> </slot> <slot name="top-left"> </slot>
@ -608,35 +698,28 @@ const checkbox = ref(null);
:skip="columnsVisibilitySkipped" :skip="columnsVisibilitySkipped"
/> />
<QBtnToggle <QBtnToggle
v-if="!tableModes.some((mode) => mode.disable)"
v-model="mode" v-model="mode"
toggle-color="primary" toggle-color="primary"
class="bg-vn-section-color" class="bg-vn-section-color"
dense dense
:options="tableModes.filter((mode) => !mode.disable)" :options="tableModes.filter((mode) => !mode.disable)"
/> />
<QBtn
v-if="showRightIcon"
icon="filter_alt"
class="bg-vn-section-color q-ml-sm"
dense
@click="stateStore.toggleRightDrawer()"
/>
</template> </template>
<template #header-cell="{ col }"> <template #header-cell="{ col }">
<QTh <QTh
v-if="col.visible ?? true" v-if="col.visible ?? true"
v-bind:class="col.headerClass"
class="body-cell" class="body-cell"
:style="col?.width ? `max-width: ${col?.width}` : ''" :style="col?.width ? `max-width: ${col?.width}` : ''"
style="padding: inherit"
> >
<div <div
class="no-padding" class="no-padding"
:style=" :style="[
withFilters && $props.columnSearch ? 'height: 75px' : '' withFilters && $props.columnSearch ? 'height: 75px' : '',
" ]"
> >
<div class="text-center" style="height: 30px"> <div style="height: 30px">
<QTooltip v-if="col.toolTip">{{ col.toolTip }}</QTooltip> <QTooltip v-if="col.toolTip">{{ col.toolTip }}</QTooltip>
<VnTableOrder <VnTableOrder
v-model="orders[col.orderBy ?? col.name]" v-model="orders[col.orderBy ?? col.name]"
@ -644,6 +727,7 @@ const checkbox = ref(null);
:label="col?.labelAbbreviation ?? col?.label" :label="col?.labelAbbreviation ?? col?.label"
:data-key="$attrs['data-key']" :data-key="$attrs['data-key']"
:search-url="searchUrl" :search-url="searchUrl"
:align="getColAlign(col)"
/> />
</div> </div>
<VnFilter <VnFilter
@ -691,12 +775,13 @@ const checkbox = ref(null);
:data-col-field="col?.name" :data-col-field="col?.name"
> >
<div <div
class="no-padding no-margin peter" class="no-padding no-margin"
style=" style="
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
" "
:data-cy="`vnTableCell_${col.name}`"
> >
<slot <slot
:name="`column-${col.name}`" :name="`column-${col.name}`"
@ -725,7 +810,11 @@ const checkbox = ref(null);
<span <span
v-else v-else
:class="hasEditableFormat(col)" :class="hasEditableFormat(col)"
:style="col?.style ? col.style(row) : null" :style="
typeof col?.style == 'function'
? col.style(row)
: col?.style
"
style="bottom: 0" style="bottom: 0"
> >
{{ formatColumnValue(col, row, dashIfEmpty) }} {{ formatColumnValue(col, row, dashIfEmpty) }}
@ -752,7 +841,7 @@ const checkbox = ref(null);
flat flat
dense dense
:class=" :class="
btn.isPrimary ? 'text-primary-light' : 'color-vn-text ' btn.isPrimary ? 'text-primary-light' : 'color-vn-label'
" "
:style="`visibility: ${ :style="`visibility: ${
((btn.show && btn.show(row)) ?? true) ((btn.show && btn.show(row)) ?? true)
@ -760,23 +849,19 @@ const checkbox = ref(null);
: 'hidden' : 'hidden'
}`" }`"
@click="btn.action(row)" @click="btn.action(row)"
:data-cy="btn?.name ?? `tableAction-${index}`"
/> />
</QTd> </QTd>
</template> </template>
<template #item="{ row, colsMap }"> <template #item="{ row, colsMap }">
<component <component
:is="$props.redirect ? 'router-link' : 'span'" v-bind:is="'div'"
:to="`/${$props.redirect}/` + row.id" @click="(event) => cardClick(event, row)"
> >
<QCard <QCard
bordered bordered
flat flat
class="row no-wrap justify-between cursor-pointer q-pa-sm" class="row no-wrap justify-between cursor-pointer q-pa-sm"
@click="
(_, row) => {
$props.rowClick && $props.rowClick(row);
}
"
style="height: 100%" style="height: 100%"
> >
<QCardSection <QCardSection
@ -813,7 +898,7 @@ const checkbox = ref(null);
</QCardSection> </QCardSection>
<!-- Fields --> <!-- Fields -->
<QCardSection <QCardSection
class="q-pl-sm q-pr-lg q-py-xs" class="q-pl-sm q-py-xs"
:class="$props.cardClass" :class="$props.cardClass"
> >
<div <div
@ -835,12 +920,24 @@ const checkbox = ref(null);
:row-index="index" :row-index="index"
> >
<VnColumn <VnColumn
:column="col" :column="{
...col,
disable:
col?.component ===
'checkbox'
? true
: false,
}"
:row="row" :row="row"
:is-editable="false" :is-editable="false"
v-model="row[col.name]" v-model="row[col.name]"
component-prop="columnField" component-prop="columnField"
:show-label="true" :show-label="
col?.component ===
'checkbox'
? false
: true
"
/> />
</slot> </slot>
</span> </span>
@ -860,13 +957,14 @@ const checkbox = ref(null);
:key="index" :key="index"
:title="btn.title" :title="btn.title"
:icon="btn.icon" :icon="btn.icon"
data-cy="cardBtn"
class="q-pa-xs" class="q-pa-xs"
flat
:class=" :class="
btn.isPrimary btn.isPrimary
? 'text-primary-light' ? 'text-primary-light'
: 'color-vn-text ' : 'color-vn-label'
" "
flat
@click="btn.action(row)" @click="btn.action(row)"
/> />
</QCardSection> </QCardSection>
@ -880,6 +978,8 @@ const checkbox = ref(null);
v-for="col of cols.filter((cols) => cols.visible ?? true)" v-for="col of cols.filter((cols) => cols.visible ?? true)"
:key="col?.id" :key="col?.id"
:class="getColAlign(col)" :class="getColAlign(col)"
:style="col?.width ? `max-width: ${col?.width}` : ''"
style="font-size: small"
> >
<slot <slot
:name="`column-footer-${col.name}`" :name="`column-footer-${col.name}`"
@ -933,14 +1033,6 @@ const checkbox = ref(null);
transition-show="scale" transition-show="scale"
transition-hide="scale" transition-hide="scale"
:full-width="createComplement?.isFullWidth ?? false" :full-width="createComplement?.isFullWidth ?? false"
@before-hide="
() => {
if (createRef.isSaveAndContinue) {
showForm = true;
createForm.formInitialData = { ...create.formInitialData };
}
}
"
data-cy="vn-table-create-dialog" data-cy="vn-table-create-dialog"
> >
<FormModelPopup <FormModelPopup
@ -950,32 +1042,43 @@ const checkbox = ref(null);
@on-data-saved="(_, res) => createForm.onDataSaved(res)" @on-data-saved="(_, res) => createForm.onDataSaved(res)"
> >
<template #form-inputs="{ data }"> <template #form-inputs="{ data }">
<div :style="createComplement?.containerStyle"> <slot name="alter-create" :data="data">
<div> <div :style="createComplement?.containerStyle">
<slot name="previous-create-dialog" :data="data" /> <div
</div> :style="createComplement?.previousStyle"
<div class="grid-create" :style="createComplement?.columnGridStyle"> v-if="!quasar.screen.xs"
<slot
v-for="column of splittedColumns.create"
:key="column.name"
:name="`column-create-${column.name}`"
:data="data"
:column-name="column.name"
:label="column.label"
> >
<VnColumn <slot name="previous-create-dialog" :data="data" />
:column="column" </div>
:row="{}" <div
default="input" class="grid-create"
v-model="data[column.name]" :style="createComplement?.columnGridStyle"
:show-label="true" >
component-prop="columnCreate" <slot
:data-cy="`${column.name}-create-popup`" v-for="column of splittedColumns.create"
/> :key="column.name"
</slot> :name="`column-create-${column.name}`"
<slot name="more-create-dialog" :data="data" /> :data="data"
:column-name="column.name"
:label="column.label"
>
<VnColumn
:column="{
...column,
...column?.createAttrs,
}"
:row="{}"
default="input"
v-model="data[column.name]"
:show-label="true"
component-prop="columnCreate"
:data-cy="`${column.name}-create-popup`"
/>
</slot>
<slot name="more-create-dialog" :data="data" />
</div>
</div> </div>
</div> </slot>
</template> </template>
</FormModelPopup> </FormModelPopup>
</QDialog> </QDialog>
@ -1024,8 +1127,8 @@ es:
} }
.body-cell { .body-cell {
padding-left: 2px !important; padding-left: 4px !important;
padding-right: 2px !important; padding-right: 4px !important;
position: relative; position: relative;
} }
.bg-chip-secondary { .bg-chip-secondary {
@ -1045,16 +1148,20 @@ es:
.grid-three { .grid-three {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, max-content)); grid-template-columns: repeat(auto-fit, minmax(300px, max-content));
max-width: 100%; width: 100%;
grid-gap: 20px; grid-gap: 20px;
margin: 0 auto; margin: 0 auto;
} }
.grid-create { .grid-create {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, max-content)); grid-template-columns: 1fr 1fr;
max-width: 100%;
grid-gap: 20px; grid-gap: 20px;
margin: 0 auto; margin: 0 auto;
.col-span-2 {
grid-column: span 2;
}
} }
.flex-one { .flex-one {
@ -1119,6 +1226,7 @@ es:
.vn-label-value { .vn-label-value {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
align-items: center;
color: var(--vn-text-color); color: var(--vn-text-color);
.value { .value {
overflow: hidden; overflow: hidden;

View File

@ -27,30 +27,58 @@ describe('VnTable', () => {
beforeEach(() => (vm.selected = [])); beforeEach(() => (vm.selected = []));
describe('handleSelection()', () => { describe('handleSelection()', () => {
const rows = [{ $index: 0 }, { $index: 1 }, { $index: 2 }]; const rows = [
const selectedRows = [{ $index: 1 }]; { $index: 0 },
it('should add rows to selected when shift key is pressed and rows are added except last one', () => { { $index: 1 },
{ $index: 2 },
{ $index: 3 },
{ $index: 4 },
];
it('should add rows to selected when shift key is pressed and rows are added in ascending order', () => {
const selectedRows = [{ $index: 1 }];
vm.handleSelection( vm.handleSelection(
{ evt: { shiftKey: true }, added: true, rows: selectedRows }, { evt: { shiftKey: true }, added: true, rows: selectedRows },
rows rows,
); );
expect(vm.selected).toEqual([{ $index: 0 }]); expect(vm.selected).toEqual([{ $index: 0 }]);
}); });
it('should add rows to selected when shift key is pressed and rows are added in descending order', () => {
const selectedRows = [{ $index: 3 }];
vm.handleSelection(
{ evt: { shiftKey: true }, added: true, rows: selectedRows },
rows,
);
expect(vm.selected).toEqual([{ $index: 0 }, { $index: 1 }, { $index: 2 }]);
});
it('should not add rows to selected when shift key is not pressed', () => { it('should not add rows to selected when shift key is not pressed', () => {
const selectedRows = [{ $index: 1 }];
vm.handleSelection( vm.handleSelection(
{ evt: { shiftKey: false }, added: true, rows: selectedRows }, { evt: { shiftKey: false }, added: true, rows: selectedRows },
rows rows,
); );
expect(vm.selected).toEqual([]); expect(vm.selected).toEqual([]);
}); });
it('should not add rows to selected when rows are not added', () => { it('should not add rows to selected when rows are not added', () => {
const selectedRows = [{ $index: 1 }];
vm.handleSelection( vm.handleSelection(
{ evt: { shiftKey: true }, added: false, rows: selectedRows }, { evt: { shiftKey: true }, added: false, rows: selectedRows },
rows rows,
); );
expect(vm.selected).toEqual([]); expect(vm.selected).toEqual([]);
}); });
it('should add all rows between the smallest and largest selected indexes', () => {
vm.selected = [{ $index: 1 }, { $index: 3 }];
const selectedRows = [{ $index: 4 }];
vm.handleSelection(
{ evt: { shiftKey: true }, added: true, rows: selectedRows },
rows,
);
expect(vm.selected).toEqual([{ $index: 1 }, { $index: 3 }, { $index: 2 }]);
});
}); });
}); });

View File

@ -30,8 +30,8 @@ describe('CrudModel', () => {
saveFn: '', saveFn: '',
}, },
}); });
wrapper=wrapper.wrapper; wrapper = wrapper.wrapper;
vm=wrapper.vm; vm = wrapper.vm;
}); });
beforeEach(() => { beforeEach(() => {
@ -143,14 +143,14 @@ describe('CrudModel', () => {
}); });
it('should return true if object is empty', async () => { it('should return true if object is empty', async () => {
dummyObj ={}; dummyObj = {};
result = vm.isEmpty(dummyObj); result = vm.isEmpty(dummyObj);
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('should return false if object is not empty', async () => { it('should return false if object is not empty', async () => {
dummyObj = {a:1, b:2, c:3}; dummyObj = { a: 1, b: 2, c: 3 };
result = vm.isEmpty(dummyObj); result = vm.isEmpty(dummyObj);
expect(result).toBe(false); expect(result).toBe(false);
@ -158,29 +158,31 @@ describe('CrudModel', () => {
it('should return true if array is empty', async () => { it('should return true if array is empty', async () => {
dummyArray = []; dummyArray = [];
result = vm.isEmpty(dummyArray); result = vm.isEmpty(dummyArray);
expect(result).toBe(true); expect(result).toBe(true);
}); });
it('should return false if array is not empty', async () => { it('should return false if array is not empty', async () => {
dummyArray = [1,2,3]; dummyArray = [1, 2, 3];
result = vm.isEmpty(dummyArray); result = vm.isEmpty(dummyArray);
expect(result).toBe(false); expect(result).toBe(false);
}) });
}); });
describe('resetData()', () => { describe('resetData()', () => {
it('should add $index to elements in data[] and sets originalData and formData with data', async () => { it('should add $index to elements in data[] and sets originalData and formData with data', async () => {
data = [{ data = [
name: 'Tony', {
lastName: 'Stark', name: 'Tony',
age: 42, lastName: 'Stark',
}]; age: 42,
},
];
vm.resetData(data); vm.resetData(data);
expect(vm.originalData).toEqual(data); expect(vm.originalData).toEqual(data);
expect(vm.originalData[0].$index).toEqual(0); expect(vm.originalData[0].$index).toEqual(0);
expect(vm.formData).toEqual(data); expect(vm.formData).toEqual(data);
@ -200,7 +202,7 @@ describe('CrudModel', () => {
lastName: 'Stark', lastName: 'Stark',
age: 42, age: 42,
}; };
vm.resetData(data); vm.resetData(data);
expect(vm.originalData).toEqual(data); expect(vm.originalData).toEqual(data);
@ -210,17 +212,19 @@ describe('CrudModel', () => {
}); });
describe('saveChanges()', () => { describe('saveChanges()', () => {
data = [{ data = [
name: 'Tony', {
lastName: 'Stark', name: 'Tony',
age: 42, lastName: 'Stark',
}]; age: 42,
},
];
it('should call saveFn if exists', async () => { it('should call saveFn if exists', async () => {
await wrapper.setProps({ saveFn: vi.fn() }); await wrapper.setProps({ saveFn: vi.fn() });
vm.saveChanges(data); vm.saveChanges(data);
expect(vm.saveFn).toHaveBeenCalledOnce(); expect(vm.saveFn).toHaveBeenCalledOnce();
expect(vm.isLoading).toBe(false); expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false); expect(vm.hasChanges).toBe(false);
@ -229,13 +233,15 @@ describe('CrudModel', () => {
}); });
it("should use default url if there's not saveFn", async () => { it("should use default url if there's not saveFn", async () => {
const postMock =vi.spyOn(axios, 'post'); const postMock = vi.spyOn(axios, 'post');
vm.formData = [{ vm.formData = [
name: 'Bruce', {
lastName: 'Wayne', name: 'Bruce',
age: 45, lastName: 'Wayne',
}] age: 45,
},
];
await vm.saveChanges(data); await vm.saveChanges(data);

View File

@ -57,6 +57,7 @@ describe('FormModel', () => {
vm.state.set(model, formInitialData); vm.state.set(model, formInitialData);
expect(vm.hasChanges).toBe(false); expect(vm.hasChanges).toBe(false);
await vm.$nextTick();
vm.formData.mockKey = 'newVal'; vm.formData.mockKey = 'newVal';
await vm.$nextTick(); await vm.$nextTick();
expect(vm.hasChanges).toBe(true); expect(vm.hasChanges).toBe(true);
@ -94,8 +95,12 @@ describe('FormModel', () => {
it('should call axios.patch with the right data', async () => { it('should call axios.patch with the right data', async () => {
const spy = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} }); const spy = vi.spyOn(axios, 'patch').mockResolvedValue({ data: {} });
const { vm } = mount({ propsData: { url, model } }); const { vm } = mount({ propsData: { url, model } });
vm.formData.mockKey = 'newVal';
vm.formData = {};
await vm.$nextTick(); await vm.$nextTick();
vm.formData = { mockKey: 'newVal' };
await vm.$nextTick();
await vm.save(); await vm.save();
expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalled();
vm.formData.mockKey = 'mockVal'; vm.formData.mockKey = 'mockVal';

View File

@ -15,10 +15,7 @@ vi.mock('src/router/modules', () => ({
meta: { meta: {
title: 'customers', title: 'customers',
icon: 'vn:client', icon: 'vn:client',
}, menu: ['CustomerList', 'CustomerCreate'],
menus: {
main: ['CustomerList', 'CustomerCreate'],
card: ['CustomerBasicData'],
}, },
children: [ children: [
{ {
@ -50,14 +47,6 @@ vi.mock('src/router/modules', () => ({
], ],
}, },
}, },
{
path: 'create',
name: 'CustomerCreate',
meta: {
title: 'createCustomer',
icon: 'vn:addperson',
},
},
], ],
}, },
], ],
@ -98,7 +87,7 @@ vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
icon: 'vn:client', icon: 'vn:client',
moduleName: 'Customer', moduleName: 'Customer',
keyBinding: 'c', keyBinding: 'c',
menu: 'customer', menu: ['customer'],
}, },
}, },
], ],
@ -260,15 +249,6 @@ describe('Leftmenu as main', () => {
}); });
}); });
it('should handle a single matched route with a menu', () => {
const route = {
matched: [{ meta: { menu: 'customer' } }],
};
const result = vm.betaGetRoutes();
expect(result.meta.menu).toEqual(route.matched[0].meta.menu);
});
it('should get routes for main source', () => { it('should get routes for main source', () => {
vm.props.source = 'main'; vm.props.source = 'main';
vm.getRoutes(); vm.getRoutes();
@ -351,8 +331,9 @@ describe('addChildren', () => {
it('should handle routes with no meta menu', () => { it('should handle routes with no meta menu', () => {
const route = { const route = {
meta: {}, meta: {
menus: {}, menu: [],
},
}; };
const parent = []; const parent = [];

View File

@ -11,6 +11,13 @@ const stateStore = useStateStore();
const slots = useSlots(); const slots = useSlots();
const hasContent = useHasContent('#right-panel'); const hasContent = useHasContent('#right-panel');
defineProps({
overlay: {
type: Boolean,
default: false,
},
});
onMounted(() => { onMounted(() => {
if ((!slots['right-panel'] && !hasContent.value) || quasar.platform.is.mobile) if ((!slots['right-panel'] && !hasContent.value) || quasar.platform.is.mobile)
stateStore.rightDrawer = false; stateStore.rightDrawer = false;
@ -34,7 +41,12 @@ onMounted(() => {
</QBtn> </QBtn>
</div> </div>
</Teleport> </Teleport>
<QDrawer v-model="stateStore.rightDrawer" side="right" :width="256"> <QDrawer
v-model="stateStore.rightDrawer"
side="right"
:width="256"
:overlay="overlay"
>
<QScrollArea class="fit"> <QScrollArea class="fit">
<div id="right-panel"></div> <div id="right-panel"></div>
<slot v-if="!hasContent" name="right-panel" /> <slot v-if="!hasContent" name="right-panel" />

View File

@ -56,7 +56,12 @@ async function confirm() {
{{ t('The notification will be sent to the following address') }} {{ t('The notification will be sent to the following address') }}
</QCardSection> </QCardSection>
<QCardSection class="q-pt-none"> <QCardSection class="q-pt-none">
<VnInput v-model="address" is-outlined autofocus /> <VnInput
v-model="address"
is-outlined
autofocus
data-cy="SendEmailNotifiactionDialogInput"
/>
</QCardSection> </QCardSection>
<QCardActions align="right"> <QCardActions align="right">
<QBtn :label="t('globals.cancel')" color="primary" flat v-close-popup /> <QBtn :label="t('globals.cancel')" color="primary" flat v-close-popup />

View File

@ -1,12 +1,9 @@
<script setup> <script setup>
import { nextTick, ref, watch } from 'vue'; import { nextTick, ref } from 'vue';
import { QInput } from 'quasar'; import VnInput from './VnInput.vue';
import { useAccountShortToStandard } from 'src/composables/useAccountShortToStandard';
const $props = defineProps({ const $props = defineProps({
modelValue: {
type: String,
default: '',
},
insertable: { insertable: {
type: Boolean, type: Boolean,
default: false, default: false,
@ -14,70 +11,25 @@ const $props = defineProps({
}); });
const emit = defineEmits(['update:modelValue', 'accountShortToStandard']); const emit = defineEmits(['update:modelValue', 'accountShortToStandard']);
const model = defineModel({ prop: 'modelValue' });
const inputRef = ref(false);
let internalValue = ref($props.modelValue); function setCursorPosition(pos) {
const input = inputRef.value.vnInputRef.$el.querySelector('input');
watch( input.focus();
() => $props.modelValue, input.setSelectionRange(pos, pos);
(newVal) => {
internalValue.value = newVal;
}
);
watch(
() => internalValue.value,
(newVal) => {
emit('update:modelValue', newVal);
accountShortToStandard();
}
);
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) => { async function handleUpdateModel(val) {
e.preventDefault(); model.value = val?.at(-1) === '.' ? useAccountShortToStandard(val) : val;
const input = e.target; await nextTick(() => setCursorPosition(0));
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() {
internalValue.value = internalValue.value?.replace(
'.',
'0'.repeat(11 - internalValue.value.length)
);
} }
</script> </script>
<template> <template>
<QInput @keydown="handleKeydown" ref="vnInputRef" v-model="internalValue" /> <VnInput
v-model="model"
ref="inputRef"
:insertable
@update:model-value="handleUpdateModel"
/>
</template> </template>

View File

@ -1,50 +1,56 @@
<script setup> <script setup>
import { onBeforeMount, computed } from 'vue'; import { onBeforeMount } from 'vue';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'; import { useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } 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';
import VnSubToolbar from '../ui/VnSubToolbar.vue'; import VnSubToolbar from '../ui/VnSubToolbar.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import LeftMenu from 'components/LeftMenu.vue';
import RightMenu from 'components/common/RightMenu.vue';
const props = defineProps({ const props = defineProps({
dataKey: { type: String, required: true }, dataKey: { type: String, required: true },
url: { type: String, default: undefined }, url: { type: String, default: undefined },
idInWhere: { type: Boolean, default: false },
filter: { type: Object, default: () => {} }, filter: { type: Object, default: () => {} },
descriptor: { type: Object, required: true }, descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined }, filterPanel: { type: Object, default: undefined },
idInWhere: { type: Boolean, default: false },
searchDataKey: { type: String, default: undefined }, searchDataKey: { type: String, default: undefined },
searchbarProps: { type: Object, default: undefined }, searchbarProps: { type: Object, default: undefined },
redirectOnError: { type: Boolean, default: false }, redirectOnError: { type: Boolean, default: false },
}); });
const stateStore = useStateStore(); const stateStore = useStateStore();
const route = useRoute();
const router = useRouter(); const router = useRouter();
const searchRightDataKey = computed(() => {
if (!props.searchDataKey) return route.name;
return props.searchDataKey;
});
const arrayData = useArrayData(props.dataKey, { const arrayData = useArrayData(props.dataKey, {
url: props.url, url: props.url,
userFilter: props.filter, userFilter: props.filter,
oneRecord: true, oneRecord: true,
}); });
onBeforeRouteLeave(() => {
stateStore.cardDescriptorChangeValue(null);
});
onBeforeMount(async () => { onBeforeMount(async () => {
stateStore.cardDescriptorChangeValue(props.descriptor);
const route = router.currentRoute.value;
try { try {
await fetch(route.params.id); await fetch(route.params.id);
} catch { } catch {
const { matched: matches } = router.currentRoute.value; const { matched: matches } = route;
const { path } = matches.at(-1); const { path } = matches.at(-1);
router.push({ path: path.replace(/:id.*/, '') }); router.push({ path: path.replace(/:id.*/, '') });
} }
}); });
onBeforeRouteUpdate(async (to, from) => { onBeforeRouteUpdate(async (to, from) => {
if (hasRouteParam(to.params)) {
const { matched } = router.currentRoute.value;
const { name } = matched.at(-3);
if (name) {
router.push({ name, params: to.params });
}
}
const id = to.params.id; const id = to.params.id;
if (id !== from.params.id) await fetch(id, true); if (id !== from.params.id) await fetch(id, true);
}); });
@ -56,34 +62,13 @@ async function fetch(id, append = false) {
else arrayData.store.url = props.url.replace(regex, `/${id}`); else arrayData.store.url = props.url.replace(regex, `/${id}`);
await arrayData.fetch({ append, updateRouter: false }); await arrayData.fetch({ append, updateRouter: false });
} }
function hasRouteParam(params, valueToCheck = ':addressId') {
return Object.values(params).includes(valueToCheck);
}
</script> </script>
<template> <template>
<QDrawer <VnSubToolbar />
v-model="stateStore.leftDrawer" <div :class="[useCardSize(), $attrs.class]">
show-if-above <RouterView :key="$route.path" />
:width="256" </div>
v-if="stateStore.isHeaderMounted()"
>
<QScrollArea class="fit">
<component :is="descriptor" />
<QSeparator />
<LeftMenu source="card" />
</QScrollArea>
</QDrawer>
<slot name="searchbar" v-if="props.searchDataKey">
<VnSearchbar :data-key="props.searchDataKey" v-bind="props.searchbarProps" />
</slot>
<RightMenu>
<template #right-panel v-if="props.filterPanel">
<component :is="props.filterPanel" :data-key="searchRightDataKey" />
</template>
</RightMenu>
<QPageContainer>
<QPage>
<VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]">
<RouterView :key="$route.path" />
</div>
</QPage>
</QPageContainer>
</template> </template>

View File

@ -1,64 +0,0 @@
<script setup>
import { onBeforeMount } from 'vue';
import { useRouter, onBeforeRouteUpdate } from 'vue-router';
import { useArrayData } from 'src/composables/useArrayData';
import { useStateStore } from 'stores/useStateStore';
import useCardSize from 'src/composables/useCardSize';
import LeftMenu from 'components/LeftMenu.vue';
import VnSubToolbar from '../ui/VnSubToolbar.vue';
const props = defineProps({
dataKey: { type: String, required: true },
url: { type: String, default: undefined },
idInWhere: { type: Boolean, default: false },
filter: { type: Object, default: () => {} },
descriptor: { type: Object, required: true },
filterPanel: { type: Object, default: undefined },
searchDataKey: { type: String, default: undefined },
searchbarProps: { type: Object, default: undefined },
redirectOnError: { type: Boolean, default: false },
});
const stateStore = useStateStore();
const router = useRouter();
const arrayData = useArrayData(props.dataKey, {
url: props.url,
userFilter: props.filter,
oneRecord: true,
});
onBeforeMount(async () => {
const route = router.currentRoute.value;
try {
await fetch(route.params.id);
} catch {
const { matched: matches } = route;
const { path } = matches.at(-1);
router.push({ path: path.replace(/:id.*/, '') });
}
});
onBeforeRouteUpdate(async (to, from) => {
const id = to.params.id;
if (id !== from.params.id) await fetch(id, true);
});
async function fetch(id, append = false) {
const regex = /\/(\d+)/;
if (props.idInWhere) arrayData.store.filter.where = { id };
else if (!regex.test(props.url)) arrayData.store.url = `${props.url}/${id}`;
else arrayData.store.url = props.url.replace(regex, `/${id}`);
await arrayData.fetch({ append, updateRouter: false });
}
</script>
<template>
<Teleport to="#left-panel" v-if="stateStore.isHeaderMounted()">
<component :is="descriptor" />
<QSeparator />
<LeftMenu source="card" />
</Teleport>
<VnSubToolbar />
<div :class="[useCardSize(), $attrs.class]">
<RouterView :key="$route.path" />
</div>
</template>

View File

@ -27,7 +27,11 @@ const checkboxModel = computed({
</script> </script>
<template> <template>
<div> <div>
<QCheckbox v-bind="$attrs" v-on="$attrs" v-model="checkboxModel" /> <QCheckbox
v-bind="$attrs"
v-model="checkboxModel"
:data-cy="$attrs['data-cy'] ?? `vnCheckbox${$attrs['label'] ?? ''}`"
/>
<QIcon <QIcon
v-if="info" v-if="info"
v-bind="$attrs" v-bind="$attrs"

View File

@ -48,7 +48,8 @@ function toValueAttrs(attrs) {
<span <span
v-for="toComponent of componentArray" v-for="toComponent of componentArray"
:key="toComponent.name" :key="toComponent.name"
class="column flex-center fit" class="column fit"
:class="toComponent?.component == 'checkbox' ? 'flex-center' : ''"
> >
<component <component
v-if="toComponent?.component" v-if="toComponent?.component"

View File

@ -177,6 +177,7 @@ function addDefaultData(data) {
name="vn:attach" name="vn:attach"
class="cursor-pointer" class="cursor-pointer"
@click="inputFileRef.pickFiles()" @click="inputFileRef.pickFiles()"
data-cy="attachFile"
> >
<QTooltip>{{ t('globals.selectFile') }}</QTooltip> <QTooltip>{{ t('globals.selectFile') }}</QTooltip>
</QIcon> </QIcon>

View File

@ -389,10 +389,7 @@ defineExpose({
</div> </div>
</template> </template>
</QTable> </QTable>
<div <div v-else class="info-row q-pa-md text-center">
v-else
class="info-row q-pa-md text-center"
>
<h5> <h5>
{{ t('No data to display') }} {{ t('No data to display') }}
</h5> </h5>
@ -416,6 +413,7 @@ defineExpose({
v-shortcut v-shortcut
@click="showFormDialog()" @click="showFormDialog()"
class="fill-icon" class="fill-icon"
data-cy="addButton"
> >
<QTooltip> <QTooltip>
{{ t('Upload file') }} {{ t('Upload file') }}

View File

@ -83,7 +83,7 @@ const mixinRules = [
requiredFieldRule, requiredFieldRule,
...($attrs.rules ?? []), ...($attrs.rules ?? []),
(val) => { (val) => {
const { maxlength } = vnInputRef.value; const maxlength = $props.maxlength;
if (maxlength && +val.length > maxlength) if (maxlength && +val.length > maxlength)
return t(`maxLength`, { value: maxlength }); return t(`maxLength`, { value: maxlength });
const { min, max } = vnInputRef.value.$attrs; const { min, max } = vnInputRef.value.$attrs;
@ -108,7 +108,7 @@ const handleInsertMode = (e) => {
e.preventDefault(); e.preventDefault();
const input = e.target; const input = e.target;
const cursorPos = input.selectionStart; const cursorPos = input.selectionStart;
const { maxlength } = vnInputRef.value; const maxlength = $props.maxlength;
let currentValue = value.value; let currentValue = value.value;
if (!currentValue) currentValue = e.key; if (!currentValue) currentValue = e.key;
const newValue = e.key; const newValue = e.key;
@ -143,7 +143,7 @@ const handleUppercase = () => {
:rules="mixinRules" :rules="mixinRules"
:lazy-rules="true" :lazy-rules="true"
hide-bottom-space hide-bottom-space
:data-cy="$attrs.dataCy ?? $attrs.label + '_input'" :data-cy="($attrs['data-cy'] ?? $attrs.label) + '_input'"
> >
<template #prepend v-if="$slots.prepend"> <template #prepend v-if="$slots.prepend">
<slot name="prepend" /> <slot name="prepend" />

View File

@ -107,6 +107,7 @@ const manageDate = (date) => {
@click="isPopupOpen = !isPopupOpen" @click="isPopupOpen = !isPopupOpen"
@keydown="isPopupOpen = false" @keydown="isPopupOpen = false"
hide-bottom-space hide-bottom-space
:data-cy="($attrs['data-cy'] ?? $attrs.label) + '_inputDate'"
> >
<template #append> <template #append>
<QIcon <QIcon

View File

@ -85,6 +85,7 @@ const handleModelValue = (data) => {
:tooltip="t('Create new location')" :tooltip="t('Create new location')"
:rules="mixinRules" :rules="mixinRules"
:lazy-rules="true" :lazy-rules="true"
required
> >
<template #form> <template #form>
<CreateNewPostcode <CreateNewPostcode

View File

@ -10,7 +10,7 @@ import { useColor } from 'src/composables/useColor';
import { useCapitalize } from 'src/composables/useCapitalize'; import { useCapitalize } from 'src/composables/useCapitalize';
import { useValidator } from 'src/composables/useValidator'; import { useValidator } from 'src/composables/useValidator';
import VnAvatar from '../ui/VnAvatar.vue'; import VnAvatar from '../ui/VnAvatar.vue';
import VnJsonValue from '../common/VnJsonValue.vue'; import VnLogValue from './VnLogValue.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';
@ -560,10 +560,11 @@ watch(
value.nameI18n value.nameI18n
}}: }}:
</span> </span>
<VnJsonValue <VnLogValue
:value=" :value="
value.val.val value.val.val
" "
:name="value.name"
/> />
</QItem> </QItem>
</QCardSection> </QCardSection>
@ -614,7 +615,11 @@ watch(
> >
{{ prop.nameI18n }}: {{ prop.nameI18n }}:
</span> </span>
<VnJsonValue :value="prop.val.val" /> <VnLogValue
:value="prop.val.val"
:name="prop.name"
/>
<VnIconLink />
<span <span
v-if=" v-if="
propIndex < propIndex <
@ -641,17 +646,10 @@ watch(
> >
{{ prop.nameI18n }}: {{ prop.nameI18n }}:
</span> </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'"> <span v-if="log.action == 'update'">
<VnLogValue
<VnJsonValue
:value="prop.old.val" :value="prop.old.val"
:name="prop.name"
/> />
<span <span
v-if="prop.old.id" v-if="prop.old.id"
@ -659,6 +657,28 @@ watch(
> >
#{{ prop.old.id }} #{{ prop.old.id }}
</span> </span>
<VnLogValue
:value="prop.val.val"
:name="prop.name"
/>
<span
v-if="prop.val.id"
class="id-value"
>
#{{ prop.val.id }}
</span>
</span>
<span v-else="prop.old.val">
<VnLogValue
:value="prop.val.val"
:name="prop.name"
/>
<span
v-if="prop.old.id"
class="id-value"
>#{{ prop.old.id }}</span
>
</span> </span>
</div> </div>
</span> </span>

View File

@ -0,0 +1,22 @@
<script setup>
import { useDescriptorStore } from 'src/stores/useDescriptorStore';
import VnJsonValue from './VnJsonValue.vue';
import { computed } from 'vue';
const descriptorStore = useDescriptorStore();
const $props = defineProps({
name: { type: [String], default: undefined },
});
const descriptor = computed(() => descriptorStore.has($props.name));
</script>
<template>
<VnJsonValue v-bind="$attrs" />
<QIcon
name="launch"
class="link"
v-if="$attrs.value && descriptor"
:data-cy="'iconLaunch-' + $props.name"
/>
<component :is="descriptor" :id="$attrs.value" v-if="$attrs.value && descriptor" />
</template>

View File

@ -12,7 +12,7 @@ const $props = defineProps({
}, },
}); });
onMounted( onMounted(
() => (stateStore.leftDrawer = useQuasar().screen.gt.xs ? $props.leftDrawer : false) () => (stateStore.leftDrawer = useQuasar().screen.gt.xs ? $props.leftDrawer : false),
); );
const teleportRef = ref({}); const teleportRef = ref({});
@ -35,8 +35,14 @@ onMounted(() => {
<template> <template>
<QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256"> <QDrawer v-model="stateStore.leftDrawer" show-if-above :width="256">
<QScrollArea class="fit text-grey-8"> <QScrollArea class="fit text-grey-8">
<div id="left-panel" ref="teleportRef"></div> <div id="left-panel" ref="teleportRef">
<LeftMenu v-if="!hasContent" /> <template v-if="stateStore.cardDescriptor">
<component :is="stateStore.cardDescriptor" />
<QSeparator />
<LeftMenu source="card" />
</template>
<template v-else> <LeftMenu /></template>
</div>
</QScrollArea> </QScrollArea>
</QDrawer> </QDrawer>
<QPageContainer> <QPageContainer>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref, toRefs, computed, watch, onMounted, useAttrs } from 'vue'; import { ref, toRefs, computed, watch, onMounted, useAttrs, nextTick } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { useRequired } from 'src/composables/useRequired'; import { useRequired } from 'src/composables/useRequired';
@ -247,6 +247,7 @@ async function fetchFilter(val) {
} }
async function filterHandler(val, update) { async function filterHandler(val, update) {
if (isLoading.value) return update();
if (!val && lastVal.value === val) { if (!val && lastVal.value === val) {
lastVal.value = val; lastVal.value = val;
return update(); return update();
@ -294,6 +295,7 @@ async function onScroll({ to, direction, from, index }) {
await arrayData.loadMore(); await arrayData.loadMore();
setOptions(arrayData.store.data); setOptions(arrayData.store.data);
vnSelectRef.value.scrollTo(lastIndex); vnSelectRef.value.scrollTo(lastIndex);
await nextTick();
isLoading.value = false; isLoading.value = false;
} }
} }

View File

@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest';
import VnLogValue from 'src/components/common/VnLogValue.vue';
import { createWrapper } from 'app/test/vitest/helper';
const buildComponent = (props) => {
return createWrapper(VnLogValue, {
props,
global: {},
}).wrapper;
};
describe('VnLogValue', () => {
const id = 1;
it('renders without descriptor', async () => {
expect(getIcon('inventFk').exists()).toBe(false);
});
it('renders with descriptor', async () => {
expect(getIcon('claimFk').text()).toBe('launch');
});
function getIcon(name) {
const wrapper = buildComponent({ value: { val: id }, name });
return wrapper.find('.q-icon');
}
});

View File

@ -5,7 +5,7 @@ import SkeletonDescriptor from 'components/ui/SkeletonDescriptor.vue';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useState } from 'src/composables/useState'; import { useState } from 'src/composables/useState';
import { useRoute } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import { useClipboard } from 'src/composables/useClipboard'; import { useClipboard } from 'src/composables/useClipboard';
import VnMoreOptions from './VnMoreOptions.vue'; import VnMoreOptions from './VnMoreOptions.vue';
@ -38,10 +38,15 @@ const $props = defineProps({
type: String, type: String,
default: 'md-width', default: 'md-width',
}, },
toModule: {
type: String,
default: null,
},
}); });
const state = useState(); const state = useState();
const route = useRoute(); const route = useRoute();
const router = useRouter();
const { t } = useI18n(); const { t } = useI18n();
const { copyText } = useClipboard(); const { copyText } = useClipboard();
const { viewSummary } = useSummaryDialog(); const { viewSummary } = useSummaryDialog();
@ -50,6 +55,9 @@ let store;
let entity; let entity;
const isLoading = ref(false); const isLoading = ref(false);
const isSameDataKey = computed(() => $props.dataKey === route.meta.moduleName); const isSameDataKey = computed(() => $props.dataKey === route.meta.moduleName);
const DESCRIPTOR_PROXY = 'DescriptorProxy';
const moduleName = ref();
const isSameModuleName = route.matched[1].meta.moduleName !== moduleName.value;
defineExpose({ getData }); defineExpose({ getData });
onBeforeMount(async () => { onBeforeMount(async () => {
@ -76,6 +84,18 @@ onBeforeMount(async () => {
); );
}); });
function getName() {
let name = $props.dataKey;
if ($props.dataKey.includes(DESCRIPTOR_PROXY)) {
name = name.split(DESCRIPTOR_PROXY)[0];
}
return name;
}
const routeName = computed(() => {
let routeName = getName();
return `${routeName}Summary`;
});
async function getData() { async function getData() {
store.url = $props.url; store.url = $props.url;
store.filter = $props.filter ?? {}; store.filter = $props.filter ?? {};
@ -111,20 +131,39 @@ function copyIdText(id) {
const emit = defineEmits(['onFetch']); const emit = defineEmits(['onFetch']);
const iconModule = computed(() => route.matched[1].meta.icon); const iconModule = computed(() => {
const toModule = computed(() => moduleName.value = getName();
route.matched[1].path.split('/').length > 2 if ($props.toModule) {
? route.matched[1].redirect return router.getRoutes().find((r) => r.name === $props.toModule.name).meta.icon;
: route.matched[1].children[0].redirect, }
); if (isSameModuleName) {
return router.options.routes[1].children.find((r) => r.name === moduleName.value)
?.meta?.icon;
} else {
return route.matched[1].meta.icon;
}
});
const toModule = computed(() => {
moduleName.value = getName();
if ($props.toModule) return $props.toModule;
if (isSameModuleName) {
return router.options.routes[1].children.find((r) => r.name === moduleName.value)
?.redirect;
} else {
return 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" data-cy="cardDescriptor">
<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 <QBtn
round round
flat flat
dense dense
@ -132,13 +171,13 @@ const toModule = computed(() =>
:icon="iconModule" :icon="iconModule"
color="white" color="white"
class="link" class="link"
:to="$attrs['to-module'] ?? toModule" :to="toModule"
> >
<QTooltip> <QTooltip>
{{ t('globals.goToModuleIndex') }} {{ t('globals.goToModuleIndex') }}
</QTooltip> </QTooltip>
</QBtn></slot </QBtn>
> </slot>
<QBtn <QBtn
@click.stop="viewSummary(entity.id, $props.summary, $props.width)" @click.stop="viewSummary(entity.id, $props.summary, $props.width)"
round round
@ -149,14 +188,13 @@ const toModule = computed(() =>
color="white" color="white"
class="link" class="link"
v-if="summary" v-if="summary"
data-cy="openSummaryBtn"
> >
<QTooltip> <QTooltip>
{{ t('components.smartCard.openSummary') }} {{ t('components.smartCard.openSummary') }}
</QTooltip> </QTooltip>
</QBtn> </QBtn>
<RouterLink <RouterLink :to="{ name: routeName, params: { id: entity.id } }">
:to="{ name: `${dataKey}Summary`, params: { id: entity.id } }"
>
<QBtn <QBtn
class="link" class="link"
color="white" color="white"
@ -165,6 +203,7 @@ const toModule = computed(() =>
icon="launch" icon="launch"
round round
size="md" size="md"
data-cy="goToSummaryBtn"
> >
<QTooltip> <QTooltip>
{{ t('components.cardDescriptor.summary') }} {{ t('components.cardDescriptor.summary') }}
@ -182,48 +221,59 @@ 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="getValueFromPath(title)"
:data-cy="`${$attrs['data-cy'] ?? 'cardDescriptor'}_title`"
>
{{ getValueFromPath(title) ?? $props.title }} {{ getValueFromPath(title) ?? $props.title }}
</span> </span>
<slot v-else name="description" :entity="entity"> <slot v-else name="description" :entity="entity">
<span :title="entity.name"> <span
{{ entity.name }} :title="entity.name"
</span> :data-cy="`${$attrs['data-cy'] ?? 'cardDescriptor'}_description`"
v-text="entity.name"
/>
</slot> </slot>
</div> </div>
</QItemLabel> </QItemLabel>
<QItem> <QItem>
<QItemLabel class="subtitle" caption> <QItemLabel
class="subtitle"
:data-cy="`${$attrs['data-cy'] ?? 'cardDescriptor'}_subtitle`"
>
#{{ getValueFromPath(subtitle) ?? entity.id }} #{{ getValueFromPath(subtitle) ?? entity.id }}
<QBtn
round
flat
dense
size="sm"
icon="content_copy"
color="primary"
@click.stop="copyIdText(entity.id)"
>
<QTooltip>
{{ t('globals.copyId') }}
</QTooltip>
</QBtn>
</QItemLabel> </QItemLabel>
<QBtn
round
flat
dense
size="sm"
icon="content_copy"
color="primary"
@click.stop="copyIdText(entity.id)"
>
<QTooltip>
{{ t('globals.copyId') }}
</QTooltip>
</QBtn>
</QItem> </QItem>
</QList> </QList>
<div class="list-box q-mt-xs"> <div
class="list-box q-mt-xs"
:data-cy="`${$attrs['data-cy'] ?? 'cardDescriptor'}_listbox`"
>
<slot name="body" :entity="entity" /> <slot name="body" :entity="entity" />
</div> </div>
</div> </div>
<div class="icons"> <div class="icons">
<slot name="icons" :entity="entity" /> <slot name="icons" :entity="entity" />
</div> </div>
<div class="actions justify-center"> <div class="actions justify-center" data-cy="descriptor_actions">
<slot name="actions" :entity="entity" /> <slot name="actions" :entity="entity" />
</div> </div>
<slot name="after" /> <slot name="after" />
</template> </template>
<!-- Skeleton -->
<SkeletonDescriptor v-if="!entity || isLoading" /> <SkeletonDescriptor v-if="!entity || isLoading" />
</div> </div>
<QInnerLoading <QInnerLoading

View File

@ -81,6 +81,7 @@ async function fetch() {
name: `${moduleName ?? route.meta.moduleName}Summary`, name: `${moduleName ?? route.meta.moduleName}Summary`,
params: { id: entityId || entity.id }, params: { id: entityId || entity.id },
}" }"
data-cy="goToSummaryBtn"
> >
<QIcon name="open_in_new" color="white" size="sm" /> <QIcon name="open_in_new" color="white" size="sm" />
</router-link> </router-link>

View File

@ -132,7 +132,8 @@ const card = toRef(props, 'item');
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 4px; gap: 4px;
white-space: nowrap;
width: 192px;
p { p {
margin-bottom: 0; margin-bottom: 0;
} }

View File

@ -54,7 +54,7 @@ const $props = defineProps({
default: 'table', default: 'table',
}, },
redirect: { redirect: {
type: Boolean, type: [String, Boolean],
default: true, default: true,
}, },
arrayData: { arrayData: {
@ -249,7 +249,7 @@ const getLocale = (label) => {
: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" :data-cy="`vnFilterPanelChip_${chip.label}`"
> >
<slot <slot
name="tags" name="tags"

View File

@ -28,7 +28,7 @@ function copyValueText() {
const val = computed(() => $props.value); const val = computed(() => $props.value);
</script> </script>
<template> <template>
<div class="vn-label-value"> <div class="vn-label-value" :data-cy="`${$attrs['data-cy'] ?? 'vnLv'}${label ?? ''}`">
<QCheckbox <QCheckbox
v-if="typeof value === 'boolean'" v-if="typeof value === 'boolean'"
v-model="val" v-model="val"

View File

@ -12,7 +12,7 @@
{{ $t('components.cardDescriptor.moreOptions') }} {{ $t('components.cardDescriptor.moreOptions') }}
</QTooltip> </QTooltip>
<QMenu ref="menuRef" data-cy="descriptor-more-opts-menu"> <QMenu ref="menuRef" data-cy="descriptor-more-opts-menu">
<QList> <QList data-cy="descriptor-more-opts_list">
<slot name="menu" :menu-ref="$refs.menuRef" /> <slot name="menu" :menu-ref="$refs.menuRef" />
</QList> </QList>
</QMenu> </QMenu>

View File

@ -18,20 +18,16 @@ import VnInput from 'components/common/VnInput.vue';
const emit = defineEmits(['onFetch']); const emit = defineEmits(['onFetch']);
const originalAttrs = useAttrs(); const $attrs = useAttrs();
const $attrs = computed(() => {
const { style, ...rest } = originalAttrs;
return rest;
});
const isRequired = computed(() => { const isRequired = computed(() => {
return Object.keys($attrs).includes('required') return Object.keys($attrs).includes('required');
}); });
const $props = defineProps({ const $props = defineProps({
url: { type: String, default: null }, url: { type: String, default: null },
saveUrl: {type: String, default: null}, saveUrl: { type: String, default: null },
userFilter: { type: Object, default: () => {} },
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 },
@ -65,7 +61,7 @@ async function insert() {
} }
function confirmAndUpdate() { function confirmAndUpdate() {
if(!newNote.text && originalText) if (!newNote.text && originalText)
quasar quasar
.dialog({ .dialog({
component: VnConfirm, component: VnConfirm,
@ -88,11 +84,17 @@ async function update() {
...body, ...body,
...{ notes: newNote.text }, ...{ notes: newNote.text },
}; };
await axios.patch(`${$props.saveUrl ?? `${$props.url}/${$props.body.workerFk}`}`, newBody); await axios.patch(
`${$props.saveUrl ?? `${$props.url}/${$props.body.workerFk}`}`,
newBody,
);
} }
onBeforeRouteLeave((to, from, next) => { onBeforeRouteLeave((to, from, next) => {
if ((newNote.text && !$props.justInput) || (newNote.text !== originalText) && $props.justInput) if (
(newNote.text && !$props.justInput) ||
(newNote.text !== originalText && $props.justInput)
)
quasar.dialog({ quasar.dialog({
component: VnConfirm, component: VnConfirm,
componentProps: { componentProps: {
@ -104,12 +106,11 @@ onBeforeRouteLeave((to, from, next) => {
else next(); else next();
}); });
function fetchData([ data ]) { function fetchData([data]) {
newNote.text = data?.notes; newNote.text = data?.notes;
originalText = data?.notes; originalText = data?.notes;
emit('onFetch', data); emit('onFetch', data);
} }
</script> </script>
<template> <template>
<FetchData <FetchData
@ -126,8 +127,8 @@ function fetchData([ data ]) {
@on-fetch="fetchData" @on-fetch="fetchData"
auto-load auto-load
/> />
<QCard <QCard
class="q-pa-xs q-mb-lg full-width" class="q-pa-xs q-mb-lg full-width"
:class="{ 'just-input': $props.justInput }" :class="{ 'just-input': $props.justInput }"
v-if="$props.addNote || $props.justInput" v-if="$props.addNote || $props.justInput"
> >
@ -179,12 +180,13 @@ function fetchData([ data ]) {
:url="$props.url" :url="$props.url"
order="created DESC" order="created DESC"
:limit="0" :limit="0"
:user-filter="$props.filter" :user-filter="userFilter"
:filter="filter"
auto-load auto-load
ref="vnPaginateRef" ref="vnPaginateRef"
class="show" class="show"
v-bind="$attrs" v-bind="$attrs"
search-url="notes" :search-url="false"
@on-fetch=" @on-fetch="
newNote.text = ''; newNote.text = '';
newNote.observationTypeFk = null; newNote.observationTypeFk = null;
@ -218,7 +220,7 @@ function fetchData([ data ]) {
> >
{{ {{
observationTypes.find( observationTypes.find(
(ot) => ot.id === note.observationTypeFk (ot) => ot.id === note.observationTypeFk,
)?.description )?.description
}} }}
</QBadge> </QBadge>

View File

@ -33,6 +33,10 @@ const props = defineProps({
type: String, type: String,
default: '', default: '',
}, },
userFilter: {
type: Object,
default: null,
},
filter: { filter: {
type: Object, type: Object,
default: null, default: null,
@ -204,8 +208,9 @@ async function search() {
} }
:deep(.q-field--focused) { :deep(.q-field--focused) {
.q-icon { .q-icon,
color: black; .q-placeholder {
color: var(--vn-black-text-color);
} }
} }

View File

@ -53,3 +53,8 @@ const manaCode = ref(props.manaCode);
/> />
</div> </div>
</template> </template>
<i18n>
es:
Promotion mana: Maná promoción
Claim mana: Maná reclamación
</i18n>

View File

@ -0,0 +1,66 @@
import { describe, it, expect, vi } from 'vitest';
import { useRequired } from '../useRequired';
vi.mock('../useValidator', () => ({
useValidator: () => ({
validations: () => ({
required: vi.fn((isRequired, val) => {
if (!isRequired) return true;
return val !== null && val !== undefined && val !== '';
}),
}),
}),
}));
describe('useRequired', () => {
it('should detect required when attr is boolean true', () => {
const attrs = { required: true };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(true);
});
it('should detect required when attr is boolean false', () => {
const attrs = { required: false };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(false);
});
it('should detect required when attr exists without value', () => {
const attrs = { required: '' };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(true);
});
it('should return false when required attr does not exist', () => {
const attrs = { someOtherAttr: 'value' };
const { isRequired } = useRequired(attrs);
expect(isRequired).toBe(false);
});
describe('requiredFieldRule', () => {
it('should validate required field with value', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('some value')).toBe(true);
});
it('should validate required field with empty value', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('')).toBe(false);
});
it('should pass validation when field is not required', () => {
const attrs = { required: false };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule('')).toBe(true);
});
it('should handle null and undefined values', () => {
const attrs = { required: true };
const { requiredFieldRule } = useRequired(attrs);
expect(requiredFieldRule(null)).toBe(false);
expect(requiredFieldRule(undefined)).toBe(false);
});
});
});

View File

@ -29,7 +29,6 @@ export async function checkEntryLock(entryFk, userFk) {
.dialog({ .dialog({
component: VnConfirm, component: VnConfirm,
componentProps: { componentProps: {
'data-cy': 'entry-lock-confirm',
title: t('entry.lock.title'), title: t('entry.lock.title'),
message: t('entry.lock.message', { message: t('entry.lock.message', {
userName: data?.user?.nickname, userName: data?.user?.nickname,

View File

@ -1,12 +1,15 @@
export function getColAlign(col) { export function getColAlign(col) {
let align; let align;
switch (col.component) { switch (col.component) {
case 'time':
case 'date':
case 'select': case 'select':
align = 'left'; align = 'left';
break; break;
case 'number': case 'number':
align = 'right'; align = 'right';
break; break;
case 'time':
case 'date': case 'date':
case 'checkbox': case 'checkbox':
align = 'center'; align = 'center';

View File

@ -148,8 +148,7 @@ export function useArrayData(key, userOptions) {
} }
async function applyFilter({ filter, params }, fetchOptions = {}) { async function applyFilter({ filter, params }, fetchOptions = {}) {
if (filter) store.userFilter = filter; if (filter) store.filter = filter;
store.filter = {};
if (params) store.userParams = { ...params }; if (params) store.userParams = { ...params };
const response = await fetch(fetchOptions); const response = await fetch(fetchOptions);
@ -245,7 +244,7 @@ export function useArrayData(key, userOptions) {
async function loadMore() { async function loadMore() {
if (!store.hasMoreData) return; if (!store.hasMoreData) return;
store.skip = store.limit * store.page; store.skip = (store?.filter?.limit ?? store.limit) * store.page;
store.page += 1; store.page += 1;
await fetch({ append: true }); await fetch({ append: true });

View File

@ -11,6 +11,7 @@ export async function useCau(res, message) {
const { config, headers, request, status, statusText, data } = res || {}; const { config, headers, request, status, statusText, data } = res || {};
const { params, url, method, signal, headers: confHeaders } = config || {}; const { params, url, method, signal, headers: confHeaders } = config || {};
const { message: resMessage, code, name } = data?.error || {}; const { message: resMessage, code, name } = data?.error || {};
delete confHeaders?.Authorization;
const additionalData = { const additionalData = {
path: location.hash, path: location.hash,
@ -40,7 +41,7 @@ export async function useCau(res, message) {
handler: async () => { handler: async () => {
const locale = i18n.global.t; const locale = i18n.global.t;
const reason = ref( const reason = ref(
code == 'ACCESS_DENIED' ? locale('cau.askPrivileges') : '' code == 'ACCESS_DENIED' ? locale('cau.askPrivileges') : '',
); );
openConfirmationModal( openConfirmationModal(
locale('cau.title'), locale('cau.title'),
@ -59,10 +60,9 @@ export async function useCau(res, message) {
'onUpdate:modelValue': (val) => (reason.value = val), 'onUpdate:modelValue': (val) => (reason.value = val),
label: locale('cau.inputLabel'), label: locale('cau.inputLabel'),
class: 'full-width', class: 'full-width',
required: true,
autofocus: true, autofocus: true,
}, },
} },
); );
}, },
}, },

View File

@ -2,14 +2,10 @@ import { useValidator } from 'src/composables/useValidator';
export function useRequired($attrs) { export function useRequired($attrs) {
const { validations } = useValidator(); const { validations } = useValidator();
const hasRequired = Object.keys($attrs).includes('required'); const isRequired =
let isRequired = false; typeof $attrs['required'] === 'boolean'
if (hasRequired) { ? $attrs['required']
const required = $attrs['required']; : Object.keys($attrs).includes('required');
if (typeof required === 'boolean') {
isRequired = required;
}
}
const requiredFieldRule = (val) => validations().required(isRequired, val); const requiredFieldRule = (val) => validations().required(isRequired, val);
return { return {

View File

@ -15,6 +15,7 @@ body.body--light {
--vn-empty-tag: #acacac; --vn-empty-tag: #acacac;
--vn-black-text-color: black; --vn-black-text-color: black;
--vn-text-color-contrast: white; --vn-text-color-contrast: white;
--vn-link-color: #1e90ff;
background-color: var(--vn-page-color); background-color: var(--vn-page-color);
@ -38,6 +39,7 @@ body.body--dark {
--vn-empty-tag: #2d2d2d; --vn-empty-tag: #2d2d2d;
--vn-black-text-color: black; --vn-black-text-color: black;
--vn-text-color-contrast: black; --vn-text-color-contrast: black;
--vn-link-color: #66bfff;
background-color: var(--vn-page-color); background-color: var(--vn-page-color);
@ -49,7 +51,7 @@ a {
} }
.link { .link {
color: $color-link; color: var(--vn-link-color);
cursor: pointer; cursor: pointer;
&--white { &--white {
@ -58,14 +60,14 @@ a {
} }
.tx-color-link { .tx-color-link {
color: $color-link !important; color: var(--vn-link-color) !important;
} }
.tx-color-font { .tx-color-font {
color: $color-link !important; color: var(--vn-link-color) !important;
} }
.header-link { .header-link {
color: $color-link !important; color: var(--vn-link-color) !important;
cursor: pointer; cursor: pointer;
border-bottom: solid $primary; border-bottom: solid $primary;
border-width: 2px; border-width: 2px;
@ -335,3 +337,7 @@ input::-webkit-inner-spin-button {
border: 1px solid; border: 1px solid;
box-shadow: 0 4px 6px #00000000; box-shadow: 0 4px 6px #00000000;
} }
.containerShrinked {
width: 70%;
}

View File

@ -24,7 +24,6 @@ $alert: $negative;
$white: #fff; $white: #fff;
$dark: #3d3d3d; $dark: #3d3d3d;
// custom // custom
$color-link: #66bfff;
$color-spacer-light: #a3a3a31f; $color-spacer-light: #a3a3a31f;
$color-spacer: #7979794d; $color-spacer: #7979794d;
$border-thin-light: 1px solid $color-spacer-light; $border-thin-light: 1px solid $color-spacer-light;

View File

@ -3,6 +3,8 @@ import { useI18n } from 'vue-i18n';
export default function (value, options = {}) { export default function (value, options = {}) {
if (!value) return; if (!value) return;
if (!isValidDate(value)) return null;
if (!options.dateStyle && !options.timeStyle) { if (!options.dateStyle && !options.timeStyle) {
options.day = '2-digit'; options.day = '2-digit';
options.month = '2-digit'; options.month = '2-digit';
@ -10,7 +12,12 @@ export default function (value, options = {}) {
} }
const { locale } = useI18n(); const { locale } = useI18n();
const date = new Date(value); const newDate = new Date(value);
return new Intl.DateTimeFormat(locale.value, options).format(date); return new Intl.DateTimeFormat(locale.value, options).format(newDate);
}
// handle 0000-00-00
function isValidDate(date) {
const parsedDate = new Date(date);
return parsedDate instanceof Date && !isNaN(parsedDate.getTime());
} }

View File

@ -49,6 +49,7 @@ globals:
rowRemoved: Row removed rowRemoved: Row removed
pleaseWait: Please wait... pleaseWait: Please wait...
noPinnedModules: You don't have any pinned modules noPinnedModules: You don't have any pinned modules
enterToConfirm: Press Enter to confirm
summary: summary:
basicData: Basic data basicData: Basic data
daysOnward: Days onward daysOnward: Days onward
@ -98,7 +99,6 @@ globals:
file: File file: File
selectFile: Select a file selectFile: Select a file
copyClipboard: Copy on clipboard copyClipboard: Copy on clipboard
salesPerson: SalesPerson
send: Send send: Send
code: Code code: Code
since: Since since: Since
@ -152,11 +152,14 @@ globals:
maxTemperature: Max maxTemperature: Max
minTemperature: Min minTemperature: Min
changePass: Change password changePass: Change password
setPass: Set password
deleteConfirmTitle: Delete selected elements deleteConfirmTitle: Delete selected elements
changeState: Change state changeState: Change state
raid: 'Raid {daysInForward} days' raid: 'Raid {daysInForward} days'
isVies: Vies isVies: Vies
department: Department
noData: No data available noData: No data available
vehicle: Vehicle
pageTitles: pageTitles:
logIn: Login logIn: Login
addressEdit: Update address addressEdit: Update address
@ -344,7 +347,6 @@ globals:
params: params:
description: Description description: Description
clientFk: Client id clientFk: Client id
salesPersonFk: Sales person
warehouseFk: Warehouse warehouseFk: Warehouse
provinceFk: Province provinceFk: Province
stateFk: State stateFk: State
@ -367,6 +369,7 @@ globals:
countryFk: Country countryFk: Country
countryCodeFk: Country countryCodeFk: Country
companyFk: Company companyFk: Company
nickname: Alias
model: Model model: Model
fuel: Fuel fuel: Fuel
active: Active active: Active
@ -528,6 +531,7 @@ ticket:
customerCard: Customer card customerCard: Customer card
ticketList: Ticket List ticketList: Ticket List
newOrder: New Order newOrder: New Order
ticketClaimed: Claimed ticket
boxing: boxing:
expedition: Expedition expedition: Expedition
created: Created created: Created
@ -600,7 +604,6 @@ worker:
balance: Balance balance: Balance
medical: Medical medical: Medical
list: list:
department: Department
schedule: Schedule schedule: Schedule
newWorker: New worker newWorker: New worker
summary: summary:
@ -692,8 +695,10 @@ worker:
machine: Machine machine: Machine
business: business:
tableVisibleColumns: tableVisibleColumns:
id: ID
started: Start Date started: Start Date
ended: End Date ended: End Date
hourlyLabor: Time sheet
company: Company company: Company
reasonEnd: Reason for Termination reasonEnd: Reason for Termination
department: Department department: Department
@ -701,6 +706,7 @@ worker:
calendarType: Work Calendar calendarType: Work Calendar
workCenter: Work Center workCenter: Work Center
payrollCategories: Contract Category payrollCategories: Contract Category
workerBusinessAgreementName: Agreement
occupationCode: Contribution Code occupationCode: Contribution Code
rate: Rate rate: Rate
businessType: Contract Type businessType: Contract Type
@ -830,6 +836,8 @@ travel:
CloneTravelAndEntries: Clone travel and his entries CloneTravelAndEntries: Clone travel and his entries
deleteTravel: Delete travel deleteTravel: Delete travel
AddEntry: Add entry AddEntry: Add entry
availabled: Availabled
availabledHour: Availabled hour
thermographs: Thermographs thermographs: Thermographs
hb: HB hb: HB
basicData: basicData:
@ -854,7 +862,6 @@ components:
mine: For me mine: For me
hasMinPrice: Minimum price hasMinPrice: Minimum price
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Buyer
supplierFk: Supplier supplierFk: Supplier
from: From from: From
to: To to: To
@ -885,6 +892,8 @@ components:
VnLv: VnLv:
copyText: '{copyValue} has been copied to the clipboard' copyText: '{copyValue} has been copied to the clipboard'
iban_tooltip: 'IBAN: ES21 1234 5678 90 0123456789' iban_tooltip: 'IBAN: ES21 1234 5678 90 0123456789'
VnNotes:
clientWithoutPhone: 'The following clients do not have a phone number and the message will not be sent to them: {clientWithoutPhone}'
weekdays: weekdays:
sun: Sunday sun: Sunday
mon: Monday mon: Monday

View File

@ -51,6 +51,7 @@ globals:
pleaseWait: Por favor espera... pleaseWait: Por favor espera...
noPinnedModules: No has fijado ningún módulo noPinnedModules: No has fijado ningún módulo
split: Split split: Split
enterToConfirm: Pulsa Enter para confirmar
summary: summary:
basicData: Datos básicos basicData: Datos básicos
daysOnward: Días adelante daysOnward: Días adelante
@ -102,7 +103,6 @@ globals:
file: Fichero file: Fichero
selectFile: Seleccione un fichero selectFile: Seleccione un fichero
copyClipboard: Copiar en portapapeles copyClipboard: Copiar en portapapeles
salesPerson: Comercial
send: Enviar send: Enviar
code: Código code: Código
since: Desde since: Desde
@ -156,11 +156,14 @@ globals:
maxTemperature: Máx maxTemperature: Máx
minTemperature: Mín minTemperature: Mín
changePass: Cambiar contraseña changePass: Cambiar contraseña
setPass: Establecer contraseña
deleteConfirmTitle: Eliminar los elementos seleccionados deleteConfirmTitle: Eliminar los elementos seleccionados
changeState: Cambiar estado changeState: Cambiar estado
raid: 'Redada {daysInForward} días' raid: 'Redada {daysInForward} días'
isVies: Vies isVies: Vies
noData: Datos no disponibles noData: Datos no disponibles
department: Departamento
vehicle: Vehículo
pageTitles: pageTitles:
logIn: Inicio de sesión logIn: Inicio de sesión
addressEdit: Modificar consignatario addressEdit: Modificar consignatario
@ -347,7 +350,6 @@ globals:
params: params:
description: Descripción description: Descripción
clientFk: Id cliente clientFk: Id cliente
salesPersonFk: Comercial
warehouseFk: Almacén warehouseFk: Almacén
provinceFk: Provincia provinceFk: Provincia
stateFk: Estado stateFk: Estado
@ -368,6 +370,7 @@ globals:
countryFk: País countryFk: País
countryCodeFk: País countryCodeFk: País
companyFk: Empresa companyFk: Empresa
nickname: Alias
errors: errors:
statusUnauthorized: Acceso denegado statusUnauthorized: Acceso denegado
statusInternalServerError: Ha ocurrido un error interno del servidor statusInternalServerError: Ha ocurrido un error interno del servidor
@ -528,13 +531,13 @@ ticket:
state: Estado state: Estado
shipped: Enviado shipped: Enviado
landed: Entregado landed: Entregado
salesPerson: Comercial
total: Total total: Total
card: card:
customerId: ID cliente customerId: ID cliente
customerCard: Ficha del cliente customerCard: Ficha del cliente
ticketList: Listado de tickets ticketList: Listado de tickets
newOrder: Nuevo pedido newOrder: Nuevo pedido
ticketClaimed: Ticket reclamado
boxing: boxing:
expedition: Expedición expedition: Expedición
created: Creado created: Creado
@ -619,8 +622,6 @@ invoiceOut:
errors: errors:
downloadCsvFailed: Error al descargar CSV downloadCsvFailed: Error al descargar CSV
order: order:
field:
salesPersonFk: Comercial
form: form:
clientFk: Cliente clientFk: Cliente
addressFk: Dirección addressFk: Dirección
@ -688,7 +689,6 @@ worker:
formation: Formación formation: Formación
medical: Mutua medical: Mutua
list: list:
department: Departamento
schedule: Horario schedule: Horario
newWorker: Nuevo trabajador newWorker: Nuevo trabajador
summary: summary:
@ -768,8 +768,10 @@ worker:
concept: Concepto concept: Concepto
business: business:
tableVisibleColumns: tableVisibleColumns:
id: Id
started: Fecha inicio started: Fecha inicio
ended: Fecha fin ended: Fecha fin
hourlyLabor: Ficha
company: Empresa company: Empresa
reasonEnd: Motivo finalización reasonEnd: Motivo finalización
department: Departamento department: Departamento
@ -780,12 +782,13 @@ worker:
occupationCode: Cotización occupationCode: Cotización
rate: Tarifa rate: Tarifa
businessType: Contrato businessType: Contrato
workerBusinessAgreementName: Convenio
amount: Salario amount: Salario
basicSalary: Salario transportistas basicSalary: Salario transportistas
notes: Notas notes: Notas
operator: operator:
numberOfWagons: Número de vagones numberOfWagons: Número de vagones
train: tren train: Tren
itemPackingType: Tipo de embalaje itemPackingType: Tipo de embalaje
warehouse: Almacén warehouse: Almacén
sector: Sector sector: Sector
@ -839,6 +842,7 @@ supplier:
verified: Verificado verified: Verificado
isActive: Está activo isActive: Está activo
billingData: Forma de pago billingData: Forma de pago
financialData: Datos financieros
payDeadline: Plazo de pago payDeadline: Plazo de pago
payDay: Día de pago payDay: Día de pago
account: Cuenta account: Cuenta
@ -916,6 +920,8 @@ travel:
deleteTravel: Eliminar envío deleteTravel: Eliminar envío
AddEntry: Añadir entrada AddEntry: Añadir entrada
thermographs: Termógrafos thermographs: Termógrafos
availabled: F. Disponible
availabledHour: Hora Disponible
hb: HB hb: HB
basicData: basicData:
daysInForward: Desplazamiento automatico (redada) daysInForward: Desplazamiento automatico (redada)
@ -940,7 +946,6 @@ components:
hasMinPrice: Precio mínimo hasMinPrice: Precio mínimo
wareHouseFk: Almacén wareHouseFk: Almacén
# LatestBuysFilter # LatestBuysFilter
salesPersonFk: Comprador
supplierFk: Proveedor supplierFk: Proveedor
visible: Visible visible: Visible
active: Activo active: Activo
@ -971,6 +976,8 @@ components:
VnLv: VnLv:
copyText: '{copyValue} se ha copiado al portapepeles' copyText: '{copyValue} se ha copiado al portapepeles'
iban_tooltip: 'IBAN: ES21 1234 5678 90 0123456789' iban_tooltip: 'IBAN: ES21 1234 5678 90 0123456789'
VnNotes:
clientWithoutPhone: 'Estos clientes no tienen asociado número de télefono y el sms no les será enviado: {clientWithoutPhone}'
weekdays: weekdays:
sun: Domingo sun: Domingo
mon: Lunes mon: Lunes

View File

@ -149,14 +149,12 @@ const columns = computed(() => [
:right-search="false" :right-search="false"
> >
<template #more-create-dialog="{ data }"> <template #more-create-dialog="{ data }">
<QCardSection>
<VnInputPassword <VnInputPassword
:label="t('Password')" :label="t('Password')"
v-model="data.password" v-model="data.password"
:required="true" :required="true"
autocomplete="new-password" autocomplete="new-password"
/> />
</QCardSection>
</template> </template>
</VnTable> </VnTable>
</template> </template>

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCard from 'components/common/VnCard.vue';
import AliasDescriptor from './AliasDescriptor.vue'; import AliasDescriptor from './AliasDescriptor.vue';
</script> </script>
<template> <template>
<VnCardBeta <VnCard
data-key="Alias" data-key="Alias"
url="MailAliases" url="MailAliases"
:descriptor="AliasDescriptor" :descriptor="AliasDescriptor"

View File

@ -53,6 +53,7 @@ const removeAlias = () => {
:url="`MailAliases/${entityId}`" :url="`MailAliases/${entityId}`"
data-key="Alias" data-key="Alias"
title="alias" title="alias"
:to-module="{ name: 'AccountAlias' }"
> >
<template #menu> <template #menu>
<QItem v-ripple clickable @click="removeAlias()"> <QItem v-ripple clickable @click="removeAlias()">

View File

@ -5,6 +5,7 @@ import { useI18n } from 'vue-i18n';
import CardSummary from 'components/ui/CardSummary.vue'; import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import VnTitle from 'src/components/common/VnTitle.vue';
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
@ -27,13 +28,10 @@ const entityId = computed(() => $props.id || route.params.id);
<template #body="{ entity: alias }"> <template #body="{ entity: alias }">
<QCard class="vn-one"> <QCard class="vn-one">
<QCardSection class="q-pa-none"> <QCardSection class="q-pa-none">
<router-link <VnTitle
:to="{ name: 'AliasBasicData', params: { id: entityId } }" :url="`#/account/alias/${entityId}/basic-data`"
class="header header-link" :text="t('globals.summary.basicData')"
> />
{{ t('globals.summary.basicData') }}
<QIcon name="open_in_new" />
</router-link>
</QCardSection> </QCardSection>
<VnLv :label="t('role.id')" :value="alias.id" /> <VnLv :label="t('role.id')" :value="alias.id" />
<VnLv :label="t('role.description')" :value="alias.description" /> <VnLv :label="t('role.description')" :value="alias.description" />

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCard from 'components/common/VnCard.vue';
import AccountDescriptor from './AccountDescriptor.vue'; import AccountDescriptor from './AccountDescriptor.vue';
import filter from './AccountFilter.js'; import filter from './AccountFilter.js';
</script> </script>
<template> <template>
<VnCardBeta <VnCard
url="VnUsers/preview" url="VnUsers/preview"
:id-in-where="true" :id-in-where="true"
data-key="Account" data-key="Account"

View File

@ -25,16 +25,23 @@ const $props = defineProps({
const { t } = useI18n(); const { t } = useI18n();
const { hasAccount } = toRefs($props); const { hasAccount } = toRefs($props);
const { openConfirmationModal } = useVnConfirm(); const { openConfirmationModal } = useVnConfirm();
const arrayData = useArrayData('Account');
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const state = useState(); const state = useState();
const user = state.getUser(); const user = state.getUser();
const { notify } = useQuasar(); const { notify } = useQuasar();
const account = computed(() => useArrayData('Account').store.data[0]); const account = computed(() => arrayData.store.data);
account.value.hasAccount = hasAccount.value; account.value.hasAccount = hasAccount.value;
const entityId = computed(() => +route.params.id); const entityId = computed(() => +route.params.id);
const hasitManagementAccess = ref(); const hasitManagementAccess = ref();
const hasSysadminAccess = ref(); const hasSysadminAccess = ref();
const isHimself = computed(() => user.value.id === account.value.id);
const url = computed(() =>
isHimself.value
? 'Accounts/change-password'
: `Accounts/${entityId.value}/setPassword`,
);
async function updateStatusAccount(active) { async function updateStatusAccount(active) {
if (active) { if (active) {
@ -107,11 +114,8 @@ onMounted(() => {
:ask-old-pass="askOldPass" :ask-old-pass="askOldPass"
:submit-fn=" :submit-fn="
async (newPassword, oldPassword) => { async (newPassword, oldPassword) => {
await axios.patch(`Accounts/change-password`, { const body = isHimself ? { userId: entityId, oldPassword } : {};
userId: entityId, await axios.patch(url, { ...body, newPassword });
newPassword,
oldPassword,
});
} }
" "
/> />
@ -150,21 +154,16 @@ onMounted(() => {
t('account.card.actions.disableAccount.title'), t('account.card.actions.disableAccount.title'),
t('account.card.actions.disableAccount.subtitle'), t('account.card.actions.disableAccount.subtitle'),
() => deleteAccount(), () => deleteAccount(),
() => deleteAccount(),
) )
" "
> >
<QItemSection>{{ t('globals.delete') }}</QItemSection> <QItemSection>{{ t('globals.delete') }}</QItemSection>
</QItem> </QItem>
<QItem <QItem v-if="hasSysadminAccess || isHimself" v-ripple clickable>
v-if="hasSysadminAccess" <QItemSection @click="onChangePass(isHimself)">
v-ripple {{ isHimself ? t('globals.changePass') : t('globals.setPass') }}
clickable
@click="user.id === account.id ? onChangePass(true) : onChangePass(false)"
>
<QItemSection v-if="user.id === account.id">
{{ t('globals.changePass') }}
</QItemSection> </QItemSection>
<QItemSection v-else>{{ t('globals.setPass') }}</QItemSection>
</QItem> </QItem>
<QItem <QItem
v-if="!account.hasAccount && hasSysadminAccess" v-if="!account.hasAccount && hasSysadminAccess"
@ -175,6 +174,7 @@ onMounted(() => {
t('account.card.actions.enableAccount.title'), t('account.card.actions.enableAccount.title'),
t('account.card.actions.enableAccount.subtitle'), t('account.card.actions.enableAccount.subtitle'),
() => updateStatusAccount(true), () => updateStatusAccount(true),
() => updateStatusAccount(true),
) )
" "
> >
@ -189,6 +189,7 @@ onMounted(() => {
t('account.card.actions.disableAccount.title'), t('account.card.actions.disableAccount.title'),
t('account.card.actions.disableAccount.subtitle'), t('account.card.actions.disableAccount.subtitle'),
() => updateStatusAccount(false), () => updateStatusAccount(false),
() => updateStatusAccount(false),
) )
" "
> >
@ -204,6 +205,7 @@ onMounted(() => {
t('account.card.actions.activateUser.title'), t('account.card.actions.activateUser.title'),
t('account.card.actions.activateUser.title'), t('account.card.actions.activateUser.title'),
() => updateStatusUser(true), () => updateStatusUser(true),
() => updateStatusUser(true),
) )
" "
> >
@ -218,6 +220,7 @@ onMounted(() => {
t('account.card.actions.deactivateUser.title'), t('account.card.actions.deactivateUser.title'),
t('account.card.actions.deactivateUser.title'), t('account.card.actions.deactivateUser.title'),
() => updateStatusUser(false), () => updateStatusUser(false),
() => updateStatusUser(false),
) )
" "
> >

View File

@ -0,0 +1,14 @@
<script setup>
import AccountDescriptor from './AccountDescriptor.vue';
import AccountSummary from './AccountSummary.vue';
</script>
<template>
<QPopupProxy style="max-width: 10px">
<AccountDescriptor
v-if="$attrs.id"
v-bind="$attrs.id"
:summary="AccountSummary"
:proxy-render="true"
/>
</QPopupProxy>
</template>

View File

@ -5,6 +5,7 @@ import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import filter from './AccountFilter.js'; import filter from './AccountFilter.js';
import AccountDescriptorMenu from './AccountDescriptorMenu.vue'; import AccountDescriptorMenu from './AccountDescriptorMenu.vue';
import VnTitle from 'src/components/common/VnTitle.vue';
const $props = defineProps({ id: { type: Number, default: 0 } }); const $props = defineProps({ id: { type: Number, default: 0 } });
@ -26,13 +27,10 @@ const entityId = computed(() => $props.id || route.params.id);
<template #body="{ entity }"> <template #body="{ entity }">
<QCard class="vn-one"> <QCard class="vn-one">
<QCardSection class="q-pa-none"> <QCardSection class="q-pa-none">
<router-link <VnTitle
:to="{ name: 'AccountBasicData', params: { id: entityId } }" :url="`#/account/${entityId}/basic-data`"
class="header header-link" :text="$t('globals.pageTitles.basicData')"
> />
{{ $t('globals.pageTitles.basicData') }}
<QIcon name="open_in_new" />
</router-link>
</QCardSection> </QCardSection>
<VnLv :label="$t('account.card.nickname')" :value="entity.name" /> <VnLv :label="$t('account.card.nickname')" :value="entity.name" />
<VnLv :label="$t('account.card.role')" :value="entity.role?.name" /> <VnLv :label="$t('account.card.role')" :value="entity.role?.name" />

View File

@ -1,9 +1,9 @@
<script setup> <script setup>
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCard from 'components/common/VnCard.vue';
import RoleDescriptor from './RoleDescriptor.vue'; import RoleDescriptor from './RoleDescriptor.vue';
</script> </script>
<template> <template>
<VnCardBeta <VnCard
url="VnRoles" url="VnRoles"
data-key="Role" data-key="Role"
:id-in-where="true" :id-in-where="true"

View File

@ -37,6 +37,7 @@ const removeRole = async () => {
:filter="{ where: { id: entityId } }" :filter="{ where: { id: entityId } }"
data-key="Role" data-key="Role"
:summary="$props.summary" :summary="$props.summary"
:to-module="{ name: 'AccountRoles' }"
> >
<template #menu> <template #menu>
<QItem v-ripple clickable @click="removeRole()"> <QItem v-ripple clickable @click="removeRole()">

View File

@ -4,6 +4,7 @@ import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import CardSummary from 'components/ui/CardSummary.vue'; import CardSummary from 'components/ui/CardSummary.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import VnTitle from 'src/components/common/VnTitle.vue';
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
@ -29,13 +30,10 @@ const entityId = computed(() => $props.id || route.params.id);
<template #body="{ entity }"> <template #body="{ entity }">
<QCard class="vn-one"> <QCard class="vn-one">
<QCardSection class="q-pa-none"> <QCardSection class="q-pa-none">
<a <VnTitle
class="header header-link" :url="`#/account/role/${entityId}/basic-data`"
:href="`#/VnUser/${entityId}/basic-data`" :text="$t('globals.pageTitles.basicData')"
> />
{{ t('globals.pageTitles.basicData') }}
<QIcon name="open_in_new" />
</a>
</QCardSection> </QCardSection>
<VnLv :label="t('role.id')" :value="entity.id" /> <VnLv :label="t('role.id')" :value="entity.id" />
<VnLv :label="t('globals.name')" :value="entity.name" /> <VnLv :label="t('globals.name')" :value="entity.name" />

View File

@ -27,6 +27,7 @@ const claimActionsForm = ref();
const rows = ref([]); const rows = ref([]);
const selectedRows = ref([]); const selectedRows = ref([]);
const destinationTypes = ref([]); const destinationTypes = ref([]);
const shelvings = ref([]);
const totalClaimed = ref(null); const totalClaimed = ref(null);
const DEFAULT_MAX_RESPONSABILITY = 5; const DEFAULT_MAX_RESPONSABILITY = 5;
const DEFAULT_MIN_RESPONSABILITY = 1; const DEFAULT_MIN_RESPONSABILITY = 1;
@ -56,6 +57,12 @@ const columns = computed(() => [
field: (row) => row.claimDestinationFk, field: (row) => row.claimDestinationFk,
align: 'left', align: 'left',
}, },
{
name: 'shelving',
label: t('shelvings.shelving'),
field: (row) => row.shelvingFk,
align: 'left',
},
{ {
name: 'Landed', name: 'Landed',
label: t('Landed'), label: t('Landed'),
@ -125,6 +132,10 @@ async function updateDestination(claimDestinationFk, row, options = {}) {
options.reload && claimActionsForm.value.reload(); options.reload && claimActionsForm.value.reload();
} }
} }
async function updateShelving(shelvingFk, row) {
await axios.patch(`ClaimEnds/${row.id}`, { shelvingFk });
claimActionsForm.value.reload();
}
async function regularizeClaim() { async function regularizeClaim() {
await post(`Claims/${claimId}/regularizeClaim`); await post(`Claims/${claimId}/regularizeClaim`);
@ -200,6 +211,7 @@ async function post(query, params) {
auto-load auto-load
@on-fetch="(data) => (destinationTypes = data)" @on-fetch="(data) => (destinationTypes = data)"
/> />
<FetchData url="Shelvings" auto-load @on-fetch="(data) => (shelvings = data)" />
<RightMenu v-if="claim"> <RightMenu v-if="claim">
<template #right-panel> <template #right-panel>
<QCard class="totalClaim q-my-md q-pa-sm no-box-shadow"> <QCard class="totalClaim q-my-md q-pa-sm no-box-shadow">
@ -312,6 +324,20 @@ async function post(query, params) {
/> />
</QTd> </QTd>
</template> </template>
<template #body-cell-shelving="{ row }">
<QTd>
<VnSelect
v-model="row.shelvingFk"
url="Shelvings"
option-label="code"
option-value="id"
style="width: 100px"
hide-selected
@update:model-value="(value) => updateShelving(value, row)"
/>
</QTd>
</template>
<template #body-cell-price="{ value }"> <template #body-cell-price="{ value }">
<QTd align="center"> <QTd align="center">
{{ toCurrency(value) }} {{ toCurrency(value) }}
@ -354,7 +380,7 @@ async function post(query, params) {
(value) => (value) =>
updateDestination( updateDestination(
value, value,
props.row props.row,
) )
" "
/> />
@ -371,6 +397,17 @@ async function post(query, params) {
</QTable> </QTable>
</template> </template>
<template #moreBeforeActions> <template #moreBeforeActions>
<QBtn
color="primary"
text-color="white"
:unelevated="true"
:label="tMobile('Import claim')"
:title="t('Import claim')"
icon="Download"
@click="importToNewRefundTicket"
:disable="claim.claimStateFk == resolvedStateId"
:loading="loading"
/>
<QBtn <QBtn
color="primary" color="primary"
text-color="white" text-color="white"
@ -394,17 +431,6 @@ async function post(query, params) {
@click="dialogDestination = !dialogDestination" @click="dialogDestination = !dialogDestination"
:loading="loading" :loading="loading"
/> />
<QBtn
color="primary"
text-color="white"
:unelevated="true"
:label="tMobile('Import claim')"
:title="t('Import claim')"
icon="Upload"
@click="importToNewRefundTicket"
:disable="claim.claimStateFk == resolvedStateId"
:loading="loading"
/>
</template> </template>
</CrudModel> </CrudModel>
<QDialog v-model="dialogDestination"> <QDialog v-model="dialogDestination">

View File

@ -40,7 +40,7 @@ const workersOptions = ref([]);
</VnRow> </VnRow>
<VnRow> <VnRow>
<VnSelect <VnSelect
:label="t('claim.assignedTo')" :label="t('claim.attendedBy')"
v-model="data.workerFk" v-model="data.workerFk"
:options="workersOptions" :options="workersOptions"
option-value="id" option-value="id"

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCard from 'components/common/VnCard.vue';
import ClaimDescriptor from './ClaimDescriptor.vue'; import ClaimDescriptor from './ClaimDescriptor.vue';
import filter from './ClaimFilter.js'; import filter from './ClaimFilter.js';
</script> </script>
<template> <template>
<VnCardBeta <VnCard
data-key="Claim" data-key="Claim"
url="Claims" url="Claims"
:descriptor="ClaimDescriptor" :descriptor="ClaimDescriptor"

View File

@ -5,6 +5,7 @@ import { useI18n } from 'vue-i18n';
import { toDateHourMinSec, toPercentage } from 'src/filters'; import { toDateHourMinSec, toPercentage } from 'src/filters';
import TicketDescriptorProxy from 'pages/Ticket/Card/TicketDescriptorProxy.vue'; import TicketDescriptorProxy from 'pages/Ticket/Card/TicketDescriptorProxy.vue';
import ClaimDescriptorMenu from 'pages/Claim/Card/ClaimDescriptorMenu.vue'; import ClaimDescriptorMenu from 'pages/Claim/Card/ClaimDescriptorMenu.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import CardDescriptor from 'components/ui/CardDescriptor.vue'; import CardDescriptor from 'components/ui/CardDescriptor.vue';
import VnLv from 'src/components/ui/VnLv.vue'; import VnLv from 'src/components/ui/VnLv.vue';
import VnUserLink from 'src/components/ui/VnUserLink.vue'; import VnUserLink from 'src/components/ui/VnUserLink.vue';
@ -65,12 +66,12 @@ onMounted(async () => {
</template> </template>
</VnLv> </VnLv>
<VnLv :label="t('claim.created')" :value="toDateHourMinSec(entity.created)" /> <VnLv :label="t('claim.created')" :value="toDateHourMinSec(entity.created)" />
<VnLv :label="t('claim.commercial')"> <VnLv :label="t('globals.department')">
<template #value> <template #value>
<VnUserLink <span class="link">
:name="entity.client?.salesPersonUser?.name" {{ entity?.client?.department?.name || '-' }}
:worker-id="entity.client?.salesPersonFk" <DepartmentDescriptorProxy :id="entity?.client?.departmentFk" />
/> </span>
</template> </template>
</VnLv> </VnLv>
<VnLv <VnLv

View File

@ -0,0 +1,14 @@
<script setup>
import ClaimDescriptor from './ClaimDescriptor.vue';
import ClaimSummary from './ClaimSummary.vue';
</script>
<template>
<QPopupProxy style="max-width: 10px">
<ClaimDescriptor
v-if="$attrs.id"
v-bind="$attrs.id"
:summary="ClaimSummary"
:proxy-render="true"
/>
</QPopupProxy>
</template>

View File

@ -14,7 +14,7 @@ export default {
relation: 'client', relation: 'client',
scope: { scope: {
include: [ include: [
{ relation: 'salesPersonUser' }, { relation: 'department' },
{ {
relation: 'claimsRatio', relation: 'claimsRatio',
scope: { scope: {

View File

@ -117,7 +117,7 @@ const selected = ref([]);
const mana = ref(0); const mana = ref(0);
async function fetchMana() { async function fetchMana() {
const ticketId = claim.value.ticketFk; const ticketId = claim.value.ticketFk;
const response = await axios.get(`Tickets/${ticketId}/getSalesPersonMana`); const response = await axios.get(`Tickets/${ticketId}/getDepartmentMana`);
mana.value = response.data; mana.value = response.data;
} }
@ -190,7 +190,7 @@ async function saveWhenHasChanges() {
ref="claimLinesForm" ref="claimLinesForm"
:url="`Claims/${route.params.id}/lines`" :url="`Claims/${route.params.id}/lines`"
save-url="ClaimBeginnings/crud" save-url="ClaimBeginnings/crud"
:filter="linesFilter" :user-filter="linesFilter"
@on-fetch="onFetch" @on-fetch="onFetch"
v-model:selected="selected" v-model:selected="selected"
:default-save="false" :default-save="false"

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed, useAttrs } from 'vue'; import { computed } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { useState } from 'src/composables/useState'; import { useState } from 'src/composables/useState';
import VnNotes from 'src/components/ui/VnNotes.vue'; import VnNotes from 'src/components/ui/VnNotes.vue';
@ -7,7 +7,6 @@ import VnNotes from 'src/components/ui/VnNotes.vue';
const route = useRoute(); const route = useRoute();
const state = useState(); const state = useState();
const user = state.getUser(); const user = state.getUser();
const $attrs = useAttrs();
const $props = defineProps({ const $props = defineProps({
id: { type: [Number, String], default: null }, id: { type: [Number, String], default: null },
@ -15,24 +14,21 @@ const $props = defineProps({
}); });
const claimId = computed(() => $props.id || route.params.id); const claimId = computed(() => $props.id || route.params.id);
const claimFilter = computed(() => { const claimFilter = {
return { fields: ['id', 'created', 'workerFk', 'text'],
where: { claimFk: claimId.value }, include: {
fields: ['id', 'created', 'workerFk', 'text'], relation: 'worker',
include: { scope: {
relation: 'worker', fields: ['id', 'firstName', 'lastName'],
scope: { include: {
fields: ['id', 'firstName', 'lastName'], relation: 'user',
include: { scope: {
relation: 'user', fields: ['id', 'nickname', 'name'],
scope: {
fields: ['id', 'nickname', 'name'],
},
}, },
}, },
}, },
}; },
}); };
const body = { const body = {
claimFk: claimId.value, claimFk: claimId.value,
@ -43,7 +39,8 @@ const body = {
<VnNotes <VnNotes
url="claimObservations" url="claimObservations"
:add-note="$props.addNote" :add-note="$props.addNote"
:filter="claimFilter" :user-filter="claimFilter"
:filter="{ where: { claimFk: claimId } }"
:body="body" :body="body"
v-bind="$attrs" v-bind="$attrs"
style="overflow-y: auto" style="overflow-y: auto"

View File

@ -156,7 +156,6 @@ function onDrag() {
url="Claims" url="Claims"
:filter="claimDmsFilter" :filter="claimDmsFilter"
@on-fetch="([data]) => setClaimDms(data)" @on-fetch="([data]) => setClaimDms(data)"
limit="20"
auto-load auto-load
ref="claimDmsRef" ref="claimDmsRef"
/> />
@ -211,6 +210,7 @@ function onDrag() {
class="all-pointer-events absolute delete-button zindex" class="all-pointer-events absolute delete-button zindex"
@click.stop="viewDeleteDms(index)" @click.stop="viewDeleteDms(index)"
round round
:data-cy="`delete-button-${index+1}`"
/> />
<QIcon <QIcon
name="play_circle" name="play_circle"
@ -228,6 +228,7 @@ function onDrag() {
class="rounded-borders cursor-pointer fit" class="rounded-borders cursor-pointer fit"
@click="openDialog(media.dmsFk)" @click="openDialog(media.dmsFk)"
v-if="!media.isVideo" v-if="!media.isVideo"
:data-cy="`file-${index+1}`"
> >
</QImg> </QImg>
<video <video
@ -236,6 +237,7 @@ function onDrag() {
muted="muted" muted="muted"
v-if="media.isVideo" v-if="media.isVideo"
@click="openDialog(media.dmsFk)" @click="openDialog(media.dmsFk)"
:data-cy="`file-${index+1}`"
/> />
</QCard> </QCard>
</div> </div>

View File

@ -19,6 +19,7 @@ import ClaimNotes from 'src/pages/Claim/Card/ClaimNotes.vue';
import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue'; import ItemDescriptorProxy from 'src/pages/Item/Card/ItemDescriptorProxy.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue'; import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue'; import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import ClaimDescriptorMenu from './ClaimDescriptorMenu.vue'; import ClaimDescriptorMenu from './ClaimDescriptorMenu.vue';
const route = useRoute(); const route = useRoute();
@ -233,28 +234,37 @@ function claimUrl(section) {
<ClaimDescriptorMenu :claim="entity.claim" /> <ClaimDescriptorMenu :claim="entity.claim" />
</template> </template>
<template #body="{ entity: { claim, salesClaimed, developments } }"> <template #body="{ entity: { claim, salesClaimed, developments } }">
<QCard class="vn-one" v-if="$route.name != 'ClaimSummary'"> <QCard class="vn-one">
<VnTitle <VnTitle
:url="claimUrl('basic-data')" :url="claimUrl('basic-data')"
:text="t('globals.pageTitles.basicData')" :text="t('globals.pageTitles.basicData')"
/> />
<VnLv :label="t('claim.created')" :value="toDate(claim.created)" /> <VnLv
<VnLv :label="t('claim.state')"> v-if="$route.name != 'ClaimSummary'"
:label="t('claim.created')"
:value="toDate(claim.created)"
/>
<VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.state')">
<template #value> <template #value>
<QChip :color="stateColor(claim.claimState.code)" dense> <QChip :color="stateColor(claim.claimState.code)" dense>
{{ claim.claimState.description }} {{ claim.claimState.description }}
</QChip> </QChip>
</template> </template>
</VnLv> </VnLv>
<VnLv :label="t('globals.salesPerson')"> <VnLv
v-if="$route.name != 'ClaimSummary'"
:label="t('customer.summary.team')"
>
<template #value> <template #value>
<VnUserLink <span class="link">
:name="claim.client?.salesPersonUser?.name" {{ claim?.client?.department?.name || '-' }}
:worker-id="claim.client?.salesPersonFk" <DepartmentDescriptorProxy
/> :id="claim?.client?.departmentFk"
/>
</span>
</template> </template>
</VnLv> </VnLv>
<VnLv :label="t('claim.attendedBy')"> <VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.attendedBy')">
<template #value> <template #value>
<VnUserLink <VnUserLink
:name="claim.worker?.user?.nickname" :name="claim.worker?.user?.nickname"
@ -262,9 +272,9 @@ function claimUrl(section) {
/> />
</template> </template>
</VnLv> </VnLv>
<VnLv :label="t('claim.customer')"> <VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.customer')">
<template #value> <template #value>
<span class="link cursor-pointer"> <span class="link">
{{ claim.client?.name }} {{ claim.client?.name }}
<CustomerDescriptorProxy :id="claim.clientFk" /> <CustomerDescriptorProxy :id="claim.clientFk" />
</span> </span>
@ -274,6 +284,11 @@ function claimUrl(section) {
:label="t('claim.pickup')" :label="t('claim.pickup')"
:value="`${dashIfEmpty(claim.pickup)}`" :value="`${dashIfEmpty(claim.pickup)}`"
/> />
<VnLv
:label="t('globals.packages')"
:value="`${dashIfEmpty(claim.packages)}`"
:translation="(value) => t(`claim.packages`)"
/>
</QCard> </QCard>
<QCard class="vn-two"> <QCard class="vn-two">
<VnTitle :url="claimUrl('notes')" :text="t('claim.notes')" /> <VnTitle :url="claimUrl('notes')" :text="t('claim.notes')" />

View File

@ -19,30 +19,36 @@ const columns = [
name: 'itemFk', name: 'itemFk',
label: t('Id item'), label: t('Id item'),
columnFilter: false, columnFilter: false,
align: 'left', align: 'right',
}, },
{ {
name: 'ticketFk', name: 'ticketFk',
label: t('Ticket'), label: t('Ticket'),
columnFilter: false, columnFilter: false,
align: 'left', align: 'right',
}, },
{ {
name: 'claimDestinationFk', name: 'claimDestinationFk',
label: t('Destination'), label: t('Destination'),
columnFilter: false, columnFilter: false,
align: 'left', align: 'right',
},
{
name: 'shelvingCode',
label: t('Shelving'),
columnFilter: false,
align: 'right',
}, },
{ {
name: 'landed', name: 'landed',
label: t('Landed'), label: t('Landed'),
format: (row) => toDate(row.landed), format: (row) => toDate(row.landed),
align: 'left', align: 'center',
}, },
{ {
name: 'quantity', name: 'quantity',
label: t('Quantity'), label: t('Quantity'),
align: 'left', align: 'right',
}, },
{ {
name: 'concept', name: 'concept',
@ -52,18 +58,18 @@ const columns = [
{ {
name: 'price', name: 'price',
label: t('Price'), label: t('Price'),
align: 'left', align: 'right',
}, },
{ {
name: 'discount', name: 'discount',
label: t('Discount'), label: t('Discount'),
format: ({ discount }) => toPercentage(discount / 100), format: ({ discount }) => toPercentage(discount / 100),
align: 'left', align: 'right',
}, },
{ {
name: 'total', name: 'total',
label: t('Total'), label: t('Total'),
align: 'left', align: 'right',
}, },
]; ];
</script> </script>
@ -74,7 +80,7 @@ const columns = [
:right-search="false" :right-search="false"
:column-search="false" :column-search="false"
:disable-option="{ card: true, table: true }" :disable-option="{ card: true, table: true }"
search-url="actions" :search-url="false"
:filter="{ where: { claimFk: $props.id } }" :filter="{ where: { claimFk: $props.id } }"
:columns="columns" :columns="columns"
:limit="0" :limit="0"

View File

@ -1,8 +1,6 @@
<script setup> <script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue'; import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'components/common/VnSelect.vue'; import VnSelect from 'components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
@ -14,15 +12,14 @@ const props = defineProps({
type: String, type: String,
required: true, required: true,
}, },
states: {
type: Array,
default: () => [],
},
}); });
const states = ref([]);
defineExpose({ states });
</script> </script>
<template> <template>
<FetchData url="ClaimStates" @on-fetch="(data) => (states = data)" auto-load />
<VnFilterPanel :data-key="props.dataKey" :search-button="true"> <VnFilterPanel :data-key="props.dataKey" :search-button="true">
<template #tags="{ tag, formatFn }"> <template #tags="{ tag, formatFn }">
<div class="q-gutter-x-xs"> <div class="q-gutter-x-xs">
@ -47,15 +44,14 @@ defineExpose({ states });
is-outlined is-outlined
/> />
<VnSelect <VnSelect
:label="t('Salesperson')"
v-model="params.salesPersonFk"
url="Workers/activeWithInheritedRole"
:filter="{ where: { role: 'salesPerson' } }"
:use-like="false"
option-filter="firstName"
dense
outlined outlined
dense
rounded rounded
:label="t('globals.params.departmentFk')"
v-model="params.departmentFk"
option-value="id"
option-label="name"
url="Departments"
/> />
<VnSelect <VnSelect
:label="t('claim.attendedBy')" :label="t('claim.attendedBy')"
@ -109,7 +105,6 @@ defineExpose({ states });
:label="t('claim.zone')" :label="t('claim.zone')"
v-model="params.zoneFk" v-model="params.zoneFk"
url="Zones" url="Zones"
:use-like="false"
outlined outlined
rounded rounded
dense dense
@ -130,7 +125,6 @@ en:
search: Contains search: Contains
clientFk: Customer clientFk: Customer
clientName: Customer clientName: Customer
salesPersonFk: Salesperson
attenderFk: Attender attenderFk: Attender
claimResponsibleFk: Responsible claimResponsibleFk: Responsible
claimStateFk: State claimStateFk: State
@ -143,7 +137,6 @@ es:
search: Contiene search: Contiene
clientFk: Cliente clientFk: Cliente
clientName: Cliente clientName: Cliente
salesPersonFk: Comercial
attenderFk: Asistente attenderFk: Asistente
claimResponsibleFk: Responsable claimResponsibleFk: Responsable
claimStateFk: Estado claimStateFk: Estado
@ -152,6 +145,5 @@ es:
itemFk: Artículo itemFk: Artículo
zoneFk: Zona zoneFk: Zona
Client Name: Nombre del cliente Client Name: Nombre del cliente
Salesperson: Comercial
Item: Artículo Item: Artículo
</i18n> </i18n>

View File

@ -4,18 +4,20 @@ import { useI18n } from 'vue-i18n';
import { toDate } from 'filters/index'; import { toDate } from 'filters/index';
import ClaimFilter from './ClaimFilter.vue'; import ClaimFilter from './ClaimFilter.vue';
import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue'; import CustomerDescriptorProxy from 'src/pages/Customer/Card/CustomerDescriptorProxy.vue';
import DepartmentDescriptorProxy from 'src/pages/Worker/Department/Card/DepartmentDescriptorProxy.vue';
import VnUserLink from 'src/components/ui/VnUserLink.vue'; import VnUserLink from 'src/components/ui/VnUserLink.vue';
import ClaimSummary from './Card/ClaimSummary.vue'; import ClaimSummary from './Card/ClaimSummary.vue';
import { useSummaryDialog } from 'src/composables/useSummaryDialog'; import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import VnTable from 'src/components/VnTable/VnTable.vue'; import VnTable from 'src/components/VnTable/VnTable.vue';
import ZoneDescriptorProxy from '../Zone/Card/ZoneDescriptorProxy.vue'; import ZoneDescriptorProxy from '../Zone/Card/ZoneDescriptorProxy.vue';
import VnSection from 'src/components/common/VnSection.vue'; import VnSection from 'src/components/common/VnSection.vue';
import FetchData from 'src/components/FetchData.vue';
const { t } = useI18n(); const { t } = useI18n();
const { viewSummary } = useSummaryDialog(); const { viewSummary } = useSummaryDialog();
const dataKey = 'ClaimList'; const dataKey = 'ClaimList';
const claimFilterRef = ref(); const states = ref([]);
const columns = computed(() => [ const columns = computed(() => [
{ {
align: 'left', align: 'left',
@ -47,6 +49,20 @@ const columns = computed(() => [
}, },
columnClass: 'expand', columnClass: 'expand',
}, },
{
align: 'left',
name: 'departmentFk',
label: t('customer.summary.team'),
component: 'select',
attrs: {
url: 'Departments',
},
create: true,
columnField: {
component: null,
},
format: (row, dashIfEmpty) => dashIfEmpty(row.departmentName),
},
{ {
align: 'left', align: 'left',
label: t('claim.attendedBy'), label: t('claim.attendedBy'),
@ -81,8 +97,7 @@ const columns = computed(() => [
align: 'left', align: 'left',
label: t('claim.state'), label: t('claim.state'),
format: ({ stateCode }) => format: ({ stateCode }) =>
claimFilterRef.value?.states.find(({ code }) => code === stateCode) states.value?.find(({ code }) => code === stateCode)?.description,
?.description,
name: 'stateCode', name: 'stateCode',
chip: { chip: {
condition: () => true, condition: () => true,
@ -92,7 +107,7 @@ const columns = computed(() => [
name: 'claimStateFk', name: 'claimStateFk',
component: 'select', component: 'select',
attrs: { attrs: {
options: claimFilterRef.value?.states, options: states.value,
optionLabel: 'description', optionLabel: 'description',
}, },
}, },
@ -125,6 +140,7 @@ const STATE_COLOR = {
</script> </script>
<template> <template>
<FetchData url="ClaimStates" @on-fetch="(data) => (states = data)" auto-load />
<VnSection <VnSection
:data-key="dataKey" :data-key="dataKey"
:columns="columns" :columns="columns"
@ -135,7 +151,7 @@ const STATE_COLOR = {
}" }"
> >
<template #advanced-menu> <template #advanced-menu>
<ClaimFilter data-key="ClaimList" ref="claimFilterRef" /> <ClaimFilter :data-key ref="claimFilterRef" :states />
</template> </template>
<template #body> <template #body>
<VnTable <VnTable
@ -151,6 +167,12 @@ const STATE_COLOR = {
<CustomerDescriptorProxy :id="row.clientFk" /> <CustomerDescriptorProxy :id="row.clientFk" />
</span> </span>
</template> </template>
<template #column-departmentFk="{ row }">
<span class="link" @click.stop>
{{ row.departmentName || '-' }}
<DepartmentDescriptorProxy :id="row?.departmentFk" />
</span>
</template>
<template #column-attendedBy="{ row }"> <template #column-attendedBy="{ row }">
<span @click.stop> <span @click.stop>
<VnUserLink :name="row.workerName" :worker-id="row.workerFk" /> <VnUserLink :name="row.workerName" :worker-id="row.workerFk" />

View File

@ -13,7 +13,6 @@ claim:
province: Province province: Province
zone: Zone zone: Zone
customerId: client ID customerId: client ID
assignedTo: Assigned
created: Created created: Created
details: Details details: Details
item: Item item: Item

View File

@ -13,7 +13,6 @@ claim:
province: Provincia province: Provincia
zone: Zona zone: Zona
customerId: ID de cliente customerId: ID de cliente
assignedTo: Asignado a
created: Creado created: Creado
details: Detalles details: Detalles
item: Artículo item: Artículo

View File

@ -8,7 +8,6 @@ import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue'; import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
import { getDifferences, getUpdatedValues } from 'src/filters'; import { getDifferences, getUpdatedValues } from 'src/filters';
const route = useRoute(); const route = useRoute();
@ -37,7 +36,7 @@ const exprBuilder = (param, value) => {
function onBeforeSave(formData, originalData) { function onBeforeSave(formData, originalData) {
return getUpdatedValues( return getUpdatedValues(
Object.keys(getDifferences(formData, originalData)), Object.keys(getDifferences(formData, originalData)),
formData formData,
); );
} }
</script> </script>
@ -119,16 +118,11 @@ function onBeforeSave(formData, originalData) {
/> />
</VnRow> </VnRow>
<VnRow> <VnRow>
<VnSelectWorker <VnSelect
:label="t('customer.summary.salesPerson')" :label="t('globals.department')"
v-model="data.salesPersonFk" v-model="data.departmentFk"
:params="{ url="Departments"
departmentCodes: ['VT', 'shopping'], :fields="['id', 'name']"
}"
:has-avatar="true"
:rules="validate('client.salesPersonFk')"
:expr-builder="exprBuilder"
emit-value
/> />
<VnSelect <VnSelect
v-model="data.contactChannelFk" v-model="data.contactChannelFk"
@ -160,7 +154,7 @@ function onBeforeSave(formData, originalData) {
<QIcon name="info" class="cursor-pointer"> <QIcon name="info" class="cursor-pointer">
<QTooltip>{{ <QTooltip>{{
t( t(
'In case of a company succession, specify the grantor company' 'In case of a company succession, specify the grantor company',
) )
}}</QTooltip> }}</QTooltip>
</QIcon> </QIcon>

View File

@ -17,8 +17,7 @@ const bankEntitiesRef = ref(null);
const filter = { const filter = {
fields: ['id', 'bic', 'name'], fields: ['id', 'bic', 'name'],
order: 'bic ASC', order: 'bic ASC'
limit: 30,
}; };
const getBankEntities = (data, formData) => { const getBankEntities = (data, formData) => {

View File

@ -1,10 +1,10 @@
<script setup> <script setup>
import VnCardBeta from 'components/common/VnCardBeta.vue'; import VnCard from 'components/common/VnCard.vue';
import CustomerDescriptor from './CustomerDescriptor.vue'; import CustomerDescriptor from './CustomerDescriptor.vue';
</script> </script>
<template> <template>
<VnCardBeta <VnCard
data-key="Customer" data-key="Customer"
:url="`Clients/${$route.params.id}/getCard`" :url="`Clients/${$route.params.id}/getCard`"
:descriptor="CustomerDescriptor" :descriptor="CustomerDescriptor"

View File

@ -232,7 +232,6 @@ const updateDateParams = (value, params) => {
:include="'category'" :include="'category'"
:sortBy="'name ASC'" :sortBy="'name ASC'"
dense dense
@update:model-value="(data) => updateDateParams(data, params)"
> >
<template #option="scope"> <template #option="scope">
<QItem v-bind="scope.itemProps"> <QItem v-bind="scope.itemProps">
@ -254,7 +253,6 @@ const updateDateParams = (value, params) => {
:fields="['id', 'name']" :fields="['id', 'name']"
:sortBy="'name ASC'" :sortBy="'name ASC'"
dense dense
@update:model-value="(data) => updateDateParams(data, params)"
/> />
<VnSelect <VnSelect
v-model="params.campaign" v-model="params.campaign"
@ -303,12 +301,14 @@ en:
valentinesDay: Valentine's Day valentinesDay: Valentine's Day
mothersDay: Mother's Day mothersDay: Mother's Day
allSaints: All Saints' Day allSaints: All Saints' Day
frenchMothersDay: Mother's Day in France
es: es:
Enter a new search: Introduce una nueva búsqueda Enter a new search: Introduce una nueva búsqueda
Group by items: Agrupar por artículos Group by items: Agrupar por artículos
valentinesDay: Día de San Valentín valentinesDay: Día de San Valentín
mothersDay: Día de la Madre mothersDay: Día de la Madre
allSaints: Día de Todos los Santos allSaints: Día de Todos los Santos
frenchMothersDay: (Francia) Día de la Madre
Campaign consumption: Consumo campaña Campaign consumption: Consumo campaña
Campaign: Campaña Campaign: Campaña
From: Desde From: Desde

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