Compare commits

..

39 Commits

Author SHA1 Message Date
Carlos Satorres d3613a1fc9 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2025-02-10 12:41:19 +01:00
Carlos Satorres 8fcd60b3d8 fix: refs #4774 translationVn 2025-02-10 12:40:45 +01:00
Carlos Satorres 6055f4eb5a fix: refs #4774 remove trad 2025-02-10 10:43:02 +01:00
Carlos Satorres 7ecbfcd5af fix: refs #4774 remove js 2025-02-10 10:32:14 +01:00
Carlos Satorres aaf58c80f0 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2025-02-10 10:17:46 +01:00
Carlos Satorres 58ab439b50 fix: refs #4774 create test 2025-01-27 08:45:48 +01:00
Carlos Satorres 4327c0c65b Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2025-01-27 08:04:56 +01:00
Carlos Satorres c512fdab0a fix: refs #4774 create e2e 2025-01-24 14:01:06 +01:00
Carlos Satorres 59b86ac994 fix: refs #4774 clean code 2025-01-24 13:44:19 +01:00
Carlos Satorres ce61af0ce8 fix: refs #4774 remove copy 2025-01-24 13:43:40 +01:00
Carlos Satorres 2b6909d60e fix: refs #4774 fix delete translations 2025-01-24 13:42:54 +01:00
Carlos Satorres dc93ec8fb5 fix: refs #4774 translations conflicts 2025-01-24 12:32:40 +01:00
Carlos Satorres b1faf14f18 Merge branch 'dev' of https: refs #4774//gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2025-01-24 12:07:28 +01:00
Carlos Satorres f849e71050 fix: refs #4774 fix routes 2025-01-13 07:58:55 +01:00
Carlos Satorres 0291749800 fix: refs #4774 fix changes 2025-01-10 12:06:26 +01:00
Carlos Satorres a9d07ff5b3 Merge branch 'dev' of https: refs #4774//gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2025-01-10 11:14:05 +01:00
Carlos Satorres a2d9868c14 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-12-23 13:04:48 +01:00
Carlos Satorres 7b0f78bb41 fix: refs #4774 clean code
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-12-13 10:21:23 +01:00
Carlos Satorres 35b3656447 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-12-12 10:11:44 +01:00
Carlos Satorres ea2620662b fix: refs #4774 front
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-12-12 07:08:09 +01:00
Carlos Satorres 1bc26c3e74 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-12-03 11:31:45 +01:00
Carlos Satorres fc007921bd fix: refs #4774 fix translation front
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-11-26 12:40:32 +01:00
Carlos Satorres aa0b0d8317 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-11-26 10:28:31 +01:00
Carlos Satorres bafb2621ab Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-11-13 09:42:42 +01:00
Carlos Satorres ffe6e73b63 fix: refs #4774 fix vnConfirm
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-11-11 08:51:55 +01:00
Carlos Satorres 11afabbaf8 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-11-11 07:15:27 +01:00
Carlos Satorres c29dedaad7 fix: refs #4774 front remove
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-10-28 11:52:39 +01:00
Carlos Satorres 82b53ea1aa fix: refs #4774 finalize
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-10-24 12:57:17 +02:00
Carlos Satorres 42f975b025 fix: refs #4774 create
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-10-22 12:22:45 +02:00
Carlos Satorres 0b18119c41 Merge branch 'dev' of https: refs #4774//gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-10-22 10:40:40 +02:00
Carlos Satorres 61bbeb7012 fix: refs #4774 fix translations
gitea/salix-front/pipeline/pr-dev There was a failure building this commit Details
2024-10-22 10:37:54 +02:00
Carlos Satorres 4e8ffacea2 fix: refs #4774 fix front table
gitea/salix-front/pipeline/pr-dev This commit looks good Details
2024-10-18 07:55:02 +02:00
Carlos Satorres cd1c70850e Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-10-17 09:37:59 +02:00
Carlos Satorres 9e9a83bc01 Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-10-07 08:11:11 +02:00
Carlos Satorres deb1948873 refs #4774 changes traductions 2024-04-26 08:28:19 +02:00
Carlos Satorres f041e0837f Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-04-24 14:40:34 +02:00
Carlos Satorres 03f7443d40 refs #4774 qtable 2024-02-14 11:45:38 +01:00
Carlos Satorres 77cfb2cffd Merge branch 'dev' of https://gitea.verdnatura.es/verdnatura/salix-front into 4774-traducciones 2024-02-13 16:55:12 +01:00
Carlos Satorres 74da17c8e2 refs #4774 router, template trad 2024-02-06 11:59:00 +01:00
395 changed files with 6822 additions and 13921 deletions

View File

@ -1 +0,0 @@
node_modules

1
.gitignore vendored
View File

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

File diff suppressed because it is too large Load Diff

112
Jenkinsfile vendored
View File

@ -1,7 +1,6 @@
#!/usr/bin/env groovy
def PROTECTED_BRANCH
def IS_LATEST
def BRANCH_ENV = [
test: 'test',
@ -11,22 +10,19 @@ def BRANCH_ENV = [
node {
stage('Setup') {
env.FRONT_REPLICAS = 1
env.NODE_ENV = BRANCH_ENV[env.BRANCH_NAME] ?: 'dev'
PROTECTED_BRANCH = [
'dev',
'test',
'master',
'main',
'beta'
]
].contains(env.BRANCH_NAME)
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
// https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
echo "NODE_NAME: ${env.NODE_NAME}"
echo "WORKSPACE: ${env.WORKSPACE}"
echo "CHANGE_TARGET: ${env.CHANGE_TARGET}"
configFileProvider([
configFile(fileId: 'salix-front.properties',
@ -37,7 +33,7 @@ node {
props.each {key, value -> echo "${key}: ${value}" }
}
if (IS_PROTECTED_BRANCH) {
if (PROTECTED_BRANCH) {
configFileProvider([
configFile(fileId: "salix-front.branch.${env.BRANCH_NAME}",
variable: 'BRANCH_PROPS_FILE')
@ -62,19 +58,6 @@ pipeline {
PROJECT_NAME = 'lilium'
}
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') {
environment {
NODE_ENV = ""
@ -85,89 +68,48 @@ pipeline {
}
stage('Test') {
when {
expression { !IS_PROTECTED_BRANCH }
expression { !PROTECTED_BRANCH }
}
environment {
NODE_ENV = ''
CI = 'true'
TZ = 'Europe/Madrid'
NODE_ENV = ""
}
parallel {
stage('Unit') {
steps {
sh 'pnpm run test:front:ci'
}
post {
always {
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'
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} up -d"
image.inside("--network ${env.COMPOSE_PROJECT}_default -e CI -e TZ --init") {
sh 'sh test/cypress/cypressParallel.sh 3'
}
}
}
post {
always {
sh "docker-compose ${env.COMPOSE_PARAMS} down -v"
junit(
testResults: 'junit/e2e-*.xml',
allowEmptyResults: true
)
}
}
steps {
sh 'pnpm run test:unit:ci'
}
post {
always {
junit(
testResults: 'junitresults.xml',
allowEmptyResults: true
)
}
}
}
stage('Build') {
when {
expression { IS_PROTECTED_BRANCH }
expression { PROTECTED_BRANCH }
}
environment {
VERSION = readFile 'VERSION.txt'
CREDENTIALS = credentials('docker-registry')
}
steps {
sh 'quasar build'
script {
sh 'quasar build'
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')
}
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
}
dockerBuild()
}
}
stage('Deploy') {
when {
expression { IS_PROTECTED_BRANCH }
}
environment {
VERSION = readFile 'VERSION.txt'
expression { PROTECTED_BRANCH }
}
steps {
script {
def packageJson = readJSON file: 'package.json'
env.VERSION = "${packageJson.version}-build${env.BUILD_ID}"
}
withKubeConfig([
serverUrl: "$KUBERNETES_API",
credentialsId: 'kubernetes',

View File

@ -23,7 +23,7 @@ quasar dev
### Run unit tests
```bash
pnpm run test:front
pnpm run test:unit
```
### Run e2e tests

View File

@ -1,44 +1,12 @@
import { defineConfig } from 'cypress';
let urlHost, reporter, reporterOptions, timeouts;
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,
};
}
// https://docs.cypress.io/app/tooling/reporters
// https://docs.cypress.io/app/references/configuration
// https://www.npmjs.com/package/cypress-mochawesome-reporter
export default defineConfig({
e2e: {
baseUrl: `http://${urlHost}:9000`,
experimentalStudio: false,
trashAssetsBeforeRuns: false,
defaultBrowser: 'chromium',
baseUrl: 'http://localhost:9000/',
experimentalStudio: true,
fixturesFolder: 'test/cypress/fixtures',
screenshotsFolder: 'test/cypress/screenshots',
supportFile: 'test/cypress/support/index.js',
@ -48,17 +16,27 @@ export default defineConfig({
specPattern: 'test/cypress/integration/**/*.spec.js',
experimentalRunAllSpecs: true,
watchForFileChanges: true,
reporter,
reporterOptions,
reporter: 'cypress-mochawesome-reporter',
reporterOptions: {
charts: true,
reportPageTitle: 'Cypress Inline Reporter',
reportFilename: '[status]_[datetime]-report',
embeddedScreenshots: true,
reportDir: 'test/cypress/reports',
inlineAssets: true,
},
component: {
componentFolder: 'src',
testFiles: '**/*.spec.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,
viewportHeight: 720,
...timeouts,
includeShadowDom: true,
waitForAnimations: true,
},
});

7
docker-compose.yml Normal file
View File

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

View File

@ -1,45 +0,0 @@
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 \
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",
"version": "25.12.0",
"version": "25.08.0",
"description": "Salix frontend",
"productName": "Salix",
"author": "Verdnatura",
@ -13,11 +13,9 @@
"format": "prettier --write \"**/*.{js,vue,scss,html,md,json}\" --ignore-path .gitignore",
"test:e2e": "cypress open",
"test:e2e:ci": "npm run resetDatabase && cd ../salix-front && cypress run",
"test:e2e:parallel": "bash ./test/cypress/cypressParallel.sh",
"test:e2e:summary": "bash ./test/cypress/summary.sh",
"test": "echo \"See package.json => scripts for available tests.\" && exit 0",
"test:front": "vitest",
"test:front:ci": "vitest run",
"test:unit": "vitest",
"test:unit:ci": "vitest run",
"commitlint": "commitlint --edit",
"prepare": "npx husky install",
"addReferenceTag": "node .husky/addReferenceTag.js",
@ -49,20 +47,18 @@
"@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0",
"@vue/test-utils": "^2.4.4",
"autoprefixer": "^10.4.14",
"cypress": "^14.1.0",
"cypress": "^13.6.6",
"cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-cypress": "^4.1.0",
"eslint-plugin-vue": "^9.32.0",
"husky": "^8.0.0",
"mocha": "^11.1.0",
"postcss": "^8.4.23",
"prettier": "^3.4.2",
"sass": "^1.83.4",
"vitepress": "^1.6.3",
"vitest": "^0.34.0",
"xunit-viewer": "^10.6.1"
"vitest": "^0.34.0"
},
"engines": {
"node": "^20 || ^18 || ^16",

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -11,7 +11,6 @@
import { configure } from 'quasar/wrappers';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import path from 'path';
const target = `http://${process.env.CI ? 'back' : 'localhost'}:3000`;
export default configure(function (/* ctx */) {
return {
@ -31,6 +30,7 @@ export default configure(function (/* ctx */) {
// --> boot files are part of "main.js"
// https://v2.quasar.dev/quasar-cli/boot-files
boot: ['i18n', 'axios', 'vnDate', 'validations', 'quasar', 'quasar.defaults'],
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#css
css: ['app.scss'],
@ -109,17 +109,13 @@ export default configure(function (/* ctx */) {
},
proxy: {
'/api': {
target: target,
target: 'http://0.0.0.0:3000',
logLevel: 'debug',
changeOrigin: true,
secure: 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

View File

@ -9,19 +9,19 @@ export default {
if (!form) return;
try {
const inputsFormCard = form.querySelectorAll(
`input:not([disabled]):not([type="checkbox"])`,
`input:not([disabled]):not([type="checkbox"])`
);
if (inputsFormCard.length) {
focusFirstInput(inputsFormCard[0]);
}
const textareas = document.querySelectorAll(
'textarea:not([disabled]), [contenteditable]:not([disabled])',
'textarea:not([disabled]), [contenteditable]:not([disabled])'
);
if (textareas.length) {
focusFirstInput(textareas[textareas.length - 1]);
}
const inputs = document.querySelectorAll(
'form#formModel input:not([disabled]):not([type="checkbox"])',
'form#formModel input:not([disabled]):not([type="checkbox"])'
);
const input = inputs[0];
if (!input) return;
@ -30,5 +30,22 @@ export default {
} catch (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

@ -51,5 +51,4 @@ export default boot(({ app }) => {
await useCau(response, message);
};
app.provide('app', app);
});

View File

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

View File

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

View File

@ -1,6 +1,6 @@
<script setup>
import axios from 'axios';
import { computed, ref, useAttrs, watch } from 'vue';
import { computed, nextTick, ref, useAttrs, watch } from 'vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
@ -64,10 +64,6 @@ const $props = defineProps({
type: Function,
default: null,
},
beforeSaveFn: {
type: Function,
default: null,
},
goTo: {
type: String,
default: '',
@ -102,6 +98,7 @@ defineExpose({
formData,
originalData,
vnPaginateRef,
resetData,
});
onBeforeRouteLeave((to, from, next) => {
@ -180,15 +177,8 @@ async function saveChanges(data) {
hasChanges.value = false;
return;
}
let changes = data || getChanges();
if ($props.beforeSaveFn) {
changes = await $props.beforeSaveFn(changes, getChanges);
}
const changes = data || getChanges();
try {
if (changes?.creates?.length === 0 && changes?.updates?.length === 0) {
return;
}
await axios.post($props.saveUrl || $props.url + '/crud', changes);
} finally {
isLoading.value = false;
@ -240,12 +230,12 @@ async function remove(data) {
componentProps: {
title: t('globals.confirmDeletion'),
message: t('globals.confirmDeletionMessage'),
data: { deletes: ids },
newData,
ids,
promise: saveChanges,
},
})
.onOk(async () => {
await saveChanges({ deletes: ids });
newData = newData.filter((form) => !ids.some((id) => id == form[pk]));
fetch(newData);
});
@ -385,8 +375,6 @@ watch(formUrl, async () => {
@click="onSubmit"
:disable="!hasChanges"
:title="t('globals.save')"
v-shortcut="'s'"
shortcut="s"
data-cy="crudModelDefaultSaveBtn"
/>
<slot name="moreAfterActions" />

View File

@ -42,6 +42,7 @@ const itemFilter = {
const itemFilterParams = reactive({});
const closeButton = ref(null);
const isLoading = ref(false);
const producersOptions = ref([]);
const ItemTypesOptions = ref([]);
const InksOptions = ref([]);
const tableRows = ref([]);
@ -120,17 +121,23 @@ const selectItem = ({ id }) => {
</script>
<template>
<FetchData
url="Producers"
@on-fetch="(data) => (producersOptions = data)"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
auto-load
/>
<FetchData
url="ItemTypes"
:filter="{ fields: ['id', 'name'], order: 'name ASC' }"
order="name ASC"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
order="name"
@on-fetch="(data) => (ItemTypesOptions = data)"
auto-load
/>
<FetchData
url="Inks"
:filter="{ fields: ['id', 'name'], order: 'name ASC' }"
order="name ASC"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
order="name"
@on-fetch="(data) => (InksOptions = data)"
auto-load
/>
@ -145,11 +152,11 @@ const selectItem = ({ id }) => {
<VnInput :label="t('entry.buys.size')" v-model="itemFilterParams.size" />
<VnSelect
:label="t('globals.producer')"
:options="producersOptions"
hide-selected
option-label="name"
option-value="id"
v-model="itemFilterParams.producerFk"
url="Producers"
:fields="['id', 'name']"
sort-by="name ASC"
/>
<VnSelect
:label="t('globals.type')"

View File

@ -124,7 +124,7 @@ const selectTravel = ({ id }) => {
<FetchData
url="AgencyModes"
@on-fetch="(data) => (agenciesOptions = data)"
:filter="{ fields: ['id', 'name'], order: ['name ASC'] }"
:filter="{ fields: ['id', 'name'], order: 'name ASC', limit: 30 }"
auto-load
/>
<FetchData
@ -181,7 +181,6 @@ const selectTravel = ({ id }) => {
color="primary"
:disabled="isLoading"
:loading="isLoading"
data-cy="save-filter-travel-form"
/>
</div>
<QTable
@ -192,10 +191,9 @@ const selectTravel = ({ id }) => {
:no-data-label="t('Enter a new search')"
class="q-mt-lg"
@row-click="(_, row) => selectTravel(row)"
data-cy="table-filter-travel-form"
>
<template #body-cell-id="{ row }">
<QTd auto-width @click.stop data-cy="travelFk-travel-form">
<QTd auto-width @click.stop>
<QBtn flat color="blue">{{ row.id }}</QBtn>
<TravelDescriptorProxy :id="row.id" />
</QTd>

View File

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

View File

@ -1,13 +1,12 @@
<script setup>
import { ref, computed, useAttrs, nextTick } from 'vue';
import { ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useState } from 'src/composables/useState';
import FormModel from 'components/FormModel.vue';
const emit = defineEmits(['onDataSaved', 'onDataCanceled']);
const props = defineProps({
defineProps({
title: {
type: String,
default: '',
@ -16,41 +15,23 @@ const props = defineProps({
type: String,
default: '',
},
showSaveAndContinueBtn: {
type: Boolean,
default: false,
},
});
const { t } = useI18n();
const attrs = useAttrs();
const state = useState();
const formModelRef = ref(null);
const closeButton = ref(null);
const isSaveAndContinue = ref(props.showSaveAndContinueBtn);
const isLoading = computed(() => formModelRef.value?.isLoading);
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;
const onDataSaved = (formData, requestResponse) => {
if (closeButton.value) closeButton.value.click();
emit('onDataSaved', formData, requestResponse);
};
const onClick = async (saveAndContinue) => {
isSaveAndContinue.value = saveAndContinue;
await formModelRef.value.save();
};
const isLoading = computed(() => formModelRef.value?.isLoading);
defineExpose({
isLoading,
onDataSaved,
isSaveAndContinue,
reset,
});
</script>
@ -78,16 +59,15 @@ defineExpose({
flat
:disabled="isLoading"
:loading="isLoading"
data-cy="FormModelPopup_cancel"
v-close-popup
z-max
@click="emit('onDataCanceled')"
v-close-popup
data-cy="FormModelPopup_cancel"
z-max
/>
<QBtn
:flat="showSaveAndContinueBtn"
:label="t('globals.save')"
:title="t('globals.save')"
@click="onClick(false)"
type="submit"
color="primary"
class="q-ml-sm"
:disabled="isLoading"
@ -95,18 +75,6 @@ defineExpose({
data-cy="FormModelPopup_save"
z-max
/>
<QBtn
v-if="showSaveAndContinueBtn"
:label="t('globals.isSaveAndContinue')"
:title="t('globals.isSaveAndContinue')"
color="primary"
class="q-ml-sm"
:disabled="isLoading"
:loading="isLoading"
data-cy="FormModelPopup_isSaveAndContinue"
z-max
@click="onClick(true)"
/>
</div>
</template>
</FormModel>

View File

@ -121,25 +121,23 @@ const removeTag = (index, params, search) => {
applyTags(params, search);
};
const setCategoryList = (data) => {
categoryList.value = (data || []).map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
categoryList.value = (data || [])
.filter((category) => category.display)
.map((category) => ({
...category,
icon: `vn:${(category.icon || '').split('-')[1]}`,
}));
fetchItemTypes();
};
</script>
<template>
<FetchData
url="ItemCategories"
auto-load
@on-fetch="setCategoryList"
:where="{ display: { neq: 0 } }"
/>
<FetchData url="ItemCategories" limit="30" auto-load @on-fetch="setCategoryList" />
<FetchData
url="Tags"
:filter="{ fields: ['id', 'name', 'isFree'] }"
auto-load
limit="30"
@on-fetch="(data) => (tagOptions = data)"
/>
<VnFilterPanel
@ -197,6 +195,8 @@ const setCategoryList = (data) => {
:label="t('components.itemsFilterPanel.typeFk')"
v-model="params.typeFk"
:options="itemTypesOptions"
option-value="id"
option-label="name"
dense
outlined
rounded
@ -234,6 +234,7 @@ const setCategoryList = (data) => {
:label="t('globals.tag')"
v-model="value.selectedTag"
:options="tagOptions"
option-label="name"
dense
outlined
rounded
@ -327,6 +328,7 @@ en:
active: Is active
visible: Is visible
floramondo: Is floramondo
salesPersonFk: Buyer
categoryFk: Category
es:
@ -337,6 +339,7 @@ es:
active: Activo
visible: Visible
floramondo: Floramondo
salesPersonFk: Comprador
categoryFk: Categoría
Plant: Planta natural
Flower: Flor fresca

View File

@ -26,7 +26,6 @@ const itemComputed = computed(() => {
:to="{ name: itemComputed.name }"
clickable
v-ripple
:data-cy="`${itemComputed.name}-menu-item`"
>
<QItemSection avatar v-if="itemComputed.icon">
<QIcon :name="itemComputed.icon" />

View File

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

View File

@ -9,7 +9,6 @@ import VnSelect from 'components/common/VnSelect.vue';
import FormPopup from './FormPopup.vue';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
const $props = defineProps({
invoiceOutData: {
@ -132,11 +131,15 @@ const refund = async () => {
:required="true"
/> </VnRow
><VnRow>
<VnCheckbox
v-model="invoiceParams.inheritWarehouse"
:label="t('Inherit warehouse')"
:info="t('Inherit warehouse tooltip')"
/>
<div>
<QCheckbox
:label="t('Inherit warehouse')"
v-model="invoiceParams.inheritWarehouse"
/>
<QIcon name="info" class="cursor-info q-ml-sm" size="sm">
<QTooltip>{{ t('Inherit warehouse tooltip') }}</QTooltip>
</QIcon>
</div>
</VnRow>
</template>
</FormPopup>

View File

@ -1,42 +1,16 @@
<script setup>
import { toCurrency } from 'src/filters';
defineProps({ row: { type: Object, required: true } });
</script>
<template>
<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
v-if="row?.reserved"
color="primary"
name="vn:reserva"
size="xs"
data-cy="ticketSaleReservedIcon"
>
<QTooltip>
{{ t('ticketSale.reserved') }}
</QTooltip>
</QIcon>
<QIcon
v-if="row?.hasRisk"
v-if="row?.risk"
name="vn:risk"
:color="row.hasHighRisk ? 'negative' : 'primary'"
size="xs"
>
<QTooltip>
{{ $t('salesTicketsTable.risk') }}:
{{ toCurrency(row.risk - (row.credit ?? 0)) }}
{{ $t('salesTicketsTable.risk') }}: {{ row.risk - row.credit }}
</QTooltip>
</QIcon>
<QIcon
@ -78,7 +52,12 @@ defineProps({ row: { type: Object, required: true } });
>
<QTooltip>{{ $t('salesTicketsTable.purchaseRequest') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isTaxDataChecked" name="vn:no036" color="primary" size="xs">
<QIcon
v-if="!row?.isTaxDataChecked === 0"
name="vn:no036"
color="primary"
size="xs"
>
<QTooltip>{{ $t('salesTicketsTable.noVerifiedData') }}</QTooltip>
</QIcon>
<QIcon v-if="row?.isFreezed" name="vn:frozen" color="primary" size="xs">

View File

@ -10,7 +10,6 @@ import VnSelect from 'components/common/VnSelect.vue';
import FormPopup from './FormPopup.vue';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import VnCheckbox from './common/VnCheckbox.vue';
const $props = defineProps({
invoiceOutData: {
@ -87,7 +86,7 @@ const makeInvoice = async () => {
(data) => (
(rectificativeTypeOptions = data),
(transferInvoiceParams.cplusRectificationTypeFk = data.filter(
(type) => type.description == 'I Por diferencias',
(type) => type.description == 'I Por diferencias'
)[0].id)
)
"
@ -100,7 +99,7 @@ const makeInvoice = async () => {
(data) => (
(siiTypeInvoiceOutsOptions = data),
(transferInvoiceParams.siiTypeInvoiceOutFk = data.filter(
(type) => type.code == 'R4',
(type) => type.code == 'R4'
)[0].id)
)
"
@ -122,6 +121,7 @@ const makeInvoice = async () => {
<VnRow>
<VnSelect
:label="t('Client')"
:options="clientsOptions"
hide-selected
option-label="name"
option-value="id"
@ -186,11 +186,15 @@ const makeInvoice = async () => {
/>
</VnRow>
<VnRow>
<VnCheckbox
v-model="checked"
:label="t('Bill destination client')"
:info="t('transferInvoiceInfo')"
/>
<div>
<QCheckbox
:label="t('Bill destination client')"
v-model="checked"
/>
<QIcon name="info" class="cursor-info q-ml-sm" size="sm">
<QTooltip>{{ t('transferInvoiceInfo') }}</QTooltip>
</QIcon>
</div>
</VnRow>
</template>
</FormPopup>

View File

@ -1,8 +1,9 @@
<script setup>
import { markRaw, computed } from 'vue';
import { QIcon, QToggle } from 'quasar';
import { QIcon, QCheckbox } from 'quasar';
import { dashIfEmpty } from 'src/filters';
/* basic input */
import VnSelect from 'components/common/VnSelect.vue';
import VnSelectCache from 'components/common/VnSelectCache.vue';
import VnInput from 'components/common/VnInput.vue';
@ -11,11 +12,8 @@ import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnComponent from 'components/common/VnComponent.vue';
import VnUserLink from 'components/ui/VnUserLink.vue';
import VnSelectEnum from '../common/VnSelectEnum.vue';
import VnCheckbox from '../common/VnCheckbox.vue';
const model = defineModel(undefined, { required: true });
const emit = defineEmits(['blur']);
const $props = defineProps({
column: {
type: Object,
@ -41,18 +39,10 @@ const $props = defineProps({
type: Object,
default: null,
},
autofocus: {
type: Boolean,
default: false,
},
showLabel: {
type: Boolean,
default: null,
},
eventHandlers: {
type: Object,
default: null,
},
});
const defaultSelect = {
@ -109,8 +99,7 @@ const defaultComponents = {
},
},
checkbox: {
ref: 'checkbox',
component: markRaw(VnCheckbox),
component: markRaw(QCheckbox),
attrs: ({ model }) => {
const defaultAttrs = {
disable: !$props.isEditable,
@ -126,10 +115,6 @@ const defaultComponents = {
},
forceAttrs: {
label: $props.showLabel && $props.column.label,
autofocus: true,
},
events: {
blur: () => emit('blur'),
},
},
select: {
@ -140,19 +125,12 @@ const defaultComponents = {
component: markRaw(VnSelect),
...defaultSelect,
},
selectEnum: {
component: markRaw(VnSelectEnum),
...defaultSelect,
},
icon: {
component: markRaw(QIcon),
},
userLink: {
component: markRaw(VnUserLink),
},
toggle: {
component: markRaw(QToggle),
},
};
const value = computed(() => {
@ -182,28 +160,7 @@ const col = computed(() => {
return newColumn;
});
const components = computed(() => {
const sourceComponents = $props.components ?? defaultComponents;
return Object.keys(sourceComponents).reduce((acc, key) => {
const component = sourceComponents[key];
if (!component || typeof component !== 'object') {
acc[key] = component;
return acc;
}
acc[key] = {
...component,
attrs: {
...(component.attrs || {}),
autofocus: $props.autofocus,
},
event: { ...component?.event, ...$props?.eventHandlers },
};
return acc;
}, {});
});
const components = computed(() => $props.components ?? defaultComponents);
</script>
<template>
<div class="row no-wrap">

View File

@ -1,12 +1,14 @@
<script setup>
import { markRaw, computed } from 'vue';
import { QCheckbox, QToggle } from 'quasar';
import { QCheckbox } from 'quasar';
import { useArrayData } from 'composables/useArrayData';
/* basic input */
import VnSelect from 'components/common/VnSelect.vue';
import VnInput from 'components/common/VnInput.vue';
import VnInputDate from 'components/common/VnInputDate.vue';
import VnInputTime from 'components/common/VnInputTime.vue';
import VnColumn from 'components/VnTable/VnColumn.vue';
import VnTableColumn from 'components/VnTable/VnColumn.vue';
const $props = defineProps({
column: {
@ -25,10 +27,6 @@ const $props = defineProps({
type: String,
default: 'table',
},
customClass: {
type: String,
default: '',
},
});
defineExpose({ addFilter, props: $props });
@ -36,7 +34,7 @@ defineExpose({ addFilter, props: $props });
const model = defineModel(undefined, { required: true });
const arrayData = useArrayData(
$props.dataKey,
$props.searchUrl ? { searchUrl: $props.searchUrl } : null,
$props.searchUrl ? { searchUrl: $props.searchUrl } : null
);
const columnFilter = computed(() => $props.column?.columnFilter);
@ -48,18 +46,19 @@ const enterEvent = {
const defaultAttrs = {
filled: !$props.showTitle,
class: 'q-px-xs q-pb-xs q-pt-none fit',
dense: true,
};
const forceAttrs = {
label: $props.showTitle ? '' : (columnFilter.value?.label ?? $props.column.label),
label: $props.showTitle ? '' : columnFilter.value?.label ?? $props.column.label,
};
const selectComponent = {
component: markRaw(VnSelect),
event: updateEvent,
attrs: {
class: `q-pt-none fit ${$props.customClass}`,
class: 'q-px-sm q-pb-xs q-pt-none fit',
dense: true,
filled: !$props.showTitle,
},
@ -91,6 +90,7 @@ const components = {
event: updateEvent,
attrs: {
...defaultAttrs,
style: 'min-width: 150px',
},
forceAttrs,
},
@ -109,24 +109,14 @@ const components = {
component: markRaw(QCheckbox),
event: updateEvent,
attrs: {
class: $props.showTitle ? 'q-py-sm' : 'q-px-md q-py-xs fit',
dense: true,
class: $props.showTitle ? 'q-py-sm q-mt-md' : 'q-px-md q-py-xs fit',
'toggle-indeterminate': true,
size: 'sm',
},
forceAttrs,
},
select: selectComponent,
rawSelect: selectComponent,
toggle: {
component: markRaw(QToggle),
event: updateEvent,
attrs: {
class: $props.showTitle ? 'q-py-sm' : 'q-px-md q-py-xs fit',
'toggle-indeterminate': true,
size: 'sm',
},
forceAttrs,
},
};
async function addFilter(value, name) {
@ -142,8 +132,19 @@ async function addFilter(value, name) {
await arrayData.addFilter({ params: { [field]: value } });
}
function alignRow() {
switch ($props.column.align) {
case 'left':
return 'justify-start items-start';
case 'right':
return 'justify-end items-end';
default:
return 'flex-center';
}
}
const showFilter = computed(
() => $props.column?.columnFilter !== false && $props.column.name != 'tableActions',
() => $props.column?.columnFilter !== false && $props.column.name != 'tableActions'
);
const onTabPressed = async () => {
@ -151,8 +152,13 @@ const onTabPressed = async () => {
};
</script>
<template>
<div v-if="showFilter" class="full-width" style="overflow: hidden">
<VnColumn
<div
v-if="showFilter"
class="full-width"
:class="alignRow()"
style="max-height: 45px; overflow: hidden"
>
<VnTableColumn
:column="$props.column"
default="input"
v-model="model"
@ -162,8 +168,3 @@ const onTabPressed = async () => {
/>
</div>
</template>
<style lang="scss" scoped>
label.vn-label-padding > .q-field__inner > .q-field__control {
padding: inherit !important;
}
</style>

View File

@ -23,10 +23,6 @@ const $props = defineProps({
type: Boolean,
default: false,
},
align: {
type: String,
default: 'end',
},
});
const hover = ref();
const arrayData = useArrayData($props.dataKey, { searchUrl: $props.searchUrl });
@ -45,78 +41,55 @@ async function orderBy(name, direction) {
break;
}
if (!direction) return await arrayData.deleteOrder(name);
await arrayData.addOrder(name, direction);
}
defineExpose({ orderBy });
function textAlignToFlex(textAlign) {
return `justify-content: ${
{
'text-center': 'center',
'text-left': 'start',
'text-right': 'end',
}[textAlign] || 'start'
};`;
}
</script>
<template>
<div
@mouseenter="hover = true"
@mouseleave="hover = false"
@click="orderBy(name, model?.direction)"
class="items-center no-wrap cursor-pointer title"
:style="textAlignToFlex(align)"
class="row items-center no-wrap cursor-pointer"
>
<span :title="label">{{ label }}</span>
<div v-if="name && model?.index">
<QChip
:label="!vertical ? model?.index : ''"
:icon="
(model?.index || hover) && !vertical
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: undefined
"
:size="vertical ? '' : 'sm'"
:class="[
model?.index ? 'color-vn-text' : 'bg-transparent',
vertical ? 'q-px-none' : '',
]"
class="no-box-shadow"
:clickable="true"
style="min-width: 40px; max-height: 30px"
<QChip
v-if="name"
:label="!vertical ? model?.index : ''"
:icon="
(model?.index || hover) && !vertical
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: undefined
"
:size="vertical ? '' : 'sm'"
:class="[
model?.index ? 'color-vn-text' : 'bg-transparent',
vertical ? 'q-px-none' : '',
]"
class="no-box-shadow"
:clickable="true"
style="min-width: 40px"
>
<div
class="column flex-center"
v-if="vertical"
:style="!model?.index && 'color: #5d5d5d'"
>
<div
class="column flex-center"
v-if="vertical"
:style="!model?.index && 'color: #5d5d5d'"
>
{{ model?.index }}
<QIcon
:name="
model?.index
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: 'swap_vert'
"
size="xs"
/>
</div>
</QChip>
</div>
{{ model?.index }}
<QIcon
:name="
model?.index
? model?.direction == 'DESC'
? 'arrow_downward'
: 'arrow_upward'
: 'swap_vert'
"
size="xs"
/>
</div>
</QChip>
</div>
</template>
<style lang="scss" scoped>
.title {
display: flex;
align-items: center;
height: 30px;
width: 100%;
color: var(--vn-label-color);
white-space: nowrap;
}
</style>

View File

@ -1,39 +1,22 @@
<script setup>
import {
ref,
onBeforeMount,
onMounted,
onUnmounted,
computed,
watch,
h,
render,
inject,
useAttrs,
nextTick,
} from 'vue';
import { useArrayData } from 'src/composables/useArrayData';
import { ref, onBeforeMount, onMounted, computed, watch, useAttrs } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useQuasar, date } from 'quasar';
import { useQuasar } from 'quasar';
import { useStateStore } from 'stores/useStateStore';
import { useFilterParams } from 'src/composables/useFilterParams';
import { dashIfEmpty, toDate } from 'src/filters';
import CrudModel from 'src/components/CrudModel.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnColumn from 'components/VnTable/VnColumn.vue';
import VnTableColumn from 'components/VnTable/VnColumn.vue';
import VnFilter from 'components/VnTable/VnFilter.vue';
import VnTableChip from 'components/VnTable/VnChip.vue';
import VnVisibleColumn from 'src/components/VnTable/VnVisibleColumn.vue';
import VnLv from 'components/ui/VnLv.vue';
import VnTableOrder from 'src/components/VnTable/VnOrder.vue';
import VnTableFilter from './VnTableFilter.vue';
import { getColAlign } from 'src/composables/getColAlign';
import RightMenu from '../common/RightMenu.vue';
const arrayData = useArrayData(useAttrs()['data-key']);
const $props = defineProps({
columns: {
type: Array,
@ -51,6 +34,10 @@ const $props = defineProps({
type: Boolean,
default: true,
},
rightSearchIcon: {
type: Boolean,
default: true,
},
rowClick: {
type: [Function, Boolean],
default: null,
@ -127,23 +114,7 @@ const $props = defineProps({
type: Boolean,
default: false,
},
withFilters: {
type: Boolean,
default: true,
},
overlay: {
type: Boolean,
default: false,
},
createComplement: {
type: Object,
},
dataCy: {
type: String,
default: 'vn-table',
},
});
const { t } = useI18n();
const stateStore = useStateStore();
const route = useRoute();
@ -161,17 +132,10 @@ const showForm = ref(false);
const splittedColumns = ref({ columns: [] });
const columnsVisibilitySkipped = ref();
const createForm = ref();
const createRef = ref(null);
const tableRef = ref();
const params = ref(useFilterParams($attrs['data-key']).params);
const orders = ref(useFilterParams($attrs['data-key']).orders);
const app = inject('app');
const editingRow = ref(null);
const editingField = ref(null);
const isTableMode = computed(() => mode.value == TABLE_MODE);
const selectRegex = /select/;
const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']);
const tableModes = [
{
icon: 'view_column',
@ -192,8 +156,7 @@ onBeforeMount(() => {
hasParams.value = urlParams && Object.keys(urlParams).length !== 0;
});
onMounted(async () => {
if ($props.isEditable) document.addEventListener('click', clickHandler);
onMounted(() => {
mode.value =
quasar.platform.is.mobile && !$props.disableOption?.card
? CARD_MODE
@ -215,25 +178,20 @@ onMounted(async () => {
}
});
onUnmounted(async () => {
if ($props.isEditable) document.removeEventListener('click', clickHandler);
});
watch(
() => $props.columns,
(value) => splitColumns(value),
{ immediate: true },
);
defineExpose({
create: createForm,
reload,
redirect: redirectFn,
selected,
CrudModelRef,
params,
tableRef,
});
watch(
() => $props.create,
(value) => (createForm.value = value),
{ immediate: true }
);
const isTableMode = computed(() => mode.value == TABLE_MODE);
const showRightIcon = computed(() => $props.rightSearch || $props.rightSearchIcon);
function splitColumns(columns) {
splittedColumns.value = {
@ -257,9 +215,7 @@ function splitColumns(columns) {
col.columnFilter = { inWhere: true, ...col.columnFilter };
splittedColumns.value.columns.push(col);
}
splittedColumns.value.create = createOrderSort(splittedColumns.value.create);
// Status column
if (splittedColumns.value.chips.length) {
splittedColumns.value.columnChips = splittedColumns.value.chips.filter(
(c) => !c.isId,
@ -275,30 +231,22 @@ 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(() => {
if ($props.rowClick != undefined) return $props.rowClick;
if ($props.redirect) return ({ id }) => redirectFn(id);
return () => {};
});
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 () => {};
});
function redirectFn(id) {
router.push({ path: `/${$props.redirect}/${id}` });
}
@ -320,6 +268,21 @@ function columnName(col) {
return name;
}
function getColAlign(col) {
return 'text-' + (col.align ?? 'left');
}
const emit = defineEmits(['onFetch', 'update:selected', 'saveChanges']);
defineExpose({
create: createForm,
reload,
redirect: redirectFn,
selected,
CrudModelRef,
params,
tableRef,
});
function handleOnDataSaved(_) {
if (_.onDataSaved) _.onDataSaved({ CrudModelRef: CrudModelRef.value });
else $props.create.onDataSaved(_);
@ -338,14 +301,8 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
if (evt?.shiftKey && added) {
const rowIndex = selectedRows[0].$index;
const selectedIndexes = new Set(selected.value.map((row) => row.$index));
const minIndex = selectedIndexes.size
? 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;
for (const row of rows) {
if (row.$index == rowIndex) break;
if (!selectedIndexes.has(row.$index)) {
selected.value.push(row);
selectedIndexes.add(row.$index);
@ -353,283 +310,16 @@ function handleSelection({ evt, added, rows: selectedRows }, rows) {
}
}
}
function isEditableColumn(column) {
const isEditableCol = column?.isEditable ?? true;
const isVisible = column?.visible ?? true;
const hasComponent = column?.component;
return $props.isEditable && isVisible && hasComponent && isEditableCol;
}
function hasEditableFormat(column) {
if (isEditableColumn(column)) return 'editable-text';
}
const clickHandler = async (event) => {
const clickedElement = event.target.closest('td');
const isDateElement = event.target.closest('.q-date');
const isTimeElement = event.target.closest('.q-time');
const isQSelectDropDown = event.target.closest('.q-select__dropdown-icon');
if (isDateElement || isTimeElement || isQSelectDropDown) return;
if (clickedElement === null) {
await destroyInput(editingRow.value, editingField.value);
return;
}
const rowIndex = clickedElement.getAttribute('data-row-index');
const colField = clickedElement.getAttribute('data-col-field');
const column = $props.columns.find((col) => col.name === colField);
if (editingRow.value !== null && editingField.value !== null) {
if (editingRow.value == rowIndex && editingField.value == colField) return;
await destroyInput(editingRow.value, editingField.value);
}
if (isEditableColumn(column)) {
await renderInput(Number(rowIndex), colField, clickedElement);
}
};
async function handleTabKey(event, rowIndex, colField) {
if (editingRow.value == rowIndex && editingField.value == colField)
await destroyInput(editingRow.value, editingField.value);
const direction = event.shiftKey ? -1 : 1;
const { nextRowIndex, nextColumnName } = await handleTabNavigation(
rowIndex,
colField,
direction,
);
if (nextRowIndex < 0 || nextRowIndex >= arrayData.store.data.length) return;
event.preventDefault();
await renderInput(nextRowIndex, nextColumnName, null);
}
async function renderInput(rowId, field, clickedElement) {
editingField.value = field;
editingRow.value = rowId;
const originalColumn = $props.columns.find((col) => col.name === field);
const column = { ...originalColumn, ...{ label: '' } };
const row = CrudModelRef.value.formData[rowId];
const oldValue = CrudModelRef.value.formData[rowId][column?.name];
if (!clickedElement)
clickedElement = document.querySelector(
`[data-row-index="${rowId}"][data-col-field="${field}"]`,
);
Array.from(clickedElement.childNodes).forEach((child) => {
child.style.visibility = 'hidden';
child.style.position = 'relative';
});
const isSelect = selectRegex.test(column?.component);
if (isSelect) column.attrs = { ...column.attrs, 'emit-value': false };
const node = h(VnColumn, {
row: row,
class: 'temp-input',
column: column,
modelValue: row[column.name],
componentProp: 'columnField',
autofocus: true,
focusOnMount: true,
eventHandlers: {
'update:modelValue': async (value) => {
if (isSelect && value) {
await updateSelectValue(value, column, row, oldValue);
} else row[column.name] = value;
await column?.cellEvent?.['update:modelValue']?.(value, oldValue, row);
},
keyup: async (event) => {
if (event.key === 'Enter')
await destroyInput(rowId, field, clickedElement);
},
keydown: async (event) => {
switch (event.key) {
case 'Tab':
await handleTabKey(event, rowId, field);
event.stopPropagation();
break;
case 'Escape':
await destroyInput(rowId, field, clickedElement);
break;
default:
break;
}
},
click: (event) => {
column?.cellEvent?.['click']?.(event, row);
},
},
});
node.appContext = app._context;
render(node, clickedElement);
if (['toggle'].includes(column?.component))
node.el?.querySelector('span > div').focus();
if (['checkbox', undefined].includes(column?.component))
node.el?.querySelector('span > div > div').focus();
}
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)
clickedElement = document.querySelector(
`[data-row-index="${rowIndex}"][data-col-field="${field}"]`,
);
if (clickedElement) {
await nextTick();
render(null, clickedElement);
Array.from(clickedElement.childNodes).forEach((child) => {
child.style.visibility = 'visible';
child.style.position = '';
});
}
if (editingRow.value !== rowIndex || editingField.value !== field) return;
editingRow.value = null;
editingField.value = null;
}
async function handleTabNavigation(rowIndex, colName, direction) {
const columns = $props.columns;
const totalColumns = columns.length;
let currentColumnIndex = columns.findIndex((col) => col.name === colName);
let iterations = 0;
let newColumnIndex = currentColumnIndex;
do {
iterations++;
newColumnIndex = (newColumnIndex + direction + totalColumns) % totalColumns;
if (isEditableColumn(columns[newColumnIndex])) break;
} while (iterations < totalColumns);
if (iterations >= totalColumns + 1) return;
if (direction === 1 && newColumnIndex <= currentColumnIndex) {
rowIndex++;
} else if (direction === -1 && newColumnIndex >= currentColumnIndex) {
rowIndex--;
}
return { nextRowIndex: rowIndex, nextColumnName: columns[newColumnIndex].name };
}
function getCheckboxIcon(value) {
switch (typeof value) {
case 'boolean':
return value ? 'check' : 'close';
case 'number':
return value === 0 ? 'close' : 'check';
case 'undefined':
return 'indeterminate_check_box';
default:
return 'indeterminate_check_box';
}
}
function getToggleIcon(value) {
if (value === null) return 'help_outline';
return value ? 'toggle_on' : 'toggle_off';
}
function formatColumnValue(col, row, dashIfEmpty) {
if (col?.format || row[col?.name + 'VnTableTextValue']) {
if (selectRegex.test(col?.component) && row[col?.name + 'VnTableTextValue']) {
return dashIfEmpty(row[col?.name + 'VnTableTextValue']);
} else {
return col.format(row, dashIfEmpty);
}
}
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]);
}
function cardClick(_, row) {
if ($props.redirect) router.push({ path: `/${$props.redirect}/${row.id}` });
}
function removeTextValue(data, getChanges) {
let changes = data.updates;
if (!changes) return data;
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>
<template>
<RightMenu v-if="$props.rightSearch" :overlay="overlay">
<template #right-panel>
<QDrawer
v-if="$props.rightSearch"
v-model="stateStore.rightDrawer"
side="right"
:width="256"
show-if-above
>
<QScrollArea class="fit">
<VnTableFilter
:data-key="$attrs['data-key']"
:columns="columns"
@ -643,17 +333,16 @@ const rowCtrlClickFunction = computed(() => {
<slot :name="slotName" v-bind="slotData ?? {}" :key="slotName" />
</template>
</VnTableFilter>
</template>
</RightMenu>
</QScrollArea>
</QDrawer>
<CrudModel
v-bind="$attrs"
:class="$attrs['class'] ?? 'q-px-md'"
:limit="$attrs['limit'] ?? 100"
:limit="$attrs['limit'] ?? 20"
ref="CrudModelRef"
@on-fetch="(...args) => emit('onFetch', ...args)"
:search-url="searchUrl"
:disable-infinite-scroll="isTableMode"
:before-save-fn="removeTextValue"
@save-changes="reload"
:has-sub-toolbar="$props.hasSubToolbar ?? isEditable"
:auto-load="hasParams || $attrs['auto-load']"
@ -665,12 +354,8 @@ const rowCtrlClickFunction = computed(() => {
<QTable
ref="tableRef"
v-bind="table"
:class="[
'vnTable',
table ? 'selection-cell' : '',
$props.footer ? 'last-row-sticky' : '',
]"
wrap-cells
class="vnTable"
:class="{ 'last-row-sticky': $props.footer }"
:columns="splittedColumns.columns"
:rows="rows"
v-model:selected="selected"
@ -681,17 +366,14 @@ const rowCtrlClickFunction = computed(() => {
:style="isTableMode && `max-height: ${tableHeight}`"
:virtual-scroll="isTableMode"
@virtual-scroll="handleScroll"
@row-click="(event, row) => handleRowClick(event, row)"
@row-click="(_, row) => rowClickFunction && rowClickFunction(row)"
@update:selected="emit('update:selected', $event)"
@selection="(details) => handleSelection(details, rows)"
:hide-selected-banner="true"
:data-cy="$props.dataCy ?? 'vnTable'"
>
<template #top-left v-if="!$props.withoutHeader">
<slot name="top-left"> </slot>
<slot name="top-left"></slot>
</template>
<template #top-right v-if="!$props.withoutHeader">
<slot name="top-right"></slot>
<VnVisibleColumn
v-if="isTableMode"
v-model="splittedColumns.columns"
@ -699,50 +381,49 @@ const rowCtrlClickFunction = computed(() => {
:skip="columnsVisibilitySkipped"
/>
<QBtnToggle
v-if="!tableModes.some((mode) => mode.disable)"
v-model="mode"
toggle-color="primary"
class="bg-vn-section-color"
dense
: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 #header-cell="{ col }">
<QTh
v-if="col.visible ?? true"
v-bind:class="col.headerClass"
class="body-cell"
:style="col?.width ? `max-width: ${col?.width}` : ''"
:style="col.headerStyle"
:class="col.headerClass"
>
<div
class="no-padding"
:style="[
withFilters && $props.columnSearch ? 'height: 75px' : '',
]"
class="column ellipsis"
:class="`text-${col?.align ?? 'left'}`"
:style="$props.columnSearch ? 'height: 75px' : ''"
>
<div style="height: 30px">
<div class="row items-center no-wrap" style="height: 30px">
<QTooltip v-if="col.toolTip">{{ col.toolTip }}</QTooltip>
<VnTableOrder
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:label="col?.labelAbbreviation ?? col?.label"
:label="col?.label"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:align="getColAlign(col)"
/>
</div>
<VnFilter
v-if="
$props.columnSearch &&
col.columnSearch !== false &&
withFilters
"
v-if="$props.columnSearch"
:column="col"
:show-title="true"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
customClass="header-filter"
class="full-width"
/>
</div>
</QTh>
@ -760,67 +441,32 @@ const rowCtrlClickFunction = computed(() => {
</QTd>
</template>
<template #body-cell="{ col, row, rowIndex }">
<!-- Columns -->
<QTd
class="no-margin q-px-xs"
auto-width
class="no-margin"
:class="[getColAlign(col), col.columnClass]"
:style="col.style"
v-if="col.visible ?? true"
:style="{
'max-width': col?.width ?? false,
position: 'relative',
}"
:class="[
col.columnClass,
'body-cell no-margin no-padding',
getColAlign(col),
]"
:data-row-index="rowIndex"
:data-col-field="col?.name"
@click.ctrl="
($event) =>
rowCtrlClickFunction && rowCtrlClickFunction($event, row)
"
>
<div
class="no-padding no-margin peter"
style="
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
"
<slot
:name="`column-${col.name}`"
:col="col"
:row="row"
:row-index="rowIndex"
>
<slot
:name="`column-${col.name}`"
:col="col"
<VnTableColumn
:column="col"
:row="row"
:row-index="rowIndex"
>
<QIcon
v-if="col?.component === 'toggle'"
:name="
col?.getIcon
? col.getIcon(row[col?.name])
: getToggleIcon(row[col?.name])
"
style="color: var(--vn-text-color)"
:class="hasEditableFormat(col)"
size="14px"
/>
<QIcon
v-else-if="col?.component === 'checkbox'"
:name="getCheckboxIcon(row[col?.name])"
style="color: var(--vn-text-color)"
:class="hasEditableFormat(col)"
size="14px"
/>
<span
v-else
:class="hasEditableFormat(col)"
:style="
typeof col?.style == 'function'
? col.style(row)
: col?.style
"
style="bottom: 0"
>
{{ formatColumnValue(col, row, dashIfEmpty) }}
</span>
</slot>
</div>
:is-editable="col.isEditable ?? isEditable"
v-model="row[col.name]"
component-prop="columnField"
/>
</slot>
</QTd>
</template>
<template #body-cell-tableActions="{ col, row }">
@ -834,6 +480,7 @@ const rowCtrlClickFunction = computed(() => {
<QBtn
v-for="(btn, index) of col.actions"
v-show="btn.show ? btn.show(row) : true"
v-bind="row.attrs"
:key="index"
:title="btn.title"
:icon="btn.icon"
@ -841,7 +488,7 @@ const rowCtrlClickFunction = computed(() => {
flat
dense
:class="
btn.isPrimary ? 'text-primary-light' : 'color-vn-label'
btn.isPrimary ? 'text-primary-light' : 'color-vn-text '
"
:style="`visibility: ${
((btn.show && btn.show(row)) ?? true)
@ -849,19 +496,24 @@ const rowCtrlClickFunction = computed(() => {
: 'hidden'
}`"
@click="btn.action(row)"
:data-cy="btn?.name ?? `tableAction-${index}`"
:disable="btn.disable ? btn.disable(row) : true"
/>
</QTd>
</template>
<template #item="{ row, colsMap }">
<component
v-bind:is="'div'"
@click="(event) => cardClick(event, row)"
:is="$props.redirect ? 'router-link' : 'span'"
:to="`/${$props.redirect}/` + row.id"
>
<QCard
bordered
flat
class="row no-wrap justify-between cursor-pointer q-pa-sm"
@click="
(_, row) => {
$props.rowClick && $props.rowClick(row);
}
"
style="height: 100%"
>
<QCardSection
@ -898,7 +550,7 @@ const rowCtrlClickFunction = computed(() => {
</QCardSection>
<!-- Fields -->
<QCardSection
class="q-pl-sm q-py-xs"
class="q-pl-sm q-pr-lg q-py-xs"
:class="$props.cardClass"
>
<div
@ -919,7 +571,7 @@ const rowCtrlClickFunction = computed(() => {
:row="row"
:row-index="index"
>
<VnColumn
<VnTableColumn
:column="col"
:row="row"
:is-editable="false"
@ -945,14 +597,13 @@ const rowCtrlClickFunction = computed(() => {
:key="index"
:title="btn.title"
:icon="btn.icon"
data-cy="cardBtn"
class="q-pa-xs"
flat
:class="
btn.isPrimary
? 'text-primary-light'
: 'color-vn-label'
: 'color-vn-text '
"
flat
@click="btn.action(row)"
/>
</QCardSection>
@ -960,17 +611,14 @@ const rowCtrlClickFunction = computed(() => {
</component>
</template>
<template #bottom-row="{ cols }" v-if="$props.footer">
<QTr v-if="rows.length" style="height: 45px">
<QTh v-if="table.selection" />
<QTr v-if="rows.length" style="height: 30px">
<QTh
v-for="col of cols.filter((cols) => cols.visible ?? true)"
:key="col?.id"
class="text-center"
:class="getColAlign(col)"
>
<slot
:name="`column-footer-${col.name}`"
:isEditableColumn="isEditableColumn(col)"
/>
<slot :name="`column-footer-${col.name}`" />
</QTh>
</QTr>
</template>
@ -1014,51 +662,32 @@ const rowCtrlClickFunction = computed(() => {
{{ createForm?.title }}
</QTooltip>
</QPageSticky>
<QDialog
v-model="showForm"
transition-show="scale"
transition-hide="scale"
:full-width="createComplement?.isFullWidth ?? false"
data-cy="vn-table-create-dialog"
>
<QDialog v-model="showForm" transition-show="scale" transition-hide="scale">
<FormModelPopup
ref="createRef"
v-bind="createForm"
:model="$attrs['data-key'] + 'Create'"
@on-data-saved="(_, res) => createForm.onDataSaved(res)"
>
<template #form-inputs="{ data }">
<div :style="createComplement?.containerStyle">
<div
:style="createComplement?.previousStyle"
v-if="!quasar.screen.xs"
<div class="grid-create">
<slot
v-for="column of splittedColumns.create"
:key="column.name"
:name="`column-create-${column.name}`"
:data="data"
:column-name="column.name"
:label="column.label"
>
<slot name="previous-create-dialog" :data="data" />
</div>
<div class="grid-create" :style="createComplement?.columnGridStyle">
<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
:column="{
...column,
...{ disable: column?.createDisable ?? false },
}"
: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>
<VnTableColumn
:column="column"
:row="{}"
default="input"
v-model="data[column.name]"
:show-label="true"
component-prop="columnCreate"
/>
</slot>
<slot name="more-create-dialog" :data="data" />
</div>
</template>
</FormModelPopup>
@ -1076,42 +705,6 @@ es:
</i18n>
<style lang="scss">
.selection-cell {
table td:first-child {
padding: 0px;
}
}
.side-padding {
padding-left: 1px;
padding-right: 1px;
}
.editable-text:hover {
border-bottom: 1px dashed var(--q-primary);
@extend .side-padding;
}
.editable-text {
border-bottom: 1px dashed var(--vn-label-color);
@extend .side-padding;
}
.cell-input {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding-top: 0px !important;
}
.q-field--labeled .q-field__native,
.q-field--labeled .q-field__prefix,
.q-field--labeled .q-field__suffix {
padding-top: 20px;
}
.body-cell {
padding-left: 4px !important;
padding-right: 4px !important;
position: relative;
}
.bg-chip-secondary {
background-color: var(--vn-page-color);
color: var(--vn-text-color);
@ -1128,8 +721,8 @@ es:
.grid-three {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, max-content));
width: 100%;
grid-template-columns: repeat(auto-fit, minmax(350px, max-content));
max-width: 100%;
grid-gap: 20px;
margin: 0 auto;
}
@ -1137,6 +730,7 @@ es:
.grid-create {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, max-content));
max-width: 100%;
grid-gap: 20px;
margin: 0 auto;
}
@ -1152,9 +746,7 @@ es:
}
}
}
.q-table tbody tr td {
position: relative;
}
.q-table {
th {
padding: 0;
@ -1203,7 +795,6 @@ es:
.vn-label-value {
display: flex;
flex-direction: row;
align-items: center;
color: var(--vn-text-color);
.value {
overflow: hidden;
@ -1255,15 +846,4 @@ es:
.q-table__middle.q-virtual-scroll.q-virtual-scroll--vertical.scroll {
background-color: var(--vn-section-color);
}
.temp-input {
top: 0;
position: absolute;
width: 100%;
height: 100%;
display: flex;
}
label.header-filter > .q-field__inner > .q-field__control {
padding: inherit;
}
</style>

View File

@ -29,29 +29,25 @@ function columnName(col) {
<VnFilterPanel v-bind="$attrs" :search-button="true" :disable-submit-event="true">
<template #body="{ params, orders, searchFn }">
<div
class="container"
class="row no-wrap flex-center"
v-for="col of columns.filter((c) => c.columnFilter ?? true)"
:key="col.id"
>
<div class="filter">
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
</div>
<div class="order">
<VnTableOrder
v-if="col?.columnFilter !== false && col?.name !== 'tableActions'"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="true"
/>
</div>
<VnFilter
ref="tableFilterRef"
:column="col"
:data-key="$attrs['data-key']"
v-model="params[columnName(col)]"
:search-url="searchUrl"
/>
<VnTableOrder
v-if="col?.columnFilter !== false && col?.name !== 'tableActions'"
v-model="orders[col.orderBy ?? col.name]"
:name="col.orderBy ?? col.name"
:data-key="$attrs['data-key']"
:search-url="searchUrl"
:vertical="true"
/>
</div>
<slot
name="moreFilterPanel"
@ -72,21 +68,3 @@ function columnName(col) {
</template>
</VnFilterPanel>
</template>
<style lang="scss" scoped>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 45px;
gap: 10px;
}
.filter {
width: 70%;
height: 40px;
text-align: center;
}
.order {
width: 10%;
}
</style>

View File

@ -32,21 +32,16 @@ const areAllChecksMarked = computed(() => {
function setUserConfigViewData(data, isLocal) {
if (!data) return;
// Importante: El name de las columnas de la tabla debe conincidir con el name de las variables que devuelve la view config
if (!isLocal) localColumns.value = [];
// Array to Object
const skippeds = $props.skip.reduce((a, v) => ({ ...a, [v]: v }), {});
for (let column of columns.value) {
const { label, name, labelAbbreviation } = column;
const { label, name } = column;
if (skippeds[name]) continue;
column.visible = data[name] ?? true;
if (!isLocal)
localColumns.value.push({
name,
label,
labelAbbreviation,
visible: column.visible,
});
if (!isLocal) localColumns.value.push({ name, label, visible: column.visible });
}
}
@ -157,11 +152,7 @@ onMounted(async () => {
<QCheckbox
v-for="col in localColumns"
:key="col.name"
:label="
col?.labelAbbreviation
? col.labelAbbreviation + ` (${col.label ?? col.name})`
: (col.label ?? col.name)
"
:label="col.label ?? col.name"
v-model="col.visible"
/>
</div>

View File

@ -27,58 +27,30 @@ describe('VnTable', () => {
beforeEach(() => (vm.selected = []));
describe('handleSelection()', () => {
const rows = [
{ $index: 0 },
{ $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 }];
const rows = [{ $index: 0 }, { $index: 1 }, { $index: 2 }];
const selectedRows = [{ $index: 1 }];
it('should add rows to selected when shift key is pressed and rows are added except last one', () => {
vm.handleSelection(
{ evt: { shiftKey: true }, added: true, rows: selectedRows },
rows,
rows
);
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', () => {
const selectedRows = [{ $index: 1 }];
vm.handleSelection(
{ evt: { shiftKey: false }, added: true, rows: selectedRows },
rows,
rows
);
expect(vm.selected).toEqual([]);
});
it('should not add rows to selected when rows are not added', () => {
const selectedRows = [{ $index: 1 }];
vm.handleSelection(
{ evt: { shiftKey: true }, added: false, rows: selectedRows },
rows,
rows
);
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: '',
},
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
wrapper=wrapper.wrapper;
vm=wrapper.vm;
});
beforeEach(() => {
@ -143,14 +143,14 @@ describe('CrudModel', () => {
});
it('should return true if object is empty', async () => {
dummyObj = {};
result = vm.isEmpty(dummyObj);
dummyObj ={};
result = vm.isEmpty(dummyObj);
expect(result).toBe(true);
});
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);
expect(result).toBe(false);
@ -158,31 +158,29 @@ describe('CrudModel', () => {
it('should return true if array is empty', async () => {
dummyArray = [];
result = vm.isEmpty(dummyArray);
result = vm.isEmpty(dummyArray);
expect(result).toBe(true);
});
it('should return false if array is not empty', async () => {
dummyArray = [1, 2, 3];
dummyArray = [1,2,3];
result = vm.isEmpty(dummyArray);
expect(result).toBe(false);
});
})
});
describe('resetData()', () => {
it('should add $index to elements in data[] and sets originalData and formData with data', async () => {
data = [
{
name: 'Tony',
lastName: 'Stark',
age: 42,
},
];
data = [{
name: 'Tony',
lastName: 'Stark',
age: 42,
}];
vm.resetData(data);
expect(vm.originalData).toEqual(data);
expect(vm.originalData[0].$index).toEqual(0);
expect(vm.formData).toEqual(data);
@ -202,7 +200,7 @@ describe('CrudModel', () => {
lastName: 'Stark',
age: 42,
};
vm.resetData(data);
expect(vm.originalData).toEqual(data);
@ -212,19 +210,17 @@ describe('CrudModel', () => {
});
describe('saveChanges()', () => {
data = [
{
name: 'Tony',
lastName: 'Stark',
age: 42,
},
];
data = [{
name: 'Tony',
lastName: 'Stark',
age: 42,
}];
it('should call saveFn if exists', async () => {
await wrapper.setProps({ saveFn: vi.fn() });
vm.saveChanges(data);
expect(vm.saveFn).toHaveBeenCalledOnce();
expect(vm.isLoading).toBe(false);
expect(vm.hasChanges).toBe(false);
@ -233,15 +229,13 @@ describe('CrudModel', () => {
});
it("should use default url if there's not saveFn", async () => {
const postMock = vi.spyOn(axios, 'post');
vm.formData = [
{
name: 'Bruce',
lastName: 'Wayne',
age: 45,
},
];
const postMock =vi.spyOn(axios, 'post');
vm.formData = [{
name: 'Bruce',
lastName: 'Wayne',
age: 45,
}]
await vm.saveChanges(data);

View File

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

View File

@ -1,65 +1,61 @@
import { vi, describe, expect, it, beforeEach, afterEach } from 'vitest';
import { vi, describe, expect, it, beforeEach, beforeAll, afterEach } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper';
import UserPanel from 'src/components/UserPanel.vue';
import axios from 'axios';
import { useState } from 'src/composables/useState';
vi.mock('src/utils/quasarLang', () => ({
default: vi.fn(),
}));
describe('UserPanel', () => {
let wrapper;
let vm;
let state;
let wrapper;
let vm;
let state;
beforeEach(() => {
wrapper = createWrapper(UserPanel, {});
state = useState();
state.setUser({
id: 115,
name: 'itmanagement',
nickname: 'itManagementNick',
lang: 'en',
darkMode: false,
companyFk: 442,
warehouseFk: 1,
beforeEach(() => {
wrapper = createWrapper(UserPanel, {});
state = useState();
state.setUser({
id: 115,
name: 'itmanagement',
nickname: 'itManagementNick',
lang: 'en',
darkMode: false,
companyFk: 442,
warehouseFk: 1,
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
});
wrapper = wrapper.wrapper;
vm = wrapper.vm;
});
afterEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.clearAllMocks();
});
it('should fetch warehouses data on mounted', async () => {
const fetchData = wrapper.findComponent({ name: 'FetchData' });
expect(fetchData.props('url')).toBe('Warehouses');
expect(fetchData.props('autoLoad')).toBe(true);
});
it('should fetch warehouses data on mounted', async () => {
const fetchData = wrapper.findComponent({ name: 'FetchData' });
expect(fetchData.props('url')).toBe('Warehouses');
expect(fetchData.props('autoLoad')).toBe(true);
});
it('should toggle dark mode correctly and update preferences', async () => {
await vm.saveDarkMode(true);
expect(axios.patch).toHaveBeenCalledWith('/UserConfigs/115', { darkMode: true });
expect(vm.user.darkMode).toBe(true);
await vm.updatePreferences();
expect(vm.darkMode).toBe(true);
});
it('should toggle dark mode correctly and update preferences', async () => {
await vm.saveDarkMode(true);
expect(axios.patch).toHaveBeenCalledWith('/UserConfigs/115', { darkMode: true });
expect(vm.user.darkMode).toBe(true);
vm.updatePreferences();
expect(vm.darkMode).toBe(true);
});
it('should change user language and update preferences', async () => {
const userLanguage = 'es';
await vm.saveLanguage(userLanguage);
expect(axios.patch).toHaveBeenCalledWith('/VnUsers/115', { lang: userLanguage });
expect(vm.user.lang).toBe(userLanguage);
await vm.updatePreferences();
expect(vm.locale).toBe(userLanguage);
});
it('should change user language and update preferences', async () => {
const userLanguage = 'es';
await vm.saveLanguage(userLanguage);
expect(axios.patch).toHaveBeenCalledWith('/VnUsers/115', { lang: userLanguage });
expect(vm.user.lang).toBe(userLanguage);
vm.updatePreferences();
expect(vm.locale).toBe(userLanguage);
});
it('should update user data', async () => {
const key = 'name';
const value = 'itboss';
await vm.saveUserData(key, value);
expect(axios.post).toHaveBeenCalledWith('UserConfigs/setUserConfig', { [key]: value });
});
});
it('should update user data', async () => {
const key = 'name';
const value = 'itboss';
await vm.saveUserData(key, value);
expect(axios.post).toHaveBeenCalledWith('UserConfigs/setUserConfig', { [key]: value });
});
});

View File

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

View File

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

View File

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

View File

@ -1,9 +1,10 @@
<script setup>
import { onBeforeMount } from 'vue';
import { useRouter, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue-router';
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({
@ -26,13 +27,7 @@ const arrayData = useArrayData(props.dataKey, {
oneRecord: true,
});
onBeforeRouteLeave(() => {
stateStore.cardDescriptorChangeValue(null);
});
onBeforeMount(async () => {
stateStore.cardDescriptorChangeValue(props.descriptor);
const route = router.currentRoute.value;
try {
await fetch(route.params.id);
@ -44,13 +39,6 @@ onBeforeMount(async () => {
});
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;
if (id !== from.params.id) await fetch(id, true);
});
@ -62,11 +50,13 @@ async function fetch(id, append = false) {
else arrayData.store.url = props.url.replace(regex, `/${id}`);
await arrayData.fetch({ append, updateRouter: false });
}
function hasRouteParam(params, valueToCheck = ':addressId') {
return Object.values(params).includes(valueToCheck);
}
</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" />

View File

@ -1,43 +0,0 @@
<script setup>
import { computed } from 'vue';
const model = defineModel({ type: [Number, Boolean] });
const $props = defineProps({
info: {
type: String,
default: null,
},
});
const checkboxModel = computed({
get() {
if (typeof model.value === 'number') {
return model.value !== 0;
}
return model.value;
},
set(value) {
if (typeof model.value === 'number') {
model.value = value ? 1 : 0;
} else {
model.value = value;
}
},
});
</script>
<template>
<div>
<QCheckbox v-bind="$attrs" v-model="checkboxModel" />
<QIcon
v-if="info"
v-bind="$attrs"
class="cursor-info q-ml-sm"
name="info"
size="sm"
>
<QTooltip>
{{ info }}
</QTooltip>
</QIcon>
</div>
</template>

View File

@ -1,32 +0,0 @@
<script setup>
const $props = defineProps({
colors: {
type: String,
default: '{"value": []}',
},
});
const colorArray = JSON.parse($props.colors)?.value;
const maxHeight = 30;
const colorHeight = maxHeight / colorArray?.length;
</script>
<template>
<div v-if="colors" class="color-div" :style="{ height: `${maxHeight}px` }">
<div
v-for="(color, index) in colorArray"
:key="index"
:style="{
backgroundColor: `#${color}`,
height: `${colorHeight}px`,
}"
>
&nbsp;
</div>
</div>
</template>
<style scoped>
.color-div {
display: flex;
flex-direction: column;
}
</style>

View File

@ -17,8 +17,6 @@ const $props = defineProps({
},
});
const emit = defineEmits(['blur']);
const componentArray = computed(() => {
if (typeof $props.prop === 'object') return [$props.prop];
return $props.prop;
@ -48,8 +46,7 @@ function toValueAttrs(attrs) {
<span
v-for="toComponent of componentArray"
:key="toComponent.name"
class="column fit"
:class="toComponent?.component == 'checkbox' ? 'flex-center' : ''"
class="column flex-center fit"
>
<component
v-if="toComponent?.component"
@ -57,7 +54,6 @@ function toValueAttrs(attrs) {
v-bind="mix(toComponent).attrs"
v-on="mix(toComponent).event ?? {}"
v-model="model"
@blur="emit('blur')"
/>
</span>
</template>

View File

@ -11,7 +11,6 @@ const emit = defineEmits([
'update:options',
'keyup.enter',
'remove',
'blur',
]);
const $props = defineProps({
@ -83,7 +82,7 @@ const mixinRules = [
requiredFieldRule,
...($attrs.rules ?? []),
(val) => {
const maxlength = $props.maxlength;
const { maxlength } = vnInputRef.value;
if (maxlength && +val.length > maxlength)
return t(`maxLength`, { value: maxlength });
const { min, max } = vnInputRef.value.$attrs;
@ -108,7 +107,7 @@ const handleInsertMode = (e) => {
e.preventDefault();
const input = e.target;
const cursorPos = input.selectionStart;
const maxlength = $props.maxlength;
const { maxlength } = vnInputRef.value;
let currentValue = value.value;
if (!currentValue) currentValue = e.key;
const newValue = e.key;
@ -137,15 +136,14 @@ const handleUppercase = () => {
:type="$attrs.type"
:class="{ required: isRequired }"
@keyup.enter="emit('keyup.enter')"
@blur="emit('blur')"
@keydown="handleKeydown"
:clearable="false"
:rules="mixinRules"
:lazy-rules="true"
hide-bottom-space
:data-cy="($attrs['data-cy'] ?? $attrs.label) + '_input'"
:data-cy="$attrs.dataCy ?? $attrs.label + '_input'"
>
<template #prepend v-if="$slots.prepend">
<template #prepend>
<slot name="prepend" />
</template>
<template #append>
@ -170,11 +168,11 @@ const handleUppercase = () => {
}
"
></QIcon>
<QIcon
name="match_case"
size="xs"
v-if="!$attrs.disabled && !$attrs.readonly && $props.uppercase"
v-if="!$attrs.disabled && !($attrs.readonly) && $props.uppercase"
@click="handleUppercase"
class="uppercase-icon"
>
@ -182,7 +180,7 @@ const handleUppercase = () => {
{{ t('Convert to uppercase') }}
</QTooltip>
</QIcon>
<slot name="append" v-if="$slots.append && !$attrs.disabled" />
<QIcon v-if="info" name="info">
<QTooltip max-width="350px">
@ -196,15 +194,13 @@ const handleUppercase = () => {
<style>
.uppercase-icon {
transition:
color 0.3s,
transform 0.2s;
cursor: pointer;
transition: color 0.3s, transform 0.2s;
cursor: pointer;
}
.uppercase-icon:hover {
color: #ed9937;
transform: scale(1.2);
color: #ed9937;
transform: scale(1.2);
}
</style>
<i18n>
@ -218,4 +214,4 @@ const handleUppercase = () => {
maxLength: El valor excede los {value} carácteres
inputMax: Debe ser menor a {value}
Convert to uppercase: Convertir a mayúsculas
</i18n>
</i18n>

View File

@ -42,7 +42,7 @@ const formattedDate = computed({
if (value.at(2) == '/') value = value.split('/').reverse().join('/');
value = date.formatDate(
new Date(value).toISOString(),
'YYYY-MM-DDTHH:mm:ss.SSSZ',
'YYYY-MM-DDTHH:mm:ss.SSSZ'
);
}
const [year, month, day] = value.split('-').map((e) => parseInt(e));
@ -55,7 +55,7 @@ const formattedDate = computed({
orgDate.getHours(),
orgDate.getMinutes(),
orgDate.getSeconds(),
orgDate.getMilliseconds(),
orgDate.getMilliseconds()
);
}
}
@ -64,7 +64,7 @@ const formattedDate = computed({
});
const popupDate = computed(() =>
model.value ? date.formatDate(new Date(model.value), 'YYYY/MM/DD') : model.value,
model.value ? date.formatDate(new Date(model.value), 'YYYY/MM/DD') : model.value
);
onMounted(() => {
// fix quasar bug
@ -73,7 +73,7 @@ onMounted(() => {
watch(
() => model.value,
(val) => (formattedDate.value = val),
{ immediate: true },
{ immediate: true }
);
const styleAttrs = computed(() => {
@ -107,7 +107,6 @@ const manageDate = (date) => {
@click="isPopupOpen = !isPopupOpen"
@keydown="isPopupOpen = false"
hide-bottom-space
:data-cy="$attrs.dataCy ?? $attrs.label + '_inputDate'"
>
<template #append>
<QIcon

View File

@ -8,7 +8,6 @@ defineProps({
});
const model = defineModel({ type: [Number, String] });
const emit = defineEmits(['blur']);
</script>
<template>
<VnInput
@ -25,6 +24,5 @@ const emit = defineEmits(['blur']);
model = parseFloat(val).toFixed(decimalPlaces);
}
"
@blur="emit('blur')"
/>
</template>

View File

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

View File

@ -641,7 +641,15 @@ watch(
>
{{ prop.nameI18n }}:
</span>
<VnJsonValue :value="prop.val.val" />
<span
v-if="prop.val.id"
class="id-value"
>
#{{ prop.val.id }}
</span>
<span v-if="log.action == 'update'">
<VnJsonValue
:value="prop.old.val"
/>
@ -651,26 +659,6 @@ watch(
>
#{{ prop.old.id }}
</span>
<VnJsonValue
:value="prop.val.val"
/>
<span
v-if="prop.val.id"
class="id-value"
>
#{{ prop.val.id }}
</span>
</span>
<span v-else="prop.old.val">
<VnJsonValue
:value="prop.val.val"
/>
<span
v-if="prop.old.id"
class="id-value"
>#{{ prop.old.id }}</span
>
</span>
</div>
</span>

View File

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

View File

@ -1,38 +0,0 @@
<script setup>
import { ref } from 'vue';
defineProps({
label: {
type: String,
default: '',
},
icon: {
type: String,
required: true,
default: null,
},
color: {
type: String,
default: 'primary',
},
tooltip: {
type: String,
default: null,
},
});
const popupProxyRef = ref(null);
</script>
<template>
<QBtn :color="$props.color" :icon="$props.icon" :label="$t($props.label)">
<template #default>
<slot name="extraIcon"></slot>
<QPopupProxy ref="popupProxyRef" style="max-width: none">
<QCard>
<slot :popup="popupProxyRef"></slot>
</QCard>
</QPopupProxy>
<QTooltip>{{ $t($props.tooltip) }}</QTooltip>
</template>
</QBtn>
</template>

View File

@ -14,7 +14,7 @@ const $props = defineProps({
},
});
const options = ref([]);
const emit = defineEmits(['blur']);
onBeforeMount(async () => {
const { url, optionValue, optionLabel } = useAttrs();
const findBy = $props.find ?? url?.charAt(0)?.toLocaleLowerCase() + url?.slice(1, -1);
@ -35,5 +35,5 @@ onBeforeMount(async () => {
});
</script>
<template>
<VnSelect v-bind="$attrs" :options="$attrs.options ?? options" @blur="emit('blur')" />
<VnSelect v-bind="$attrs" :options="$attrs.options ?? options" />
</template>

View File

@ -37,6 +37,7 @@ const isAllowedToCreate = computed(() => {
defineExpose({ vnSelectDialogRef: select });
</script>
<template>
<VnSelect
ref="select"
@ -66,6 +67,7 @@ defineExpose({ vnSelectDialogRef: select });
</template>
</VnSelect>
</template>
<style lang="scss" scoped>
.default-icon {
cursor: pointer;

View File

@ -15,7 +15,6 @@ const model = defineModel({ type: [String, Number, Object] });
:fields="['id', 'name', 'nickname', 'nif']"
:filter-options="['id', 'name', 'nickname', 'nif']"
sort-by="name ASC"
data-cy="vnSupplierSelect"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">

View File

@ -1,50 +0,0 @@
<script setup>
import VnSelectDialog from './VnSelectDialog.vue';
import FilterTravelForm from 'src/components/FilterTravelForm.vue';
import { useI18n } from 'vue-i18n';
import { toDate } from 'src/filters';
const { t } = useI18n();
const $props = defineProps({
data: {
type: Object,
required: true,
},
onFilterTravelSelected: {
type: Function,
required: true,
},
});
</script>
<template>
<VnSelectDialog
:label="t('entry.basicData.travel')"
v-bind="$attrs"
url="Travels/filter"
:fields="['id', 'warehouseInName']"
option-value="id"
option-label="warehouseInName"
map-options
hide-selected
:required="true"
action-icon="filter_alt"
:roles-allowed-to-create="['buyer']"
>
<template #form>
<FilterTravelForm @travel-selected="onFilterTravelSelected(data, $event)" />
</template>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>
{{ scope.opt?.agencyModeName }} -
{{ scope.opt?.warehouseInName }}
({{ toDate(scope.opt?.shipped) }})
{{ scope.opt?.warehouseOutName }}
({{ toDate(scope.opt?.landed) }})
</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelectDialog>
</template>

View File

@ -5,8 +5,7 @@ import SkeletonDescriptor from 'components/ui/SkeletonDescriptor.vue';
import { useArrayData } from 'composables/useArrayData';
import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useState } from 'src/composables/useState';
import { useRoute, useRouter } from 'vue-router';
import { useClipboard } from 'src/composables/useClipboard';
import { useRoute } from 'vue-router';
import VnMoreOptions from './VnMoreOptions.vue';
const $props = defineProps({
@ -30,6 +29,10 @@ const $props = defineProps({
type: String,
default: null,
},
module: {
type: String,
default: null,
},
summary: {
type: Object,
default: null,
@ -42,18 +45,13 @@ const $props = defineProps({
const state = useState();
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const { copyText } = useClipboard();
const { viewSummary } = useSummaryDialog();
let arrayData;
let store;
let entity;
const isLoading = ref(false);
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 });
onBeforeMount(async () => {
@ -80,18 +78,6 @@ 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() {
store.url = $props.url;
store.filter = $props.filter ?? {};
@ -117,45 +103,22 @@ function getValueFromPath(path) {
return current;
}
function copyIdText(id) {
copyText(id, {
component: {
copyValue: id,
},
});
}
const emit = defineEmits(['onFetch']);
const iconModule = computed(() => {
moduleName.value = getName();
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 (isSameModuleName) {
return router.options.routes[1].children.find((r) => r.name === moduleName.value)
?.children[0]?.redirect;
} else {
return route.matched[1].path.split('/').length > 2
? route.matched[1].redirect
: route.matched[1].children[0].redirect;
}
});
const iconModule = computed(() => route.matched[1].meta.icon);
const toModule = computed(() =>
route.matched[1].path.split('/').length > 2
? route.matched[1].redirect
: route.matched[1].children[0].redirect,
);
</script>
<template>
<div class="descriptor">
<template v-if="entity && !isLoading">
<div class="header bg-primary q-pa-sm justify-between">
<slot name="header-extra-action">
<QBtn
<slot name="header-extra-action"
><QBtn
round
flat
dense
@ -163,13 +126,13 @@ const toModule = computed(() => {
:icon="iconModule"
color="white"
class="link"
:to="toModule"
:to="$attrs['to-module'] ?? toModule"
>
<QTooltip>
{{ t('globals.goToModuleIndex') }}
</QTooltip>
</QBtn>
</slot>
</QBtn></slot
>
<QBtn
@click.stop="viewSummary(entity.id, $props.summary, $props.width)"
round
@ -185,7 +148,7 @@ const toModule = computed(() => {
{{ t('components.smartCard.openSummary') }}
</QTooltip>
</QBtn>
<RouterLink :to="{ name: routeName, params: { id: entity.id } }">
<RouterLink :to="{ name: `${module}Summary`, params: { id: entity.id } }">
<QBtn
class="link"
color="white"
@ -221,23 +184,10 @@ const toModule = computed(() => {
</slot>
</div>
</QItemLabel>
<QItem>
<QItemLabel class="subtitle">
<QItem dense>
<QItemLabel class="subtitle" caption>
#{{ getValueFromPath(subtitle) ?? entity.id }}
</QItemLabel>
<QBtn
round
flat
dense
size="sm"
icon="content_copy"
color="primary"
@click.stop="copyIdText(entity.id)"
>
<QTooltip>
{{ t('globals.copyId') }}
</QTooltip>
</QBtn>
</QItem>
</QList>
<div class="list-box q-mt-xs">
@ -247,11 +197,12 @@ const toModule = computed(() => {
<div class="icons">
<slot name="icons" :entity="entity" />
</div>
<div class="actions justify-center" data-cy="descriptor_actions">
<div class="actions justify-center">
<slot name="actions" :entity="entity" />
</div>
<slot name="after" />
</template>
<!-- Skeleton -->
<SkeletonDescriptor v-if="!entity || isLoading" />
</div>
<QInnerLoading
@ -343,11 +294,3 @@ const toModule = computed(() => {
}
}
</style>
<i18n>
en:
globals:
copyId: Copy ID
es:
globals:
copyId: Copiar ID
</i18n>

View File

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

View File

@ -1,32 +1,53 @@
<script setup>
defineProps({
hasImage: {
type: Boolean,
default: false,
},
});
</script>
<template>
<div id="descriptor-skeleton" class="bg-vn-page">
<div id="descriptor-skeleton">
<div class="row justify-between q-pa-sm">
<QSkeleton square size="30px" v-for="i in 3" :key="i" />
<QSkeleton square size="40px" />
<QSkeleton square size="40px" />
<QSkeleton square height="40px" width="20px" />
</div>
<div class="q-pa-xs" v-if="hasImage">
<QSkeleton square height="200px" width="100%" />
<div class="col justify-between q-pa-sm q-gutter-y-xs">
<QSkeleton square height="40px" width="150px" />
<QSkeleton square height="30px" width="70px" />
</div>
<div class="col justify-between q-pa-md q-gutter-y-xs">
<QSkeleton square height="25px" width="150px" />
<QSkeleton square height="15px" width="70px" />
</div>
<div class="q-pl-sm q-pa-sm q-mb-md">
<div class="row q-gutter-x-sm q-pa-none q-ma-none" v-for="i in 5" :key="i">
<QSkeleton type="text" square height="20px" width="30%" />
<QSkeleton type="text" square height="20px" width="60%" />
<div class="col q-pl-sm q-pa-sm q-mb-md">
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
<div class="row justify-between">
<QSkeleton type="text" square height="30px" width="20%" />
<QSkeleton type="text" square height="30px" width="60%" />
</div>
</div>
<QCardActions class="q-gutter-x-sm justify-between">
<QSkeleton size="40px" v-for="i in 5" :key="i" />
<QCardActions>
<QSkeleton size="40px" />
<QSkeleton size="40px" />
<QSkeleton size="40px" />
<QSkeleton size="40px" />
<QSkeleton size="40px" />
</QCardActions>
</div>
</template>
<style lang="scss" scoped>
#descriptor-skeleton .q-card__actions {
justify-content: space-between;
}
</style>

View File

@ -82,7 +82,7 @@ function cancel() {
@click="cancel()"
/>
</QCardSection>
<QCardSection class="q-pb-none" data-cy="VnConfirm_message">
<QCardSection class="q-pb-none">
<span v-if="message !== false" v-html="message" />
</QCardSection>
<QCardSection class="row items-center q-pt-none">
@ -95,7 +95,6 @@ function cancel() {
:disable="isLoading"
flat
@click="cancel()"
data-cy="VnConfirm_cancel"
/>
<QBtn
:label="t('globals.confirm')"

View File

@ -293,9 +293,6 @@ const getLocale = (label) => {
/>
</template>
<style scoped lang="scss">
.q-field__label.no-pointer-events.absolute.ellipsis {
margin-left: 6px !important;
}
.list {
width: 256px;
}

View File

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

View File

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

View File

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

View File

@ -1,41 +0,0 @@
<script setup>
import { toPercentage } from 'filters/index';
import { computed } from 'vue';
const props = defineProps({
value: {
type: Number,
required: true,
},
});
const valueClass = computed(() =>
props.value === 0 ? 'neutral' : props.value > 0 ? 'positive' : 'negative',
);
const iconName = computed(() =>
props.value === 0 ? 'equal' : props.value > 0 ? 'arrow_upward' : 'arrow_downward',
);
const formattedValue = computed(() => props.value);
</script>
<template>
<span :class="valueClass">
<QIcon :name="iconName" size="sm" class="value-icon" />
{{ toPercentage(formattedValue) }}
</span>
</template>
<style lang="scss" scoped>
.positive {
color: $secondary;
}
.negative {
color: $negative;
}
.neutral {
color: $primary;
}
.value-icon {
margin-right: 4px;
}
</style>

View File

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

View File

@ -1,66 +0,0 @@
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

@ -1,64 +0,0 @@
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import axios from 'axios';
import VnConfirm from 'components/ui/VnConfirm.vue';
export async function checkEntryLock(entryFk, userFk) {
const { t } = useI18n();
const quasar = useQuasar();
const { push } = useRouter();
const { data } = await axios.get(`Entries/${entryFk}`, {
params: {
filter: JSON.stringify({
fields: ['id', 'locked', 'lockerUserFk'],
include: { relation: 'user', scope: { fields: ['id', 'nickname'] } },
}),
},
});
const entryConfig = await axios.get('EntryConfigs/findOne');
if (data?.lockerUserFk && data?.locked) {
const now = new Date(Date.vnNow()).getTime();
const lockedTime = new Date(data.locked).getTime();
const timeDiff = (now - lockedTime) / 1000;
const isMaxTimeLockExceeded = entryConfig.data.maxLockTime > timeDiff;
if (data?.lockerUserFk !== userFk && isMaxTimeLockExceeded) {
quasar
.dialog({
component: VnConfirm,
componentProps: {
title: t('entry.lock.title'),
message: t('entry.lock.message', {
userName: data?.user?.nickname,
time: timeDiff / 60,
}),
},
})
.onOk(
async () =>
await axios.patch(`Entries/${entryFk}`, {
locked: Date.vnNow(),
lockerUserFk: userFk,
}),
)
.onCancel(() => {
push({ path: `summary` });
});
}
} else {
await axios
.patch(`Entries/${entryFk}`, {
locked: Date.vnNow(),
lockerUserFk: userFk,
})
.then(
quasar.notify({
message: t('entry.lock.success'),
color: 'positive',
group: false,
}),
);
}
}

View File

@ -1,22 +0,0 @@
export function getColAlign(col) {
let align;
switch (col.component) {
case 'time':
case 'date':
case 'select':
align = 'left';
break;
case 'number':
align = 'right';
break;
case 'checkbox':
align = 'center';
break;
default:
align = col?.align;
}
if (/^is[A-Z]/.test(col.name) || /^has[A-Z]/.test(col.name)) align = 'center';
return 'text-' + (align ?? 'center');
}

View File

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

View File

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

View File

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

View File

@ -27,15 +27,6 @@ export function useRole() {
return false;
}
function likeAny(roles) {
const roleStore = state.getRoles();
for (const role of roles) {
if (!roleStore.value.findIndex((rs) => rs.startsWith(role)) !== -1)
return true;
}
return false;
}
function isEmployee() {
return hasAny(['employee']);
}
@ -44,7 +35,6 @@ export function useRole() {
isEmployee,
fetch,
hasAny,
likeAny,
state,
};
}

View File

@ -21,10 +21,7 @@ body.body--light {
.q-header .q-toolbar {
color: var(--vn-text-color);
}
--vn-color-negative: $negative;
}
body.body--dark {
--vn-header-color: #5d5d5d;
--vn-page-color: #222;
@ -40,8 +37,6 @@ body.body--dark {
--vn-text-color-contrast: black;
background-color: var(--vn-page-color);
--vn-color-negative: $negative;
}
a {
@ -80,6 +75,7 @@ a {
text-decoration: underline;
}
// Removes chrome autofill background
input:-webkit-autofill,
select:-webkit-autofill {
color: var(--vn-text-color);
@ -153,6 +149,11 @@ select:-webkit-autofill {
cursor: pointer;
}
.vn-table-separation-row {
height: 16px !important;
background-color: var(--vn-section-color) !important;
}
/* Estilo para el asterisco en campos requeridos */
.q-field.required .q-field__label:after {
content: ' *';
@ -229,12 +230,10 @@ input::-webkit-inner-spin-button {
max-width: 100%;
}
.remove-bg {
filter: brightness(1.1);
mix-blend-mode: multiply;
}
.q-table__container {
/* ===== Scrollbar CSS ===== /
/ Firefox */
* {
scrollbar-width: auto;
scrollbar-color: var(--vn-label-color) transparent;
@ -275,6 +274,8 @@ input::-webkit-inner-spin-button {
font-size: 11pt;
}
td {
font-size: 11pt;
border-top: 1px solid var(--vn-page-color);
border-collapse: collapse;
}
}
@ -318,6 +319,9 @@ input::-webkit-inner-spin-button {
max-width: fit-content;
}
.row > .column:has(.q-checkbox) {
max-width: fit-content;
}
.q-field__inner {
.q-field__control {
min-height: auto !important;
@ -335,7 +339,3 @@ input::-webkit-inner-spin-button {
border: 1px solid;
box-shadow: 0 4px 6px #00000000;
}
.containerShrinked {
width: 70%;
}

View File

@ -13,7 +13,7 @@
// Tip: Use the "Theme Builder" on Quasar's documentation website.
// Tip: to add new colors https://quasar.dev/style/color-palette/#adding-your-own-colors
$primary: #ec8916;
$secondary: #89be34;
$secondary: $primary;
$positive: #c8e484;
$negative: #fb5252;
$info: #84d0e2;
@ -30,9 +30,7 @@ $color-spacer: #7979794d;
$border-thin-light: 1px solid $color-spacer-light;
$primary-light: #f5b351;
$dark-shadow-color: black;
$layout-shadow-dark:
0 0 10px 2px #00000033,
0 0px 10px #0000003d;
$layout-shadow-dark: 0 0 10px 2px #00000033, 0 0px 10px #0000003d;
$spacing-md: 16px;
$color-font-secondary: #777;
$width-xs: 400px;

View File

@ -3,8 +3,6 @@ import { useI18n } from 'vue-i18n';
export default function (value, options = {}) {
if (!value) return;
if (!isValidDate(value)) return null;
if (!options.dateStyle && !options.timeStyle) {
options.day = '2-digit';
options.month = '2-digit';
@ -12,12 +10,7 @@ export default function (value, options = {}) {
}
const { locale } = useI18n();
const newDate = new Date(value);
const date = new Date(value);
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());
return new Intl.DateTimeFormat(locale.value, options).format(date);
}

View File

@ -33,7 +33,6 @@ globals:
reset: Reset
close: Close
cancel: Cancel
isSaveAndContinue: Save and continue
clone: Clone
confirm: Confirm
assign: Assign
@ -49,7 +48,6 @@ globals:
rowRemoved: Row removed
pleaseWait: Please wait...
noPinnedModules: You don't have any pinned modules
enterToConfirm: Press Enter to confirm
summary:
basicData: Basic data
daysOnward: Days onward
@ -153,12 +151,10 @@ globals:
maxTemperature: Max
minTemperature: Min
changePass: Change password
setPass: Set password
deleteConfirmTitle: Delete selected elements
changeState: Change state
raid: 'Raid {daysInForward} days'
isVies: Vies
noData: No data available
pageTitles:
logIn: Login
addressEdit: Update address
@ -171,7 +167,6 @@ globals:
workCenters: Work centers
modes: Modes
zones: Zones
negative: Negative
zonesList: List
deliveryDays: Delivery days
upcomingDeliveries: Upcoming deliveries
@ -179,7 +174,6 @@ globals:
alias: Alias
aliasUsers: Users
subRoles: Subroles
myAccount: Mi cuenta
inheritedRoles: Inherited Roles
customers: Customers
customerCreate: New customer
@ -336,6 +330,7 @@ globals:
medical: Mutual
pit: IRPF
wasteRecalc: Waste recaclulate
translations: Translations
operator: Operator
parking: Parking
vehicleList: Vehicles
@ -369,7 +364,6 @@ globals:
countryFk: Country
countryCodeFk: Country
companyFk: Company
nickname: Alias
model: Model
fuel: Fuel
active: Active
@ -413,106 +407,6 @@ cau:
subtitle: By sending this ticket, all the data related to the error, the section, the user, etc., are already sent.
inputLabel: Explain why this error should not appear
askPrivileges: Ask for privileges
entry:
list:
newEntry: New entry
tableVisibleColumns:
isExcludedFromAvailable: Exclude from inventory
isOrdered: Ordered
isConfirmed: Ready to label
isReceived: Received
isRaid: Raid
landed: Date
supplierFk: Supplier
reference: Ref/Alb/Guide
invoiceNumber: Invoice
agencyModeId: Agency
isBooked: Booked
companyFk: Company
evaNotes: Notes
warehouseOutFk: Origin
warehouseInFk: Destiny
entryTypeDescription: Entry type
invoiceAmount: Import
travelFk: Travel
summary:
invoiceAmount: Amount
commission: Commission
currency: Currency
invoiceNumber: Invoice number
ordered: Ordered
booked: Booked
excludedFromAvailable: Inventory
travelReference: Reference
travelAgency: Agency
travelShipped: Shipped
travelDelivered: Delivered
travelLanded: Landed
travelReceived: Received
buys: Buys
stickers: Stickers
package: Package
packing: Pack.
grouping: Group.
buyingValue: Buying value
import: Import
pvp: PVP
basicData:
travel: Travel
currency: Currency
commission: Commission
observation: Observation
booked: Booked
excludedFromAvailable: Inventory
buys:
observations: Observations
packagingFk: Box
color: Color
printedStickers: Printed stickers
notes:
observationType: Observation type
latestBuys:
tableVisibleColumns:
image: Picture
itemFk: Item ID
weightByPiece: Weight/Piece
isActive: Active
family: Family
entryFk: Entry
freightValue: Freight value
comissionValue: Commission value
packageValue: Package value
isIgnored: Is ignored
price2: Grouping
price3: Packing
minPrice: Min
ektFk: Ekt
packingOut: Package out
landing: Landing
isExcludedFromAvailable: Exclude from inventory
isRaid: Raid
invoiceNumber: Invoice
reference: Ref/Alb/Guide
params:
isExcludedFromAvailable: Excluir del inventario
isOrdered: Pedida
isConfirmed: Lista para etiquetar
isReceived: Recibida
isRaid: Redada
landed: Fecha
supplierFk: Proveedor
invoiceNumber: Nº Factura
reference: Ref/Alb/Guía
agencyModeId: Agencia
isBooked: Asentado
companyFk: Empresa
travelFk: Envio
evaNotes: Notas
warehouseOutFk: Origen
warehouseInFk: Destino
entryTypeDescription: Tipo entrada
invoiceAmount: Importe
dated: Fecha
ticket:
params:
ticketFk: Ticket ID
@ -695,10 +589,8 @@ worker:
machine: Machine
business:
tableVisibleColumns:
id: ID
started: Start Date
ended: End Date
hourlyLabor: Time sheet
company: Company
reasonEnd: Reason for Termination
department: Department
@ -706,7 +598,6 @@ worker:
calendarType: Work Calendar
workCenter: Work Center
payrollCategories: Contract Category
workerBusinessAgreementName: Agreement
occupationCode: Contribution Code
rate: Rate
businessType: Contract Type
@ -836,8 +727,6 @@ travel:
CloneTravelAndEntries: Clone travel and his entries
deleteTravel: Delete travel
AddEntry: Add entry
availabled: Availabled
availabledHour: Availabled hour
thermographs: Thermographs
hb: HB
basicData:

View File

@ -33,11 +33,9 @@ globals:
reset: Restaurar
close: Cerrar
cancel: Cancelar
isSaveAndContinue: Guardar y continuar
clone: Clonar
confirm: Confirmar
assign: Asignar
replace: Sustituir
back: Volver
yes: Si
no: No
@ -50,8 +48,6 @@ globals:
rowRemoved: Fila eliminada
pleaseWait: Por favor espera...
noPinnedModules: No has fijado ningún módulo
split: Split
enterToConfirm: Pulsa Enter para confirmar
summary:
basicData: Datos básicos
daysOnward: Días adelante
@ -59,8 +55,8 @@ globals:
today: Hoy
yesterday: Ayer
dateFormat: es-ES
noSelectedRows: No tienes ninguna línea seleccionada
microsip: Abrir en MicroSIP
noSelectedRows: No tienes ninguna línea seleccionada
downloadCSVSuccess: Descarga de CSV exitosa
reference: Referencia
agency: Agencia
@ -80,10 +76,8 @@ globals:
requiredField: Campo obligatorio
class: clase
type: Tipo
reason: Motivo
removeSelection: Eliminar selección
reason: motivo
noResults: Sin resultados
results: resultados
system: Sistema
notificationSent: Notificación enviada
warehouse: Almacén
@ -157,12 +151,10 @@ globals:
maxTemperature: Máx
minTemperature: Mín
changePass: Cambiar contraseña
setPass: Establecer contraseña
deleteConfirmTitle: Eliminar los elementos seleccionados
changeState: Cambiar estado
raid: 'Redada {daysInForward} días'
isVies: Vies
noData: Datos no disponibles
pageTitles:
logIn: Inicio de sesión
addressEdit: Modificar consignatario
@ -174,7 +166,6 @@ globals:
agency: Agencia
workCenters: Centros de trabajo
modes: Modos
negative: Tickets negativos
zones: Zonas
zonesList: Listado
deliveryDays: Días de entrega
@ -295,9 +286,9 @@ globals:
buyRequest: Peticiones de compra
wasteBreakdown: Deglose de mermas
itemCreate: Nuevo artículo
tax: IVA
botanical: Botánico
barcode: Código de barras
tax: 'IVA'
botanical: 'Botánico'
barcode: 'Código de barras'
itemTypeCreate: Nueva familia
family: Familia
lastEntries: Últimas entradas
@ -339,6 +330,7 @@ globals:
medical: Mutua
pit: IRPF
wasteRecalc: Recalcular mermas
translations: Traducciones
operator: Operario
parking: Parking
vehicleList: Vehículos
@ -370,7 +362,6 @@ globals:
countryFk: País
countryCodeFk: País
companyFk: Empresa
nickname: Alias
errors:
statusUnauthorized: Acceso denegado
statusInternalServerError: Ha ocurrido un error interno del servidor
@ -407,87 +398,6 @@ cau:
subtitle: Al enviar este cau ya se envían todos los datos relacionados con el error, la sección, el usuario, etc
inputLabel: Explique el motivo por el que no deberia aparecer este fallo
askPrivileges: Solicitar permisos
entry:
list:
newEntry: Nueva entrada
tableVisibleColumns:
isExcludedFromAvailable: Excluir del inventario
isOrdered: Pedida
isConfirmed: Lista para etiquetar
isReceived: Recibida
isRaid: Redada
landed: Fecha
supplierFk: Proveedor
invoiceNumber: Nº Factura
reference: Ref/Alb/Guía
agencyModeId: Agencia
isBooked: Asentado
companyFk: Empresa
travelFk: Envio
evaNotes: Notas
warehouseOutFk: Origen
warehouseInFk: Destino
entryTypeDescription: Tipo entrada
invoiceAmount: Importe
summary:
invoiceAmount: Importe
commission: Comisión
currency: Moneda
invoiceNumber: Núm. factura
ordered: Pedida
booked: Contabilizada
excludedFromAvailable: Inventario
travelReference: Referencia
travelAgency: Agencia
travelShipped: F. envio
travelWarehouseOut: Alm. salida
travelDelivered: Enviada
travelLanded: F. entrega
travelReceived: Recibida
buys: Compras
stickers: Etiquetas
package: Embalaje
packing: Pack.
grouping: Group.
buyingValue: Coste
import: Importe
pvp: PVP
basicData:
travel: Envío
currency: Moneda
observation: Observación
commission: Comisión
booked: Asentado
excludedFromAvailable: Inventario
buys:
observations: Observaciónes
packagingFk: Embalaje
color: Color
printedStickers: Etiquetas impresas
notes:
observationType: Tipo de observación
latestBuys:
tableVisibleColumns:
image: Foto
itemFk: Id Artículo
weightByPiece: Peso (gramos)/tallo
isActive: Activo
family: Familia
entryFk: Entrada
freightValue: Porte
comissionValue: Comisión
packageValue: Embalaje
isIgnored: Ignorado
price2: Grouping
price3: Packing
minPrice: Min
ektFk: Ekt
packingOut: Embalaje envíos
landing: Llegada
isExcludedFromAvailable: Excluir del inventario
isRaid: Redada
invoiceNumber: Nº Factura
reference: Ref/Alb/Guía
ticket:
params:
ticketFk: ID de ticket
@ -501,38 +411,6 @@ ticket:
freightItemName: Nombre
packageItemName: Embalaje
longName: Descripción
pageTitles:
tickets: Tickets
list: Listado
ticketCreate: Nuevo ticket
summary: Resumen
basicData: Datos básicos
boxing: Encajado
sms: Sms
notes: Notas
sale: Lineas del pedido
dms: Gestión documental
negative: Tickets negativos
volume: Volumen
observation: Notas
ticketAdvance: Adelantar tickets
futureTickets: Tickets a futuro
expedition: Expedición
purchaseRequest: Petición de compra
weeklyTickets: Tickets programados
saleTracking: Líneas preparadas
services: Servicios
tracking: Estados
components: Componentes
pictures: Fotos
packages: Bultos
list:
nickname: Alias
state: Estado
shipped: Enviado
landed: Entregado
salesPerson: Comercial
total: Total
card:
customerId: ID cliente
customerCard: Ficha del cliente
@ -579,48 +457,6 @@ ticket:
consigneeStreet: Dirección
create:
address: Dirección
invoiceOut:
card:
issued: Fecha emisión
customerCard: Ficha del cliente
ticketList: Listado de tickets
summary:
issued: Fecha
dued: Fecha límite
booked: Contabilizada
taxBreakdown: Desglose impositivo
taxableBase: Base imp.
rate: Tarifa
fee: Cuota
tickets: Tickets
totalWithVat: Importe
globalInvoices:
errors:
chooseValidClient: Selecciona un cliente válido
chooseValidCompany: Selecciona una empresa válida
chooseValidPrinter: Selecciona una impresora válida
chooseValidSerialType: Selecciona una tipo de serie válida
fillDates: La fecha de la factura y la fecha máxima deben estar completas
invoiceDateLessThanMaxDate: La fecha de la factura no puede ser menor que la fecha máxima
invoiceWithFutureDate: Existe una factura con una fecha futura
noTicketsToInvoice: No existen tickets para facturar
criticalInvoiceError: Error crítico en la facturación proceso detenido
invalidSerialTypeForAll: El tipo de serie debe ser global cuando se facturan todos los clientes
table:
addressId: Id dirección
streetAddress: Dirección fiscal
statusCard:
percentageText: '{getPercentage}% {getAddressNumber} de {getNAddresses}'
pdfsNumberText: '{nPdfs} de {totalPdfs} PDFs'
negativeBases:
clientId: Id cliente
base: Base
active: Activo
hasToInvoice: Facturar
verifiedData: Datos comprobados
comercial: Comercial
errors:
downloadCsvFailed: Error al descargar CSV
order:
field:
salesPersonFk: Comercial
@ -631,34 +467,15 @@ order:
list:
newOrder: Nuevo Pedido
summary:
basket: Cesta
notConfirmed: No confirmada
created: Creado
createdFrom: Creado desde
address: Dirección
total: Total
vat: IVA
state: Estado
alias: Alias
items: Artículos
orderTicketList: Tickets del pedido
amount: Monto
confirm: Confirmar
confirmLines: Confirmar lineas
shelving:
list:
parking: Parking
priority: Prioridad
newShelving: Nuevo Carro
summary:
recyclable: Reciclable
parking:
pickingOrder: Orden de recogida
row: Fila
column: Columna
searchBar:
info: Puedes buscar por código de parking
label: Buscar parking...
issued: Fecha
dued: Fecha límite
booked: Contabilizada
taxBreakdown: Desglose impositivo
taxableBase: Base imp.
rate: Tarifa
fee: Cuota
tickets: Tickets
totalWithVat: Importe
department:
chat: Chat
bossDepartment: Jefe de departamento
@ -771,10 +588,8 @@ worker:
concept: Concepto
business:
tableVisibleColumns:
id: Id
started: Fecha inicio
ended: Fecha fin
hourlyLabor: Ficha
company: Empresa
reasonEnd: Motivo finalización
department: Departamento
@ -785,13 +600,12 @@ worker:
occupationCode: Cotización
rate: Tarifa
businessType: Contrato
workerBusinessAgreementName: Convenio
amount: Salario
basicSalary: Salario transportistas
notes: Notas
operator:
numberOfWagons: Número de vagones
train: Tren
train: tren
itemPackingType: Tipo de embalaje
warehouse: Almacén
sector: Sector
@ -822,8 +636,8 @@ wagon:
volumeNotEmpty: El volumen no puede estar vacío
typeNotEmpty: El tipo no puede estar vacío
maxTrays: Has alcanzado el número máximo de bandejas
minHeightBetweenTrays: La distancia mínima entre bandejas es
maxWagonHeight: La altura máxima del vagón es
minHeightBetweenTrays: 'La distancia mínima entre bandejas es '
maxWagonHeight: 'La altura máxima del vagón es '
uncompleteTrays: Hay bandejas sin completar
params:
label: Etiqueta
@ -840,12 +654,12 @@ supplier:
tableVisibleColumns:
nif: NIF/CIF
account: Cuenta
summary:
responsible: Responsable
verified: Verificado
isActive: Está activo
billingData: Forma de pago
financialData: Datos financieros
payDeadline: Plazo de pago
payDay: Día de pago
account: Cuenta
@ -923,8 +737,6 @@ travel:
deleteTravel: Eliminar envío
AddEntry: Añadir entrada
thermographs: Termógrafos
availabled: F. Disponible
availabledHour: Hora Disponible
hb: HB
basicData:
daysInForward: Desplazamiento automatico (redada)
@ -973,7 +785,7 @@ components:
cardDescriptor:
mainList: Listado principal
summary: Resumen
moreOptions: Más opciones
moreOptions: 'Más opciones'
leftMenu:
addToPinned: Añadir a fijados
removeFromPinned: Eliminar de fijados

View File

@ -51,6 +51,7 @@ const removeAlias = () => {
<CardDescriptor
ref="descriptor"
:url="`MailAliases/${entityId}`"
module="Alias"
data-key="Alias"
title="alias"
>

View File

@ -24,6 +24,7 @@ onMounted(async () => {
ref="descriptor"
:url="`VnUsers/preview`"
:filter="{ ...filter, where: { id: entityId } }"
module="Account"
data-key="Account"
title="nickname"
>

View File

@ -12,7 +12,6 @@ import VnInputPassword from 'src/components/common/VnInputPassword.vue';
import VnChangePassword from 'src/components/common/VnChangePassword.vue';
import { useQuasar } from 'quasar';
import { useRouter } from 'vue-router';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
const $props = defineProps({
hasAccount: {
@ -25,23 +24,16 @@ const $props = defineProps({
const { t } = useI18n();
const { hasAccount } = toRefs($props);
const { openConfirmationModal } = useVnConfirm();
const arrayData = useArrayData('Account');
const route = useRoute();
const router = useRouter();
const state = useState();
const user = state.getUser();
const { notify } = useQuasar();
const account = computed(() => arrayData.store.data);
const account = computed(() => useArrayData('Account').store.data[0]);
account.value.hasAccount = hasAccount.value;
const entityId = computed(() => +route.params.id);
const hasitManagementAccess = 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) {
if (active) {
@ -114,8 +106,11 @@ onMounted(() => {
:ask-old-pass="askOldPass"
:submit-fn="
async (newPassword, oldPassword) => {
const body = isHimself ? { userId: entityId, oldPassword } : {};
await axios.patch(url, { ...body, newPassword });
await axios.patch(`Accounts/change-password`, {
userId: entityId,
newPassword,
oldPassword,
});
}
"
/>
@ -126,14 +121,18 @@ onMounted(() => {
:promise="sync"
>
<template #customHTML>
<VnCheckbox
v-model="shouldSyncPassword"
{{ shouldSyncPassword }}
<QCheckbox
:label="t('account.card.actions.sync.checkbox')"
:info="t('account.card.actions.sync.tooltip')"
v-model="shouldSyncPassword"
class="full-width"
clearable
clear-icon="close"
color="primary"
/>
>
<QIcon style="padding-left: 10px" color="primary" name="info" size="sm">
<QTooltip>{{ t('account.card.actions.sync.tooltip') }}</QTooltip>
</QIcon></QCheckbox
>
<VnInputPassword
v-if="shouldSyncPassword"
:label="t('login.password')"
@ -154,16 +153,21 @@ onMounted(() => {
t('account.card.actions.disableAccount.title'),
t('account.card.actions.disableAccount.subtitle'),
() => deleteAccount(),
() => deleteAccount(),
)
"
>
<QItemSection>{{ t('globals.delete') }}</QItemSection>
</QItem>
<QItem v-if="hasSysadminAccess || isHimself" v-ripple clickable>
<QItemSection @click="onChangePass(isHimself)">
{{ isHimself ? t('globals.changePass') : t('globals.setPass') }}
<QItem
v-if="hasSysadminAccess"
v-ripple
clickable
@click="user.id === account.id ? onChangePass(true) : onChangePass(false)"
>
<QItemSection v-if="user.id === account.id">
{{ t('globals.changePass') }}
</QItemSection>
<QItemSection v-else>{{ t('globals.setPass') }}</QItemSection>
</QItem>
<QItem
v-if="!account.hasAccount && hasSysadminAccess"
@ -174,7 +178,6 @@ onMounted(() => {
t('account.card.actions.enableAccount.title'),
t('account.card.actions.enableAccount.subtitle'),
() => updateStatusAccount(true),
() => updateStatusAccount(true),
)
"
>
@ -189,7 +192,6 @@ onMounted(() => {
t('account.card.actions.disableAccount.title'),
t('account.card.actions.disableAccount.subtitle'),
() => updateStatusAccount(false),
() => updateStatusAccount(false),
)
"
>
@ -205,7 +207,6 @@ onMounted(() => {
t('account.card.actions.activateUser.title'),
t('account.card.actions.activateUser.title'),
() => updateStatusUser(true),
() => updateStatusUser(true),
)
"
>
@ -220,7 +221,6 @@ onMounted(() => {
t('account.card.actions.deactivateUser.title'),
t('account.card.actions.deactivateUser.title'),
() => updateStatusUser(false),
() => updateStatusUser(false),
)
"
>

View File

@ -35,6 +35,7 @@ const removeRole = async () => {
<CardDescriptor
url="VnRoles"
:filter="{ where: { id: entityId } }"
module="Role"
data-key="Role"
:summary="$props.summary"
>

View File

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

View File

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

View File

@ -46,6 +46,7 @@ onMounted(async () => {
<CardDescriptor
:url="`Claims/${entityId}`"
:filter="filter"
module="Claim"
title="client.name"
data-key="Claim"
>

View File

@ -190,7 +190,7 @@ async function saveWhenHasChanges() {
ref="claimLinesForm"
:url="`Claims/${route.params.id}/lines`"
save-url="ClaimBeginnings/crud"
:user-filter="linesFilter"
:filter="linesFilter"
@on-fetch="onFetch"
v-model:selected="selected"
:default-save="false"

View File

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

View File

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

View File

@ -233,27 +233,20 @@ function claimUrl(section) {
<ClaimDescriptorMenu :claim="entity.claim" />
</template>
<template #body="{ entity: { claim, salesClaimed, developments } }">
<QCard class="vn-one">
<QCard class="vn-one" v-if="$route.name != 'ClaimSummary'">
<VnTitle
:url="claimUrl('basic-data')"
:text="t('globals.pageTitles.basicData')"
/>
<VnLv
v-if="$route.name != 'ClaimSummary'"
:label="t('claim.created')"
:value="toDate(claim.created)"
/>
<VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.state')">
<VnLv :label="t('claim.created')" :value="toDate(claim.created)" />
<VnLv :label="t('claim.state')">
<template #value>
<QChip :color="stateColor(claim.claimState.code)" dense>
{{ claim.claimState.description }}
</QChip>
</template>
</VnLv>
<VnLv
v-if="$route.name != 'ClaimSummary'"
:label="t('globals.salesPerson')"
>
<VnLv :label="t('globals.salesPerson')">
<template #value>
<VnUserLink
:name="claim.client?.salesPersonUser?.name"
@ -261,7 +254,7 @@ function claimUrl(section) {
/>
</template>
</VnLv>
<VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.attendedBy')">
<VnLv :label="t('claim.attendedBy')">
<template #value>
<VnUserLink
:name="claim.worker?.user?.nickname"
@ -269,7 +262,7 @@ function claimUrl(section) {
/>
</template>
</VnLv>
<VnLv v-if="$route.name != 'ClaimSummary'" :label="t('claim.customer')">
<VnLv :label="t('claim.customer')">
<template #value>
<span class="link cursor-pointer">
{{ claim.client?.name }}
@ -281,11 +274,6 @@ function claimUrl(section) {
:label="t('claim.pickup')"
:value="`${dashIfEmpty(claim.pickup)}`"
/>
<VnLv
:label="t('globals.packages')"
:value="`${dashIfEmpty(claim.packages)}`"
:translation="(value) => t(`claim.packages`)"
/>
</QCard>
<QCard class="vn-two">
<VnTitle :url="claimUrl('notes')" :text="t('claim.notes')" />

View File

@ -19,36 +19,30 @@ const columns = [
name: 'itemFk',
label: t('Id item'),
columnFilter: false,
align: 'right',
align: 'left',
},
{
name: 'ticketFk',
label: t('Ticket'),
columnFilter: false,
align: 'right',
align: 'left',
},
{
name: 'claimDestinationFk',
label: t('Destination'),
columnFilter: false,
align: 'right',
},
{
name: 'shelvingCode',
label: t('Shelving'),
columnFilter: false,
align: 'right',
align: 'left',
},
{
name: 'landed',
label: t('Landed'),
format: (row) => toDate(row.landed),
align: 'center',
align: 'left',
},
{
name: 'quantity',
label: t('Quantity'),
align: 'right',
align: 'left',
},
{
name: 'concept',
@ -58,18 +52,18 @@ const columns = [
{
name: 'price',
label: t('Price'),
align: 'right',
align: 'left',
},
{
name: 'discount',
label: t('Discount'),
format: ({ discount }) => toPercentage(discount / 100),
align: 'right',
align: 'left',
},
{
name: 'total',
label: t('Total'),
align: 'right',
align: 'left',
},
];
</script>

View File

@ -1,6 +1,8 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import FetchData from 'components/FetchData.vue';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue';
@ -12,14 +14,15 @@ const props = defineProps({
type: String,
required: true,
},
states: {
type: Array,
default: () => [],
},
});
const states = ref([]);
defineExpose({ states });
</script>
<template>
<FetchData url="ClaimStates" @on-fetch="(data) => (states = data)" auto-load />
<VnFilterPanel :data-key="props.dataKey" :search-button="true">
<template #tags="{ tag, formatFn }">
<div class="q-gutter-x-xs">
@ -106,6 +109,7 @@ const props = defineProps({
:label="t('claim.zone')"
v-model="params.zoneFk"
url="Zones"
:use-like="false"
outlined
rounded
dense

View File

@ -10,13 +10,12 @@ import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import VnTable from 'src/components/VnTable/VnTable.vue';
import ZoneDescriptorProxy from '../Zone/Card/ZoneDescriptorProxy.vue';
import VnSection from 'src/components/common/VnSection.vue';
import FetchData from 'src/components/FetchData.vue';
const { t } = useI18n();
const { viewSummary } = useSummaryDialog();
const dataKey = 'ClaimList';
const states = ref([]);
const claimFilterRef = ref();
const columns = computed(() => [
{
align: 'left',
@ -82,7 +81,8 @@ const columns = computed(() => [
align: 'left',
label: t('claim.state'),
format: ({ stateCode }) =>
states.value?.find(({ code }) => code === stateCode)?.description,
claimFilterRef.value?.states.find(({ code }) => code === stateCode)
?.description,
name: 'stateCode',
chip: {
condition: () => true,
@ -92,7 +92,7 @@ const columns = computed(() => [
name: 'claimStateFk',
component: 'select',
attrs: {
options: states.value,
options: claimFilterRef.value?.states,
optionLabel: 'description',
},
},
@ -125,7 +125,6 @@ const STATE_COLOR = {
</script>
<template>
<FetchData url="ClaimStates" @on-fetch="(data) => (states = data)" auto-load />
<VnSection
:data-key="dataKey"
:columns="columns"
@ -136,7 +135,7 @@ const STATE_COLOR = {
}"
>
<template #advanced-menu>
<ClaimFilter :data-key ref="claimFilterRef" :states />
<ClaimFilter data-key="ClaimList" ref="claimFilterRef" />
</template>
<template #body>
<VnTable

View File

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

View File

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

View File

@ -117,7 +117,7 @@ const toCustomerAddressEdit = (addressId) => {
data-key="CustomerAddresses"
order="id DESC"
ref="vnPaginateRef"
:filter="addressFilter"
:user-filter="addressFilter"
:url="`Clients/${route.params.id}/addresses`"
/>
<div class="full-width flex justify-center">
@ -189,11 +189,11 @@ const toCustomerAddressEdit = (addressId) => {
<QSeparator
class="q-mx-lg"
v-if="item?.observations?.length"
v-if="item.observations.length"
vertical
/>
<div v-if="item?.observations?.length">
<div v-if="item.observations.length">
<div
:key="obIndex"
class="flex q-mb-sm"

View File

@ -108,6 +108,7 @@ function onBeforeSave(formData, originalData) {
:label="t('customer.extendedList.tableVisibleColumns.phone')"
:rules="validate('client.phone')"
clearable
type="number"
v-model="data.phone"
data-cy="customerPhone"
/>
@ -115,6 +116,7 @@ function onBeforeSave(formData, originalData) {
:label="t('customer.summary.mobile')"
:rules="validate('client.mobile')"
clearable
type="number"
v-model="data.mobile"
/>
</VnRow>

View File

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

View File

@ -61,23 +61,6 @@ const columns = computed(() => [
columnFilter: false,
cardVisible: true,
},
{
align: 'left',
name: 'buyerId',
label: t('customer.params.buyerId'),
component: 'select',
attrs: {
url: 'TicketRequests/getItemTypeWorker',
optionLabel: 'nickname',
optionValue: 'id',
fields: ['id', 'nickname'],
sortBy: ['nickname ASC'],
optionFilter: 'firstName',
},
cardVisible: false,
visible: false,
},
{
name: 'description',
align: 'left',
@ -91,7 +74,6 @@ const columns = computed(() => [
name: 'quantity',
label: t('globals.quantity'),
cardVisible: true,
visible: true,
columnFilter: {
inWhere: true,
},
@ -156,11 +138,11 @@ const updateDateParams = (value, params) => {
const campaign = campaignList.value.find((c) => c.id === value);
if (!campaign) return;
const { dated, scopeDays } = campaign;
const from = new Date(dated);
from.setDate(from.getDate() - scopeDays);
params.from = from;
params.to = dated;
const { dated, previousDays, scopeDays } = campaign;
const _date = new Date(dated);
const [from, to] = dateRange(_date);
params.from = new Date(from.setDate(from.getDate() - previousDays)).toISOString();
params.to = new Date(to.setDate(to.getDate() + scopeDays)).toISOString();
return params;
};
</script>
@ -218,60 +200,29 @@ const updateDateParams = (value, params) => {
<div v-if="row.subName" class="subName">
{{ row.subName }}
</div>
<FetchedTags :item="row" />
<FetchedTags :item="row" :max-length="3" />
</template>
<template #moreFilterPanel="{ params }">
<div class="column no-wrap flex-center q-gutter-y-md q-mt-xs q-pr-xl">
<VnSelect
:filled="true"
class="q-px-sm q-pt-none fit"
url="ItemTypes"
v-model="params.typeId"
:label="t('item.list.typeName')"
:fields="['id', 'name', 'categoryFk']"
:include="'category'"
:sortBy="'name ASC'"
dense
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel>{{ scope.opt?.name }}</QItemLabel>
<QItemLabel caption>{{
scope.opt?.category?.name
}}</QItemLabel>
</QItemSection>
</QItem>
</template>
</VnSelect>
<VnSelect
:filled="true"
class="q-px-sm q-pt-none fit"
url="ItemCategories"
v-model="params.categoryId"
:label="t('item.list.category')"
:fields="['id', 'name']"
:sortBy="'name ASC'"
dense
/>
<VnSelect
v-model="params.campaign"
:options="campaignList"
:label="t('globals.campaign')"
:filled="true"
class="q-px-sm q-pt-none fit"
:option-label="(opt) => t(opt.code)"
:fields="['id', 'code', 'dated', 'scopeDays']"
@update:model-value="(data) => updateDateParams(data, params)"
dense
option-label="code"
@update:model-value="(data) => updateDateParams(data, params)"
>
<template #option="scope">
<QItem v-bind="scope.itemProps">
<QItemSection>
<QItemLabel> {{ t(scope.opt?.code) }} </QItemLabel>
<QItemLabel caption>
{{ new Date(scope.opt?.dated).getFullYear() }}
</QItemLabel>
<QItemLabel>
{{ scope.opt?.code }}
{{
new Date(scope.opt?.dated).getFullYear()
}}</QItemLabel
>
</QItemSection>
</QItem>
</template>
@ -296,21 +247,7 @@ const updateDateParams = (value, params) => {
</template>
<i18n>
en:
valentinesDay: Valentine's Day
mothersDay: Mother's Day
allSaints: All Saints' Day
frenchMothersDay: Mother's Day in France
es:
Enter a new search: Introduce una nueva búsqueda
Group by items: Agrupar por artículos
valentinesDay: Día de San Valentín
mothersDay: Día de la Madre
allSaints: Día de Todos los Santos
frenchMothersDay: (Francia) Día de la Madre
Campaign consumption: Consumo campaña
Campaign: Campaña
From: Desde
To: Hasta
</i18n>

View File

@ -55,6 +55,7 @@ const debtWarning = computed(() => {
<template>
<CardDescriptor
module="Customer"
:url="`Clients/${entityId}/getCard`"
:summary="$props.summary"
data-key="Customer"
@ -109,14 +110,8 @@ const debtWarning = computed(() => {
>
<QTooltip>{{ t('customer.card.isDisabled') }}</QTooltip>
</QIcon>
<QIcon
v-if="entity?.substitutionAllowed"
name="help"
size="xs"
color="primary"
>
<QTooltip>{{ t('Allowed substitution') }}</QTooltip>
<QIcon v-if="entity.isFreezed" name="vn:frozen" size="xs" color="primary">
<QTooltip>{{ t('customer.card.isFrozen') }}</QTooltip>
</QIcon>
<QIcon
v-if="!entity.account?.active"
@ -142,14 +137,6 @@ const debtWarning = computed(() => {
>
<QTooltip>{{ t('customer.card.notChecked') }}</QTooltip>
</QIcon>
<QIcon
v-if="entity?.isFreezed"
name="vn:frozen"
size="xs"
color="primary"
>
<QTooltip>{{ t('customer.card.isFrozen') }}</QTooltip>
</QIcon>
<QBtn
v-if="entity.unpaid"
flat
@ -163,13 +150,13 @@ const debtWarning = computed(() => {
<br />
{{
t('unpaidDated', {
dated: toDate(entity.unpaid?.dated),
dated: toDate(customer.unpaid?.dated),
})
}}
<br />
{{
t('unpaidAmount', {
amount: toCurrency(entity.unpaid?.amount),
amount: toCurrency(customer.unpaid?.amount),
})
}}
</QTooltip>

View File

@ -61,16 +61,6 @@ const openCreateForm = (type) => {
.join('&');
useOpenURL(`/#/${type}/list?${params}`);
};
const updateSubstitutionAllowed = async () => {
try {
await axios.patch(`Clients/${route.params.id}`, {
substitutionAllowed: !$props.customer.substitutionAllowed,
});
notify('globals.notificationSent', 'positive');
} catch (error) {
notify(error.message, 'positive');
}
};
</script>
<template>
@ -79,13 +69,6 @@ const updateSubstitutionAllowed = async () => {
{{ t('globals.pageTitles.createTicket') }}
</QItemSection>
</QItem>
<QItem v-ripple clickable>
<QItemSection @click="updateSubstitutionAllowed()">{{
$props.customer.substitutionAllowed
? t('Disable substitution')
: t('Allow substitution')
}}</QItemSection>
</QItem>
<QItem v-ripple clickable>
<QItemSection @click="showSmsDialog()">{{ t('Send SMS') }}</QItemSection>
</QItem>

View File

@ -2,24 +2,16 @@
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import { useQuasar } from 'quasar';
import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';
import FetchData from 'components/FetchData.vue';
import FormModel from 'components/FormModel.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnInput from 'src/components/common/VnInput.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import VnLocation from 'src/components/common/VnLocation.vue';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';
import { getDifferences, getUpdatedValues } from 'src/filters';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
const quasar = useQuasar();
const { t } = useI18n();
const route = useRoute();
const { notify } = useNotify();
const typesTaxes = ref([]);
const typesTransactions = ref([]);
@ -31,37 +23,6 @@ function handleLocation(data, location) {
data.provinceFk = provinceFk;
data.countryFk = countryFk;
}
function onBeforeSave(formData, originalData) {
return getUpdatedValues(
Object.keys(getDifferences(formData, originalData)),
formData,
);
}
async function checkEtChanges(data, _, originalData) {
const equalizatedHasChanged = originalData.isEqualizated != data.isEqualizated;
const hasToInvoiceByAddress =
originalData.hasToInvoiceByAddress || data.hasToInvoiceByAddress;
if (equalizatedHasChanged && hasToInvoiceByAddress) {
quasar.dialog({
component: VnConfirm,
componentProps: {
title: t('You changed the equalization tax'),
message: t('Do you want to spread the change?'),
promise: () => acceptPropagate(data),
},
});
} else if (equalizatedHasChanged) {
await acceptPropagate(data);
}
}
async function acceptPropagate({ isEqualizated }) {
await axios.patch(`Clients/${route.params.id}/addressesPropagateRe`, {
isEqualizated,
});
notify(t('Equivalent tax spreaded'), 'warning');
}
</script>
<template>
@ -75,9 +36,6 @@ async function acceptPropagate({ isEqualizated }) {
:url-update="`Clients/${route.params.id}/updateFiscalData`"
auto-load
model="Customer"
:mapper="onBeforeSave"
observe-form-changes
@on-data-saved="checkEtChanges"
>
<template #form="{ data, validate }">
<VnRow>
@ -152,11 +110,14 @@ async function acceptPropagate({ isEqualizated }) {
</VnRow>
<VnRow>
<QCheckbox :label="t('Has to invoice')" v-model="data.hasToInvoice" />
<VnCheckbox
v-model="data.isVies"
:label="t('globals.isVies')"
:info="t('whenActivatingIt')"
/>
<div>
<QCheckbox :label="t('globals.isVies')" v-model="data.isVies" />
<QIcon name="info" class="cursor-info q-ml-sm" size="sm">
<QTooltip>
{{ t('whenActivatingIt') }}
</QTooltip>
</QIcon>
</div>
</VnRow>
<VnRow>
@ -168,11 +129,17 @@ async function acceptPropagate({ isEqualizated }) {
</VnRow>
<VnRow>
<VnCheckbox
v-model="data.isEqualizated"
:label="t('Is equalizated')"
:info="t('inOrderToInvoice')"
/>
<div>
<QCheckbox
:label="t('Is equalizated')"
v-model="data.isEqualizated"
/>
<QIcon class="cursor-info q-ml-sm" name="info" size="sm">
<QTooltip>
{{ t('inOrderToInvoice') }}
</QTooltip>
</QIcon>
</div>
<QCheckbox :label="t('Daily invoice')" v-model="data.hasDailyInvoice" />
</VnRow>
@ -213,9 +180,6 @@ es:
whenActivatingIt: Al activarlo, no informar el código del país en el campo nif
inOrderToInvoice: Para facturar no se consulta este campo, sino el RE de consignatario. Al modificar este campo si no esta marcada la casilla Facturar por consignatario, se propagará automaticamente el cambio a todos lo consignatarios, en caso contrario preguntará al usuario si quiere o no propagar
Daily invoice: Facturación diaria
Equivalent tax spreaded: Recargo de equivalencia propagado
You changed the equalization tax: Has cambiado el recargo de equivalencia
Do you want to spread the change?: ¿Deseas propagar el cambio a sus consignatarios?
en:
onlyLetters: Only letters, numbers and spaces can be used
whenActivatingIt: When activating it, do not enter the country code in the ID field

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