Merge branch 'dev' into 6696-manaAfterDepartment
gitea/salix-front/pipeline/pr-dev This commit is unstable Details

This commit is contained in:
Javi Gallego 2025-04-09 14:05:35 +02:00
commit 70d8b65fcb
87 changed files with 2029 additions and 2708 deletions

View File

@ -18,6 +18,8 @@
"test:e2e:summary": "bash ./test/cypress/summary.sh", "test:e2e:summary": "bash ./test/cypress/summary.sh",
"test": "echo \"See package.json => scripts for available tests.\" && exit 0", "test": "echo \"See package.json => scripts for available tests.\" && exit 0",
"test:front": "vitest", "test:front": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage",
"test:front:ci": "vitest run", "test:front:ci": "vitest run",
"commitlint": "commitlint --edit", "commitlint": "commitlint --edit",
"prepare": "npx husky install", "prepare": "npx husky install",
@ -27,6 +29,8 @@
"docs:preview": "vitepress preview docs" "docs:preview": "vitepress preview docs"
}, },
"dependencies": { "dependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.20.0",
"@quasar/cli": "^2.4.1", "@quasar/cli": "^2.4.1",
"@quasar/extras": "^1.16.16", "@quasar/extras": "^1.16.16",
"axios": "^1.4.0", "axios": "^1.4.0",
@ -52,6 +56,7 @@
"@quasar/app-vite": "^2.0.8", "@quasar/app-vite": "^2.0.8",
"@quasar/quasar-app-extension-qcalendar": "^4.0.2", "@quasar/quasar-app-extension-qcalendar": "^4.0.2",
"@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0", "@quasar/quasar-app-extension-testing-unit-vitest": "^0.4.0",
"@vitest/ui": "3.1.1",
"@vue/compiler-sfc": "^3.5.13", "@vue/compiler-sfc": "^3.5.13",
"@vue/test-utils": "^2.4.4", "@vue/test-utils": "^2.4.4",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
@ -59,6 +64,7 @@
"cypress-mochawesome-reporter": "^3.8.2", "cypress-mochawesome-reporter": "^3.8.2",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1", "eslint-config-prettier": "^10.0.1",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-plugin-cypress": "^4.1.0", "eslint-plugin-cypress": "^4.1.0",
"eslint-plugin-import": "^2.31.0", "eslint-plugin-import": "^2.31.0",
"eslint-plugin-vue": "^9.32.0", "eslint-plugin-vue": "^9.32.0",
@ -69,8 +75,7 @@
"postcss": "^8.4.23", "postcss": "^8.4.23",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"sass": "^1.83.4", "sass": "^1.83.4",
"vitepress": "^1.6.3", "vitest": "^3.0.3",
"vitest": "^0.34.0",
"xunit-viewer": "^10.6.1" "xunit-viewer": "^10.6.1"
}, },
"engines": { "engines": {

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,227 @@
/* eslint-disable */
/**
* THIS FILE IS GENERATED AUTOMATICALLY.
* 1. DO NOT edit this file directly as it won't do anything.
* 2. EDIT the original quasar.config file INSTEAD.
* 3. DO NOT git commit this file. It should be ignored.
*
* This file is still here because there was an error in
* the original quasar.config file and this allows you to
* investigate the Node.js stack error.
*
* After you fix the original file, this file will be
* deleted automatically.
**/
// quasar.config.js
import { configure } from "quasar/wrappers";
import VueI18nPlugin from "@intlify/unplugin-vue-i18n/vite";
import path from "path";
var __quasar_inject_dirname__ = "/home/jsegarra/Projects/salix-front";
var target = `http://${process.env.CI ? "back" : "localhost"}:3000`;
var quasar_config_default = configure(function() {
return {
eslint: {
// fix: true,
// include = [],
// exclude = [],
// rawOptions = {},
warnings: true,
errors: true
},
// https://v2.quasar.dev/quasar-cli/prefetch-feature
// preFetch: true,
// app boot file (/src/boot)
// --> 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"],
// https://github.com/quasarframework/quasar/tree/dev/extras
extras: [
// 'ionicons-v4',
// 'mdi-v5',
// 'fontawesome-v6',
// 'eva-icons',
// 'themify',
// 'line-awesome',
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
"roboto-font",
"material-icons-outlined",
"material-symbols-outlined"
],
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#build
build: {
target: {
browser: ["es2022", "edge88", "firefox78", "chrome87", "safari13.1"],
node: "node20"
},
vueRouterMode: "hash",
// available values: 'hash', 'history'
// vueRouterBase,
// vueDevtools,
// vueOptionsAPI: false,
// rebuildCache: true, // rebuilds Vite/linter/etc cache on startup
// publicPath: '/',
// analyze: true,
// env: {},
rawDefine: {
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
},
// ignorePublicFolder: true,
// minify: false,
// polyfillModulePreload: true,
// distDir
extendViteConf(viteConf) {
delete viteConf.build.polyfillModulePreload;
viteConf.build.modulePreload = {
polyfill: false
};
},
// viteVuePluginOptions: {},
alias: {
composables: path.join(__quasar_inject_dirname__, "./src/composables"),
filters: path.join(__quasar_inject_dirname__, "./src/filters")
},
vitePlugins: [
[
VueI18nPlugin({
strictMessage: false,
runtimeOnly: false,
include: [
path.resolve(__quasar_inject_dirname__, "./src/i18n/locale/**"),
path.resolve(__quasar_inject_dirname__, "./src/pages/**/locale/**")
]
})
]
]
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#devServer
devServer: {
server: {
type: "http"
},
proxy: {
"/api": {
target,
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
framework: {
config: {
config: {
dark: "auto"
}
},
lang: "en-GB",
// iconSet: 'material-icons', // Quasar icon set
// lang: 'en-US', // Quasar language pack
// For special cases outside of where the auto-import strategy can have an impact
// (like functional components as one of the examples),
// you can manually specify Quasar components/directives to be available everywhere:
//
// components: [],
// directives: [],
// Quasar plugins
plugins: ["Notify", "Dialog"],
all: "auto",
autoImportComponentCase: "pascal"
},
// animations: 'all', // --- includes all animations
// https://v2.quasar.dev/options/animations
animations: [],
// https://v2.quasar.dev/quasar-cli-vite/quasar-config-js#property-sourcefiles
// sourceFiles: {
// rootComponent: 'src/App.vue',
// router: 'src/router/index',
// store: 'src/store/index',
// registerServiceWorker: 'src-pwa/register-service-worker',
// serviceWorker: 'src-pwa/custom-service-worker',
// pwaManifestFile: 'src-pwa/manifest.json',
// electronMain: 'src-electron/electron-main',
// electronPreload: 'src-electron/electron-preload'
// },
// https://v2.quasar.dev/quasar-cli/developing-ssr/configuring-ssr
ssr: {
// ssrPwaHtmlFilename: 'offline.html', // do NOT use index.html as name!
// will mess up SSR
// extendSSRWebserverConf (esbuildConf) {},
// extendPackageJson (json) {},
pwa: false,
// manualStoreHydration: true,
// manualPostHydrationTrigger: true,
prodPort: 3e3,
// The default port that the production server should use
// (gets superseded if process.env.PORT is specified at runtime)
middlewares: [
"render"
// keep this as last one
]
},
// https://v2.quasar.dev/quasar-cli/developing-pwa/configuring-pwa
pwa: {
workboxMode: "generateSW",
// or 'injectManifest'
injectPwaMetaTags: true,
swFilename: "sw.js",
manifestFilename: "manifest.json",
useCredentialsForManifestTag: false
// useFilenameHashes: true,
// extendGenerateSWOptions (cfg) {}
// extendInjectManifestOptions (cfg) {},
// extendManifestJson (json) {}
// extendPWACustomSWConf (esbuildConf) {}
},
// Full list of options: https://v2.quasar.dev/quasar-cli/developing-cordova-apps/configuring-cordova
cordova: {
// noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
},
// Full list of options: https://v2.quasar.dev/quasar-cli/developing-capacitor-apps/configuring-capacitor
capacitor: {
hideSplashscreen: true
},
// Full list of options: https://v2.quasar.dev/quasar-cli/developing-electron-apps/configuring-electron
electron: {
// extendElectronMainConf (esbuildConf)
// extendElectronPreloadConf (esbuildConf)
inspectPort: 5858,
bundler: "packager",
// 'packager' or 'builder'
packager: {
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
// OS X / Mac App Store
// appBundleId: '',
// appCategoryType: '',
// osxSign: '',
// protocol: 'myapp://path',
// Windows only
// win32metadata: { ... }
},
builder: {
// https://www.electron.build/configuration/configuration
appId: "salix-frontend"
}
},
// Full list of options: https://v2.quasar.dev/quasar-cli-vite/developing-browser-extensions/configuring-bex
bex: {
contentScripts: ["my-content-script"]
// extendBexScriptsConf (esbuildConf) {}
// extendBexManifestJson (json) {}
}
};
});
export {
quasar_config_default as default
};

View File

@ -9,6 +9,30 @@ vi.mock('src/composables/useSession', () => ({
}), }),
})); }));
// Mock axios
vi.mock('axios', () => ({
default: {
create: vi.fn(() => ({
interceptors: {
request: { use: vi.fn() },
response: { use: vi.fn() },
},
})),
interceptors: {
request: { use: vi.fn() },
response: { use: vi.fn() },
},
defaults: {
baseURL: '',
},
},
}));
vi.mock('src/router', () => ({
Router: {
push: vi.fn(),
},
}));
vi.mock('src/stores/useStateQueryStore', () => ({ vi.mock('src/stores/useStateQueryStore', () => ({
useStateQueryStore: () => ({ useStateQueryStore: () => ({
add: () => vi.fn(), add: () => vi.fn(),
@ -29,7 +53,7 @@ describe('Axios boot', () => {
'Accept-Language': 'en-US', 'Accept-Language': 'en-US',
Authorization: 'DEFAULT_TOKEN', Authorization: 'DEFAULT_TOKEN',
}, },
}) }),
); );
}); });
}); });

View File

@ -13,13 +13,12 @@ import VnConfirm from './ui/VnConfirm.vue';
import { tMobile } from 'src/composables/tMobile'; import { tMobile } from 'src/composables/tMobile';
import { useArrayData } from 'src/composables/useArrayData'; import { useArrayData } from 'src/composables/useArrayData';
import { getDifferences, getUpdatedValues } from 'src/filters'; import { getDifferences, getUpdatedValues } from 'src/filters';
const { push } = useRouter(); const { push } = useRouter();
const quasar = useQuasar(); const quasar = useQuasar();
const state = useState(); const state = useState();
const stateStore = useStateStore(); const stateStore = useStateStore();
const { t } = useI18n(); const { t } = useI18n();
const { validate } = useValidator(); const { validate, validations } = useValidator();
const { notify } = useNotify(); const { notify } = useNotify();
const route = useRoute(); const route = useRoute();
const myForm = ref(null); const myForm = ref(null);
@ -119,7 +118,7 @@ const defaultButtons = computed(() => ({
color: 'primary', color: 'primary',
icon: 'save', icon: 'save',
label: 'globals.save', label: 'globals.save',
click: async () => await save(), click: async (evt) => submitForm(evt),
type: 'submit', type: 'submit',
}, },
reset: { reset: {
@ -132,6 +131,13 @@ const defaultButtons = computed(() => ({
...$props.defaultButtons, ...$props.defaultButtons,
})); }));
const submitForm = async (evt) => {
const isFormValid = await myForm.value.validate();
if (isFormValid) {
await save(evt);
}
};
onMounted(async () => { onMounted(async () => {
nextTick(() => (componentIsRendered.value = true)); nextTick(() => (componentIsRendered.value = true));
@ -227,10 +233,9 @@ async function save() {
const method = $props.urlCreate ? 'post' : 'patch'; const method = $props.urlCreate ? 'post' : 'patch';
const url = const url =
$props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url; $props.urlCreate || $props.urlUpdate || $props.url || arrayData.store.url;
let response; const response = await Promise.resolve(
$props.saveFn ? $props.saveFn(body) : axios[method](url, body),
if ($props.saveFn) response = await $props.saveFn(body); );
else response = await axios[method](url, body);
if ($props.urlCreate) notify('globals.dataCreated', 'positive'); if ($props.urlCreate) notify('globals.dataCreated', 'positive');
@ -307,11 +312,13 @@ async function onKeyup(evt) {
selectionStart = selectionEnd = selectionStart + 1; selectionStart = selectionEnd = selectionStart + 1;
return; return;
} }
await save(); await myForm.value.submit(evt);
} }
} }
defineExpose({ defineExpose({
submitForm,
myForm,
save, save,
isLoading, isLoading,
hasChanges, hasChanges,
@ -325,7 +332,7 @@ defineExpose({
<QForm <QForm
ref="myForm" ref="myForm"
v-if="formData" v-if="formData"
@submit.prevent @submit.prevent="save"
@keyup.prevent="onKeyup" @keyup.prevent="onKeyup"
@reset="reset" @reset="reset"
class="q-pa-md" class="q-pa-md"
@ -339,6 +346,7 @@ defineExpose({
name="form" name="form"
:data="formData" :data="formData"
:validate="validate" :validate="validate"
:validations="validations()"
:filter="filter" :filter="filter"
/> />
<SkeletonForm v-else /> <SkeletonForm v-else />

View File

@ -41,9 +41,12 @@ const onDataSaved = async (formData, requestResponse) => {
emit('onDataSaved', formData, requestResponse); emit('onDataSaved', formData, requestResponse);
}; };
const onClick = async (saveAndContinue) => { const onClick = async (saveAndContinue = showSaveAndContinueBtn) => {
await formModelRef.value.myForm.validate(true);
isSaveAndContinue.value = saveAndContinue; isSaveAndContinue.value = saveAndContinue;
await formModelRef.value.save(); if (formModelRef.value) {
await formModelRef.value.submitForm();
}
}; };
defineExpose({ defineExpose({
@ -59,16 +62,23 @@ defineExpose({
ref="formModelRef" ref="formModelRef"
:observe-form-changes="false" :observe-form-changes="false"
:default-actions="false" :default-actions="false"
@submit="onClick"
v-bind="$attrs" v-bind="$attrs"
@on-data-saved="onDataSaved" @on-data-saved="onDataSaved"
:prevent-submit="false"
> >
<template #form="{ data, validate }"> <template #form="{ data, validate, validations }">
<span ref="closeButton" class="close-icon" v-close-popup> <span ref="closeButton" class="close-icon" v-close-popup>
<QIcon name="close" size="sm" /> <QIcon name="close" size="sm" />
</span> </span>
<h1 class="title">{{ title }}</h1> <h1 class="title">{{ title }}</h1>
<p>{{ subtitle }}</p> <p>{{ subtitle }}</p>
<slot name="form-inputs" :data="data" :validate="validate" /> <slot
name="form-inputs"
:data="data"
:validate="validate"
:validations="validations"
/>
<div class="q-mt-lg row justify-end"> <div class="q-mt-lg row justify-end">
<QBtn <QBtn
:label="t('globals.cancel')" :label="t('globals.cancel')"
@ -87,12 +97,13 @@ defineExpose({
:flat="showSaveAndContinueBtn" :flat="showSaveAndContinueBtn"
:label="t('globals.save')" :label="t('globals.save')"
:title="t('globals.save')" :title="t('globals.save')"
@click="onClick(false)" :type="!showSaveAndContinueBtn ? 'submit' : 'button'"
color="primary" color="primary"
class="q-ml-sm" class="q-ml-sm"
:disabled="isLoading" :disabled="isLoading"
:loading="isLoading" :loading="isLoading"
data-cy="FormModelPopup_save" data-cy="FormModelPopup_save"
@click="showSaveAndContinueBtn ? onClick(false) : null"
z-max z-max
/> />
<QBtn <QBtn
@ -100,12 +111,13 @@ defineExpose({
:label="t('globals.isSaveAndContinue')" :label="t('globals.isSaveAndContinue')"
:title="t('globals.isSaveAndContinue')" :title="t('globals.isSaveAndContinue')"
color="primary" color="primary"
:type="showSaveAndContinueBtn ? 'submit' : 'button'"
class="q-ml-sm" class="q-ml-sm"
:disabled="isLoading" :disabled="isLoading"
:loading="isLoading" :loading="isLoading"
data-cy="FormModelPopup_isSaveAndContinue" data-cy="FormModelPopup_isSaveAndContinue"
@click="showSaveAndContinueBtn ? onClick(true) : null"
z-max z-max
@click="onClick(true)"
/> />
</div> </div>
</template> </template>

View File

@ -19,6 +19,7 @@ import { useQuasar, date } from 'quasar';
import { useStateStore } from 'stores/useStateStore'; import { useStateStore } from 'stores/useStateStore';
import { useFilterParams } from 'src/composables/useFilterParams'; import { useFilterParams } from 'src/composables/useFilterParams';
import { dashIfEmpty, toDate } from 'src/filters'; import { dashIfEmpty, toDate } from 'src/filters';
import { useTableHeight } from './filters/useTableHeight';
import CrudModel from 'src/components/CrudModel.vue'; import CrudModel from 'src/components/CrudModel.vue';
import FormModelPopup from 'components/FormModelPopup.vue'; import FormModelPopup from 'components/FormModelPopup.vue';
@ -117,7 +118,7 @@ const $props = defineProps({
}, },
tableHeight: { tableHeight: {
type: String, type: String,
default: '90vh', default: undefined,
}, },
footer: { footer: {
type: Boolean, type: Boolean,
@ -166,6 +167,7 @@ const tableRef = ref();
const params = ref(useFilterParams($attrs['data-key']).params); const params = ref(useFilterParams($attrs['data-key']).params);
const orders = ref(useFilterParams($attrs['data-key']).orders); const orders = ref(useFilterParams($attrs['data-key']).orders);
const app = inject('app'); const app = inject('app');
const tableHeight = useTableHeight();
const editingRow = ref(null); const editingRow = ref(null);
const editingField = ref(null); const editingField = ref(null);
@ -678,7 +680,7 @@ const rowCtrlClickFunction = computed(() => {
table-header-class="bg-header" table-header-class="bg-header"
card-container-class="grid-three" card-container-class="grid-three"
flat flat
:style="isTableMode && `max-height: ${tableHeight}`" :style="isTableMode && `max-height: ${$props.tableHeight || tableHeight}`"
:virtual-scroll="isTableMode" :virtual-scroll="isTableMode"
@virtual-scroll="handleScroll" @virtual-scroll="handleScroll"
@row-click="(event, row) => handleRowClick(event, row)" @row-click="(event, row) => handleRowClick(event, row)"
@ -1042,7 +1044,7 @@ const rowCtrlClickFunction = computed(() => {
:model="$attrs['data-key'] + 'Create'" :model="$attrs['data-key'] + 'Create'"
@on-data-saved="(_, res) => createForm.onDataSaved(res)" @on-data-saved="(_, res) => createForm.onDataSaved(res)"
> >
<template #form-inputs="{ data }"> <template #form-inputs="{ data, validations }">
<slot name="alter-create" :data="data"> <slot name="alter-create" :data="data">
<div :style="createComplement?.containerStyle"> <div :style="createComplement?.containerStyle">
<div <div
@ -1060,6 +1062,7 @@ const rowCtrlClickFunction = computed(() => {
:key="column.name" :key="column.name"
:name="`column-create-${column.name}`" :name="`column-create-${column.name}`"
:data="data" :data="data"
:validations="validations"
:column-name="column.name" :column-name="column.name"
:label="column.label" :label="column.label"
> >

View File

@ -1,8 +1,7 @@
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'; import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { createWrapper } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import VnVisibleColumn from '../VnVisibleColumn.vue'; import VnVisibleColumn from '../VnVisibleColumn.vue';
import { axios } from 'app/test/vitest/helper'; import { default as axios } from 'axios';
describe('VnVisibleColumns', () => { describe('VnVisibleColumns', () => {
let wrapper; let wrapper;
let vm; let vm;

View File

@ -0,0 +1,18 @@
import { onMounted, nextTick, ref } from 'vue';
export function useTableHeight() {
const tableHeight = ref('90vh');
onMounted(async () => {
await nextTick();
let height = 100;
Array.from(document.querySelectorAll('[role="toolbar"]'))
.filter((element) => window.getComputedStyle(element).display !== 'none')
.forEach(() => {
height -= 10;
});
tableHeight.value = `${height}vh`;
});
return tableHeight;
}

View File

@ -1,4 +1,6 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import CrudModel from 'components/CrudModel.vue'; import CrudModel from 'components/CrudModel.vue';
import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest'; import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest';

View File

@ -1,4 +1,5 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import EditForm from 'components/EditTableCellValueForm.vue'; import EditForm from 'components/EditTableCellValueForm.vue';
import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest';

View File

@ -1,4 +1,6 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import FilterItemForm from 'src/components/FilterItemForm.vue'; import FilterItemForm from 'src/components/FilterItemForm.vue';
import { vi, beforeAll, describe, expect, it } from 'vitest'; import { vi, beforeAll, describe, expect, it } from 'vitest';
@ -38,9 +40,9 @@ describe('FilterItemForm', () => {
{ relation: 'producer', scope: { fields: ['name'] } }, { relation: 'producer', scope: { fields: ['name'] } },
{ relation: 'ink', scope: { fields: ['name'] } }, { relation: 'ink', scope: { fields: ['name'] } },
], ],
where: {"name":{"like":"%bolas de madera%"}}, where: { name: { like: '%bolas de madera%' } },
}; };
expect(axios.get).toHaveBeenCalledWith('Items/withName', { expect(axios.get).toHaveBeenCalledWith('Items/withName', {
params: { filter: JSON.stringify(expectedFilter) }, params: { filter: JSON.stringify(expectedFilter) },
}); });
@ -79,4 +81,4 @@ describe('FilterItemForm', () => {
vm.selectItem({ id: 12345 }); vm.selectItem({ id: 12345 });
expect(wrapper.emitted('itemSelected')[0]).toEqual([12345]); expect(wrapper.emitted('itemSelected')[0]).toEqual([12345]);
}); });
}); });

View File

@ -1,5 +1,7 @@
import { describe, expect, it, beforeAll, vi, afterAll } from 'vitest'; import { describe, expect, it, beforeAll, vi, afterAll } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import FormModel from 'src/components/FormModel.vue'; import FormModel from 'src/components/FormModel.vue';
describe('FormModel', () => { describe('FormModel', () => {

View File

@ -1,6 +1,7 @@
import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { default as axios } from 'axios';
import Leftmenu from 'components/LeftMenu.vue'; import { createWrapper } from 'app/test/vitest/helper';
import LeftMenu from 'components/LeftMenu.vue';
import * as vueRouter from 'vue-router'; import * as vueRouter from 'vue-router';
import { useNavigationStore } from 'src/stores/useNavigationStore'; import { useNavigationStore } from 'src/stores/useNavigationStore';
@ -101,7 +102,7 @@ function mount(source = 'main') {
vi.spyOn(axios, 'get').mockResolvedValue({ vi.spyOn(axios, 'get').mockResolvedValue({
data: [], data: [],
}); });
const wrapper = createWrapper(Leftmenu, { const wrapper = createWrapper(LeftMenu, {
propsData: { propsData: {
source, source,
}, },
@ -164,7 +165,7 @@ describe('getRoutes', () => {
}); });
}); });
describe('Leftmenu as card', () => { describe('LeftMenu as card', () => {
beforeAll(() => { beforeAll(() => {
vm = mount('card').vm; vm = mount('card').vm;
}); });
@ -173,7 +174,7 @@ describe('Leftmenu as card', () => {
vm.getRoutes(); vm.getRoutes();
}); });
}); });
describe('Leftmenu as main', () => { describe('LeftMenu as main', () => {
beforeEach(() => { beforeEach(() => {
vm = mount().vm; vm = mount().vm;
}); });

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { watch } from 'vue'; import { watch } from 'vue';
import { toDateString } from 'src/filters'; import { toDateHourMinSec } from 'src/filters';
const props = defineProps({ const props = defineProps({
value: { type: [String, Number, Boolean, Object], default: undefined }, value: { type: [String, Number, Boolean, Object], default: undefined },
@ -40,7 +40,7 @@ const updateValue = () => {
break; break;
case 'object': case 'object':
if (props.value instanceof Date) { if (props.value instanceof Date) {
t = toDateString(props.value); t = toDateHourMinSec(props.value);
} else { } else {
t = props.value.toString(); t = props.value.toString();
} }

View File

@ -1,4 +1,5 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import VnChangePassword from 'src/components/common/VnChangePassword.vue'; import VnChangePassword from 'src/components/common/VnChangePassword.vue';
import { vi, beforeEach, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { vi, beforeEach, afterEach, beforeAll, describe, expect, it } from 'vitest';
import { Notify } from 'quasar'; import { Notify } from 'quasar';

View File

@ -1,4 +1,5 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest'; import { vi, afterEach, beforeEach, beforeAll, describe, expect, it } from 'vitest';
import VnDms from 'src/components/common/VnDms.vue'; import VnDms from 'src/components/common/VnDms.vue';
@ -40,7 +41,10 @@ describe('VnDms', () => {
companyFk: 2, companyFk: 2,
dmsTypeFk: 3, dmsTypeFk: 3,
description: 'This is a test description', description: 'This is a test description',
files: { name: 'example.txt', content: new Blob(['file content'], { type: 'text/plain' })}, files: {
name: 'example.txt',
content: new Blob(['file content'], { type: 'text/plain' }),
},
}; };
const expectedBody = { const expectedBody = {
@ -59,7 +63,7 @@ describe('VnDms', () => {
url: '/test', url: '/test',
formInitialData: { id: 1, reference: 'test' }, formInitialData: { id: 1, reference: 'test' },
model: 'Worker', model: 'Worker',
} },
}); });
wrapper = wrapper.wrapper; wrapper = wrapper.wrapper;
vm = wrapper.vm; vm = wrapper.vm;
@ -98,7 +102,7 @@ describe('VnDms', () => {
expect(vm.getUrl()).toBe('/test'); expect(vm.getUrl()).toBe('/test');
}); });
it('should returns url dms/"props.formInitialData.id"/updateFile when prop url is null', async () => { it('should returns url dms/"props.formInitialData.id"/updateFile when prop url is null', async () => {
await wrapper.setProps({ url: null }); await wrapper.setProps({ url: null });
expect(vm.getUrl()).toBe('dms/1/updateFile'); expect(vm.getUrl()).toBe('dms/1/updateFile');
}); });
@ -113,7 +117,9 @@ describe('VnDms', () => {
describe('save', () => { describe('save', () => {
it('should save data correctly', async () => { it('should save data correctly', async () => {
await vm.save(); await vm.save();
expect(postMock).toHaveBeenCalledWith(vm.getUrl(), expect.any(FormData), { params: expectedBody }); expect(postMock).toHaveBeenCalledWith(vm.getUrl(), expect.any(FormData), {
params: expectedBody,
});
expect(wrapper.emitted('onDataSaved')).toBeTruthy(); expect(wrapper.emitted('onDataSaved')).toBeTruthy();
}); });
}); });
@ -127,8 +133,8 @@ describe('VnDms', () => {
warehouseFk: 2, warehouseFk: 2,
companyFk: 3, companyFk: 3,
dmsTypeFk: 2, dmsTypeFk: 2,
description: 'This is a test description' description: 'This is a test description',
} };
await wrapper.setProps({ formInitialData: testData }); await wrapper.setProps({ formInitialData: testData });
vm.defaultData(); vm.defaultData();
@ -137,10 +143,10 @@ describe('VnDms', () => {
it('should add reference with "route.params.id" to dms if formInitialData is null', async () => { it('should add reference with "route.params.id" to dms if formInitialData is null', async () => {
await wrapper.setProps({ formInitialData: null }); await wrapper.setProps({ formInitialData: null });
vm.route.params.id= '111'; vm.route.params.id = '111';
vm.defaultData(); vm.defaultData();
expect(vm.dms.reference).toBe('111'); expect(vm.dms.reference).toBe('111');
}); });
}); });
}); });

View File

@ -1,4 +1,6 @@
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import VnDmsList from 'src/components/common/VnDmsList.vue'; import VnDmsList from 'src/components/common/VnDmsList.vue';
import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest'; import { vi, afterEach, beforeAll, describe, expect, it } from 'vitest';

View File

@ -65,7 +65,7 @@ describe('VnJsonValue', () => {
const date = new Date('2023-01-01'); const date = new Date('2023-01-01');
const wrapper = buildComponent({ value: date }); const wrapper = buildComponent({ value: date });
const span = wrapper.find('span'); const span = wrapper.find('span');
expect(span.text()).toBe('2023-01-01'); expect(span.text()).toBe('01/01/2023, 01:00:00');
expect(span.classes()).toContain('json-object'); expect(span.classes()).toContain('json-object');
}); });

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import VnLog from 'src/components/common/VnLog.vue'; import VnLog from 'src/components/common/VnLog.vue';
describe('VnLog', () => { describe('VnLog', () => {

View File

@ -1,5 +1,6 @@
import { describe, it, expect, vi, afterEach, beforeEach, afterAll } from 'vitest'; import { describe, it, expect, vi, afterEach, beforeEach, afterAll } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import VnNotes from 'src/components/ui/VnNotes.vue'; import VnNotes from 'src/components/ui/VnNotes.vue';
describe('VnNotes', () => { describe('VnNotes', () => {

View File

@ -1,5 +1,7 @@
import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import { default as axios } from 'axios';
import CardSummary from 'src/components/ui/CardSummary.vue'; import CardSummary from 'src/components/ui/CardSummary.vue';
import * as vueRouter from 'vue-router'; import * as vueRouter from 'vue-router';

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import VnPaginate from 'src/components/ui/VnPaginate.vue'; import VnPaginate from 'src/components/ui/VnPaginate.vue';
describe('VnPaginate', () => { describe('VnPaginate', () => {

View File

@ -1,5 +1,5 @@
import { describe, it, expect, beforeAll, vi } from 'vitest'; import { describe, it, expect, beforeAll, vi } from 'vitest';
import { axios } from 'app/test/vitest/helper'; import axios from 'axios';
import parsePhone from 'src/filters/parsePhone'; import parsePhone from 'src/filters/parsePhone';
describe('parsePhone filter', () => { describe('parsePhone filter', () => {

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import VnSms from 'src/components/ui/VnSms.vue'; import VnSms from 'src/components/ui/VnSms.vue';
describe('VnSms', () => { describe('VnSms', () => {

View File

@ -1,5 +1,5 @@
import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest';
import { axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { downloadFile } from 'src/composables/downloadFile'; import { downloadFile } from 'src/composables/downloadFile';
import { useSession } from 'src/composables/useSession'; import { useSession } from 'src/composables/useSession';
const session = useSession(); const session = useSession();

View File

@ -1,5 +1,7 @@
import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterAll } from 'vitest';
import { axios, flushPromises } from 'app/test/vitest/helper'; import axios from 'axios';
import { flushPromises } from '@vue/test-utils';
import { useAcl } from 'src/composables/useAcl'; import { useAcl } from 'src/composables/useAcl';
describe('useAcl', () => { describe('useAcl', () => {

View File

@ -1,15 +1,39 @@
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'; import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { axios, flushPromises } from 'app/test/vitest/helper'; import { default as axios } from 'axios';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import * as vueRouter from 'vue-router'; import * as vueRouter from 'vue-router';
import { setActivePinia, createPinia } from 'pinia';
describe('useArrayData', () => { describe('useArrayData', () => {
const filter = '{"limit":20,"skip":0}'; const filter = '{"limit":20,"skip":0}';
const params = { supplierFk: 2 }; const params = { supplierFk: 2 };
beforeEach(() => { beforeEach(() => {
vi.spyOn(useRouter(), 'replace'); setActivePinia(createPinia());
vi.spyOn(useRouter(), 'push');
// Mock route
vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
path: 'mockSection/list',
matched: [],
query: {},
params: {},
meta: { moduleName: 'mockName' },
});
// Mock router
vi.spyOn(vueRouter, 'useRouter').mockReturnValue({
push: vi.fn(),
replace: vi.fn(),
currentRoute: {
value: {
path: 'mockSection/list',
params: { id: 1 },
meta: { moduleName: 'mockName' },
matched: [{ path: 'mockName/:id' }],
},
},
});
}); });
afterEach(() => { afterEach(() => {
@ -17,103 +41,69 @@ describe('useArrayData', () => {
}); });
it('should fetch and replace url with new params', async () => { it('should fetch and replace url with new params', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [] }); vi.spyOn(axios, 'get').mockResolvedValueOnce({ data: [] });
const arrayData = useArrayData('ArrayData', { url: 'mockUrl' }); const arrayData = useArrayData('ArrayData', {
url: 'mockUrl',
searchUrl: 'params',
});
arrayData.store.userParams = params; arrayData.store.userParams = params;
arrayData.fetch({}); await arrayData.fetch({});
await flushPromises();
const routerReplace = useRouter().replace.mock.calls[0][0]; const routerReplace = useRouter().replace.mock.calls[0][0];
expect(axios.get.mock.calls[0][1].params).toEqual({ expect(axios.get).toHaveBeenCalledWith('mockUrl', {
filter, signal: expect.any(Object),
supplierFk: 2, params: {
filter,
supplierFk: 2,
},
}); });
expect(routerReplace.path).toEqual('mockSection/list');
expect(routerReplace.path).toBe('mockSection/list');
expect(JSON.parse(routerReplace.query.params)).toEqual( expect(JSON.parse(routerReplace.query.params)).toEqual(
expect.objectContaining(params), expect.objectContaining(params),
); );
}); });
it('should get data and send new URL without keeping parameters, if there is only one record', async () => { it('should redirect to detail when single record is returned with navigation', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }] }); vi.spyOn(axios, 'get').mockResolvedValueOnce({
data: [{ id: 1 }],
});
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', navigate: {} }); const arrayData = useArrayData('ArrayData', {
url: 'mockUrl',
navigate: {},
});
arrayData.store.userParams = params; arrayData.store.userParams = params;
arrayData.fetch({}); await arrayData.fetch({});
await flushPromises();
const routerPush = useRouter().push.mock.calls[0][0]; const routerPush = useRouter().push.mock.calls[0][0];
expect(axios.get.mock.calls[0][1].params).toEqual({ expect(routerPush.path).toBe('mockName/1');
filter,
supplierFk: 2,
});
expect(routerPush.path).toEqual('mockName/1');
expect(routerPush.query).toBeUndefined(); expect(routerPush.query).toBeUndefined();
}); });
it('should get data and send new URL keeping parameters, if you have more than one record', async () => { it('should return one record when oneRecord is true', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [{ id: 1 }, { id: 2 }] }); vi.spyOn(axios, 'get').mockResolvedValueOnce({
vi.spyOn(vueRouter, 'useRoute').mockReturnValue({
matched: [],
query: {},
params: {},
meta: { moduleName: 'mockName' },
path: 'mockName/1',
});
vi.spyOn(vueRouter, 'useRouter').mockReturnValue({
push: vi.fn(),
replace: vi.fn(),
currentRoute: {
value: {
params: {
id: 1,
},
meta: { moduleName: 'mockName' },
matched: [{ path: 'mockName/:id' }],
},
},
});
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', navigate: {} });
arrayData.store.userParams = params;
arrayData.fetch({});
await flushPromises();
const routerPush = useRouter().push.mock.calls[0][0];
expect(axios.get.mock.calls[0][1].params).toEqual({
filter,
supplierFk: 2,
});
expect(routerPush.path).toEqual('mockName/');
expect(routerPush.query.params).toBeDefined();
});
it('should return one record', async () => {
vi.spyOn(axios, 'get').mockReturnValueOnce({
data: [ data: [
{ id: 1, name: 'Entity 1' }, { id: 1, name: 'Entity 1' },
{ id: 2, name: 'Entity 2' }, { id: 2, name: 'Entity 2' },
], ],
}); });
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', oneRecord: true });
const arrayData = useArrayData('ArrayData', {
url: 'mockUrl',
oneRecord: true,
});
await arrayData.fetch({}); await arrayData.fetch({});
expect(arrayData.store.data).toEqual({ id: 1, name: 'Entity 1' }); expect(arrayData.store.data).toEqual({
}); id: 1,
name: 'Entity 1',
it('should handle empty data gracefully if has to return one record', async () => { });
vi.spyOn(axios, 'get').mockReturnValueOnce({ data: [] });
const arrayData = useArrayData('ArrayData', { url: 'mockUrl', oneRecord: true });
await arrayData.fetch({});
expect(arrayData.store.data).toBeUndefined();
}); });
}); });

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it } from 'vitest'; import { vi, describe, expect, it } from 'vitest';
import { axios, flushPromises } from 'app/test/vitest/helper'; import axios from 'axios';
import { flushPromises } from '@vue/test-utils';
import { useRole } from 'composables/useRole'; import { useRole } from 'composables/useRole';
const role = useRole(); const role = useRole();

View File

@ -1,5 +1,5 @@
import { vi, describe, expect, it, beforeAll, beforeEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, beforeEach } from 'vitest';
import { axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { useSession } from 'composables/useSession'; import { useSession } from 'composables/useSession';
import { useState } from 'composables/useState'; import { useState } from 'composables/useState';

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it } from 'vitest'; import { vi, describe, expect, it } from 'vitest';
import { axios, flushPromises } from 'app/test/vitest/helper'; import axios from 'axios';
import { flushPromises } from '@vue/test-utils';
import { useTokenConfig } from 'composables/useTokenConfig'; import { useTokenConfig } from 'composables/useTokenConfig';
const tokenConfig = useTokenConfig(); const tokenConfig = useTokenConfig();

View File

@ -5,12 +5,11 @@ import { useArrayDataStore } from 'stores/useArrayDataStore';
import { buildFilter } from 'filters/filterPanel'; import { buildFilter } from 'filters/filterPanel';
import { isDialogOpened } from 'src/filters'; import { isDialogOpened } from 'src/filters';
const arrayDataStore = useArrayDataStore();
export function useArrayData(key, userOptions) { export function useArrayData(key, userOptions) {
key ??= useRoute().meta.moduleName; key ??= useRoute().meta.moduleName;
if (!key) throw new Error('ArrayData: A key is required to use this composable'); if (!key) throw new Error('ArrayData: A key is required to use this composable');
const arrayDataStore = useArrayDataStore(); // Move inside function
if (!arrayDataStore.get(key)) arrayDataStore.set(key); if (!arrayDataStore.get(key)) arrayDataStore.set(key);

View File

@ -60,7 +60,7 @@ export function useSession() {
const { data: isValidToken } = await axios.get('VnUsers/validateToken'); const { data: isValidToken } = await axios.get('VnUsers/validateToken');
if (isValidToken) if (isValidToken)
destroyTokenPromises = Object.entries(tokens).map(([key, url]) => destroyTokenPromises = Object.entries(tokens).map(([key, url]) =>
destroyToken(url, storage, key) destroyToken(url, storage, key),
); );
} }
} finally { } finally {

View File

@ -78,7 +78,8 @@ export function useValidator() {
if (min >= 0) if (min >= 0)
if (Math.floor(value) < min) return t('inputMin', { value: min }); if (Math.floor(value) < min) return t('inputMin', { value: min });
}, },
custom: (value) => validation.bindedFunction(value) || 'Invalid value', custom: (value) =>
eval(`(${validation.bindedFunction})`)(value) || 'Invalid value',
}; };
}; };

View File

@ -340,3 +340,6 @@ input::-webkit-inner-spin-button {
.containerShrinked { .containerShrinked {
width: 70%; width: 70%;
} }
.q-item__section--main ~ .q-item__section--side {
padding-inline: 0;
}

View File

@ -88,13 +88,13 @@ const columns = [
auto-load auto-load
> >
<template #column-itemFk="{ row }"> <template #column-itemFk="{ row }">
<span class="link"> <span class="link" @click.stop>
{{ row.itemFk }} {{ row.itemFk }}
<ItemDescriptorProxy :id="row.itemFk" /> <ItemDescriptorProxy :id="row.itemFk" />
</span> </span>
</template> </template>
<template #column-ticketFk="{ row }"> <template #column-ticketFk="{ row }">
<span class="link"> <span class="link" @click.stop>
{{ row.ticketFk }} {{ row.ticketFk }}
<TicketDescriptorProxy :id="row.ticketFk" /> <TicketDescriptorProxy :id="row.ticketFk" />
</span> </span>

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import ClaimDescriptorMenu from 'pages/Claim/Card/ClaimDescriptorMenu.vue'; import ClaimDescriptorMenu from 'pages/Claim/Card/ClaimDescriptorMenu.vue';
describe('ClaimDescriptorMenu', () => { describe('ClaimDescriptorMenu', () => {

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import ClaimLines from '/src/pages/Claim/Card/ClaimLines.vue'; import ClaimLines from '/src/pages/Claim/Card/ClaimLines.vue';
describe('ClaimLines', () => { describe('ClaimLines', () => {

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, beforeEach, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import ClaimLinesImport from 'pages/Claim/Card/ClaimLinesImport.vue'; import ClaimLinesImport from 'pages/Claim/Card/ClaimLinesImport.vue';
describe('ClaimLinesImport', () => { describe('ClaimLinesImport', () => {

View File

@ -1,7 +1,7 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import ClaimPhoto from 'pages/Claim/Card/ClaimPhoto.vue'; import ClaimPhoto from 'pages/Claim/Card/ClaimPhoto.vue';
describe('ClaimPhoto', () => { describe('ClaimPhoto', () => {
let vm; let vm;
@ -61,7 +61,7 @@ describe('ClaimPhoto', () => {
title: 'This file will be deleted', title: 'This file will be deleted',
icon: 'delete', icon: 'delete',
data: { index: 1 }, data: { index: 1 },
promise: vm.deleteDms promise: vm.deleteDms,
}, },
}) })
); );

View File

@ -79,7 +79,7 @@ async function acceptPropagate({ isEqualizated }) {
observe-form-changes observe-form-changes
@on-data-saved="checkEtChanges" @on-data-saved="checkEtChanges"
> >
<template #form="{ data, validate }"> <template #form="{ data, validate, validations }">
<VnRow> <VnRow>
<VnInput <VnInput
:label="t('Social name')" :label="t('Social name')"
@ -112,6 +112,7 @@ async function acceptPropagate({ isEqualizated }) {
v-model="data.sageTaxTypeFk" v-model="data.sageTaxTypeFk"
data-cy="sageTaxTypeFk" data-cy="sageTaxTypeFk"
:required="data.isTaxDataChecked" :required="data.isTaxDataChecked"
:rules="[(val) => validations.required(data.isTaxDataChecked, val)]"
/> />
<VnSelect <VnSelect
:label="t('Sage transaction type')" :label="t('Sage transaction type')"
@ -122,6 +123,9 @@ async function acceptPropagate({ isEqualizated }) {
data-cy="sageTransactionTypeFk" data-cy="sageTransactionTypeFk"
v-model="data.sageTransactionTypeFk" v-model="data.sageTransactionTypeFk"
:required="data.isTaxDataChecked" :required="data.isTaxDataChecked"
:rules="[
(val) => validations.required(data.sageTransactionTypeFk, val),
]"
> >
<template #option="scope"> <template #option="scope">
<QItem v-bind="scope.itemProps"> <QItem v-bind="scope.itemProps">

View File

@ -181,7 +181,7 @@ const sumRisk = ({ clientRisks }) => {
<QCard class="vn-one"> <QCard class="vn-one">
<VnTitle <VnTitle
:url="`#/customer/${entityId}/billing-data`" :url="`#/customer/${entityId}/billing-data`"
:text="t('customer.summary.billingData')" :text="t('customer.summary.payMethodFk')"
/> />
<VnLv <VnLv
:label="t('customer.summary.payMethod')" :label="t('customer.summary.payMethod')"

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import CustomerPayments from 'src/pages/Customer/Payments/CustomerPayments.vue'; import CustomerPayments from 'src/pages/Customer/Payments/CustomerPayments.vue';
describe('CustomerPayments', () => { describe('CustomerPayments', () => {

View File

@ -787,7 +787,7 @@ onMounted(() => {
<span data-cy="footer-amount">{{ footer?.amount }} / </span> <span data-cy="footer-amount">{{ footer?.amount }} / </span>
<span style="color: var(--q-positive)">{{ footer?.checkedAmount }}</span> <span style="color: var(--q-positive)">{{ footer?.checkedAmount }}</span>
</template> </template>
<template #column-create-itemFk="{ data }"> <template #column-create-itemFk="{ data, validations }">
<VnSelect <VnSelect
url="Items/search" url="Items/search"
v-model="data.itemFk" v-model="data.itemFk"
@ -801,7 +801,8 @@ onMounted(() => {
await setBuyUltimate(value, data); await setBuyUltimate(value, data);
} }
" "
:required="true" required
:rules="[(val) => validations.required(true, val)]"
data-cy="itemFk-create-popup" data-cy="itemFk-create-popup"
sort-by="nickname DESC" sort-by="nickname DESC"
> >

View File

@ -79,6 +79,30 @@ const columns = computed(() => [
inWhere: true, inWhere: true,
}, },
}, },
{
align: 'left',
name: 'issued',
label: t('invoiceOut.summary.issued'),
component: 'date',
format: (row) => toDate(row.issued),
columnField: { component: null },
},
{
align: 'left',
name: 'created',
label: t('globals.created'),
component: 'date',
columnField: { component: null },
format: (row) => toDate(row.created),
},
{
align: 'left',
name: 'dued',
label: t('invoiceOut.summary.expirationDate'),
component: 'date',
columnField: { component: null },
format: (row) => toDate(row.dued),
},
{ {
align: 'left', align: 'left',
name: 'clientFk', name: 'clientFk',
@ -132,22 +156,6 @@ const columns = computed(() => [
cardVisible: true, cardVisible: true,
format: (row) => toCurrency(row.amount), format: (row) => toCurrency(row.amount),
}, },
{
align: 'left',
name: 'created',
label: t('globals.created'),
component: 'date',
columnField: { component: null },
format: (row) => toDate(row.created),
},
{
align: 'left',
name: 'dued',
label: t('invoiceOut.summary.dued'),
component: 'date',
columnField: { component: null },
format: (row) => toDate(row.dued),
},
{ {
align: 'left', align: 'left',
name: 'customsAgentFk', name: 'customsAgentFk',

View File

@ -22,7 +22,7 @@ const $props = defineProps({
}); });
</script> </script>
<template> <template>
<QPopupProxy style="max-width: 10px"> <QPopupProxy style="max-width: 10px" data-cy="ItemDescriptor">
<ItemDescriptor <ItemDescriptor
v-if="$props.id" v-if="$props.id"
:id="$props.id" :id="$props.id"

View File

@ -7,7 +7,7 @@ import FetchData from 'components/FetchData.vue';
import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue'; import VnFilterPanel from 'src/components/ui/VnFilterPanel.vue';
import VnSelect from 'src/components/common/VnSelect.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnInput from 'src/components/common/VnInput.vue'; import VnInput from 'src/components/common/VnInput.vue';
import { QCheckbox } from 'quasar'; import VnCheckbox from 'src/components/common/VnCheckbox.vue';
import { useArrayData } from 'composables/useArrayData'; import { useArrayData } from 'composables/useArrayData';
import { useValidator } from 'src/composables/useValidator'; import { useValidator } from 'src/composables/useValidator';
@ -250,10 +250,9 @@ onMounted(async () => {
</QItemSection> </QItemSection>
</QItem> </QItem>
<!-- Tags filter --> <!-- Tags filter -->
<QItem class="row items-center"> <QItemLabel header>
<QItemLabel> {{ t('params.tags') }}
{{ t('params.tags') }}
</QItemLabel>
<QIcon <QIcon
name="add_circle" name="add_circle"
class="fill-icon-on-hover q-ml-md" class="fill-icon-on-hover q-ml-md"
@ -261,7 +260,7 @@ onMounted(async () => {
color="primary" color="primary"
@click="tagValues.push({})" @click="tagValues.push({})"
/> />
</QItem> </QItemLabel>
<QItem <QItem
v-for="(tag, index) in tagValues" v-for="(tag, index) in tagValues"
:key="index" :key="index"
@ -269,6 +268,7 @@ onMounted(async () => {
> >
<QItemSection class="col"> <QItemSection class="col">
<VnSelect <VnSelect
class="full-width"
:label="t('params.tag')" :label="t('params.tag')"
v-model="tag.selectedTag" v-model="tag.selectedTag"
:options="tagOptions" :options="tagOptions"
@ -316,25 +316,19 @@ onMounted(async () => {
/> />
</QItem> </QItem>
<!-- Filter fields --> <!-- Filter fields -->
<QItem class="row items-center"> <QItemLabel header
<QItemLabel> >{{ t('More fields') }}
{{ t('More fields') }}
</QItemLabel>
<QIcon <QIcon
name="add_circle" name="add_circle"
class="fill-icon-on-hover q-ml-md" class="fill-icon-on-hover q-ml-md"
size="sm" size="sm"
color="primary" color="primary"
@click="fieldFiltersValues.push({})" @click="fieldFiltersValues.push({})"
/> /></QItemLabel>
</QItem> <QItem v-for="(fieldFilter, index) in fieldFiltersValues" :key="index">
<QItem
v-for="(fieldFilter, index) in fieldFiltersValues"
:key="index"
class="row items-center"
>
<QItemSection class="col"> <QItemSection class="col">
<VnSelect <VnSelect
class="full-width"
:label="t('params.tag')" :label="t('params.tag')"
:model-value="fieldFilter.selectedField" :model-value="fieldFilter.selectedField"
:options="moreFields" :options="moreFields"
@ -355,7 +349,7 @@ onMounted(async () => {
/> />
</QItemSection> </QItemSection>
<QItemSection class="col"> <QItemSection class="col">
<QCheckbox <VnCheckbox
v-if="fieldFilter.selectedField?.type === 'boolean'" v-if="fieldFilter.selectedField?.type === 'boolean'"
v-model="fieldFilter.value" v-model="fieldFilter.value"
:label="t('params.value')" :label="t('params.value')"
@ -370,13 +364,14 @@ onMounted(async () => {
@keydown.enter="applyFieldFilters(params, searchFn)" @keydown.enter="applyFieldFilters(params, searchFn)"
/> />
</QItemSection> </QItemSection>
<QIcon <QItemSection side
name="delete" ><QIcon
class="fill-icon-on-hover q-ml-xs" name="delete"
size="sm" class="fill-icon-on-hover q-ml-xs"
color="primary" size="sm"
@click="removeFieldFilter(index, params, searchFn)" color="primary"
/> @click="removeFieldFilter(index, params, searchFn)"
/></QItemSection>
</QItem> </QItem>
<QItem> <QItem>
<QItemSection> <QItemSection>

View File

@ -1,6 +1,7 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import { createWrapper } from 'app/test/vitest/helper';
import Login from 'pages/Login/LoginMain.vue'; import Login from 'pages/Login/LoginMain.vue';
import axios from 'axios';
describe('Login', () => { describe('Login', () => {
let vm; let vm;

View File

@ -91,7 +91,7 @@ const totalPrice = computed(() => {
const totalNewPrice = computed(() => { const totalNewPrice = computed(() => {
return rows.value.reduce( return rows.value.reduce(
(acc, item) => acc + item.component.newPrice * item.quantity, (acc, item) => acc + item.component.newPrice * item.quantity,
0 0,
); );
}); });
@ -210,18 +210,18 @@ onMounted(async () => {
flat flat
> >
<template #body-cell-item="{ row }"> <template #body-cell-item="{ row }">
<QTd @click.stop class="link"> <QTd align="center">
<QBtn flat> <span @click.stop class="link">
{{ row.itemFk }} {{ row.itemFk }}
<ItemDescriptorProxy :id="row.itemFk" /> <ItemDescriptorProxy :id="row.itemFk" />
</QBtn> </span>
</QTd> </QTd>
</template> </template>
<template #body-cell-description="{ row }"> <template #body-cell-description="{ row }">
<QTd style="min-width: 120px; max-width: 120px"> <QTd style="min-width: 120px; max-width: 120px">
<div class="column q-pb-xs" style="min-width: 120px"> <div class="column q-pb-xs" style="min-width: 120px">
<span>{{ row.item.name }}</span> <span>{{ row.item.name }}</span>
<FetchedTags :item="row.item" class="full-width" /> <FetchedTags :item="row.item" class="full-width" :columns="6" />
</div> </div>
</QTd> </QTd>
</template> </template>

View File

@ -1,59 +0,0 @@
<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnRow from 'components/ui/VnRow.vue';
import VnSelect from 'src/components/common/VnSelect.vue';
import FetchData from 'components/FetchData.vue';
import { useState } from 'src/composables/useState';
import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
const emit = defineEmits(['onRequestCreated']);
const route = useRoute();
const { t } = useI18n();
const state = useState();
const user = state.getUser();
const stateFetchDataRef = ref(null);
const statesOptions = ref([]);
const onStateFkChange = (formData) => (formData.userFk = user.value.id);
</script>
<template>
<FetchData
ref="stateFetchDataRef"
url="States"
auto-load
@on-fetch="(data) => (statesOptions = data)"
/>
<FormModelPopup
:title="t('Create tracking')"
url-create="Tickets/state"
model="CreateTicketTracking"
:form-initial-data="{ ticketFk: route.params.id }"
@on-data-saved="() => emit('onRequestCreated')"
>
<template #form-inputs="{ data }">
<VnRow>
<VnSelect
v-model="data.stateFk"
:label="t('ticketList.state')"
:options="statesOptions"
@update:model-value="onStateFkChange(data)"
hide-selected
option-label="name"
option-value="id"
/>
<VnSelectWorker v-model="data.userFk" :fields="['id', 'name']" />
</VnRow>
</template>
</FormModelPopup>
</template>
<i18n>
es:
Create tracking: Crear estado
</i18n>

View File

@ -99,6 +99,7 @@ const columns = computed(() => [
align: 'left', align: 'left',
label: t('globals.quantity'), label: t('globals.quantity'),
name: 'quantity', name: 'quantity',
class: 'shrink',
format: (row) => toCurrency(row.quantity), format: (row) => toCurrency(row.quantity),
}, },
{ {
@ -795,7 +796,7 @@ watch(
{{ row?.item?.subName.toUpperCase() }} {{ row?.item?.subName.toUpperCase() }}
</div> </div>
</div> </div>
<FetchedTags v-if="row.item" :item="row.item" :max-length="6" /> <FetchedTags v-if="row.item" :item="row.item" :columns="6" :max-length="6" />
<QPopupProxy v-if="row.id && isTicketEditable"> <QPopupProxy v-if="row.id && isTicketEditable">
<VnInput <VnInput
v-model="row.concept" v-model="row.concept"

View File

@ -1,27 +1,23 @@
<script setup> <script setup>
import { ref, computed, watch, reactive } from 'vue'; import { ref, reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue'; import WorkerDescriptorProxy from 'src/pages/Worker/Card/WorkerDescriptorProxy.vue';
import TicketCreateTracking from './TicketCreateTracking.vue'; import VnSelect from 'src/components/common/VnSelect.vue';
import VnPaginate from 'components/ui/VnPaginate.vue'; import VnSelectWorker from 'src/components/common/VnSelectWorker.vue';
import { useState } from 'src/composables/useState';
import { toDateTimeFormat } from 'src/filters/date.js'; import { toDateTimeFormat } from 'src/filters/date.js';
import VnTable from 'src/components/VnTable/VnTable.vue';
const state = useState();
const user = state.getUser();
const route = useRoute(); const route = useRoute();
const { t } = useI18n(); const { t } = useI18n();
const createTrackingDialogRef = ref(null); const tableRef = ref(null);
const paginateRef = ref(null); const onStateFkChange = (formData) => (formData.userFk = user.value.id);
watch(
() => route.params.id,
async (val) => {
paginateFilter.where.ticketFk = val;
paginateRef.value.fetch();
},
);
const paginateFilter = reactive({ const paginateFilter = reactive({
include: [ include: [
{ {
@ -56,75 +52,68 @@ const columns = computed(() => [
name: 'state', name: 'state',
field: 'state', field: 'state',
align: 'left', align: 'left',
format: (val) => val.name, format: (row) => row.state?.name,
}, },
{ {
label: t('expedition.worker'), label: t('expedition.worker'),
name: 'worker', name: 'worker',
align: 'left', align: 'left',
field: 'user',
}, },
{ {
label: t('expedition.created'), label: t('expedition.created'),
name: 'created', name: 'created',
field: 'created', field: 'created',
align: 'left', align: 'left',
format: (val) => toDateTimeFormat(val), format: ({ created }) => toDateTimeFormat(created),
}, },
]); ]);
const openCreateModal = () => createTrackingDialogRef.value.show();
</script> </script>
<template> <template>
<QPage class="column items-center q-pa-md"> <VnTable
<VnPaginate ref="tableRef"
ref="paginateRef" :right-search="false"
data-key="TicketTracking" :column-search="false"
:user-filter="paginateFilter" :disable-option="{ card: true, table: true }"
search-url="table" :search-url="false"
url="TicketTrackings" :columns="columns"
auto-load data-key="TicketTracking"
order="created DESC" :user-filter="paginateFilter"
:limit="0" url="TicketTrackings"
> auto-load
<template #body="{ rows }"> order="created DESC"
<QTable :limit="0"
:rows="rows" :without-header="true"
:columns="columns" :create="{
row-key="id" urlCreate: 'Tickets/state',
:pagination="{ rowsPerPage: 0 }" title: t('Create tracking'),
class="full-width q-mt-md" onDataSaved: () => tableRef.reload(),
:no-data-label="t('globals.noResults')" formInitialData: {
> ticketFk: route.params.id,
<template #body-cell-worker="{ row }"> },
<QTd> }"
<QBtn flat class="link" @click.stop> >
{{ row.user?.name }} <template #more-create-dialog="{ data }">
<WorkerDescriptorProxy :id="row.user?.worker?.id" /> <VnSelect
</QBtn> url="States"
</QTd> v-model="data.stateFk"
</template> :label="t('ticketList.state')"
</QTable> auto-load
</template> @update:model-value="onStateFkChange(data)"
</VnPaginate> hide-selected
<QDialog
ref="createTrackingDialogRef"
transition-show="scale"
transition-hide="scale"
>
<TicketCreateTracking @on-request-created="paginateRef.fetch()" />
</QDialog>
<QPageSticky :offset="[20, 20]">
<QBtn
@click="openCreateModal()"
color="primary"
fab
icon="add"
v-shortcut="'+'"
/> />
<QTooltip class="text-no-wrap"> <VnSelectWorker v-model="data.userFk" :fields="['id', 'name']" />
{{ t('tracking.addState') }} </template>
</QTooltip> <template #column-worker="{ row }">
</QPageSticky> <span class="link" @click.stop>
</QPage> {{ row.user.name }}
<WorkerDescriptorProxy :id="row.user?.worker?.id" />
</span>
</template>
</VnTable>
</template> </template>
<i18n>
es:
Create tracking: Crear estado
</i18n>

View File

@ -134,7 +134,7 @@ onMounted(() => (stateStore.rightDrawer = true));
auto-load auto-load
> >
<template #column-itemFk="{ row }"> <template #column-itemFk="{ row }">
<span class="link"> <span class="link" @click.stop>
{{ row.itemFk }} {{ row.itemFk }}
<ItemDescriptorProxy :id="row.itemFk" /> <ItemDescriptorProxy :id="row.itemFk" />
</span> </span>

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import TicketBoxing from 'pages/Ticket/Card/TicketBoxing.vue'; import TicketBoxing from 'pages/Ticket/Card/TicketBoxing.vue';
// #4836 - Investigate how to test q-drawer outside // #4836 - Investigate how to test q-drawer outside
@ -21,7 +22,11 @@ describe('TicketBoxing', () => {
min: 1, min: 1,
max: 2, max: 2,
}; };
const videoList = ['2022-01-01T01-01-00.mp4', '2022-02-02T02-02-00.mp4', '2022-03-03T03-03-00.mp4']; const videoList = [
'2022-01-01T01-01-00.mp4',
'2022-02-02T02-02-00.mp4',
'2022-03-03T03-03-00.mp4',
];
vi.spyOn(axios, 'get').mockResolvedValue({ data: videoList }); vi.spyOn(axios, 'get').mockResolvedValue({ data: videoList });
vi.spyOn(vm.quasar, 'notify'); vi.spyOn(vm.quasar, 'notify');
@ -44,7 +49,9 @@ describe('TicketBoxing', () => {
await vm.getVideoList(expeditionId, timed); await vm.getVideoList(expeditionId, timed);
expect(vm.quasar.notify).toHaveBeenCalledWith(expect.objectContaining({ type: 'negative' })); expect(vm.quasar.notify).toHaveBeenCalledWith(
expect.objectContaining({ type: 'negative' })
);
}); });
}); });
}); });

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach, beforeEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import TicketAdvance from 'pages/Ticket/TicketAdvance.vue'; import TicketAdvance from 'pages/Ticket/TicketAdvance.vue';
import { Notify } from 'quasar'; import { Notify } from 'quasar';
import { nextTick } from 'vue'; import { nextTick } from 'vue';

View File

@ -1,5 +1,6 @@
import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest'; import { vi, describe, expect, it, beforeAll, afterEach } from 'vitest';
import { createWrapper, axios } from 'app/test/vitest/helper'; import axios from 'axios';
import { createWrapper } from 'app/test/vitest/helper';
import WagonCreate from 'pages/Wagon/WagonCreate.vue'; import WagonCreate from 'pages/Wagon/WagonCreate.vue';
describe('WagonCreate', () => { describe('WagonCreate', () => {

View File

@ -166,50 +166,44 @@ const yearList = ref(generateYears());
}} }}
</QCardSection> </QCardSection>
</div> </div>
<QList dense class="list q-gutter-y-sm q-my-lg"> <div dense class="column q-gutter-y-sm q-px-md">
<QItem> <VnSelect
<QItemSection> :label="t('Year')"
<VnSelect v-model="selectedYear"
:label="t('Year')" :options="yearList"
v-model="selectedYear" dense
:options="yearList" filled
dense use-input
filled :is-clearable="false"
use-input />
:is-clearable="false" <VnSelect
/> :label="t('Contract')"
</QItemSection> v-model="selectedBusinessFk"
<QItemSection> :options="contractList"
<VnSelect option-value="businessFk"
:label="t('Contract')" option-label="businessFk"
v-model="selectedBusinessFk" dense
:options="contractList" filled
option-value="businessFk" use-input
option-label="businessFk" :is-clearable="false"
dense >
filled <template #option="scope">
use-input <QItem v-bind="scope.itemProps">
:is-clearable="false" <QItemSection>
> <QItemLabel># {{ scope.opt?.businessFk }}</QItemLabel>
<template #option="scope"> <QItemLabel caption>
<QItem v-bind="scope.itemProps"> {{ toDateFormat(scope.opt?.started) }} -
<QItemSection> {{
<QItemLabel># {{ scope.opt?.businessFk }}</QItemLabel> scope.opt?.ended
<QItemLabel caption> ? toDateFormat(scope.opt?.ended)
{{ toDateFormat(scope.opt?.started) }} - : 'Indef.'
{{ }}
scope.opt?.ended </QItemLabel>
? toDateFormat(scope.opt?.ended) </QItemSection>
: 'Indef.' </QItem>
}} </template>
</QItemLabel> </VnSelect>
</QItemSection> </div>
</QItem>
</template>
</VnSelect>
</QItemSection>
</QItem>
</QList>
<QList dense class="list q-gutter-y-xs q-my-md"> <QList dense class="list q-gutter-y-xs q-my-md">
<QItem v-for="type in absenceTypeList" :key="type.id"> <QItem v-for="type in absenceTypeList" :key="type.id">
<WorkerEventLabel <WorkerEventLabel

View File

@ -11,7 +11,7 @@ const $props = defineProps({
</script> </script>
<template> <template>
<QPopupProxy> <QPopupProxy data-cy="WorkerDescriptor">
<WorkerDescriptor <WorkerDescriptor
v-if="$props.id" v-if="$props.id"
:id="$props.id" :id="$props.id"

View File

@ -20,6 +20,7 @@ const { notify } = useNotify();
const loadingDocuware = ref(true); const loadingDocuware = ref(true);
const tableRef = ref(); const tableRef = ref();
const dialog = ref(); const dialog = ref();
const getAvailablePdaRef = ref();
const route = useRoute(); const route = useRoute();
const { openConfirmationModal } = useVnConfirm(); const { openConfirmationModal } = useVnConfirm();
const routeId = computed(() => route.params.id); const routeId = computed(() => route.params.id);
@ -84,6 +85,7 @@ function reloadData() {
initialData.value.deviceProductionFk = null; initialData.value.deviceProductionFk = null;
initialData.value.simFk = null; initialData.value.simFk = null;
tableRef.value.reload(); tableRef.value.reload();
getAvailablePdaRef.value.fetch();
} }
async function fetchDocuware() { async function fetchDocuware() {
@ -135,6 +137,7 @@ async function deallocatePDA(deviceProductionFk) {
); );
delete tableRef.value.CrudModelRef.formData[index]; delete tableRef.value.CrudModelRef.formData[index];
notify(t('PDA deallocated'), 'positive'); notify(t('PDA deallocated'), 'positive');
await getAvailablePdaRef.value.fetch();
} }
function isSigned(row) { function isSigned(row) {
@ -144,6 +147,7 @@ function isSigned(row) {
<template> <template>
<FetchData <FetchData
ref="getAvailablePdaRef"
url="workers/getAvailablePda" url="workers/getAvailablePda"
@on-fetch="(data) => (deviceProductions = data)" @on-fetch="(data) => (deviceProductions = data)"
auto-load auto-load
@ -234,7 +238,7 @@ function isSigned(row) {
data-cy="workerPda-download" data-cy="workerPda-download"
> >
<QTooltip> <QTooltip>
{{ t('worker.pda.download') }} {{ t('globals.downloadPdf') }}
</QTooltip> </QTooltip>
</QBtn> </QBtn>
</template> </template>
@ -307,4 +311,5 @@ es:
This PDA is already assigned to another user: Este PDA ya está asignado a otro usuario This PDA is already assigned to another user: Este PDA ya está asignado a otro usuario
Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Are you sure you want to send it?: ¿Seguro que quieres enviarlo?
Sign PDA: Firmar PDA Sign PDA: Firmar PDA
PDF sended to signed: PDF enviado para firmar
</i18n> </i18n>

View File

@ -11,7 +11,7 @@ const $props = defineProps({
</script> </script>
<template> <template>
<QPopupProxy> <QPopupProxy data-cy="ZoneDescriptor">
<ZoneDescriptor v-if="$props.id" :id="$props.id" :summary="ZoneSummary" /> <ZoneDescriptor v-if="$props.id" :id="$props.id" :summary="ZoneSummary" />
</QPopupProxy> </QPopupProxy>
</template> </template>

View File

@ -0,0 +1,95 @@
import { describe, expect, it, beforeEach } from 'vitest';
import { setActivePinia, createPinia } from 'pinia';
import { useArrayDataStore } from '../useArrayDataStore';
describe('useArrayDataStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('should get undefined for non-existent key', () => {
const store = useArrayDataStore();
expect(store.get('nonExistent')).toBeUndefined();
});
it('should set default state for new key', () => {
const store = useArrayDataStore();
store.set('test');
const state = store.get('test');
expect(state).toMatchObject({
filter: {},
userFilter: {},
userParams: {},
url: '',
limit: 20,
skip: 0,
order: '',
isLoading: false,
userParamsChanged: false,
exprBuilder: null,
searchUrl: 'params',
navigate: null,
page: 1,
mapKey: 'id',
oneRecord: false,
});
});
it('should clear state for specific key', () => {
const store = useArrayDataStore();
store.set('test');
store.clear('test');
expect(store.get('test')).toBeUndefined();
});
it('should reset all properties when no options provided', () => {
const store = useArrayDataStore();
store.set('test');
const state = store.get('test');
state.limit = 50;
state.page = 3;
store.reset('test');
expect(store.get('test').limit).toBe(20);
expect(store.get('test').page).toBe(1);
});
it('should reset only specified properties', () => {
const store = useArrayDataStore();
store.set('test');
const state = store.get('test');
state.limit = 50;
state.page = 3;
state.url = 'test-url';
store.reset('test', ['limit', 'page']);
expect(state.limit).toBe(20);
expect(state.page).toBe(1);
expect(state.url).toBe('test-url');
});
it('should reset nested properties', () => {
const store = useArrayDataStore();
store.set('test');
const state = store.get('test');
state.filter.skip = 10;
store.reset('test', ['filter.skip']);
expect(state.filter.skip).toBe(0);
});
it('should reset pagination properties', () => {
const store = useArrayDataStore();
store.set('test');
const state = store.get('test');
state.skip = 20;
state.filter.skip = 20;
state.page = 3;
store.resetPagination('test');
expect(state.skip).toBe(0);
expect(state.filter.skip).toBe(0);
expect(state.page).toBe(1);
});
});

View File

@ -1,15 +1,17 @@
import { setActivePinia, createPinia } from 'pinia'; import { setActivePinia, createPinia } from 'pinia';
import { describe, beforeEach, afterEach, it, expect, vi, beforeAll } from 'vitest'; import { describe, beforeEach, afterEach, it, expect, vi } from 'vitest';
import { useNavigationStore } from '../useNavigationStore'; import { useNavigationStore } from '../useNavigationStore';
import axios from 'axios'; import { default as axios } from 'axios';
let store; let store;
vi.mock('src/router/modules', () => [ vi.mock('src/router/modules', () => ({
{ name: 'Item', meta: {} }, default: [
{ name: 'Shelving', meta: {} }, { name: 'Item', meta: {} },
{ name: 'Order', meta: {} }, { name: 'Shelving', meta: {} },
]); { name: 'Order', meta: {} },
],
}));
vi.mock('src/filters', () => ({ vi.mock('src/filters', () => ({
toLowerCamel: vi.fn((name) => name.toLowerCase()), toLowerCamel: vi.fn((name) => name.toLowerCase()),

View File

@ -44,7 +44,7 @@ export async function findImports(targetFile, visited = new Set(), identation =
]; ];
} }
return getUniques(fullTree); // Remove duplicates return getUniques([...fullTree, targetFile]); // Remove duplicates
} }
function getUniques(array) { function getUniques(array) {

View File

@ -25,7 +25,7 @@ async function getChangedModules() {
if (change.startsWith(E2E_PATH)) changedArray.push(change); if (change.startsWith(E2E_PATH)) changedArray.push(change);
changedModules = new Set(changedArray); changedModules = new Set(changedArray);
} }
return [...changedModules].join('\n'); return cleanSpecs(changedModules).join('\n');
} }
getChangedModules() getChangedModules()
@ -34,3 +34,20 @@ getChangedModules()
console.error(e); console.error(e);
process.exit(1); process.exit(1);
}); });
function cleanSpecs(changedModules) {
let specifics = [];
const modules = [];
for (const changed of changedModules) {
if (changed.endsWith('*.spec.js')) {
modules.push(changed);
continue;
}
specifics.push(changed);
}
specifics = specifics.filter(
(spec) => !modules.some((module) => spec.startsWith(module.split('**')[0])),
);
return [...modules, ...specifics];
}

View File

@ -18,6 +18,7 @@ describe('Item summary', () => {
cy.get('.q-menu > .q-list > :nth-child(1) > .q-item__section').click(); cy.get('.q-menu > .q-list > :nth-child(1) > .q-item__section').click();
cy.dataCy('regularizeStockInput').type('10'); cy.dataCy('regularizeStockInput').type('10');
cy.dataCy('Warehouse_select').type('Warehouse One{enter}'); cy.dataCy('Warehouse_select').type('Warehouse One{enter}');
cy.dataCy('FormModelPopup_save').click();
cy.checkNotification('Data created'); cy.checkNotification('Data created');
}); });
}); });

View File

@ -0,0 +1,46 @@
/// <reference types="cypress" />
describe('TicketBasicData', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/31/basic-data');
});
it('Should redirect to customer basic data', () => {
cy.get('.q-page').should('be.visible');
cy.get(':nth-child(2) > div > .text-primary').click();
cy.dataCy('Address_select').click();
cy.get('.q-btn-group ').find('.q-btn__content > .q-icon').click();
cy.get(
'[data-cy="CustomerBasicData-menu-item"] > .q-item__section--main',
).click();
cy.url().should('include', '/customer/1104/basic-data');
});
it.only('stepper', () => {
cy.get('.q-stepper__tab--active').should('have.class', 'q-stepper__tab--active');
cy.get('.q-stepper__nav > .q-btn--standard').click();
cy.get('.q-stepper__tab--done').should('have.class', 'q-stepper__tab--done');
cy.get('.q-stepper__tab--active').should('have.class', 'q-stepper__tab--active');
cy.get('tr:nth-child(1)>:nth-child(1)>span').should('have.class', 'link').click();
cy.dataCy('ItemDescriptor').should('exist');
cy.get('.q-drawer__content > :nth-child(1)').each(() => {
cy.get('span').should('contain.text', 'Price: €');
cy.get('span').should('contain.text', 'New price: €');
cy.get('span').should('contain.text', 'Difference: €');
});
cy.get(
':nth-child(3) > .q-radio > .q-radio__inner > .q-radio__bg > .q-radio__check',
).should('have.class', 'q-radio__check');
cy.get(
'.q-stepper__step-inner > .q-drawer-container > .q-drawer > .q-drawer__content',
).click();
cy.get(':nth-child(2) > :nth-child(1) > .text-weight-bold').click();
cy.get(':nth-child(3) > .q-radio > .q-radio__inner').should(
'have.class',
'q-radio__inner--truthy',
);
cy.get('.q-drawer__content > :nth-child(2)').click();
});
});

View File

@ -0,0 +1,30 @@
/// <reference types="cypress" />
describe('TicketComponents', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/1/components');
});
it('Should load layout', () => {
cy.get('.q-page').should('be.visible');
cy.validateScrollContent([
{ row: 2, col: 2, text: 'Base to commission: €799.20' },
{ row: 2, col: 3, text: 'Total without VAT: €807.20' },
{ row: 3, col: 2, text: 'valor de compra: €425.000' },
{ row: 3, col: 4, text: 'maná auto: €7.998' },
{ row: 4, col: 2, text: 'Price: €5.00' },
{ row: 4, col: 3, text: 'Bonus: €1.00' },
{ row: 4, col: 5, text: 'Packages: 6' },
{ row: 4, col: 4, text: 'Zone: Zone pickup A ' },
{ row: 5, col: 2, text: 'Total price: €16.00' },
]);
cy.get(':nth-child(4) > .link').click();
cy.dataCy('ZoneDescriptor').should('exist');
cy.getRowCol('total').should('have.text', '€250.000€247.000€4.970');
cy.getRowCol('import').should('have.text', '€50.000€49.400€0.994');
cy.getRowCol('components').should('have.text', 'valor de compramargenmaná auto');
cy.getRowCol('serie').should('have.text', 'costeempresacartera_comercial');
});
});

View File

@ -1,7 +1,5 @@
/// <reference types="cypress" /> /// <reference types="cypress" />
describe('TicketList', () => { describe('TicketList', () => {
const firstRow = 'tbody.q-virtual-scroll__content tr:nth-child(1)';
beforeEach(() => { beforeEach(() => {
cy.login('developer'); cy.login('developer');
cy.visit('/#/ticket/list', false); cy.visit('/#/ticket/list', false);
@ -10,7 +8,7 @@ describe('TicketList', () => {
const searchResults = (search) => { const searchResults = (search) => {
if (search) cy.typeSearchbar().type(search); if (search) cy.typeSearchbar().type(search);
cy.dataCy('vn-searchbar').find('input').type('{enter}'); cy.dataCy('vn-searchbar').find('input').type('{enter}');
cy.get(firstRow).should('exist'); cy.getRow().should('exist');
}; };
it('should search results', () => { it('should search results', () => {
@ -23,13 +21,13 @@ describe('TicketList', () => {
cy.window().then((win) => { cy.window().then((win) => {
cy.stub(win, 'open').as('windowOpen'); cy.stub(win, 'open').as('windowOpen');
}); });
cy.get(firstRow).should('be.visible').find('.q-btn:first').click(); cy.getRow().should('be.visible').find('.q-btn:first').click();
cy.get('@windowOpen').should('be.calledWithMatch', /\/ticket\/\d+\/sale/); cy.get('@windowOpen').should('be.calledWithMatch', /\/ticket\/\d+\/sale/);
}); });
it('should open ticket summary', () => { it('should open ticket summary', () => {
searchResults(); searchResults();
cy.get(firstRow).find('.q-btn:last').click(); cy.getRow().find('.q-btn:last').click();
cy.get('.summaryHeader').should('exist'); cy.get('.summaryHeader').should('exist');
cy.get('.summaryBody').should('exist'); cy.get('.summaryBody').should('exist');
}); });
@ -42,8 +40,9 @@ describe('TicketList', () => {
cy.dataCy('Customer ID_input').clear('1'); cy.dataCy('Customer ID_input').clear('1');
cy.dataCy('Customer ID_input').type('1101{enter}'); cy.dataCy('Customer ID_input').type('1101{enter}');
cy.get('[data-cy="vnTableCreateBtn"] > .q-btn__content > .q-icon').click(); cy.intercept('GET', /\/api\/Clients\?filter/).as('clientFilter');
cy.waitSpinner(); cy.vnTableCreateBtn();
cy.wait('@clientFilter');
cy.dataCy('Customer_select').should('have.value', 'Bruce Wayne'); cy.dataCy('Customer_select').should('have.value', 'Bruce Wayne');
cy.dataCy('Address_select').click(); cy.dataCy('Address_select').click();
@ -51,8 +50,7 @@ describe('TicketList', () => {
cy.dataCy('Address_select').should('have.value', 'Bruce Wayne'); cy.dataCy('Address_select').should('have.value', 'Bruce Wayne');
}); });
it('Client list create new ticket', () => { it('Client list create new ticket', () => {
cy.dataCy('vnTableCreateBtn').should('exist'); cy.vnTableCreateBtn();
cy.dataCy('vnTableCreateBtn').click();
const data = { const data = {
Customer: { val: 1, type: 'select' }, Customer: { val: 1, type: 'select' },
Warehouse: { val: 'Warehouse One', type: 'select' }, Warehouse: { val: 'Warehouse One', type: 'select' },

View File

@ -18,7 +18,7 @@ describe('TicketNotes', () => {
cy.checkNotification('Data saved'); cy.checkNotification('Data saved');
cy.dataCy('ticketNotesRemoveNoteBtn').should('exist'); cy.dataCy('ticketNotesRemoveNoteBtn').should('exist');
cy.dataCy('ticketNotesRemoveNoteBtn').click(); cy.dataCy('ticketNotesRemoveNoteBtn').click();
cy.dataCy('VnConfirm_confirm').click(); cy.confirmVnConfirm();
cy.checkNotification('Data saved'); cy.checkNotification('Data saved');
}); });
}); });

View File

@ -0,0 +1,21 @@
/// <reference types="cypress" />
describe('TicketPackages', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/31/package');
});
it('Should load layout', () => {
cy.get('.q-page').should('be.visible');
cy.get('.vn-row > .q-btn > .q-btn__content > .q-icon').click();
cy.dataCy('Package_select').click();
cy.get('.q-menu :nth-child(1) >.q-item__section').click();
cy.dataCy('Quantity_input').clear().type('5');
cy.saveCrudModel();
cy.checkNotification('Data saved');
cy.get('.q-mb-md > .text-primary').click();
cy.confirmVnConfirm();
cy.checkNotification('Data saved');
});
});

View File

@ -0,0 +1,18 @@
/// <reference types="cypress" />
describe('TicketPictures', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/31/picture');
});
it('Should load layout', () => {
cy.get(':nth-child(1) > .q-card > .content').should('be.visible');
cy.get('.content > .link').should('be.visible').click();
cy.dataCy('ItemDescriptor').should('exist');
cy.dataCy('vnLvColor:');
cy.dataCy('vnLvColor:');
cy.dataCy('vnLvTallos:');
cy.get('.q-mt-md').should('be.visible');
cy.get(':nth-child(1) > .q-card > .img-wrapper').should('be.visible');
});
});

View File

@ -6,8 +6,7 @@ describe('TicketRequest', () => {
}); });
it('Creates a new request', () => { it('Creates a new request', () => {
cy.dataCy('vnTableCreateBtn').should('exist'); cy.vnTableCreateBtn();
cy.dataCy('vnTableCreateBtn').click();
const data = { const data = {
Description: { val: 'Purchase description' }, Description: { val: 'Purchase description' },
Atender: { val: 'buyerNick', type: 'select' }, Atender: { val: 'buyerNick', type: 'select' },

View File

@ -2,7 +2,7 @@
const firstRow = 'tbody > :nth-child(1)'; const firstRow = 'tbody > :nth-child(1)';
describe('TicketSale', () => { describe('TicketSale', () => {
describe('Ticket #23', () => { describe('#23', () => {
beforeEach(() => { beforeEach(() => {
cy.login('salesPerson'); cy.login('salesPerson');
cy.visit('/#/ticket/23/sale'); cy.visit('/#/ticket/23/sale');
@ -17,10 +17,12 @@ describe('TicketSale', () => {
cy.get('[data-cy="componentOption-37"]').click(); cy.get('[data-cy="componentOption-37"]').click();
cy.waitForElement('[data-cy="Price_input"]'); cy.waitForElement('[data-cy="Price_input"]');
cy.dataCy('Price_input').clear(); cy.dataCy('Price_input').clear().type(price);
cy.dataCy('Price_input').type(price); cy.intercept('POST', /\/api\/Sales\/\d+\/updatePrice/).as('updatePrice');
cy.dataCy('saveManaBtn').click(); cy.dataCy('saveManaBtn').click();
handleVnConfirm(); handleVnConfirm();
cy.wait('@updatePrice').its('response.statusCode').should('eq', 200);
cy.get('[data-col-field="price"]') cy.get('[data-col-field="price"]')
.find('.q-btn > .q-btn__content') .find('.q-btn > .q-btn__content')
@ -34,10 +36,14 @@ describe('TicketSale', () => {
cy.dataCy('ticketEditManaProxy').should('exist'); cy.dataCy('ticketEditManaProxy').should('exist');
cy.get('[data-cy="componentOption-37"]').click(); cy.get('[data-cy="componentOption-37"]').click();
cy.waitForElement('[data-cy="Disc_input"]'); cy.waitForElement('[data-cy="Disc_input"]');
cy.dataCy('Disc_input').clear(); cy.dataCy('Disc_input').clear().type(discount);
cy.dataCy('Disc_input').type(discount); cy.intercept('POST', /\/api\/Tickets\/\d+\/updateDiscount/).as(
'updateDiscount',
);
cy.dataCy('saveManaBtn').click(); cy.dataCy('saveManaBtn').click();
handleVnConfirm(); handleVnConfirm();
cy.wait('@updateDiscount').its('response.statusCode').should('eq', 204);
cy.get('[data-col-field="discount"]') cy.get('[data-col-field="discount"]')
.find('.q-btn > .q-btn__content') .find('.q-btn > .q-btn__content')
@ -48,6 +54,8 @@ describe('TicketSale', () => {
const concept = Math.floor(Math.random() * 100) + 1; const concept = Math.floor(Math.random() * 100) + 1;
cy.waitForElement(firstRow); cy.waitForElement(firstRow);
cy.get('[data-col-field="item"]').click(); cy.get('[data-col-field="item"]').click();
cy.intercept('POST', '**/api').as('postRequest');
cy.get('.q-menu') cy.get('.q-menu')
.find('[data-cy="undefined_input"]') .find('[data-cy="undefined_input"]')
.type(concept) .type(concept)
@ -60,6 +68,8 @@ describe('TicketSale', () => {
const quantity = Math.floor(Math.random() * 100) + 1; const quantity = Math.floor(Math.random() * 100) + 1;
cy.waitForElement(firstRow); cy.waitForElement(firstRow);
cy.dataCy('ticketSaleQuantityInput').find('input').clear(); cy.dataCy('ticketSaleQuantityInput').find('input').clear();
cy.intercept('POST', '**/api').as('postRequest');
cy.dataCy('ticketSaleQuantityInput') cy.dataCy('ticketSaleQuantityInput')
.find('input') .find('input')
.type(quantity) .type(quantity)
@ -73,7 +83,7 @@ describe('TicketSale', () => {
.should('have.value', `${quantity}`); .should('have.value', `${quantity}`);
}); });
}); });
describe('Ticket to add claim #24', () => { describe('#24 add claim', () => {
beforeEach(() => { beforeEach(() => {
cy.login('salesPerson'); cy.login('salesPerson');
cy.visit('/#/ticket/24/sale'); cy.visit('/#/ticket/24/sale');
@ -83,15 +93,15 @@ describe('TicketSale', () => {
selectFirstRow(); selectFirstRow();
cy.dataCy('ticketSaleMoreActionsDropdown').click(); cy.dataCy('ticketSaleMoreActionsDropdown').click();
cy.dataCy('createClaimItem').click(); cy.dataCy('createClaimItem').click();
cy.dataCy('VnConfirm_confirm').click(); cy.confirmVnConfirm();
cy.url().should('contain', 'claim/'); cy.url().should('contain', 'claim/');
// Delete created claim to avoid cluttering the database // Delete created claim to avoid cluttering the database
cy.dataCy('descriptor-more-opts').click(); cy.dataCy('descriptor-more-opts').click();
cy.dataCy('deleteClaim').click(); cy.dataCy('deleteClaim').click();
cy.dataCy('VnConfirm_confirm').click(); cy.confirmVnConfirm();
}); });
}); });
describe.only('Free ticket #31', () => { describe('#31 free ticket', () => {
beforeEach(() => { beforeEach(() => {
cy.login('salesPerson'); cy.login('salesPerson');
cy.visit('/#/ticket/31/sale'); cy.visit('/#/ticket/31/sale');
@ -129,7 +139,9 @@ describe('TicketSale', () => {
cy.dataCy('ticketSaleMoreActionsDropdown').should('be.disabled'); cy.dataCy('ticketSaleMoreActionsDropdown').should('be.disabled');
}); });
it.only('should update discount when "Update discount" is clicked', () => { it('should update discount when "Update discount" is clicked', () => {
const discount = Number((Math.random() * 99 + 1).toFixed(2));
selectFirstRow(); selectFirstRow();
cy.dataCy('ticketSaleMoreActionsDropdown').click(); cy.dataCy('ticketSaleMoreActionsDropdown').click();
cy.waitForElement('[data-cy="updateDiscountItem"]'); cy.waitForElement('[data-cy="updateDiscountItem"]');
@ -138,9 +150,13 @@ describe('TicketSale', () => {
cy.get('[data-cy="componentOption-37"]').click(); cy.get('[data-cy="componentOption-37"]').click();
cy.waitForElement('[data-cy="ticketSaleDiscountInput"]'); cy.waitForElement('[data-cy="ticketSaleDiscountInput"]');
cy.dataCy('ticketSaleDiscountInput').find('input').focus(); cy.dataCy('ticketSaleDiscountInput').find('input').focus();
cy.dataCy('ticketSaleDiscountInput').find('input').type('10'); cy.intercept('POST', /\/api\/Tickets\/\d+\/updateDiscount/).as(
'updateDiscount',
);
cy.dataCy('ticketSaleDiscountInput').find('input').type(discount);
cy.dataCy('saveManaBtn').click(); cy.dataCy('saveManaBtn').click();
cy.waitForElement('.q-notification__message'); cy.wait('@updateDiscount').its('response.statusCode').should('eq', 204);
cy.checkNotification('Data saved'); cy.checkNotification('Data saved');
cy.dataCy('ticketSaleMoreActionsDropdown').should('be.disabled'); cy.dataCy('ticketSaleMoreActionsDropdown').should('be.disabled');
}); });
@ -149,7 +165,7 @@ describe('TicketSale', () => {
selectFirstRow(); selectFirstRow();
cy.dataCy('ticketSaleMoreActionsDropdown').click(); cy.dataCy('ticketSaleMoreActionsDropdown').click();
cy.dataCy('createClaimItem').click(); cy.dataCy('createClaimItem').click();
cy.dataCy('VnConfirm_confirm').click(); cy.confirmVnConfirm();
cy.checkNotification('Future ticket date not allowed'); cy.checkNotification('Future ticket date not allowed');
}); });
@ -174,7 +190,7 @@ describe('TicketSale', () => {
cy.url().should('match', /\/ticket\/31\/log/); cy.url().should('match', /\/ticket\/31\/log/);
}); });
}); });
describe('Ticket to transfer #32', () => { describe('#32 transfer', () => {
beforeEach(() => { beforeEach(() => {
cy.login('salesPerson'); cy.login('salesPerson');
cy.visit('/#/ticket/32/sale'); cy.visit('/#/ticket/32/sale');
@ -194,9 +210,7 @@ function selectFirstRow() {
cy.get(firstRow).find('.q-checkbox__inner').click(); cy.get(firstRow).find('.q-checkbox__inner').click();
} }
function handleVnConfirm() { function handleVnConfirm() {
cy.get('[data-cy="VnConfirm_confirm"]').click(); cy.confirmVnConfirm();
cy.waitForElement('.q-notification__message');
cy.get('.q-notification__message').should('be.visible');
cy.checkNotification('Data saved'); cy.checkNotification('Data saved');
} }

View File

@ -0,0 +1,53 @@
/// <reference types="cypress" />
function uncheckedSVG(className, state) {
cy.get(`${className} .q-checkbox__svg`).should(
state === 'checked' ? 'not.have.attr' : 'have.attr',
'fill',
'none',
);
}
function checkedSVG(className, state) {
cy.get(`${className} .q-checkbox__svg> .q-checkbox__truthy`).should(
state === 'checked' ? 'not.have.attr' : 'have.attr',
'fill',
'none',
);
}
function clickIconAndCloseDialog(n) {
cy.get(
`:nth-child(1) > :nth-child(6) > :nth-child(${n}) > .q-btn__content > .q-icon`,
).click();
}
describe('TicketSaleTracking', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/1/sale-tracking');
});
it('Should load layout', () => {
cy.get('.q-page').should('be.visible');
// Check checkbox states
uncheckedSVG('.pink', 'checked');
uncheckedSVG('.cyan', 'checked');
uncheckedSVG('.warning', 'checked');
uncheckedSVG('.info', 'checked');
checkedSVG('.yellow', 'unchecked');
cy.get('.q-page').click();
cy.get(
':nth-child(1) > :nth-child(6) > :nth-child(2) > .q-btn__content > .q-icon',
).click();
cy.get('body').type('{esc}');
cy.get(
':nth-child(1) > :nth-child(6) > :nth-child(1) > .q-btn__content > .q-icon',
).click();
cy.get(
'.q-dialog__inner > .q-table__container :nth-child(1) > :nth-child(2) .link.q-btn',
).click();
cy.dataCy('WorkerDescriptor').should('exist');
});
});

View File

@ -0,0 +1,23 @@
/// <reference types="cypress" />
describe('TicketService', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/31/service');
});
it('Add and remove service', () => {
cy.get('.q-page').should('be.visible');
cy.addBtnClick();
cy.dataCy('Description_icon').click();
cy.dataCy('Description_input').clear().type('test');
cy.saveFormModel();
cy.selectOption('[data-cy="Description_select"]', 'test');
cy.dataCy('Quantity_input').clear().type('1');
cy.dataCy('Price_input').clear().type('2');
cy.saveCrudModel();
cy.checkNotification('Data saved');
cy.get(':nth-child(5) > .q-icon').click();
});
});

View File

@ -0,0 +1,22 @@
/// <reference types="cypress" />
describe('TicketSms', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/32/sms');
});
it('Should load layout', () => {
cy.get('.q-page').should('be.visible');
cy.get('.q-infinite-scroll > :nth-child(1)').should(
'contain.text',
'0004 444444444Lorem ipsum dolor sit amet, consectetur adipiscing elit.2001-01-01 00:00:00OK',
);
cy.get(
':nth-child(1) > .q-item > .q-item__section--top > .column > .q-avatar',
).should('be.visible');
cy.get(
':nth-child(1) > .q-item > .q-item__section--side.justify-center > .center > .q-chip > .q-chip__content',
).should('have.class', 'q-chip__content');
});
});

View File

@ -0,0 +1,25 @@
/// <reference types="cypress" />
describe('Ticket tracking', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/31/tracking');
});
it('Add new tracking', () => {
cy.get('.q-page').should('be.visible');
cy.getRowCol('worker').find('span').should('have.class', 'link').click();
cy.dataCy('WorkerDescriptor').should('exist');
cy.vnTableCreateBtn();
cy.selectOption('.q-field--float [data-cy="State_select"]', 'OK').click();
cy.saveFormModel();
cy.get(
':last-child > [data-col-field="state"] > [data-cy="vnTableCell_state"]',
).should('have.text', 'OK');
cy.get(':last-child > [data-col-field="worker"]').should(
'have.text',
'developer ',
);
});
});

View File

@ -0,0 +1,27 @@
/// <reference types="cypress" />
function checkRightLabel(index, value, tag = 'Volume: ') {
cy.get(`.q-scrollarea__content > :nth-child(${index}) > :nth-child(2) > span`)
.should('be.visible')
.should('have.text', `${tag}${value}`);
}
describe('TicketVolume', () => {
beforeEach(() => {
cy.login('developer');
cy.viewport(1920, 1080);
cy.visit('/#/ticket/1/volume');
});
it('Check right panel info', () => {
cy.get('.q-page').should('be.visible');
checkRightLabel(2, '0.028');
checkRightLabel(3, '0.014');
checkRightLabel(4, '1.526');
});
it('Descriptors', () => {
cy.get(':nth-child(1) > [data-col-field="itemFk"]')
.find('span')
.should('have.class', 'link')
.click();
cy.dataCy('ItemDescriptor').should('exist');
});
});

View File

@ -0,0 +1,3 @@
Cypress.Commands.add('saveCrudModel', () =>
cy.dataCy('crudModelDefaultSaveBtn').should('exist').click(),
);

View File

@ -0,0 +1,3 @@
Cypress.Commands.add('saveFormModel', () =>
cy.dataCy('FormModelPopup_save').should('exist').click(),
);

View File

@ -0,0 +1,3 @@
Cypress.Commands.add('confirmVnConfirm', () =>
cy.dataCy('VnConfirm_confirm').should('exist').click(),
);

View File

@ -0,0 +1,3 @@
Cypress.Commands.add('clickOption', (index = 1) =>
cy.get(`.q-menu :nth-child(${index}) >.q-item__section`).click(),
);

View File

@ -0,0 +1,16 @@
Cypress.Commands.add('getRow', (index = 1) =>
cy.get(`.vnTable .q-virtual-scroll__content tr:nth-child(${index})`),
);
Cypress.Commands.add('getRowCol', (field, index = 1) =>
cy.get(
`.vnTable .q-virtual-scroll__content > :nth-child(${index}) > [data-col-field="${field}"]`,
),
);
Cypress.Commands.add('vnTableCreateBtn', () =>
cy.dataCy('vnTableCreateBtn').should('exist').click(),
);
Cypress.Commands.add('waitTableScrollLoad', () =>
cy.waitForElement('[data-q-vs-anchor]'),
);

View File

@ -29,7 +29,12 @@
// import { registerCommands } from '@quasar/quasar-app-extension-testing-e2e-cypress'; // import { registerCommands } from '@quasar/quasar-app-extension-testing-e2e-cypress';
import moment from 'moment'; import moment from 'moment';
import waitUntil from './waitUntil'; import waitUntil from './waitUntil';
// Importar dinámicamente todos los archivos con el sufijo .commands.js dentro de la carpeta src/test/cypress/integration
const requireCommands = require.context('../integration', true, /\.commands\.js$/);
// Iterar sobre cada archivo y requerirlo
requireCommands.keys().forEach(requireCommands);
// Common comma
Cypress.Commands.add('waitUntil', { prevSubject: 'optional' }, waitUntil); Cypress.Commands.add('waitUntil', { prevSubject: 'optional' }, waitUntil);
Cypress.Commands.add('resetDB', () => { Cypress.Commands.add('resetDB', () => {
@ -606,6 +611,11 @@ Cypress.Commands.add('checkQueryParams', (expectedParams = {}) => {
}); });
}); });
Cypress.Commands.add('waitTableScrollLoad', () => Cypress.Commands.add('validateScrollContent', (validations) => {
cy.waitForElement('[data-q-vs-anchor]'), validations.forEach(({ row, col, text }) => {
); cy.get(`.q-scrollarea__content > :nth-child(${row}) > :nth-child(${col})`).should(
'have.text',
text,
);
});
});

View File

@ -4,7 +4,6 @@ import { createTestingPinia } from '@pinia/testing';
import { vi } from 'vitest'; import { vi } from 'vitest';
import { i18n } from 'src/boot/i18n'; import { i18n } from 'src/boot/i18n';
import { Notify, Dialog } from 'quasar'; import { Notify, Dialog } from 'quasar';
import axios from 'axios';
import * as useValidator from 'src/composables/useValidator'; import * as useValidator from 'src/composables/useValidator';
installQuasarPlugin({ installQuasarPlugin({
@ -41,8 +40,6 @@ vi.mock('vue-router', () => ({
onBeforeRouteLeave: () => {}, onBeforeRouteLeave: () => {},
})); }));
vi.mock('axios');
vi.spyOn(useValidator, 'useValidator').mockImplementation(() => { vi.spyOn(useValidator, 'useValidator').mockImplementation(() => {
return { return {
validate: vi.fn(), validate: vi.fn(),
@ -112,5 +109,4 @@ export function createWrapper(component, options) {
return { vm, wrapper }; return { vm, wrapper };
} }
export { flushPromises };
export { axios, flushPromises };

View File

@ -1 +1,27 @@
// This file will be run before each test file, don't delete or vitest will not work. // This file will be run before each test file, don't delete or vitest will not work.
import { vi } from 'vitest';
vi.mock('axios');
vi.mock('vue-router', () => ({
useRouter: () => ({
push: vi.fn(),
replace: vi.fn(),
currentRoute: {
value: {
params: {
id: 1,
},
meta: { moduleName: 'mockName' },
matched: [{ path: 'mockName/list' }],
},
},
}),
useRoute: () => ({
matched: [],
query: {},
params: {},
meta: { moduleName: 'mockName' },
path: 'mockSection/list',
}),
onBeforeRouteLeave: () => {},
}));

View File

@ -17,6 +17,7 @@ if (process.env.CI) {
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
test: { test: {
globals: true,
reporters, reporters,
outputFile, outputFile,
environment: 'happy-dom', environment: 'happy-dom',